From c8d12324ab47b069c509c9021072e887944e8395 Mon Sep 17 00:00:00 2001 From: ben-jaynes <1btjaynes@gmail.com> Date: Mon, 18 May 2026 12:25:16 -0700 Subject: [PATCH] vault backup: 2026-05-18 12:25:16 --- .../plugins/folder-note-plugin/data.json | 9 - .obsidian/plugins/folder-note-plugin/main.js | 9283 --- .../plugins/folder-note-plugin/manifest.json | 10 - .../plugins/folder-note-plugin/styles.css | 229 - .../plugins/obsidian-full-calendar/data.json | 17 - .../plugins/obsidian-full-calendar/main.js | 54279 ---------------- .../obsidian-full-calendar/manifest.json | 10 - .../plugins/obsidian-full-calendar/styles.css | 1327 - .../Reflection 2.md | 2 +- 9 files changed, 1 insertion(+), 65165 deletions(-) delete mode 100644 .obsidian/plugins/folder-note-plugin/data.json delete mode 100644 .obsidian/plugins/folder-note-plugin/main.js delete mode 100644 .obsidian/plugins/folder-note-plugin/manifest.json delete mode 100644 .obsidian/plugins/folder-note-plugin/styles.css delete mode 100644 .obsidian/plugins/obsidian-full-calendar/data.json delete mode 100644 .obsidian/plugins/obsidian-full-calendar/main.js delete mode 100644 .obsidian/plugins/obsidian-full-calendar/manifest.json delete mode 100644 .obsidian/plugins/obsidian-full-calendar/styles.css diff --git a/.obsidian/plugins/folder-note-plugin/data.json b/.obsidian/plugins/folder-note-plugin/data.json deleted file mode 100644 index b31018b..0000000 --- a/.obsidian/plugins/folder-note-plugin/data.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "folderNoteHide": true, - "folderNoteType": "inside", - "folderNoteName": "_about_", - "folderNoteKey": "ctrl", - "folderNoteAutoRename": true, - "folderDelete2Note": false, - "folderNoteStrInit": "# {{FOLDER_NAME}} Overview\n {{FOLDER_BRIEF_LIVE}} \n" -} \ No newline at end of file diff --git a/.obsidian/plugins/folder-note-plugin/main.js b/.obsidian/plugins/folder-note-plugin/main.js deleted file mode 100644 index 80a52bc..0000000 --- a/.obsidian/plugins/folder-note-plugin/main.js +++ /dev/null @@ -1,9283 +0,0 @@ -'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. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -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()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -// ------------------------------------------------------------ -// Card block -// ------------------------------------------------------------ -var CardStyle; -(function (CardStyle) { - CardStyle[CardStyle["Folder"] = 0] = "Folder"; - CardStyle[CardStyle["Note"] = 1] = "Note"; - CardStyle[CardStyle["Image"] = 2] = "Image"; -})(CardStyle || (CardStyle = {})); -var CardBlock = /** @class */ (function () { - function CardBlock() { - this.style = 'card'; - this.cards = []; - this.col = -1; - this.imagePrefix = ''; - } - CardBlock.prototype.addCard = function (card) { - this.cards.push(card); - }; - CardBlock.prototype.clear = function () { - this.cards = []; - }; - CardBlock.prototype.getCardNum = function () { - return this.cards.length; - }; - CardBlock.prototype.getDocElement = function (app) { - var cardDiv = document.createElement('div'); - if (this.style == 'strip') { - cardDiv.addClass('strip-card-band'); - for (var i in this.cards) { - var cardEl = this.cards[i].getBoxElement(app, this.imagePrefix); - cardEl.addClass('strip-card-view'); - cardDiv.appendChild(cardEl); - } - } - else { // default: this.style == 'card' - cardDiv.addClass('cute-card-band'); - for (var i in this.cards) { - var cardEl = this.cards[i].getBoxElement(app, this.imagePrefix); - cardEl.addClass('cute-card-view'); - cardDiv.appendChild(cardEl); - } - if (this.col > 0) { - cardDiv.setAttr('style', "grid-template-columns: repeat(" + this.col + ", 1fr);"); - } - } - return cardDiv; - }; - CardBlock.prototype.getYamlCode = function () { - var yamlStr = ''; - var nCard = this.getCardNum(); - if (nCard > 0) { - yamlStr = '\n```ccard\nitems: ['; - for (var i in this.cards) { - yamlStr += '\n {\n'; - yamlStr += this.cards[i].getYamlCode(' '); - yamlStr += ' },'; - } - // get rid of last period - yamlStr = yamlStr.substring(0, yamlStr.length - 1); - yamlStr += '\n]\n'; - if (this.col > 0) { - yamlStr += "col: " + this.col + "\n"; - } - yamlStr += '```\n'; - } - return yamlStr; - }; - CardBlock.prototype.fromYamlCards = function (yaml) { - // parser options - this.fromYamlOptions(yaml); - // parser items - if (yaml.items) { - this.clear(); - var allItems = yaml.items; - for (var i in allItems) { - var cardInfo = allItems[i]; - if ('title' in cardInfo) { - var cardItem = new CardItem(cardInfo['title'], CardStyle.Note); - cardItem.fromDict(cardInfo); - this.addCard(cardItem); - } - } - } - // return - return (this.getCardNum() > 0); - }; - CardBlock.prototype.fromYamlOptions = function (yaml) { - if (yaml.style) { - this.style = yaml.style; - } - if (yaml.col) { - this.col = yaml.col; - } - if (yaml.imagePrefix) { - this.imagePrefix = yaml.imagePrefix; - } - }; - return CardBlock; -}()); -var CardItem = /** @class */ (function () { - function CardItem(title, style) { - this.title = title; - this.abstract = "No abstract."; - this.cardStyle = style; - } - CardItem.prototype.setHeadText = function (text) { - this.headText = text; - }; - CardItem.prototype.setHeadImage = function (linkUrl) { - this.headImage = linkUrl; - }; - CardItem.prototype.setTitle = function (title) { - this.title = title; - }; - CardItem.prototype.setTitleLink = function (linkUrl) { - this.titleLink = linkUrl; - }; - CardItem.prototype.setAbstract = function (abstract) { - this.abstract = abstract; - }; - CardItem.prototype.setFootnote = function (footnote) { - this.footnote = footnote; - }; - CardItem.prototype.fromDict = function (dict) { - if ('head' in dict) { - this.headText = dict['head']; - if (this.headText == 'Folder') { - this.cardStyle = CardStyle.Folder; - } - else if (this.headText == 'Note') { - this.cardStyle = CardStyle.Note; - } - } - if ('image' in dict) - this.headImage = dict['image']; - if ('link' in dict) - this.titleLink = dict['link']; - if ('brief' in dict) - this.abstract = dict['brief']; - if ('foot' in dict) - this.footnote = dict['foot']; - }; - CardItem.prototype.yamlEscapeQuotes = function (org) { - return org.replace(/'/gi, "''"); - }; - CardItem.prototype.getYamlCode = function (prefix) { - var yamlStr = ''; - yamlStr += prefix + "title: '" + this.yamlEscapeQuotes(this.title) + "'"; - if (this.titleLink) - yamlStr += ",\n" + prefix + "link: '" + this.yamlEscapeQuotes(this.titleLink) + "'"; - if (this.abstract) - yamlStr += ",\n" + prefix + "brief: '" + this.yamlEscapeQuotes(this.abstract) + "'"; - if (this.footnote) - yamlStr += ",\n" + prefix + "foot: '" + this.yamlEscapeQuotes(this.footnote) + "'"; - if (this.headImage) { - yamlStr += ",\n" + prefix + "image: '" + this.yamlEscapeQuotes(this.headImage) + "'"; - } - else if (this.headText) { - yamlStr += ",\n" + prefix + "head: '" + this.yamlEscapeQuotes(this.headText) + "'"; - } - else { - if (this.cardStyle == CardStyle.Folder) { - yamlStr += ",\n" + prefix + "head: 'Folder'"; - } - else if (this.cardStyle == CardStyle.Note) { - yamlStr += ",\n" + prefix + "head: 'Note'"; - } - else { - yamlStr += ",\n" + prefix + "head: 'Card'"; - } - } - yamlStr += '\n'; - return yamlStr; - }; - CardItem.prototype.getBoxElement = function (app, imagePrefix) { - var cardEl = document.createElement('div'); - // Heading - var headEl = cardEl.appendChild(document.createElement('div')); - if (this.headImage) { - this.cardStyle = CardStyle.Image; - if (this.headImage.startsWith("#")) { - // color - headEl.addClass('thumb-color'); - headEl.setAttr('style', "background-color: " + this.headImage + ";"); - } - else if (this.headImage.contains("://")) { - // app local image - headEl.addClass('thumb'); - headEl.setAttr('style', "background-image: url(" + this.headImage + ");"); - } - else { - // asset file name? - var imageUrl = this.headImage; - if (imagePrefix.length > 0) { - // skip explicitly path - var urlPathList = imageUrl.split('/').join(' ').trimStart(); - var fixPathList = imagePrefix.split('/').join(' ').trimStart(); - if (!urlPathList.startsWith(fixPathList)) { - imageUrl = imagePrefix + this.headImage; - } - } - if (!imageUrl.contains('://')) { - imageUrl = app.vault.adapter.getResourcePath(imageUrl); - } - headEl.addClass('thumb'); - headEl.setAttr('style', "background-image: url(" + imageUrl + ");"); - } - if (this.headText) { - headEl.textContent = this.headText; - } - } - else if (this.cardStyle == CardStyle.Folder) { - headEl.addClasses(['thumb-color', 'thumb-color-folder']); - headEl.textContent = 'Folder'; - } - else if (this.cardStyle == CardStyle.Note) { - headEl.addClasses(['thumb-color', 'thumb-color-note']); - headEl.textContent = 'Note'; - } - // article - var articleEl = cardEl.appendChild(document.createElement('article')); - // Title - if (this.titleLink) { - var titleEl = articleEl.appendChild(document.createElement('a')); - if (this.titleLink.endsWith('.md')) { - titleEl.addClass('internal-link'); - } - titleEl.href = this.titleLink; - var h1El = document.createElement('h1'); - h1El.textContent = this.title; - titleEl.appendChild(h1El); - } - else { - var titleEl = articleEl.appendChild(document.createElement('h1')); - titleEl.textContent = this.title; - } - // abstract - var briefEl = articleEl.appendChild(document.createElement('p')); - briefEl.textContent = this.abstract; - // footnote - if (this.footnote) { - var footEl = articleEl.appendChild(document.createElement('span')); - footEl.textContent = this.footnote; - } - // close - return cardEl; - }; - return CardItem; -}()); - -// ------------------------------------------------------------ -// Folder Brief -// ------------------------------------------------------------ -var FolderBrief = /** @class */ (function () { - function FolderBrief(app) { - this.app = app; - this.folderPath = ''; - this.briefMax = 64; - this.noteOnly = false; - } - // for cards type: folder_brief - FolderBrief.prototype.yamlFolderBrief = function (yaml) { - return __awaiter(this, void 0, void 0, function () { - var folderPath, activeFile, notePath, folderExist, view, briefCards, cardsElem; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - folderPath = ''; - activeFile = this.app.workspace.getActiveFile(); - notePath = activeFile.path; - if (!yaml.cards.folder) return [3 /*break*/, 2]; - folderPath = yaml.cards.folder; - return [4 /*yield*/, this.app.vault.adapter.exists(folderPath)]; - case 1: - folderExist = _a.sent(); - if (!folderExist) - folderPath = ''; - return [3 /*break*/, 3]; - case 2: - folderPath = activeFile.parent.path; - _a.label = 3; - case 3: - if (!(folderPath.length > 0)) return [3 /*break*/, 5]; - view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView); - if (!view) return [3 /*break*/, 5]; - return [4 /*yield*/, this.makeBriefCards(folderPath, notePath)]; - case 4: - briefCards = _a.sent(); - cardsElem = briefCards.getDocElement(this.app); - return [2 /*return*/, cardsElem]; - case 5: return [2 /*return*/, null]; - } - }); - }); - }; - // generate folder overview - FolderBrief.prototype.makeBriefCards = function (folderPath, activeNotePath) { - return __awaiter(this, void 0, void 0, function () { - var cardBlock, pathList, subFolderList, subFileList, i, subFolderPath, noteExists, folderCard, i, subFilePath, noteCard; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - cardBlock = new CardBlock(); - return [4 /*yield*/, this.app.vault.adapter.list(folderPath)]; - case 1: - pathList = _a.sent(); - subFolderList = pathList.folders; - subFileList = pathList.files; - if (!!this.noteOnly) return [3 /*break*/, 6]; - i = 0; - _a.label = 2; - case 2: - if (!(i < subFolderList.length)) return [3 /*break*/, 6]; - subFolderPath = subFolderList[i]; - return [4 /*yield*/, this.app.vault.adapter.exists(subFolderPath + '.md')]; - case 3: - noteExists = _a.sent(); - if (!!noteExists) return [3 /*break*/, 5]; - return [4 /*yield*/, this.makeFolderCard(folderPath, subFolderPath)]; - case 4: - folderCard = _a.sent(); - cardBlock.addCard(folderCard); - _a.label = 5; - case 5: - i++; - return [3 /*break*/, 2]; - case 6: - i = 0; - _a.label = 7; - case 7: - if (!(i < subFileList.length)) return [3 /*break*/, 10]; - subFilePath = subFileList[i]; - if (!subFilePath.endsWith('.md')) - return [3 /*break*/, 9]; - if (subFilePath == activeNotePath) - return [3 /*break*/, 9]; // omit self includeing - return [4 /*yield*/, this.makeNoteCard(folderPath, subFilePath)]; - case 8: - noteCard = _a.sent(); - cardBlock.addCard(noteCard); - _a.label = 9; - case 9: - i++; - return [3 /*break*/, 7]; - case 10: - // return - return [2 /*return*/, cardBlock]; - } - }); - }); - }; - // make folder brief card - FolderBrief.prototype.makeFolderCard = function (folderPath, subFolderPath) { - return __awaiter(this, void 0, void 0, function () { - var subFolderName, card, subPathList, folderBrief; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - subFolderName = subFolderPath.split('/').pop(); - card = new CardItem(subFolderName, CardStyle.Folder); - return [4 /*yield*/, this.app.vault.adapter.list(subFolderPath)]; - case 1: - subPathList = _a.sent(); - folderBrief = 'Contains '; - folderBrief += subPathList.folders.length.toString() + ' folders, '; - folderBrief += subPathList.files.length.toString() + ' notes.'; - card.setAbstract(folderBrief); - // footnote, use date in the future - card.setFootnote(subFolderPath.replace(folderPath + '/', '')); - // return - return [2 /*return*/, card]; - } - }); - }); - }; - // make note brief card - FolderBrief.prototype.makeNoteCard = function (folderPath, notePath) { - return __awaiter(this, void 0, void 0, function () { - var noteName, noteTitle, card, file, contentOrg, imageUrl, contentBrief, fileSt, date; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - noteName = notePath.split('/').pop(); - noteTitle = noteName.substring(0, noteName.length - 3); - card = new CardItem(noteTitle, CardStyle.Note); - card.setTitleLink(notePath); - file = this.app.vault.getAbstractFileByPath(notePath); - if (!(file && file instanceof obsidian.TFile)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.app.vault.cachedRead(file)]; - case 1: - contentOrg = _a.sent(); - imageUrl = this.getContentImage(contentOrg, folderPath); - if (imageUrl.length > 0) { - card.setHeadImage(imageUrl); - } - contentBrief = this.getContentBrief(contentOrg); - if (contentBrief.length > 0) { - if (contentBrief.length > this.briefMax) { - contentBrief = contentBrief.substring(0, this.briefMax); - contentBrief += '...'; - } - card.setAbstract(contentBrief); - } - fileSt = file; - if (fileSt.stat) { - date = new Date(fileSt.stat.mtime); - card.setFootnote(date.toLocaleString()); - } - else { - card.setFootnote(notePath.replace(folderPath + '/', '')); - } - _a.label = 2; - case 2: - // return - return [2 /*return*/, card]; - } - }); - }); - }; - FolderBrief.prototype.getContentImage = function (contentOrg, folderPath) { - var imageUrl = ''; - // for patten: ![xxx.png] - var regexImg = new RegExp('!\\[(.*?)\\]\\((.*?)\\)'); - var match = regexImg.exec(contentOrg); - if (match != null) { - imageUrl = match[2]; - } - else { - // for patten: ![[xxx.png]] - var regexImg2 = new RegExp('!\\[\\[(.*?)\\]\\]'); - match = regexImg2.exec(contentOrg); - if (match != null) - imageUrl = match[1]; - } - // add image url - if (imageUrl.length > 0) { - if (!imageUrl.startsWith('http')) { - var headPath = folderPath; - var relativePath = false; - while (imageUrl.startsWith('../')) { - imageUrl = imageUrl.substring(3); - headPath = headPath.substring(0, headPath.lastIndexOf('/')); - relativePath = true; - } - if (relativePath) { - imageUrl = headPath + '/' + imageUrl; - } - imageUrl = imageUrl.replace(/\%20/g, ' '); - // imageUrl = this.app.vault.adapter.getResourcePath(imageUrl); - } - } - return imageUrl; - }; - FolderBrief.prototype.getContentBrief = function (contentOrg) { - // remove some special content - var content = contentOrg.trim(); - // skip yaml head - if (content.startsWith('---\r') || content.startsWith('---\n')) { - var hPos2 = content.indexOf('---', 4); - if (hPos2 >= 0 && (content[hPos2 - 1] == '\n' || (content[hPos2 - 1] == '\r'))) { - content = content.substring(hPos2 + 4).trim(); - } - } - content = content - // Remove YAML code - // .replace(/^---[\r\n][^(---)]*[\r\n]---[\r\n]/g, '') - // Remove HTML tags - .replace(/<[^>]*>/g, '') - // wiki style links - .replace(/\!\[\[(.*?)\]\]/g, '') - .replace(/\[\[(.*?)\]\]/g, '$1') - // Remove images - .replace(/\!\[(.*?)\][\[\(].*?[\]\)]/g, '') - // Remove inline links - .replace(/\[(.*?)\][\[\(].*?[\]\)]/g, '$1') - // Remove emphasis (repeat the line to remove double emphasis) - .replace(/([\*_]{1,3})(\S.*?\S{0,1})\1/g, '$2') - // Remove blockquotes - .replace(/\n(>|\>)(.*)/g, '') - // Remove code blocks - .replace(/(```[^\s]*\n[\s\S]*?\n```)/g, '') - // Remove inline code - .replace(/`(.+?)`/g, '$1') - .trim(); - // try to get the first paragraph - var contentBrief = ''; - content = '\n' + content + '\n'; - var regexP1 = new RegExp('\n([^\n|^#|^>])([^\n]+)\n', 'g'); - var match = null; - if ((match = regexP1.exec(content)) !== null) { - contentBrief = match[1] + match[2]; - } - // console.log('contentBrief', contentBrief); - contentBrief = contentBrief.trim(); - // use section headings - if (contentBrief.length == 0) { - var regexHead = new RegExp('^#{1,6}(?!#)(.*)[\r\n]', 'mg'); - while ((match = regexHead.exec(content)) !== null) { - contentBrief += match[1] + ', '; - if (contentBrief.length > this.briefMax) { - break; - } - } - if (contentBrief.endsWith(', ')) { - contentBrief = contentBrief.substring(0, contentBrief.length - 2); - } - } - // return - return contentBrief; - }; - return FolderBrief; -}()); - -// ------------------------------------------------------------ -// Folder Note -// ------------------------------------------------------------ -var NoteFileMethod; -(function (NoteFileMethod) { - NoteFileMethod[NoteFileMethod["Index"] = 0] = "Index"; - NoteFileMethod[NoteFileMethod["Inside"] = 1] = "Inside"; - NoteFileMethod[NoteFileMethod["Outside"] = 2] = "Outside"; -})(NoteFileMethod || (NoteFileMethod = {})); -var FolderNote = /** @class */ (function () { - function FolderNote(app, methodStr, indexBase) { - this.app = app; - this.setMethod(methodStr, indexBase); - this.emptyPath(); - // for rename - this.filesToRename = []; - this.filesToRenameSet = false; - } - // set the method - FolderNote.prototype.setMethod = function (methodStr, indexBase) { - if (methodStr == 'index') { - this.method = NoteFileMethod.Index; - this.indexBase = indexBase; - } - else if (methodStr == 'inside') { - this.method = NoteFileMethod.Inside; - } - else if (methodStr == 'outside') { - this.method = NoteFileMethod.Outside; - } - }; - // clear - FolderNote.prototype.emptyPath = function () { - this.folderPath = ''; - this.notePath = ''; - this.noteBase = ''; - }; - // set by folder path - FolderNote.prototype.setByFolderPath = function (path) { - this.emptyPath(); - var folderPath = path.trim(); - if (folderPath.length == 0) - return; - // set - this.folderPath = folderPath; - var notePaths = this.getFolderNotePath(folderPath); - this.notePath = notePaths[0]; - this.noteBase = notePaths[1]; - }; - // set by note, should ends with .md - FolderNote.prototype.setByNotePath = function (path) { - this.emptyPath(); - var notePath = path.trim(); - if (notePath.length == 0) - return; - if (!notePath.endsWith('.md')) - return; - // set - this.notePath = notePath; - this.noteBase = this.getFileBaseName(notePath); - this.folderPath = this.getNoteFolderPath(notePath); - }; - // set by folder element - FolderNote.prototype.setByFolderElement = function (folderItemEl) { - var folderPath = ''; - var folderName = ''; - var className = folderItemEl.className.toString(); - var folderElem = folderItemEl; - if (className.contains('nav-folder-title-content')) { - folderName = folderElem.getText(); - folderElem = folderItemEl.parentElement; - folderPath = folderElem.attributes.getNamedItem('data-path').textContent; - } - else if (className.contains('nav-folder-title')) { - folderPath = folderItemEl.attributes.getNamedItem('data-path').textContent; - folderName = folderItemEl.lastElementChild.getText(); - } - // fix the folder path - if (folderPath.length > 0) { - var slashLast = folderPath.lastIndexOf('/'); - var folderPathLast = folderPath.split('/').pop(); - if (folderPathLast != folderName) { - folderPath = folderPath.substring(0, slashLast + 1) + folderName; - } - } - // set to mine - this.setByFolderPath(folderPath); - // return the element in useage - return folderElem; - }; - // get file base name - FolderNote.prototype.getFileBaseName = function (filePath) { - var baseName = filePath.split('/').pop(); - var dotPos = baseName.lastIndexOf('.'); - if (dotPos > 0) - baseName = baseName.substring(0, dotPos); - return baseName; - }; - // get folder note path by folder path - FolderNote.prototype.getFolderNotePath = function (folderPath) { - var notePath = ''; - var noteBaseName = this.indexBase; - if (this.method == NoteFileMethod.Index) { - notePath = folderPath + '/' + noteBaseName + '.md'; - } - else { - noteBaseName = folderPath.split('/').pop(); - if (this.method == NoteFileMethod.Inside) { - notePath = folderPath + '/' + noteBaseName + '.md'; - } - else if (this.method == NoteFileMethod.Outside) { - notePath = folderPath + '.md'; - } - } - // console.log('notePath: ', notePath); - return [notePath, noteBaseName]; - }; - // get note folder, make sure it is a note file - FolderNote.prototype.getNoteFolderPath = function (notePath) { - var folderPath = ''; - if (this.method == NoteFileMethod.Index) { - folderPath = notePath.substring(0, notePath.lastIndexOf('/')); - } - else if (this.method == NoteFileMethod.Inside) { - folderPath = notePath.substring(0, notePath.lastIndexOf('/')); - } - else if (this.method == NoteFileMethod.Outside) { - folderPath = notePath.substring(0, notePath.length - 3); - } - return folderPath; - }; - // check if it is folder note name - FolderNote.prototype.isFolderNotePath = function (notePath) { - return __awaiter(this, void 0, void 0, function () { - var isFN, noteBaseName, folderPath; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - isFN = false; - if (!notePath.endsWith('.md')) - return [2 /*return*/, false]; - if (!(this.method == NoteFileMethod.Index)) return [3 /*break*/, 1]; - isFN = notePath.endsWith("/" + this.indexBase + ".md"); - return [3 /*break*/, 4]; - case 1: - if (!(this.method == NoteFileMethod.Inside)) return [3 /*break*/, 2]; - noteBaseName = this.getFileBaseName(notePath); - if (notePath.endsWith(noteBaseName + '/' + noteBaseName + '.md')) { - isFN = true; - } - return [3 /*break*/, 4]; - case 2: - if (!(this.method == NoteFileMethod.Outside)) return [3 /*break*/, 4]; - folderPath = notePath.substring(0, notePath.length - 3); - return [4 /*yield*/, this.app.vault.adapter.exists(folderPath)]; - case 3: - isFN = _a.sent(); - _a.label = 4; - case 4: return [2 /*return*/, isFN]; - } - }); - }); - }; - // check is folder note file? - FolderNote.prototype.isFolderNote = function (notePath) { - return __awaiter(this, void 0, void 0, function () { - var isFN, noteBaseName, folderPath; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - isFN = false; - if (!(this.method == NoteFileMethod.Index)) return [3 /*break*/, 1]; - isFN = notePath.endsWith("/" + this.indexBase + ".md"); - return [3 /*break*/, 4]; - case 1: - if (!(this.method == NoteFileMethod.Inside)) return [3 /*break*/, 2]; - noteBaseName = this.getFileBaseName(notePath); - isFN = notePath.endsWith(noteBaseName + "/" + noteBaseName + ".md"); - return [3 /*break*/, 4]; - case 2: - if (!(this.method == NoteFileMethod.Outside)) return [3 /*break*/, 4]; - folderPath = notePath.substring(0, notePath.length - 3); - return [4 /*yield*/, this.app.vault.adapter.exists(folderPath)]; - case 3: - isFN = _a.sent(); - _a.label = 4; - case 4: return [2 /*return*/, isFN]; - } - }); - }); - }; - // open note file - FolderNote.prototype.openFolderNote = function (folderElem, doCreate) { - return __awaiter(this, void 0, void 0, function () { - var folderNoteExists; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.app.vault.adapter.exists(this.notePath)]; - case 1: - folderNoteExists = _a.sent(); - if (!(!folderNoteExists && doCreate)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.newFolderNote()]; - case 2: - _a.sent(); - folderNoteExists = true; - _a.label = 3; - case 3: - // open the note - if (folderNoteExists) { - this.hideFolderNote(folderElem); - // show the note - this.app.workspace.openLinkText(this.notePath, '', false, { active: true }); - } - else if (folderElem.hasClass('has-folder-note')) { - folderElem.removeClass('has-folder-note'); - } - return [2 /*return*/]; - } - }); - }); - }; - // create folder note - FolderNote.prototype.newFolderNote = function () { - return __awaiter(this, void 0, void 0, function () { - var noteInitContent; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.expandContent(this.initContent)]; - case 1: - noteInitContent = _a.sent(); - return [4 /*yield*/, this.app.vault.adapter.write(this.notePath, noteInitContent)]; - case 2: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }; - // create folder by note - FolderNote.prototype.newNoteFolder = function () { - return __awaiter(this, void 0, void 0, function () { - var folderExists, folderPath, folderExists, newNotePath; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(this.method == NoteFileMethod.Outside)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.app.vault.adapter.exists(this.folderPath)]; - case 1: - folderExists = _a.sent(); - if (!!folderExists) return [3 /*break*/, 3]; - return [4 /*yield*/, this.app.vault.adapter.mkdir(this.folderPath)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [3 /*break*/, 8]; - case 4: - if (!(this.method == NoteFileMethod.Inside)) return [3 /*break*/, 8]; - folderPath = this.notePath.substring(0, this.notePath.length - 3); - return [4 /*yield*/, this.app.vault.adapter.exists(folderPath)]; - case 5: - folderExists = _a.sent(); - if (!!folderExists) return [3 /*break*/, 8]; - return [4 /*yield*/, this.app.vault.adapter.mkdir(folderPath)]; - case 6: - _a.sent(); - newNotePath = folderPath + '/' + this.noteBase + '.md'; - return [4 /*yield*/, this.app.vault.adapter.rename(this.notePath, newNotePath)]; - case 7: - _a.sent(); - this.app.workspace.openLinkText(newNotePath, '', false, { active: true }); - _a.label = 8; - case 8: return [2 /*return*/]; - } - }); - }); - }; - // expand content template - FolderNote.prototype.expandContent = function (template) { - return __awaiter(this, void 0, void 0, function () { - var folderName, content, folderBrief, briefCards, briefLiveCode; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - folderName = this.folderPath.split('/').pop(); - content = template - .replace(/{{FOLDER_NAME}}/g, folderName) - .replace(/{{FOLDER_PATH}}/g, this.folderPath); - if (!content.contains('{{FOLDER_BRIEF}}')) return [3 /*break*/, 2]; - folderBrief = new FolderBrief(this.app); - return [4 /*yield*/, folderBrief.makeBriefCards(this.folderPath, this.notePath)]; - case 1: - briefCards = _a.sent(); - content = content.replace('{{FOLDER_BRIEF}}', briefCards.getYamlCode()); - _a.label = 2; - case 2: - // keyword: {{FOLDER_BRIEF_LIVE}} - if (content.contains('{{FOLDER_BRIEF_LIVE}}')) { - briefLiveCode = '\n```ccard\ntype: folder_brief_live\n```\n'; - content = content.replace('{{FOLDER_BRIEF_LIVE}}', briefLiveCode); - } - return [2 /*return*/, content]; - } - }); - }); - }; - // hide folder note - FolderNote.prototype.hideFolderNote = function (folderElem) { - // modify the element - var hideSetting = this.hideNoteFile; - folderElem.addClass('has-folder-note'); - var parentElem = folderElem.parentElement; - var fileSelector = ':scope > div.nav-folder-children > div.nav-file > div.nav-file-title'; - var isOutsideMethod = (this.method == NoteFileMethod.Outside); - if (isOutsideMethod) { - parentElem = parentElem.parentElement; - fileSelector = ':scope > div.nav-file > div.nav-file-title'; - } - var noteBase = this.noteBase; - parentElem.querySelectorAll(fileSelector) - .forEach(function (fileElem) { - var fileNodeTitle = fileElem.firstElementChild.textContent; - // console.log('fileNoteTitle: ', fileNodeTitle); - if (hideSetting && (fileNodeTitle == noteBase)) { - fileElem.addClass('is-folder-note'); - } - else if (!isOutsideMethod) { - fileElem.removeClass('is-folder-note'); - } - // console.log('isOutsideMethod: ', isOutsideMethod); - }); - }; - // get the file breif path - FolderNote.prototype.getNoteFolderBriefPath = function (notePath) { - return __awaiter(this, void 0, void 0, function () { - var folderPath, isFN; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - folderPath = ''; - return [4 /*yield*/, this.isFolderNote(notePath)]; - case 1: - isFN = _a.sent(); - if (isFN) { - folderPath = this.getNoteFolderPath(notePath); - } - else { - folderPath = notePath.substring(0, notePath.lastIndexOf('/')); - } - return [2 /*return*/, folderPath]; - } - }); - }); - }; - // delete a folder - FolderNote.prototype.deleteFolder = function (pathToDel) { - return __awaiter(this, void 0, void 0, function () { - var myNotePath, noteExists; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(this.method == NoteFileMethod.Outside && !pathToDel.endsWith('.md'))) return [3 /*break*/, 3]; - myNotePath = pathToDel + '.md'; - return [4 /*yield*/, this.app.vault.adapter.exists(myNotePath)]; - case 1: - noteExists = _a.sent(); - if (!noteExists) return [3 /*break*/, 3]; - return [4 /*yield*/, this.app.vault.adapter.trashLocal(myNotePath)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); - }; - // sync folder / note name - FolderNote.prototype.syncName = function (newPath, oldPath) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(this.method == NoteFileMethod.Outside)) return [3 /*break*/, 2]; - return [4 /*yield*/, this.syncNameOutside(newPath, oldPath)]; - case 1: - _a.sent(); - return [3 /*break*/, 4]; - case 2: - if (!(this.method == NoteFileMethod.Inside)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.syncNameInside(newPath, oldPath)]; - case 3: - _a.sent(); - _a.label = 4; - case 4: return [2 /*return*/]; - } - }); - }); - }; - // sync folder / note name for outside - FolderNote.prototype.syncNameOutside = function (newPath, oldPath) { - return __awaiter(this, void 0, void 0, function () { - var noteExists, oldNotePaths, newNotePaths, isFN, oldFolderPath, newFolderPath; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!oldPath.endsWith('.md')) return [3 /*break*/, 4]; - return [4 /*yield*/, this.app.vault.adapter.exists(oldPath + '.md')]; - case 1: - noteExists = _a.sent(); - if (!noteExists) return [3 /*break*/, 3]; - oldNotePaths = this.getFolderNotePath(oldPath); - newNotePaths = this.getFolderNotePath(newPath.path); - if (!(oldNotePaths[1] != newNotePaths[1])) return [3 /*break*/, 3]; - return [4 /*yield*/, this.app.vault.adapter.rename(oldNotePaths[0], newNotePaths[0])]; - case 2: - _a.sent(); - _a.label = 3; - case 3: return [3 /*break*/, 7]; - case 4: return [4 /*yield*/, this.isFolderNote(oldPath)]; - case 5: - isFN = _a.sent(); - if (!isFN) return [3 /*break*/, 7]; - oldFolderPath = this.getNoteFolderPath(oldPath); - newFolderPath = this.getNoteFolderPath(newPath.path); - return [4 /*yield*/, this.app.vault.adapter.rename(oldFolderPath, newFolderPath)]; - case 6: - _a.sent(); - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); - }; - // sync folder / note name for inside case - FolderNote.prototype.syncNameInside = function (newPath, oldPath) { - return __awaiter(this, void 0, void 0, function () { - var oldNotePaths, newNotePaths, oldNotePathNew, noteExists, isFN, oldFolderPath, noteDir, noteBase, newFolderPath; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!!oldPath.endsWith('.md')) return [3 /*break*/, 2]; - oldNotePaths = this.getFolderNotePath(oldPath); - newNotePaths = this.getFolderNotePath(newPath.path); - oldNotePathNew = newPath.path + '/' + oldNotePaths[1] + '.md'; - return [4 /*yield*/, this.app.vault.adapter.exists(oldNotePathNew)]; - case 1: - noteExists = _a.sent(); - if (noteExists) { - if (newNotePaths[0] != oldNotePathNew) { - // put it to rename - this.filesToRename.push(oldNotePathNew); - this.filesToRename.push(newNotePaths[0]); - } - } - return [3 /*break*/, 4]; - case 2: - if (!(this.filesToRename.length == 0)) return [3 /*break*/, 4]; - return [4 /*yield*/, this.isFolderNote(oldPath)]; - case 3: - isFN = _a.sent(); - if (isFN) { - oldFolderPath = this.getNoteFolderPath(oldPath); - noteDir = newPath.path; - noteDir = noteDir.substring(0, noteDir.lastIndexOf('/')); - noteDir = noteDir.substring(0, noteDir.lastIndexOf('/')); - noteBase = newPath.path.split('/').pop(); - noteBase = noteBase.substring(0, noteBase.length - 3); - newFolderPath = ''; - if (noteDir.length > 0) { - newFolderPath = noteDir + '/' + noteBase; - } - else { - newFolderPath = noteBase; - } - // put it to rename - if (oldFolderPath != newFolderPath) { - this.filesToRename.push(oldFolderPath); - this.filesToRename.push(newFolderPath); - } - } - _a.label = 4; - case 4: - // only do once a time - if (!this.filesToRenameSet && this.filesToRename.length > 0) { - this.filesToRenameSet = true; - setTimeout(function () { - // console.log('rename is running after 1 s.'); - if (_this.filesToRename.length) { - var oldFolderPath = _this.filesToRename[0]; - var newFolderPath = _this.filesToRename[1]; - // console.log('Mod Old Path:', oldFolderPath); - // console.log('Mod New Path:', newFolderPath); - _this.app.vault.adapter.rename(oldFolderPath, newFolderPath); - _this.filesToRename = []; - _this.filesToRenameSet = false; - } - }, 1000); - } - return [2 /*return*/]; - } - }); - }); - }; - return FolderNote; -}()); - -function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -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 _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); -} - -function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); -} - -function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); -} - -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } -} - -function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); -} - -function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); -} - -function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function () { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; -} - -function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - - return object; -} - -function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - } - - return _get(target, property, receiver || target); -} - -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} - -function _toArray(arr) { - return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); -} - -function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; -} - -function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); -} - -function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; -} - -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); -} - -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; -} - -function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} - -function _createForOfIteratorHelper(o) { - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { - var i = 0; - - var F = function () {}; - - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var it, - normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = o[Symbol.iterator](); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; -} - -var Char = { - ANCHOR: '&', - COMMENT: '#', - TAG: '!', - DIRECTIVES_END: '-', - DOCUMENT_END: '.' -}; -var Type = { - ALIAS: 'ALIAS', - BLANK_LINE: 'BLANK_LINE', - BLOCK_FOLDED: 'BLOCK_FOLDED', - BLOCK_LITERAL: 'BLOCK_LITERAL', - COMMENT: 'COMMENT', - DIRECTIVE: 'DIRECTIVE', - DOCUMENT: 'DOCUMENT', - FLOW_MAP: 'FLOW_MAP', - FLOW_SEQ: 'FLOW_SEQ', - MAP: 'MAP', - MAP_KEY: 'MAP_KEY', - MAP_VALUE: 'MAP_VALUE', - PLAIN: 'PLAIN', - QUOTE_DOUBLE: 'QUOTE_DOUBLE', - QUOTE_SINGLE: 'QUOTE_SINGLE', - SEQ: 'SEQ', - SEQ_ITEM: 'SEQ_ITEM' -}; -var defaultTagPrefix = 'tag:yaml.org,2002:'; -var defaultTags = { - MAP: 'tag:yaml.org,2002:map', - SEQ: 'tag:yaml.org,2002:seq', - STR: 'tag:yaml.org,2002:str' -}; - -function findLineStarts(src) { - var ls = [0]; - var offset = src.indexOf('\n'); - - while (offset !== -1) { - offset += 1; - ls.push(offset); - offset = src.indexOf('\n', offset); - } - - return ls; -} - -function getSrcInfo(cst) { - var lineStarts, src; - - if (typeof cst === 'string') { - lineStarts = findLineStarts(cst); - src = cst; - } else { - if (Array.isArray(cst)) cst = cst[0]; - - if (cst && cst.context) { - if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); - lineStarts = cst.lineStarts; - src = cst.context.src; - } - } - - return { - lineStarts: lineStarts, - src: src - }; -} -/** - * @typedef {Object} LinePos - One-indexed position in the source - * @property {number} line - * @property {number} col - */ - -/** - * Determine the line/col position matching a character offset. - * - * Accepts a source string or a CST document as the second parameter. With - * the latter, starting indices for lines are cached in the document as - * `lineStarts: number[]`. - * - * Returns a one-indexed `{ line, col }` location if found, or - * `undefined` otherwise. - * - * @param {number} offset - * @param {string|Document|Document[]} cst - * @returns {?LinePos} - */ - - -function getLinePos(offset, cst) { - if (typeof offset !== 'number' || offset < 0) return null; - - var _getSrcInfo = getSrcInfo(cst), - lineStarts = _getSrcInfo.lineStarts, - src = _getSrcInfo.src; - - if (!lineStarts || !src || offset > src.length) return null; - - for (var i = 0; i < lineStarts.length; ++i) { - var start = lineStarts[i]; - - if (offset < start) { - return { - line: i, - col: offset - lineStarts[i - 1] + 1 - }; - } - - if (offset === start) return { - line: i + 1, - col: 1 - }; - } - - var line = lineStarts.length; - return { - line: line, - col: offset - lineStarts[line - 1] + 1 - }; -} -/** - * Get a specified line from the source. - * - * Accepts a source string or a CST document as the second parameter. With - * the latter, starting indices for lines are cached in the document as - * `lineStarts: number[]`. - * - * Returns the line as a string if found, or `null` otherwise. - * - * @param {number} line One-indexed line number - * @param {string|Document|Document[]} cst - * @returns {?string} - */ - -function getLine(line, cst) { - var _getSrcInfo2 = getSrcInfo(cst), - lineStarts = _getSrcInfo2.lineStarts, - src = _getSrcInfo2.src; - - if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; - var start = lineStarts[line - 1]; - var end = lineStarts[line]; // undefined for last line; that's ok for slice() - - while (end && end > start && src[end - 1] === '\n') { - --end; - } - - return src.slice(start, end); -} -/** - * Pretty-print the starting line from the source indicated by the range `pos` - * - * Trims output to `maxWidth` chars while keeping the starting column visible, - * using `…` at either end to indicate dropped characters. - * - * Returns a two-line string (or `null`) with `\n` as separator; the second line - * will hold appropriately indented `^` marks indicating the column range. - * - * @param {Object} pos - * @param {LinePos} pos.start - * @param {LinePos} [pos.end] - * @param {string|Document|Document[]*} cst - * @param {number} [maxWidth=80] - * @returns {?string} - */ - -function getPrettyContext(_ref, cst) { - var start = _ref.start, - end = _ref.end; - var maxWidth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 80; - var src = getLine(start.line, cst); - if (!src) return null; - var col = start.col; - - if (src.length > maxWidth) { - if (col <= maxWidth - 10) { - src = src.substr(0, maxWidth - 1) + '…'; - } else { - var halfWidth = Math.round(maxWidth / 2); - if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; - col -= src.length - maxWidth; - src = '…' + src.substr(1 - maxWidth); - } - } - - var errLen = 1; - var errEnd = ''; - - if (end) { - if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { - errLen = end.col - start.col; - } else { - errLen = Math.min(src.length + 1, maxWidth) - col; - errEnd = '…'; - } - } - - var offset = col > 1 ? ' '.repeat(col - 1) : ''; - var err = '^'.repeat(errLen); - return "".concat(src, "\n").concat(offset).concat(err).concat(errEnd); -} - -var Range = /*#__PURE__*/function () { - _createClass(Range, null, [{ - key: "copy", - value: function copy(orig) { - return new Range(orig.start, orig.end); - } - }]); - - function Range(start, end) { - _classCallCheck(this, Range); - - this.start = start; - this.end = end || start; - } - - _createClass(Range, [{ - key: "isEmpty", - value: function isEmpty() { - return typeof this.start !== 'number' || !this.end || this.end <= this.start; - } - /** - * Set `origStart` and `origEnd` to point to the original source range for - * this node, which may differ due to dropped CR characters. - * - * @param {number[]} cr - Positions of dropped CR characters - * @param {number} offset - Starting index of `cr` from the last call - * @returns {number} - The next offset, matching the one found for `origStart` - */ - - }, { - key: "setOrigRange", - value: function setOrigRange(cr, offset) { - var start = this.start, - end = this.end; - - if (cr.length === 0 || end <= cr[0]) { - this.origStart = start; - this.origEnd = end; - return offset; - } - - var i = offset; - - while (i < cr.length) { - if (cr[i] > start) break;else ++i; - } - - this.origStart = start + i; - var nextOffset = i; - - while (i < cr.length) { - // if end was at \n, it should now be at \r - if (cr[i] >= end) break;else ++i; - } - - this.origEnd = end + i; - return nextOffset; - } - }]); - - return Range; -}(); - -/** Root class of all nodes */ - -var Node = /*#__PURE__*/function () { - _createClass(Node, null, [{ - key: "addStringTerminator", - value: function addStringTerminator(src, offset, str) { - if (str[str.length - 1] === '\n') return str; - var next = Node.endOfWhiteSpace(src, offset); - return next >= src.length || src[next] === '\n' ? str + '\n' : str; - } // ^(---|...) - - }, { - key: "atDocumentBoundary", - value: function atDocumentBoundary(src, offset, sep) { - var ch0 = src[offset]; - if (!ch0) return true; - var prev = src[offset - 1]; - if (prev && prev !== '\n') return false; - - if (sep) { - if (ch0 !== sep) return false; - } else { - if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; - } - - var ch1 = src[offset + 1]; - var ch2 = src[offset + 2]; - if (ch1 !== ch0 || ch2 !== ch0) return false; - var ch3 = src[offset + 3]; - return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; - } - }, { - key: "endOfIdentifier", - value: function endOfIdentifier(src, offset) { - var ch = src[offset]; - var isVerbatim = ch === '<'; - var notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; - - while (ch && notOk.indexOf(ch) === -1) { - ch = src[offset += 1]; - } - - if (isVerbatim && ch === '>') offset += 1; - return offset; - } - }, { - key: "endOfIndent", - value: function endOfIndent(src, offset) { - var ch = src[offset]; - - while (ch === ' ') { - ch = src[offset += 1]; - } - - return offset; - } - }, { - key: "endOfLine", - value: function endOfLine(src, offset) { - var ch = src[offset]; - - while (ch && ch !== '\n') { - ch = src[offset += 1]; - } - - return offset; - } - }, { - key: "endOfWhiteSpace", - value: function endOfWhiteSpace(src, offset) { - var ch = src[offset]; - - while (ch === '\t' || ch === ' ') { - ch = src[offset += 1]; - } - - return offset; - } - }, { - key: "startOfLine", - value: function startOfLine(src, offset) { - var ch = src[offset - 1]; - if (ch === '\n') return offset; - - while (ch && ch !== '\n') { - ch = src[offset -= 1]; - } - - return offset + 1; - } - /** - * End of indentation, or null if the line's indent level is not more - * than `indent` - * - * @param {string} src - * @param {number} indent - * @param {number} lineStart - * @returns {?number} - */ - - }, { - key: "endOfBlockIndent", - value: function endOfBlockIndent(src, indent, lineStart) { - var inEnd = Node.endOfIndent(src, lineStart); - - if (inEnd > lineStart + indent) { - return inEnd; - } else { - var wsEnd = Node.endOfWhiteSpace(src, inEnd); - var ch = src[wsEnd]; - if (!ch || ch === '\n') return wsEnd; - } - - return null; - } - }, { - key: "atBlank", - value: function atBlank(src, offset, endAsBlank) { - var ch = src[offset]; - return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; - } - }, { - key: "nextNodeIsIndented", - value: function nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { - if (!ch || indentDiff < 0) return false; - if (indentDiff > 0) return true; - return indicatorAsIndent && ch === '-'; - } // should be at line or string end, or at next non-whitespace char - - }, { - key: "normalizeOffset", - value: function normalizeOffset(src, offset) { - var ch = src[offset]; - return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset); - } // fold single newline into space, multiple newlines to N - 1 newlines - // presumes src[offset] === '\n' - - }, { - key: "foldNewline", - value: function foldNewline(src, offset, indent) { - var inCount = 0; - var error = false; - var fold = ''; - var ch = src[offset + 1]; - - while (ch === ' ' || ch === '\t' || ch === '\n') { - switch (ch) { - case '\n': - inCount = 0; - offset += 1; - fold += '\n'; - break; - - case '\t': - if (inCount <= indent) error = true; - offset = Node.endOfWhiteSpace(src, offset + 2) - 1; - break; - - case ' ': - inCount += 1; - offset += 1; - break; - } - - ch = src[offset + 1]; - } - - if (!fold) fold = ' '; - if (ch && inCount <= indent) error = true; - return { - fold: fold, - offset: offset, - error: error - }; - } - }]); - - function Node(type, props, context) { - _classCallCheck(this, Node); - - Object.defineProperty(this, 'context', { - value: context || null, - writable: true - }); - this.error = null; - this.range = null; - this.valueRange = null; - this.props = props || []; - this.type = type; - this.value = null; - } - - _createClass(Node, [{ - key: "getPropValue", - value: function getPropValue(idx, key, skipKey) { - if (!this.context) return null; - var src = this.context.src; - var prop = this.props[idx]; - return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; - } - }, { - key: "commentHasRequiredWhitespace", - value: function commentHasRequiredWhitespace(start) { - var src = this.context.src; - if (this.header && start === this.header.end) return false; - if (!this.valueRange) return false; - var end = this.valueRange.end; - return start !== end || Node.atBlank(src, end - 1); - } - }, { - key: "parseComment", - value: function parseComment(start) { - var src = this.context.src; - - if (src[start] === Char.COMMENT) { - var end = Node.endOfLine(src, start + 1); - var commentRange = new Range(start, end); - this.props.push(commentRange); - return end; - } - - return start; - } - /** - * Populates the `origStart` and `origEnd` values of all ranges for this - * node. Extended by child classes to handle descendant nodes. - * - * @param {number[]} cr - Positions of dropped CR characters - * @param {number} offset - Starting index of `cr` from the last call - * @returns {number} - The next offset, matching the one found for `origStart` - */ - - }, { - key: "setOrigRanges", - value: function setOrigRanges(cr, offset) { - if (this.range) offset = this.range.setOrigRange(cr, offset); - if (this.valueRange) this.valueRange.setOrigRange(cr, offset); - this.props.forEach(function (prop) { - return prop.setOrigRange(cr, offset); - }); - return offset; - } - }, { - key: "toString", - value: function toString() { - var src = this.context.src, - range = this.range, - value = this.value; - if (value != null) return value; - var str = src.slice(range.start, range.end); - return Node.addStringTerminator(src, range.end, str); - } - }, { - key: "anchor", - get: function get() { - for (var i = 0; i < this.props.length; ++i) { - var anchor = this.getPropValue(i, Char.ANCHOR, true); - if (anchor != null) return anchor; - } - - return null; - } - }, { - key: "comment", - get: function get() { - var comments = []; - - for (var i = 0; i < this.props.length; ++i) { - var comment = this.getPropValue(i, Char.COMMENT, true); - if (comment != null) comments.push(comment); - } - - return comments.length > 0 ? comments.join('\n') : null; - } - }, { - key: "hasComment", - get: function get() { - if (this.context) { - var src = this.context.src; - - for (var i = 0; i < this.props.length; ++i) { - if (src[this.props[i].start] === Char.COMMENT) return true; - } - } - - return false; - } - }, { - key: "hasProps", - get: function get() { - if (this.context) { - var src = this.context.src; - - for (var i = 0; i < this.props.length; ++i) { - if (src[this.props[i].start] !== Char.COMMENT) return true; - } - } - - return false; - } - }, { - key: "includesTrailingLines", - get: function get() { - return false; - } - }, { - key: "jsonLike", - get: function get() { - var jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; - return jsonLikeTypes.indexOf(this.type) !== -1; - } - }, { - key: "rangeAsLinePos", - get: function get() { - if (!this.range || !this.context) return undefined; - var start = getLinePos(this.range.start, this.context.root); - if (!start) return undefined; - var end = getLinePos(this.range.end, this.context.root); - return { - start: start, - end: end - }; - } - }, { - key: "rawValue", - get: function get() { - if (!this.valueRange || !this.context) return null; - var _this$valueRange = this.valueRange, - start = _this$valueRange.start, - end = _this$valueRange.end; - return this.context.src.slice(start, end); - } - }, { - key: "tag", - get: function get() { - for (var i = 0; i < this.props.length; ++i) { - var tag = this.getPropValue(i, Char.TAG, false); - - if (tag != null) { - if (tag[1] === '<') { - return { - verbatim: tag.slice(2, -1) - }; - } else { - // eslint-disable-next-line no-unused-vars - var _tag$match = tag.match(/^(.*!)([^!]*)$/), - _tag$match2 = _slicedToArray(_tag$match, 3); - _tag$match2[0]; - var handle = _tag$match2[1], - suffix = _tag$match2[2]; - - return { - handle: handle, - suffix: suffix - }; - } - } - } - - return null; - } - }, { - key: "valueRangeContainsNewline", - get: function get() { - if (!this.valueRange || !this.context) return false; - var _this$valueRange2 = this.valueRange, - start = _this$valueRange2.start, - end = _this$valueRange2.end; - var src = this.context.src; - - for (var i = start; i < end; ++i) { - if (src[i] === '\n') return true; - } - - return false; - } - }]); - - return Node; -}(); - -var YAMLError = /*#__PURE__*/function (_Error) { - _inherits(YAMLError, _Error); - - var _super = _createSuper(YAMLError); - - function YAMLError(name, source, message) { - var _this; - - _classCallCheck(this, YAMLError); - - if (!message || !(source instanceof Node)) throw new Error("Invalid arguments for new ".concat(name)); - _this = _super.call(this); - _this.name = name; - _this.message = message; - _this.source = source; - return _this; - } - - _createClass(YAMLError, [{ - key: "makePretty", - value: function makePretty() { - if (!this.source) return; - this.nodeType = this.source.type; - var cst = this.source.context && this.source.context.root; - - if (typeof this.offset === 'number') { - this.range = new Range(this.offset, this.offset + 1); - var start = cst && getLinePos(this.offset, cst); - - if (start) { - var end = { - line: start.line, - col: start.col + 1 - }; - this.linePos = { - start: start, - end: end - }; - } - - delete this.offset; - } else { - this.range = this.source.range; - this.linePos = this.source.rangeAsLinePos; - } - - if (this.linePos) { - var _this$linePos$start = this.linePos.start, - line = _this$linePos$start.line, - col = _this$linePos$start.col; - this.message += " at line ".concat(line, ", column ").concat(col); - var ctx = cst && getPrettyContext(this.linePos, cst); - if (ctx) this.message += ":\n\n".concat(ctx, "\n"); - } - - delete this.source; - } - }]); - - return YAMLError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); -var YAMLReferenceError = /*#__PURE__*/function (_YAMLError) { - _inherits(YAMLReferenceError, _YAMLError); - - var _super2 = _createSuper(YAMLReferenceError); - - function YAMLReferenceError(source, message) { - _classCallCheck(this, YAMLReferenceError); - - return _super2.call(this, 'YAMLReferenceError', source, message); - } - - return YAMLReferenceError; -}(YAMLError); -var YAMLSemanticError = /*#__PURE__*/function (_YAMLError2) { - _inherits(YAMLSemanticError, _YAMLError2); - - var _super3 = _createSuper(YAMLSemanticError); - - function YAMLSemanticError(source, message) { - _classCallCheck(this, YAMLSemanticError); - - return _super3.call(this, 'YAMLSemanticError', source, message); - } - - return YAMLSemanticError; -}(YAMLError); -var YAMLSyntaxError = /*#__PURE__*/function (_YAMLError3) { - _inherits(YAMLSyntaxError, _YAMLError3); - - var _super4 = _createSuper(YAMLSyntaxError); - - function YAMLSyntaxError(source, message) { - _classCallCheck(this, YAMLSyntaxError); - - return _super4.call(this, 'YAMLSyntaxError', source, message); - } - - return YAMLSyntaxError; -}(YAMLError); -var YAMLWarning = /*#__PURE__*/function (_YAMLError4) { - _inherits(YAMLWarning, _YAMLError4); - - var _super5 = _createSuper(YAMLWarning); - - function YAMLWarning(source, message) { - _classCallCheck(this, YAMLWarning); - - return _super5.call(this, 'YAMLWarning', source, message); - } - - return YAMLWarning; -}(YAMLError); - -var PlainValue = /*#__PURE__*/function (_Node) { - _inherits(PlainValue, _Node); - - var _super = _createSuper(PlainValue); - - function PlainValue() { - _classCallCheck(this, PlainValue); - - return _super.apply(this, arguments); - } - - _createClass(PlainValue, [{ - key: "parseBlockValue", - value: function parseBlockValue(start) { - var _this$context = this.context, - indent = _this$context.indent, - inFlow = _this$context.inFlow, - src = _this$context.src; - var offset = start; - var valueEnd = start; - - for (var ch = src[offset]; ch === '\n'; ch = src[offset]) { - if (Node.atDocumentBoundary(src, offset + 1)) break; - var end = Node.endOfBlockIndent(src, indent, offset + 1); - if (end === null || src[end] === '#') break; - - if (src[end] === '\n') { - offset = end; - } else { - valueEnd = PlainValue.endOfLine(src, end, inFlow); - offset = valueEnd; - } - } - - if (this.valueRange.isEmpty()) this.valueRange.start = start; - this.valueRange.end = valueEnd; - return valueEnd; - } - /** - * Parses a plain value from the source - * - * Accepted forms are: - * ``` - * #comment - * - * first line - * - * first line #comment - * - * first line - * block - * lines - * - * #comment - * block - * lines - * ``` - * where block lines are empty or have an indent level greater than `indent`. - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar, may be `\n` - */ - - }, { - key: "parse", - value: function parse(context, start) { - this.context = context; - var inFlow = context.inFlow, - src = context.src; - var offset = start; - var ch = src[offset]; - - if (ch && ch !== '#' && ch !== '\n') { - offset = PlainValue.endOfLine(src, start, inFlow); - } - - this.valueRange = new Range(start, offset); - offset = Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - - if (!this.hasComment || this.valueRange.isEmpty()) { - offset = this.parseBlockValue(offset); - } - - return offset; - } - }, { - key: "strValue", - get: function get() { - if (!this.valueRange || !this.context) return null; - var _this$valueRange = this.valueRange, - start = _this$valueRange.start, - end = _this$valueRange.end; - var src = this.context.src; - var ch = src[end - 1]; - - while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) { - ch = src[--end - 1]; - } - - var str = ''; - - for (var i = start; i < end; ++i) { - var _ch = src[i]; - - if (_ch === '\n') { - var _Node$foldNewline = Node.foldNewline(src, i, -1), - fold = _Node$foldNewline.fold, - offset = _Node$foldNewline.offset; - - str += fold; - i = offset; - } else if (_ch === ' ' || _ch === '\t') { - // trim trailing whitespace - var wsStart = i; - var next = src[i + 1]; - - while (i < end && (next === ' ' || next === '\t')) { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : _ch; - } else { - str += _ch; - } - } - - var ch0 = src[start]; - - switch (ch0) { - case '\t': - { - var msg = 'Plain value cannot start with a tab character'; - var errors = [new YAMLSemanticError(this, msg)]; - return { - errors: errors, - str: str - }; - } - - case '@': - case '`': - { - var _msg = "Plain value cannot start with reserved character ".concat(ch0); - - var _errors = [new YAMLSemanticError(this, _msg)]; - return { - errors: _errors, - str: str - }; - } - - default: - return str; - } - } - }], [{ - key: "endOfLine", - value: function endOfLine(src, start, inFlow) { - var ch = src[start]; - var offset = start; - - while (ch && ch !== '\n') { - if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; - var next = src[offset + 1]; - if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; - if ((ch === ' ' || ch === '\t') && next === '#') break; - offset += 1; - ch = next; - } - - return offset; - } - }]); - - return PlainValue; -}(Node); - -var BlankLine = /*#__PURE__*/function (_Node) { - _inherits(BlankLine, _Node); - - var _super = _createSuper(BlankLine); - - function BlankLine() { - _classCallCheck(this, BlankLine); - - return _super.call(this, Type.BLANK_LINE); - } - /* istanbul ignore next */ - - - _createClass(BlankLine, [{ - key: "parse", - - /** - * Parses a blank line from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first \n character - * @returns {number} - Index of the character after this - */ - value: function parse(context, start) { - this.context = context; - this.range = new Range(start, start + 1); - return start + 1; - } - }, { - key: "includesTrailingLines", - get: function get() { - // This is never called from anywhere, but if it were, - // this is the value it should return. - return true; - } - }]); - - return BlankLine; -}(Node); - -var CollectionItem = /*#__PURE__*/function (_Node) { - _inherits(CollectionItem, _Node); - - var _super = _createSuper(CollectionItem); - - function CollectionItem(type, props) { - var _this; - - _classCallCheck(this, CollectionItem); - - _this = _super.call(this, type, props); - _this.node = null; - return _this; - } - - _createClass(CollectionItem, [{ - key: "parse", - - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - value: function parse(context, start) { - this.context = context; - var parseNode = context.parseNode, - src = context.src; - var atLineStart = context.atLineStart, - lineStart = context.lineStart; - if (!atLineStart && this.type === Type.SEQ_ITEM) this.error = new YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); - var indent = atLineStart ? start - lineStart : context.indent; - var offset = Node.endOfWhiteSpace(src, start + 1); - var ch = src[offset]; - var inlineComment = ch === '#'; - var comments = []; - var blankLine = null; - - while (ch === '\n' || ch === '#') { - if (ch === '#') { - var _end = Node.endOfLine(src, offset + 1); - - comments.push(new Range(offset, _end)); - offset = _end; - } else { - atLineStart = true; - lineStart = offset + 1; - var wsEnd = Node.endOfWhiteSpace(src, lineStart); - - if (src[wsEnd] === '\n' && comments.length === 0) { - blankLine = new BlankLine(); - lineStart = blankLine.parse({ - src: src - }, lineStart); - } - - offset = Node.endOfIndent(src, lineStart); - } - - ch = src[offset]; - } - - if (Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== Type.SEQ_ITEM)) { - this.node = parseNode({ - atLineStart: atLineStart, - inCollection: false, - indent: indent, - lineStart: lineStart, - parent: this - }, offset); - } else if (ch && lineStart > start + 1) { - offset = lineStart - 1; - } - - if (this.node) { - if (blankLine) { - // Only blank lines preceding non-empty nodes are captured. Note that - // this means that collection item range start indices do not always - // increase monotonically. -- eemeli/yaml#126 - var items = context.parent.items || context.parent.contents; - if (items) items.push(blankLine); - } - - if (comments.length) Array.prototype.push.apply(this.props, comments); - offset = this.node.range.end; - } else { - if (inlineComment) { - var c = comments[0]; - this.props.push(c); - offset = c.end; - } else { - offset = Node.endOfLine(src, start + 1); - } - } - - var end = this.node ? this.node.valueRange.end : offset; - this.valueRange = new Range(start, end); - return offset; - } - }, { - key: "setOrigRanges", - value: function setOrigRanges(cr, offset) { - offset = _get(_getPrototypeOf(CollectionItem.prototype), "setOrigRanges", this).call(this, cr, offset); - return this.node ? this.node.setOrigRanges(cr, offset) : offset; - } - }, { - key: "toString", - value: function toString() { - var src = this.context.src, - node = this.node, - range = this.range, - value = this.value; - if (value != null) return value; - var str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); - return Node.addStringTerminator(src, range.end, str); - } - }, { - key: "includesTrailingLines", - get: function get() { - return !!this.node && this.node.includesTrailingLines; - } - }]); - - return CollectionItem; -}(Node); - -var Comment = /*#__PURE__*/function (_Node) { - _inherits(Comment, _Node); - - var _super = _createSuper(Comment); - - function Comment() { - _classCallCheck(this, Comment); - - return _super.call(this, Type.COMMENT); - } - /** - * Parses a comment line from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - - _createClass(Comment, [{ - key: "parse", - value: function parse(context, start) { - this.context = context; - var offset = this.parseComment(start); - this.range = new Range(start, offset); - return offset; - } - }]); - - return Comment; -}(Node); - -function grabCollectionEndComments(node) { - var cnode = node; - - while (cnode instanceof CollectionItem) { - cnode = cnode.node; - } - - if (!(cnode instanceof Collection)) return null; - var len = cnode.items.length; - var ci = -1; - - for (var i = len - 1; i >= 0; --i) { - var n = cnode.items[i]; - - if (n.type === Type.COMMENT) { - // Keep sufficiently indented comments with preceding node - var _n$context = n.context, - indent = _n$context.indent, - lineStart = _n$context.lineStart; - if (indent > 0 && n.range.start >= lineStart + indent) break; - ci = i; - } else if (n.type === Type.BLANK_LINE) ci = i;else break; - } - - if (ci === -1) return null; - var ca = cnode.items.splice(ci, len - ci); - var prevEnd = ca[0].range.start; - - while (true) { - cnode.range.end = prevEnd; - if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; - if (cnode === node) break; - cnode = cnode.context.parent; - } - - return ca; -} -var Collection = /*#__PURE__*/function (_Node) { - _inherits(Collection, _Node); - - var _super = _createSuper(Collection); - - _createClass(Collection, null, [{ - key: "nextContentHasIndent", - value: function nextContentHasIndent(src, offset, indent) { - var lineStart = Node.endOfLine(src, offset) + 1; - offset = Node.endOfWhiteSpace(src, lineStart); - var ch = src[offset]; - if (!ch) return false; - if (offset >= lineStart + indent) return true; - if (ch !== '#' && ch !== '\n') return false; - return Collection.nextContentHasIndent(src, offset, indent); - } - }]); - - function Collection(firstItem) { - var _this; - - _classCallCheck(this, Collection); - - _this = _super.call(this, firstItem.type === Type.SEQ_ITEM ? Type.SEQ : Type.MAP); - - for (var i = firstItem.props.length - 1; i >= 0; --i) { - if (firstItem.props[i].start < firstItem.context.lineStart) { - // props on previous line are assumed by the collection - _this.props = firstItem.props.slice(0, i + 1); - firstItem.props = firstItem.props.slice(i + 1); - var itemRange = firstItem.props[0] || firstItem.valueRange; - firstItem.range.start = itemRange.start; - break; - } - } - - _this.items = [firstItem]; - var ec = grabCollectionEndComments(firstItem); - if (ec) Array.prototype.push.apply(_this.items, ec); - return _this; - } - - _createClass(Collection, [{ - key: "parse", - - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - value: function parse(context, start) { - this.context = context; - var parseNode = context.parseNode, - src = context.src; // It's easier to recalculate lineStart here rather than tracking down the - // last context from which to read it -- eemeli/yaml#2 - - var lineStart = Node.startOfLine(src, start); - var firstItem = this.items[0]; // First-item context needs to be correct for later comment handling - // -- eemeli/yaml#17 - - firstItem.context.parent = this; - this.valueRange = Range.copy(firstItem.valueRange); - var indent = firstItem.range.start - firstItem.context.lineStart; - var offset = start; - offset = Node.normalizeOffset(src, offset); - var ch = src[offset]; - var atLineStart = Node.endOfWhiteSpace(src, lineStart) === offset; - var prevIncludesTrailingLines = false; - - while (ch) { - while (ch === '\n' || ch === '#') { - if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { - var blankLine = new BlankLine(); - offset = blankLine.parse({ - src: src - }, offset); - this.valueRange.end = offset; - - if (offset >= src.length) { - ch = null; - break; - } - - this.items.push(blankLine); - offset -= 1; // blankLine.parse() consumes terminal newline - } else if (ch === '#') { - if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) { - return offset; - } - - var comment = new Comment(); - offset = comment.parse({ - indent: indent, - lineStart: lineStart, - src: src - }, offset); - this.items.push(comment); - this.valueRange.end = offset; - - if (offset >= src.length) { - ch = null; - break; - } - } - - lineStart = offset + 1; - offset = Node.endOfIndent(src, lineStart); - - if (Node.atBlank(src, offset)) { - var wsEnd = Node.endOfWhiteSpace(src, offset); - var next = src[wsEnd]; - - if (!next || next === '\n' || next === '#') { - offset = wsEnd; - } - } - - ch = src[offset]; - atLineStart = true; - } - - if (!ch) { - break; - } - - if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { - if (offset < lineStart + indent) { - if (lineStart > start) offset = lineStart; - break; - } else if (!this.error) { - var msg = 'All collection items must start at the same column'; - this.error = new YAMLSyntaxError(this, msg); - } - } - - if (firstItem.type === Type.SEQ_ITEM) { - if (ch !== '-') { - if (lineStart > start) offset = lineStart; - break; - } - } else if (ch === '-' && !this.error) { - // map key may start with -, as long as it's followed by a non-whitespace char - var _next = src[offset + 1]; - - if (!_next || _next === '\n' || _next === '\t' || _next === ' ') { - var _msg = 'A collection cannot be both a mapping and a sequence'; - this.error = new YAMLSyntaxError(this, _msg); - } - } - - var node = parseNode({ - atLineStart: atLineStart, - inCollection: true, - indent: indent, - lineStart: lineStart, - parent: this - }, offset); - if (!node) return offset; // at next document start - - this.items.push(node); - this.valueRange.end = node.valueRange.end; - offset = Node.normalizeOffset(src, node.range.end); - ch = src[offset]; - atLineStart = false; - prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range - // has advanced to check the current line's indentation level - // -- eemeli/yaml#10 & eemeli/yaml#38 - - if (ch) { - var ls = offset - 1; - var prev = src[ls]; - - while (prev === ' ' || prev === '\t') { - prev = src[--ls]; - } - - if (prev === '\n') { - lineStart = ls + 1; - atLineStart = true; - } - } - - var ec = grabCollectionEndComments(node); - if (ec) Array.prototype.push.apply(this.items, ec); - } - - return offset; - } - }, { - key: "setOrigRanges", - value: function setOrigRanges(cr, offset) { - offset = _get(_getPrototypeOf(Collection.prototype), "setOrigRanges", this).call(this, cr, offset); - this.items.forEach(function (node) { - offset = node.setOrigRanges(cr, offset); - }); - return offset; - } - }, { - key: "toString", - value: function toString() { - var src = this.context.src, - items = this.items, - range = this.range, - value = this.value; - if (value != null) return value; - var str = src.slice(range.start, items[0].range.start) + String(items[0]); - - for (var i = 1; i < items.length; ++i) { - var item = items[i]; - var _item$context = item.context, - atLineStart = _item$context.atLineStart, - indent = _item$context.indent; - if (atLineStart) for (var _i = 0; _i < indent; ++_i) { - str += ' '; - } - str += String(item); - } - - return Node.addStringTerminator(src, range.end, str); - } - }, { - key: "includesTrailingLines", - get: function get() { - return this.items.length > 0; - } - }]); - - return Collection; -}(Node); - -var Directive = /*#__PURE__*/function (_Node) { - _inherits(Directive, _Node); - - var _super = _createSuper(Directive); - - function Directive() { - var _this; - - _classCallCheck(this, Directive); - - _this = _super.call(this, Type.DIRECTIVE); - _this.name = null; - return _this; - } - - _createClass(Directive, [{ - key: "parseName", - value: function parseName(start) { - var src = this.context.src; - var offset = start; - var ch = src[offset]; - - while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') { - ch = src[offset += 1]; - } - - this.name = src.slice(start, offset); - return offset; - } - }, { - key: "parseParameters", - value: function parseParameters(start) { - var src = this.context.src; - var offset = start; - var ch = src[offset]; - - while (ch && ch !== '\n' && ch !== '#') { - ch = src[offset += 1]; - } - - this.valueRange = new Range(start, offset); - return offset; - } - }, { - key: "parse", - value: function parse(context, start) { - this.context = context; - var offset = this.parseName(start + 1); - offset = this.parseParameters(offset); - offset = this.parseComment(offset); - this.range = new Range(start, offset); - return offset; - } - }, { - key: "parameters", - get: function get() { - var raw = this.rawValue; - return raw ? raw.trim().split(/[ \t]+/) : []; - } - }]); - - return Directive; -}(Node); - -var Document = /*#__PURE__*/function (_Node) { - _inherits(Document, _Node); - - var _super = _createSuper(Document); - - _createClass(Document, null, [{ - key: "startCommentOrEndBlankLine", - value: function startCommentOrEndBlankLine(src, start) { - var offset = Node.endOfWhiteSpace(src, start); - var ch = src[offset]; - return ch === '#' || ch === '\n' ? offset : start; - } - }]); - - function Document() { - var _this; - - _classCallCheck(this, Document); - - _this = _super.call(this, Type.DOCUMENT); - _this.directives = null; - _this.contents = null; - _this.directivesEndMarker = null; - _this.documentEndMarker = null; - return _this; - } - - _createClass(Document, [{ - key: "parseDirectives", - value: function parseDirectives(start) { - var src = this.context.src; - this.directives = []; - var atLineStart = true; - var hasDirectives = false; - var offset = start; - - while (!Node.atDocumentBoundary(src, offset, Char.DIRECTIVES_END)) { - offset = Document.startCommentOrEndBlankLine(src, offset); - - switch (src[offset]) { - case '\n': - if (atLineStart) { - var blankLine = new BlankLine(); - offset = blankLine.parse({ - src: src - }, offset); - - if (offset < src.length) { - this.directives.push(blankLine); - } - } else { - offset += 1; - atLineStart = true; - } - - break; - - case '#': - { - var comment = new Comment(); - offset = comment.parse({ - src: src - }, offset); - this.directives.push(comment); - atLineStart = false; - } - break; - - case '%': - { - var directive = new Directive(); - offset = directive.parse({ - parent: this, - src: src - }, offset); - this.directives.push(directive); - hasDirectives = true; - atLineStart = false; - } - break; - - default: - if (hasDirectives) { - this.error = new YAMLSemanticError(this, 'Missing directives-end indicator line'); - } else if (this.directives.length > 0) { - this.contents = this.directives; - this.directives = []; - } - - return offset; - } - } - - if (src[offset]) { - this.directivesEndMarker = new Range(offset, offset + 3); - return offset + 3; - } - - if (hasDirectives) { - this.error = new YAMLSemanticError(this, 'Missing directives-end indicator line'); - } else if (this.directives.length > 0) { - this.contents = this.directives; - this.directives = []; - } - - return offset; - } - }, { - key: "parseContents", - value: function parseContents(start) { - var _this$context = this.context, - parseNode = _this$context.parseNode, - src = _this$context.src; - if (!this.contents) this.contents = []; - var lineStart = start; - - while (src[lineStart - 1] === '-') { - lineStart -= 1; - } - - var offset = Node.endOfWhiteSpace(src, start); - var atLineStart = lineStart === start; - this.valueRange = new Range(offset); - - while (!Node.atDocumentBoundary(src, offset, Char.DOCUMENT_END)) { - switch (src[offset]) { - case '\n': - if (atLineStart) { - var blankLine = new BlankLine(); - offset = blankLine.parse({ - src: src - }, offset); - - if (offset < src.length) { - this.contents.push(blankLine); - } - } else { - offset += 1; - atLineStart = true; - } - - lineStart = offset; - break; - - case '#': - { - var comment = new Comment(); - offset = comment.parse({ - src: src - }, offset); - this.contents.push(comment); - atLineStart = false; - } - break; - - default: - { - var iEnd = Node.endOfIndent(src, offset); - var context = { - atLineStart: atLineStart, - indent: -1, - inFlow: false, - inCollection: false, - lineStart: lineStart, - parent: this - }; - var node = parseNode(context, iEnd); - if (!node) return this.valueRange.end = iEnd; // at next document start - - this.contents.push(node); - offset = node.range.end; - atLineStart = false; - var ec = grabCollectionEndComments(node); - if (ec) Array.prototype.push.apply(this.contents, ec); - } - } - - offset = Document.startCommentOrEndBlankLine(src, offset); - } - - this.valueRange.end = offset; - - if (src[offset]) { - this.documentEndMarker = new Range(offset, offset + 3); - offset += 3; - - if (src[offset]) { - offset = Node.endOfWhiteSpace(src, offset); - - if (src[offset] === '#') { - var _comment = new Comment(); - - offset = _comment.parse({ - src: src - }, offset); - this.contents.push(_comment); - } - - switch (src[offset]) { - case '\n': - offset += 1; - break; - - case undefined: - break; - - default: - this.error = new YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); - } - } - } - - return offset; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - }, { - key: "parse", - value: function parse(context, start) { - context.root = this; - this.context = context; - var src = context.src; - var offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM - - offset = this.parseDirectives(offset); - offset = this.parseContents(offset); - return offset; - } - }, { - key: "setOrigRanges", - value: function setOrigRanges(cr, offset) { - offset = _get(_getPrototypeOf(Document.prototype), "setOrigRanges", this).call(this, cr, offset); - this.directives.forEach(function (node) { - offset = node.setOrigRanges(cr, offset); - }); - if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); - this.contents.forEach(function (node) { - offset = node.setOrigRanges(cr, offset); - }); - if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); - return offset; - } - }, { - key: "toString", - value: function toString() { - var contents = this.contents, - directives = this.directives, - value = this.value; - if (value != null) return value; - var str = directives.join(''); - - if (contents.length > 0) { - if (directives.length > 0 || contents[0].type === Type.COMMENT) str += '---\n'; - str += contents.join(''); - } - - if (str[str.length - 1] !== '\n') str += '\n'; - return str; - } - }]); - - return Document; -}(Node); - -var Alias = /*#__PURE__*/function (_Node) { - _inherits(Alias, _Node); - - var _super = _createSuper(Alias); - - function Alias() { - _classCallCheck(this, Alias); - - return _super.apply(this, arguments); - } - - _createClass(Alias, [{ - key: "parse", - - /** - * Parses an *alias from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - value: function parse(context, start) { - this.context = context; - var src = context.src; - var offset = Node.endOfIdentifier(src, start + 1); - this.valueRange = new Range(start + 1, offset); - offset = Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } - }]); - - return Alias; -}(Node); - -var Chomp = { - CLIP: 'CLIP', - KEEP: 'KEEP', - STRIP: 'STRIP' -}; -var BlockValue = /*#__PURE__*/function (_Node) { - _inherits(BlockValue, _Node); - - var _super = _createSuper(BlockValue); - - function BlockValue(type, props) { - var _this; - - _classCallCheck(this, BlockValue); - - _this = _super.call(this, type, props); - _this.blockIndent = null; - _this.chomping = Chomp.CLIP; - _this.header = null; - return _this; - } - - _createClass(BlockValue, [{ - key: "parseBlockHeader", - value: function parseBlockHeader(start) { - var src = this.context.src; - var offset = start + 1; - var bi = ''; - - while (true) { - var ch = src[offset]; - - switch (ch) { - case '-': - this.chomping = Chomp.STRIP; - break; - - case '+': - this.chomping = Chomp.KEEP; - break; - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - bi += ch; - break; - - default: - this.blockIndent = Number(bi) || null; - this.header = new Range(start, offset); - return offset; - } - - offset += 1; - } - } - }, { - key: "parseBlockValue", - value: function parseBlockValue(start) { - var _this$context = this.context, - indent = _this$context.indent, - src = _this$context.src; - var explicit = !!this.blockIndent; - var offset = start; - var valueEnd = start; - var minBlockIndent = 1; - - for (var ch = src[offset]; ch === '\n'; ch = src[offset]) { - offset += 1; - if (Node.atDocumentBoundary(src, offset)) break; - var end = Node.endOfBlockIndent(src, indent, offset); // should not include tab? - - if (end === null) break; - var _ch = src[end]; - var lineIndent = end - (offset + indent); - - if (!this.blockIndent) { - // no explicit block indent, none yet detected - if (src[end] !== '\n') { - // first line with non-whitespace content - if (lineIndent < minBlockIndent) { - var msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; - this.error = new YAMLSemanticError(this, msg); - } - - this.blockIndent = lineIndent; - } else if (lineIndent > minBlockIndent) { - // empty line with more whitespace - minBlockIndent = lineIndent; - } - } else if (_ch && _ch !== '\n' && lineIndent < this.blockIndent) { - if (src[end] === '#') break; - - if (!this.error) { - var _src = explicit ? 'explicit indentation indicator' : 'first line'; - - var _msg = "Block scalars must not be less indented than their ".concat(_src); - - this.error = new YAMLSemanticError(this, _msg); - } - } - - if (src[end] === '\n') { - offset = end; - } else { - offset = valueEnd = Node.endOfLine(src, end); - } - } - - if (this.chomping !== Chomp.KEEP) { - offset = src[valueEnd] ? valueEnd + 1 : valueEnd; - } - - this.valueRange = new Range(start + 1, offset); - return offset; - } - /** - * Parses a block value from the source - * - * Accepted forms are: - * ``` - * BS - * block - * lines - * - * BS #comment - * block - * lines - * ``` - * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines - * are empty or have an indent level greater than `indent`. - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this block - */ - - }, { - key: "parse", - value: function parse(context, start) { - this.context = context; - var src = context.src; - var offset = this.parseBlockHeader(start); - offset = Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - offset = this.parseBlockValue(offset); - return offset; - } - }, { - key: "setOrigRanges", - value: function setOrigRanges(cr, offset) { - offset = _get(_getPrototypeOf(BlockValue.prototype), "setOrigRanges", this).call(this, cr, offset); - return this.header ? this.header.setOrigRange(cr, offset) : offset; - } - }, { - key: "includesTrailingLines", - get: function get() { - return this.chomping === Chomp.KEEP; - } - }, { - key: "strValue", - get: function get() { - if (!this.valueRange || !this.context) return null; - var _this$valueRange = this.valueRange, - start = _this$valueRange.start, - end = _this$valueRange.end; - var _this$context2 = this.context, - indent = _this$context2.indent, - src = _this$context2.src; - if (this.valueRange.isEmpty()) return ''; - var lastNewLine = null; - var ch = src[end - 1]; - - while (ch === '\n' || ch === '\t' || ch === ' ') { - end -= 1; - - if (end <= start) { - if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens - } - - if (ch === '\n') lastNewLine = end; - ch = src[end - 1]; - } - - var keepStart = end + 1; - - if (lastNewLine) { - if (this.chomping === Chomp.KEEP) { - keepStart = lastNewLine; - end = this.valueRange.end; - } else { - end = lastNewLine; - } - } - - var bi = indent + this.blockIndent; - var folded = this.type === Type.BLOCK_FOLDED; - var atStart = true; - var str = ''; - var sep = ''; - var prevMoreIndented = false; - - for (var i = start; i < end; ++i) { - for (var j = 0; j < bi; ++j) { - if (src[i] !== ' ') break; - i += 1; - } - - var _ch2 = src[i]; - - if (_ch2 === '\n') { - if (sep === '\n') str += '\n';else sep = '\n'; - } else { - var lineEnd = Node.endOfLine(src, i); - var line = src.slice(i, lineEnd); - i = lineEnd; - - if (folded && (_ch2 === ' ' || _ch2 === '\t') && i < keepStart) { - if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; - str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') - - sep = lineEnd < end && src[lineEnd] || ''; - prevMoreIndented = true; - } else { - str += sep + line; - sep = folded && i < keepStart ? ' ' : '\n'; - prevMoreIndented = false; - } - - if (atStart && line !== '') atStart = false; - } - } - - return this.chomping === Chomp.STRIP ? str : str + '\n'; - } - }]); - - return BlockValue; -}(Node); - -var FlowCollection = /*#__PURE__*/function (_Node) { - _inherits(FlowCollection, _Node); - - var _super = _createSuper(FlowCollection); - - function FlowCollection(type, props) { - var _this; - - _classCallCheck(this, FlowCollection); - - _this = _super.call(this, type, props); - _this.items = null; - return _this; - } - - _createClass(FlowCollection, [{ - key: "prevNodeIsJsonLike", - value: function prevNodeIsJsonLike() { - var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.items.length; - var node = this.items[idx - 1]; - return !!node && (node.jsonLike || node.type === Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - }, { - key: "parse", - value: function parse(context, start) { - this.context = context; - var parseNode = context.parseNode, - src = context.src; - var indent = context.indent, - lineStart = context.lineStart; - var char = src[start]; // { or [ - - this.items = [{ - char: char, - offset: start - }]; - var offset = Node.endOfWhiteSpace(src, start + 1); - char = src[offset]; - - while (char && char !== ']' && char !== '}') { - switch (char) { - case '\n': - { - lineStart = offset + 1; - var wsEnd = Node.endOfWhiteSpace(src, lineStart); - - if (src[wsEnd] === '\n') { - var blankLine = new BlankLine(); - lineStart = blankLine.parse({ - src: src - }, lineStart); - this.items.push(blankLine); - } - - offset = Node.endOfIndent(src, lineStart); - - if (offset <= lineStart + indent) { - char = src[offset]; - - if (offset < lineStart + indent || char !== ']' && char !== '}') { - var msg = 'Insufficient indentation in flow collection'; - this.error = new YAMLSemanticError(this, msg); - } - } - } - break; - - case ',': - { - this.items.push({ - char: char, - offset: offset - }); - offset += 1; - } - break; - - case '#': - { - var comment = new Comment(); - offset = comment.parse({ - src: src - }, offset); - this.items.push(comment); - } - break; - - case '?': - case ':': - { - var next = src[offset + 1]; - - if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace - char === ':' && this.prevNodeIsJsonLike()) { - this.items.push({ - char: char, - offset: offset - }); - offset += 1; - break; - } - } - // fallthrough - - default: - { - var node = parseNode({ - atLineStart: false, - inCollection: false, - inFlow: true, - indent: -1, - lineStart: lineStart, - parent: this - }, offset); - - if (!node) { - // at next document start - this.valueRange = new Range(start, offset); - return offset; - } - - this.items.push(node); - offset = Node.normalizeOffset(src, node.range.end); - } - } - - offset = Node.endOfWhiteSpace(src, offset); - char = src[offset]; - } - - this.valueRange = new Range(start, offset + 1); - - if (char) { - this.items.push({ - char: char, - offset: offset - }); - offset = Node.endOfWhiteSpace(src, offset + 1); - offset = this.parseComment(offset); - } - - return offset; - } - }, { - key: "setOrigRanges", - value: function setOrigRanges(cr, offset) { - offset = _get(_getPrototypeOf(FlowCollection.prototype), "setOrigRanges", this).call(this, cr, offset); - this.items.forEach(function (node) { - if (node instanceof Node) { - offset = node.setOrigRanges(cr, offset); - } else if (cr.length === 0) { - node.origOffset = node.offset; - } else { - var i = offset; - - while (i < cr.length) { - if (cr[i] > node.offset) break;else ++i; - } - - node.origOffset = node.offset + i; - offset = i; - } - }); - return offset; - } - }, { - key: "toString", - value: function toString() { - var src = this.context.src, - items = this.items, - range = this.range, - value = this.value; - if (value != null) return value; - var nodes = items.filter(function (item) { - return item instanceof Node; - }); - var str = ''; - var prevEnd = range.start; - nodes.forEach(function (node) { - var prefix = src.slice(prevEnd, node.range.start); - prevEnd = node.range.end; - str += prefix + String(node); - - if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { - // Comment range does not include the terminal newline, but its - // stringified value does. Without this fix, newlines at comment ends - // get duplicated. - prevEnd += 1; - } - }); - str += src.slice(prevEnd, range.end); - return Node.addStringTerminator(src, range.end, str); - } - }]); - - return FlowCollection; -}(Node); - -var QuoteDouble = /*#__PURE__*/function (_Node) { - _inherits(QuoteDouble, _Node); - - var _super = _createSuper(QuoteDouble); - - function QuoteDouble() { - _classCallCheck(this, QuoteDouble); - - return _super.apply(this, arguments); - } - - _createClass(QuoteDouble, [{ - key: "parseCharCode", - value: function parseCharCode(offset, length, errors) { - var src = this.context.src; - var cc = src.substr(offset, length); - var ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); - var code = ok ? parseInt(cc, 16) : NaN; - - if (isNaN(code)) { - errors.push(new YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(offset - 2, length + 2)))); - return src.substr(offset - 2, length + 2); - } - - return String.fromCodePoint(code); - } - /** - * Parses a "double quoted" value from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - }, { - key: "parse", - value: function parse(context, start) { - this.context = context; - var src = context.src; - var offset = QuoteDouble.endOfQuote(src, start + 1); - this.valueRange = new Range(start, offset); - offset = Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } - }, { - key: "strValue", - - /** - * @returns {string | { str: string, errors: YAMLSyntaxError[] }} - */ - get: function get() { - if (!this.valueRange || !this.context) return null; - var errors = []; - var _this$valueRange = this.valueRange, - start = _this$valueRange.start, - end = _this$valueRange.end; - var _this$context = this.context, - indent = _this$context.indent, - src = _this$context.src; - if (src[end - 1] !== '"') errors.push(new YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by - // escaped backslashes; also, this should be faster. - - var str = ''; - - for (var i = start + 1; i < end - 1; ++i) { - var ch = src[i]; - - if (ch === '\n') { - if (Node.atDocumentBoundary(src, i + 1)) errors.push(new YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); - - var _Node$foldNewline = Node.foldNewline(src, i, indent), - fold = _Node$foldNewline.fold, - offset = _Node$foldNewline.offset, - error = _Node$foldNewline.error; - - str += fold; - i = offset; - if (error) errors.push(new YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); - } else if (ch === '\\') { - i += 1; - - switch (src[i]) { - case '0': - str += '\0'; - break; - // null character - - case 'a': - str += '\x07'; - break; - // bell character - - case 'b': - str += '\b'; - break; - // backspace - - case 'e': - str += '\x1b'; - break; - // escape character - - case 'f': - str += '\f'; - break; - // form feed - - case 'n': - str += '\n'; - break; - // line feed - - case 'r': - str += '\r'; - break; - // carriage return - - case 't': - str += '\t'; - break; - // horizontal tab - - case 'v': - str += '\v'; - break; - // vertical tab - - case 'N': - str += "\x85"; - break; - // Unicode next line - - case '_': - str += "\xA0"; - break; - // Unicode non-breaking space - - case 'L': - str += "\u2028"; - break; - // Unicode line separator - - case 'P': - str += "\u2029"; - break; - // Unicode paragraph separator - - case ' ': - str += ' '; - break; - - case '"': - str += '"'; - break; - - case '/': - str += '/'; - break; - - case '\\': - str += '\\'; - break; - - case '\t': - str += '\t'; - break; - - case 'x': - str += this.parseCharCode(i + 1, 2, errors); - i += 2; - break; - - case 'u': - str += this.parseCharCode(i + 1, 4, errors); - i += 4; - break; - - case 'U': - str += this.parseCharCode(i + 1, 8, errors); - i += 8; - break; - - case '\n': - // skip escaped newlines, but still trim the following line - while (src[i + 1] === ' ' || src[i + 1] === '\t') { - i += 1; - } - - break; - - default: - errors.push(new YAMLSyntaxError(this, "Invalid escape sequence ".concat(src.substr(i - 1, 2)))); - str += '\\' + src[i]; - } - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - var wsStart = i; - var next = src[i + 1]; - - while (next === ' ' || next === '\t') { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } - - return errors.length > 0 ? { - errors: errors, - str: str - } : str; - } - }], [{ - key: "endOfQuote", - value: function endOfQuote(src, offset) { - var ch = src[offset]; - - while (ch && ch !== '"') { - offset += ch === '\\' ? 2 : 1; - ch = src[offset]; - } - - return offset + 1; - } - }]); - - return QuoteDouble; -}(Node); - -var QuoteSingle = /*#__PURE__*/function (_Node) { - _inherits(QuoteSingle, _Node); - - var _super = _createSuper(QuoteSingle); - - function QuoteSingle() { - _classCallCheck(this, QuoteSingle); - - return _super.apply(this, arguments); - } - - _createClass(QuoteSingle, [{ - key: "parse", - - /** - * Parses a 'single quoted' value from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - value: function parse(context, start) { - this.context = context; - var src = context.src; - var offset = QuoteSingle.endOfQuote(src, start + 1); - this.valueRange = new Range(start, offset); - offset = Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } - }, { - key: "strValue", - - /** - * @returns {string | { str: string, errors: YAMLSyntaxError[] }} - */ - get: function get() { - if (!this.valueRange || !this.context) return null; - var errors = []; - var _this$valueRange = this.valueRange, - start = _this$valueRange.start, - end = _this$valueRange.end; - var _this$context = this.context, - indent = _this$context.indent, - src = _this$context.src; - if (src[end - 1] !== "'") errors.push(new YAMLSyntaxError(this, "Missing closing 'quote")); - var str = ''; - - for (var i = start + 1; i < end - 1; ++i) { - var ch = src[i]; - - if (ch === '\n') { - if (Node.atDocumentBoundary(src, i + 1)) errors.push(new YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); - - var _Node$foldNewline = Node.foldNewline(src, i, indent), - fold = _Node$foldNewline.fold, - offset = _Node$foldNewline.offset, - error = _Node$foldNewline.error; - - str += fold; - i = offset; - if (error) errors.push(new YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); - } else if (ch === "'") { - str += ch; - i += 1; - if (src[i] !== "'") errors.push(new YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - var wsStart = i; - var next = src[i + 1]; - - while (next === ' ' || next === '\t') { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } - - return errors.length > 0 ? { - errors: errors, - str: str - } : str; - } - }], [{ - key: "endOfQuote", - value: function endOfQuote(src, offset) { - var ch = src[offset]; - - while (ch) { - if (ch === "'") { - if (src[offset + 1] !== "'") break; - ch = src[offset += 2]; - } else { - ch = src[offset += 1]; - } - } - - return offset + 1; - } - }]); - - return QuoteSingle; -}(Node); - -function createNewNode(type, props) { - switch (type) { - case Type.ALIAS: - return new Alias(type, props); - - case Type.BLOCK_FOLDED: - case Type.BLOCK_LITERAL: - return new BlockValue(type, props); - - case Type.FLOW_MAP: - case Type.FLOW_SEQ: - return new FlowCollection(type, props); - - case Type.MAP_KEY: - case Type.MAP_VALUE: - case Type.SEQ_ITEM: - return new CollectionItem(type, props); - - case Type.COMMENT: - case Type.PLAIN: - return new PlainValue(type, props); - - case Type.QUOTE_DOUBLE: - return new QuoteDouble(type, props); - - case Type.QUOTE_SINGLE: - return new QuoteSingle(type, props); - - /* istanbul ignore next */ - - default: - return null; - // should never happen - } -} -/** - * @param {boolean} atLineStart - Node starts at beginning of line - * @param {boolean} inFlow - true if currently in a flow context - * @param {boolean} inCollection - true if currently in a collection context - * @param {number} indent - Current level of indentation - * @param {number} lineStart - Start of the current line - * @param {Node} parent - The parent of the node - * @param {string} src - Source of the YAML document - */ - - -var ParseContext = /*#__PURE__*/function () { - _createClass(ParseContext, null, [{ - key: "parseType", - value: function parseType(src, offset, inFlow) { - switch (src[offset]) { - case '*': - return Type.ALIAS; - - case '>': - return Type.BLOCK_FOLDED; - - case '|': - return Type.BLOCK_LITERAL; - - case '{': - return Type.FLOW_MAP; - - case '[': - return Type.FLOW_SEQ; - - case '?': - return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.MAP_KEY : Type.PLAIN; - - case ':': - return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.MAP_VALUE : Type.PLAIN; - - case '-': - return !inFlow && Node.atBlank(src, offset + 1, true) ? Type.SEQ_ITEM : Type.PLAIN; - - case '"': - return Type.QUOTE_DOUBLE; - - case "'": - return Type.QUOTE_SINGLE; - - default: - return Type.PLAIN; - } - } - }]); - - function ParseContext() { - var _this = this; - - var orig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - atLineStart = _ref.atLineStart, - inCollection = _ref.inCollection, - inFlow = _ref.inFlow, - indent = _ref.indent, - lineStart = _ref.lineStart, - parent = _ref.parent; - - _classCallCheck(this, ParseContext); - - _defineProperty(this, "parseNode", function (overlay, start) { - if (Node.atDocumentBoundary(_this.src, start)) return null; - var context = new ParseContext(_this, overlay); - - var _context$parseProps = context.parseProps(start), - props = _context$parseProps.props, - type = _context$parseProps.type, - valueStart = _context$parseProps.valueStart; - - var node = createNewNode(type, props); - var offset = node.parse(context, valueStart); - node.range = new Range(start, offset); - /* istanbul ignore if */ - - if (offset <= start) { - // This should never happen, but if it does, let's make sure to at least - // step one character forward to avoid a busy loop. - node.error = new Error("Node#parse consumed no characters"); - node.error.parseEnd = offset; - node.error.source = node; - node.range.end = start + 1; - } - - if (context.nodeStartsCollection(node)) { - if (!node.error && !context.atLineStart && context.parent.type === Type.DOCUMENT) { - node.error = new YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); - } - - var collection = new Collection(node); - offset = collection.parse(new ParseContext(context), offset); - collection.range = new Range(start, offset); - return collection; - } - - return node; - }); - - this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; - this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; - this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; - this.indent = indent != null ? indent : orig.indent; - this.lineStart = lineStart != null ? lineStart : orig.lineStart; - this.parent = parent != null ? parent : orig.parent || {}; - this.root = orig.root; - this.src = orig.src; - } - - _createClass(ParseContext, [{ - key: "nodeStartsCollection", - value: function nodeStartsCollection(node) { - var inCollection = this.inCollection, - inFlow = this.inFlow, - src = this.src; - if (inCollection || inFlow) return false; - if (node instanceof CollectionItem) return true; // check for implicit key - - var offset = node.range.end; - if (src[offset] === '\n' || src[offset - 1] === '\n') return false; - offset = Node.endOfWhiteSpace(src, offset); - return src[offset] === ':'; - } // Anchor and tag are before type, which determines the node implementation - // class; hence this intermediate step. - - }, { - key: "parseProps", - value: function parseProps(offset) { - var inFlow = this.inFlow, - parent = this.parent, - src = this.src; - var props = []; - var lineHasProps = false; - offset = this.atLineStart ? Node.endOfIndent(src, offset) : Node.endOfWhiteSpace(src, offset); - var ch = src[offset]; - - while (ch === Char.ANCHOR || ch === Char.COMMENT || ch === Char.TAG || ch === '\n') { - if (ch === '\n') { - var lineStart = offset + 1; - var inEnd = Node.endOfIndent(src, lineStart); - var indentDiff = inEnd - (lineStart + this.indent); - var noIndicatorAsIndent = parent.type === Type.SEQ_ITEM && parent.context.atLineStart; - if (!Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; - this.atLineStart = true; - this.lineStart = lineStart; - lineHasProps = false; - offset = inEnd; - } else if (ch === Char.COMMENT) { - var end = Node.endOfLine(src, offset + 1); - props.push(new Range(offset, end)); - offset = end; - } else { - var _end = Node.endOfIdentifier(src, offset + 1); - - if (ch === Char.TAG && src[_end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, _end + 13))) { - // Let's presume we're dealing with a YAML 1.0 domain tag here, rather - // than an empty but 'foo.bar' private-tagged node in a flow collection - // followed without whitespace by a plain string starting with a year - // or date divided by something. - _end = Node.endOfIdentifier(src, _end + 5); - } - - props.push(new Range(offset, _end)); - lineHasProps = true; - offset = Node.endOfWhiteSpace(src, _end); - } - - ch = src[offset]; - } // '- &a : b' has an anchor on an empty node - - - if (lineHasProps && ch === ':' && Node.atBlank(src, offset + 1, true)) offset -= 1; - var type = ParseContext.parseType(src, offset, inFlow); - return { - props: props, - type: type, - valueStart: offset - }; - } - /** - * Parses a node from the source - * @param {ParseContext} overlay - * @param {number} start - Index of first non-whitespace character for the node - * @returns {?Node} - null if at a document boundary - */ - - }]); - - return ParseContext; -}(); - -// Published as 'yaml/parse-cst' -function parse(src) { - var cr = []; - - if (src.indexOf('\r') !== -1) { - src = src.replace(/\r\n?/g, function (match, offset) { - if (match.length > 1) cr.push(offset); - return '\n'; - }); - } - - var documents = []; - var offset = 0; - - do { - var doc = new Document(); - var context = new ParseContext({ - src: src - }); - offset = doc.parse(context, offset); - documents.push(doc); - } while (offset < src.length); - - documents.setOrigRanges = function () { - if (cr.length === 0) return false; - - for (var i = 1; i < cr.length; ++i) { - cr[i] -= i; - } - - var crOffset = 0; - - for (var _i = 0; _i < documents.length; ++_i) { - crOffset = documents[_i].setOrigRanges(cr, crOffset); - } - - cr.splice(0, cr.length); - return true; - }; - - documents.toString = function () { - return documents.join('...\n'); - }; - - return documents; -} - -function addCommentBefore(str, indent, comment) { - if (!comment) return str; - var cc = comment.replace(/[\s\S]^/gm, "$&".concat(indent, "#")); - return "#".concat(cc, "\n").concat(indent).concat(str); -} -function addComment(str, indent, comment) { - return !comment ? str : comment.indexOf('\n') === -1 ? "".concat(str, " #").concat(comment) : "".concat(str, "\n") + comment.replace(/^/gm, "".concat(indent || '', "#")); -} - -var Node$1 = function Node() { - _classCallCheck(this, Node); -}; - -function toJSON(value, arg, ctx) { - if (Array.isArray(value)) return value.map(function (v, i) { - return toJSON(v, String(i), ctx); - }); - - if (value && typeof value.toJSON === 'function') { - var anchor = ctx && ctx.anchors && ctx.anchors.get(value); - if (anchor) ctx.onCreate = function (res) { - anchor.res = res; - delete ctx.onCreate; - }; - var res = value.toJSON(arg, ctx); - if (anchor && ctx.onCreate) ctx.onCreate(res); - return res; - } - - if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); - return value; -} - -var Scalar = /*#__PURE__*/function (_Node) { - _inherits(Scalar, _Node); - - var _super = _createSuper(Scalar); - - function Scalar(value) { - var _this; - - _classCallCheck(this, Scalar); - - _this = _super.call(this); - _this.value = value; - return _this; - } - - _createClass(Scalar, [{ - key: "toJSON", - value: function toJSON$1(arg, ctx) { - return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); - } - }, { - key: "toString", - value: function toString() { - return String(this.value); - } - }]); - - return Scalar; -}(Node$1); - -function collectionFromPath(schema, path, value) { - var v = value; - - for (var i = path.length - 1; i >= 0; --i) { - var k = path[i]; - var o = Number.isInteger(k) && k >= 0 ? [] : {}; - o[k] = v; - v = o; - } - - return schema.createNode(v, false); -} // null, undefined, or an empty non-string iterable (e.g. []) - - -var isEmptyPath = function isEmptyPath(path) { - return path == null || _typeof(path) === 'object' && path[Symbol.iterator]().next().done; -}; -var Collection$1 = /*#__PURE__*/function (_Node) { - _inherits(Collection, _Node); - - var _super = _createSuper(Collection); - - function Collection(schema) { - var _this; - - _classCallCheck(this, Collection); - - _this = _super.call(this); - - _defineProperty(_assertThisInitialized(_this), "items", []); - - _this.schema = schema; - return _this; - } - - _createClass(Collection, [{ - key: "addIn", - value: function addIn(path, value) { - if (isEmptyPath(path)) this.add(value);else { - var _path = _toArray(path), - key = _path[0], - rest = _path.slice(1); - - var node = this.get(key, true); - if (node instanceof Collection) node.addIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error("Expected YAML collection at ".concat(key, ". Remaining path: ").concat(rest)); - } - } - }, { - key: "deleteIn", - value: function deleteIn(_ref) { - var _ref2 = _toArray(_ref), - key = _ref2[0], - rest = _ref2.slice(1); - - if (rest.length === 0) return this.delete(key); - var node = this.get(key, true); - if (node instanceof Collection) return node.deleteIn(rest);else throw new Error("Expected YAML collection at ".concat(key, ". Remaining path: ").concat(rest)); - } - }, { - key: "getIn", - value: function getIn(_ref3, keepScalar) { - var _ref4 = _toArray(_ref3), - key = _ref4[0], - rest = _ref4.slice(1); - - var node = this.get(key, true); - if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; - } - }, { - key: "hasAllNullValues", - value: function hasAllNullValues() { - return this.items.every(function (node) { - if (!node || node.type !== 'PAIR') return false; - var n = node.value; - return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; - }); - } - }, { - key: "hasIn", - value: function hasIn(_ref5) { - var _ref6 = _toArray(_ref5), - key = _ref6[0], - rest = _ref6.slice(1); - - if (rest.length === 0) return this.has(key); - var node = this.get(key, true); - return node instanceof Collection ? node.hasIn(rest) : false; - } - }, { - key: "setIn", - value: function setIn(_ref7, value) { - var _ref8 = _toArray(_ref7), - key = _ref8[0], - rest = _ref8.slice(1); - - if (rest.length === 0) { - this.set(key, value); - } else { - var node = this.get(key, true); - if (node instanceof Collection) node.setIn(rest, value);else if (node === undefined && this.schema) this.set(key, collectionFromPath(this.schema, rest, value));else throw new Error("Expected YAML collection at ".concat(key, ". Remaining path: ").concat(rest)); - } - } // overridden in implementations - - /* istanbul ignore next */ - - }, { - key: "toJSON", - value: function toJSON() { - return null; - } - }, { - key: "toString", - value: function toString(ctx, _ref9, onComment, onChompKeep) { - var _this2 = this; - - var blockItem = _ref9.blockItem, - flowChars = _ref9.flowChars, - isMap = _ref9.isMap, - itemIndent = _ref9.itemIndent; - var _ctx = ctx, - indent = _ctx.indent, - indentStep = _ctx.indentStep, - stringify = _ctx.stringify; - var inFlow = this.type === Type.FLOW_MAP || this.type === Type.FLOW_SEQ || ctx.inFlow; - if (inFlow) itemIndent += indentStep; - var allNullValues = isMap && this.hasAllNullValues(); - ctx = Object.assign({}, ctx, { - allNullValues: allNullValues, - indent: itemIndent, - inFlow: inFlow, - type: null - }); - var chompKeep = false; - var hasItemWithNewLine = false; - var nodes = this.items.reduce(function (nodes, item, i) { - var comment; - - if (item) { - if (!chompKeep && item.spaceBefore) nodes.push({ - type: 'comment', - str: '' - }); - if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(function (line) { - nodes.push({ - type: 'comment', - str: "#".concat(line) - }); - }); - if (item.comment) comment = item.comment; - if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; - } - - chompKeep = false; - var str = stringify(item, ctx, function () { - return comment = null; - }, function () { - return chompKeep = true; - }); - if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; - if (inFlow && i < _this2.items.length - 1) str += ','; - str = addComment(str, itemIndent, comment); - if (chompKeep && (comment || inFlow)) chompKeep = false; - nodes.push({ - type: 'item', - str: str - }); - return nodes; - }, []); - var str; - - if (nodes.length === 0) { - str = flowChars.start + flowChars.end; - } else if (inFlow) { - var start = flowChars.start, - end = flowChars.end; - var strings = nodes.map(function (n) { - return n.str; - }); - - if (hasItemWithNewLine || strings.reduce(function (sum, str) { - return sum + str.length + 2; - }, 2) > Collection.maxFlowStringSingleLineLength) { - str = start; - - var _iterator = _createForOfIteratorHelper(strings), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var s = _step.value; - str += s ? "\n".concat(indentStep).concat(indent).concat(s) : '\n'; - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - str += "\n".concat(indent).concat(end); - } else { - str = "".concat(start, " ").concat(strings.join(' '), " ").concat(end); - } - } else { - var _strings = nodes.map(blockItem); - - str = _strings.shift(); - - var _iterator2 = _createForOfIteratorHelper(_strings), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var _s = _step2.value; - str += _s ? "\n".concat(indent).concat(_s) : '\n'; - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - - if (this.comment) { - str += '\n' + this.comment.replace(/^/gm, "".concat(indent, "#")); - if (onComment) onComment(); - } else if (chompKeep && onChompKeep) onChompKeep(); - - return str; - } - }]); - - return Collection; -}(Node$1); - -_defineProperty(Collection$1, "maxFlowStringSingleLineLength", 60); - -function asItemIndex(key) { - var idx = key instanceof Scalar ? key.value : key; - if (idx && typeof idx === 'string') idx = Number(idx); - return Number.isInteger(idx) && idx >= 0 ? idx : null; -} - -var YAMLSeq = /*#__PURE__*/function (_Collection) { - _inherits(YAMLSeq, _Collection); - - var _super = _createSuper(YAMLSeq); - - function YAMLSeq() { - _classCallCheck(this, YAMLSeq); - - return _super.apply(this, arguments); - } - - _createClass(YAMLSeq, [{ - key: "add", - value: function add(value) { - this.items.push(value); - } - }, { - key: "delete", - value: function _delete(key) { - var idx = asItemIndex(key); - if (typeof idx !== 'number') return false; - var del = this.items.splice(idx, 1); - return del.length > 0; - } - }, { - key: "get", - value: function get(key, keepScalar) { - var idx = asItemIndex(key); - if (typeof idx !== 'number') return undefined; - var it = this.items[idx]; - return !keepScalar && it instanceof Scalar ? it.value : it; - } - }, { - key: "has", - value: function has(key) { - var idx = asItemIndex(key); - return typeof idx === 'number' && idx < this.items.length; - } - }, { - key: "set", - value: function set(key, value) { - var idx = asItemIndex(key); - if (typeof idx !== 'number') throw new Error("Expected a valid index, not ".concat(key, ".")); - this.items[idx] = value; - } - }, { - key: "toJSON", - value: function toJSON$1(_, ctx) { - var seq = []; - if (ctx && ctx.onCreate) ctx.onCreate(seq); - var i = 0; - - var _iterator = _createForOfIteratorHelper(this.items), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var item = _step.value; - seq.push(toJSON(item, String(i++), ctx)); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return seq; - } - }, { - key: "toString", - value: function toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - return _get(_getPrototypeOf(YAMLSeq.prototype), "toString", this).call(this, ctx, { - blockItem: function blockItem(n) { - return n.type === 'comment' ? n.str : "- ".concat(n.str); - }, - flowChars: { - start: '[', - end: ']' - }, - isMap: false, - itemIndent: (ctx.indent || '') + ' ' - }, onComment, onChompKeep); - } - }]); - - return YAMLSeq; -}(Collection$1); - -var stringifyKey = function stringifyKey(key, jsKey, ctx) { - if (jsKey === null) return ''; - if (_typeof(jsKey) !== 'object') return String(jsKey); - if (key instanceof Node$1 && ctx && ctx.doc) return key.toString({ - anchors: {}, - doc: ctx.doc, - indent: '', - indentStep: ctx.indentStep, - inFlow: true, - inStringifyKey: true, - stringify: ctx.stringify - }); - return JSON.stringify(jsKey); -}; - -var Pair = /*#__PURE__*/function (_Node) { - _inherits(Pair, _Node); - - var _super = _createSuper(Pair); - - function Pair(key) { - var _this; - - var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - - _classCallCheck(this, Pair); - - _this = _super.call(this); - _this.key = key; - _this.value = value; - _this.type = Pair.Type.PAIR; - return _this; - } - - _createClass(Pair, [{ - key: "addToJSMap", - value: function addToJSMap(ctx, map) { - var key = toJSON(this.key, '', ctx); - - if (map instanceof Map) { - var value = toJSON(this.value, key, ctx); - map.set(key, value); - } else if (map instanceof Set) { - map.add(key); - } else { - var stringKey = stringifyKey(this.key, key, ctx); - map[stringKey] = toJSON(this.value, stringKey, ctx); - } - - return map; - } - }, { - key: "toJSON", - value: function toJSON(_, ctx) { - var pair = ctx && ctx.mapAsMap ? new Map() : {}; - return this.addToJSMap(ctx, pair); - } - }, { - key: "toString", - value: function toString(ctx, onComment, onChompKeep) { - if (!ctx || !ctx.doc) return JSON.stringify(this); - var _ctx$doc$options = ctx.doc.options, - indentSize = _ctx$doc$options.indent, - indentSeq = _ctx$doc$options.indentSeq, - simpleKeys = _ctx$doc$options.simpleKeys; - var key = this.key, - value = this.value; - var keyComment = key instanceof Node$1 && key.comment; - - if (simpleKeys) { - if (keyComment) { - throw new Error('With simple keys, key nodes cannot have comments'); - } - - if (key instanceof Collection$1) { - var msg = 'With simple keys, collection cannot be used as a key value'; - throw new Error(msg); - } - } - - var explicitKey = !simpleKeys && (!key || keyComment || key instanceof Collection$1 || key.type === Type.BLOCK_FOLDED || key.type === Type.BLOCK_LITERAL); - var _ctx = ctx, - doc = _ctx.doc, - indent = _ctx.indent, - indentStep = _ctx.indentStep, - stringify = _ctx.stringify; - ctx = Object.assign({}, ctx, { - implicitKey: !explicitKey, - indent: indent + indentStep - }); - var chompKeep = false; - var str = stringify(key, ctx, function () { - return keyComment = null; - }, function () { - return chompKeep = true; - }); - str = addComment(str, ctx.indent, keyComment); - - if (ctx.allNullValues && !simpleKeys) { - if (this.comment) { - str = addComment(str, ctx.indent, this.comment); - if (onComment) onComment(); - } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); - - return ctx.inFlow ? str : "? ".concat(str); - } - - str = explicitKey ? "? ".concat(str, "\n").concat(indent, ":") : "".concat(str, ":"); - - if (this.comment) { - // expected (but not strictly required) to be a single-line comment - str = addComment(str, ctx.indent, this.comment); - if (onComment) onComment(); - } - - var vcb = ''; - var valueComment = null; - - if (value instanceof Node$1) { - if (value.spaceBefore) vcb = '\n'; - - if (value.commentBefore) { - var cs = value.commentBefore.replace(/^/gm, "".concat(ctx.indent, "#")); - vcb += "\n".concat(cs); - } - - valueComment = value.comment; - } else if (value && _typeof(value) === 'object') { - value = doc.schema.createNode(value, true); - } - - ctx.implicitKey = false; - if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; - chompKeep = false; - - if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { - // If indentSeq === false, consider '- ' as part of indentation where possible - ctx.indent = ctx.indent.substr(2); - } - - var valueStr = stringify(value, ctx, function () { - return valueComment = null; - }, function () { - return chompKeep = true; - }); - var ws = ' '; - - if (vcb || this.comment) { - ws = "".concat(vcb, "\n").concat(ctx.indent); - } else if (!explicitKey && value instanceof Collection$1) { - var flow = valueStr[0] === '[' || valueStr[0] === '{'; - if (!flow || valueStr.includes('\n')) ws = "\n".concat(ctx.indent); - } - - if (chompKeep && !valueComment && onChompKeep) onChompKeep(); - return addComment(str + ws + valueStr, ctx.indent, valueComment); - } - }, { - key: "commentBefore", - get: function get() { - return this.key instanceof Node$1 ? this.key.commentBefore : undefined; - }, - set: function set(cb) { - if (this.key == null) this.key = new Scalar(null); - if (this.key instanceof Node$1) this.key.commentBefore = cb;else { - var msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; - throw new Error(msg); - } - } - }]); - - return Pair; -}(Node$1); - -_defineProperty(Pair, "Type", { - PAIR: 'PAIR', - MERGE_PAIR: 'MERGE_PAIR' -}); - -var getAliasCount = function getAliasCount(node, anchors) { - if (node instanceof Alias$1) { - var anchor = anchors.get(node.source); - return anchor.count * anchor.aliasCount; - } else if (node instanceof Collection$1) { - var count = 0; - - var _iterator = _createForOfIteratorHelper(node.items), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var item = _step.value; - var c = getAliasCount(item, anchors); - if (c > count) count = c; - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return count; - } else if (node instanceof Pair) { - var kc = getAliasCount(node.key, anchors); - var vc = getAliasCount(node.value, anchors); - return Math.max(kc, vc); - } - - return 1; -}; - -var Alias$1 = /*#__PURE__*/function (_Node) { - _inherits(Alias, _Node); - - var _super = _createSuper(Alias); - - _createClass(Alias, null, [{ - key: "stringify", - value: function stringify(_ref, _ref2) { - var range = _ref.range, - source = _ref.source; - var anchors = _ref2.anchors, - doc = _ref2.doc, - implicitKey = _ref2.implicitKey, - inStringifyKey = _ref2.inStringifyKey; - var anchor = Object.keys(anchors).find(function (a) { - return anchors[a] === source; - }); - if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); - if (anchor) return "*".concat(anchor).concat(implicitKey ? ' ' : ''); - var msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; - throw new Error("".concat(msg, " [").concat(range, "]")); - } - }]); - - function Alias(source) { - var _this; - - _classCallCheck(this, Alias); - - _this = _super.call(this); - _this.source = source; - _this.type = Type.ALIAS; - return _this; - } - - _createClass(Alias, [{ - key: "toJSON", - value: function toJSON$1(arg, ctx) { - if (!ctx) return toJSON(this.source, arg, ctx); - var anchors = ctx.anchors, - maxAliasCount = ctx.maxAliasCount; - var anchor = anchors.get(this.source); - /* istanbul ignore if */ - - if (!anchor || anchor.res === undefined) { - var msg = 'This should not happen: Alias anchor was not resolved?'; - if (this.cstNode) throw new YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); - } - - if (maxAliasCount >= 0) { - anchor.count += 1; - if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); - - if (anchor.count * anchor.aliasCount > maxAliasCount) { - var _msg = 'Excessive alias count indicates a resource exhaustion attack'; - if (this.cstNode) throw new YAMLReferenceError(this.cstNode, _msg);else throw new ReferenceError(_msg); - } - } - - return anchor.res; - } // Only called when stringifying an alias mapping key while constructing - // Object output. - - }, { - key: "toString", - value: function toString(ctx) { - return Alias.stringify(this, ctx); - } - }, { - key: "tag", - set: function set(t) { - throw new Error('Alias nodes cannot have tags'); - } - }]); - - return Alias; -}(Node$1); - -_defineProperty(Alias$1, "default", true); - -function findPair(items, key) { - var k = key instanceof Scalar ? key.value : key; - - var _iterator = _createForOfIteratorHelper(items), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var it = _step.value; - - if (it instanceof Pair) { - if (it.key === key || it.key === k) return it; - if (it.key && it.key.value === k) return it; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return undefined; -} -var YAMLMap = /*#__PURE__*/function (_Collection) { - _inherits(YAMLMap, _Collection); - - var _super = _createSuper(YAMLMap); - - function YAMLMap() { - _classCallCheck(this, YAMLMap); - - return _super.apply(this, arguments); - } - - _createClass(YAMLMap, [{ - key: "add", - value: function add(pair, overwrite) { - if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); - var prev = findPair(this.items, pair.key); - var sortEntries = this.schema && this.schema.sortMapEntries; - - if (prev) { - if (overwrite) prev.value = pair.value;else throw new Error("Key ".concat(pair.key, " already set")); - } else if (sortEntries) { - var i = this.items.findIndex(function (item) { - return sortEntries(pair, item) < 0; - }); - if (i === -1) this.items.push(pair);else this.items.splice(i, 0, pair); - } else { - this.items.push(pair); - } - } - }, { - key: "delete", - value: function _delete(key) { - var it = findPair(this.items, key); - if (!it) return false; - var del = this.items.splice(this.items.indexOf(it), 1); - return del.length > 0; - } - }, { - key: "get", - value: function get(key, keepScalar) { - var it = findPair(this.items, key); - var node = it && it.value; - return !keepScalar && node instanceof Scalar ? node.value : node; - } - }, { - key: "has", - value: function has(key) { - return !!findPair(this.items, key); - } - }, { - key: "set", - value: function set(key, value) { - this.add(new Pair(key, value), true); - } - /** - * @param {*} arg ignored - * @param {*} ctx Conversion context, originally set in Document#toJSON() - * @param {Class} Type If set, forces the returned collection type - * @returns {*} Instance of Type, Map, or Object - */ - - }, { - key: "toJSON", - value: function toJSON(_, ctx, Type) { - var map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; - if (ctx && ctx.onCreate) ctx.onCreate(map); - - var _iterator2 = _createForOfIteratorHelper(this.items), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var item = _step2.value; - item.addToJSMap(ctx, map); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - return map; - } - }, { - key: "toString", - value: function toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - - var _iterator3 = _createForOfIteratorHelper(this.items), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var item = _step3.value; - if (!(item instanceof Pair)) throw new Error("Map items must all be pairs; found ".concat(JSON.stringify(item), " instead")); - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - return _get(_getPrototypeOf(YAMLMap.prototype), "toString", this).call(this, ctx, { - blockItem: function blockItem(n) { - return n.str; - }, - flowChars: { - start: '{', - end: '}' - }, - isMap: true, - itemIndent: ctx.indent || '' - }, onComment, onChompKeep); - } - }]); - - return YAMLMap; -}(Collection$1); - -var MERGE_KEY = '<<'; -var Merge = /*#__PURE__*/function (_Pair) { - _inherits(Merge, _Pair); - - var _super = _createSuper(Merge); - - function Merge(pair) { - var _this; - - _classCallCheck(this, Merge); - - if (pair instanceof Pair) { - var seq = pair.value; - - if (!(seq instanceof YAMLSeq)) { - seq = new YAMLSeq(); - seq.items.push(pair.value); - seq.range = pair.value.range; - } - - _this = _super.call(this, pair.key, seq); - _this.range = pair.range; - } else { - _this = _super.call(this, new Scalar(MERGE_KEY), new YAMLSeq()); - } - - _this.type = Pair.Type.MERGE_PAIR; - return _possibleConstructorReturn(_this); - } // If the value associated with a merge key is a single mapping node, each of - // its key/value pairs is inserted into the current mapping, unless the key - // already exists in it. If the value associated with the merge key is a - // sequence, then this sequence is expected to contain mapping nodes and each - // of these nodes is merged in turn according to its order in the sequence. - // Keys in mapping nodes earlier in the sequence override keys specified in - // later mapping nodes. -- http://yaml.org/type/merge.html - - - _createClass(Merge, [{ - key: "addToJSMap", - value: function addToJSMap(ctx, map) { - var _iterator = _createForOfIteratorHelper(this.value.items), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var source = _step.value.source; - if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); - var srcMap = source.toJSON(null, ctx, Map); - - var _iterator2 = _createForOfIteratorHelper(srcMap), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var _step2$value = _slicedToArray(_step2.value, 2), - key = _step2$value[0], - value = _step2$value[1]; - - if (map instanceof Map) { - if (!map.has(key)) map.set(key, value); - } else if (map instanceof Set) { - map.add(key); - } else { - if (!Object.prototype.hasOwnProperty.call(map, key)) map[key] = value; - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return map; - } - }, { - key: "toString", - value: function toString(ctx, onComment) { - var seq = this.value; - if (seq.items.length > 1) return _get(_getPrototypeOf(Merge.prototype), "toString", this).call(this, ctx, onComment); - this.value = seq.items[0]; - - var str = _get(_getPrototypeOf(Merge.prototype), "toString", this).call(this, ctx, onComment); - - this.value = seq; - return str; - } - }]); - - return Merge; -}(Pair); - -var binaryOptions = { - defaultType: Type.BLOCK_LITERAL, - lineWidth: 76 -}; -var boolOptions = { - trueStr: 'true', - falseStr: 'false' -}; -var intOptions = { - asBigInt: false -}; -var nullOptions = { - nullStr: 'null' -}; -var strOptions = { - defaultType: Type.PLAIN, - doubleQuoted: { - jsonEncoding: false, - minMultiLineLength: 40 - }, - fold: { - lineWidth: 80, - minContentWidth: 20 - } -}; - -function resolveScalar(str, tags, scalarFallback) { - var _iterator = _createForOfIteratorHelper(tags), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _step.value, - format = _step$value.format, - test = _step$value.test, - resolve = _step$value.resolve; - - if (test) { - var match = str.match(test); - - if (match) { - var res = resolve.apply(null, match); - if (!(res instanceof Scalar)) res = new Scalar(res); - if (format) res.format = format; - return res; - } - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (scalarFallback) str = scalarFallback(str); - return new Scalar(str); -} - -var FOLD_FLOW = 'flow'; -var FOLD_BLOCK = 'block'; -var FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line -// returns index of last newline in more-indented block - -var consumeMoreIndentedLines = function consumeMoreIndentedLines(text, i) { - var ch = text[i + 1]; - - while (ch === ' ' || ch === '\t') { - do { - ch = text[i += 1]; - } while (ch && ch !== '\n'); - - ch = text[i + 1]; - } - - return i; -}; -/** - * Tries to keep input at up to `lineWidth` characters, splitting only on spaces - * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are - * terminated with `\n` and started with `indent`. - * - * @param {string} text - * @param {string} indent - * @param {string} [mode='flow'] `'block'` prevents more-indented lines - * from being folded; `'quoted'` allows for `\` escapes, including escaped - * newlines - * @param {Object} options - * @param {number} [options.indentAtStart] Accounts for leading contents on - * the first line, defaulting to `indent.length` - * @param {number} [options.lineWidth=80] - * @param {number} [options.minContentWidth=20] Allow highly indented lines to - * stretch the line width - * @param {function} options.onFold Called once if the text is folded - * @param {function} options.onFold Called once if any line of text exceeds - * lineWidth characters - */ - - -function foldFlowLines(text, indent, mode, _ref) { - var indentAtStart = _ref.indentAtStart, - _ref$lineWidth = _ref.lineWidth, - lineWidth = _ref$lineWidth === void 0 ? 80 : _ref$lineWidth, - _ref$minContentWidth = _ref.minContentWidth, - minContentWidth = _ref$minContentWidth === void 0 ? 20 : _ref$minContentWidth, - onFold = _ref.onFold, - onOverflow = _ref.onOverflow; - if (!lineWidth || lineWidth < 0) return text; - var endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); - if (text.length <= endStep) return text; - var folds = []; - var escapedFolds = {}; - var end = lineWidth - (typeof indentAtStart === 'number' ? indentAtStart : indent.length); - var split = undefined; - var prev = undefined; - var overflow = false; - var i = -1; - - if (mode === FOLD_BLOCK) { - i = consumeMoreIndentedLines(text, i); - if (i !== -1) end = i + endStep; - } - - for (var ch; ch = text[i += 1];) { - if (mode === FOLD_QUOTED && ch === '\\') { - switch (text[i + 1]) { - case 'x': - i += 3; - break; - - case 'u': - i += 5; - break; - - case 'U': - i += 9; - break; - - default: - i += 1; - } - } - - if (ch === '\n') { - if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i); - end = i + endStep; - split = undefined; - } else { - if (ch === ' ' && prev && prev !== ' ' && prev !== '\n' && prev !== '\t') { - // space surrounded by non-space can be replaced with newline + indent - var next = text[i + 1]; - if (next && next !== ' ' && next !== '\n' && next !== '\t') split = i; - } - - if (i >= end) { - if (split) { - folds.push(split); - end = split + endStep; - split = undefined; - } else if (mode === FOLD_QUOTED) { - // white-space collected at end may stretch past lineWidth - while (prev === ' ' || prev === '\t') { - prev = ch; - ch = text[i += 1]; - overflow = true; - } // i - 2 accounts for not-dropped last char + newline-escaping \ - - - folds.push(i - 2); - escapedFolds[i - 2] = true; - end = i - 2 + endStep; - split = undefined; - } else { - overflow = true; - } - } - } - - prev = ch; - } - - if (overflow && onOverflow) onOverflow(); - if (folds.length === 0) return text; - if (onFold) onFold(); - var res = text.slice(0, folds[0]); - - for (var _i = 0; _i < folds.length; ++_i) { - var fold = folds[_i]; - - var _end = folds[_i + 1] || text.length; - - if (mode === FOLD_QUOTED && escapedFolds[fold]) res += "".concat(text[fold], "\\"); - res += "\n".concat(indent).concat(text.slice(fold + 1, _end)); - } - - return res; -} - -var getFoldOptions = function getFoldOptions(_ref) { - var indentAtStart = _ref.indentAtStart; - return indentAtStart ? Object.assign({ - indentAtStart: indentAtStart - }, strOptions.fold) : strOptions.fold; -}; // Also checks for lines starting with %, as parsing the output as YAML 1.1 will -// presume that's starting a new document. - - -var containsDocumentMarker = function containsDocumentMarker(str) { - return /^(%|---|\.\.\.)/m.test(str); -}; - -function lineLengthOverLimit(str, limit) { - var strLen = str.length; - if (strLen <= limit) return false; - - for (var i = 0, start = 0; i < strLen; ++i) { - if (str[i] === '\n') { - if (i - start > limit) return true; - start = i + 1; - if (strLen - start <= limit) return false; - } - } - - return true; -} - -function doubleQuotedString(value, ctx) { - var implicitKey = ctx.implicitKey; - var _strOptions$doubleQuo = strOptions.doubleQuoted, - jsonEncoding = _strOptions$doubleQuo.jsonEncoding, - minMultiLineLength = _strOptions$doubleQuo.minMultiLineLength; - var json = JSON.stringify(value); - if (jsonEncoding) return json; - var indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); - var str = ''; - var start = 0; - - for (var i = 0, ch = json[i]; ch; ch = json[++i]) { - if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') { - // space before newline needs to be escaped to not be folded - str += json.slice(start, i) + '\\ '; - i += 1; - start = i; - ch = '\\'; - } - - if (ch === '\\') switch (json[i + 1]) { - case 'u': - { - str += json.slice(start, i); - var code = json.substr(i + 2, 4); - - switch (code) { - case '0000': - str += '\\0'; - break; - - case '0007': - str += '\\a'; - break; - - case '000b': - str += '\\v'; - break; - - case '001b': - str += '\\e'; - break; - - case '0085': - str += '\\N'; - break; - - case '00a0': - str += '\\_'; - break; - - case '2028': - str += '\\L'; - break; - - case '2029': - str += '\\P'; - break; - - default: - if (code.substr(0, 2) === '00') str += '\\x' + code.substr(2);else str += json.substr(i, 6); - } - - i += 5; - start = i + 1; - } - break; - - case 'n': - if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { - i += 1; - } else { - // folding will eat first newline - str += json.slice(start, i) + '\n\n'; - - while (json[i + 2] === '\\' && json[i + 3] === 'n' && json[i + 4] !== '"') { - str += '\n'; - i += 2; - } - - str += indent; // space after newline needs to be escaped to not be folded - - if (json[i + 2] === ' ') str += '\\'; - i += 1; - start = i + 1; - } - - break; - - default: - i += 1; - } - } - - str = start ? str + json.slice(start) : json; - return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); -} - -function singleQuotedString(value, ctx) { - if (ctx.implicitKey) { - if (/\n/.test(value)) return doubleQuotedString(value, ctx); - } else { - // single quoted string can't have leading or trailing whitespace around newline - if (/[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); - } - - var indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : ''); - var res = "'" + value.replace(/'/g, "''").replace(/\n+/g, "$&\n".concat(indent)) + "'"; - return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx)); -} - -function blockString(_ref2, ctx, onComment, onChompKeep) { - var comment = _ref2.comment, - type = _ref2.type, - value = _ref2.value; - - // 1. Block can't end in whitespace unless the last line is non-empty. - // 2. Strings consisting of only whitespace are best rendered explicitly. - if (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { - return doubleQuotedString(value, ctx); - } - - var indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); - var indentSize = indent ? '2' : '1'; // root is at -1 - - var literal = type === Type.BLOCK_FOLDED ? false : type === Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth - indent.length); - var header = literal ? '|' : '>'; - if (!value) return header + '\n'; - var wsStart = ''; - var wsEnd = ''; - value = value.replace(/[\n\t ]*$/, function (ws) { - var n = ws.indexOf('\n'); - - if (n === -1) { - header += '-'; // strip - } else if (value === ws || n !== ws.length - 1) { - header += '+'; // keep - - if (onChompKeep) onChompKeep(); - } - - wsEnd = ws.replace(/\n$/, ''); - return ''; - }).replace(/^[\n ]*/, function (ws) { - if (ws.indexOf(' ') !== -1) header += indentSize; - var m = ws.match(/ +$/); - - if (m) { - wsStart = ws.slice(0, -m[0].length); - return m[0]; - } else { - wsStart = ws; - return ''; - } - }); - if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, "$&".concat(indent)); - if (wsStart) wsStart = wsStart.replace(/\n+/g, "$&".concat(indent)); - - if (comment) { - header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); - if (onComment) onComment(); - } - - if (!value) return "".concat(header).concat(indentSize, "\n").concat(indent).concat(wsEnd); - - if (literal) { - value = value.replace(/\n+/g, "$&".concat(indent)); - return "".concat(header, "\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd); - } - - value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded - // ^ ind.line ^ empty ^ capture next empty lines only at end of indent - .replace(/\n+/g, "$&".concat(indent)); - var body = foldFlowLines("".concat(wsStart).concat(value).concat(wsEnd), indent, FOLD_BLOCK, strOptions.fold); - return "".concat(header, "\n").concat(indent).concat(body); -} - -function plainString(item, ctx, onComment, onChompKeep) { - var comment = item.comment, - type = item.type, - value = item.value; - var actualString = ctx.actualString, - implicitKey = ctx.implicitKey, - indent = ctx.indent, - inFlow = ctx.inFlow; - - if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { - return doubleQuotedString(value, ctx); - } - - if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { - // not allowed: - // - empty string, '-' or '?' - // - start with an indicator character (except [?:-]) or /[?-] / - // - '\n ', ': ' or ' \n' anywhere - // - '#' not preceded by a non-space char - // - end with ' ' or ':' - return implicitKey || inFlow || value.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); - } - - if (!implicitKey && !inFlow && type !== Type.PLAIN && value.indexOf('\n') !== -1) { - // Where allowed & type not set explicitly, prefer block style for multiline strings - return blockString(item, ctx, onComment, onChompKeep); - } - - if (indent === '' && containsDocumentMarker(value)) { - ctx.forceBlockIndent = true; - return blockString(item, ctx, onComment, onChompKeep); - } - - var str = value.replace(/\n+/g, "$&\n".concat(indent)); // Verify that output will be parsed as a string, as e.g. plain numbers and - // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'), - // and others in v1.1. - - if (actualString) { - var tags = ctx.doc.schema.tags; - var resolved = resolveScalar(str, tags, tags.scalarFallback).value; - if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); - } - - var body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); - - if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { - if (onComment) onComment(); - return addCommentBefore(body, indent, comment); - } - - return body; -} - -function stringifyString(item, ctx, onComment, onChompKeep) { - var defaultType = strOptions.defaultType; - var implicitKey = ctx.implicitKey, - inFlow = ctx.inFlow; - var _item = item, - type = _item.type, - value = _item.value; - - if (typeof value !== 'string') { - value = String(value); - item = Object.assign({}, item, { - value: value - }); - } - - var _stringify = function _stringify(_type) { - switch (_type) { - case Type.BLOCK_FOLDED: - case Type.BLOCK_LITERAL: - return blockString(item, ctx, onComment, onChompKeep); - - case Type.QUOTE_DOUBLE: - return doubleQuotedString(value, ctx); - - case Type.QUOTE_SINGLE: - return singleQuotedString(value, ctx); - - case Type.PLAIN: - return plainString(item, ctx, onComment, onChompKeep); - - default: - return null; - } - }; - - if (type !== Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { - // force double quotes on control characters - type = Type.QUOTE_DOUBLE; - } else if ((implicitKey || inFlow) && (type === Type.BLOCK_FOLDED || type === Type.BLOCK_LITERAL)) { - // should not happen; blocks are not valid inside flow containers - type = Type.QUOTE_DOUBLE; - } - - var res = _stringify(type); - - if (res === null) { - res = _stringify(defaultType); - if (res === null) throw new Error("Unsupported default string type ".concat(defaultType)); - } - - return res; -} - -function stringifyNumber(_ref) { - var format = _ref.format, - minFractionDigits = _ref.minFractionDigits, - tag = _ref.tag, - value = _ref.value; - if (typeof value === 'bigint') return String(value); - if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 0 ? '-.inf' : '.inf'; - var n = JSON.stringify(value); - - if (!format && minFractionDigits && (!tag || tag === 'tag:yaml.org,2002:float') && /^\d/.test(n)) { - var i = n.indexOf('.'); - - if (i < 0) { - i = n.length; - n += '.'; - } - - var d = minFractionDigits - (n.length - i - 1); - - while (d-- > 0) { - n += '0'; - } - } - - return n; -} - -function checkFlowCollectionEnd(errors, cst) { - var char, name; - - switch (cst.type) { - case Type.FLOW_MAP: - char = '}'; - name = 'flow map'; - break; - - case Type.FLOW_SEQ: - char = ']'; - name = 'flow sequence'; - break; - - default: - errors.push(new YAMLSemanticError(cst, 'Not a flow collection!?')); - return; - } - - var lastItem; - - for (var i = cst.items.length - 1; i >= 0; --i) { - var item = cst.items[i]; - - if (!item || item.type !== Type.COMMENT) { - lastItem = item; - break; - } - } - - if (lastItem && lastItem.char !== char) { - var msg = "Expected ".concat(name, " to end with ").concat(char); - var err; - - if (typeof lastItem.offset === 'number') { - err = new YAMLSemanticError(cst, msg); - err.offset = lastItem.offset + 1; - } else { - err = new YAMLSemanticError(lastItem, msg); - if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; - } - - errors.push(err); - } -} -function checkFlowCommentSpace(errors, comment) { - var prev = comment.context.src[comment.range.start - 1]; - - if (prev !== '\n' && prev !== '\t' && prev !== ' ') { - var msg = 'Comments must be separated from other tokens by white space characters'; - errors.push(new YAMLSemanticError(comment, msg)); - } -} -function getLongKeyError(source, key) { - var sk = String(key); - var k = sk.substr(0, 8) + '...' + sk.substr(-8); - return new YAMLSemanticError(source, "The \"".concat(k, "\" key is too long")); -} -function resolveComments(collection, comments) { - var _iterator = _createForOfIteratorHelper(comments), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _step.value, - afterKey = _step$value.afterKey, - before = _step$value.before, - comment = _step$value.comment; - var item = collection.items[before]; - - if (!item) { - if (comment !== undefined) { - if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; - } - } else { - if (afterKey && item.value) item = item.value; - - if (comment === undefined) { - if (afterKey || !item.commentBefore) item.spaceBefore = true; - } else { - if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; - } - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } -} - -// on error, will return { str: string, errors: Error[] } -function resolveString(doc, node) { - var res = node.strValue; - if (!res) return ''; - if (typeof res === 'string') return res; - res.errors.forEach(function (error) { - if (!error.source) error.source = node; - doc.errors.push(error); - }); - return res.str; -} - -function resolveTagHandle(doc, node) { - var _node$tag = node.tag, - handle = _node$tag.handle, - suffix = _node$tag.suffix; - var prefix = doc.tagPrefixes.find(function (p) { - return p.handle === handle; - }); - - if (!prefix) { - var dtp = doc.getDefaults().tagPrefixes; - if (dtp) prefix = dtp.find(function (p) { - return p.handle === handle; - }); - if (!prefix) throw new YAMLSemanticError(node, "The ".concat(handle, " tag handle is non-default and was not declared.")); - } - - if (!suffix) throw new YAMLSemanticError(node, "The ".concat(handle, " tag has no suffix.")); - - if (handle === '!' && (doc.version || doc.options.version) === '1.0') { - if (suffix[0] === '^') { - doc.warnings.push(new YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); - return suffix; - } - - if (/[:/]/.test(suffix)) { - // word/foo -> tag:word.yaml.org,2002:foo - var vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); - return vocab ? "tag:".concat(vocab[1], ".yaml.org,2002:").concat(vocab[2]) : "tag:".concat(suffix); - } - } - - return prefix.prefix + decodeURIComponent(suffix); -} - -function resolveTagName(doc, node) { - var tag = node.tag, - type = node.type; - var nonSpecific = false; - - if (tag) { - var handle = tag.handle, - suffix = tag.suffix, - verbatim = tag.verbatim; - - if (verbatim) { - if (verbatim !== '!' && verbatim !== '!!') return verbatim; - var msg = "Verbatim tags aren't resolved, so ".concat(verbatim, " is invalid."); - doc.errors.push(new YAMLSemanticError(node, msg)); - } else if (handle === '!' && !suffix) { - nonSpecific = true; - } else { - try { - return resolveTagHandle(doc, node); - } catch (error) { - doc.errors.push(error); - } - } - } - - switch (type) { - case Type.BLOCK_FOLDED: - case Type.BLOCK_LITERAL: - case Type.QUOTE_DOUBLE: - case Type.QUOTE_SINGLE: - return defaultTags.STR; - - case Type.FLOW_MAP: - case Type.MAP: - return defaultTags.MAP; - - case Type.FLOW_SEQ: - case Type.SEQ: - return defaultTags.SEQ; - - case Type.PLAIN: - return nonSpecific ? defaultTags.STR : null; - - default: - return null; - } -} - -function resolveByTagName(doc, node, tagName) { - var tags = doc.schema.tags; - var matchWithTest = []; - - var _iterator = _createForOfIteratorHelper(tags), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var tag = _step.value; - - if (tag.tag === tagName) { - if (tag.test) matchWithTest.push(tag);else { - var res = tag.resolve(doc, node); - return res instanceof Collection$1 ? res : new Scalar(res); - } - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - var str = resolveString(doc, node); - if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); - return null; -} - -function getFallbackTagName(_ref) { - var type = _ref.type; - - switch (type) { - case Type.FLOW_MAP: - case Type.MAP: - return defaultTags.MAP; - - case Type.FLOW_SEQ: - case Type.SEQ: - return defaultTags.SEQ; - - default: - return defaultTags.STR; - } -} - -function resolveTag(doc, node, tagName) { - try { - var res = resolveByTagName(doc, node, tagName); - - if (res) { - if (tagName && node.tag) res.tag = tagName; - return res; - } - } catch (error) { - /* istanbul ignore if */ - if (!error.source) error.source = node; - doc.errors.push(error); - return null; - } - - try { - var fallback = getFallbackTagName(node); - if (!fallback) throw new Error("The tag ".concat(tagName, " is unavailable")); - var msg = "The tag ".concat(tagName, " is unavailable, falling back to ").concat(fallback); - doc.warnings.push(new YAMLWarning(node, msg)); - - var _res = resolveByTagName(doc, node, fallback); - - _res.tag = tagName; - return _res; - } catch (error) { - var refError = new YAMLReferenceError(node, error.message); - refError.stack = error.stack; - doc.errors.push(refError); - return null; - } -} - -var isCollectionItem = function isCollectionItem(node) { - if (!node) return false; - var type = node.type; - return type === Type.MAP_KEY || type === Type.MAP_VALUE || type === Type.SEQ_ITEM; -}; - -function resolveNodeProps(errors, node) { - var comments = { - before: [], - after: [] - }; - var hasAnchor = false; - var hasTag = false; - var props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; - - var _iterator = _createForOfIteratorHelper(props), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _step.value, - start = _step$value.start, - end = _step$value.end; - - switch (node.context.src[start]) { - case Char.COMMENT: - { - if (!node.commentHasRequiredWhitespace(start)) { - var msg = 'Comments must be separated from other tokens by white space characters'; - errors.push(new YAMLSemanticError(node, msg)); - } - - var header = node.header, - valueRange = node.valueRange; - var cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; - cc.push(node.context.src.slice(start + 1, end)); - break; - } - // Actual anchor & tag resolution is handled by schema, here we just complain - - case Char.ANCHOR: - if (hasAnchor) { - var _msg = 'A node can have at most one anchor'; - errors.push(new YAMLSemanticError(node, _msg)); - } - - hasAnchor = true; - break; - - case Char.TAG: - if (hasTag) { - var _msg2 = 'A node can have at most one tag'; - errors.push(new YAMLSemanticError(node, _msg2)); - } - - hasTag = true; - break; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return { - comments: comments, - hasAnchor: hasAnchor, - hasTag: hasTag - }; -} - -function resolveNodeValue(doc, node) { - var anchors = doc.anchors, - errors = doc.errors, - schema = doc.schema; - - if (node.type === Type.ALIAS) { - var name = node.rawValue; - var src = anchors.getNode(name); - - if (!src) { - var msg = "Aliased anchor not found: ".concat(name); - errors.push(new YAMLReferenceError(node, msg)); - return null; - } // Lazy resolution for circular references - - - var res = new Alias$1(src); - - anchors._cstAliases.push(res); - - return res; - } - - var tagName = resolveTagName(doc, node); - if (tagName) return resolveTag(doc, node, tagName); - - if (node.type !== Type.PLAIN) { - var _msg3 = "Failed to resolve ".concat(node.type, " node here"); - - errors.push(new YAMLSyntaxError(node, _msg3)); - return null; - } - - try { - var str = resolveString(doc, node); - return resolveScalar(str, schema.tags, schema.tags.scalarFallback); - } catch (error) { - if (!error.source) error.source = node; - errors.push(error); - return null; - } -} // sets node.resolved on success - - -function resolveNode(doc, node) { - if (!node) return null; - if (node.error) doc.errors.push(node.error); - - var _resolveNodeProps = resolveNodeProps(doc.errors, node), - comments = _resolveNodeProps.comments, - hasAnchor = _resolveNodeProps.hasAnchor, - hasTag = _resolveNodeProps.hasTag; - - if (hasAnchor) { - var anchors = doc.anchors; - var name = node.anchor; - var prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor - // name have already been resolved, so it may safely be renamed. - - if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as - // anchors need to be available during resolution to allow for - // circular references. - - anchors.map[name] = node; - } - - if (node.type === Type.ALIAS && (hasAnchor || hasTag)) { - var msg = 'An alias node must not specify any properties'; - doc.errors.push(new YAMLSemanticError(node, msg)); - } - - var res = resolveNodeValue(doc, node); - - if (res) { - res.range = [node.range.start, node.range.end]; - if (doc.options.keepCstNodes) res.cstNode = node; - if (doc.options.keepNodeTypes) res.type = node.type; - var cb = comments.before.join('\n'); - - if (cb) { - res.commentBefore = res.commentBefore ? "".concat(res.commentBefore, "\n").concat(cb) : cb; - } - - var ca = comments.after.join('\n'); - if (ca) res.comment = res.comment ? "".concat(res.comment, "\n").concat(ca) : ca; - } - - return node.resolved = res; -} - -function resolveMap(doc, cst) { - if (cst.type !== Type.MAP && cst.type !== Type.FLOW_MAP) { - var msg = "A ".concat(cst.type, " node cannot be resolved as a mapping"); - doc.errors.push(new YAMLSyntaxError(cst, msg)); - return null; - } - - var _ref = cst.type === Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst), - comments = _ref.comments, - items = _ref.items; - - var map = new YAMLMap(); - map.items = items; - resolveComments(map, comments); - var hasCollectionKey = false; - - for (var i = 0; i < items.length; ++i) { - var iKey = items[i].key; - if (iKey instanceof Collection$1) hasCollectionKey = true; - - if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { - items[i] = new Merge(items[i]); - var sources = items[i].value.items; - var error = null; - sources.some(function (node) { - if (node instanceof Alias$1) { - // During parsing, alias sources are CST nodes; to account for - // circular references their resolved values can't be used here. - var type = node.source.type; - if (type === Type.MAP || type === Type.FLOW_MAP) return false; - return error = 'Merge nodes aliases can only point to maps'; - } - - return error = 'Merge nodes can only have Alias nodes as values'; - }); - if (error) doc.errors.push(new YAMLSemanticError(cst, error)); - } else { - for (var j = i + 1; j < items.length; ++j) { - var jKey = items[j].key; - - if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { - var _msg = "Map keys must be unique; \"".concat(iKey, "\" is repeated"); - - doc.errors.push(new YAMLSemanticError(cst, _msg)); - break; - } - } - } - } - - if (hasCollectionKey && !doc.options.mapAsMap) { - var warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; - doc.warnings.push(new YAMLWarning(cst, warn)); - } - - cst.resolved = map; - return map; -} - -var valueHasPairComment = function valueHasPairComment(_ref2) { - var _ref2$context = _ref2.context, - lineStart = _ref2$context.lineStart, - node = _ref2$context.node, - src = _ref2$context.src, - props = _ref2.props; - if (props.length === 0) return false; - var start = props[0].start; - if (node && start > node.valueRange.start) return false; - if (src[start] !== Char.COMMENT) return false; - - for (var i = lineStart; i < start; ++i) { - if (src[i] === '\n') return false; - } - - return true; -}; - -function resolvePairComment(item, pair) { - if (!valueHasPairComment(item)) return; - var comment = item.getPropValue(0, Char.COMMENT, true); - var found = false; - var cb = pair.value.commentBefore; - - if (cb && cb.startsWith(comment)) { - pair.value.commentBefore = cb.substr(comment.length + 1); - found = true; - } else { - var cc = pair.value.comment; - - if (!item.node && cc && cc.startsWith(comment)) { - pair.value.comment = cc.substr(comment.length + 1); - found = true; - } - } - - if (found) pair.comment = comment; -} - -function resolveBlockMapItems(doc, cst) { - var comments = []; - var items = []; - var key = undefined; - var keyStart = null; - - for (var i = 0; i < cst.items.length; ++i) { - var item = cst.items[i]; - - switch (item.type) { - case Type.BLANK_LINE: - comments.push({ - afterKey: !!key, - before: items.length - }); - break; - - case Type.COMMENT: - comments.push({ - afterKey: !!key, - before: items.length, - comment: item.comment - }); - break; - - case Type.MAP_KEY: - if (key !== undefined) items.push(new Pair(key)); - if (item.error) doc.errors.push(item.error); - key = resolveNode(doc, item.node); - keyStart = null; - break; - - case Type.MAP_VALUE: - { - if (key === undefined) key = null; - if (item.error) doc.errors.push(item.error); - - if (!item.context.atLineStart && item.node && item.node.type === Type.MAP && !item.node.context.atLineStart) { - var msg = 'Nested mappings are not allowed in compact mappings'; - doc.errors.push(new YAMLSemanticError(item.node, msg)); - } - - var valueNode = item.node; - - if (!valueNode && item.props.length > 0) { - // Comments on an empty mapping value need to be preserved, so we - // need to construct a minimal empty node here to use instead of the - // missing `item.node`. -- eemeli/yaml#19 - valueNode = new PlainValue(Type.PLAIN, []); - valueNode.context = { - parent: item, - src: item.context.src - }; - var pos = item.range.start + 1; - valueNode.range = { - start: pos, - end: pos - }; - valueNode.valueRange = { - start: pos, - end: pos - }; - - if (typeof item.range.origStart === 'number') { - var origPos = item.range.origStart + 1; - valueNode.range.origStart = valueNode.range.origEnd = origPos; - valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; - } - } - - var pair = new Pair(key, resolveNode(doc, valueNode)); - resolvePairComment(item, pair); - items.push(pair); - - if (key && typeof keyStart === 'number') { - if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); - } - - key = undefined; - keyStart = null; - } - break; - - default: - if (key !== undefined) items.push(new Pair(key)); - key = resolveNode(doc, item); - keyStart = item.range.start; - if (item.error) doc.errors.push(item.error); - - next: for (var j = i + 1;; ++j) { - var nextItem = cst.items[j]; - - switch (nextItem && nextItem.type) { - case Type.BLANK_LINE: - case Type.COMMENT: - continue next; - - case Type.MAP_VALUE: - break next; - - default: - { - var _msg2 = 'Implicit map keys need to be followed by map values'; - doc.errors.push(new YAMLSemanticError(item, _msg2)); - break next; - } - } - } - - if (item.valueRangeContainsNewline) { - var _msg3 = 'Implicit map keys need to be on a single line'; - doc.errors.push(new YAMLSemanticError(item, _msg3)); - } - - } - } - - if (key !== undefined) items.push(new Pair(key)); - return { - comments: comments, - items: items - }; -} - -function resolveFlowMapItems(doc, cst) { - var comments = []; - var items = []; - var key = undefined; - var explicitKey = false; - var next = '{'; - - for (var i = 0; i < cst.items.length; ++i) { - var item = cst.items[i]; - - if (typeof item.char === 'string') { - var char = item.char, - offset = item.offset; - - if (char === '?' && key === undefined && !explicitKey) { - explicitKey = true; - next = ':'; - continue; - } - - if (char === ':') { - if (key === undefined) key = null; - - if (next === ':') { - next = ','; - continue; - } - } else { - if (explicitKey) { - if (key === undefined && char !== ',') key = null; - explicitKey = false; - } - - if (key !== undefined) { - items.push(new Pair(key)); - key = undefined; - - if (char === ',') { - next = ':'; - continue; - } - } - } - - if (char === '}') { - if (i === cst.items.length - 1) continue; - } else if (char === next) { - next = ':'; - continue; - } - - var msg = "Flow map contains an unexpected ".concat(char); - var err = new YAMLSyntaxError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } else if (item.type === Type.BLANK_LINE) { - comments.push({ - afterKey: !!key, - before: items.length - }); - } else if (item.type === Type.COMMENT) { - checkFlowCommentSpace(doc.errors, item); - comments.push({ - afterKey: !!key, - before: items.length, - comment: item.comment - }); - } else if (key === undefined) { - if (next === ',') doc.errors.push(new YAMLSemanticError(item, 'Separator , missing in flow map')); - key = resolveNode(doc, item); - } else { - if (next !== ',') doc.errors.push(new YAMLSemanticError(item, 'Indicator : missing in flow map entry')); - items.push(new Pair(key, resolveNode(doc, item))); - key = undefined; - explicitKey = false; - } - } - - checkFlowCollectionEnd(doc.errors, cst); - if (key !== undefined) items.push(new Pair(key)); - return { - comments: comments, - items: items - }; -} - -function resolveSeq(doc, cst) { - if (cst.type !== Type.SEQ && cst.type !== Type.FLOW_SEQ) { - var msg = "A ".concat(cst.type, " node cannot be resolved as a sequence"); - doc.errors.push(new YAMLSyntaxError(cst, msg)); - return null; - } - - var _ref = cst.type === Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst), - comments = _ref.comments, - items = _ref.items; - - var seq = new YAMLSeq(); - seq.items = items; - resolveComments(seq, comments); - - if (!doc.options.mapAsMap && items.some(function (it) { - return it instanceof Pair && it.key instanceof Collection$1; - })) { - var warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; - doc.warnings.push(new YAMLWarning(cst, warn)); - } - - cst.resolved = seq; - return seq; -} - -function resolveBlockSeqItems(doc, cst) { - var comments = []; - var items = []; - - for (var i = 0; i < cst.items.length; ++i) { - var item = cst.items[i]; - - switch (item.type) { - case Type.BLANK_LINE: - comments.push({ - before: items.length - }); - break; - - case Type.COMMENT: - comments.push({ - comment: item.comment, - before: items.length - }); - break; - - case Type.SEQ_ITEM: - if (item.error) doc.errors.push(item.error); - items.push(resolveNode(doc, item.node)); - - if (item.hasProps) { - var msg = 'Sequence items cannot have tags or anchors before the - indicator'; - doc.errors.push(new YAMLSemanticError(item, msg)); - } - - break; - - default: - if (item.error) doc.errors.push(item.error); - doc.errors.push(new YAMLSyntaxError(item, "Unexpected ".concat(item.type, " node in sequence"))); - } - } - - return { - comments: comments, - items: items - }; -} - -function resolveFlowSeqItems(doc, cst) { - var comments = []; - var items = []; - var explicitKey = false; - var key = undefined; - var keyStart = null; - var next = '['; - var prevItem = null; - - for (var i = 0; i < cst.items.length; ++i) { - var item = cst.items[i]; - - if (typeof item.char === 'string') { - var char = item.char, - offset = item.offset; - - if (char !== ':' && (explicitKey || key !== undefined)) { - if (explicitKey && key === undefined) key = next ? items.pop() : null; - items.push(new Pair(key)); - explicitKey = false; - key = undefined; - keyStart = null; - } - - if (char === next) { - next = null; - } else if (!next && char === '?') { - explicitKey = true; - } else if (next !== '[' && char === ':' && key === undefined) { - if (next === ',') { - key = items.pop(); - - if (key instanceof Pair) { - var msg = 'Chaining flow sequence pairs is invalid'; - var err = new YAMLSemanticError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } - - if (!explicitKey && typeof keyStart === 'number') { - var keyEnd = item.range ? item.range.start : item.offset; - if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); - var src = prevItem.context.src; - - for (var _i = keyStart; _i < keyEnd; ++_i) { - if (src[_i] === '\n') { - var _msg = 'Implicit keys of flow sequence pairs need to be on a single line'; - doc.errors.push(new YAMLSemanticError(prevItem, _msg)); - break; - } - } - } - } else { - key = null; - } - - keyStart = null; - explicitKey = false; - next = null; - } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { - var _msg2 = "Flow sequence contains an unexpected ".concat(char); - - var _err = new YAMLSyntaxError(cst, _msg2); - - _err.offset = offset; - doc.errors.push(_err); - } - } else if (item.type === Type.BLANK_LINE) { - comments.push({ - before: items.length - }); - } else if (item.type === Type.COMMENT) { - checkFlowCommentSpace(doc.errors, item); - comments.push({ - comment: item.comment, - before: items.length - }); - } else { - if (next) { - var _msg3 = "Expected a ".concat(next, " in flow sequence"); - - doc.errors.push(new YAMLSemanticError(item, _msg3)); - } - - var value = resolveNode(doc, item); - - if (key === undefined) { - items.push(value); - prevItem = item; - } else { - items.push(new Pair(key, value)); - key = undefined; - } - - keyStart = item.range.start; - next = ','; - } - } - - checkFlowCollectionEnd(doc.errors, cst); - if (key !== undefined) items.push(new Pair(key)); - return { - comments: comments, - items: items - }; -} - -/* global atob, btoa, Buffer */ -var binary = { - identify: function identify(value) { - return value instanceof Uint8Array; - }, - // Buffer inherits from Uint8Array - default: false, - tag: 'tag:yaml.org,2002:binary', - - /** - * Returns a Buffer in node and an Uint8Array in browsers - * - * To use the resulting buffer as an image, you'll want to do something like: - * - * const blob = new Blob([buffer], { type: 'image/jpeg' }) - * document.querySelector('#photo').src = URL.createObjectURL(blob) - */ - resolve: function resolve(doc, node) { - var src = resolveString(doc, node); - - if (typeof Buffer === 'function') { - return Buffer.from(src, 'base64'); - } else if (typeof atob === 'function') { - // On IE 11, atob() can't handle newlines - var str = atob(src.replace(/[\n\r]/g, '')); - var buffer = new Uint8Array(str.length); - - for (var i = 0; i < str.length; ++i) { - buffer[i] = str.charCodeAt(i); - } - - return buffer; - } else { - var msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; - doc.errors.push(new YAMLReferenceError(node, msg)); - return null; - } - }, - options: binaryOptions, - stringify: function stringify(_ref, ctx, onComment, onChompKeep) { - var comment = _ref.comment, - type = _ref.type, - value = _ref.value; - var src; - - if (typeof Buffer === 'function') { - src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); - } else if (typeof btoa === 'function') { - var s = ''; - - for (var i = 0; i < value.length; ++i) { - s += String.fromCharCode(value[i]); - } - - src = btoa(s); - } else { - throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required'); - } - - if (!type) type = binaryOptions.defaultType; - - if (type === Type.QUOTE_DOUBLE) { - value = src; - } else { - var lineWidth = binaryOptions.lineWidth; - var n = Math.ceil(src.length / lineWidth); - var lines = new Array(n); - - for (var _i = 0, o = 0; _i < n; ++_i, o += lineWidth) { - lines[_i] = src.substr(o, lineWidth); - } - - value = lines.join(type === Type.BLOCK_LITERAL ? '\n' : ' '); - } - - return stringifyString({ - comment: comment, - type: type, - value: value - }, ctx, onComment, onChompKeep); - } -}; - -function parsePairs(doc, cst) { - var seq = resolveSeq(doc, cst); - - for (var i = 0; i < seq.items.length; ++i) { - var item = seq.items[i]; - if (item instanceof Pair) continue;else if (item instanceof YAMLMap) { - if (item.items.length > 1) { - var msg = 'Each pair must have its own sequence indicator'; - throw new YAMLSemanticError(cst, msg); - } - - var pair = item.items[0] || new Pair(); - if (item.commentBefore) pair.commentBefore = pair.commentBefore ? "".concat(item.commentBefore, "\n").concat(pair.commentBefore) : item.commentBefore; - if (item.comment) pair.comment = pair.comment ? "".concat(item.comment, "\n").concat(pair.comment) : item.comment; - item = pair; - } - seq.items[i] = item instanceof Pair ? item : new Pair(item); - } - - return seq; -} -function createPairs(schema, iterable, ctx) { - var pairs = new YAMLSeq(schema); - pairs.tag = 'tag:yaml.org,2002:pairs'; - - var _iterator = _createForOfIteratorHelper(iterable), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var it = _step.value; - var key = void 0, - value = void 0; - - if (Array.isArray(it)) { - if (it.length === 2) { - key = it[0]; - value = it[1]; - } else throw new TypeError("Expected [key, value] tuple: ".concat(it)); - } else if (it && it instanceof Object) { - var keys = Object.keys(it); - - if (keys.length === 1) { - key = keys[0]; - value = it[key]; - } else throw new TypeError("Expected { key: value } tuple: ".concat(it)); - } else { - key = it; - } - - var pair = schema.createPair(key, value, ctx); - pairs.items.push(pair); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return pairs; -} -var pairs = { - default: false, - tag: 'tag:yaml.org,2002:pairs', - resolve: parsePairs, - createNode: createPairs -}; - -var YAMLOMap = /*#__PURE__*/function (_YAMLSeq) { - _inherits(YAMLOMap, _YAMLSeq); - - var _super = _createSuper(YAMLOMap); - - function YAMLOMap() { - var _this; - - _classCallCheck(this, YAMLOMap); - - _this = _super.call(this); - - _defineProperty(_assertThisInitialized(_this), "add", YAMLMap.prototype.add.bind(_assertThisInitialized(_this))); - - _defineProperty(_assertThisInitialized(_this), "delete", YAMLMap.prototype.delete.bind(_assertThisInitialized(_this))); - - _defineProperty(_assertThisInitialized(_this), "get", YAMLMap.prototype.get.bind(_assertThisInitialized(_this))); - - _defineProperty(_assertThisInitialized(_this), "has", YAMLMap.prototype.has.bind(_assertThisInitialized(_this))); - - _defineProperty(_assertThisInitialized(_this), "set", YAMLMap.prototype.set.bind(_assertThisInitialized(_this))); - - _this.tag = YAMLOMap.tag; - return _this; - } - - _createClass(YAMLOMap, [{ - key: "toJSON", - value: function toJSON$1(_, ctx) { - var map = new Map(); - if (ctx && ctx.onCreate) ctx.onCreate(map); - - var _iterator = _createForOfIteratorHelper(this.items), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var pair = _step.value; - var key = void 0, - value = void 0; - - if (pair instanceof Pair) { - key = toJSON(pair.key, '', ctx); - value = toJSON(pair.value, key, ctx); - } else { - key = toJSON(pair, '', ctx); - } - - if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); - map.set(key, value); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return map; - } - }]); - - return YAMLOMap; -}(YAMLSeq); - -_defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); - -function parseOMap(doc, cst) { - var pairs = parsePairs(doc, cst); - var seenKeys = []; - - var _iterator2 = _createForOfIteratorHelper(pairs.items), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var key = _step2.value.key; - - if (key instanceof Scalar) { - if (seenKeys.includes(key.value)) { - var msg = 'Ordered maps must not include duplicate keys'; - throw new YAMLSemanticError(cst, msg); - } else { - seenKeys.push(key.value); - } - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - - return Object.assign(new YAMLOMap(), pairs); -} - -function createOMap(schema, iterable, ctx) { - var pairs = createPairs(schema, iterable, ctx); - var omap = new YAMLOMap(); - omap.items = pairs.items; - return omap; -} - -var omap = { - identify: function identify(value) { - return value instanceof Map; - }, - nodeClass: YAMLOMap, - default: false, - tag: 'tag:yaml.org,2002:omap', - resolve: parseOMap, - createNode: createOMap -}; - -var YAMLSet = /*#__PURE__*/function (_YAMLMap) { - _inherits(YAMLSet, _YAMLMap); - - var _super = _createSuper(YAMLSet); - - function YAMLSet() { - var _this; - - _classCallCheck(this, YAMLSet); - - _this = _super.call(this); - _this.tag = YAMLSet.tag; - return _this; - } - - _createClass(YAMLSet, [{ - key: "add", - value: function add(key) { - var pair = key instanceof Pair ? key : new Pair(key); - var prev = findPair(this.items, pair.key); - if (!prev) this.items.push(pair); - } - }, { - key: "get", - value: function get(key, keepPair) { - var pair = findPair(this.items, key); - return !keepPair && pair instanceof Pair ? pair.key instanceof Scalar ? pair.key.value : pair.key : pair; - } - }, { - key: "set", - value: function set(key, value) { - if (typeof value !== 'boolean') throw new Error("Expected boolean value for set(key, value) in a YAML set, not ".concat(_typeof(value))); - var prev = findPair(this.items, key); - - if (prev && !value) { - this.items.splice(this.items.indexOf(prev), 1); - } else if (!prev && value) { - this.items.push(new Pair(key)); - } - } - }, { - key: "toJSON", - value: function toJSON(_, ctx) { - return _get(_getPrototypeOf(YAMLSet.prototype), "toJSON", this).call(this, _, ctx, Set); - } - }, { - key: "toString", - value: function toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - if (this.hasAllNullValues()) return _get(_getPrototypeOf(YAMLSet.prototype), "toString", this).call(this, ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); - } - }]); - - return YAMLSet; -}(YAMLMap); - -_defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); - -function parseSet(doc, cst) { - var map = resolveMap(doc, cst); - if (!map.hasAllNullValues()) throw new YAMLSemanticError(cst, 'Set items must all have null values'); - return Object.assign(new YAMLSet(), map); -} - -function createSet(schema, iterable, ctx) { - var set = new YAMLSet(); - - var _iterator = _createForOfIteratorHelper(iterable), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var value = _step.value; - set.items.push(schema.createPair(value, null, ctx)); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return set; -} - -var set = { - identify: function identify(value) { - return value instanceof Set; - }, - nodeClass: YAMLSet, - default: false, - tag: 'tag:yaml.org,2002:set', - resolve: parseSet, - createNode: createSet -}; - -var parseSexagesimal = function parseSexagesimal(sign, parts) { - var n = parts.split(':').reduce(function (n, p) { - return n * 60 + Number(p); - }, 0); - return sign === '-' ? -n : n; -}; // hhhh:mm:ss.sss - - -var stringifySexagesimal = function stringifySexagesimal(_ref) { - var value = _ref.value; - if (isNaN(value) || !isFinite(value)) return stringifyNumber(value); - var sign = ''; - - if (value < 0) { - sign = '-'; - value = Math.abs(value); - } - - var parts = [value % 60]; // seconds, including ms - - if (value < 60) { - parts.unshift(0); // at least one : is required - } else { - value = Math.round((value - parts[0]) / 60); - parts.unshift(value % 60); // minutes - - if (value >= 60) { - value = Math.round((value - parts[0]) / 60); - parts.unshift(value); // hours - } - } - - return sign + parts.map(function (n) { - return n < 10 ? '0' + String(n) : String(n); - }).join(':').replace(/000000\d*$/, '') // % 60 may introduce error - ; -}; - -var intTime = { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'TIME', - test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, - resolve: function resolve(str, sign, parts) { - return parseSexagesimal(sign, parts.replace(/_/g, '')); - }, - stringify: stringifySexagesimal -}; -var floatTime = { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - format: 'TIME', - test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/, - resolve: function resolve(str, sign, parts) { - return parseSexagesimal(sign, parts.replace(/_/g, '')); - }, - stringify: stringifySexagesimal -}; -var timestamp = { - identify: function identify(value) { - return value instanceof Date; - }, - default: true, - tag: 'tag:yaml.org,2002:timestamp', - // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part - // may be omitted altogether, resulting in a date format. In such a case, the time part is - // assumed to be 00:00:00Z (start of day, UTC). - test: RegExp('^(?:' + '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd - '(?:(?:t|T|[ \\t]+)' + // t | T | whitespace - '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)? - '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30 - ')?' + ')$'), - resolve: function resolve(str, year, month, day, hour, minute, second, millisec, tz) { - if (millisec) millisec = (millisec + '00').substr(1, 3); - var date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); - - if (tz && tz !== 'Z') { - var d = parseSexagesimal(tz[0], tz.slice(1)); - if (Math.abs(d) < 30) d *= 60; - date -= 60000 * d; - } - - return new Date(date); - }, - stringify: function stringify(_ref2) { - var value = _ref2.value; - return value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, ''); - } -}; - -/* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ -function shouldWarn(deprecation) { - var env = typeof process !== 'undefined' && process.env || {}; - - if (deprecation) { - if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; - return !env.YAML_SILENCE_DEPRECATION_WARNINGS; - } - - if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; - return !env.YAML_SILENCE_WARNINGS; -} - -function warn(warning, type) { - if (shouldWarn(false)) { - var emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to - // https://github.com/facebook/jest/issues/2549 - - if (emit) emit(warning, type);else { - // eslint-disable-next-line no-console - console.warn(type ? "".concat(type, ": ").concat(warning) : warning); - } - } -} -var warned = {}; -function warnOptionDeprecation(name, alternative) { - if (!warned[name] && shouldWarn(true)) { - warned[name] = true; - var msg = "The option '".concat(name, "' will be removed in a future release"); - msg += alternative ? ", use '".concat(alternative, "' instead.") : '.'; - warn(msg, 'DeprecationWarning'); - } -} - -function createMap(schema, obj, ctx) { - var map = new YAMLMap(schema); - - if (obj instanceof Map) { - var _iterator = _createForOfIteratorHelper(obj), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _step$value = _slicedToArray(_step.value, 2), - key = _step$value[0], - value = _step$value[1]; - - map.items.push(schema.createPair(key, value, ctx)); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } else if (obj && _typeof(obj) === 'object') { - for (var _i = 0, _Object$keys = Object.keys(obj); _i < _Object$keys.length; _i++) { - var _key = _Object$keys[_i]; - map.items.push(schema.createPair(_key, obj[_key], ctx)); - } - } - - if (typeof schema.sortMapEntries === 'function') { - map.items.sort(schema.sortMapEntries); - } - - return map; -} - -var map = { - createNode: createMap, - default: true, - nodeClass: YAMLMap, - tag: 'tag:yaml.org,2002:map', - resolve: resolveMap -}; - -function createSeq(schema, obj, ctx) { - var seq = new YAMLSeq(schema); - - if (obj && obj[Symbol.iterator]) { - var _iterator = _createForOfIteratorHelper(obj), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var it = _step.value; - var v = schema.createNode(it, ctx.wrapScalars, null, ctx); - seq.items.push(v); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - - return seq; -} - -var seq = { - createNode: createSeq, - default: true, - nodeClass: YAMLSeq, - tag: 'tag:yaml.org,2002:seq', - resolve: resolveSeq -}; - -var string = { - identify: function identify(value) { - return typeof value === 'string'; - }, - default: true, - tag: 'tag:yaml.org,2002:str', - resolve: resolveString, - stringify: function stringify(item, ctx, onComment, onChompKeep) { - ctx = Object.assign({ - actualString: true - }, ctx); - return stringifyString(item, ctx, onComment, onChompKeep); - }, - options: strOptions -}; - -var failsafe = [map, seq, string]; - -/* global BigInt */ - -var intIdentify = function intIdentify(value) { - return typeof value === 'bigint' || Number.isInteger(value); -}; - -var intResolve = function intResolve(src, part, radix) { - return intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); -}; - -function intStringify(node, radix, prefix) { - var value = node.value; - if (intIdentify(value) && value >= 0) return prefix + value.toString(radix); - return stringifyNumber(node); -} - -var nullObj = { - identify: function identify(value) { - return value == null; - }, - createNode: function createNode(schema, value, ctx) { - return ctx.wrapScalars ? new Scalar(null) : null; - }, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: function resolve() { - return null; - }, - options: nullOptions, - stringify: function stringify() { - return nullOptions.nullStr; - } -}; -var boolObj = { - identify: function identify(value) { - return typeof value === 'boolean'; - }, - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, - resolve: function resolve(str) { - return str[0] === 't' || str[0] === 'T'; - }, - options: boolOptions, - stringify: function stringify(_ref) { - var value = _ref.value; - return value ? boolOptions.trueStr : boolOptions.falseStr; - } -}; -var octObj = { - identify: function identify(value) { - return intIdentify(value) && value >= 0; - }, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'OCT', - test: /^0o([0-7]+)$/, - resolve: function resolve(str, oct) { - return intResolve(str, oct, 8); - }, - options: intOptions, - stringify: function stringify(node) { - return intStringify(node, 8, '0o'); - } -}; -var intObj = { - identify: intIdentify, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^[-+]?[0-9]+$/, - resolve: function resolve(str) { - return intResolve(str, str, 10); - }, - options: intOptions, - stringify: stringifyNumber -}; -var hexObj = { - identify: function identify(value) { - return intIdentify(value) && value >= 0; - }, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'HEX', - test: /^0x([0-9a-fA-F]+)$/, - resolve: function resolve(str, hex) { - return intResolve(str, hex, 16); - }, - options: intOptions, - stringify: function stringify(node) { - return intStringify(node, 16, '0x'); - } -}; -var nanObj = { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^(?:[-+]?\.inf|(\.nan))$/i, - resolve: function resolve(str, nan) { - return nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; - }, - stringify: stringifyNumber -}; -var expObj = { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - format: 'EXP', - test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, - resolve: function resolve(str) { - return parseFloat(str); - }, - stringify: function stringify(_ref2) { - var value = _ref2.value; - return Number(value).toExponential(); - } -}; -var floatObj = { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, - resolve: function resolve(str, frac1, frac2) { - var frac = frac1 || frac2; - var node = new Scalar(parseFloat(str)); - if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; - return node; - }, - stringify: stringifyNumber -}; -var core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); - -/* global BigInt */ - -var intIdentify$1 = function intIdentify(value) { - return typeof value === 'bigint' || Number.isInteger(value); -}; - -var stringifyJSON = function stringifyJSON(_ref) { - var value = _ref.value; - return JSON.stringify(value); -}; - -var json = [map, seq, { - identify: function identify(value) { - return typeof value === 'string'; - }, - default: true, - tag: 'tag:yaml.org,2002:str', - resolve: resolveString, - stringify: stringifyJSON -}, { - identify: function identify(value) { - return value == null; - }, - createNode: function createNode(schema, value, ctx) { - return ctx.wrapScalars ? new Scalar(null) : null; - }, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^null$/, - resolve: function resolve() { - return null; - }, - stringify: stringifyJSON -}, { - identify: function identify(value) { - return typeof value === 'boolean'; - }, - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^true|false$/, - resolve: function resolve(str) { - return str === 'true'; - }, - stringify: stringifyJSON -}, { - identify: intIdentify$1, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^-?(?:0|[1-9][0-9]*)$/, - resolve: function resolve(str) { - return intOptions.asBigInt ? BigInt(str) : parseInt(str, 10); - }, - stringify: function stringify(_ref2) { - var value = _ref2.value; - return intIdentify$1(value) ? value.toString() : JSON.stringify(value); - } -}, { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, - resolve: function resolve(str) { - return parseFloat(str); - }, - stringify: stringifyJSON -}]; - -json.scalarFallback = function (str) { - throw new SyntaxError("Unresolved plain scalar ".concat(JSON.stringify(str))); -}; - -/* global BigInt */ - -var boolStringify = function boolStringify(_ref) { - var value = _ref.value; - return value ? boolOptions.trueStr : boolOptions.falseStr; -}; - -var intIdentify$2 = function intIdentify(value) { - return typeof value === 'bigint' || Number.isInteger(value); -}; - -function intResolve$1(sign, src, radix) { - var str = src.replace(/_/g, ''); - - if (intOptions.asBigInt) { - switch (radix) { - case 2: - str = "0b".concat(str); - break; - - case 8: - str = "0o".concat(str); - break; - - case 16: - str = "0x".concat(str); - break; - } - - var _n = BigInt(str); - - return sign === '-' ? BigInt(-1) * _n : _n; - } - - var n = parseInt(str, radix); - return sign === '-' ? -1 * n : n; -} - -function intStringify$1(node, radix, prefix) { - var value = node.value; - - if (intIdentify$2(value)) { - var str = value.toString(radix); - return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; - } - - return stringifyNumber(node); -} - -var yaml11 = failsafe.concat([{ - identify: function identify(value) { - return value == null; - }, - createNode: function createNode(schema, value, ctx) { - return ctx.wrapScalars ? new Scalar(null) : null; - }, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: function resolve() { - return null; - }, - options: nullOptions, - stringify: function stringify() { - return nullOptions.nullStr; - } -}, { - identify: function identify(value) { - return typeof value === 'boolean'; - }, - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, - resolve: function resolve() { - return true; - }, - options: boolOptions, - stringify: boolStringify -}, { - identify: function identify(value) { - return typeof value === 'boolean'; - }, - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, - resolve: function resolve() { - return false; - }, - options: boolOptions, - stringify: boolStringify -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'BIN', - test: /^([-+]?)0b([0-1_]+)$/, - resolve: function resolve(str, sign, bin) { - return intResolve$1(sign, bin, 2); - }, - stringify: function stringify(node) { - return intStringify$1(node, 2, '0b'); - } -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'OCT', - test: /^([-+]?)0([0-7_]+)$/, - resolve: function resolve(str, sign, oct) { - return intResolve$1(sign, oct, 8); - }, - stringify: function stringify(node) { - return intStringify$1(node, 8, '0'); - } -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^([-+]?)([0-9][0-9_]*)$/, - resolve: function resolve(str, sign, abs) { - return intResolve$1(sign, abs, 10); - }, - stringify: stringifyNumber -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'HEX', - test: /^([-+]?)0x([0-9a-fA-F_]+)$/, - resolve: function resolve(str, sign, hex) { - return intResolve$1(sign, hex, 16); - }, - stringify: function stringify(node) { - return intStringify$1(node, 16, '0x'); - } -}, { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^(?:[-+]?\.inf|(\.nan))$/i, - resolve: function resolve(str, nan) { - return nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY; - }, - stringify: stringifyNumber -}, { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - format: 'EXP', - test: /^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/, - resolve: function resolve(str) { - return parseFloat(str.replace(/_/g, '')); - }, - stringify: function stringify(_ref2) { - var value = _ref2.value; - return Number(value).toExponential(); - } -}, { - identify: function identify(value) { - return typeof value === 'number'; - }, - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, - resolve: function resolve(str, frac) { - var node = new Scalar(parseFloat(str.replace(/_/g, ''))); - - if (frac) { - var f = frac.replace(/_/g, ''); - if (f[f.length - 1] === '0') node.minFractionDigits = f.length; - } - - return node; - }, - stringify: stringifyNumber -}], binary, omap, pairs, set, intTime, floatTime, timestamp); - -var schemas = { - core: core, - failsafe: failsafe, - json: json, - yaml11: yaml11 -}; -var tags = { - binary: binary, - bool: boolObj, - float: floatObj, - floatExp: expObj, - floatNaN: nanObj, - floatTime: floatTime, - int: intObj, - intHex: hexObj, - intOct: octObj, - intTime: intTime, - map: map, - null: nullObj, - omap: omap, - pairs: pairs, - seq: seq, - set: set, - timestamp: timestamp -}; - -function findTagObject(value, tagName, tags) { - if (tagName) { - var match = tags.filter(function (t) { - return t.tag === tagName; - }); - var tagObj = match.find(function (t) { - return !t.format; - }) || match[0]; - if (!tagObj) throw new Error("Tag ".concat(tagName, " not found")); - return tagObj; - } // TODO: deprecate/remove class check - - - return tags.find(function (t) { - return (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format; - }); -} - -function createNode(value, tagName, ctx) { - if (value instanceof Node$1) return value; - var defaultPrefix = ctx.defaultPrefix, - onTagObj = ctx.onTagObj, - prevObjects = ctx.prevObjects, - schema = ctx.schema, - wrapScalars = ctx.wrapScalars; - if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); - var tagObj = findTagObject(value, tagName, schema.tags); - - if (!tagObj) { - if (typeof value.toJSON === 'function') value = value.toJSON(); - if (_typeof(value) !== 'object') return wrapScalars ? new Scalar(value) : value; - tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map; - } - - if (onTagObj) { - onTagObj(tagObj); - delete ctx.onTagObj; - } // Detect duplicate references to the same object & use Alias nodes for all - // after first. The `obj` wrapper allows for circular references to resolve. - - - var obj = {}; - - if (value && _typeof(value) === 'object' && prevObjects) { - var prev = prevObjects.get(value); - - if (prev) { - var alias = new Alias$1(prev); // leaves source dirty; must be cleaned by caller - - ctx.aliasNodes.push(alias); // defined along with prevObjects - - return alias; - } - - obj.value = value; - prevObjects.set(value, obj); - } - - obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new Scalar(value) : value; - if (tagName && obj.node instanceof Node$1) obj.node.tag = tagName; - return obj.node; -} - -function getSchemaTags(schemas, knownTags, customTags, schemaId) { - var tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' - - if (!tags) { - var keys = Object.keys(schemas).map(function (key) { - return JSON.stringify(key); - }).join(', '); - throw new Error("Unknown schema \"".concat(schemaId, "\"; use one of ").concat(keys)); - } - - if (Array.isArray(customTags)) { - var _iterator = _createForOfIteratorHelper(customTags), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var tag = _step.value; - tags = tags.concat(tag); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } else if (typeof customTags === 'function') { - tags = customTags(tags.slice()); - } - - for (var i = 0; i < tags.length; ++i) { - var _tag = tags[i]; - - if (typeof _tag === 'string') { - var tagObj = knownTags[_tag]; - - if (!tagObj) { - var _keys = Object.keys(knownTags).map(function (key) { - return JSON.stringify(key); - }).join(', '); - - throw new Error("Unknown custom tag \"".concat(_tag, "\"; use one of ").concat(_keys)); - } - - tags[i] = tagObj; - } - } - - return tags; -} - -var sortMapEntriesByKey = function sortMapEntriesByKey(a, b) { - return a.key < b.key ? -1 : a.key > b.key ? 1 : 0; -}; - -var Schema = /*#__PURE__*/function () { - // TODO: remove in v2 - // TODO: remove in v2 - function Schema(_ref) { - var customTags = _ref.customTags, - merge = _ref.merge, - schema = _ref.schema, - sortMapEntries = _ref.sortMapEntries, - deprecatedCustomTags = _ref.tags; - - _classCallCheck(this, Schema); - - this.merge = !!merge; - this.name = schema; - this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; - if (!customTags && deprecatedCustomTags) warnOptionDeprecation('tags', 'customTags'); - this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); - } - - _createClass(Schema, [{ - key: "createNode", - value: function createNode$1(value, wrapScalars, tagName, ctx) { - var baseCtx = { - defaultPrefix: Schema.defaultPrefix, - schema: this, - wrapScalars: wrapScalars - }; - var createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; - return createNode(value, tagName, createCtx); - } - }, { - key: "createPair", - value: function createPair(key, value, ctx) { - if (!ctx) ctx = { - wrapScalars: true - }; - var k = this.createNode(key, ctx.wrapScalars, null, ctx); - var v = this.createNode(value, ctx.wrapScalars, null, ctx); - return new Pair(k, v); - } - }]); - - return Schema; -}(); - -_defineProperty(Schema, "defaultPrefix", defaultTagPrefix); - -_defineProperty(Schema, "defaultTags", defaultTags); - -var defaultOptions = { - anchorPrefix: 'a', - customTags: null, - indent: 2, - indentSeq: true, - keepCstNodes: false, - keepNodeTypes: true, - keepBlobsInJSON: true, - mapAsMap: false, - maxAliasCount: 100, - prettyErrors: false, - // TODO Set true in v2 - simpleKeys: false, - version: '1.2' -}; -var scalarOptions = { - get binary() { - return binaryOptions; - }, - - set binary(opt) { - Object.assign(binaryOptions, opt); - }, - - get bool() { - return boolOptions; - }, - - set bool(opt) { - Object.assign(boolOptions, opt); - }, - - get int() { - return intOptions; - }, - - set int(opt) { - Object.assign(intOptions, opt); - }, - - get null() { - return nullOptions; - }, - - set null(opt) { - Object.assign(nullOptions, opt); - }, - - get str() { - return strOptions; - }, - - set str(opt) { - Object.assign(strOptions, opt); - } - -}; -var documentOptions = { - '1.0': { - schema: 'yaml-1.1', - merge: true, - tagPrefixes: [{ - handle: '!', - prefix: defaultTagPrefix - }, { - handle: '!!', - prefix: 'tag:private.yaml.org,2002:' - }] - }, - '1.1': { - schema: 'yaml-1.1', - merge: true, - tagPrefixes: [{ - handle: '!', - prefix: '!' - }, { - handle: '!!', - prefix: defaultTagPrefix - }] - }, - '1.2': { - schema: 'core', - merge: false, - tagPrefixes: [{ - handle: '!', - prefix: '!' - }, { - handle: '!!', - prefix: defaultTagPrefix - }] - } -}; - -function stringifyTag(doc, tag) { - if ((doc.version || doc.options.version) === '1.0') { - var priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); - if (priv) return '!' + priv[1]; - var vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); - return vocab ? "!".concat(vocab[1], "/").concat(vocab[2]) : "!".concat(tag.replace(/^tag:/, '')); - } - - var p = doc.tagPrefixes.find(function (p) { - return tag.indexOf(p.prefix) === 0; - }); - - if (!p) { - var dtp = doc.getDefaults().tagPrefixes; - p = dtp && dtp.find(function (p) { - return tag.indexOf(p.prefix) === 0; - }); - } - - if (!p) return tag[0] === '!' ? tag : "!<".concat(tag, ">"); - var suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, function (ch) { - return { - '!': '%21', - ',': '%2C', - '[': '%5B', - ']': '%5D', - '{': '%7B', - '}': '%7D' - }[ch]; - }); - return p.handle + suffix; -} - -function getTagObject(tags, item) { - if (item instanceof Alias$1) return Alias$1; - - if (item.tag) { - var match = tags.filter(function (t) { - return t.tag === item.tag; - }); - if (match.length > 0) return match.find(function (t) { - return t.format === item.format; - }) || match[0]; - } - - var tagObj, obj; - - if (item instanceof Scalar) { - obj = item.value; // TODO: deprecate/remove class check - - var _match = tags.filter(function (t) { - return t.identify && t.identify(obj) || t.class && obj instanceof t.class; - }); - - tagObj = _match.find(function (t) { - return t.format === item.format; - }) || _match.find(function (t) { - return !t.format; - }); - } else { - obj = item; - tagObj = tags.find(function (t) { - return t.nodeClass && obj instanceof t.nodeClass; - }); - } - - if (!tagObj) { - var name = obj && obj.constructor ? obj.constructor.name : _typeof(obj); - throw new Error("Tag not resolved for ".concat(name, " value")); - } - - return tagObj; -} // needs to be called before value stringifier to allow for circular anchor refs - - -function stringifyProps(node, tagObj, _ref) { - var anchors = _ref.anchors, - doc = _ref.doc; - var props = []; - var anchor = doc.anchors.getName(node); - - if (anchor) { - anchors[anchor] = node; - props.push("&".concat(anchor)); - } - - if (node.tag) { - props.push(stringifyTag(doc, node.tag)); - } else if (!tagObj.default) { - props.push(stringifyTag(doc, tagObj.tag)); - } - - return props.join(' '); -} - -function stringify(item, ctx, onComment, onChompKeep) { - var _ctx$doc = ctx.doc, - anchors = _ctx$doc.anchors, - schema = _ctx$doc.schema; - var tagObj; - - if (!(item instanceof Node$1)) { - var createCtx = { - aliasNodes: [], - onTagObj: function onTagObj(o) { - return tagObj = o; - }, - prevObjects: new Map() - }; - item = schema.createNode(item, true, null, createCtx); - - var _iterator = _createForOfIteratorHelper(createCtx.aliasNodes), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var alias = _step.value; - alias.source = alias.source.node; - var name = anchors.getName(alias.source); - - if (!name) { - name = anchors.newName(); - anchors.map[name] = alias.source; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - - if (item instanceof Pair) return item.toString(ctx, onComment, onChompKeep); - if (!tagObj) tagObj = getTagObject(schema.tags, item); - var props = stringifyProps(item, tagObj, ctx); - if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; - var str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof Scalar ? stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); - if (!props) return str; - return item instanceof Scalar || str[0] === '{' || str[0] === '[' ? "".concat(props, " ").concat(str) : "".concat(props, "\n").concat(ctx.indent).concat(str); -} - -var Anchors = /*#__PURE__*/function () { - _createClass(Anchors, null, [{ - key: "validAnchorNode", - value: function validAnchorNode(node) { - return node instanceof Scalar || node instanceof YAMLSeq || node instanceof YAMLMap; - } - }]); - - function Anchors(prefix) { - _classCallCheck(this, Anchors); - - _defineProperty(this, "map", {}); - - this.prefix = prefix; - } - - _createClass(Anchors, [{ - key: "createAlias", - value: function createAlias(node, name) { - this.setAnchor(node, name); - return new Alias$1(node); - } - }, { - key: "createMergePair", - value: function createMergePair() { - var _this = this; - - var merge = new Merge(); - - for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) { - sources[_key] = arguments[_key]; - } - - merge.value.items = sources.map(function (s) { - if (s instanceof Alias$1) { - if (s.source instanceof YAMLMap) return s; - } else if (s instanceof YAMLMap) { - return _this.createAlias(s); - } - - throw new Error('Merge sources must be Map nodes or their Aliases'); - }); - return merge; - } - }, { - key: "getName", - value: function getName(node) { - var map = this.map; - return Object.keys(map).find(function (a) { - return map[a] === node; - }); - } - }, { - key: "getNames", - value: function getNames() { - return Object.keys(this.map); - } - }, { - key: "getNode", - value: function getNode(name) { - return this.map[name]; - } - }, { - key: "newName", - value: function newName(prefix) { - if (!prefix) prefix = this.prefix; - var names = Object.keys(this.map); - - for (var i = 1; true; ++i) { - var name = "".concat(prefix).concat(i); - if (!names.includes(name)) return name; - } - } // During parsing, map & aliases contain CST nodes - - }, { - key: "resolveNodes", - value: function resolveNodes() { - var map = this.map, - _cstAliases = this._cstAliases; - Object.keys(map).forEach(function (a) { - map[a] = map[a].resolved; - }); - - _cstAliases.forEach(function (a) { - a.source = a.source.resolved; - }); - - delete this._cstAliases; - } - }, { - key: "setAnchor", - value: function setAnchor(node, name) { - if (node != null && !Anchors.validAnchorNode(node)) { - throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); - } - - if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { - throw new Error('Anchor names must not contain whitespace or control characters'); - } - - var map = this.map; - var prev = node && Object.keys(map).find(function (a) { - return map[a] === node; - }); - - if (prev) { - if (!name) { - return prev; - } else if (prev !== name) { - delete map[prev]; - map[name] = node; - } - } else { - if (!name) { - if (!node) return null; - name = this.newName(); - } - - map[name] = node; - } - - return name; - } - }]); - - return Anchors; -}(); - -var visit = function visit(node, tags) { - if (node && _typeof(node) === 'object') { - var tag = node.tag; - - if (node instanceof Collection$1) { - if (tag) tags[tag] = true; - node.items.forEach(function (n) { - return visit(n, tags); - }); - } else if (node instanceof Pair) { - visit(node.key, tags); - visit(node.value, tags); - } else if (node instanceof Scalar) { - if (tag) tags[tag] = true; - } - } - - return tags; -}; - -var listTagNames = function listTagNames(node) { - return Object.keys(visit(node, {})); -}; - -function parseContents(doc, contents) { - var comments = { - before: [], - after: [] - }; - var body = undefined; - var spaceBefore = false; - - var _iterator = _createForOfIteratorHelper(contents), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var node = _step.value; - - if (node.valueRange) { - if (body !== undefined) { - var msg = 'Document contains trailing content not separated by a ... or --- line'; - doc.errors.push(new YAMLSyntaxError(node, msg)); - break; - } - - var res = resolveNode(doc, node); - - if (spaceBefore) { - res.spaceBefore = true; - spaceBefore = false; - } - - body = res; - } else if (node.comment !== null) { - var cc = body === undefined ? comments.before : comments.after; - cc.push(node.comment); - } else if (node.type === Type.BLANK_LINE) { - spaceBefore = true; - - if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { - // space-separated comments at start are parsed as document comments - doc.commentBefore = comments.before.join('\n'); - comments.before = []; - } - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - doc.contents = body || null; - - if (!body) { - doc.comment = comments.before.concat(comments.after).join('\n') || null; - } else { - var cb = comments.before.join('\n'); - - if (cb) { - var cbNode = body instanceof Collection$1 && body.items[0] ? body.items[0] : body; - cbNode.commentBefore = cbNode.commentBefore ? "".concat(cb, "\n").concat(cbNode.commentBefore) : cb; - } - - doc.comment = comments.after.join('\n') || null; - } -} - -function resolveTagDirective(_ref, directive) { - var tagPrefixes = _ref.tagPrefixes; - - var _directive$parameters = _slicedToArray(directive.parameters, 2), - handle = _directive$parameters[0], - prefix = _directive$parameters[1]; - - if (!handle || !prefix) { - var msg = 'Insufficient parameters given for %TAG directive'; - throw new YAMLSemanticError(directive, msg); - } - - if (tagPrefixes.some(function (p) { - return p.handle === handle; - })) { - var _msg = 'The %TAG directive must only be given at most once per handle in the same document.'; - throw new YAMLSemanticError(directive, _msg); - } - - return { - handle: handle, - prefix: prefix - }; -} - -function resolveYamlDirective(doc, directive) { - var _directive$parameters2 = _slicedToArray(directive.parameters, 1), - version = _directive$parameters2[0]; - - if (directive.name === 'YAML:1.0') version = '1.0'; - - if (!version) { - var msg = 'Insufficient parameters given for %YAML directive'; - throw new YAMLSemanticError(directive, msg); - } - - if (!documentOptions[version]) { - var v0 = doc.version || doc.options.version; - - var _msg2 = "Document will be parsed as YAML ".concat(v0, " rather than YAML ").concat(version); - - doc.warnings.push(new YAMLWarning(directive, _msg2)); - } - - return version; -} - -function parseDirectives(doc, directives, prevDoc) { - var directiveComments = []; - var hasDirectives = false; - - var _iterator = _createForOfIteratorHelper(directives), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var directive = _step.value; - var comment = directive.comment, - name = directive.name; - - switch (name) { - case 'TAG': - try { - doc.tagPrefixes.push(resolveTagDirective(doc, directive)); - } catch (error) { - doc.errors.push(error); - } - - hasDirectives = true; - break; - - case 'YAML': - case 'YAML:1.0': - if (doc.version) { - var msg = 'The %YAML directive must only be given at most once per document.'; - doc.errors.push(new YAMLSemanticError(directive, msg)); - } - - try { - doc.version = resolveYamlDirective(doc, directive); - } catch (error) { - doc.errors.push(error); - } - - hasDirectives = true; - break; - - default: - if (name) { - var _msg3 = "YAML only supports %TAG and %YAML directives, and not %".concat(name); - - doc.warnings.push(new YAMLWarning(directive, _msg3)); - } - - } - - if (comment) directiveComments.push(comment); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { - var copyTagPrefix = function copyTagPrefix(_ref2) { - var handle = _ref2.handle, - prefix = _ref2.prefix; - return { - handle: handle, - prefix: prefix - }; - }; - - doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); - doc.version = prevDoc.version; - } - - doc.commentBefore = directiveComments.join('\n') || null; -} - -function assertCollection(contents) { - if (contents instanceof Collection$1) return true; - throw new Error('Expected a YAML collection as document contents'); -} - -var Document$1 = /*#__PURE__*/function () { - function Document(options) { - _classCallCheck(this, Document); - - this.anchors = new Anchors(options.anchorPrefix); - this.commentBefore = null; - this.comment = null; - this.contents = null; - this.directivesEndMarker = null; - this.errors = []; - this.options = options; - this.schema = null; - this.tagPrefixes = []; - this.version = null; - this.warnings = []; - } - - _createClass(Document, [{ - key: "add", - value: function add(value) { - assertCollection(this.contents); - return this.contents.add(value); - } - }, { - key: "addIn", - value: function addIn(path, value) { - assertCollection(this.contents); - this.contents.addIn(path, value); - } - }, { - key: "delete", - value: function _delete(key) { - assertCollection(this.contents); - return this.contents.delete(key); - } - }, { - key: "deleteIn", - value: function deleteIn(path) { - if (isEmptyPath(path)) { - if (this.contents == null) return false; - this.contents = null; - return true; - } - - assertCollection(this.contents); - return this.contents.deleteIn(path); - } - }, { - key: "getDefaults", - value: function getDefaults() { - return Document.defaults[this.version] || Document.defaults[this.options.version] || {}; - } - }, { - key: "get", - value: function get(key, keepScalar) { - return this.contents instanceof Collection$1 ? this.contents.get(key, keepScalar) : undefined; - } - }, { - key: "getIn", - value: function getIn(path, keepScalar) { - if (isEmptyPath(path)) return !keepScalar && this.contents instanceof Scalar ? this.contents.value : this.contents; - return this.contents instanceof Collection$1 ? this.contents.getIn(path, keepScalar) : undefined; - } - }, { - key: "has", - value: function has(key) { - return this.contents instanceof Collection$1 ? this.contents.has(key) : false; - } - }, { - key: "hasIn", - value: function hasIn(path) { - if (isEmptyPath(path)) return this.contents !== undefined; - return this.contents instanceof Collection$1 ? this.contents.hasIn(path) : false; - } - }, { - key: "set", - value: function set(key, value) { - assertCollection(this.contents); - this.contents.set(key, value); - } - }, { - key: "setIn", - value: function setIn(path, value) { - if (isEmptyPath(path)) this.contents = value;else { - assertCollection(this.contents); - this.contents.setIn(path, value); - } - } - }, { - key: "setSchema", - value: function setSchema(id, customTags) { - if (!id && !customTags && this.schema) return; - if (typeof id === 'number') id = id.toFixed(1); - - if (id === '1.0' || id === '1.1' || id === '1.2') { - if (this.version) this.version = id;else this.options.version = id; - delete this.options.schema; - } else if (id && typeof id === 'string') { - this.options.schema = id; - } - - if (Array.isArray(customTags)) this.options.customTags = customTags; - var opt = Object.assign({}, this.getDefaults(), this.options); - this.schema = new Schema(opt); - } - }, { - key: "parse", - value: function parse(node, prevDoc) { - if (this.options.keepCstNodes) this.cstNode = node; - if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; - var _node$directives = node.directives, - directives = _node$directives === void 0 ? [] : _node$directives, - _node$contents = node.contents, - contents = _node$contents === void 0 ? [] : _node$contents, - directivesEndMarker = node.directivesEndMarker, - error = node.error, - valueRange = node.valueRange; - - if (error) { - if (!error.source) error.source = this; - this.errors.push(error); - } - - parseDirectives(this, directives, prevDoc); - if (directivesEndMarker) this.directivesEndMarker = true; - this.range = valueRange ? [valueRange.start, valueRange.end] : null; - this.setSchema(); - this.anchors._cstAliases = []; - parseContents(this, contents); - this.anchors.resolveNodes(); - - if (this.options.prettyErrors) { - var _iterator = _createForOfIteratorHelper(this.errors), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _error = _step.value; - if (_error instanceof YAMLError) _error.makePretty(); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - var _iterator2 = _createForOfIteratorHelper(this.warnings), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var warn = _step2.value; - if (warn instanceof YAMLError) warn.makePretty(); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - - return this; - } - }, { - key: "listNonDefaultTags", - value: function listNonDefaultTags() { - return listTagNames(this.contents).filter(function (t) { - return t.indexOf(Schema.defaultPrefix) !== 0; - }); - } - }, { - key: "setTagPrefix", - value: function setTagPrefix(handle, prefix) { - if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); - - if (prefix) { - var prev = this.tagPrefixes.find(function (p) { - return p.handle === handle; - }); - if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ - handle: handle, - prefix: prefix - }); - } else { - this.tagPrefixes = this.tagPrefixes.filter(function (p) { - return p.handle !== handle; - }); - } - } - }, { - key: "toJSON", - value: function toJSON$1(arg, onAnchor) { - var _this = this; - - var _this$options = this.options, - keepBlobsInJSON = _this$options.keepBlobsInJSON, - mapAsMap = _this$options.mapAsMap, - maxAliasCount = _this$options.maxAliasCount; - var keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof Scalar)); - var ctx = { - doc: this, - indentStep: ' ', - keep: keep, - mapAsMap: keep && !!mapAsMap, - maxAliasCount: maxAliasCount, - stringify: stringify // Requiring directly in Pair would create circular dependencies - - }; - var anchorNames = Object.keys(this.anchors.map); - if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(function (name) { - return [_this.anchors.map[name], { - alias: [], - aliasCount: 0, - count: 1 - }]; - })); - - var res = toJSON(this.contents, arg, ctx); - - if (typeof onAnchor === 'function' && ctx.anchors) { - var _iterator3 = _createForOfIteratorHelper(ctx.anchors.values()), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _step3$value = _step3.value, - count = _step3$value.count, - _res = _step3$value.res; - onAnchor(_res, count); - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - } - - return res; - } - }, { - key: "toString", - value: function toString() { - if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); - var indentSize = this.options.indent; - - if (!Number.isInteger(indentSize) || indentSize <= 0) { - var s = JSON.stringify(indentSize); - throw new Error("\"indent\" option must be a positive integer, not ".concat(s)); - } - - this.setSchema(); - var lines = []; - var hasDirectives = false; - - if (this.version) { - var vd = '%YAML 1.2'; - - if (this.schema.name === 'yaml-1.1') { - if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; - } - - lines.push(vd); - hasDirectives = true; - } - - var tagNames = this.listNonDefaultTags(); - this.tagPrefixes.forEach(function (_ref) { - var handle = _ref.handle, - prefix = _ref.prefix; - - if (tagNames.some(function (t) { - return t.indexOf(prefix) === 0; - })) { - lines.push("%TAG ".concat(handle, " ").concat(prefix)); - hasDirectives = true; - } - }); - if (hasDirectives || this.directivesEndMarker) lines.push('---'); - - if (this.commentBefore) { - if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); - lines.unshift(this.commentBefore.replace(/^/gm, '#')); - } - - var ctx = { - anchors: {}, - doc: this, - indent: '', - indentStep: ' '.repeat(indentSize), - stringify: stringify // Requiring directly in nodes would create circular dependencies - - }; - var chompKeep = false; - var contentComment = null; - - if (this.contents) { - if (this.contents instanceof Node$1) { - if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); - if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment - - ctx.forceBlockIndent = !!this.comment; - contentComment = this.contents.comment; - } - - var onChompKeep = contentComment ? null : function () { - return chompKeep = true; - }; - var body = stringify(this.contents, ctx, function () { - return contentComment = null; - }, onChompKeep); - lines.push(addComment(body, '', contentComment)); - } else if (this.contents !== undefined) { - lines.push(stringify(this.contents, ctx)); - } - - if (this.comment) { - if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); - lines.push(this.comment.replace(/^/gm, '#')); - } - - return lines.join('\n') + '\n'; - } - }]); - - return Document; -}(); - -_defineProperty(Document$1, "defaults", documentOptions); - -function createNode$1(value) { - var wrapScalars = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var tag = arguments.length > 2 ? arguments[2] : undefined; - - if (tag === undefined && typeof wrapScalars === 'string') { - tag = wrapScalars; - wrapScalars = true; - } - - var options = Object.assign({}, Document$1.defaults[defaultOptions.version], defaultOptions); - var schema = new Schema(options); - return schema.createNode(value, wrapScalars, tag); -} - -var Document$1$1 = /*#__PURE__*/function (_YAMLDocument) { - _inherits(Document, _YAMLDocument); - - var _super = _createSuper(Document); - - function Document(options) { - _classCallCheck(this, Document); - - return _super.call(this, Object.assign({}, defaultOptions, options)); - } - - return Document; -}(Document$1); - -function parseAllDocuments(src, options) { - var stream = []; - var prev; - - var _iterator = _createForOfIteratorHelper(parse(src)), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var cstDoc = _step.value; - var doc = new Document$1$1(options); - doc.parse(cstDoc, prev); - stream.push(doc); - prev = doc; - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return stream; -} - -function parseDocument(src, options) { - var cst = parse(src); - var doc = new Document$1$1(options).parse(cst[0]); - - if (cst.length > 1) { - var errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; - doc.errors.unshift(new YAMLSemanticError(cst[1], errMsg)); - } - - return doc; -} - -function parse$1(src, options) { - var doc = parseDocument(src, options); - doc.warnings.forEach(function (warning) { - return warn(warning); - }); - if (doc.errors.length > 0) throw doc.errors[0]; - return doc.toJSON(); -} - -function stringify$1(value, options) { - var doc = new Document$1$1(options); - doc.contents = value; - return String(doc); -} - -var YAML = { - createNode: createNode$1, - defaultOptions: defaultOptions, - Document: Document$1$1, - parse: parse$1, - parseAllDocuments: parseAllDocuments, - parseCST: parse, - parseDocument: parseDocument, - scalarOptions: scalarOptions, - stringify: stringify$1 -}; - -var dist = /*#__PURE__*/Object.freeze({ - __proto__: null, - YAML: YAML -}); - -function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} - -var require$$0 = /*@__PURE__*/getAugmentedNamespace(dist); - -var browser = require$$0.YAML; - -// ------------------------------------------------------------ -// ccards processor -// ------------------------------------------------------------ -var ccardProcessor = /** @class */ (function () { - function ccardProcessor(app) { - this.app = app; - } - ccardProcessor.prototype.run = function (source, el, ctx, folderNote) { - return __awaiter(this, void 0, void 0, function () { - var yaml, docEl, docEl, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 5, , 6]); - yaml = browser.parse(source); - if (!yaml) - return [2 /*return*/]; - // set default - if (yaml.type === undefined) - yaml.type = 'static'; - if (yaml.style === undefined) - yaml.style = 'card'; - if (!(yaml.type == 'static')) return [3 /*break*/, 2]; - return [4 /*yield*/, this.docElemStatic(yaml)]; - case 1: - docEl = _a.sent(); - if (docEl) { - el.appendChild(docEl); - } - return [3 /*break*/, 4]; - case 2: - if (!(yaml.type == 'folder_brief_live')) return [3 /*break*/, 4]; - return [4 /*yield*/, this.docElemFolderBriefLive(yaml, folderNote)]; - case 3: - docEl = _a.sent(); - if (docEl) { - el.appendChild(docEl); - } - _a.label = 4; - case 4: return [3 /*break*/, 6]; - case 5: - error_1 = _a.sent(); - console.log('Code Block: ccard', error_1); - return [3 /*break*/, 6]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - // static - ccardProcessor.prototype.docElemStatic = function (yaml) { - return __awaiter(this, void 0, void 0, function () { - var cardBlock, cardsElem; - return __generator(this, function (_a) { - if (yaml.items && (yaml.items instanceof Array)) { - cardBlock = new CardBlock(); - cardBlock.fromYamlCards(yaml); - cardsElem = cardBlock.getDocElement(this.app); - return [2 /*return*/, cardsElem]; - } - return [2 /*return*/, null]; - }); - }); - }; - // folder_brief_live - ccardProcessor.prototype.docElemFolderBriefLive = function (yaml, folderNote) { - return __awaiter(this, void 0, void 0, function () { - var folderPath, activeFile, notePath, folderExist, view, folderBrief, briefCards, ccardElem; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - folderPath = ''; - activeFile = this.app.workspace.getActiveFile(); - notePath = activeFile.path; - if (!yaml.folder) return [3 /*break*/, 2]; - return [4 /*yield*/, this.app.vault.adapter.exists(yaml.folder)]; - case 1: - folderExist = _a.sent(); - if (folderExist) - folderPath = yaml.folder; - return [3 /*break*/, 4]; - case 2: return [4 /*yield*/, folderNote.getNoteFolderBriefPath(notePath)]; - case 3: - folderPath = _a.sent(); - _a.label = 4; - case 4: - if (!(folderPath.length > 0)) return [3 /*break*/, 6]; - view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView); - if (!view) return [3 /*break*/, 6]; - folderBrief = new FolderBrief(this.app); - // brief options - if (yaml.briefMax) { - folderBrief.briefMax = yaml.briefMax; - } - if (yaml.noteOnly != undefined) { - folderBrief.noteOnly = yaml.noteOnly; - } - return [4 /*yield*/, folderBrief.makeBriefCards(folderPath, notePath)]; - case 5: - briefCards = _a.sent(); - briefCards.fromYamlOptions(yaml); - ccardElem = briefCards.getDocElement(this.app); - return [2 /*return*/, ccardElem]; - case 6: return [2 /*return*/, null]; - } - }); - }); - }; - return ccardProcessor; -}()); - -var FOLDER_NOTE_DEFAULT_SETTINGS = { - folderNoteHide: true, - folderNoteType: 'inside', - folderNoteName: '_about_', - folderNoteKey: 'ctrl', - folderNoteAutoRename: true, - folderDelete2Note: false, - folderNoteStrInit: '# {{FOLDER_NAME}} Overview\n {{FOLDER_BRIEF_LIVE}} \n' -}; -// ------------------------------------------------------------ -// Settings Tab -// ------------------------------------------------------------ -var FolderNoteSettingTab = /** @class */ (function (_super) { - __extends(FolderNoteSettingTab, _super); - function FolderNoteSettingTab(app, plugin) { - var _this = _super.call(this, app, plugin) || this; - _this.plugin = plugin; - return _this; - } - FolderNoteSettingTab.prototype.display = function () { - var _this = this; - var containerEl = this.containerEl; - containerEl.empty(); - containerEl.createEl('h2', { text: 'Folder Note Plugin: Settings.' }); - new obsidian.Setting(containerEl) - .setName('Note File Method') - .setDesc('Select the method to put your folder note file. (Read doc for more information.)') - .addDropdown(function (dropDown) { - return dropDown - .addOption('index', 'Index File') - .addOption('inside', 'Folder Name Inside') - .addOption('outside', 'Folder Name Outside') - .setValue(_this.plugin.settings.folderNoteType || 'inside') - .onChange(function (value) { - _this.plugin.settings.folderNoteType = value; - _this.plugin.saveSettings(); - _this.display(); - }); - }); - if (this.plugin.settings.folderNoteType == 'index') { - new obsidian.Setting(containerEl) - .setName('Index File Name') - .setDesc('Set the index file name for folder note. (only for the Index method)') - .addText(function (text) { return text - .setValue(_this.plugin.settings.folderNoteName) - .onChange(function (value) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - // console.log('Secret: ' + value); - this.plugin.settings.folderNoteName = value; - return [4 /*yield*/, this.plugin.saveSettings()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); }); - } - new obsidian.Setting(containerEl) - .setName('Inital Content') - .setDesc('Set the inital content for new folder note. {{FOLDER_NAME}} will be replaced with current folder name.') - .addTextArea(function (text) { - text - .setPlaceholder('About the folder.') - .setValue(_this.plugin.settings.folderNoteStrInit) - .onChange(function (value) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - this.plugin.settings.folderNoteStrInit = value; - return [4 /*yield*/, this.plugin.saveSettings()]; - case 1: - _a.sent(); - return [3 /*break*/, 3]; - case 2: - _a.sent(); - return [2 /*return*/, false]; - case 3: return [2 /*return*/]; - } - }); - }); }); - text.inputEl.rows = 8; - text.inputEl.cols = 50; - }); - new obsidian.Setting(containerEl) - .setName('Key for New Note') - .setDesc('Key + Click a folder to create folder note file. ') - .addDropdown(function (dropDown) { - return dropDown - .addOption('ctrl', 'Ctrl + Click') - .addOption('alt', 'Alt + Click') - .setValue(_this.plugin.settings.folderNoteKey || 'ctrl') - .onChange(function (value) { - _this.plugin.settings.folderNoteKey = value; - _this.plugin.saveSettings(); - }); - }); - new obsidian.Setting(containerEl) - .setName('Hide Folder Note') - .setDesc('Hide the folder note file in the file explorer panel.') - .addToggle(function (toggle) { - toggle.setValue(_this.plugin.settings.folderNoteHide); - toggle.onChange(function (value) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.plugin.settings.folderNoteHide = value; - return [4 /*yield*/, this.plugin.saveSettings()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); - }); - if (this.plugin.settings.folderNoteType != 'index') { - new obsidian.Setting(containerEl) - .setName('Auto Rename') - .setDesc('Try to automatically rename the folder note if a folder name is changed. (Experimental)') - .addToggle(function (toggle) { - toggle.setValue(_this.plugin.settings.folderNoteAutoRename); - toggle.onChange(function (value) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.plugin.settings.folderNoteAutoRename = value; - return [4 /*yield*/, this.plugin.saveSettings()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); - }); - } - if (this.plugin.settings.folderNoteType == 'outside') { - new obsidian.Setting(containerEl) - .setName('Delete Folder Note') - .setDesc('Try to delete folder note when a folder is deleted. (Dangerous)') - .addToggle(function (toggle) { - toggle.setValue(_this.plugin.settings.folderDelete2Note); - toggle.onChange(function (value) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - this.plugin.settings.folderDelete2Note = value; - return [4 /*yield*/, this.plugin.saveSettings()]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); - }); - } - }; - return FolderNoteSettingTab; -}(obsidian.PluginSettingTab)); - -// ------------------------------------------------------------ -// FolderNotePlugin -// ------------------------------------------------------------ -var NoteFileMethod$1; -(function (NoteFileMethod) { - NoteFileMethod[NoteFileMethod["Index"] = 0] = "Index"; - NoteFileMethod[NoteFileMethod["Inside"] = 1] = "Inside"; - NoteFileMethod[NoteFileMethod["Outside"] = 2] = "Outside"; -})(NoteFileMethod$1 || (NoteFileMethod$1 = {})); -var FolderNotePlugin = /** @class */ (function (_super) { - __extends(FolderNotePlugin, _super); - function FolderNotePlugin() { - return _super !== null && _super.apply(this, arguments) || this; - } - FolderNotePlugin.prototype.onload = function () { - return __awaiter(this, void 0, void 0, function () { - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - console.log('Loading Folder Note plugin.'); - // load settings - return [4 /*yield*/, this.loadSettings()]; - case 1: - // load settings - _a.sent(); - // for ccard rendering - this.registerMarkdownCodeBlockProcessor('ccard', function (source, el, ctx) { return __awaiter(_this, void 0, void 0, function () { - var proc; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - proc = new ccardProcessor(this.app); - return [4 /*yield*/, proc.run(source, el, ctx, this.folderNote)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); }); - // for rename event - this.registerEvent(this.app.vault.on('rename', function (newPath, oldPath) { return _this.handleFileRename(newPath, oldPath); })); - // for remove folder - this.registerEvent(this.app.vault.on('delete', function (file) { return _this.handleFileDelete(file); })); - // for settings - this.addSettingTab(new FolderNoteSettingTab(this.app, this)); - // for file explorer click - this.registerDomEvent(document, 'click', function (evt) { - // get the folder path - var elemTarget = evt.target; - var folderElem = _this.folderNote.setByFolderElement(elemTarget); - // open the infor note - if (_this.folderNote.folderPath.length > 0) { - // any key? - var newKey = false; - if (_this.settings.folderNoteKey == 'ctrl') { - newKey = (evt.ctrlKey || evt.metaKey); - } - else if (_this.settings.folderNoteKey == 'alt') { - newKey = evt.altKey; - } - // open it - _this.folderNote.openFolderNote(folderElem, newKey); - } - }); - this.addCommand({ - id: 'insert-folder-brief', - name: 'Insert Folder Brief', - callback: function () { return __awaiter(_this, void 0, void 0, function () { - var view, editor, activeFile, folderBrief, folderPath, briefCards; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView); - if (!view) return [3 /*break*/, 3]; - editor = view.sourceMode.cmEditor; - activeFile = this.app.workspace.getActiveFile(); - folderBrief = new FolderBrief(this.app); - return [4 /*yield*/, this.folderNote.getNoteFolderBriefPath(activeFile.path)]; - case 1: - folderPath = _a.sent(); - return [4 /*yield*/, folderBrief.makeBriefCards(folderPath, activeFile.path)]; - case 2: - briefCards = _a.sent(); - editor.replaceSelection(briefCards.getYamlCode(), "end"); - _a.label = 3; - case 3: return [2 /*return*/]; - } - }); - }); }, - hotkeys: [] - }); - this.addCommand({ - id: 'note-to-folder', - name: 'Make Current Note to Folder', - callback: function () { return __awaiter(_this, void 0, void 0, function () { - var view, activeFile; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - view = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView); - if (!view) return [3 /*break*/, 2]; - activeFile = this.app.workspace.getActiveFile(); - this.folderNote.setByNotePath(activeFile.path); - return [4 /*yield*/, this.folderNote.newNoteFolder()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); }, - hotkeys: [] - }); - return [2 /*return*/]; - } - }); - }); - }; - FolderNotePlugin.prototype.onunload = function () { - console.log('Unloading Folder Note plugin'); - }; - FolderNotePlugin.prototype.updateFolderNote = function () { - this.folderNote = new FolderNote(this.app, this.settings.folderNoteType, this.settings.folderNoteName); - this.folderNote.initContent = this.settings.folderNoteStrInit; - this.folderNote.hideNoteFile = this.settings.folderNoteHide; - }; - FolderNotePlugin.prototype.loadSettings = function () { - return __awaiter(this, void 0, void 0, function () { - var _a, _b, _c, _d; - return __generator(this, function (_e) { - switch (_e.label) { - case 0: - _a = this; - _c = (_b = Object).assign; - _d = [FOLDER_NOTE_DEFAULT_SETTINGS]; - return [4 /*yield*/, this.loadData()]; - case 1: - _a.settings = _c.apply(_b, _d.concat([_e.sent()])); - this.updateFolderNote(); - return [2 /*return*/]; - } - }); - }); - }; - FolderNotePlugin.prototype.saveSettings = function () { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.saveData(this.settings)]; - case 1: - _a.sent(); - this.updateFolderNote(); - return [2 /*return*/]; - } - }); - }); - }; - // keep notefile name to be the folder name - FolderNotePlugin.prototype.handleFileRename = function (newPath, oldPath) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (!this.settings.folderNoteAutoRename) - return [2 /*return*/]; - this.folderNote.syncName(newPath, oldPath); - return [2 /*return*/]; - }); - }); - }; - // delete folder - FolderNotePlugin.prototype.handleFileDelete = function (pathToDel) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - if (!this.settings.folderDelete2Note) - return [2 /*return*/]; - this.folderNote.deleteFolder(pathToDel.path); - return [2 /*return*/]; - }); - }); - }; - return FolderNotePlugin; -}(obsidian.Plugin)); - -module.exports = FolderNotePlugin; - - -/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/folder-note-plugin/manifest.json b/.obsidian/plugins/folder-note-plugin/manifest.json deleted file mode 100644 index 8355496..0000000 --- a/.obsidian/plugins/folder-note-plugin/manifest.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "folder-note-plugin", - "name": "Folder Note", - "version": "0.7.3", - "minAppVersion": "0.9.12", - "description": "Click a folder node to show a note describing the folder.", - "author": "xpgo", - "authorUrl": "https://github.com/xpgo/obsidian-folder-note", - "isDesktopOnly": false -} diff --git a/.obsidian/plugins/folder-note-plugin/styles.css b/.obsidian/plugins/folder-note-plugin/styles.css deleted file mode 100644 index abe59df..0000000 --- a/.obsidian/plugins/folder-note-plugin/styles.css +++ /dev/null @@ -1,229 +0,0 @@ -/* hide the folder note file node */ -div.is-folder-note { - display: none; -} - -/* indicate the folder has note */ -div.has-folder-note { - color: var(--text-nav-selected); -} - -/*--------------------------------------------- - Cute card view ------------------------------------------------*/ - -.cute-card-band { - width: 100%; - max-width: 900px; - margin: 0 auto; - margin-top: 15px; - margin-bottom: 5px; - display: grid; - grid-template-columns: 1fr; - grid-template-rows: auto; - grid-gap: 20px; -} - -@media (min-width: 30em) { - .cute-card-band { - grid-template-columns: 1fr 1fr; - } -} - -@media (min-width: 60em) { - .cute-card-band { - grid-template-columns: repeat(3, 1fr); - } -} - -.cute-card-view { - background: var(--background-accent); - text-decoration: none !important; - color: var(--text-normal); - box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); - display: flex; - flex-direction: column; - min-height: 100%; - position: relative; - top: 0; - transition: all 0.1s ease-in; - border-radius: 10px; -} - -.cute-card-view:hover { - top: -2px; - box-shadow: 0 4px 5px rgba(0, 0, 0, 0.2); -} - -.cute-card-view article { - padding: 15px; - flex: 1; - display: flex; - flex-direction: column; - justify-content: space-between; -} - -.cute-card-view h1 { - font-size: 1.2rem; - margin: 0; - color: var(--text-accent); -} - -.cute-card-view a { - text-decoration: none !important; -} - -.cute-card-view p { - flex: 1; - line-height: 1.0; -} - -.cute-card-view span { - font-size: 0.8rem; - font-weight: bold; - color: var(--text-faint); - letter-spacing: 0.05em; -} - -.cute-card-view .thumb { - padding-bottom: 60%; - background-size: cover; - background-position: center center; - border-radius: 10px 10px 0px 0px; -} - -.cute-card-view .thumb-color { - padding-bottom: 10%; - background-size: cover; - background-position: center center; - border-radius: 10px 10px 0px 0px; - text-transform: uppercase; - font-size: 1.2rem; - font-weight: bold; - text-align: center; - color: #FFFFFF; - padding: 10px; -} - -.cute-card-view .thumb-color-folder { - background-color: slateblue; -} - -.cute-card-view .thumb-color-note { - background-color: salmon; -} - - - -/*--------------------------------------------- - strip card view ------------------------------------------------*/ - -.strip-card-band { - width: 100%; -} - -.strip-card-view { - width: 100%; - max-width: 100%; - margin-top: 1.0rem; - margin-bottom: 1.0rem; - display: -webkit-box; - display: -webkit-flex; - display: -ms-flexbox; - display: flex; - -webkit-box-orient: horizontal; - -webkit-box-direction: normal; - -webkit-flex-direction: row; - -ms-flex-direction: row; - flex-direction: row; - -webkit-box-align: stretch; - -webkit-align-items: stretch; - -ms-flex-align: stretch; - align-items: stretch; - min-height: 8rem; - -webkit-border-radius: 10px; - border-radius: 10px; - overflow: hidden; - -webkit-transition: all .3s ease; - -o-transition: all .3s ease; - transition: all .3s ease; - -webkit-box-shadow: 0 1px 1px 0 rgba(31, 35, 46, 0.15); - box-shadow: 0 1px 1px 0 rgba(31, 35, 46, 0.15); - /* add by xpgo */ - background: var(--background-accent); - text-decoration: none !important; - color: var(--text-normal); -} - -.strip-card-view:hover { - -webkit-transform: translate(0px, -2px); - -ms-transform: translate(0px, -2px); - transform: translate(0px, -2px); - -webkit-box-shadow: 0 15px 45px -10px rgba(10, 16, 34, 0.2); - box-shadow: 0 15px 45px -10px rgba(10, 16, 34, 0.2); -} - -.strip-card-view .thumb { - width: 20%; - max-width: 100%; - min-height: 9rem; - -webkit-background-size: cover; - background-size: cover; - background-position: 50% 50%; -} - -.strip-card-view .thumb-color { - width: 20%; - max-width: 100%; - min-height: 9rem; - -webkit-background-size: cover; - background-size: cover; - background-position: center center; - /* add by xpgo */ - display: flex; - justify-content: center; - align-items: center; - padding: 10px; - text-transform: uppercase; - font-size: 1.2rem; - font-weight: bold; - text-align: center; - color: #FFFFFF; -} - -.strip-card-view .thumb-color-folder { - background-color: slateblue; -} - -.strip-card-view .thumb-color-note { - background-color: salmon; -} - -.strip-card-view article { - padding: 1rem; - width: 80%; -} - -.strip-card-view h1 { - font-size: 1.5rem; - margin: 0 0 10px; - color: var(--text-accent); -} - -.strip-card-view a { - text-decoration: none !important; -} - -.strip-card-view p { - margin-top: 0; - flex: 1; - line-height: 1.0; -} - -.strip-card-view span { - font-size: 0.8rem; - font-weight: bold; - color: var(--text-faint); - letter-spacing: 0.05em; -} diff --git a/.obsidian/plugins/obsidian-full-calendar/data.json b/.obsidian/plugins/obsidian-full-calendar/data.json deleted file mode 100644 index 0614cac..0000000 --- a/.obsidian/plugins/obsidian-full-calendar/data.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "calendarSources": [ - { - "type": "local", - "color": "#8f79fb", - "directory": "Calendar" - } - ], - "defaultCalendar": 0, - "recursiveLocal": false, - "firstDay": 0, - "initialView": { - "desktop": "dayGridMonth", - "mobile": "timeGrid3Days" - }, - "timeFormat24h": false -} \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-full-calendar/main.js b/.obsidian/plugins/obsidian-full-calendar/main.js deleted file mode 100644 index 339998f..0000000 --- a/.obsidian/plugins/obsidian-full-calendar/main.js +++ /dev/null @@ -1,54279 +0,0 @@ -/* -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 __defProps = Object.defineProperties; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropDescs = Object.getOwnPropertyDescriptors; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getOwnPropSymbols = Object.getOwnPropertySymbols; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __propIsEnum = Object.prototype.propertyIsEnumerable; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __spreadValues = (a3, b3) => { - for (var prop in b3 || (b3 = {})) - if (__hasOwnProp.call(b3, prop)) - __defNormalProp(a3, prop, b3[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b3)) { - if (__propIsEnum.call(b3, prop)) - __defNormalProp(a3, prop, b3[prop]); - } - return a3; -}; -var __spreadProps = (a3, b3) => __defProps(a3, __getOwnPropDescs(b3)); -var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - __markAsModule(target); - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __reExport = (target, module2, desc) => { - if (module2 && typeof module2 === "object" || typeof module2 === "function") { - for (let key of __getOwnPropNames(module2)) - if (!__hasOwnProp.call(target, key) && key !== "default") - __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable }); - } - return target; -}; -var __toModule = (module2) => { - return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2); -}; -var __async = (__this, __arguments, generator) => { - return new Promise((resolve, reject) => { - var fulfilled = (value) => { - try { - step(generator.next(value)); - } catch (e3) { - reject(e3); - } - }; - var rejected = (value) => { - try { - step(generator.throw(value)); - } catch (e3) { - reject(e3); - } - }; - var step = (x3) => x3.done ? resolve(x3.value) : Promise.resolve(x3.value).then(fulfilled, rejected); - step((generator = generator.apply(__this, __arguments)).next()); - }); -}; - -// node_modules/tslib/tslib.js -var require_tslib = __commonJS({ - "node_modules/tslib/tslib.js"(exports, module2) { - var __extends2; - var __assign2; - var __rest2; - var __decorate2; - var __param2; - var __metadata2; - var __awaiter2; - var __generator2; - var __exportStar2; - var __values2; - var __read2; - var __spread2; - var __spreadArrays2; - var __spreadArray2; - var __await2; - var __asyncGenerator2; - var __asyncDelegator2; - var __asyncValues2; - var __makeTemplateObject2; - var __importStar2; - var __importDefault2; - var __classPrivateFieldGet2; - var __classPrivateFieldSet2; - var __createBinding2; - (function(factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function(exports2) { - factory(createExporter(root, createExporter(exports2))); - }); - } else if (typeof module2 === "object" && typeof module2.exports === "object") { - factory(createExporter(root, createExporter(module2.exports))); - } else { - factory(createExporter(root)); - } - function createExporter(exports2, previous) { - if (exports2 !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports2, "__esModule", { value: true }); - } else { - exports2.__esModule = true; - } - } - return function(id, v3) { - return exports2[id] = previous ? previous(id, v3) : v3; - }; - } - })(function(exporter) { - var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) { - d3.__proto__ = b3; - } || function(d3, b3) { - for (var p3 in b3) - if (Object.prototype.hasOwnProperty.call(b3, p3)) - d3[p3] = b3[p3]; - }; - __extends2 = function(d3, b3) { - if (typeof b3 !== "function" && b3 !== null) - throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null"); - extendStatics(d3, b3); - function __() { - this.constructor = d3; - } - d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __()); - }; - __assign2 = Object.assign || function(t3) { - for (var s3, i3 = 1, n2 = arguments.length; i3 < n2; i3++) { - s3 = arguments[i3]; - for (var p3 in s3) - if (Object.prototype.hasOwnProperty.call(s3, p3)) - t3[p3] = s3[p3]; - } - return t3; - }; - __rest2 = function(s3, e3) { - var t3 = {}; - for (var p3 in s3) - if (Object.prototype.hasOwnProperty.call(s3, p3) && e3.indexOf(p3) < 0) - t3[p3] = s3[p3]; - if (s3 != null && typeof Object.getOwnPropertySymbols === "function") - for (var i3 = 0, p3 = Object.getOwnPropertySymbols(s3); i3 < p3.length; i3++) { - if (e3.indexOf(p3[i3]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p3[i3])) - t3[p3[i3]] = s3[p3[i3]]; - } - return t3; - }; - __decorate2 = function(decorators, target, key, desc) { - var c3 = arguments.length, r3 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") - r3 = Reflect.decorate(decorators, target, key, desc); - else - for (var i3 = decorators.length - 1; i3 >= 0; i3--) - if (d3 = decorators[i3]) - r3 = (c3 < 3 ? d3(r3) : c3 > 3 ? d3(target, key, r3) : d3(target, key)) || r3; - return c3 > 3 && r3 && Object.defineProperty(target, key, r3), r3; - }; - __param2 = function(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; - }; - __metadata2 = function(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") - return Reflect.metadata(metadataKey, metadataValue); - }; - __awaiter2 = function(thisArg, _arguments, P3, generator) { - function adopt(value) { - return value instanceof P3 ? value : new P3(function(resolve) { - resolve(value); - }); - } - return new (P3 || (P3 = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e3) { - reject(e3); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e3) { - reject(e3); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - __generator2 = function(thisArg, body) { - var _3 = { label: 0, sent: function() { - if (t3[0] & 1) - throw t3[1]; - return t3[1]; - }, trys: [], ops: [] }, f3, y3, t3, g3; - return g3 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g3[Symbol.iterator] = function() { - return this; - }), g3; - function verb(n2) { - return function(v3) { - return step([n2, v3]); - }; - } - function step(op) { - if (f3) - throw new TypeError("Generator is already executing."); - while (_3) - try { - if (f3 = 1, y3 && (t3 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t3 = y3["return"]) && t3.call(y3), 0) : y3.next) && !(t3 = t3.call(y3, op[1])).done) - return t3; - if (y3 = 0, t3) - op = [op[0] & 2, t3.value]; - switch (op[0]) { - case 0: - case 1: - t3 = op; - break; - case 4: - _3.label++; - return { value: op[1], done: false }; - case 5: - _3.label++; - y3 = op[1]; - op = [0]; - continue; - case 7: - op = _3.ops.pop(); - _3.trys.pop(); - continue; - default: - if (!(t3 = _3.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _3 = 0; - continue; - } - if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) { - _3.label = op[1]; - break; - } - if (op[0] === 6 && _3.label < t3[1]) { - _3.label = t3[1]; - t3 = op; - break; - } - if (t3 && _3.label < t3[2]) { - _3.label = t3[2]; - _3.ops.push(op); - break; - } - if (t3[2]) - _3.ops.pop(); - _3.trys.pop(); - continue; - } - op = body.call(thisArg, _3); - } catch (e3) { - op = [6, e3]; - y3 = 0; - } finally { - f3 = t3 = 0; - } - if (op[0] & 5) - throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - __exportStar2 = function(m2, o2) { - for (var p3 in m2) - if (p3 !== "default" && !Object.prototype.hasOwnProperty.call(o2, p3)) - __createBinding2(o2, m2, p3); - }; - __createBinding2 = Object.create ? function(o2, m2, k2, k22) { - if (k22 === void 0) - k22 = k2; - Object.defineProperty(o2, k22, { enumerable: true, get: function() { - return m2[k2]; - } }); - } : function(o2, m2, k2, k22) { - if (k22 === void 0) - k22 = k2; - o2[k22] = m2[k2]; - }; - __values2 = function(o2) { - var s3 = typeof Symbol === "function" && Symbol.iterator, m2 = s3 && o2[s3], i3 = 0; - if (m2) - return m2.call(o2); - if (o2 && typeof o2.length === "number") - return { - next: function() { - if (o2 && i3 >= o2.length) - o2 = void 0; - return { value: o2 && o2[i3++], done: !o2 }; - } - }; - throw new TypeError(s3 ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - __read2 = function(o2, n2) { - var m2 = typeof Symbol === "function" && o2[Symbol.iterator]; - if (!m2) - return o2; - var i3 = m2.call(o2), r3, ar = [], e3; - try { - while ((n2 === void 0 || n2-- > 0) && !(r3 = i3.next()).done) - ar.push(r3.value); - } catch (error) { - e3 = { error }; - } finally { - try { - if (r3 && !r3.done && (m2 = i3["return"])) - m2.call(i3); - } finally { - if (e3) - throw e3.error; - } - } - return ar; - }; - __spread2 = function() { - for (var ar = [], i3 = 0; i3 < arguments.length; i3++) - ar = ar.concat(__read2(arguments[i3])); - return ar; - }; - __spreadArrays2 = function() { - for (var s3 = 0, i3 = 0, il = arguments.length; i3 < il; i3++) - s3 += arguments[i3].length; - for (var r3 = Array(s3), k2 = 0, i3 = 0; i3 < il; i3++) - for (var a3 = arguments[i3], j4 = 0, jl = a3.length; j4 < jl; j4++, k2++) - r3[k2] = a3[j4]; - return r3; - }; - __spreadArray2 = function(to, from, pack) { - if (pack || arguments.length === 2) - for (var i3 = 0, l3 = from.length, ar; i3 < l3; i3++) { - if (ar || !(i3 in from)) { - if (!ar) - ar = Array.prototype.slice.call(from, 0, i3); - ar[i3] = from[i3]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - }; - __await2 = function(v3) { - return this instanceof __await2 ? (this.v = v3, this) : new __await2(v3); - }; - __asyncGenerator2 = function(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g3 = generator.apply(thisArg, _arguments || []), i3, q3 = []; - return i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() { - return this; - }, i3; - function verb(n2) { - if (g3[n2]) - i3[n2] = function(v3) { - return new Promise(function(a3, b3) { - q3.push([n2, v3, a3, b3]) > 1 || resume(n2, v3); - }); - }; - } - function resume(n2, v3) { - try { - step(g3[n2](v3)); - } catch (e3) { - settle(q3[0][3], e3); - } - } - function step(r3) { - r3.value instanceof __await2 ? Promise.resolve(r3.value.v).then(fulfill, reject) : settle(q3[0][2], r3); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f3, v3) { - if (f3(v3), q3.shift(), q3.length) - resume(q3[0][0], q3[0][1]); - } - }; - __asyncDelegator2 = function(o2) { - var i3, p3; - return i3 = {}, verb("next"), verb("throw", function(e3) { - throw e3; - }), verb("return"), i3[Symbol.iterator] = function() { - return this; - }, i3; - function verb(n2, f3) { - i3[n2] = o2[n2] ? function(v3) { - return (p3 = !p3) ? { value: __await2(o2[n2](v3)), done: n2 === "return" } : f3 ? f3(v3) : v3; - } : f3; - } - }; - __asyncValues2 = function(o2) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var m2 = o2[Symbol.asyncIterator], i3; - return m2 ? m2.call(o2) : (o2 = typeof __values2 === "function" ? __values2(o2) : o2[Symbol.iterator](), i3 = {}, verb("next"), verb("throw"), verb("return"), i3[Symbol.asyncIterator] = function() { - return this; - }, i3); - function verb(n2) { - i3[n2] = o2[n2] && function(v3) { - return new Promise(function(resolve, reject) { - v3 = o2[n2](v3), settle(resolve, reject, v3.done, v3.value); - }); - }; - } - function settle(resolve, reject, d3, v3) { - Promise.resolve(v3).then(function(v4) { - resolve({ value: v4, done: d3 }); - }, reject); - } - }; - __makeTemplateObject2 = function(cooked, raw) { - if (Object.defineProperty) { - Object.defineProperty(cooked, "raw", { value: raw }); - } else { - cooked.raw = raw; - } - return cooked; - }; - var __setModuleDefault = Object.create ? function(o2, v3) { - Object.defineProperty(o2, "default", { enumerable: true, value: v3 }); - } : function(o2, v3) { - o2["default"] = v3; - }; - __importStar2 = function(mod) { - if (mod && mod.__esModule) - return mod; - var result = {}; - if (mod != null) { - for (var k2 in mod) - if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) - __createBinding2(result, mod, k2); - } - __setModuleDefault(result, mod); - return result; - }; - __importDefault2 = function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - __classPrivateFieldGet2 = function(receiver, state, kind, f3) { - if (kind === "a" && !f3) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver); - }; - __classPrivateFieldSet2 = function(receiver, state, value, kind, f3) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f3) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value; - }; - exporter("__extends", __extends2); - exporter("__assign", __assign2); - exporter("__rest", __rest2); - exporter("__decorate", __decorate2); - exporter("__param", __param2); - exporter("__metadata", __metadata2); - exporter("__awaiter", __awaiter2); - exporter("__generator", __generator2); - exporter("__exportStar", __exportStar2); - exporter("__createBinding", __createBinding2); - exporter("__values", __values2); - exporter("__read", __read2); - exporter("__spread", __spread2); - exporter("__spreadArrays", __spreadArrays2); - exporter("__spreadArray", __spreadArray2); - exporter("__await", __await2); - exporter("__asyncGenerator", __asyncGenerator2); - exporter("__asyncDelegator", __asyncDelegator2); - exporter("__asyncValues", __asyncValues2); - exporter("__makeTemplateObject", __makeTemplateObject2); - exporter("__importStar", __importStar2); - exporter("__importDefault", __importDefault2); - exporter("__classPrivateFieldGet", __classPrivateFieldGet2); - exporter("__classPrivateFieldSet", __classPrivateFieldSet2); - }); - } -}); - -// node_modules/ical.js/build/ical.js -var require_ical = __commonJS({ - "node_modules/ical.js/build/ical.js"(exports, module2) { - var ICAL3; - (function() { - if (typeof module2 === "object") { - ICAL3 = module2.exports; - } else if (typeof HTMLScriptElement !== "undefined" && "noModule" in HTMLScriptElement.prototype) { - window.ICAL = ICAL3 = {}; - } else if (typeof ICAL3 !== "object") { - ICAL3 = {}; - } - })(); - ICAL3.foldLength = 75; - ICAL3.newLineChar = "\r\n"; - ICAL3.helpers = { - updateTimezones: function(vcal) { - var allsubs, properties, vtimezones, reqTzid, i3, tzid; - if (!vcal || vcal.name !== "vcalendar") { - return vcal; - } - allsubs = vcal.getAllSubcomponents(); - properties = []; - vtimezones = {}; - for (i3 = 0; i3 < allsubs.length; i3++) { - if (allsubs[i3].name === "vtimezone") { - tzid = allsubs[i3].getFirstProperty("tzid").getFirstValue(); - vtimezones[tzid] = allsubs[i3]; - } else { - properties = properties.concat(allsubs[i3].getAllProperties()); - } - } - reqTzid = {}; - for (i3 = 0; i3 < properties.length; i3++) { - if (tzid = properties[i3].getParameter("tzid")) { - reqTzid[tzid] = true; - } - } - for (i3 in vtimezones) { - if (vtimezones.hasOwnProperty(i3) && !reqTzid[i3]) { - vcal.removeSubcomponent(vtimezones[i3]); - } - } - for (i3 in reqTzid) { - if (reqTzid.hasOwnProperty(i3) && !vtimezones[i3] && ICAL3.TimezoneService.has(i3)) { - vcal.addSubcomponent(ICAL3.TimezoneService.get(i3).component); - } - } - return vcal; - }, - isStrictlyNaN: function(number) { - return typeof number === "number" && isNaN(number); - }, - strictParseInt: function(string) { - var result = parseInt(string, 10); - if (ICAL3.helpers.isStrictlyNaN(result)) { - throw new Error('Could not extract integer from "' + string + '"'); - } - return result; - }, - formatClassType: function formatClassType(data, type) { - if (typeof data === "undefined") { - return void 0; - } - if (data instanceof type) { - return data; - } - return new type(data); - }, - unescapedIndexOf: function(buffer, search, pos) { - while ((pos = buffer.indexOf(search, pos)) !== -1) { - if (pos > 0 && buffer[pos - 1] === "\\") { - pos += 1; - } else { - return pos; - } - } - return -1; - }, - binsearchInsert: function(list, seekVal, cmpfunc) { - if (!list.length) - return 0; - var low = 0, high = list.length - 1, mid, cmpval; - while (low <= high) { - mid = low + Math.floor((high - low) / 2); - cmpval = cmpfunc(seekVal, list[mid]); - if (cmpval < 0) - high = mid - 1; - else if (cmpval > 0) - low = mid + 1; - else - break; - } - if (cmpval < 0) - return mid; - else if (cmpval > 0) - return mid + 1; - else - return mid; - }, - dumpn: function() { - if (!ICAL3.debug) { - return; - } - if (typeof console !== "undefined" && "log" in console) { - ICAL3.helpers.dumpn = function consoleDumpn(input) { - console.log(input); - }; - } else { - ICAL3.helpers.dumpn = function geckoDumpn(input) { - dump(input + "\n"); - }; - } - ICAL3.helpers.dumpn(arguments[0]); - }, - clone: function(aSrc, aDeep) { - if (!aSrc || typeof aSrc != "object") { - return aSrc; - } else if (aSrc instanceof Date) { - return new Date(aSrc.getTime()); - } else if ("clone" in aSrc) { - return aSrc.clone(); - } else if (Array.isArray(aSrc)) { - var arr = []; - for (var i3 = 0; i3 < aSrc.length; i3++) { - arr.push(aDeep ? ICAL3.helpers.clone(aSrc[i3], true) : aSrc[i3]); - } - return arr; - } else { - var obj = {}; - for (var name in aSrc) { - if (Object.prototype.hasOwnProperty.call(aSrc, name)) { - if (aDeep) { - obj[name] = ICAL3.helpers.clone(aSrc[name], true); - } else { - obj[name] = aSrc[name]; - } - } - } - return obj; - } - }, - foldline: function foldline(aLine) { - var result = ""; - var line = aLine || "", pos = 0, line_length = 0; - while (line.length) { - var cp = line.codePointAt(pos); - if (cp < 128) - ++line_length; - else if (cp < 2048) - line_length += 2; - else if (cp < 65536) - line_length += 3; - else - line_length += 4; - if (line_length < ICAL3.foldLength + 1) - pos += cp > 65535 ? 2 : 1; - else { - result += ICAL3.newLineChar + " " + line.substring(0, pos); - line = line.substring(pos); - pos = line_length = 0; - } - } - return result.substr(ICAL3.newLineChar.length + 1); - }, - pad2: function pad(data) { - if (typeof data !== "string") { - if (typeof data === "number") { - data = parseInt(data); - } - data = String(data); - } - var len = data.length; - switch (len) { - case 0: - return "00"; - case 1: - return "0" + data; - default: - return data; - } - }, - trunc: function trunc(number) { - return number < 0 ? Math.ceil(number) : Math.floor(number); - }, - inherits: function(base, child, extra) { - function F2() { - } - F2.prototype = base.prototype; - child.prototype = new F2(); - if (extra) { - ICAL3.helpers.extend(extra, child.prototype); - } - }, - extend: function(source, target) { - for (var key in source) { - var descr = Object.getOwnPropertyDescriptor(source, key); - if (descr && !Object.getOwnPropertyDescriptor(target, key)) { - Object.defineProperty(target, key, descr); - } - } - return target; - } - }; - ICAL3.design = function() { - "use strict"; - var FROM_ICAL_NEWLINE = /\\\\|\\;|\\,|\\[Nn]/g; - var TO_ICAL_NEWLINE = /\\|;|,|\n/g; - var FROM_VCARD_NEWLINE = /\\\\|\\,|\\[Nn]/g; - var TO_VCARD_NEWLINE = /\\|,|\n/g; - function createTextType(fromNewline, toNewline) { - var result = { - matches: /.*/, - fromICAL: function(aValue, structuredEscape) { - return replaceNewline(aValue, fromNewline, structuredEscape); - }, - toICAL: function(aValue, structuredEscape) { - var regEx = toNewline; - if (structuredEscape) - regEx = new RegExp(regEx.source + "|" + structuredEscape); - return aValue.replace(regEx, function(str) { - switch (str) { - case "\\": - return "\\\\"; - case ";": - return "\\;"; - case ",": - return "\\,"; - case "\n": - return "\\n"; - default: - return str; - } - }); - } - }; - return result; - } - var DEFAULT_TYPE_TEXT = { defaultType: "text" }; - var DEFAULT_TYPE_TEXT_MULTI = { defaultType: "text", multiValue: "," }; - var DEFAULT_TYPE_TEXT_STRUCTURED = { defaultType: "text", structuredValue: ";" }; - var DEFAULT_TYPE_INTEGER = { defaultType: "integer" }; - var DEFAULT_TYPE_DATETIME_DATE = { defaultType: "date-time", allowedTypes: ["date-time", "date"] }; - var DEFAULT_TYPE_DATETIME = { defaultType: "date-time" }; - var DEFAULT_TYPE_URI = { defaultType: "uri" }; - var DEFAULT_TYPE_UTCOFFSET = { defaultType: "utc-offset" }; - var DEFAULT_TYPE_RECUR = { defaultType: "recur" }; - var DEFAULT_TYPE_DATE_ANDOR_TIME = { defaultType: "date-and-or-time", allowedTypes: ["date-time", "date", "text"] }; - function replaceNewlineReplace(string) { - switch (string) { - case "\\\\": - return "\\"; - case "\\;": - return ";"; - case "\\,": - return ","; - case "\\n": - case "\\N": - return "\n"; - default: - return string; - } - } - function replaceNewline(value, newline, structuredEscape) { - if (value.indexOf("\\") === -1) { - return value; - } - if (structuredEscape) - newline = new RegExp(newline.source + "|\\\\" + structuredEscape); - return value.replace(newline, replaceNewlineReplace); - } - var commonProperties = { - "categories": DEFAULT_TYPE_TEXT_MULTI, - "url": DEFAULT_TYPE_URI, - "version": DEFAULT_TYPE_TEXT, - "uid": DEFAULT_TYPE_TEXT - }; - var commonValues = { - "boolean": { - values: ["TRUE", "FALSE"], - fromICAL: function(aValue) { - switch (aValue) { - case "TRUE": - return true; - case "FALSE": - return false; - default: - return false; - } - }, - toICAL: function(aValue) { - if (aValue) { - return "TRUE"; - } - return "FALSE"; - } - }, - float: { - matches: /^[+-]?\d+\.\d+$/, - fromICAL: function(aValue) { - var parsed = parseFloat(aValue); - if (ICAL3.helpers.isStrictlyNaN(parsed)) { - return 0; - } - return parsed; - }, - toICAL: function(aValue) { - return String(aValue); - } - }, - integer: { - fromICAL: function(aValue) { - var parsed = parseInt(aValue); - if (ICAL3.helpers.isStrictlyNaN(parsed)) { - return 0; - } - return parsed; - }, - toICAL: function(aValue) { - return String(aValue); - } - }, - "utc-offset": { - toICAL: function(aValue) { - if (aValue.length < 7) { - return aValue.substr(0, 3) + aValue.substr(4, 2); - } else { - return aValue.substr(0, 3) + aValue.substr(4, 2) + aValue.substr(7, 2); - } - }, - fromICAL: function(aValue) { - if (aValue.length < 6) { - return aValue.substr(0, 3) + ":" + aValue.substr(3, 2); - } else { - return aValue.substr(0, 3) + ":" + aValue.substr(3, 2) + ":" + aValue.substr(5, 2); - } - }, - decorate: function(aValue) { - return ICAL3.UtcOffset.fromString(aValue); - }, - undecorate: function(aValue) { - return aValue.toString(); - } - } - }; - var icalParams = { - "cutype": { - values: ["INDIVIDUAL", "GROUP", "RESOURCE", "ROOM", "UNKNOWN"], - allowXName: true, - allowIanaToken: true - }, - "delegated-from": { - valueType: "cal-address", - multiValue: ",", - multiValueSeparateDQuote: true - }, - "delegated-to": { - valueType: "cal-address", - multiValue: ",", - multiValueSeparateDQuote: true - }, - "encoding": { - values: ["8BIT", "BASE64"] - }, - "fbtype": { - values: ["FREE", "BUSY", "BUSY-UNAVAILABLE", "BUSY-TENTATIVE"], - allowXName: true, - allowIanaToken: true - }, - "member": { - valueType: "cal-address", - multiValue: ",", - multiValueSeparateDQuote: true - }, - "partstat": { - values: [ - "NEEDS-ACTION", - "ACCEPTED", - "DECLINED", - "TENTATIVE", - "DELEGATED", - "COMPLETED", - "IN-PROCESS" - ], - allowXName: true, - allowIanaToken: true - }, - "range": { - values: ["THISANDFUTURE"] - }, - "related": { - values: ["START", "END"] - }, - "reltype": { - values: ["PARENT", "CHILD", "SIBLING"], - allowXName: true, - allowIanaToken: true - }, - "role": { - values: [ - "REQ-PARTICIPANT", - "CHAIR", - "OPT-PARTICIPANT", - "NON-PARTICIPANT" - ], - allowXName: true, - allowIanaToken: true - }, - "rsvp": { - values: ["TRUE", "FALSE"] - }, - "sent-by": { - valueType: "cal-address" - }, - "tzid": { - matches: /^\// - }, - "value": { - values: [ - "binary", - "boolean", - "cal-address", - "date", - "date-time", - "duration", - "float", - "integer", - "period", - "recur", - "text", - "time", - "uri", - "utc-offset" - ], - allowXName: true, - allowIanaToken: true - } - }; - var icalValues = ICAL3.helpers.extend(commonValues, { - text: createTextType(FROM_ICAL_NEWLINE, TO_ICAL_NEWLINE), - uri: {}, - "binary": { - decorate: function(aString) { - return ICAL3.Binary.fromString(aString); - }, - undecorate: function(aBinary) { - return aBinary.toString(); - } - }, - "cal-address": {}, - "date": { - decorate: function(aValue, aProp) { - if (design.strict) { - return ICAL3.Time.fromDateString(aValue, aProp); - } else { - return ICAL3.Time.fromString(aValue, aProp); - } - }, - undecorate: function(aValue) { - return aValue.toString(); - }, - fromICAL: function(aValue) { - if (!design.strict && aValue.length >= 15) { - return icalValues["date-time"].fromICAL(aValue); - } else { - return aValue.substr(0, 4) + "-" + aValue.substr(4, 2) + "-" + aValue.substr(6, 2); - } - }, - toICAL: function(aValue) { - var len = aValue.length; - if (len == 10) { - return aValue.substr(0, 4) + aValue.substr(5, 2) + aValue.substr(8, 2); - } else if (len >= 19) { - return icalValues["date-time"].toICAL(aValue); - } else { - return aValue; - } - } - }, - "date-time": { - fromICAL: function(aValue) { - if (!design.strict && aValue.length == 8) { - return icalValues.date.fromICAL(aValue); - } else { - var result = aValue.substr(0, 4) + "-" + aValue.substr(4, 2) + "-" + aValue.substr(6, 2) + "T" + aValue.substr(9, 2) + ":" + aValue.substr(11, 2) + ":" + aValue.substr(13, 2); - if (aValue[15] && aValue[15] === "Z") { - result += "Z"; - } - return result; - } - }, - toICAL: function(aValue) { - var len = aValue.length; - if (len == 10 && !design.strict) { - return icalValues.date.toICAL(aValue); - } else if (len >= 19) { - var result = aValue.substr(0, 4) + aValue.substr(5, 2) + aValue.substr(8, 5) + aValue.substr(14, 2) + aValue.substr(17, 2); - if (aValue[19] && aValue[19] === "Z") { - result += "Z"; - } - return result; - } else { - return aValue; - } - }, - decorate: function(aValue, aProp) { - if (design.strict) { - return ICAL3.Time.fromDateTimeString(aValue, aProp); - } else { - return ICAL3.Time.fromString(aValue, aProp); - } - }, - undecorate: function(aValue) { - return aValue.toString(); - } - }, - duration: { - decorate: function(aValue) { - return ICAL3.Duration.fromString(aValue); - }, - undecorate: function(aValue) { - return aValue.toString(); - } - }, - period: { - fromICAL: function(string) { - var parts = string.split("/"); - parts[0] = icalValues["date-time"].fromICAL(parts[0]); - if (!ICAL3.Duration.isValueString(parts[1])) { - parts[1] = icalValues["date-time"].fromICAL(parts[1]); - } - return parts; - }, - toICAL: function(parts) { - if (!design.strict && parts[0].length == 10) { - parts[0] = icalValues.date.toICAL(parts[0]); - } else { - parts[0] = icalValues["date-time"].toICAL(parts[0]); - } - if (!ICAL3.Duration.isValueString(parts[1])) { - if (!design.strict && parts[1].length == 10) { - parts[1] = icalValues.date.toICAL(parts[1]); - } else { - parts[1] = icalValues["date-time"].toICAL(parts[1]); - } - } - return parts.join("/"); - }, - decorate: function(aValue, aProp) { - return ICAL3.Period.fromJSON(aValue, aProp, !design.strict); - }, - undecorate: function(aValue) { - return aValue.toJSON(); - } - }, - recur: { - fromICAL: function(string) { - return ICAL3.Recur._stringToData(string, true); - }, - toICAL: function(data) { - var str = ""; - for (var k2 in data) { - if (!Object.prototype.hasOwnProperty.call(data, k2)) { - continue; - } - var val = data[k2]; - if (k2 == "until") { - if (val.length > 10) { - val = icalValues["date-time"].toICAL(val); - } else { - val = icalValues.date.toICAL(val); - } - } else if (k2 == "wkst") { - if (typeof val === "number") { - val = ICAL3.Recur.numericDayToIcalDay(val); - } - } else if (Array.isArray(val)) { - val = val.join(","); - } - str += k2.toUpperCase() + "=" + val + ";"; - } - return str.substr(0, str.length - 1); - }, - decorate: function decorate(aValue) { - return ICAL3.Recur.fromData(aValue); - }, - undecorate: function(aRecur) { - return aRecur.toJSON(); - } - }, - time: { - fromICAL: function(aValue) { - if (aValue.length < 6) { - return aValue; - } - var result = aValue.substr(0, 2) + ":" + aValue.substr(2, 2) + ":" + aValue.substr(4, 2); - if (aValue[6] === "Z") { - result += "Z"; - } - return result; - }, - toICAL: function(aValue) { - if (aValue.length < 8) { - return aValue; - } - var result = aValue.substr(0, 2) + aValue.substr(3, 2) + aValue.substr(6, 2); - if (aValue[8] === "Z") { - result += "Z"; - } - return result; - } - } - }); - var icalProperties = ICAL3.helpers.extend(commonProperties, { - "action": DEFAULT_TYPE_TEXT, - "attach": { defaultType: "uri" }, - "attendee": { defaultType: "cal-address" }, - "calscale": DEFAULT_TYPE_TEXT, - "class": DEFAULT_TYPE_TEXT, - "comment": DEFAULT_TYPE_TEXT, - "completed": DEFAULT_TYPE_DATETIME, - "contact": DEFAULT_TYPE_TEXT, - "created": DEFAULT_TYPE_DATETIME, - "description": DEFAULT_TYPE_TEXT, - "dtend": DEFAULT_TYPE_DATETIME_DATE, - "dtstamp": DEFAULT_TYPE_DATETIME, - "dtstart": DEFAULT_TYPE_DATETIME_DATE, - "due": DEFAULT_TYPE_DATETIME_DATE, - "duration": { defaultType: "duration" }, - "exdate": { - defaultType: "date-time", - allowedTypes: ["date-time", "date"], - multiValue: "," - }, - "exrule": DEFAULT_TYPE_RECUR, - "freebusy": { defaultType: "period", multiValue: "," }, - "geo": { defaultType: "float", structuredValue: ";" }, - "last-modified": DEFAULT_TYPE_DATETIME, - "location": DEFAULT_TYPE_TEXT, - "method": DEFAULT_TYPE_TEXT, - "organizer": { defaultType: "cal-address" }, - "percent-complete": DEFAULT_TYPE_INTEGER, - "priority": DEFAULT_TYPE_INTEGER, - "prodid": DEFAULT_TYPE_TEXT, - "related-to": DEFAULT_TYPE_TEXT, - "repeat": DEFAULT_TYPE_INTEGER, - "rdate": { - defaultType: "date-time", - allowedTypes: ["date-time", "date", "period"], - multiValue: ",", - detectType: function(string) { - if (string.indexOf("/") !== -1) { - return "period"; - } - return string.indexOf("T") === -1 ? "date" : "date-time"; - } - }, - "recurrence-id": DEFAULT_TYPE_DATETIME_DATE, - "resources": DEFAULT_TYPE_TEXT_MULTI, - "request-status": DEFAULT_TYPE_TEXT_STRUCTURED, - "rrule": DEFAULT_TYPE_RECUR, - "sequence": DEFAULT_TYPE_INTEGER, - "status": DEFAULT_TYPE_TEXT, - "summary": DEFAULT_TYPE_TEXT, - "transp": DEFAULT_TYPE_TEXT, - "trigger": { defaultType: "duration", allowedTypes: ["duration", "date-time"] }, - "tzoffsetfrom": DEFAULT_TYPE_UTCOFFSET, - "tzoffsetto": DEFAULT_TYPE_UTCOFFSET, - "tzurl": DEFAULT_TYPE_URI, - "tzid": DEFAULT_TYPE_TEXT, - "tzname": DEFAULT_TYPE_TEXT - }); - var vcardValues = ICAL3.helpers.extend(commonValues, { - text: createTextType(FROM_VCARD_NEWLINE, TO_VCARD_NEWLINE), - uri: createTextType(FROM_VCARD_NEWLINE, TO_VCARD_NEWLINE), - date: { - decorate: function(aValue) { - return ICAL3.VCardTime.fromDateAndOrTimeString(aValue, "date"); - }, - undecorate: function(aValue) { - return aValue.toString(); - }, - fromICAL: function(aValue) { - if (aValue.length == 8) { - return icalValues.date.fromICAL(aValue); - } else if (aValue[0] == "-" && aValue.length == 6) { - return aValue.substr(0, 4) + "-" + aValue.substr(4); - } else { - return aValue; - } - }, - toICAL: function(aValue) { - if (aValue.length == 10) { - return icalValues.date.toICAL(aValue); - } else if (aValue[0] == "-" && aValue.length == 7) { - return aValue.substr(0, 4) + aValue.substr(5); - } else { - return aValue; - } - } - }, - time: { - decorate: function(aValue) { - return ICAL3.VCardTime.fromDateAndOrTimeString("T" + aValue, "time"); - }, - undecorate: function(aValue) { - return aValue.toString(); - }, - fromICAL: function(aValue) { - var splitzone = vcardValues.time._splitZone(aValue, true); - var zone = splitzone[0], value = splitzone[1]; - if (value.length == 6) { - value = value.substr(0, 2) + ":" + value.substr(2, 2) + ":" + value.substr(4, 2); - } else if (value.length == 4 && value[0] != "-") { - value = value.substr(0, 2) + ":" + value.substr(2, 2); - } else if (value.length == 5) { - value = value.substr(0, 3) + ":" + value.substr(3, 2); - } - if (zone.length == 5 && (zone[0] == "-" || zone[0] == "+")) { - zone = zone.substr(0, 3) + ":" + zone.substr(3); - } - return value + zone; - }, - toICAL: function(aValue) { - var splitzone = vcardValues.time._splitZone(aValue); - var zone = splitzone[0], value = splitzone[1]; - if (value.length == 8) { - value = value.substr(0, 2) + value.substr(3, 2) + value.substr(6, 2); - } else if (value.length == 5 && value[0] != "-") { - value = value.substr(0, 2) + value.substr(3, 2); - } else if (value.length == 6) { - value = value.substr(0, 3) + value.substr(4, 2); - } - if (zone.length == 6 && (zone[0] == "-" || zone[0] == "+")) { - zone = zone.substr(0, 3) + zone.substr(4); - } - return value + zone; - }, - _splitZone: function(aValue, isFromIcal) { - var lastChar = aValue.length - 1; - var signChar = aValue.length - (isFromIcal ? 5 : 6); - var sign = aValue[signChar]; - var zone, value; - if (aValue[lastChar] == "Z") { - zone = aValue[lastChar]; - value = aValue.substr(0, lastChar); - } else if (aValue.length > 6 && (sign == "-" || sign == "+")) { - zone = aValue.substr(signChar); - value = aValue.substr(0, signChar); - } else { - zone = ""; - value = aValue; - } - return [zone, value]; - } - }, - "date-time": { - decorate: function(aValue) { - return ICAL3.VCardTime.fromDateAndOrTimeString(aValue, "date-time"); - }, - undecorate: function(aValue) { - return aValue.toString(); - }, - fromICAL: function(aValue) { - return vcardValues["date-and-or-time"].fromICAL(aValue); - }, - toICAL: function(aValue) { - return vcardValues["date-and-or-time"].toICAL(aValue); - } - }, - "date-and-or-time": { - decorate: function(aValue) { - return ICAL3.VCardTime.fromDateAndOrTimeString(aValue, "date-and-or-time"); - }, - undecorate: function(aValue) { - return aValue.toString(); - }, - fromICAL: function(aValue) { - var parts = aValue.split("T"); - return (parts[0] ? vcardValues.date.fromICAL(parts[0]) : "") + (parts[1] ? "T" + vcardValues.time.fromICAL(parts[1]) : ""); - }, - toICAL: function(aValue) { - var parts = aValue.split("T"); - return vcardValues.date.toICAL(parts[0]) + (parts[1] ? "T" + vcardValues.time.toICAL(parts[1]) : ""); - } - }, - timestamp: icalValues["date-time"], - "language-tag": { - matches: /^[a-zA-Z0-9-]+$/ - } - }); - var vcardParams = { - "type": { - valueType: "text", - multiValue: "," - }, - "value": { - values: [ - "text", - "uri", - "date", - "time", - "date-time", - "date-and-or-time", - "timestamp", - "boolean", - "integer", - "float", - "utc-offset", - "language-tag" - ], - allowXName: true, - allowIanaToken: true - } - }; - var vcardProperties = ICAL3.helpers.extend(commonProperties, { - "adr": { defaultType: "text", structuredValue: ";", multiValue: "," }, - "anniversary": DEFAULT_TYPE_DATE_ANDOR_TIME, - "bday": DEFAULT_TYPE_DATE_ANDOR_TIME, - "caladruri": DEFAULT_TYPE_URI, - "caluri": DEFAULT_TYPE_URI, - "clientpidmap": DEFAULT_TYPE_TEXT_STRUCTURED, - "email": DEFAULT_TYPE_TEXT, - "fburl": DEFAULT_TYPE_URI, - "fn": DEFAULT_TYPE_TEXT, - "gender": DEFAULT_TYPE_TEXT_STRUCTURED, - "geo": DEFAULT_TYPE_URI, - "impp": DEFAULT_TYPE_URI, - "key": DEFAULT_TYPE_URI, - "kind": DEFAULT_TYPE_TEXT, - "lang": { defaultType: "language-tag" }, - "logo": DEFAULT_TYPE_URI, - "member": DEFAULT_TYPE_URI, - "n": { defaultType: "text", structuredValue: ";", multiValue: "," }, - "nickname": DEFAULT_TYPE_TEXT_MULTI, - "note": DEFAULT_TYPE_TEXT, - "org": { defaultType: "text", structuredValue: ";" }, - "photo": DEFAULT_TYPE_URI, - "related": DEFAULT_TYPE_URI, - "rev": { defaultType: "timestamp" }, - "role": DEFAULT_TYPE_TEXT, - "sound": DEFAULT_TYPE_URI, - "source": DEFAULT_TYPE_URI, - "tel": { defaultType: "uri", allowedTypes: ["uri", "text"] }, - "title": DEFAULT_TYPE_TEXT, - "tz": { defaultType: "text", allowedTypes: ["text", "utc-offset", "uri"] }, - "xml": DEFAULT_TYPE_TEXT - }); - var vcard3Values = ICAL3.helpers.extend(commonValues, { - binary: icalValues.binary, - date: vcardValues.date, - "date-time": vcardValues["date-time"], - "phone-number": {}, - uri: icalValues.uri, - text: icalValues.text, - time: icalValues.time, - vcard: icalValues.text, - "utc-offset": { - toICAL: function(aValue) { - return aValue.substr(0, 7); - }, - fromICAL: function(aValue) { - return aValue.substr(0, 7); - }, - decorate: function(aValue) { - return ICAL3.UtcOffset.fromString(aValue); - }, - undecorate: function(aValue) { - return aValue.toString(); - } - } - }); - var vcard3Params = { - "type": { - valueType: "text", - multiValue: "," - }, - "value": { - values: [ - "text", - "uri", - "date", - "date-time", - "phone-number", - "time", - "boolean", - "integer", - "float", - "utc-offset", - "vcard", - "binary" - ], - allowXName: true, - allowIanaToken: true - } - }; - var vcard3Properties = ICAL3.helpers.extend(commonProperties, { - fn: DEFAULT_TYPE_TEXT, - n: { defaultType: "text", structuredValue: ";", multiValue: "," }, - nickname: DEFAULT_TYPE_TEXT_MULTI, - photo: { defaultType: "binary", allowedTypes: ["binary", "uri"] }, - bday: { - defaultType: "date-time", - allowedTypes: ["date-time", "date"], - detectType: function(string) { - return string.indexOf("T") === -1 ? "date" : "date-time"; - } - }, - adr: { defaultType: "text", structuredValue: ";", multiValue: "," }, - label: DEFAULT_TYPE_TEXT, - tel: { defaultType: "phone-number" }, - email: DEFAULT_TYPE_TEXT, - mailer: DEFAULT_TYPE_TEXT, - tz: { defaultType: "utc-offset", allowedTypes: ["utc-offset", "text"] }, - geo: { defaultType: "float", structuredValue: ";" }, - title: DEFAULT_TYPE_TEXT, - role: DEFAULT_TYPE_TEXT, - logo: { defaultType: "binary", allowedTypes: ["binary", "uri"] }, - agent: { defaultType: "vcard", allowedTypes: ["vcard", "text", "uri"] }, - org: DEFAULT_TYPE_TEXT_STRUCTURED, - note: DEFAULT_TYPE_TEXT_MULTI, - prodid: DEFAULT_TYPE_TEXT, - rev: { - defaultType: "date-time", - allowedTypes: ["date-time", "date"], - detectType: function(string) { - return string.indexOf("T") === -1 ? "date" : "date-time"; - } - }, - "sort-string": DEFAULT_TYPE_TEXT, - sound: { defaultType: "binary", allowedTypes: ["binary", "uri"] }, - class: DEFAULT_TYPE_TEXT, - key: { defaultType: "binary", allowedTypes: ["binary", "text"] } - }); - var icalSet = { - value: icalValues, - param: icalParams, - property: icalProperties - }; - var vcardSet = { - value: vcardValues, - param: vcardParams, - property: vcardProperties - }; - var vcard3Set = { - value: vcard3Values, - param: vcard3Params, - property: vcard3Properties - }; - var design = { - strict: true, - defaultSet: icalSet, - defaultType: "unknown", - components: { - vcard: vcardSet, - vcard3: vcard3Set, - vevent: icalSet, - vtodo: icalSet, - vjournal: icalSet, - valarm: icalSet, - vtimezone: icalSet, - daylight: icalSet, - standard: icalSet - }, - icalendar: icalSet, - vcard: vcardSet, - vcard3: vcard3Set, - getDesignSet: function(componentName) { - var isInDesign = componentName && componentName in design.components; - return isInDesign ? design.components[componentName] : design.defaultSet; - } - }; - return design; - }(); - ICAL3.stringify = function() { - "use strict"; - var LINE_ENDING = "\r\n"; - var DEFAULT_VALUE_TYPE = "unknown"; - var design = ICAL3.design; - var helpers = ICAL3.helpers; - function stringify(jCal) { - if (typeof jCal[0] == "string") { - jCal = [jCal]; - } - var i3 = 0; - var len = jCal.length; - var result = ""; - for (; i3 < len; i3++) { - result += stringify.component(jCal[i3]) + LINE_ENDING; - } - return result; - } - stringify.component = function(component, designSet) { - var name = component[0].toUpperCase(); - var result = "BEGIN:" + name + LINE_ENDING; - var props = component[1]; - var propIdx = 0; - var propLen = props.length; - var designSetName = component[0]; - if (designSetName === "vcard" && component[1].length > 0 && !(component[1][0][0] === "version" && component[1][0][3] === "4.0")) { - designSetName = "vcard3"; - } - designSet = designSet || design.getDesignSet(designSetName); - for (; propIdx < propLen; propIdx++) { - result += stringify.property(props[propIdx], designSet) + LINE_ENDING; - } - var comps = component[2] || []; - var compIdx = 0; - var compLen = comps.length; - for (; compIdx < compLen; compIdx++) { - result += stringify.component(comps[compIdx], designSet) + LINE_ENDING; - } - result += "END:" + name; - return result; - }; - stringify.property = function(property, designSet, noFold) { - var name = property[0].toUpperCase(); - var jsName = property[0]; - var params = property[1]; - var line = name; - var paramName; - for (paramName in params) { - var value = params[paramName]; - if (params.hasOwnProperty(paramName)) { - var multiValue = paramName in designSet.param && designSet.param[paramName].multiValue; - if (multiValue && Array.isArray(value)) { - if (designSet.param[paramName].multiValueSeparateDQuote) { - multiValue = '"' + multiValue + '"'; - } - value = value.map(stringify._rfc6868Unescape); - value = stringify.multiValue(value, multiValue, "unknown", null, designSet); - } else { - value = stringify._rfc6868Unescape(value); - } - line += ";" + paramName.toUpperCase(); - line += "=" + stringify.propertyValue(value); - } - } - if (property.length === 3) { - return line + ":"; - } - var valueType = property[2]; - if (!designSet) { - designSet = design.defaultSet; - } - var propDetails; - var multiValue = false; - var structuredValue = false; - var isDefault = false; - if (jsName in designSet.property) { - propDetails = designSet.property[jsName]; - if ("multiValue" in propDetails) { - multiValue = propDetails.multiValue; - } - if ("structuredValue" in propDetails && Array.isArray(property[3])) { - structuredValue = propDetails.structuredValue; - } - if ("defaultType" in propDetails) { - if (valueType === propDetails.defaultType) { - isDefault = true; - } - } else { - if (valueType === DEFAULT_VALUE_TYPE) { - isDefault = true; - } - } - } else { - if (valueType === DEFAULT_VALUE_TYPE) { - isDefault = true; - } - } - if (!isDefault) { - line += ";VALUE=" + valueType.toUpperCase(); - } - line += ":"; - if (multiValue && structuredValue) { - line += stringify.multiValue(property[3], structuredValue, valueType, multiValue, designSet, structuredValue); - } else if (multiValue) { - line += stringify.multiValue(property.slice(3), multiValue, valueType, null, designSet, false); - } else if (structuredValue) { - line += stringify.multiValue(property[3], structuredValue, valueType, null, designSet, structuredValue); - } else { - line += stringify.value(property[3], valueType, designSet, false); - } - return noFold ? line : ICAL3.helpers.foldline(line); - }; - stringify.propertyValue = function(value) { - if (helpers.unescapedIndexOf(value, ",") === -1 && helpers.unescapedIndexOf(value, ":") === -1 && helpers.unescapedIndexOf(value, ";") === -1) { - return value; - } - return '"' + value + '"'; - }; - stringify.multiValue = function(values, delim, type, innerMulti, designSet, structuredValue) { - var result = ""; - var len = values.length; - var i3 = 0; - for (; i3 < len; i3++) { - if (innerMulti && Array.isArray(values[i3])) { - result += stringify.multiValue(values[i3], innerMulti, type, null, designSet, structuredValue); - } else { - result += stringify.value(values[i3], type, designSet, structuredValue); - } - if (i3 !== len - 1) { - result += delim; - } - } - return result; - }; - stringify.value = function(value, type, designSet, structuredValue) { - if (type in designSet.value && "toICAL" in designSet.value[type]) { - return designSet.value[type].toICAL(value, structuredValue); - } - return value; - }; - stringify._rfc6868Unescape = function(val) { - return val.replace(/[\n^"]/g, function(x3) { - return RFC6868_REPLACE_MAP[x3]; - }); - }; - var RFC6868_REPLACE_MAP = { '"': "^'", "\n": "^n", "^": "^^" }; - return stringify; - }(); - ICAL3.parse = function() { - "use strict"; - var CHAR = /[^ \t]/; - var MULTIVALUE_DELIMITER = ","; - var VALUE_DELIMITER = ":"; - var PARAM_DELIMITER = ";"; - var PARAM_NAME_DELIMITER = "="; - var DEFAULT_VALUE_TYPE = "unknown"; - var DEFAULT_PARAM_TYPE = "text"; - var design = ICAL3.design; - var helpers = ICAL3.helpers; - function ParserError(message) { - this.message = message; - this.name = "ParserError"; - try { - throw new Error(); - } catch (e3) { - if (e3.stack) { - var split = e3.stack.split("\n"); - split.shift(); - this.stack = split.join("\n"); - } - } - } - ParserError.prototype = Error.prototype; - function parser(input) { - var state = {}; - var root = state.component = []; - state.stack = [root]; - parser._eachLine(input, function(err, line) { - parser._handleContentLine(line, state); - }); - if (state.stack.length > 1) { - throw new ParserError("invalid ical body. component began but did not end"); - } - state = null; - return root.length == 1 ? root[0] : root; - } - parser.property = function(str, designSet) { - var state = { - component: [[], []], - designSet: designSet || design.defaultSet - }; - parser._handleContentLine(str, state); - return state.component[1][0]; - }; - parser.component = function(str) { - return parser(str); - }; - parser.ParserError = ParserError; - parser._handleContentLine = function(line, state) { - var valuePos = line.indexOf(VALUE_DELIMITER); - var paramPos = line.indexOf(PARAM_DELIMITER); - var lastParamIndex; - var lastValuePos; - var name; - var value; - var params = {}; - if (paramPos !== -1 && valuePos !== -1) { - if (paramPos > valuePos) { - paramPos = -1; - } - } - var parsedParams; - if (paramPos !== -1) { - name = line.substring(0, paramPos).toLowerCase(); - parsedParams = parser._parseParameters(line.substring(paramPos), 0, state.designSet); - if (parsedParams[2] == -1) { - throw new ParserError("Invalid parameters in '" + line + "'"); - } - params = parsedParams[0]; - lastParamIndex = parsedParams[1].length + parsedParams[2] + paramPos; - if ((lastValuePos = line.substring(lastParamIndex).indexOf(VALUE_DELIMITER)) !== -1) { - value = line.substring(lastParamIndex + lastValuePos + 1); - } else { - throw new ParserError("Missing parameter value in '" + line + "'"); - } - } else if (valuePos !== -1) { - name = line.substring(0, valuePos).toLowerCase(); - value = line.substring(valuePos + 1); - if (name === "begin") { - var newComponent = [value.toLowerCase(), [], []]; - if (state.stack.length === 1) { - state.component.push(newComponent); - } else { - state.component[2].push(newComponent); - } - state.stack.push(state.component); - state.component = newComponent; - if (!state.designSet) { - state.designSet = design.getDesignSet(state.component[0]); - } - return; - } else if (name === "end") { - state.component = state.stack.pop(); - return; - } - } else { - throw new ParserError('invalid line (no token ";" or ":") "' + line + '"'); - } - var valueType; - var multiValue = false; - var structuredValue = false; - var propertyDetails; - if (name in state.designSet.property) { - propertyDetails = state.designSet.property[name]; - if ("multiValue" in propertyDetails) { - multiValue = propertyDetails.multiValue; - } - if ("structuredValue" in propertyDetails) { - structuredValue = propertyDetails.structuredValue; - } - if (value && "detectType" in propertyDetails) { - valueType = propertyDetails.detectType(value); - } - } - if (!valueType) { - if (!("value" in params)) { - if (propertyDetails) { - valueType = propertyDetails.defaultType; - } else { - valueType = DEFAULT_VALUE_TYPE; - } - } else { - valueType = params.value.toLowerCase(); - } - } - delete params.value; - var result; - if (multiValue && structuredValue) { - value = parser._parseMultiValue(value, structuredValue, valueType, [], multiValue, state.designSet, structuredValue); - result = [name, params, valueType, value]; - } else if (multiValue) { - result = [name, params, valueType]; - parser._parseMultiValue(value, multiValue, valueType, result, null, state.designSet, false); - } else if (structuredValue) { - value = parser._parseMultiValue(value, structuredValue, valueType, [], null, state.designSet, structuredValue); - result = [name, params, valueType, value]; - } else { - value = parser._parseValue(value, valueType, state.designSet, false); - result = [name, params, valueType, value]; - } - if (state.component[0] === "vcard" && state.component[1].length === 0 && !(name === "version" && value === "4.0")) { - state.designSet = design.getDesignSet("vcard3"); - } - state.component[1].push(result); - }; - parser._parseValue = function(value, type, designSet, structuredValue) { - if (type in designSet.value && "fromICAL" in designSet.value[type]) { - return designSet.value[type].fromICAL(value, structuredValue); - } - return value; - }; - parser._parseParameters = function(line, start, designSet) { - var lastParam = start; - var pos = 0; - var delim = PARAM_NAME_DELIMITER; - var result = {}; - var name, lcname; - var value, valuePos = -1; - var type, multiValue, mvdelim; - while (pos !== false && (pos = helpers.unescapedIndexOf(line, delim, pos + 1)) !== -1) { - name = line.substr(lastParam + 1, pos - lastParam - 1); - if (name.length == 0) { - throw new ParserError("Empty parameter name in '" + line + "'"); - } - lcname = name.toLowerCase(); - mvdelim = false; - multiValue = false; - if (lcname in designSet.param && designSet.param[lcname].valueType) { - type = designSet.param[lcname].valueType; - } else { - type = DEFAULT_PARAM_TYPE; - } - if (lcname in designSet.param) { - multiValue = designSet.param[lcname].multiValue; - if (designSet.param[lcname].multiValueSeparateDQuote) { - mvdelim = parser._rfc6868Escape('"' + multiValue + '"'); - } - } - var nextChar = line[pos + 1]; - if (nextChar === '"') { - valuePos = pos + 2; - pos = helpers.unescapedIndexOf(line, '"', valuePos); - if (multiValue && pos != -1) { - var extendedValue = true; - while (extendedValue) { - if (line[pos + 1] == multiValue && line[pos + 2] == '"') { - pos = helpers.unescapedIndexOf(line, '"', pos + 3); - } else { - extendedValue = false; - } - } - } - if (pos === -1) { - throw new ParserError('invalid line (no matching double quote) "' + line + '"'); - } - value = line.substr(valuePos, pos - valuePos); - lastParam = helpers.unescapedIndexOf(line, PARAM_DELIMITER, pos); - if (lastParam === -1) { - pos = false; - } - } else { - valuePos = pos + 1; - var nextPos = helpers.unescapedIndexOf(line, PARAM_DELIMITER, valuePos); - var propValuePos = helpers.unescapedIndexOf(line, VALUE_DELIMITER, valuePos); - if (propValuePos !== -1 && nextPos > propValuePos) { - nextPos = propValuePos; - pos = false; - } else if (nextPos === -1) { - if (propValuePos === -1) { - nextPos = line.length; - } else { - nextPos = propValuePos; - } - pos = false; - } else { - lastParam = nextPos; - pos = nextPos; - } - value = line.substr(valuePos, nextPos - valuePos); - } - value = parser._rfc6868Escape(value); - if (multiValue) { - var delimiter = mvdelim || multiValue; - value = parser._parseMultiValue(value, delimiter, type, [], null, designSet); - } else { - value = parser._parseValue(value, type, designSet); - } - if (multiValue && lcname in result) { - if (Array.isArray(result[lcname])) { - result[lcname].push(value); - } else { - result[lcname] = [ - result[lcname], - value - ]; - } - } else { - result[lcname] = value; - } - } - return [result, value, valuePos]; - }; - parser._rfc6868Escape = function(val) { - return val.replace(/\^['n^]/g, function(x3) { - return RFC6868_REPLACE_MAP[x3]; - }); - }; - var RFC6868_REPLACE_MAP = { "^'": '"', "^n": "\n", "^^": "^" }; - parser._parseMultiValue = function(buffer, delim, type, result, innerMulti, designSet, structuredValue) { - var pos = 0; - var lastPos = 0; - var value; - if (delim.length === 0) { - return buffer; - } - while ((pos = helpers.unescapedIndexOf(buffer, delim, lastPos)) !== -1) { - value = buffer.substr(lastPos, pos - lastPos); - if (innerMulti) { - value = parser._parseMultiValue(value, innerMulti, type, [], null, designSet, structuredValue); - } else { - value = parser._parseValue(value, type, designSet, structuredValue); - } - result.push(value); - lastPos = pos + delim.length; - } - value = buffer.substr(lastPos); - if (innerMulti) { - value = parser._parseMultiValue(value, innerMulti, type, [], null, designSet, structuredValue); - } else { - value = parser._parseValue(value, type, designSet, structuredValue); - } - result.push(value); - return result.length == 1 ? result[0] : result; - }; - parser._eachLine = function(buffer, callback) { - var len = buffer.length; - var lastPos = buffer.search(CHAR); - var pos = lastPos; - var line; - var firstChar; - var newlineOffset; - do { - pos = buffer.indexOf("\n", lastPos) + 1; - if (pos > 1 && buffer[pos - 2] === "\r") { - newlineOffset = 2; - } else { - newlineOffset = 1; - } - if (pos === 0) { - pos = len; - newlineOffset = 0; - } - firstChar = buffer[lastPos]; - if (firstChar === " " || firstChar === " ") { - line += buffer.substr(lastPos + 1, pos - lastPos - (newlineOffset + 1)); - } else { - if (line) - callback(null, line); - line = buffer.substr(lastPos, pos - lastPos - newlineOffset); - } - lastPos = pos; - } while (pos !== len); - line = line.trim(); - if (line.length) - callback(null, line); - }; - return parser; - }(); - ICAL3.Component = function() { - "use strict"; - var PROPERTY_INDEX = 1; - var COMPONENT_INDEX = 2; - var NAME_INDEX = 0; - function Component5(jCal, parent) { - if (typeof jCal === "string") { - jCal = [jCal, [], []]; - } - this.jCal = jCal; - this.parent = parent || null; - } - Component5.prototype = { - _hydratedPropertyCount: 0, - _hydratedComponentCount: 0, - get name() { - return this.jCal[NAME_INDEX]; - }, - get _designSet() { - var parentDesign = this.parent && this.parent._designSet; - return parentDesign || ICAL3.design.getDesignSet(this.name); - }, - _hydrateComponent: function(index) { - if (!this._components) { - this._components = []; - this._hydratedComponentCount = 0; - } - if (this._components[index]) { - return this._components[index]; - } - var comp = new Component5(this.jCal[COMPONENT_INDEX][index], this); - this._hydratedComponentCount++; - return this._components[index] = comp; - }, - _hydrateProperty: function(index) { - if (!this._properties) { - this._properties = []; - this._hydratedPropertyCount = 0; - } - if (this._properties[index]) { - return this._properties[index]; - } - var prop = new ICAL3.Property(this.jCal[PROPERTY_INDEX][index], this); - this._hydratedPropertyCount++; - return this._properties[index] = prop; - }, - getFirstSubcomponent: function(name) { - if (name) { - var i3 = 0; - var comps = this.jCal[COMPONENT_INDEX]; - var len = comps.length; - for (; i3 < len; i3++) { - if (comps[i3][NAME_INDEX] === name) { - var result = this._hydrateComponent(i3); - return result; - } - } - } else { - if (this.jCal[COMPONENT_INDEX].length) { - return this._hydrateComponent(0); - } - } - return null; - }, - getAllSubcomponents: function(name) { - var jCalLen = this.jCal[COMPONENT_INDEX].length; - var i3 = 0; - if (name) { - var comps = this.jCal[COMPONENT_INDEX]; - var result = []; - for (; i3 < jCalLen; i3++) { - if (name === comps[i3][NAME_INDEX]) { - result.push(this._hydrateComponent(i3)); - } - } - return result; - } else { - if (!this._components || this._hydratedComponentCount !== jCalLen) { - for (; i3 < jCalLen; i3++) { - this._hydrateComponent(i3); - } - } - return this._components || []; - } - }, - hasProperty: function(name) { - var props = this.jCal[PROPERTY_INDEX]; - var len = props.length; - var i3 = 0; - for (; i3 < len; i3++) { - if (props[i3][NAME_INDEX] === name) { - return true; - } - } - return false; - }, - getFirstProperty: function(name) { - if (name) { - var i3 = 0; - var props = this.jCal[PROPERTY_INDEX]; - var len = props.length; - for (; i3 < len; i3++) { - if (props[i3][NAME_INDEX] === name) { - var result = this._hydrateProperty(i3); - return result; - } - } - } else { - if (this.jCal[PROPERTY_INDEX].length) { - return this._hydrateProperty(0); - } - } - return null; - }, - getFirstPropertyValue: function(name) { - var prop = this.getFirstProperty(name); - if (prop) { - return prop.getFirstValue(); - } - return null; - }, - getAllProperties: function(name) { - var jCalLen = this.jCal[PROPERTY_INDEX].length; - var i3 = 0; - if (name) { - var props = this.jCal[PROPERTY_INDEX]; - var result = []; - for (; i3 < jCalLen; i3++) { - if (name === props[i3][NAME_INDEX]) { - result.push(this._hydrateProperty(i3)); - } - } - return result; - } else { - if (!this._properties || this._hydratedPropertyCount !== jCalLen) { - for (; i3 < jCalLen; i3++) { - this._hydrateProperty(i3); - } - } - return this._properties || []; - } - }, - _removeObjectByIndex: function(jCalIndex, cache, index) { - cache = cache || []; - if (cache[index]) { - var obj = cache[index]; - if ("parent" in obj) { - obj.parent = null; - } - } - cache.splice(index, 1); - this.jCal[jCalIndex].splice(index, 1); - }, - _removeObject: function(jCalIndex, cache, nameOrObject) { - var i3 = 0; - var objects = this.jCal[jCalIndex]; - var len = objects.length; - var cached = this[cache]; - if (typeof nameOrObject === "string") { - for (; i3 < len; i3++) { - if (objects[i3][NAME_INDEX] === nameOrObject) { - this._removeObjectByIndex(jCalIndex, cached, i3); - return true; - } - } - } else if (cached) { - for (; i3 < len; i3++) { - if (cached[i3] && cached[i3] === nameOrObject) { - this._removeObjectByIndex(jCalIndex, cached, i3); - return true; - } - } - } - return false; - }, - _removeAllObjects: function(jCalIndex, cache, name) { - var cached = this[cache]; - var objects = this.jCal[jCalIndex]; - var i3 = objects.length - 1; - for (; i3 >= 0; i3--) { - if (!name || objects[i3][NAME_INDEX] === name) { - this._removeObjectByIndex(jCalIndex, cached, i3); - } - } - }, - addSubcomponent: function(component) { - if (!this._components) { - this._components = []; - this._hydratedComponentCount = 0; - } - if (component.parent) { - component.parent.removeSubcomponent(component); - } - var idx = this.jCal[COMPONENT_INDEX].push(component.jCal); - this._components[idx - 1] = component; - this._hydratedComponentCount++; - component.parent = this; - return component; - }, - removeSubcomponent: function(nameOrComp) { - var removed = this._removeObject(COMPONENT_INDEX, "_components", nameOrComp); - if (removed) { - this._hydratedComponentCount--; - } - return removed; - }, - removeAllSubcomponents: function(name) { - var removed = this._removeAllObjects(COMPONENT_INDEX, "_components", name); - this._hydratedComponentCount = 0; - return removed; - }, - addProperty: function(property) { - if (!(property instanceof ICAL3.Property)) { - throw new TypeError("must instance of ICAL.Property"); - } - if (!this._properties) { - this._properties = []; - this._hydratedPropertyCount = 0; - } - if (property.parent) { - property.parent.removeProperty(property); - } - var idx = this.jCal[PROPERTY_INDEX].push(property.jCal); - this._properties[idx - 1] = property; - this._hydratedPropertyCount++; - property.parent = this; - return property; - }, - addPropertyWithValue: function(name, value) { - var prop = new ICAL3.Property(name); - prop.setValue(value); - this.addProperty(prop); - return prop; - }, - updatePropertyWithValue: function(name, value) { - var prop = this.getFirstProperty(name); - if (prop) { - prop.setValue(value); - } else { - prop = this.addPropertyWithValue(name, value); - } - return prop; - }, - removeProperty: function(nameOrProp) { - var removed = this._removeObject(PROPERTY_INDEX, "_properties", nameOrProp); - if (removed) { - this._hydratedPropertyCount--; - } - return removed; - }, - removeAllProperties: function(name) { - var removed = this._removeAllObjects(PROPERTY_INDEX, "_properties", name); - this._hydratedPropertyCount = 0; - return removed; - }, - toJSON: function() { - return this.jCal; - }, - toString: function() { - return ICAL3.stringify.component(this.jCal, this._designSet); - } - }; - Component5.fromString = function(str) { - return new Component5(ICAL3.parse.component(str)); - }; - return Component5; - }(); - ICAL3.Property = function() { - "use strict"; - var NAME_INDEX = 0; - var PROP_INDEX = 1; - var TYPE_INDEX = 2; - var VALUE_INDEX = 3; - var design = ICAL3.design; - function Property(jCal, parent) { - this._parent = parent || null; - if (typeof jCal === "string") { - this.jCal = [jCal, {}, design.defaultType]; - this.jCal[TYPE_INDEX] = this.getDefaultType(); - } else { - this.jCal = jCal; - } - this._updateType(); - } - Property.prototype = { - get type() { - return this.jCal[TYPE_INDEX]; - }, - get name() { - return this.jCal[NAME_INDEX]; - }, - get parent() { - return this._parent; - }, - set parent(p3) { - var designSetChanged = !this._parent || p3 && p3._designSet != this._parent._designSet; - this._parent = p3; - if (this.type == design.defaultType && designSetChanged) { - this.jCal[TYPE_INDEX] = this.getDefaultType(); - this._updateType(); - } - return p3; - }, - get _designSet() { - return this.parent ? this.parent._designSet : design.defaultSet; - }, - _updateType: function() { - var designSet = this._designSet; - if (this.type in designSet.value) { - var designType = designSet.value[this.type]; - if ("decorate" in designSet.value[this.type]) { - this.isDecorated = true; - } else { - this.isDecorated = false; - } - if (this.name in designSet.property) { - this.isMultiValue = "multiValue" in designSet.property[this.name]; - this.isStructuredValue = "structuredValue" in designSet.property[this.name]; - } - } - }, - _hydrateValue: function(index) { - if (this._values && this._values[index]) { - return this._values[index]; - } - if (this.jCal.length <= VALUE_INDEX + index) { - return null; - } - if (this.isDecorated) { - if (!this._values) { - this._values = []; - } - return this._values[index] = this._decorate(this.jCal[VALUE_INDEX + index]); - } else { - return this.jCal[VALUE_INDEX + index]; - } - }, - _decorate: function(value) { - return this._designSet.value[this.type].decorate(value, this); - }, - _undecorate: function(value) { - return this._designSet.value[this.type].undecorate(value, this); - }, - _setDecoratedValue: function(value, index) { - if (!this._values) { - this._values = []; - } - if (typeof value === "object" && "icaltype" in value) { - this.jCal[VALUE_INDEX + index] = this._undecorate(value); - this._values[index] = value; - } else { - this.jCal[VALUE_INDEX + index] = value; - this._values[index] = this._decorate(value); - } - }, - getParameter: function(name) { - if (name in this.jCal[PROP_INDEX]) { - return this.jCal[PROP_INDEX][name]; - } else { - return void 0; - } - }, - getFirstParameter: function(name) { - var parameters = this.getParameter(name); - if (Array.isArray(parameters)) { - return parameters[0]; - } - return parameters; - }, - setParameter: function(name, value) { - var lcname = name.toLowerCase(); - if (typeof value === "string" && lcname in this._designSet.param && "multiValue" in this._designSet.param[lcname]) { - value = [value]; - } - this.jCal[PROP_INDEX][name] = value; - }, - removeParameter: function(name) { - delete this.jCal[PROP_INDEX][name]; - }, - getDefaultType: function() { - var name = this.jCal[NAME_INDEX]; - var designSet = this._designSet; - if (name in designSet.property) { - var details = designSet.property[name]; - if ("defaultType" in details) { - return details.defaultType; - } - } - return design.defaultType; - }, - resetType: function(type) { - this.removeAllValues(); - this.jCal[TYPE_INDEX] = type; - this._updateType(); - }, - getFirstValue: function() { - return this._hydrateValue(0); - }, - getValues: function() { - var len = this.jCal.length - VALUE_INDEX; - if (len < 1) { - return []; - } - var i3 = 0; - var result = []; - for (; i3 < len; i3++) { - result[i3] = this._hydrateValue(i3); - } - return result; - }, - removeAllValues: function() { - if (this._values) { - this._values.length = 0; - } - this.jCal.length = 3; - }, - setValues: function(values) { - if (!this.isMultiValue) { - throw new Error(this.name + ": does not not support mulitValue.\noverride isMultiValue"); - } - var len = values.length; - var i3 = 0; - this.removeAllValues(); - if (len > 0 && typeof values[0] === "object" && "icaltype" in values[0]) { - this.resetType(values[0].icaltype); - } - if (this.isDecorated) { - for (; i3 < len; i3++) { - this._setDecoratedValue(values[i3], i3); - } - } else { - for (; i3 < len; i3++) { - this.jCal[VALUE_INDEX + i3] = values[i3]; - } - } - }, - setValue: function(value) { - this.removeAllValues(); - if (typeof value === "object" && "icaltype" in value) { - this.resetType(value.icaltype); - } - if (this.isDecorated) { - this._setDecoratedValue(value, 0); - } else { - this.jCal[VALUE_INDEX] = value; - } - }, - toJSON: function() { - return this.jCal; - }, - toICALString: function() { - return ICAL3.stringify.property(this.jCal, this._designSet, true); - } - }; - Property.fromString = function(str, designSet) { - return new Property(ICAL3.parse.property(str, designSet)); - }; - return Property; - }(); - ICAL3.UtcOffset = function() { - function UtcOffset(aData) { - this.fromData(aData); - } - UtcOffset.prototype = { - hours: 0, - minutes: 0, - factor: 1, - icaltype: "utc-offset", - clone: function() { - return ICAL3.UtcOffset.fromSeconds(this.toSeconds()); - }, - fromData: function(aData) { - if (aData) { - for (var key in aData) { - if (aData.hasOwnProperty(key)) { - this[key] = aData[key]; - } - } - } - this._normalize(); - }, - fromSeconds: function(aSeconds) { - var secs = Math.abs(aSeconds); - this.factor = aSeconds < 0 ? -1 : 1; - this.hours = ICAL3.helpers.trunc(secs / 3600); - secs -= this.hours * 3600; - this.minutes = ICAL3.helpers.trunc(secs / 60); - return this; - }, - toSeconds: function() { - return this.factor * (60 * this.minutes + 3600 * this.hours); - }, - compare: function icaltime_compare(other) { - var a3 = this.toSeconds(); - var b3 = other.toSeconds(); - return (a3 > b3) - (b3 > a3); - }, - _normalize: function() { - var secs = this.toSeconds(); - var factor = this.factor; - while (secs < -43200) { - secs += 97200; - } - while (secs > 50400) { - secs -= 97200; - } - this.fromSeconds(secs); - if (secs == 0) { - this.factor = factor; - } - }, - toICALString: function() { - return ICAL3.design.icalendar.value["utc-offset"].toICAL(this.toString()); - }, - toString: function toString() { - return (this.factor == 1 ? "+" : "-") + ICAL3.helpers.pad2(this.hours) + ":" + ICAL3.helpers.pad2(this.minutes); - } - }; - UtcOffset.fromString = function(aString) { - var options = {}; - options.factor = aString[0] === "+" ? 1 : -1; - options.hours = ICAL3.helpers.strictParseInt(aString.substr(1, 2)); - options.minutes = ICAL3.helpers.strictParseInt(aString.substr(4, 2)); - return new ICAL3.UtcOffset(options); - }; - UtcOffset.fromSeconds = function(aSeconds) { - var instance = new UtcOffset(); - instance.fromSeconds(aSeconds); - return instance; - }; - return UtcOffset; - }(); - ICAL3.Binary = function() { - function Binary(aValue) { - this.value = aValue; - } - Binary.prototype = { - icaltype: "binary", - decodeValue: function decodeValue() { - return this._b64_decode(this.value); - }, - setEncodedValue: function setEncodedValue(aValue) { - this.value = this._b64_encode(aValue); - }, - _b64_encode: function base64_encode(data) { - var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var o1, o2, o3, h1, h22, h3, h4, bits, i3 = 0, ac = 0, enc = "", tmp_arr = []; - if (!data) { - return data; - } - do { - o1 = data.charCodeAt(i3++); - o2 = data.charCodeAt(i3++); - o3 = data.charCodeAt(i3++); - bits = o1 << 16 | o2 << 8 | o3; - h1 = bits >> 18 & 63; - h22 = bits >> 12 & 63; - h3 = bits >> 6 & 63; - h4 = bits & 63; - tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h22) + b64.charAt(h3) + b64.charAt(h4); - } while (i3 < data.length); - enc = tmp_arr.join(""); - var r3 = data.length % 3; - return (r3 ? enc.slice(0, r3 - 3) : enc) + "===".slice(r3 || 3); - }, - _b64_decode: function base64_decode(data) { - var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var o1, o2, o3, h1, h22, h3, h4, bits, i3 = 0, ac = 0, dec = "", tmp_arr = []; - if (!data) { - return data; - } - data += ""; - do { - h1 = b64.indexOf(data.charAt(i3++)); - h22 = b64.indexOf(data.charAt(i3++)); - h3 = b64.indexOf(data.charAt(i3++)); - h4 = b64.indexOf(data.charAt(i3++)); - bits = h1 << 18 | h22 << 12 | h3 << 6 | h4; - o1 = bits >> 16 & 255; - o2 = bits >> 8 & 255; - o3 = bits & 255; - if (h3 == 64) { - tmp_arr[ac++] = String.fromCharCode(o1); - } else if (h4 == 64) { - tmp_arr[ac++] = String.fromCharCode(o1, o2); - } else { - tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); - } - } while (i3 < data.length); - dec = tmp_arr.join(""); - return dec; - }, - toString: function() { - return this.value; - } - }; - Binary.fromString = function(aString) { - return new Binary(aString); - }; - return Binary; - }(); - (function() { - ICAL3.Period = function icalperiod(aData) { - this.wrappedJSObject = this; - if (aData && "start" in aData) { - if (aData.start && !(aData.start instanceof ICAL3.Time)) { - throw new TypeError(".start must be an instance of ICAL.Time"); - } - this.start = aData.start; - } - if (aData && aData.end && aData.duration) { - throw new Error("cannot accept both end and duration"); - } - if (aData && "end" in aData) { - if (aData.end && !(aData.end instanceof ICAL3.Time)) { - throw new TypeError(".end must be an instance of ICAL.Time"); - } - this.end = aData.end; - } - if (aData && "duration" in aData) { - if (aData.duration && !(aData.duration instanceof ICAL3.Duration)) { - throw new TypeError(".duration must be an instance of ICAL.Duration"); - } - this.duration = aData.duration; - } - }; - ICAL3.Period.prototype = { - start: null, - end: null, - duration: null, - icalclass: "icalperiod", - icaltype: "period", - clone: function() { - return ICAL3.Period.fromData({ - start: this.start ? this.start.clone() : null, - end: this.end ? this.end.clone() : null, - duration: this.duration ? this.duration.clone() : null - }); - }, - getDuration: function duration() { - if (this.duration) { - return this.duration; - } else { - return this.end.subtractDate(this.start); - } - }, - getEnd: function() { - if (this.end) { - return this.end; - } else { - var end = this.start.clone(); - end.addDuration(this.duration); - return end; - } - }, - toString: function toString() { - return this.start + "/" + (this.end || this.duration); - }, - toJSON: function() { - return [this.start.toString(), (this.end || this.duration).toString()]; - }, - toICALString: function() { - return this.start.toICALString() + "/" + (this.end || this.duration).toICALString(); - } - }; - ICAL3.Period.fromString = function fromString(str, prop) { - var parts = str.split("/"); - if (parts.length !== 2) { - throw new Error('Invalid string value: "' + str + '" must contain a "/" char.'); - } - var options = { - start: ICAL3.Time.fromDateTimeString(parts[0], prop) - }; - var end = parts[1]; - if (ICAL3.Duration.isValueString(end)) { - options.duration = ICAL3.Duration.fromString(end); - } else { - options.end = ICAL3.Time.fromDateTimeString(end, prop); - } - return new ICAL3.Period(options); - }; - ICAL3.Period.fromData = function fromData(aData) { - return new ICAL3.Period(aData); - }; - ICAL3.Period.fromJSON = function(aData, aProp, aLenient) { - function fromDateOrDateTimeString(aValue, aProp2) { - if (aLenient) { - return ICAL3.Time.fromString(aValue, aProp2); - } else { - return ICAL3.Time.fromDateTimeString(aValue, aProp2); - } - } - if (ICAL3.Duration.isValueString(aData[1])) { - return ICAL3.Period.fromData({ - start: fromDateOrDateTimeString(aData[0], aProp), - duration: ICAL3.Duration.fromString(aData[1]) - }); - } else { - return ICAL3.Period.fromData({ - start: fromDateOrDateTimeString(aData[0], aProp), - end: fromDateOrDateTimeString(aData[1], aProp) - }); - } - }; - })(); - (function() { - var DURATION_LETTERS = /([PDWHMTS]{1,1})/; - ICAL3.Duration = function icalduration(data) { - this.wrappedJSObject = this; - this.fromData(data); - }; - ICAL3.Duration.prototype = { - weeks: 0, - days: 0, - hours: 0, - minutes: 0, - seconds: 0, - isNegative: false, - icalclass: "icalduration", - icaltype: "duration", - clone: function clone() { - return ICAL3.Duration.fromData(this); - }, - toSeconds: function toSeconds() { - var seconds = this.seconds + 60 * this.minutes + 3600 * this.hours + 86400 * this.days + 7 * 86400 * this.weeks; - return this.isNegative ? -seconds : seconds; - }, - fromSeconds: function fromSeconds(aSeconds) { - var secs = Math.abs(aSeconds); - this.isNegative = aSeconds < 0; - this.days = ICAL3.helpers.trunc(secs / 86400); - if (this.days % 7 == 0) { - this.weeks = this.days / 7; - this.days = 0; - } else { - this.weeks = 0; - } - secs -= (this.days + 7 * this.weeks) * 86400; - this.hours = ICAL3.helpers.trunc(secs / 3600); - secs -= this.hours * 3600; - this.minutes = ICAL3.helpers.trunc(secs / 60); - secs -= this.minutes * 60; - this.seconds = secs; - return this; - }, - fromData: function fromData(aData) { - var propsToCopy = [ - "weeks", - "days", - "hours", - "minutes", - "seconds", - "isNegative" - ]; - for (var key in propsToCopy) { - if (!propsToCopy.hasOwnProperty(key)) { - continue; - } - var prop = propsToCopy[key]; - if (aData && prop in aData) { - this[prop] = aData[prop]; - } else { - this[prop] = 0; - } - } - }, - reset: function reset() { - this.isNegative = false; - this.weeks = 0; - this.days = 0; - this.hours = 0; - this.minutes = 0; - this.seconds = 0; - }, - compare: function compare(aOther) { - var thisSeconds = this.toSeconds(); - var otherSeconds = aOther.toSeconds(); - return (thisSeconds > otherSeconds) - (thisSeconds < otherSeconds); - }, - normalize: function normalize() { - this.fromSeconds(this.toSeconds()); - }, - toString: function toString() { - if (this.toSeconds() == 0) { - return "PT0S"; - } else { - var str = ""; - if (this.isNegative) - str += "-"; - str += "P"; - if (this.weeks) - str += this.weeks + "W"; - if (this.days) - str += this.days + "D"; - if (this.hours || this.minutes || this.seconds) { - str += "T"; - if (this.hours) - str += this.hours + "H"; - if (this.minutes) - str += this.minutes + "M"; - if (this.seconds) - str += this.seconds + "S"; - } - return str; - } - }, - toICALString: function() { - return this.toString(); - } - }; - ICAL3.Duration.fromSeconds = function icalduration_from_seconds(aSeconds) { - return new ICAL3.Duration().fromSeconds(aSeconds); - }; - function parseDurationChunk(letter, number, object) { - var type; - switch (letter) { - case "P": - if (number && number === "-") { - object.isNegative = true; - } else { - object.isNegative = false; - } - break; - case "D": - type = "days"; - break; - case "W": - type = "weeks"; - break; - case "H": - type = "hours"; - break; - case "M": - type = "minutes"; - break; - case "S": - type = "seconds"; - break; - default: - return 0; - } - if (type) { - if (!number && number !== 0) { - throw new Error('invalid duration value: Missing number before "' + letter + '"'); - } - var num = parseInt(number, 10); - if (ICAL3.helpers.isStrictlyNaN(num)) { - throw new Error('invalid duration value: Invalid number "' + number + '" before "' + letter + '"'); - } - object[type] = num; - } - return 1; - } - ICAL3.Duration.isValueString = function(string) { - return string[0] === "P" || string[1] === "P"; - }; - ICAL3.Duration.fromString = function icalduration_from_string(aStr) { - var pos = 0; - var dict = Object.create(null); - var chunks = 0; - while ((pos = aStr.search(DURATION_LETTERS)) !== -1) { - var type = aStr[pos]; - var numeric = aStr.substr(0, pos); - aStr = aStr.substr(pos + 1); - chunks += parseDurationChunk(type, numeric, dict); - } - if (chunks < 2) { - throw new Error('invalid duration value: Not enough duration components in "' + aStr + '"'); - } - return new ICAL3.Duration(dict); - }; - ICAL3.Duration.fromData = function icalduration_from_data(aData) { - return new ICAL3.Duration(aData); - }; - })(); - (function() { - var OPTIONS = [ - "tzid", - "location", - "tznames", - "latitude", - "longitude" - ]; - ICAL3.Timezone = function icaltimezone(data) { - this.wrappedJSObject = this; - this.fromData(data); - }; - ICAL3.Timezone.prototype = { - tzid: "", - location: "", - tznames: "", - latitude: 0, - longitude: 0, - component: null, - expandedUntilYear: 0, - icalclass: "icaltimezone", - fromData: function fromData(aData) { - this.expandedUntilYear = 0; - this.changes = []; - if (aData instanceof ICAL3.Component) { - this.component = aData; - } else { - if (aData && "component" in aData) { - if (typeof aData.component == "string") { - var jCal = ICAL3.parse(aData.component); - this.component = new ICAL3.Component(jCal); - } else if (aData.component instanceof ICAL3.Component) { - this.component = aData.component; - } else { - this.component = null; - } - } - for (var key in OPTIONS) { - if (OPTIONS.hasOwnProperty(key)) { - var prop = OPTIONS[key]; - if (aData && prop in aData) { - this[prop] = aData[prop]; - } - } - } - } - if (this.component instanceof ICAL3.Component && !this.tzid) { - this.tzid = this.component.getFirstPropertyValue("tzid"); - } - return this; - }, - utcOffset: function utcOffset(tt) { - if (this == ICAL3.Timezone.utcTimezone || this == ICAL3.Timezone.localTimezone) { - return 0; - } - this._ensureCoverage(tt.year); - if (!this.changes.length) { - return 0; - } - var tt_change = { - year: tt.year, - month: tt.month, - day: tt.day, - hour: tt.hour, - minute: tt.minute, - second: tt.second - }; - var change_num = this._findNearbyChange(tt_change); - var change_num_to_use = -1; - var step = 1; - for (; ; ) { - var change = ICAL3.helpers.clone(this.changes[change_num], true); - if (change.utcOffset < change.prevUtcOffset) { - ICAL3.Timezone.adjust_change(change, 0, 0, 0, change.utcOffset); - } else { - ICAL3.Timezone.adjust_change(change, 0, 0, 0, change.prevUtcOffset); - } - var cmp = ICAL3.Timezone._compare_change_fn(tt_change, change); - if (cmp >= 0) { - change_num_to_use = change_num; - } else { - step = -1; - } - if (step == -1 && change_num_to_use != -1) { - break; - } - change_num += step; - if (change_num < 0) { - return 0; - } - if (change_num >= this.changes.length) { - break; - } - } - var zone_change = this.changes[change_num_to_use]; - var utcOffset_change = zone_change.utcOffset - zone_change.prevUtcOffset; - if (utcOffset_change < 0 && change_num_to_use > 0) { - var tmp_change = ICAL3.helpers.clone(zone_change, true); - ICAL3.Timezone.adjust_change(tmp_change, 0, 0, 0, tmp_change.prevUtcOffset); - if (ICAL3.Timezone._compare_change_fn(tt_change, tmp_change) < 0) { - var prev_zone_change = this.changes[change_num_to_use - 1]; - var want_daylight = false; - if (zone_change.is_daylight != want_daylight && prev_zone_change.is_daylight == want_daylight) { - zone_change = prev_zone_change; - } - } - } - return zone_change.utcOffset; - }, - _findNearbyChange: function icaltimezone_find_nearby_change(change) { - var idx = ICAL3.helpers.binsearchInsert(this.changes, change, ICAL3.Timezone._compare_change_fn); - if (idx >= this.changes.length) { - return this.changes.length - 1; - } - return idx; - }, - _ensureCoverage: function(aYear) { - if (ICAL3.Timezone._minimumExpansionYear == -1) { - var today = ICAL3.Time.now(); - ICAL3.Timezone._minimumExpansionYear = today.year; - } - var changesEndYear = aYear; - if (changesEndYear < ICAL3.Timezone._minimumExpansionYear) { - changesEndYear = ICAL3.Timezone._minimumExpansionYear; - } - changesEndYear += ICAL3.Timezone.EXTRA_COVERAGE; - if (changesEndYear > ICAL3.Timezone.MAX_YEAR) { - changesEndYear = ICAL3.Timezone.MAX_YEAR; - } - if (!this.changes.length || this.expandedUntilYear < aYear) { - var subcomps = this.component.getAllSubcomponents(); - var compLen = subcomps.length; - var compIdx = 0; - for (; compIdx < compLen; compIdx++) { - this._expandComponent(subcomps[compIdx], changesEndYear, this.changes); - } - this.changes.sort(ICAL3.Timezone._compare_change_fn); - this.expandedUntilYear = changesEndYear; - } - }, - _expandComponent: function(aComponent, aYear, changes) { - if (!aComponent.hasProperty("dtstart") || !aComponent.hasProperty("tzoffsetto") || !aComponent.hasProperty("tzoffsetfrom")) { - return null; - } - var dtstart = aComponent.getFirstProperty("dtstart").getFirstValue(); - var change; - function convert_tzoffset(offset) { - return offset.factor * (offset.hours * 3600 + offset.minutes * 60); - } - function init_changes() { - var changebase = {}; - changebase.is_daylight = aComponent.name == "daylight"; - changebase.utcOffset = convert_tzoffset(aComponent.getFirstProperty("tzoffsetto").getFirstValue()); - changebase.prevUtcOffset = convert_tzoffset(aComponent.getFirstProperty("tzoffsetfrom").getFirstValue()); - return changebase; - } - if (!aComponent.hasProperty("rrule") && !aComponent.hasProperty("rdate")) { - change = init_changes(); - change.year = dtstart.year; - change.month = dtstart.month; - change.day = dtstart.day; - change.hour = dtstart.hour; - change.minute = dtstart.minute; - change.second = dtstart.second; - ICAL3.Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); - changes.push(change); - } else { - var props = aComponent.getAllProperties("rdate"); - for (var rdatekey in props) { - if (!props.hasOwnProperty(rdatekey)) { - continue; - } - var rdate = props[rdatekey]; - var time = rdate.getFirstValue(); - change = init_changes(); - change.year = time.year; - change.month = time.month; - change.day = time.day; - if (time.isDate) { - change.hour = dtstart.hour; - change.minute = dtstart.minute; - change.second = dtstart.second; - if (dtstart.zone != ICAL3.Timezone.utcTimezone) { - ICAL3.Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); - } - } else { - change.hour = time.hour; - change.minute = time.minute; - change.second = time.second; - if (time.zone != ICAL3.Timezone.utcTimezone) { - ICAL3.Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); - } - } - changes.push(change); - } - var rrule = aComponent.getFirstProperty("rrule"); - if (rrule) { - rrule = rrule.getFirstValue(); - change = init_changes(); - if (rrule.until && rrule.until.zone == ICAL3.Timezone.utcTimezone) { - rrule.until.adjust(0, 0, 0, change.prevUtcOffset); - rrule.until.zone = ICAL3.Timezone.localTimezone; - } - var iterator = rrule.iterator(dtstart); - var occ; - while (occ = iterator.next()) { - change = init_changes(); - if (occ.year > aYear || !occ) { - break; - } - change.year = occ.year; - change.month = occ.month; - change.day = occ.day; - change.hour = occ.hour; - change.minute = occ.minute; - change.second = occ.second; - change.isDate = occ.isDate; - ICAL3.Timezone.adjust_change(change, 0, 0, 0, -change.prevUtcOffset); - changes.push(change); - } - } - } - return changes; - }, - toString: function toString() { - return this.tznames ? this.tznames : this.tzid; - } - }; - ICAL3.Timezone._compare_change_fn = function icaltimezone_compare_change_fn(a3, b3) { - if (a3.year < b3.year) - return -1; - else if (a3.year > b3.year) - return 1; - if (a3.month < b3.month) - return -1; - else if (a3.month > b3.month) - return 1; - if (a3.day < b3.day) - return -1; - else if (a3.day > b3.day) - return 1; - if (a3.hour < b3.hour) - return -1; - else if (a3.hour > b3.hour) - return 1; - if (a3.minute < b3.minute) - return -1; - else if (a3.minute > b3.minute) - return 1; - if (a3.second < b3.second) - return -1; - else if (a3.second > b3.second) - return 1; - return 0; - }; - ICAL3.Timezone.convert_time = function icaltimezone_convert_time(tt, from_zone, to_zone) { - if (tt.isDate || from_zone.tzid == to_zone.tzid || from_zone == ICAL3.Timezone.localTimezone || to_zone == ICAL3.Timezone.localTimezone) { - tt.zone = to_zone; - return tt; - } - var utcOffset = from_zone.utcOffset(tt); - tt.adjust(0, 0, 0, -utcOffset); - utcOffset = to_zone.utcOffset(tt); - tt.adjust(0, 0, 0, utcOffset); - return null; - }; - ICAL3.Timezone.fromData = function icaltimezone_fromData(aData) { - var tt = new ICAL3.Timezone(); - return tt.fromData(aData); - }; - ICAL3.Timezone.utcTimezone = ICAL3.Timezone.fromData({ - tzid: "UTC" - }); - ICAL3.Timezone.localTimezone = ICAL3.Timezone.fromData({ - tzid: "floating" - }); - ICAL3.Timezone.adjust_change = function icaltimezone_adjust_change(change, days, hours, minutes, seconds) { - return ICAL3.Time.prototype.adjust.call(change, days, hours, minutes, seconds, change); - }; - ICAL3.Timezone._minimumExpansionYear = -1; - ICAL3.Timezone.MAX_YEAR = 2035; - ICAL3.Timezone.EXTRA_COVERAGE = 5; - })(); - ICAL3.TimezoneService = function() { - var zones; - var TimezoneService = { - get count() { - return Object.keys(zones).length; - }, - reset: function() { - zones = Object.create(null); - var utc = ICAL3.Timezone.utcTimezone; - zones.Z = utc; - zones.UTC = utc; - zones.GMT = utc; - }, - has: function(tzid) { - return !!zones[tzid]; - }, - get: function(tzid) { - return zones[tzid]; - }, - register: function(name, timezone) { - if (name instanceof ICAL3.Component) { - if (name.name === "vtimezone") { - timezone = new ICAL3.Timezone(name); - name = timezone.tzid; - } - } - if (timezone instanceof ICAL3.Timezone) { - zones[name] = timezone; - } else { - throw new TypeError("timezone must be ICAL.Timezone or ICAL.Component"); - } - }, - remove: function(tzid) { - return delete zones[tzid]; - } - }; - TimezoneService.reset(); - return TimezoneService; - }(); - (function() { - ICAL3.Time = function icaltime(data, zone) { - this.wrappedJSObject = this; - var time = this._time = Object.create(null); - time.year = 0; - time.month = 1; - time.day = 1; - time.hour = 0; - time.minute = 0; - time.second = 0; - time.isDate = false; - this.fromData(data, zone); - }; - ICAL3.Time._dowCache = {}; - ICAL3.Time._wnCache = {}; - ICAL3.Time.prototype = { - icalclass: "icaltime", - _cachedUnixTime: null, - get icaltype() { - return this.isDate ? "date" : "date-time"; - }, - zone: null, - _pendingNormalization: false, - clone: function() { - return new ICAL3.Time(this._time, this.zone); - }, - reset: function icaltime_reset() { - this.fromData(ICAL3.Time.epochTime); - this.zone = ICAL3.Timezone.utcTimezone; - }, - resetTo: function icaltime_resetTo(year, month, day, hour, minute, second, timezone) { - this.fromData({ - year, - month, - day, - hour, - minute, - second, - zone: timezone - }); - }, - fromJSDate: function icaltime_fromJSDate(aDate, useUTC) { - if (!aDate) { - this.reset(); - } else { - if (useUTC) { - this.zone = ICAL3.Timezone.utcTimezone; - this.year = aDate.getUTCFullYear(); - this.month = aDate.getUTCMonth() + 1; - this.day = aDate.getUTCDate(); - this.hour = aDate.getUTCHours(); - this.minute = aDate.getUTCMinutes(); - this.second = aDate.getUTCSeconds(); - } else { - this.zone = ICAL3.Timezone.localTimezone; - this.year = aDate.getFullYear(); - this.month = aDate.getMonth() + 1; - this.day = aDate.getDate(); - this.hour = aDate.getHours(); - this.minute = aDate.getMinutes(); - this.second = aDate.getSeconds(); - } - } - this._cachedUnixTime = null; - return this; - }, - fromData: function fromData(aData, aZone) { - if (aData) { - for (var key in aData) { - if (Object.prototype.hasOwnProperty.call(aData, key)) { - if (key === "icaltype") - continue; - this[key] = aData[key]; - } - } - } - if (aZone) { - this.zone = aZone; - } - if (aData && !("isDate" in aData)) { - this.isDate = !("hour" in aData); - } else if (aData && "isDate" in aData) { - this.isDate = aData.isDate; - } - if (aData && "timezone" in aData) { - var zone = ICAL3.TimezoneService.get(aData.timezone); - this.zone = zone || ICAL3.Timezone.localTimezone; - } - if (aData && "zone" in aData) { - this.zone = aData.zone; - } - if (!this.zone) { - this.zone = ICAL3.Timezone.localTimezone; - } - this._cachedUnixTime = null; - return this; - }, - dayOfWeek: function icaltime_dayOfWeek(aWeekStart) { - var firstDow = aWeekStart || ICAL3.Time.SUNDAY; - var dowCacheKey = (this.year << 12) + (this.month << 8) + (this.day << 3) + firstDow; - if (dowCacheKey in ICAL3.Time._dowCache) { - return ICAL3.Time._dowCache[dowCacheKey]; - } - var q3 = this.day; - var m2 = this.month + (this.month < 3 ? 12 : 0); - var Y2 = this.year - (this.month < 3 ? 1 : 0); - var h3 = q3 + Y2 + ICAL3.helpers.trunc((m2 + 1) * 26 / 10) + ICAL3.helpers.trunc(Y2 / 4); - if (true) { - h3 += ICAL3.helpers.trunc(Y2 / 100) * 6 + ICAL3.helpers.trunc(Y2 / 400); - } else { - h3 += 5; - } - h3 = (h3 + 7 - firstDow) % 7 + 1; - ICAL3.Time._dowCache[dowCacheKey] = h3; - return h3; - }, - dayOfYear: function dayOfYear() { - var is_leap = ICAL3.Time.isLeapYear(this.year) ? 1 : 0; - var diypm = ICAL3.Time.daysInYearPassedMonth; - return diypm[is_leap][this.month - 1] + this.day; - }, - startOfWeek: function startOfWeek(aWeekStart) { - var firstDow = aWeekStart || ICAL3.Time.SUNDAY; - var result = this.clone(); - result.day -= (this.dayOfWeek() + 7 - firstDow) % 7; - result.isDate = true; - result.hour = 0; - result.minute = 0; - result.second = 0; - return result; - }, - endOfWeek: function endOfWeek(aWeekStart) { - var firstDow = aWeekStart || ICAL3.Time.SUNDAY; - var result = this.clone(); - result.day += (7 - this.dayOfWeek() + firstDow - ICAL3.Time.SUNDAY) % 7; - result.isDate = true; - result.hour = 0; - result.minute = 0; - result.second = 0; - return result; - }, - startOfMonth: function startOfMonth() { - var result = this.clone(); - result.day = 1; - result.isDate = true; - result.hour = 0; - result.minute = 0; - result.second = 0; - return result; - }, - endOfMonth: function endOfMonth() { - var result = this.clone(); - result.day = ICAL3.Time.daysInMonth(result.month, result.year); - result.isDate = true; - result.hour = 0; - result.minute = 0; - result.second = 0; - return result; - }, - startOfYear: function startOfYear() { - var result = this.clone(); - result.day = 1; - result.month = 1; - result.isDate = true; - result.hour = 0; - result.minute = 0; - result.second = 0; - return result; - }, - endOfYear: function endOfYear() { - var result = this.clone(); - result.day = 31; - result.month = 12; - result.isDate = true; - result.hour = 0; - result.minute = 0; - result.second = 0; - return result; - }, - startDoyWeek: function startDoyWeek(aFirstDayOfWeek) { - var firstDow = aFirstDayOfWeek || ICAL3.Time.SUNDAY; - var delta = this.dayOfWeek() - firstDow; - if (delta < 0) - delta += 7; - return this.dayOfYear() - delta; - }, - getDominicalLetter: function() { - return ICAL3.Time.getDominicalLetter(this.year); - }, - nthWeekDay: function icaltime_nthWeekDay(aDayOfWeek, aPos) { - var daysInMonth = ICAL3.Time.daysInMonth(this.month, this.year); - var weekday; - var pos = aPos; - var start = 0; - var otherDay = this.clone(); - if (pos >= 0) { - otherDay.day = 1; - if (pos != 0) { - pos--; - } - start = otherDay.day; - var startDow = otherDay.dayOfWeek(); - var offset = aDayOfWeek - startDow; - if (offset < 0) - offset += 7; - start += offset; - start -= aDayOfWeek; - weekday = aDayOfWeek; - } else { - otherDay.day = daysInMonth; - var endDow = otherDay.dayOfWeek(); - pos++; - weekday = endDow - aDayOfWeek; - if (weekday < 0) { - weekday += 7; - } - weekday = daysInMonth - weekday; - } - weekday += pos * 7; - return start + weekday; - }, - isNthWeekDay: function(aDayOfWeek, aPos) { - var dow = this.dayOfWeek(); - if (aPos === 0 && dow === aDayOfWeek) { - return true; - } - var day = this.nthWeekDay(aDayOfWeek, aPos); - if (day === this.day) { - return true; - } - return false; - }, - weekNumber: function weekNumber(aWeekStart) { - var wnCacheKey = (this.year << 12) + (this.month << 8) + (this.day << 3) + aWeekStart; - if (wnCacheKey in ICAL3.Time._wnCache) { - return ICAL3.Time._wnCache[wnCacheKey]; - } - var week1; - var dt = this.clone(); - dt.isDate = true; - var isoyear = this.year; - if (dt.month == 12 && dt.day > 25) { - week1 = ICAL3.Time.weekOneStarts(isoyear + 1, aWeekStart); - if (dt.compare(week1) < 0) { - week1 = ICAL3.Time.weekOneStarts(isoyear, aWeekStart); - } else { - isoyear++; - } - } else { - week1 = ICAL3.Time.weekOneStarts(isoyear, aWeekStart); - if (dt.compare(week1) < 0) { - week1 = ICAL3.Time.weekOneStarts(--isoyear, aWeekStart); - } - } - var daysBetween = dt.subtractDate(week1).toSeconds() / 86400; - var answer = ICAL3.helpers.trunc(daysBetween / 7) + 1; - ICAL3.Time._wnCache[wnCacheKey] = answer; - return answer; - }, - addDuration: function icaltime_add(aDuration) { - var mult = aDuration.isNegative ? -1 : 1; - var second = this.second; - var minute = this.minute; - var hour = this.hour; - var day = this.day; - second += mult * aDuration.seconds; - minute += mult * aDuration.minutes; - hour += mult * aDuration.hours; - day += mult * aDuration.days; - day += mult * 7 * aDuration.weeks; - this.second = second; - this.minute = minute; - this.hour = hour; - this.day = day; - this._cachedUnixTime = null; - }, - subtractDate: function icaltime_subtract(aDate) { - var unixTime = this.toUnixTime() + this.utcOffset(); - var other = aDate.toUnixTime() + aDate.utcOffset(); - return ICAL3.Duration.fromSeconds(unixTime - other); - }, - subtractDateTz: function icaltime_subtract_abs(aDate) { - var unixTime = this.toUnixTime(); - var other = aDate.toUnixTime(); - return ICAL3.Duration.fromSeconds(unixTime - other); - }, - compare: function icaltime_compare(other) { - var a3 = this.toUnixTime(); - var b3 = other.toUnixTime(); - if (a3 > b3) - return 1; - if (b3 > a3) - return -1; - return 0; - }, - compareDateOnlyTz: function icaltime_compareDateOnlyTz(other, tz) { - function cmp(attr) { - return ICAL3.Time._cmp_attr(a3, b3, attr); - } - var a3 = this.convertToZone(tz); - var b3 = other.convertToZone(tz); - var rc = 0; - if ((rc = cmp("year")) != 0) - return rc; - if ((rc = cmp("month")) != 0) - return rc; - if ((rc = cmp("day")) != 0) - return rc; - return rc; - }, - convertToZone: function convertToZone(zone) { - var copy = this.clone(); - var zone_equals = this.zone.tzid == zone.tzid; - if (!this.isDate && !zone_equals) { - ICAL3.Timezone.convert_time(copy, this.zone, zone); - } - copy.zone = zone; - return copy; - }, - utcOffset: function utc_offset() { - if (this.zone == ICAL3.Timezone.localTimezone || this.zone == ICAL3.Timezone.utcTimezone) { - return 0; - } else { - return this.zone.utcOffset(this); - } - }, - toICALString: function() { - var string = this.toString(); - if (string.length > 10) { - return ICAL3.design.icalendar.value["date-time"].toICAL(string); - } else { - return ICAL3.design.icalendar.value.date.toICAL(string); - } - }, - toString: function toString() { - var result = this.year + "-" + ICAL3.helpers.pad2(this.month) + "-" + ICAL3.helpers.pad2(this.day); - if (!this.isDate) { - result += "T" + ICAL3.helpers.pad2(this.hour) + ":" + ICAL3.helpers.pad2(this.minute) + ":" + ICAL3.helpers.pad2(this.second); - if (this.zone === ICAL3.Timezone.utcTimezone) { - result += "Z"; - } - } - return result; - }, - toJSDate: function toJSDate() { - if (this.zone == ICAL3.Timezone.localTimezone) { - if (this.isDate) { - return new Date(this.year, this.month - 1, this.day); - } else { - return new Date(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, 0); - } - } else { - return new Date(this.toUnixTime() * 1e3); - } - }, - _normalize: function icaltime_normalize() { - var isDate = this._time.isDate; - if (this._time.isDate) { - this._time.hour = 0; - this._time.minute = 0; - this._time.second = 0; - } - this.adjust(0, 0, 0, 0); - return this; - }, - adjust: function icaltime_adjust(aExtraDays, aExtraHours, aExtraMinutes, aExtraSeconds, aTime) { - var minutesOverflow, hoursOverflow, daysOverflow = 0, yearsOverflow = 0; - var second, minute, hour, day; - var daysInMonth; - var time = aTime || this._time; - if (!time.isDate) { - second = time.second + aExtraSeconds; - time.second = second % 60; - minutesOverflow = ICAL3.helpers.trunc(second / 60); - if (time.second < 0) { - time.second += 60; - minutesOverflow--; - } - minute = time.minute + aExtraMinutes + minutesOverflow; - time.minute = minute % 60; - hoursOverflow = ICAL3.helpers.trunc(minute / 60); - if (time.minute < 0) { - time.minute += 60; - hoursOverflow--; - } - hour = time.hour + aExtraHours + hoursOverflow; - time.hour = hour % 24; - daysOverflow = ICAL3.helpers.trunc(hour / 24); - if (time.hour < 0) { - time.hour += 24; - daysOverflow--; - } - } - if (time.month > 12) { - yearsOverflow = ICAL3.helpers.trunc((time.month - 1) / 12); - } else if (time.month < 1) { - yearsOverflow = ICAL3.helpers.trunc(time.month / 12) - 1; - } - time.year += yearsOverflow; - time.month -= 12 * yearsOverflow; - day = time.day + aExtraDays + daysOverflow; - if (day > 0) { - for (; ; ) { - daysInMonth = ICAL3.Time.daysInMonth(time.month, time.year); - if (day <= daysInMonth) { - break; - } - time.month++; - if (time.month > 12) { - time.year++; - time.month = 1; - } - day -= daysInMonth; - } - } else { - while (day <= 0) { - if (time.month == 1) { - time.year--; - time.month = 12; - } else { - time.month--; - } - day += ICAL3.Time.daysInMonth(time.month, time.year); - } - } - time.day = day; - this._cachedUnixTime = null; - return this; - }, - fromUnixTime: function fromUnixTime(seconds) { - this.zone = ICAL3.Timezone.utcTimezone; - var epoch = ICAL3.Time.epochTime.clone(); - epoch.adjust(0, 0, 0, seconds); - this.year = epoch.year; - this.month = epoch.month; - this.day = epoch.day; - this.hour = epoch.hour; - this.minute = epoch.minute; - this.second = Math.floor(epoch.second); - this._cachedUnixTime = null; - }, - toUnixTime: function toUnixTime() { - if (this._cachedUnixTime !== null) { - return this._cachedUnixTime; - } - var offset = this.utcOffset(); - var ms = Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second - offset); - this._cachedUnixTime = ms / 1e3; - return this._cachedUnixTime; - }, - toJSON: function() { - var copy = [ - "year", - "month", - "day", - "hour", - "minute", - "second", - "isDate" - ]; - var result = Object.create(null); - var i3 = 0; - var len = copy.length; - var prop; - for (; i3 < len; i3++) { - prop = copy[i3]; - result[prop] = this[prop]; - } - if (this.zone) { - result.timezone = this.zone.tzid; - } - return result; - } - }; - (function setupNormalizeAttributes() { - function defineAttr(attr) { - Object.defineProperty(ICAL3.Time.prototype, attr, { - get: function getTimeAttr() { - if (this._pendingNormalization) { - this._normalize(); - this._pendingNormalization = false; - } - return this._time[attr]; - }, - set: function setTimeAttr(val) { - if (attr === "isDate" && val && !this._time.isDate) { - this.adjust(0, 0, 0, 0); - } - this._cachedUnixTime = null; - this._pendingNormalization = true; - this._time[attr] = val; - return val; - } - }); - } - if ("defineProperty" in Object) { - defineAttr("year"); - defineAttr("month"); - defineAttr("day"); - defineAttr("hour"); - defineAttr("minute"); - defineAttr("second"); - defineAttr("isDate"); - } - })(); - ICAL3.Time.daysInMonth = function icaltime_daysInMonth(month, year) { - var _daysInMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - var days = 30; - if (month < 1 || month > 12) - return days; - days = _daysInMonth[month]; - if (month == 2) { - days += ICAL3.Time.isLeapYear(year); - } - return days; - }; - ICAL3.Time.isLeapYear = function isLeapYear(year) { - if (year <= 1752) { - return year % 4 == 0; - } else { - return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; - } - }; - ICAL3.Time.fromDayOfYear = function icaltime_fromDayOfYear(aDayOfYear, aYear) { - var year = aYear; - var doy = aDayOfYear; - var tt = new ICAL3.Time(); - tt.auto_normalize = false; - var is_leap = ICAL3.Time.isLeapYear(year) ? 1 : 0; - if (doy < 1) { - year--; - is_leap = ICAL3.Time.isLeapYear(year) ? 1 : 0; - doy += ICAL3.Time.daysInYearPassedMonth[is_leap][12]; - return ICAL3.Time.fromDayOfYear(doy, year); - } else if (doy > ICAL3.Time.daysInYearPassedMonth[is_leap][12]) { - is_leap = ICAL3.Time.isLeapYear(year) ? 1 : 0; - doy -= ICAL3.Time.daysInYearPassedMonth[is_leap][12]; - year++; - return ICAL3.Time.fromDayOfYear(doy, year); - } - tt.year = year; - tt.isDate = true; - for (var month = 11; month >= 0; month--) { - if (doy > ICAL3.Time.daysInYearPassedMonth[is_leap][month]) { - tt.month = month + 1; - tt.day = doy - ICAL3.Time.daysInYearPassedMonth[is_leap][month]; - break; - } - } - tt.auto_normalize = true; - return tt; - }; - ICAL3.Time.fromStringv2 = function fromString(str) { - return new ICAL3.Time({ - year: parseInt(str.substr(0, 4), 10), - month: parseInt(str.substr(5, 2), 10), - day: parseInt(str.substr(8, 2), 10), - isDate: true - }); - }; - ICAL3.Time.fromDateString = function(aValue) { - return new ICAL3.Time({ - year: ICAL3.helpers.strictParseInt(aValue.substr(0, 4)), - month: ICAL3.helpers.strictParseInt(aValue.substr(5, 2)), - day: ICAL3.helpers.strictParseInt(aValue.substr(8, 2)), - isDate: true - }); - }; - ICAL3.Time.fromDateTimeString = function(aValue, prop) { - if (aValue.length < 19) { - throw new Error('invalid date-time value: "' + aValue + '"'); - } - var zone; - if (aValue[19] && aValue[19] === "Z") { - zone = "Z"; - } else if (prop) { - zone = prop.getParameter("tzid"); - } - var time = new ICAL3.Time({ - year: ICAL3.helpers.strictParseInt(aValue.substr(0, 4)), - month: ICAL3.helpers.strictParseInt(aValue.substr(5, 2)), - day: ICAL3.helpers.strictParseInt(aValue.substr(8, 2)), - hour: ICAL3.helpers.strictParseInt(aValue.substr(11, 2)), - minute: ICAL3.helpers.strictParseInt(aValue.substr(14, 2)), - second: ICAL3.helpers.strictParseInt(aValue.substr(17, 2)), - timezone: zone - }); - return time; - }; - ICAL3.Time.fromString = function fromString(aValue, aProperty) { - if (aValue.length > 10) { - return ICAL3.Time.fromDateTimeString(aValue, aProperty); - } else { - return ICAL3.Time.fromDateString(aValue); - } - }; - ICAL3.Time.fromJSDate = function fromJSDate(aDate, useUTC) { - var tt = new ICAL3.Time(); - return tt.fromJSDate(aDate, useUTC); - }; - ICAL3.Time.fromData = function fromData(aData, aZone) { - var t3 = new ICAL3.Time(); - return t3.fromData(aData, aZone); - }; - ICAL3.Time.now = function icaltime_now() { - return ICAL3.Time.fromJSDate(new Date(), false); - }; - ICAL3.Time.weekOneStarts = function weekOneStarts(aYear, aWeekStart) { - var t3 = ICAL3.Time.fromData({ - year: aYear, - month: 1, - day: 1, - isDate: true - }); - var dow = t3.dayOfWeek(); - var wkst = aWeekStart || ICAL3.Time.DEFAULT_WEEK_START; - if (dow > ICAL3.Time.THURSDAY) { - t3.day += 7; - } - if (wkst > ICAL3.Time.THURSDAY) { - t3.day -= 7; - } - t3.day -= dow - wkst; - return t3; - }; - ICAL3.Time.getDominicalLetter = function(yr) { - var LTRS = "GFEDCBA"; - var dom = (yr + (yr / 4 | 0) + (yr / 400 | 0) - (yr / 100 | 0) - 1) % 7; - var isLeap = ICAL3.Time.isLeapYear(yr); - if (isLeap) { - return LTRS[(dom + 6) % 7] + LTRS[dom]; - } else { - return LTRS[dom]; - } - }; - ICAL3.Time.epochTime = ICAL3.Time.fromData({ - year: 1970, - month: 1, - day: 1, - hour: 0, - minute: 0, - second: 0, - isDate: false, - timezone: "Z" - }); - ICAL3.Time._cmp_attr = function _cmp_attr(a3, b3, attr) { - if (a3[attr] > b3[attr]) - return 1; - if (a3[attr] < b3[attr]) - return -1; - return 0; - }; - ICAL3.Time.daysInYearPassedMonth = [ - [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365], - [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] - ]; - ICAL3.Time.SUNDAY = 1; - ICAL3.Time.MONDAY = 2; - ICAL3.Time.TUESDAY = 3; - ICAL3.Time.WEDNESDAY = 4; - ICAL3.Time.THURSDAY = 5; - ICAL3.Time.FRIDAY = 6; - ICAL3.Time.SATURDAY = 7; - ICAL3.Time.DEFAULT_WEEK_START = ICAL3.Time.MONDAY; - })(); - (function() { - ICAL3.VCardTime = function(data, zone, icaltype) { - this.wrappedJSObject = this; - var time = this._time = Object.create(null); - time.year = null; - time.month = null; - time.day = null; - time.hour = null; - time.minute = null; - time.second = null; - this.icaltype = icaltype || "date-and-or-time"; - this.fromData(data, zone); - }; - ICAL3.helpers.inherits(ICAL3.Time, ICAL3.VCardTime, { - icalclass: "vcardtime", - icaltype: "date-and-or-time", - zone: null, - clone: function() { - return new ICAL3.VCardTime(this._time, this.zone, this.icaltype); - }, - _normalize: function() { - return this; - }, - utcOffset: function() { - if (this.zone instanceof ICAL3.UtcOffset) { - return this.zone.toSeconds(); - } else { - return ICAL3.Time.prototype.utcOffset.apply(this, arguments); - } - }, - toICALString: function() { - return ICAL3.design.vcard.value[this.icaltype].toICAL(this.toString()); - }, - toString: function toString() { - var p22 = ICAL3.helpers.pad2; - var y3 = this.year, m2 = this.month, d3 = this.day; - var h3 = this.hour, mm = this.minute, s3 = this.second; - var hasYear = y3 !== null, hasMonth = m2 !== null, hasDay = d3 !== null; - var hasHour = h3 !== null, hasMinute = mm !== null, hasSecond = s3 !== null; - var datepart = (hasYear ? p22(y3) + (hasMonth || hasDay ? "-" : "") : hasMonth || hasDay ? "--" : "") + (hasMonth ? p22(m2) : "") + (hasDay ? "-" + p22(d3) : ""); - var timepart = (hasHour ? p22(h3) : "-") + (hasHour && hasMinute ? ":" : "") + (hasMinute ? p22(mm) : "") + (!hasHour && !hasMinute ? "-" : "") + (hasMinute && hasSecond ? ":" : "") + (hasSecond ? p22(s3) : ""); - var zone; - if (this.zone === ICAL3.Timezone.utcTimezone) { - zone = "Z"; - } else if (this.zone instanceof ICAL3.UtcOffset) { - zone = this.zone.toString(); - } else if (this.zone === ICAL3.Timezone.localTimezone) { - zone = ""; - } else if (this.zone instanceof ICAL3.Timezone) { - var offset = ICAL3.UtcOffset.fromSeconds(this.zone.utcOffset(this)); - zone = offset.toString(); - } else { - zone = ""; - } - switch (this.icaltype) { - case "time": - return timepart + zone; - case "date-and-or-time": - case "date-time": - return datepart + (timepart == "--" ? "" : "T" + timepart + zone); - case "date": - return datepart; - } - return null; - } - }); - ICAL3.VCardTime.fromDateAndOrTimeString = function(aValue, aIcalType) { - function part(v3, s3, e3) { - return v3 ? ICAL3.helpers.strictParseInt(v3.substr(s3, e3)) : null; - } - var parts = aValue.split("T"); - var dt = parts[0], tmz = parts[1]; - var splitzone = tmz ? ICAL3.design.vcard.value.time._splitZone(tmz) : []; - var zone = splitzone[0], tm = splitzone[1]; - var stoi = ICAL3.helpers.strictParseInt; - var dtlen = dt ? dt.length : 0; - var tmlen = tm ? tm.length : 0; - var hasDashDate = dt && dt[0] == "-" && dt[1] == "-"; - var hasDashTime = tm && tm[0] == "-"; - var o2 = { - year: hasDashDate ? null : part(dt, 0, 4), - month: hasDashDate && (dtlen == 4 || dtlen == 7) ? part(dt, 2, 2) : dtlen == 7 ? part(dt, 5, 2) : dtlen == 10 ? part(dt, 5, 2) : null, - day: dtlen == 5 ? part(dt, 3, 2) : dtlen == 7 && hasDashDate ? part(dt, 5, 2) : dtlen == 10 ? part(dt, 8, 2) : null, - hour: hasDashTime ? null : part(tm, 0, 2), - minute: hasDashTime && tmlen == 3 ? part(tm, 1, 2) : tmlen > 4 ? hasDashTime ? part(tm, 1, 2) : part(tm, 3, 2) : null, - second: tmlen == 4 ? part(tm, 2, 2) : tmlen == 6 ? part(tm, 4, 2) : tmlen == 8 ? part(tm, 6, 2) : null - }; - if (zone == "Z") { - zone = ICAL3.Timezone.utcTimezone; - } else if (zone && zone[3] == ":") { - zone = ICAL3.UtcOffset.fromString(zone); - } else { - zone = null; - } - return new ICAL3.VCardTime(o2, zone, aIcalType); - }; - })(); - (function() { - var DOW_MAP = { - SU: ICAL3.Time.SUNDAY, - MO: ICAL3.Time.MONDAY, - TU: ICAL3.Time.TUESDAY, - WE: ICAL3.Time.WEDNESDAY, - TH: ICAL3.Time.THURSDAY, - FR: ICAL3.Time.FRIDAY, - SA: ICAL3.Time.SATURDAY - }; - var REVERSE_DOW_MAP = {}; - for (var key in DOW_MAP) { - if (DOW_MAP.hasOwnProperty(key)) { - REVERSE_DOW_MAP[DOW_MAP[key]] = key; - } - } - var COPY_PARTS = [ - "BYSECOND", - "BYMINUTE", - "BYHOUR", - "BYDAY", - "BYMONTHDAY", - "BYYEARDAY", - "BYWEEKNO", - "BYMONTH", - "BYSETPOS" - ]; - ICAL3.Recur = function icalrecur(data) { - this.wrappedJSObject = this; - this.parts = {}; - if (data && typeof data === "object") { - this.fromData(data); - } - }; - ICAL3.Recur.prototype = { - parts: null, - interval: 1, - wkst: ICAL3.Time.MONDAY, - until: null, - count: null, - freq: null, - icalclass: "icalrecur", - icaltype: "recur", - iterator: function(aStart) { - return new ICAL3.RecurIterator({ - rule: this, - dtstart: aStart - }); - }, - clone: function clone() { - return new ICAL3.Recur(this.toJSON()); - }, - isFinite: function isfinite() { - return !!(this.count || this.until); - }, - isByCount: function isbycount() { - return !!(this.count && !this.until); - }, - addComponent: function addPart(aType, aValue) { - var ucname = aType.toUpperCase(); - if (ucname in this.parts) { - this.parts[ucname].push(aValue); - } else { - this.parts[ucname] = [aValue]; - } - }, - setComponent: function setComponent(aType, aValues) { - this.parts[aType.toUpperCase()] = aValues.slice(); - }, - getComponent: function getComponent(aType) { - var ucname = aType.toUpperCase(); - return ucname in this.parts ? this.parts[ucname].slice() : []; - }, - getNextOccurrence: function getNextOccurrence(aStartTime, aRecurrenceId) { - var iter = this.iterator(aStartTime); - var next, cdt; - do { - next = iter.next(); - } while (next && next.compare(aRecurrenceId) <= 0); - if (next && aRecurrenceId.zone) { - next.zone = aRecurrenceId.zone; - } - return next; - }, - fromData: function(data) { - for (var key2 in data) { - var uckey = key2.toUpperCase(); - if (uckey in partDesign) { - if (Array.isArray(data[key2])) { - this.parts[uckey] = data[key2]; - } else { - this.parts[uckey] = [data[key2]]; - } - } else { - this[key2] = data[key2]; - } - } - if (this.interval && typeof this.interval != "number") { - optionDesign.INTERVAL(this.interval, this); - } - if (this.wkst && typeof this.wkst != "number") { - this.wkst = ICAL3.Recur.icalDayToNumericDay(this.wkst); - } - if (this.until && !(this.until instanceof ICAL3.Time)) { - this.until = ICAL3.Time.fromString(this.until); - } - }, - toJSON: function() { - var res = Object.create(null); - res.freq = this.freq; - if (this.count) { - res.count = this.count; - } - if (this.interval > 1) { - res.interval = this.interval; - } - for (var k2 in this.parts) { - if (!this.parts.hasOwnProperty(k2)) { - continue; - } - var kparts = this.parts[k2]; - if (Array.isArray(kparts) && kparts.length == 1) { - res[k2.toLowerCase()] = kparts[0]; - } else { - res[k2.toLowerCase()] = ICAL3.helpers.clone(this.parts[k2]); - } - } - if (this.until) { - res.until = this.until.toString(); - } - if ("wkst" in this && this.wkst !== ICAL3.Time.DEFAULT_WEEK_START) { - res.wkst = ICAL3.Recur.numericDayToIcalDay(this.wkst); - } - return res; - }, - toString: function icalrecur_toString() { - var str = "FREQ=" + this.freq; - if (this.count) { - str += ";COUNT=" + this.count; - } - if (this.interval > 1) { - str += ";INTERVAL=" + this.interval; - } - for (var k2 in this.parts) { - if (this.parts.hasOwnProperty(k2)) { - str += ";" + k2 + "=" + this.parts[k2]; - } - } - if (this.until) { - str += ";UNTIL=" + this.until.toICALString(); - } - if ("wkst" in this && this.wkst !== ICAL3.Time.DEFAULT_WEEK_START) { - str += ";WKST=" + ICAL3.Recur.numericDayToIcalDay(this.wkst); - } - return str; - } - }; - function parseNumericValue(type, min, max, value) { - var result = value; - if (value[0] === "+") { - result = value.substr(1); - } - result = ICAL3.helpers.strictParseInt(result); - if (min !== void 0 && value < min) { - throw new Error(type + ': invalid value "' + value + '" must be > ' + min); - } - if (max !== void 0 && value > max) { - throw new Error(type + ': invalid value "' + value + '" must be < ' + min); - } - return result; - } - ICAL3.Recur.icalDayToNumericDay = function toNumericDay(string, aWeekStart) { - var firstDow = aWeekStart || ICAL3.Time.SUNDAY; - return (DOW_MAP[string] - firstDow + 7) % 7 + 1; - }; - ICAL3.Recur.numericDayToIcalDay = function toIcalDay(num, aWeekStart) { - var firstDow = aWeekStart || ICAL3.Time.SUNDAY; - var dow = num + firstDow - ICAL3.Time.SUNDAY; - if (dow > 7) { - dow -= 7; - } - return REVERSE_DOW_MAP[dow]; - }; - var VALID_DAY_NAMES = /^(SU|MO|TU|WE|TH|FR|SA)$/; - var VALID_BYDAY_PART = /^([+-])?(5[0-3]|[1-4][0-9]|[1-9])?(SU|MO|TU|WE|TH|FR|SA)$/; - var ALLOWED_FREQ = [ - "SECONDLY", - "MINUTELY", - "HOURLY", - "DAILY", - "WEEKLY", - "MONTHLY", - "YEARLY" - ]; - var optionDesign = { - FREQ: function(value, dict, fmtIcal) { - if (ALLOWED_FREQ.indexOf(value) !== -1) { - dict.freq = value; - } else { - throw new Error('invalid frequency "' + value + '" expected: "' + ALLOWED_FREQ.join(", ") + '"'); - } - }, - COUNT: function(value, dict, fmtIcal) { - dict.count = ICAL3.helpers.strictParseInt(value); - }, - INTERVAL: function(value, dict, fmtIcal) { - dict.interval = ICAL3.helpers.strictParseInt(value); - if (dict.interval < 1) { - dict.interval = 1; - } - }, - UNTIL: function(value, dict, fmtIcal) { - if (value.length > 10) { - dict.until = ICAL3.design.icalendar.value["date-time"].fromICAL(value); - } else { - dict.until = ICAL3.design.icalendar.value.date.fromICAL(value); - } - if (!fmtIcal) { - dict.until = ICAL3.Time.fromString(dict.until); - } - }, - WKST: function(value, dict, fmtIcal) { - if (VALID_DAY_NAMES.test(value)) { - dict.wkst = ICAL3.Recur.icalDayToNumericDay(value); - } else { - throw new Error('invalid WKST value "' + value + '"'); - } - } - }; - var partDesign = { - BYSECOND: parseNumericValue.bind(this, "BYSECOND", 0, 60), - BYMINUTE: parseNumericValue.bind(this, "BYMINUTE", 0, 59), - BYHOUR: parseNumericValue.bind(this, "BYHOUR", 0, 23), - BYDAY: function(value) { - if (VALID_BYDAY_PART.test(value)) { - return value; - } else { - throw new Error('invalid BYDAY value "' + value + '"'); - } - }, - BYMONTHDAY: parseNumericValue.bind(this, "BYMONTHDAY", -31, 31), - BYYEARDAY: parseNumericValue.bind(this, "BYYEARDAY", -366, 366), - BYWEEKNO: parseNumericValue.bind(this, "BYWEEKNO", -53, 53), - BYMONTH: parseNumericValue.bind(this, "BYMONTH", 1, 12), - BYSETPOS: parseNumericValue.bind(this, "BYSETPOS", -366, 366) - }; - ICAL3.Recur.fromString = function(string) { - var data = ICAL3.Recur._stringToData(string, false); - return new ICAL3.Recur(data); - }; - ICAL3.Recur.fromData = function(aData) { - return new ICAL3.Recur(aData); - }; - ICAL3.Recur._stringToData = function(string, fmtIcal) { - var dict = Object.create(null); - var values = string.split(";"); - var len = values.length; - for (var i3 = 0; i3 < len; i3++) { - var parts = values[i3].split("="); - var ucname = parts[0].toUpperCase(); - var lcname = parts[0].toLowerCase(); - var name = fmtIcal ? lcname : ucname; - var value = parts[1]; - if (ucname in partDesign) { - var partArr = value.split(","); - var partArrIdx = 0; - var partArrLen = partArr.length; - for (; partArrIdx < partArrLen; partArrIdx++) { - partArr[partArrIdx] = partDesign[ucname](partArr[partArrIdx]); - } - dict[name] = partArr.length == 1 ? partArr[0] : partArr; - } else if (ucname in optionDesign) { - optionDesign[ucname](value, dict, fmtIcal); - } else { - dict[lcname] = value; - } - } - return dict; - }; - })(); - ICAL3.RecurIterator = function() { - function icalrecur_iterator(options) { - this.fromData(options); - } - icalrecur_iterator.prototype = { - completed: false, - rule: null, - dtstart: null, - last: null, - occurrence_number: 0, - by_indices: null, - initialized: false, - by_data: null, - days: null, - days_index: 0, - fromData: function(options) { - this.rule = ICAL3.helpers.formatClassType(options.rule, ICAL3.Recur); - if (!this.rule) { - throw new Error("iterator requires a (ICAL.Recur) rule"); - } - this.dtstart = ICAL3.helpers.formatClassType(options.dtstart, ICAL3.Time); - if (!this.dtstart) { - throw new Error("iterator requires a (ICAL.Time) dtstart"); - } - if (options.by_data) { - this.by_data = options.by_data; - } else { - this.by_data = ICAL3.helpers.clone(this.rule.parts, true); - } - if (options.occurrence_number) - this.occurrence_number = options.occurrence_number; - this.days = options.days || []; - if (options.last) { - this.last = ICAL3.helpers.formatClassType(options.last, ICAL3.Time); - } - this.by_indices = options.by_indices; - if (!this.by_indices) { - this.by_indices = { - "BYSECOND": 0, - "BYMINUTE": 0, - "BYHOUR": 0, - "BYDAY": 0, - "BYMONTH": 0, - "BYWEEKNO": 0, - "BYMONTHDAY": 0 - }; - } - this.initialized = options.initialized || false; - if (!this.initialized) { - this.init(); - } - }, - init: function icalrecur_iterator_init() { - this.initialized = true; - this.last = this.dtstart.clone(); - var parts = this.by_data; - if ("BYDAY" in parts) { - this.sort_byday_rules(parts.BYDAY); - } - if ("BYYEARDAY" in parts) { - if ("BYMONTH" in parts || "BYWEEKNO" in parts || "BYMONTHDAY" in parts || "BYDAY" in parts) { - throw new Error("Invalid BYYEARDAY rule"); - } - } - if ("BYWEEKNO" in parts && "BYMONTHDAY" in parts) { - throw new Error("BYWEEKNO does not fit to BYMONTHDAY"); - } - if (this.rule.freq == "MONTHLY" && ("BYYEARDAY" in parts || "BYWEEKNO" in parts)) { - throw new Error("For MONTHLY recurrences neither BYYEARDAY nor BYWEEKNO may appear"); - } - if (this.rule.freq == "WEEKLY" && ("BYYEARDAY" in parts || "BYMONTHDAY" in parts)) { - throw new Error("For WEEKLY recurrences neither BYMONTHDAY nor BYYEARDAY may appear"); - } - if (this.rule.freq != "YEARLY" && "BYYEARDAY" in parts) { - throw new Error("BYYEARDAY may only appear in YEARLY rules"); - } - this.last.second = this.setup_defaults("BYSECOND", "SECONDLY", this.dtstart.second); - this.last.minute = this.setup_defaults("BYMINUTE", "MINUTELY", this.dtstart.minute); - this.last.hour = this.setup_defaults("BYHOUR", "HOURLY", this.dtstart.hour); - this.last.day = this.setup_defaults("BYMONTHDAY", "DAILY", this.dtstart.day); - this.last.month = this.setup_defaults("BYMONTH", "MONTHLY", this.dtstart.month); - if (this.rule.freq == "WEEKLY") { - if ("BYDAY" in parts) { - var bydayParts = this.ruleDayOfWeek(parts.BYDAY[0], this.rule.wkst); - var pos = bydayParts[0]; - var dow = bydayParts[1]; - var wkdy = dow - this.last.dayOfWeek(this.rule.wkst); - if (this.last.dayOfWeek(this.rule.wkst) < dow && wkdy >= 0 || wkdy < 0) { - this.last.day += wkdy; - } - } else { - var dayName = ICAL3.Recur.numericDayToIcalDay(this.dtstart.dayOfWeek()); - parts.BYDAY = [dayName]; - } - } - if (this.rule.freq == "YEARLY") { - for (; ; ) { - this.expand_year_days(this.last.year); - if (this.days.length > 0) { - break; - } - this.increment_year(this.rule.interval); - } - this._nextByYearDay(); - } - if (this.rule.freq == "MONTHLY" && this.has_by_data("BYDAY")) { - var tempLast = null; - var initLast = this.last.clone(); - var daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - for (var i3 in this.by_data.BYDAY) { - if (!this.by_data.BYDAY.hasOwnProperty(i3)) { - continue; - } - this.last = initLast.clone(); - var bydayParts = this.ruleDayOfWeek(this.by_data.BYDAY[i3]); - var pos = bydayParts[0]; - var dow = bydayParts[1]; - var dayOfMonth = this.last.nthWeekDay(dow, pos); - if (pos >= 6 || pos <= -6) { - throw new Error("Malformed values in BYDAY part"); - } - if (dayOfMonth > daysInMonth || dayOfMonth <= 0) { - if (tempLast && tempLast.month == initLast.month) { - continue; - } - while (dayOfMonth > daysInMonth || dayOfMonth <= 0) { - this.increment_month(); - daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - dayOfMonth = this.last.nthWeekDay(dow, pos); - } - } - this.last.day = dayOfMonth; - if (!tempLast || this.last.compare(tempLast) < 0) { - tempLast = this.last.clone(); - } - } - this.last = tempLast.clone(); - if (this.has_by_data("BYMONTHDAY")) { - this._byDayAndMonthDay(true); - } - if (this.last.day > daysInMonth || this.last.day == 0) { - throw new Error("Malformed values in BYDAY part"); - } - } else if (this.has_by_data("BYMONTHDAY")) { - if (this.last.day < 0) { - var daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - this.last.day = daysInMonth + this.last.day + 1; - } - } - }, - next: function icalrecur_iterator_next() { - var before = this.last ? this.last.clone() : null; - if (this.rule.count && this.occurrence_number >= this.rule.count || this.rule.until && this.last.compare(this.rule.until) > 0) { - this.completed = true; - return null; - } - if (this.occurrence_number == 0 && this.last.compare(this.dtstart) >= 0) { - this.occurrence_number++; - return this.last; - } - var valid; - do { - valid = 1; - switch (this.rule.freq) { - case "SECONDLY": - this.next_second(); - break; - case "MINUTELY": - this.next_minute(); - break; - case "HOURLY": - this.next_hour(); - break; - case "DAILY": - this.next_day(); - break; - case "WEEKLY": - this.next_week(); - break; - case "MONTHLY": - valid = this.next_month(); - break; - case "YEARLY": - this.next_year(); - break; - default: - return null; - } - } while (!this.check_contracting_rules() || this.last.compare(this.dtstart) < 0 || !valid); - if (this.last.compare(before) == 0) { - throw new Error("Same occurrence found twice, protecting you from death by recursion"); - } - if (this.rule.until && this.last.compare(this.rule.until) > 0) { - this.completed = true; - return null; - } else { - this.occurrence_number++; - return this.last; - } - }, - next_second: function next_second() { - return this.next_generic("BYSECOND", "SECONDLY", "second", "minute"); - }, - increment_second: function increment_second(inc) { - return this.increment_generic(inc, "second", 60, "minute"); - }, - next_minute: function next_minute() { - return this.next_generic("BYMINUTE", "MINUTELY", "minute", "hour", "next_second"); - }, - increment_minute: function increment_minute(inc) { - return this.increment_generic(inc, "minute", 60, "hour"); - }, - next_hour: function next_hour() { - return this.next_generic("BYHOUR", "HOURLY", "hour", "monthday", "next_minute"); - }, - increment_hour: function increment_hour(inc) { - this.increment_generic(inc, "hour", 24, "monthday"); - }, - next_day: function next_day() { - var has_by_day = "BYDAY" in this.by_data; - var this_freq = this.rule.freq == "DAILY"; - if (this.next_hour() == 0) { - return 0; - } - if (this_freq) { - this.increment_monthday(this.rule.interval); - } else { - this.increment_monthday(1); - } - return 0; - }, - next_week: function next_week() { - var end_of_data = 0; - if (this.next_weekday_by_week() == 0) { - return end_of_data; - } - if (this.has_by_data("BYWEEKNO")) { - var idx = ++this.by_indices.BYWEEKNO; - if (this.by_indices.BYWEEKNO == this.by_data.BYWEEKNO.length) { - this.by_indices.BYWEEKNO = 0; - end_of_data = 1; - } - this.last.month = 1; - this.last.day = 1; - var week_no = this.by_data.BYWEEKNO[this.by_indices.BYWEEKNO]; - this.last.day += 7 * week_no; - if (end_of_data) { - this.increment_year(1); - } - } else { - this.increment_monthday(7 * this.rule.interval); - } - return end_of_data; - }, - normalizeByMonthDayRules: function(year, month, rules) { - var daysInMonth = ICAL3.Time.daysInMonth(month, year); - var newRules = []; - var ruleIdx = 0; - var len = rules.length; - var rule; - for (; ruleIdx < len; ruleIdx++) { - rule = rules[ruleIdx]; - if (Math.abs(rule) > daysInMonth) { - continue; - } - if (rule < 0) { - rule = daysInMonth + (rule + 1); - } else if (rule === 0) { - continue; - } - if (newRules.indexOf(rule) === -1) { - newRules.push(rule); - } - } - return newRules.sort(function(a3, b3) { - return a3 - b3; - }); - }, - _byDayAndMonthDay: function(isInit) { - var byMonthDay; - var byDay = this.by_data.BYDAY; - var date; - var dateIdx = 0; - var dateLen; - var dayLen = byDay.length; - var dataIsValid = 0; - var daysInMonth; - var self2 = this; - var lastDay = this.last.day; - function initMonth() { - daysInMonth = ICAL3.Time.daysInMonth(self2.last.month, self2.last.year); - byMonthDay = self2.normalizeByMonthDayRules(self2.last.year, self2.last.month, self2.by_data.BYMONTHDAY); - dateLen = byMonthDay.length; - while (byMonthDay[dateIdx] <= lastDay && !(isInit && byMonthDay[dateIdx] == lastDay) && dateIdx < dateLen - 1) { - dateIdx++; - } - } - function nextMonth() { - lastDay = 0; - self2.increment_month(); - dateIdx = 0; - initMonth(); - } - initMonth(); - if (isInit) { - lastDay -= 1; - } - var monthsCounter = 48; - while (!dataIsValid && monthsCounter) { - monthsCounter--; - date = lastDay + 1; - if (date > daysInMonth) { - nextMonth(); - continue; - } - var next = byMonthDay[dateIdx++]; - if (next >= date) { - lastDay = next; - } else { - nextMonth(); - continue; - } - for (var dayIdx = 0; dayIdx < dayLen; dayIdx++) { - var parts = this.ruleDayOfWeek(byDay[dayIdx]); - var pos = parts[0]; - var dow = parts[1]; - this.last.day = lastDay; - if (this.last.isNthWeekDay(dow, pos)) { - dataIsValid = 1; - break; - } - } - if (!dataIsValid && dateIdx === dateLen) { - nextMonth(); - continue; - } - } - if (monthsCounter <= 0) { - throw new Error("Malformed values in BYDAY combined with BYMONTHDAY parts"); - } - return dataIsValid; - }, - next_month: function next_month() { - var this_freq = this.rule.freq == "MONTHLY"; - var data_valid = 1; - if (this.next_hour() == 0) { - return data_valid; - } - if (this.has_by_data("BYDAY") && this.has_by_data("BYMONTHDAY")) { - data_valid = this._byDayAndMonthDay(); - } else if (this.has_by_data("BYDAY")) { - var daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - var setpos = 0; - var setpos_total = 0; - if (this.has_by_data("BYSETPOS")) { - var last_day = this.last.day; - for (var day = 1; day <= daysInMonth; day++) { - this.last.day = day; - if (this.is_day_in_byday(this.last)) { - setpos_total++; - if (day <= last_day) { - setpos++; - } - } - } - this.last.day = last_day; - } - data_valid = 0; - for (var day = this.last.day + 1; day <= daysInMonth; day++) { - this.last.day = day; - if (this.is_day_in_byday(this.last)) { - if (!this.has_by_data("BYSETPOS") || this.check_set_position(++setpos) || this.check_set_position(setpos - setpos_total - 1)) { - data_valid = 1; - break; - } - } - } - if (day > daysInMonth) { - this.last.day = 1; - this.increment_month(); - if (this.is_day_in_byday(this.last)) { - if (!this.has_by_data("BYSETPOS") || this.check_set_position(1)) { - data_valid = 1; - } - } else { - data_valid = 0; - } - } - } else if (this.has_by_data("BYMONTHDAY")) { - this.by_indices.BYMONTHDAY++; - if (this.by_indices.BYMONTHDAY >= this.by_data.BYMONTHDAY.length) { - this.by_indices.BYMONTHDAY = 0; - this.increment_month(); - } - var daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - var day = this.by_data.BYMONTHDAY[this.by_indices.BYMONTHDAY]; - if (day < 0) { - day = daysInMonth + day + 1; - } - if (day > daysInMonth) { - this.last.day = 1; - data_valid = this.is_day_in_byday(this.last); - } else { - this.last.day = day; - } - } else { - this.increment_month(); - var daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - if (this.by_data.BYMONTHDAY[0] > daysInMonth) { - data_valid = 0; - } else { - this.last.day = this.by_data.BYMONTHDAY[0]; - } - } - return data_valid; - }, - next_weekday_by_week: function next_weekday_by_week() { - var end_of_data = 0; - if (this.next_hour() == 0) { - return end_of_data; - } - if (!this.has_by_data("BYDAY")) { - return 1; - } - for (; ; ) { - var tt = new ICAL3.Time(); - this.by_indices.BYDAY++; - if (this.by_indices.BYDAY == Object.keys(this.by_data.BYDAY).length) { - this.by_indices.BYDAY = 0; - end_of_data = 1; - } - var coded_day = this.by_data.BYDAY[this.by_indices.BYDAY]; - var parts = this.ruleDayOfWeek(coded_day); - var dow = parts[1]; - dow -= this.rule.wkst; - if (dow < 0) { - dow += 7; - } - tt.year = this.last.year; - tt.month = this.last.month; - tt.day = this.last.day; - var startOfWeek = tt.startDoyWeek(this.rule.wkst); - if (dow + startOfWeek < 1) { - if (!end_of_data) { - continue; - } - } - var next = ICAL3.Time.fromDayOfYear(startOfWeek + dow, this.last.year); - this.last.year = next.year; - this.last.month = next.month; - this.last.day = next.day; - return end_of_data; - } - }, - next_year: function next_year() { - if (this.next_hour() == 0) { - return 0; - } - if (++this.days_index == this.days.length) { - this.days_index = 0; - do { - this.increment_year(this.rule.interval); - this.expand_year_days(this.last.year); - } while (this.days.length == 0); - } - this._nextByYearDay(); - return 1; - }, - _nextByYearDay: function _nextByYearDay() { - var doy = this.days[this.days_index]; - var year = this.last.year; - if (doy < 1) { - doy += 1; - year += 1; - } - var next = ICAL3.Time.fromDayOfYear(doy, year); - this.last.day = next.day; - this.last.month = next.month; - }, - ruleDayOfWeek: function ruleDayOfWeek(dow, aWeekStart) { - var matches = dow.match(/([+-]?[0-9])?(MO|TU|WE|TH|FR|SA|SU)/); - if (matches) { - var pos = parseInt(matches[1] || 0, 10); - dow = ICAL3.Recur.icalDayToNumericDay(matches[2], aWeekStart); - return [pos, dow]; - } else { - return [0, 0]; - } - }, - next_generic: function next_generic(aRuleType, aInterval, aDateAttr, aFollowingAttr, aPreviousIncr) { - var has_by_rule = aRuleType in this.by_data; - var this_freq = this.rule.freq == aInterval; - var end_of_data = 0; - if (aPreviousIncr && this[aPreviousIncr]() == 0) { - return end_of_data; - } - if (has_by_rule) { - this.by_indices[aRuleType]++; - var idx = this.by_indices[aRuleType]; - var dta = this.by_data[aRuleType]; - if (this.by_indices[aRuleType] == dta.length) { - this.by_indices[aRuleType] = 0; - end_of_data = 1; - } - this.last[aDateAttr] = dta[this.by_indices[aRuleType]]; - } else if (this_freq) { - this["increment_" + aDateAttr](this.rule.interval); - } - if (has_by_rule && end_of_data && this_freq) { - this["increment_" + aFollowingAttr](1); - } - return end_of_data; - }, - increment_monthday: function increment_monthday(inc) { - for (var i3 = 0; i3 < inc; i3++) { - var daysInMonth = ICAL3.Time.daysInMonth(this.last.month, this.last.year); - this.last.day++; - if (this.last.day > daysInMonth) { - this.last.day -= daysInMonth; - this.increment_month(); - } - } - }, - increment_month: function increment_month() { - this.last.day = 1; - if (this.has_by_data("BYMONTH")) { - this.by_indices.BYMONTH++; - if (this.by_indices.BYMONTH == this.by_data.BYMONTH.length) { - this.by_indices.BYMONTH = 0; - this.increment_year(1); - } - this.last.month = this.by_data.BYMONTH[this.by_indices.BYMONTH]; - } else { - if (this.rule.freq == "MONTHLY") { - this.last.month += this.rule.interval; - } else { - this.last.month++; - } - this.last.month--; - var years = ICAL3.helpers.trunc(this.last.month / 12); - this.last.month %= 12; - this.last.month++; - if (years != 0) { - this.increment_year(years); - } - } - }, - increment_year: function increment_year(inc) { - this.last.year += inc; - }, - increment_generic: function increment_generic(inc, aDateAttr, aFactor, aNextIncrement) { - this.last[aDateAttr] += inc; - var nextunit = ICAL3.helpers.trunc(this.last[aDateAttr] / aFactor); - this.last[aDateAttr] %= aFactor; - if (nextunit != 0) { - this["increment_" + aNextIncrement](nextunit); - } - }, - has_by_data: function has_by_data(aRuleType) { - return aRuleType in this.rule.parts; - }, - expand_year_days: function expand_year_days(aYear) { - var t3 = new ICAL3.Time(); - this.days = []; - var parts = {}; - var rules = ["BYDAY", "BYWEEKNO", "BYMONTHDAY", "BYMONTH", "BYYEARDAY"]; - for (var p3 in rules) { - if (rules.hasOwnProperty(p3)) { - var part = rules[p3]; - if (part in this.rule.parts) { - parts[part] = this.rule.parts[part]; - } - } - } - if ("BYMONTH" in parts && "BYWEEKNO" in parts) { - var valid = 1; - var validWeeks = {}; - t3.year = aYear; - t3.isDate = true; - for (var monthIdx = 0; monthIdx < this.by_data.BYMONTH.length; monthIdx++) { - var month = this.by_data.BYMONTH[monthIdx]; - t3.month = month; - t3.day = 1; - var first_week = t3.weekNumber(this.rule.wkst); - t3.day = ICAL3.Time.daysInMonth(month, aYear); - var last_week = t3.weekNumber(this.rule.wkst); - for (monthIdx = first_week; monthIdx < last_week; monthIdx++) { - validWeeks[monthIdx] = 1; - } - } - for (var weekIdx = 0; weekIdx < this.by_data.BYWEEKNO.length && valid; weekIdx++) { - var weekno = this.by_data.BYWEEKNO[weekIdx]; - if (weekno < 52) { - valid &= validWeeks[weekIdx]; - } else { - valid = 0; - } - } - if (valid) { - delete parts.BYMONTH; - } else { - delete parts.BYWEEKNO; - } - } - var partCount = Object.keys(parts).length; - if (partCount == 0) { - var t1 = this.dtstart.clone(); - t1.year = this.last.year; - this.days.push(t1.dayOfYear()); - } else if (partCount == 1 && "BYMONTH" in parts) { - for (var monthkey in this.by_data.BYMONTH) { - if (!this.by_data.BYMONTH.hasOwnProperty(monthkey)) { - continue; - } - var t22 = this.dtstart.clone(); - t22.year = aYear; - t22.month = this.by_data.BYMONTH[monthkey]; - t22.isDate = true; - this.days.push(t22.dayOfYear()); - } - } else if (partCount == 1 && "BYMONTHDAY" in parts) { - for (var monthdaykey in this.by_data.BYMONTHDAY) { - if (!this.by_data.BYMONTHDAY.hasOwnProperty(monthdaykey)) { - continue; - } - var t32 = this.dtstart.clone(); - var day_ = this.by_data.BYMONTHDAY[monthdaykey]; - if (day_ < 0) { - var daysInMonth = ICAL3.Time.daysInMonth(t32.month, aYear); - day_ = day_ + daysInMonth + 1; - } - t32.day = day_; - t32.year = aYear; - t32.isDate = true; - this.days.push(t32.dayOfYear()); - } - } else if (partCount == 2 && "BYMONTHDAY" in parts && "BYMONTH" in parts) { - for (var monthkey in this.by_data.BYMONTH) { - if (!this.by_data.BYMONTH.hasOwnProperty(monthkey)) { - continue; - } - var month_ = this.by_data.BYMONTH[monthkey]; - var daysInMonth = ICAL3.Time.daysInMonth(month_, aYear); - for (var monthdaykey in this.by_data.BYMONTHDAY) { - if (!this.by_data.BYMONTHDAY.hasOwnProperty(monthdaykey)) { - continue; - } - var day_ = this.by_data.BYMONTHDAY[monthdaykey]; - if (day_ < 0) { - day_ = day_ + daysInMonth + 1; - } - t3.day = day_; - t3.month = month_; - t3.year = aYear; - t3.isDate = true; - this.days.push(t3.dayOfYear()); - } - } - } else if (partCount == 1 && "BYWEEKNO" in parts) { - } else if (partCount == 2 && "BYWEEKNO" in parts && "BYMONTHDAY" in parts) { - } else if (partCount == 1 && "BYDAY" in parts) { - this.days = this.days.concat(this.expand_by_day(aYear)); - } else if (partCount == 2 && "BYDAY" in parts && "BYMONTH" in parts) { - for (var monthkey in this.by_data.BYMONTH) { - if (!this.by_data.BYMONTH.hasOwnProperty(monthkey)) { - continue; - } - var month = this.by_data.BYMONTH[monthkey]; - var daysInMonth = ICAL3.Time.daysInMonth(month, aYear); - t3.year = aYear; - t3.month = this.by_data.BYMONTH[monthkey]; - t3.day = 1; - t3.isDate = true; - var first_dow = t3.dayOfWeek(); - var doy_offset = t3.dayOfYear() - 1; - t3.day = daysInMonth; - var last_dow = t3.dayOfWeek(); - if (this.has_by_data("BYSETPOS")) { - var set_pos_counter = 0; - var by_month_day = []; - for (var day = 1; day <= daysInMonth; day++) { - t3.day = day; - if (this.is_day_in_byday(t3)) { - by_month_day.push(day); - } - } - for (var spIndex = 0; spIndex < by_month_day.length; spIndex++) { - if (this.check_set_position(spIndex + 1) || this.check_set_position(spIndex - by_month_day.length)) { - this.days.push(doy_offset + by_month_day[spIndex]); - } - } - } else { - for (var daycodedkey in this.by_data.BYDAY) { - if (!this.by_data.BYDAY.hasOwnProperty(daycodedkey)) { - continue; - } - var coded_day = this.by_data.BYDAY[daycodedkey]; - var bydayParts = this.ruleDayOfWeek(coded_day); - var pos = bydayParts[0]; - var dow = bydayParts[1]; - var month_day; - var first_matching_day = (dow + 7 - first_dow) % 7 + 1; - var last_matching_day = daysInMonth - (last_dow + 7 - dow) % 7; - if (pos == 0) { - for (var day = first_matching_day; day <= daysInMonth; day += 7) { - this.days.push(doy_offset + day); - } - } else if (pos > 0) { - month_day = first_matching_day + (pos - 1) * 7; - if (month_day <= daysInMonth) { - this.days.push(doy_offset + month_day); - } - } else { - month_day = last_matching_day + (pos + 1) * 7; - if (month_day > 0) { - this.days.push(doy_offset + month_day); - } - } - } - } - } - this.days.sort(function(a3, b3) { - return a3 - b3; - }); - } else if (partCount == 2 && "BYDAY" in parts && "BYMONTHDAY" in parts) { - var expandedDays = this.expand_by_day(aYear); - for (var daykey in expandedDays) { - if (!expandedDays.hasOwnProperty(daykey)) { - continue; - } - var day = expandedDays[daykey]; - var tt = ICAL3.Time.fromDayOfYear(day, aYear); - if (this.by_data.BYMONTHDAY.indexOf(tt.day) >= 0) { - this.days.push(day); - } - } - } else if (partCount == 3 && "BYDAY" in parts && "BYMONTHDAY" in parts && "BYMONTH" in parts) { - var expandedDays = this.expand_by_day(aYear); - for (var daykey in expandedDays) { - if (!expandedDays.hasOwnProperty(daykey)) { - continue; - } - var day = expandedDays[daykey]; - var tt = ICAL3.Time.fromDayOfYear(day, aYear); - if (this.by_data.BYMONTH.indexOf(tt.month) >= 0 && this.by_data.BYMONTHDAY.indexOf(tt.day) >= 0) { - this.days.push(day); - } - } - } else if (partCount == 2 && "BYDAY" in parts && "BYWEEKNO" in parts) { - var expandedDays = this.expand_by_day(aYear); - for (var daykey in expandedDays) { - if (!expandedDays.hasOwnProperty(daykey)) { - continue; - } - var day = expandedDays[daykey]; - var tt = ICAL3.Time.fromDayOfYear(day, aYear); - var weekno = tt.weekNumber(this.rule.wkst); - if (this.by_data.BYWEEKNO.indexOf(weekno)) { - this.days.push(day); - } - } - } else if (partCount == 3 && "BYDAY" in parts && "BYWEEKNO" in parts && "BYMONTHDAY" in parts) { - } else if (partCount == 1 && "BYYEARDAY" in parts) { - this.days = this.days.concat(this.by_data.BYYEARDAY); - } else { - this.days = []; - } - return 0; - }, - expand_by_day: function expand_by_day(aYear) { - var days_list = []; - var tmp = this.last.clone(); - tmp.year = aYear; - tmp.month = 1; - tmp.day = 1; - tmp.isDate = true; - var start_dow = tmp.dayOfWeek(); - tmp.month = 12; - tmp.day = 31; - tmp.isDate = true; - var end_dow = tmp.dayOfWeek(); - var end_year_day = tmp.dayOfYear(); - for (var daykey in this.by_data.BYDAY) { - if (!this.by_data.BYDAY.hasOwnProperty(daykey)) { - continue; - } - var day = this.by_data.BYDAY[daykey]; - var parts = this.ruleDayOfWeek(day); - var pos = parts[0]; - var dow = parts[1]; - if (pos == 0) { - var tmp_start_doy = (dow + 7 - start_dow) % 7 + 1; - for (var doy = tmp_start_doy; doy <= end_year_day; doy += 7) { - days_list.push(doy); - } - } else if (pos > 0) { - var first; - if (dow >= start_dow) { - first = dow - start_dow + 1; - } else { - first = dow - start_dow + 8; - } - days_list.push(first + (pos - 1) * 7); - } else { - var last; - pos = -pos; - if (dow <= end_dow) { - last = end_year_day - end_dow + dow; - } else { - last = end_year_day - end_dow + dow - 7; - } - days_list.push(last - (pos - 1) * 7); - } - } - return days_list; - }, - is_day_in_byday: function is_day_in_byday(tt) { - for (var daykey in this.by_data.BYDAY) { - if (!this.by_data.BYDAY.hasOwnProperty(daykey)) { - continue; - } - var day = this.by_data.BYDAY[daykey]; - var parts = this.ruleDayOfWeek(day); - var pos = parts[0]; - var dow = parts[1]; - var this_dow = tt.dayOfWeek(); - if (pos == 0 && dow == this_dow || tt.nthWeekDay(dow, pos) == tt.day) { - return 1; - } - } - return 0; - }, - check_set_position: function check_set_position(aPos) { - if (this.has_by_data("BYSETPOS")) { - var idx = this.by_data.BYSETPOS.indexOf(aPos); - return idx !== -1; - } - return false; - }, - sort_byday_rules: function icalrecur_sort_byday_rules(aRules) { - for (var i3 = 0; i3 < aRules.length; i3++) { - for (var j4 = 0; j4 < i3; j4++) { - var one = this.ruleDayOfWeek(aRules[j4], this.rule.wkst)[1]; - var two = this.ruleDayOfWeek(aRules[i3], this.rule.wkst)[1]; - if (one > two) { - var tmp = aRules[i3]; - aRules[i3] = aRules[j4]; - aRules[j4] = tmp; - } - } - } - }, - check_contract_restriction: function check_contract_restriction(aRuleType, v3) { - var indexMapValue = icalrecur_iterator._indexMap[aRuleType]; - var ruleMapValue = icalrecur_iterator._expandMap[this.rule.freq][indexMapValue]; - var pass = false; - if (aRuleType in this.by_data && ruleMapValue == icalrecur_iterator.CONTRACT) { - var ruleType = this.by_data[aRuleType]; - for (var bydatakey in ruleType) { - if (ruleType.hasOwnProperty(bydatakey)) { - if (ruleType[bydatakey] == v3) { - pass = true; - break; - } - } - } - } else { - pass = true; - } - return pass; - }, - check_contracting_rules: function check_contracting_rules() { - var dow = this.last.dayOfWeek(); - var weekNo = this.last.weekNumber(this.rule.wkst); - var doy = this.last.dayOfYear(); - return this.check_contract_restriction("BYSECOND", this.last.second) && this.check_contract_restriction("BYMINUTE", this.last.minute) && this.check_contract_restriction("BYHOUR", this.last.hour) && this.check_contract_restriction("BYDAY", ICAL3.Recur.numericDayToIcalDay(dow)) && this.check_contract_restriction("BYWEEKNO", weekNo) && this.check_contract_restriction("BYMONTHDAY", this.last.day) && this.check_contract_restriction("BYMONTH", this.last.month) && this.check_contract_restriction("BYYEARDAY", doy); - }, - setup_defaults: function setup_defaults(aRuleType, req, deftime) { - var indexMapValue = icalrecur_iterator._indexMap[aRuleType]; - var ruleMapValue = icalrecur_iterator._expandMap[this.rule.freq][indexMapValue]; - if (ruleMapValue != icalrecur_iterator.CONTRACT) { - if (!(aRuleType in this.by_data)) { - this.by_data[aRuleType] = [deftime]; - } - if (this.rule.freq != req) { - return this.by_data[aRuleType][0]; - } - } - return deftime; - }, - toJSON: function() { - var result = Object.create(null); - result.initialized = this.initialized; - result.rule = this.rule.toJSON(); - result.dtstart = this.dtstart.toJSON(); - result.by_data = this.by_data; - result.days = this.days; - result.last = this.last.toJSON(); - result.by_indices = this.by_indices; - result.occurrence_number = this.occurrence_number; - return result; - } - }; - icalrecur_iterator._indexMap = { - "BYSECOND": 0, - "BYMINUTE": 1, - "BYHOUR": 2, - "BYDAY": 3, - "BYMONTHDAY": 4, - "BYYEARDAY": 5, - "BYWEEKNO": 6, - "BYMONTH": 7, - "BYSETPOS": 8 - }; - icalrecur_iterator._expandMap = { - "SECONDLY": [1, 1, 1, 1, 1, 1, 1, 1], - "MINUTELY": [2, 1, 1, 1, 1, 1, 1, 1], - "HOURLY": [2, 2, 1, 1, 1, 1, 1, 1], - "DAILY": [2, 2, 2, 1, 1, 1, 1, 1], - "WEEKLY": [2, 2, 2, 2, 3, 3, 1, 1], - "MONTHLY": [2, 2, 2, 2, 2, 3, 3, 1], - "YEARLY": [2, 2, 2, 2, 2, 2, 2, 2] - }; - icalrecur_iterator.UNKNOWN = 0; - icalrecur_iterator.CONTRACT = 1; - icalrecur_iterator.EXPAND = 2; - icalrecur_iterator.ILLEGAL = 3; - return icalrecur_iterator; - }(); - ICAL3.RecurExpansion = function() { - function formatTime(item) { - return ICAL3.helpers.formatClassType(item, ICAL3.Time); - } - function compareTime(a3, b3) { - return a3.compare(b3); - } - function isRecurringComponent(comp) { - return comp.hasProperty("rdate") || comp.hasProperty("rrule") || comp.hasProperty("recurrence-id"); - } - function RecurExpansion(options) { - this.ruleDates = []; - this.exDates = []; - this.fromData(options); - } - RecurExpansion.prototype = { - complete: false, - ruleIterators: null, - ruleDates: null, - exDates: null, - ruleDateInc: 0, - exDateInc: 0, - exDate: null, - ruleDate: null, - dtstart: null, - last: null, - fromData: function(options) { - var start = ICAL3.helpers.formatClassType(options.dtstart, ICAL3.Time); - if (!start) { - throw new Error(".dtstart (ICAL.Time) must be given"); - } else { - this.dtstart = start; - } - if (options.component) { - this._init(options.component); - } else { - this.last = formatTime(options.last) || start.clone(); - if (!options.ruleIterators) { - throw new Error(".ruleIterators or .component must be given"); - } - this.ruleIterators = options.ruleIterators.map(function(item) { - return ICAL3.helpers.formatClassType(item, ICAL3.RecurIterator); - }); - this.ruleDateInc = options.ruleDateInc; - this.exDateInc = options.exDateInc; - if (options.ruleDates) { - this.ruleDates = options.ruleDates.map(formatTime); - this.ruleDate = this.ruleDates[this.ruleDateInc]; - } - if (options.exDates) { - this.exDates = options.exDates.map(formatTime); - this.exDate = this.exDates[this.exDateInc]; - } - if (typeof options.complete !== "undefined") { - this.complete = options.complete; - } - } - }, - next: function() { - var iter; - var ruleOfDay; - var next; - var compare; - var maxTries = 500; - var currentTry = 0; - while (true) { - if (currentTry++ > maxTries) { - throw new Error("max tries have occured, rule may be impossible to forfill."); - } - next = this.ruleDate; - iter = this._nextRecurrenceIter(this.last); - if (!next && !iter) { - this.complete = true; - break; - } - if (!next || iter && next.compare(iter.last) > 0) { - next = iter.last.clone(); - iter.next(); - } - if (this.ruleDate === next) { - this._nextRuleDay(); - } - this.last = next; - if (this.exDate) { - compare = this.exDate.compare(this.last); - if (compare < 0) { - this._nextExDay(); - } - if (compare === 0) { - this._nextExDay(); - continue; - } - } - return this.last; - } - }, - toJSON: function() { - function toJSON(item) { - return item.toJSON(); - } - var result = Object.create(null); - result.ruleIterators = this.ruleIterators.map(toJSON); - if (this.ruleDates) { - result.ruleDates = this.ruleDates.map(toJSON); - } - if (this.exDates) { - result.exDates = this.exDates.map(toJSON); - } - result.ruleDateInc = this.ruleDateInc; - result.exDateInc = this.exDateInc; - result.last = this.last.toJSON(); - result.dtstart = this.dtstart.toJSON(); - result.complete = this.complete; - return result; - }, - _extractDates: function(component, propertyName) { - function handleProp(prop2) { - idx = ICAL3.helpers.binsearchInsert(result, prop2, compareTime); - result.splice(idx, 0, prop2); - } - var result = []; - var props = component.getAllProperties(propertyName); - var len = props.length; - var i3 = 0; - var prop; - var idx; - for (; i3 < len; i3++) { - props[i3].getValues().forEach(handleProp); - } - return result; - }, - _init: function(component) { - this.ruleIterators = []; - this.last = this.dtstart.clone(); - if (!isRecurringComponent(component)) { - this.ruleDate = this.last.clone(); - this.complete = true; - return; - } - if (component.hasProperty("rdate")) { - this.ruleDates = this._extractDates(component, "rdate"); - if (this.ruleDates[0] && this.ruleDates[0].compare(this.dtstart) < 0) { - this.ruleDateInc = 0; - this.last = this.ruleDates[0].clone(); - } else { - this.ruleDateInc = ICAL3.helpers.binsearchInsert(this.ruleDates, this.last, compareTime); - } - this.ruleDate = this.ruleDates[this.ruleDateInc]; - } - if (component.hasProperty("rrule")) { - var rules = component.getAllProperties("rrule"); - var i3 = 0; - var len = rules.length; - var rule; - var iter; - for (; i3 < len; i3++) { - rule = rules[i3].getFirstValue(); - iter = rule.iterator(this.dtstart); - this.ruleIterators.push(iter); - iter.next(); - } - } - if (component.hasProperty("exdate")) { - this.exDates = this._extractDates(component, "exdate"); - this.exDateInc = ICAL3.helpers.binsearchInsert(this.exDates, this.last, compareTime); - this.exDate = this.exDates[this.exDateInc]; - } - }, - _nextExDay: function() { - this.exDate = this.exDates[++this.exDateInc]; - }, - _nextRuleDay: function() { - this.ruleDate = this.ruleDates[++this.ruleDateInc]; - }, - _nextRecurrenceIter: function() { - var iters = this.ruleIterators; - if (iters.length === 0) { - return null; - } - var len = iters.length; - var iter; - var iterTime; - var iterIdx = 0; - var chosenIter; - for (; iterIdx < len; iterIdx++) { - iter = iters[iterIdx]; - iterTime = iter.last; - if (iter.completed) { - len--; - if (iterIdx !== 0) { - iterIdx--; - } - iters.splice(iterIdx, 1); - continue; - } - if (!chosenIter || chosenIter.last.compare(iterTime) > 0) { - chosenIter = iter; - } - } - return chosenIter; - } - }; - return RecurExpansion; - }(); - ICAL3.Event = function() { - function Event3(component, options) { - if (!(component instanceof ICAL3.Component)) { - options = component; - component = null; - } - if (component) { - this.component = component; - } else { - this.component = new ICAL3.Component("vevent"); - } - this._rangeExceptionCache = Object.create(null); - this.exceptions = Object.create(null); - this.rangeExceptions = []; - if (options && options.strictExceptions) { - this.strictExceptions = options.strictExceptions; - } - if (options && options.exceptions) { - options.exceptions.forEach(this.relateException, this); - } else if (this.component.parent && !this.isRecurrenceException()) { - this.component.parent.getAllSubcomponents("vevent").forEach(function(event) { - if (event.hasProperty("recurrence-id")) { - this.relateException(event); - } - }, this); - } - } - Event3.prototype = { - THISANDFUTURE: "THISANDFUTURE", - exceptions: null, - strictExceptions: false, - relateException: function(obj) { - if (this.isRecurrenceException()) { - throw new Error("cannot relate exception to exceptions"); - } - if (obj instanceof ICAL3.Component) { - obj = new ICAL3.Event(obj); - } - if (this.strictExceptions && obj.uid !== this.uid) { - throw new Error("attempted to relate unrelated exception"); - } - var id = obj.recurrenceId.toString(); - this.exceptions[id] = obj; - if (obj.modifiesFuture()) { - var item = [ - obj.recurrenceId.toUnixTime(), - id - ]; - var idx = ICAL3.helpers.binsearchInsert(this.rangeExceptions, item, compareRangeException); - this.rangeExceptions.splice(idx, 0, item); - } - }, - modifiesFuture: function() { - if (!this.component.hasProperty("recurrence-id")) { - return false; - } - var range = this.component.getFirstProperty("recurrence-id").getParameter("range"); - return range === this.THISANDFUTURE; - }, - findRangeException: function(time) { - if (!this.rangeExceptions.length) { - return null; - } - var utc = time.toUnixTime(); - var idx = ICAL3.helpers.binsearchInsert(this.rangeExceptions, [utc], compareRangeException); - idx -= 1; - if (idx < 0) { - return null; - } - var rangeItem = this.rangeExceptions[idx]; - if (utc < rangeItem[0]) { - return null; - } - return rangeItem[1]; - }, - getOccurrenceDetails: function(occurrence) { - var id = occurrence.toString(); - var utcId = occurrence.convertToZone(ICAL3.Timezone.utcTimezone).toString(); - var item; - var result = { - recurrenceId: occurrence - }; - if (id in this.exceptions) { - item = result.item = this.exceptions[id]; - result.startDate = item.startDate; - result.endDate = item.endDate; - result.item = item; - } else if (utcId in this.exceptions) { - item = this.exceptions[utcId]; - result.startDate = item.startDate; - result.endDate = item.endDate; - result.item = item; - } else { - var rangeExceptionId = this.findRangeException(occurrence); - var end; - if (rangeExceptionId) { - var exception = this.exceptions[rangeExceptionId]; - result.item = exception; - var startDiff = this._rangeExceptionCache[rangeExceptionId]; - if (!startDiff) { - var original = exception.recurrenceId.clone(); - var newStart = exception.startDate.clone(); - original.zone = newStart.zone; - startDiff = newStart.subtractDate(original); - this._rangeExceptionCache[rangeExceptionId] = startDiff; - } - var start = occurrence.clone(); - start.zone = exception.startDate.zone; - start.addDuration(startDiff); - end = start.clone(); - end.addDuration(exception.duration); - result.startDate = start; - result.endDate = end; - } else { - end = occurrence.clone(); - end.addDuration(this.duration); - result.endDate = end; - result.startDate = occurrence; - result.item = this; - } - } - return result; - }, - iterator: function(startTime) { - return new ICAL3.RecurExpansion({ - component: this.component, - dtstart: startTime || this.startDate - }); - }, - isRecurring: function() { - var comp = this.component; - return comp.hasProperty("rrule") || comp.hasProperty("rdate"); - }, - isRecurrenceException: function() { - return this.component.hasProperty("recurrence-id"); - }, - getRecurrenceTypes: function() { - var rules = this.component.getAllProperties("rrule"); - var i3 = 0; - var len = rules.length; - var result = Object.create(null); - for (; i3 < len; i3++) { - var value = rules[i3].getFirstValue(); - result[value.freq] = true; - } - return result; - }, - get uid() { - return this._firstProp("uid"); - }, - set uid(value) { - this._setProp("uid", value); - }, - get startDate() { - return this._firstProp("dtstart"); - }, - set startDate(value) { - this._setTime("dtstart", value); - }, - get endDate() { - var endDate = this._firstProp("dtend"); - if (!endDate) { - var duration = this._firstProp("duration"); - endDate = this.startDate.clone(); - if (duration) { - endDate.addDuration(duration); - } else if (endDate.isDate) { - endDate.day += 1; - } - } - return endDate; - }, - set endDate(value) { - if (this.component.hasProperty("duration")) { - this.component.removeProperty("duration"); - } - this._setTime("dtend", value); - }, - get duration() { - var duration = this._firstProp("duration"); - if (!duration) { - return this.endDate.subtractDateTz(this.startDate); - } - return duration; - }, - set duration(value) { - if (this.component.hasProperty("dtend")) { - this.component.removeProperty("dtend"); - } - this._setProp("duration", value); - }, - get location() { - return this._firstProp("location"); - }, - set location(value) { - return this._setProp("location", value); - }, - get attendees() { - return this.component.getAllProperties("attendee"); - }, - get summary() { - return this._firstProp("summary"); - }, - set summary(value) { - this._setProp("summary", value); - }, - get description() { - return this._firstProp("description"); - }, - set description(value) { - this._setProp("description", value); - }, - get color() { - return this._firstProp("color"); - }, - set color(value) { - this._setProp("color", value); - }, - get organizer() { - return this._firstProp("organizer"); - }, - set organizer(value) { - this._setProp("organizer", value); - }, - get sequence() { - return this._firstProp("sequence"); - }, - set sequence(value) { - this._setProp("sequence", value); - }, - get recurrenceId() { - return this._firstProp("recurrence-id"); - }, - set recurrenceId(value) { - this._setTime("recurrence-id", value); - }, - _setTime: function(propName, time) { - var prop = this.component.getFirstProperty(propName); - if (!prop) { - prop = new ICAL3.Property(propName); - this.component.addProperty(prop); - } - if (time.zone === ICAL3.Timezone.localTimezone || time.zone === ICAL3.Timezone.utcTimezone) { - prop.removeParameter("tzid"); - } else { - prop.setParameter("tzid", time.zone.tzid); - } - prop.setValue(time); - }, - _setProp: function(name, value) { - this.component.updatePropertyWithValue(name, value); - }, - _firstProp: function(name) { - return this.component.getFirstPropertyValue(name); - }, - toString: function() { - return this.component.toString(); - } - }; - function compareRangeException(a3, b3) { - if (a3[0] > b3[0]) - return 1; - if (b3[0] > a3[0]) - return -1; - return 0; - } - return Event3; - }(); - ICAL3.ComponentParser = function() { - function ComponentParser(options) { - if (typeof options === "undefined") { - options = {}; - } - var key; - for (key in options) { - if (options.hasOwnProperty(key)) { - this[key] = options[key]; - } - } - } - ComponentParser.prototype = { - parseEvent: true, - parseTimezone: true, - oncomplete: function() { - }, - onerror: function(err) { - }, - ontimezone: function(component) { - }, - onevent: function(component) { - }, - process: function(ical) { - if (typeof ical === "string") { - ical = ICAL3.parse(ical); - } - if (!(ical instanceof ICAL3.Component)) { - ical = new ICAL3.Component(ical); - } - var components = ical.getAllSubcomponents(); - var i3 = 0; - var len = components.length; - var component; - for (; i3 < len; i3++) { - component = components[i3]; - switch (component.name) { - case "vtimezone": - if (this.parseTimezone) { - var tzid = component.getFirstPropertyValue("tzid"); - if (tzid) { - this.ontimezone(new ICAL3.Timezone({ - tzid, - component - })); - } - } - break; - case "vevent": - if (this.parseEvent) { - this.onevent(new ICAL3.Event(component)); - } - break; - default: - continue; - } - } - this.oncomplete(); - } - }; - return ComponentParser; - }(); - } -}); - -// node_modules/object-assign/index.js -var require_object_assign = __commonJS({ - "node_modules/object-assign/index.js"(exports, module2) { - "use strict"; - var getOwnPropertySymbols = Object.getOwnPropertySymbols; - var hasOwnProperty2 = Object.prototype.hasOwnProperty; - var propIsEnumerable = Object.prototype.propertyIsEnumerable; - function toObject(val) { - if (val === null || val === void 0) { - throw new TypeError("Object.assign cannot be called with null or undefined"); - } - return Object(val); - } - function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - var test1 = new String("abc"); - test1[5] = "de"; - if (Object.getOwnPropertyNames(test1)[0] === "5") { - return false; - } - var test2 = {}; - for (var i3 = 0; i3 < 10; i3++) { - test2["_" + String.fromCharCode(i3)] = i3; - } - var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { - return test2[n2]; - }); - if (order2.join("") !== "0123456789") { - return false; - } - var test3 = {}; - "abcdefghijklmnopqrst".split("").forEach(function(letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { - return false; - } - return true; - } catch (err) { - return false; - } - } - module2.exports = shouldUseNative() ? Object.assign : function(target, source) { - var from; - var to = toObject(target); - var symbols; - for (var s3 = 1; s3 < arguments.length; s3++) { - from = Object(arguments[s3]); - for (var key in from) { - if (hasOwnProperty2.call(from, key)) { - to[key] = from[key]; - } - } - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i3 = 0; i3 < symbols.length; i3++) { - if (propIsEnumerable.call(from, symbols[i3])) { - to[symbols[i3]] = from[symbols[i3]]; - } - } - } - } - return to; - }; - } -}); - -// node_modules/react/cjs/react.development.js -var require_react_development = __commonJS({ - "node_modules/react/cjs/react.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var _assign = require_object_assign(); - var ReactVersion = "17.0.2"; - var REACT_ELEMENT_TYPE = 60103; - var REACT_PORTAL_TYPE = 60106; - exports.Fragment = 60107; - exports.StrictMode = 60108; - exports.Profiler = 60114; - var REACT_PROVIDER_TYPE = 60109; - var REACT_CONTEXT_TYPE = 60110; - var REACT_FORWARD_REF_TYPE = 60112; - exports.Suspense = 60113; - var REACT_SUSPENSE_LIST_TYPE = 60120; - var REACT_MEMO_TYPE = 60115; - var REACT_LAZY_TYPE = 60116; - var REACT_BLOCK_TYPE = 60121; - var REACT_SERVER_BLOCK_TYPE = 60122; - var REACT_FUNDAMENTAL_TYPE = 60117; - var REACT_SCOPE_TYPE = 60119; - var REACT_OPAQUE_ID_TYPE = 60128; - var REACT_DEBUG_TRACING_MODE_TYPE = 60129; - var REACT_OFFSCREEN_TYPE = 60130; - var REACT_LEGACY_HIDDEN_TYPE = 60131; - if (typeof Symbol === "function" && Symbol.for) { - var symbolFor = Symbol.for; - REACT_ELEMENT_TYPE = symbolFor("react.element"); - REACT_PORTAL_TYPE = symbolFor("react.portal"); - exports.Fragment = symbolFor("react.fragment"); - exports.StrictMode = symbolFor("react.strict_mode"); - exports.Profiler = symbolFor("react.profiler"); - REACT_PROVIDER_TYPE = symbolFor("react.provider"); - REACT_CONTEXT_TYPE = symbolFor("react.context"); - REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref"); - exports.Suspense = symbolFor("react.suspense"); - REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list"); - REACT_MEMO_TYPE = symbolFor("react.memo"); - REACT_LAZY_TYPE = symbolFor("react.lazy"); - REACT_BLOCK_TYPE = symbolFor("react.block"); - REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block"); - REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental"); - REACT_SCOPE_TYPE = symbolFor("react.scope"); - REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id"); - REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode"); - REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen"); - REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden"); - } - var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var ReactCurrentDispatcher = { - current: null - }; - var ReactCurrentBatchConfig = { - transition: 0 - }; - var ReactCurrentOwner = { - current: null - }; - var ReactDebugCurrentFrame = {}; - var currentExtraStackFrame = null; - function setExtraStackFrame(stack) { - { - currentExtraStackFrame = stack; - } - } - { - ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { - { - currentExtraStackFrame = stack; - } - }; - ReactDebugCurrentFrame.getCurrentStack = null; - ReactDebugCurrentFrame.getStackAddendum = function() { - var stack = ""; - if (currentExtraStackFrame) { - stack += currentExtraStackFrame; - } - var impl = ReactDebugCurrentFrame.getCurrentStack; - if (impl) { - stack += impl() || ""; - } - return stack; - }; - } - var IsSomeRendererActing = { - current: false - }; - var ReactSharedInternals = { - ReactCurrentDispatcher, - ReactCurrentBatchConfig, - ReactCurrentOwner, - IsSomeRendererActing, - assign: _assign - }; - { - ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; - } - function warn(format) { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - function error(format) { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return "" + item; - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var didWarnStateUpdateForUnmountedComponent = {}; - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; - var warningKey = componentName + "." + callerName; - if (didWarnStateUpdateForUnmountedComponent[warningKey]) { - return; - } - error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); - didWarnStateUpdateForUnmountedComponent[warningKey] = true; - } - } - var ReactNoopUpdateQueue = { - isMounted: function(publicInstance) { - return false; - }, - enqueueForceUpdate: function(publicInstance, callback, callerName) { - warnNoop(publicInstance, "forceUpdate"); - }, - enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { - warnNoop(publicInstance, "replaceState"); - }, - enqueueSetState: function(publicInstance, partialState, callback, callerName) { - warnNoop(publicInstance, "setState"); - } - }; - var emptyObject = {}; - { - Object.freeze(emptyObject); - } - function Component5(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - Component5.prototype.isReactComponent = {}; - Component5.prototype.setState = function(partialState, callback) { - if (!(typeof partialState === "object" || typeof partialState === "function" || partialState == null)) { - { - throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); - } - } - this.updater.enqueueSetState(this, partialState, callback, "setState"); - }; - Component5.prototype.forceUpdate = function(callback) { - this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); - }; - { - var deprecatedAPIs = { - isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], - replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] - }; - var defineDeprecationWarning = function(methodName, info) { - Object.defineProperty(Component5.prototype, methodName, { - get: function() { - warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); - return void 0; - } - }); - }; - for (var fnName in deprecatedAPIs) { - if (deprecatedAPIs.hasOwnProperty(fnName)) { - defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); - } - } - } - function ComponentDummy() { - } - ComponentDummy.prototype = Component5.prototype; - function PureComponent2(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - var pureComponentPrototype = PureComponent2.prototype = new ComponentDummy(); - pureComponentPrototype.constructor = PureComponent2; - _assign(pureComponentPrototype, Component5.prototype); - pureComponentPrototype.isPureReactComponent = true; - function createRef2() { - var refObject = { - current: null - }; - { - Object.seal(refObject); - } - return refObject; - } - function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentName(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case exports.Fragment: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case exports.Profiler: - return "Profiler"; - case exports.StrictMode: - return "StrictMode"; - case exports.Suspense: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - return getComponentName(type.type); - case REACT_BLOCK_TYPE: - return getComponentName(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentName(init(payload)); - } catch (x3) { - return null; - } - } - } - } - return null; - } - var hasOwnProperty2 = Object.prototype.hasOwnProperty; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config2) { - { - if (hasOwnProperty2.call(config2, "ref")) { - var getter = Object.getOwnPropertyDescriptor(config2, "ref").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config2.ref !== void 0; - } - function hasValidKey(config2) { - { - if (hasOwnProperty2.call(config2, "key")) { - var getter = Object.getOwnPropertyDescriptor(config2, "key").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config2.key !== void 0; - } - function defineKeyPropWarningGetter(props, displayName) { - var warnAboutAccessingKey = function() { - { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function defineRefPropWarningGetter(props, displayName) { - var warnAboutAccessingRef = function() { - { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, "ref", { - get: warnAboutAccessingRef, - configurable: true - }); - } - function warnIfStringRefCannotBeAutoConverted(config2) { - { - if (typeof config2.ref === "string" && ReactCurrentOwner.current && config2.__self && ReactCurrentOwner.current.stateNode !== config2.__self) { - var componentName = getComponentName(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config2.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - var ReactElement = function(type, key, ref, self2, source, owner, props) { - var element = { - $$typeof: REACT_ELEMENT_TYPE, - type, - key, - ref, - props, - _owner: owner - }; - { - element._store = {}; - Object.defineProperty(element._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: false - }); - Object.defineProperty(element, "_self", { - configurable: false, - enumerable: false, - writable: false, - value: self2 - }); - Object.defineProperty(element, "_source", { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - function createElement7(type, config2, children) { - var propName; - var props = {}; - var key = null; - var ref = null; - var self2 = null; - var source = null; - if (config2 != null) { - if (hasValidRef(config2)) { - ref = config2.ref; - { - warnIfStringRefCannotBeAutoConverted(config2); - } - } - if (hasValidKey(config2)) { - key = "" + config2.key; - } - self2 = config2.__self === void 0 ? null : config2.__self; - source = config2.__source === void 0 ? null : config2.__source; - for (propName in config2) { - if (hasOwnProperty2.call(config2, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config2[propName]; - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i3 = 0; i3 < childrenLength; i3++) { - childArray[i3] = arguments[i3 + 2]; - } - { - if (Object.freeze) { - Object.freeze(childArray); - } - } - props.children = childArray; - } - if (type && type.defaultProps) { - var defaultProps = type.defaultProps; - for (propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } - { - if (key || ref) { - var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - } - return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); - } - function cloneAndReplaceKey(oldElement, newKey) { - var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); - return newElement; - } - function cloneElement(element, config2, children) { - if (!!(element === null || element === void 0)) { - { - throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); - } - } - var propName; - var props = _assign({}, element.props); - var key = element.key; - var ref = element.ref; - var self2 = element._self; - var source = element._source; - var owner = element._owner; - if (config2 != null) { - if (hasValidRef(config2)) { - ref = config2.ref; - owner = ReactCurrentOwner.current; - } - if (hasValidKey(config2)) { - key = "" + config2.key; - } - var defaultProps; - if (element.type && element.type.defaultProps) { - defaultProps = element.type.defaultProps; - } - for (propName in config2) { - if (hasOwnProperty2.call(config2, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - if (config2[propName] === void 0 && defaultProps !== void 0) { - props[propName] = defaultProps[propName]; - } else { - props[propName] = config2[propName]; - } - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i3 = 0; i3 < childrenLength; i3++) { - childArray[i3] = arguments[i3 + 2]; - } - props.children = childArray; - } - return ReactElement(element.type, key, ref, self2, source, owner, props); - } - function isValidElement(object) { - return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - var SEPARATOR = "."; - var SUBSEPARATOR = ":"; - function escape2(key) { - var escapeRegex = /[=:]/g; - var escaperLookup = { - "=": "=0", - ":": "=2" - }; - var escapedString = key.replace(escapeRegex, function(match) { - return escaperLookup[match]; - }); - return "$" + escapedString; - } - var didWarnAboutMaps = false; - var userProvidedKeyEscapeRegex = /\/+/g; - function escapeUserProvidedKey(text) { - return text.replace(userProvidedKeyEscapeRegex, "$&/"); - } - function getElementKey(element, index) { - if (typeof element === "object" && element !== null && element.key != null) { - return escape2("" + element.key); - } - return index.toString(36); - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if (type === "undefined" || type === "boolean") { - children = null; - } - var invokeCallback = false; - if (children === null) { - invokeCallback = true; - } else { - switch (type) { - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - } - } - } - if (invokeCallback) { - var _child = children; - var mappedChild = callback(_child); - var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; - if (Array.isArray(mappedChild)) { - var escapedChildKey = ""; - if (childKey != null) { - escapedChildKey = escapeUserProvidedKey(childKey) + "/"; - } - mapIntoArray(mappedChild, array, escapedChildKey, "", function(c3) { - return c3; - }); - } else if (mappedChild != null) { - if (isValidElement(mappedChild)) { - mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey); - } - array.push(mappedChild); - } - return 1; - } - var child; - var nextName; - var subtreeCount = 0; - var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; - if (Array.isArray(children)) { - for (var i3 = 0; i3 < children.length; i3++) { - child = children[i3]; - nextName = nextNamePrefix + getElementKey(child, i3); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else { - var iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === "function") { - var iterableChildren = children; - { - if (iteratorFn === iterableChildren.entries) { - if (!didWarnAboutMaps) { - warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); - } - didWarnAboutMaps = true; - } - } - var iterator = iteratorFn.call(iterableChildren); - var step; - var ii = 0; - while (!(step = iterator.next()).done) { - child = step.value; - nextName = nextNamePrefix + getElementKey(child, ii++); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else if (type === "object") { - var childrenString = "" + children; - { - { - throw Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); - } - } - } - } - return subtreeCount; - } - function mapChildren(children, func, context) { - if (children == null) { - return children; - } - var result = []; - var count = 0; - mapIntoArray(children, result, "", "", function(child) { - return func.call(context, child, count++); - }); - return result; - } - function countChildren(children) { - var n2 = 0; - mapChildren(children, function() { - n2++; - }); - return n2; - } - function forEachChildren(children, forEachFunc, forEachContext) { - mapChildren(children, function() { - forEachFunc.apply(this, arguments); - }, forEachContext); - } - function toArray(children) { - return mapChildren(children, function(child) { - return child; - }) || []; - } - function onlyChild(children) { - if (!isValidElement(children)) { - { - throw Error("React.Children.only expected to receive a single React element child."); - } - } - return children; - } - function createContext3(defaultValue, calculateChangedBits) { - if (calculateChangedBits === void 0) { - calculateChangedBits = null; - } else { - { - if (calculateChangedBits !== null && typeof calculateChangedBits !== "function") { - error("createContext: Expected the optional second argument to be a function. Instead received: %s", calculateChangedBits); - } - } - } - var context = { - $$typeof: REACT_CONTEXT_TYPE, - _calculateChangedBits: calculateChangedBits, - _currentValue: defaultValue, - _currentValue2: defaultValue, - _threadCount: 0, - Provider: null, - Consumer: null - }; - context.Provider = { - $$typeof: REACT_PROVIDER_TYPE, - _context: context - }; - var hasWarnedAboutUsingNestedContextConsumers = false; - var hasWarnedAboutUsingConsumerProvider = false; - var hasWarnedAboutDisplayNameOnConsumer = false; - { - var Consumer = { - $$typeof: REACT_CONTEXT_TYPE, - _context: context, - _calculateChangedBits: context._calculateChangedBits - }; - Object.defineProperties(Consumer, { - Provider: { - get: function() { - if (!hasWarnedAboutUsingConsumerProvider) { - hasWarnedAboutUsingConsumerProvider = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Provider; - }, - set: function(_Provider) { - context.Provider = _Provider; - } - }, - _currentValue: { - get: function() { - return context._currentValue; - }, - set: function(_currentValue) { - context._currentValue = _currentValue; - } - }, - _currentValue2: { - get: function() { - return context._currentValue2; - }, - set: function(_currentValue2) { - context._currentValue2 = _currentValue2; - } - }, - _threadCount: { - get: function() { - return context._threadCount; - }, - set: function(_threadCount) { - context._threadCount = _threadCount; - } - }, - Consumer: { - get: function() { - if (!hasWarnedAboutUsingNestedContextConsumers) { - hasWarnedAboutUsingNestedContextConsumers = true; - error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); - } - return context.Consumer; - } - }, - displayName: { - get: function() { - return context.displayName; - }, - set: function(displayName) { - if (!hasWarnedAboutDisplayNameOnConsumer) { - warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); - hasWarnedAboutDisplayNameOnConsumer = true; - } - } - } - }); - context.Consumer = Consumer; - } - { - context._currentRenderer = null; - context._currentRenderer2 = null; - } - return context; - } - var Uninitialized = -1; - var Pending = 0; - var Resolved = 1; - var Rejected = 2; - function lazyInitializer(payload) { - if (payload._status === Uninitialized) { - var ctor = payload._result; - var thenable = ctor(); - var pending = payload; - pending._status = Pending; - pending._result = thenable; - thenable.then(function(moduleObject) { - if (payload._status === Pending) { - var defaultExport = moduleObject.default; - { - if (defaultExport === void 0) { - error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); - } - } - var resolved = payload; - resolved._status = Resolved; - resolved._result = defaultExport; - } - }, function(error2) { - if (payload._status === Pending) { - var rejected = payload; - rejected._status = Rejected; - rejected._result = error2; - } - }); - } - if (payload._status === Resolved) { - return payload._result; - } else { - throw payload._result; - } - } - function lazy(ctor) { - var payload = { - _status: -1, - _result: ctor - }; - var lazyType = { - $$typeof: REACT_LAZY_TYPE, - _payload: payload, - _init: lazyInitializer - }; - { - var defaultProps; - var propTypes; - Object.defineProperties(lazyType, { - defaultProps: { - configurable: true, - get: function() { - return defaultProps; - }, - set: function(newDefaultProps) { - error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - defaultProps = newDefaultProps; - Object.defineProperty(lazyType, "defaultProps", { - enumerable: true - }); - } - }, - propTypes: { - configurable: true, - get: function() { - return propTypes; - }, - set: function(newPropTypes) { - error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); - propTypes = newPropTypes; - Object.defineProperty(lazyType, "propTypes", { - enumerable: true - }); - } - } - }); - } - return lazyType; - } - function forwardRef(render4) { - { - if (render4 != null && render4.$$typeof === REACT_MEMO_TYPE) { - error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); - } else if (typeof render4 !== "function") { - error("forwardRef requires a render function but was given %s.", render4 === null ? "null" : typeof render4); - } else { - if (render4.length !== 0 && render4.length !== 2) { - error("forwardRef render functions accept exactly two parameters: props and ref. %s", render4.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); - } - } - if (render4 != null) { - if (render4.defaultProps != null || render4.propTypes != null) { - error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); - } - } - } - var elementType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: render4 - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (render4.displayName == null) { - render4.displayName = name; - } - } - }); - } - return elementType; - } - var enableScopeAPI = false; - function isValidElementType(type) { - if (typeof type === "string" || typeof type === "function") { - return true; - } - if (type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) { - return true; - } - if (typeof type === "object" && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) { - return true; - } - } - return false; - } - function memo(type, compare) { - { - if (!isValidElementType(type)) { - error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); - } - } - var elementType = { - $$typeof: REACT_MEMO_TYPE, - type, - compare: compare === void 0 ? null : compare - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - if (type.displayName == null) { - type.displayName = name; - } - } - }); - } - return elementType; - } - function resolveDispatcher() { - var dispatcher = ReactCurrentDispatcher.current; - if (!(dispatcher !== null)) { - { - throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); - } - } - return dispatcher; - } - function useContext(Context, unstable_observedBits) { - var dispatcher = resolveDispatcher(); - { - if (unstable_observedBits !== void 0) { - error("useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", unstable_observedBits, typeof unstable_observedBits === "number" && Array.isArray(arguments[2]) ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" : ""); - } - if (Context._context !== void 0) { - var realContext = Context._context; - if (realContext.Consumer === Context) { - error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); - } else if (realContext.Provider === Context) { - error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); - } - } - } - return dispatcher.useContext(Context, unstable_observedBits); - } - function useState4(initialState) { - var dispatcher = resolveDispatcher(); - return dispatcher.useState(initialState); - } - function useReducer(reducer, initialArg, init) { - var dispatcher = resolveDispatcher(); - return dispatcher.useReducer(reducer, initialArg, init); - } - function useRef2(initialValue) { - var dispatcher = resolveDispatcher(); - return dispatcher.useRef(initialValue); - } - function useEffect2(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useEffect(create, deps); - } - function useLayoutEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useLayoutEffect(create, deps); - } - function useCallback(callback, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useCallback(callback, deps); - } - function useMemo(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useMemo(create, deps); - } - function useImperativeHandle(ref, create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useImperativeHandle(ref, create, deps); - } - function useDebugValue(value, formatterFn) { - { - var dispatcher = resolveDispatcher(); - return dispatcher.useDebugValue(value, formatterFn); - } - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: _assign({}, props, { - value: prevLog - }), - info: _assign({}, props, { - value: prevInfo - }), - warn: _assign({}, props, { - value: prevWarn - }), - error: _assign({}, props, { - value: prevError - }), - group: _assign({}, props, { - value: prevGroup - }), - groupCollapsed: _assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: _assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x3) { - var match = x3.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x3) { - control = x3; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x3) { - control = x3; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x3) { - control = x3; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s3 = sampleLines.length - 1; - var c3 = controlLines.length - 1; - while (s3 >= 1 && c3 >= 0 && sampleLines[s3] !== controlLines[c3]) { - c3--; - } - for (; s3 >= 1 && c3 >= 0; s3--, c3--) { - if (sampleLines[s3] !== controlLines[c3]) { - if (s3 !== 1 || c3 !== 1) { - do { - s3--; - c3--; - if (c3 < 0 || sampleLines[s3] !== controlLines[c3]) { - var _frame = "\n" + sampleLines[s3].replace(" at new ", " at "); - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s3 >= 1 && c3 >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component6) { - var prototype = Component6.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case exports.Suspense: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_BLOCK_TYPE: - return describeFunctionComponentFrame(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x3) { - } - } - } - } - return ""; - } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - var has = Function.call.bind(Object.prototype.hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; - try { - if (typeof typeSpecs[typeSpecName] !== "function") { - var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); - err.name = "Invariant Violation"; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error("Failed %s type: %s", location, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - setExtraStackFrame(stack); - } else { - setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - function getDeclarationErrorAddendum() { - if (ReactCurrentOwner.current) { - var name = getComponentName(ReactCurrentOwner.current.type); - if (name) { - return "\n\nCheck the render method of `" + name + "`."; - } - } - return ""; - } - function getSourceInfoErrorAddendum(source) { - if (source !== void 0) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ""); - var lineNumber = source.lineNumber; - return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; - } - return ""; - } - function getSourceInfoErrorAddendumForProps(elementProps) { - if (elementProps !== null && elementProps !== void 0) { - return getSourceInfoErrorAddendum(elementProps.__source); - } - return ""; - } - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } - } - return info; - } - function validateExplicitKey(element, parentType) { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - var childOwner = ""; - if (element && element._owner && element._owner !== ReactCurrentOwner.current) { - childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; - } - { - setCurrentlyValidatingElement$1(element); - error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - function validateChildKeys(node, parentType) { - if (typeof node !== "object") { - return; - } - if (Array.isArray(node)) { - for (var i3 = 0; i3 < node.length; i3++) { - var child = node[i3]; - if (isValidElement(child)) { - validateExplicitKey(child, parentType); - } - } - } else if (isValidElement(node)) { - if (node._store) { - node._store.validated = true; - } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === "function") { - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType); - } - } - } - } - } - } - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === void 0 || typeof type === "string") { - return; - } - var propTypes; - if (typeof type === "function") { - propTypes = type.propTypes; - } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - var name = getComponentName(type); - checkPropTypes(propTypes, element.props, "prop", name, element); - } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; - var _name = getComponentName(type); - error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); - } - if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { - error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); - } - } - } - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i3 = 0; i3 < keys.length; i3++) { - var key = keys[i3]; - if (key !== "children" && key !== "key") { - setCurrentlyValidatingElement$1(fragment); - error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error("Invalid attribute `ref` supplied to `React.Fragment`."); - setCurrentlyValidatingElement$1(null); - } - } - } - function createElementWithValidation(type, props, children) { - var validType = isValidElementType(type); - if (!validType) { - var info = ""; - if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { - info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendumForProps(props); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = "null"; - } else if (Array.isArray(type)) { - typeString = "array"; - } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentName(type.type) || "Unknown") + " />"; - info = " Did you accidentally export a JSX literal instead of a component?"; - } else { - typeString = typeof type; - } - { - error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); - } - } - var element = createElement7.apply(this, arguments); - if (element == null) { - return element; - } - if (validType) { - for (var i3 = 2; i3 < arguments.length; i3++) { - validateChildKeys(arguments[i3], type); - } - } - if (type === exports.Fragment) { - validateFragmentProps(element); - } else { - validatePropTypes(element); - } - return element; - } - var didWarnAboutDeprecatedCreateFactory = false; - function createFactoryWithValidation(type) { - var validatedFactory = createElementWithValidation.bind(null, type); - validatedFactory.type = type; - { - if (!didWarnAboutDeprecatedCreateFactory) { - didWarnAboutDeprecatedCreateFactory = true; - warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); - } - Object.defineProperty(validatedFactory, "type", { - enumerable: false, - get: function() { - warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); - Object.defineProperty(this, "type", { - value: type - }); - return type; - } - }); - } - return validatedFactory; - } - function cloneElementWithValidation(element, props, children) { - var newElement = cloneElement.apply(this, arguments); - for (var i3 = 2; i3 < arguments.length; i3++) { - validateChildKeys(arguments[i3], newElement.type); - } - validatePropTypes(newElement); - return newElement; - } - { - try { - var frozenObject = Object.freeze({}); - new Map([[frozenObject, null]]); - new Set([frozenObject]); - } catch (e3) { - } - } - var createElement$1 = createElementWithValidation; - var cloneElement$1 = cloneElementWithValidation; - var createFactory = createFactoryWithValidation; - var Children = { - map: mapChildren, - forEach: forEachChildren, - count: countChildren, - toArray, - only: onlyChild - }; - exports.Children = Children; - exports.Component = Component5; - exports.PureComponent = PureComponent2; - exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; - exports.cloneElement = cloneElement$1; - exports.createContext = createContext3; - exports.createElement = createElement$1; - exports.createFactory = createFactory; - exports.createRef = createRef2; - exports.forwardRef = forwardRef; - exports.isValidElement = isValidElement; - exports.lazy = lazy; - exports.memo = memo; - exports.useCallback = useCallback; - exports.useContext = useContext; - exports.useDebugValue = useDebugValue; - exports.useEffect = useEffect2; - exports.useImperativeHandle = useImperativeHandle; - exports.useLayoutEffect = useLayoutEffect; - exports.useMemo = useMemo; - exports.useReducer = useReducer; - exports.useRef = useRef2; - exports.useState = useState4; - exports.version = ReactVersion; - })(); - } - } -}); - -// node_modules/react/index.js -var require_react = __commonJS({ - "node_modules/react/index.js"(exports, module2) { - "use strict"; - if (false) { - module2.exports = null; - } else { - module2.exports = require_react_development(); - } - } -}); - -// node_modules/scheduler/cjs/scheduler.development.js -var require_scheduler_development = __commonJS({ - "node_modules/scheduler/cjs/scheduler.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var enableSchedulerDebugging = false; - var enableProfiling = false; - var requestHostCallback; - var requestHostTimeout; - var cancelHostTimeout; - var requestPaint; - var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; - if (hasPerformanceNow) { - var localPerformance = performance; - exports.unstable_now = function() { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - exports.unstable_now = function() { - return localDate.now() - initialTime; - }; - } - if (typeof window === "undefined" || typeof MessageChannel !== "function") { - var _callback = null; - var _timeoutID = null; - var _flushCallback = function() { - if (_callback !== null) { - try { - var currentTime = exports.unstable_now(); - var hasRemainingTime = true; - _callback(hasRemainingTime, currentTime); - _callback = null; - } catch (e3) { - setTimeout(_flushCallback, 0); - throw e3; - } - } - }; - requestHostCallback = function(cb) { - if (_callback !== null) { - setTimeout(requestHostCallback, 0, cb); - } else { - _callback = cb; - setTimeout(_flushCallback, 0); - } - }; - requestHostTimeout = function(cb, ms) { - _timeoutID = setTimeout(cb, ms); - }; - cancelHostTimeout = function() { - clearTimeout(_timeoutID); - }; - exports.unstable_shouldYield = function() { - return false; - }; - requestPaint = exports.unstable_forceFrameRate = function() { - }; - } else { - var _setTimeout = window.setTimeout; - var _clearTimeout = window.clearTimeout; - if (typeof console !== "undefined") { - var requestAnimationFrame2 = window.requestAnimationFrame; - var cancelAnimationFrame2 = window.cancelAnimationFrame; - if (typeof requestAnimationFrame2 !== "function") { - console["error"]("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"); - } - if (typeof cancelAnimationFrame2 !== "function") { - console["error"]("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"); - } - } - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; - var yieldInterval = 5; - var deadline = 0; - { - exports.unstable_shouldYield = function() { - return exports.unstable_now() >= deadline; - }; - requestPaint = function() { - }; - } - exports.unstable_forceFrameRate = function(fps) { - if (fps < 0 || fps > 125) { - console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); - return; - } - if (fps > 0) { - yieldInterval = Math.floor(1e3 / fps); - } else { - yieldInterval = 5; - } - }; - var performWorkUntilDeadline = function() { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); - deadline = currentTime + yieldInterval; - var hasTimeRemaining = true; - try { - var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - if (!hasMoreWork) { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } else { - port.postMessage(null); - } - } catch (error) { - port.postMessage(null); - throw error; - } - } else { - isMessageLoopRunning = false; - } - }; - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - requestHostCallback = function(callback) { - scheduledHostCallback = callback; - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - port.postMessage(null); - } - }; - requestHostTimeout = function(callback, ms) { - taskTimeoutID = _setTimeout(function() { - callback(exports.unstable_now()); - }, ms); - }; - cancelHostTimeout = function() { - _clearTimeout(taskTimeoutID); - taskTimeoutID = -1; - }; - } - function push(heap, node) { - var index = heap.length; - heap.push(node); - siftUp(heap, node, index); - } - function peek(heap) { - var first = heap[0]; - return first === void 0 ? null : first; - } - function pop(heap) { - var first = heap[0]; - if (first !== void 0) { - var last = heap.pop(); - if (last !== first) { - heap[0] = last; - siftDown(heap, last, 0); - } - return first; - } else { - return null; - } - } - function siftUp(heap, node, i3) { - var index = i3; - while (true) { - var parentIndex = index - 1 >>> 1; - var parent = heap[parentIndex]; - if (parent !== void 0 && compare(parent, node) > 0) { - heap[parentIndex] = node; - heap[index] = parent; - index = parentIndex; - } else { - return; - } - } - } - function siftDown(heap, node, i3) { - var index = i3; - var length = heap.length; - while (index < length) { - var leftIndex = (index + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; - if (left !== void 0 && compare(left, node) < 0) { - if (right !== void 0 && compare(right, left) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - heap[index] = left; - heap[leftIndex] = node; - index = leftIndex; - } - } else if (right !== void 0 && compare(right, node) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - return; - } - } - } - function compare(a3, b3) { - var diff = a3.sortIndex - b3.sortIndex; - return diff !== 0 ? diff : a3.id - b3.id; - } - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - function markTaskErrored(task, ms) { - } - var maxSigned31BitInt = 1073741823; - var IMMEDIATE_PRIORITY_TIMEOUT = -1; - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5e3; - var LOW_PRIORITY_TIMEOUT = 1e4; - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; - var taskQueue = []; - var timerQueue = []; - var taskIdCounter = 1; - var currentTask = null; - var currentPriorityLevel = NormalPriority; - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; - function advanceTimers(currentTime) { - var timer = peek(timerQueue); - while (timer !== null) { - if (timer.callback === null) { - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push(taskQueue, timer); - } else { - return; - } - timer = peek(timerQueue); - } - } - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - function flushWork(hasTimeRemaining, initialTime2) { - isHostCallbackScheduled = false; - if (isHostTimeoutScheduled) { - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - try { - if (enableProfiling) { - try { - return workLoop(hasTimeRemaining, initialTime2); - } catch (error) { - if (currentTask !== null) { - var currentTime = exports.unstable_now(); - markTaskErrored(currentTask, currentTime); - currentTask.isQueued = false; - } - throw error; - } - } else { - return workLoop(hasTimeRemaining, initialTime2); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - function workLoop(hasTimeRemaining, initialTime2) { - var currentTime = initialTime2; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - while (currentTask !== null && !enableSchedulerDebugging) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || exports.unstable_shouldYield())) { - break; - } - var callback = currentTask.callback; - if (typeof callback === "function") { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - if (typeof continuationCallback === "function") { - currentTask.callback = continuationCallback; - } else { - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - currentTask = peek(taskQueue); - } - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - return false; - } - } - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - default: - priorityLevel = NormalPriority; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_next(eventHandler) { - var priorityLevel; - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - priorityLevel = NormalPriority; - break; - default: - priorityLevel = currentPriorityLevel; - break; - } - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function() { - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime; - if (typeof options === "object" && options !== null) { - var delay = options.delay; - if (typeof delay === "number" && delay > 0) { - startTime = currentTime + delay; - } else { - startTime = currentTime; - } - } else { - startTime = currentTime; - } - var timeout; - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - var expirationTime = startTime + timeout; - var newTask = { - id: taskIdCounter++, - callback, - priorityLevel, - startTime, - expirationTime, - sortIndex: -1 - }; - if (startTime > currentTime) { - newTask.sortIndex = startTime; - push(timerQueue, newTask); - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - if (isHostTimeoutScheduled) { - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } - requestHostTimeout(handleTimeout, startTime - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push(taskQueue, newTask); - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - return newTask; - } - function unstable_pauseExecution() { - } - function unstable_continueExecution() { - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - function unstable_cancelCallback(task) { - task.callback = null; - } - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_wrapCallback = unstable_wrapCallback; - })(); - } - } -}); - -// node_modules/scheduler/index.js -var require_scheduler = __commonJS({ - "node_modules/scheduler/index.js"(exports, module2) { - "use strict"; - if (false) { - module2.exports = null; - } else { - module2.exports = require_scheduler_development(); - } - } -}); - -// node_modules/scheduler/cjs/scheduler-tracing.development.js -var require_scheduler_tracing_development = __commonJS({ - "node_modules/scheduler/cjs/scheduler-tracing.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var DEFAULT_THREAD_ID = 0; - var interactionIDCounter = 0; - var threadIDCounter = 0; - exports.__interactionsRef = null; - exports.__subscriberRef = null; - { - exports.__interactionsRef = { - current: new Set() - }; - exports.__subscriberRef = { - current: null - }; - } - function unstable_clear(callback) { - var prevInteractions = exports.__interactionsRef.current; - exports.__interactionsRef.current = new Set(); - try { - return callback(); - } finally { - exports.__interactionsRef.current = prevInteractions; - } - } - function unstable_getCurrent() { - { - return exports.__interactionsRef.current; - } - } - function unstable_getThreadID() { - return ++threadIDCounter; - } - function unstable_trace(name, timestamp, callback) { - var threadID = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : DEFAULT_THREAD_ID; - var interaction = { - __count: 1, - id: interactionIDCounter++, - name, - timestamp - }; - var prevInteractions = exports.__interactionsRef.current; - var interactions = new Set(prevInteractions); - interactions.add(interaction); - exports.__interactionsRef.current = interactions; - var subscriber = exports.__subscriberRef.current; - var returnValue; - try { - if (subscriber !== null) { - subscriber.onInteractionTraced(interaction); - } - } finally { - try { - if (subscriber !== null) { - subscriber.onWorkStarted(interactions, threadID); - } - } finally { - try { - returnValue = callback(); - } finally { - exports.__interactionsRef.current = prevInteractions; - try { - if (subscriber !== null) { - subscriber.onWorkStopped(interactions, threadID); - } - } finally { - interaction.__count--; - if (subscriber !== null && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } - } - } - } - } - return returnValue; - } - function unstable_wrap(callback) { - var threadID = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_THREAD_ID; - var wrappedInteractions = exports.__interactionsRef.current; - var subscriber = exports.__subscriberRef.current; - if (subscriber !== null) { - subscriber.onWorkScheduled(wrappedInteractions, threadID); - } - wrappedInteractions.forEach(function(interaction) { - interaction.__count++; - }); - var hasRun = false; - function wrapped() { - var prevInteractions = exports.__interactionsRef.current; - exports.__interactionsRef.current = wrappedInteractions; - subscriber = exports.__subscriberRef.current; - try { - var returnValue; - try { - if (subscriber !== null) { - subscriber.onWorkStarted(wrappedInteractions, threadID); - } - } finally { - try { - returnValue = callback.apply(void 0, arguments); - } finally { - exports.__interactionsRef.current = prevInteractions; - if (subscriber !== null) { - subscriber.onWorkStopped(wrappedInteractions, threadID); - } - } - } - return returnValue; - } finally { - if (!hasRun) { - hasRun = true; - wrappedInteractions.forEach(function(interaction) { - interaction.__count--; - if (subscriber !== null && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } - }); - } - } - } - wrapped.cancel = function cancel() { - subscriber = exports.__subscriberRef.current; - try { - if (subscriber !== null) { - subscriber.onWorkCanceled(wrappedInteractions, threadID); - } - } finally { - wrappedInteractions.forEach(function(interaction) { - interaction.__count--; - if (subscriber && interaction.__count === 0) { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } - }); - } - }; - return wrapped; - } - var subscribers = null; - { - subscribers = new Set(); - } - function unstable_subscribe(subscriber) { - { - subscribers.add(subscriber); - if (subscribers.size === 1) { - exports.__subscriberRef.current = { - onInteractionScheduledWorkCompleted, - onInteractionTraced, - onWorkCanceled, - onWorkScheduled, - onWorkStarted, - onWorkStopped - }; - } - } - } - function unstable_unsubscribe(subscriber) { - { - subscribers.delete(subscriber); - if (subscribers.size === 0) { - exports.__subscriberRef.current = null; - } - } - } - function onInteractionTraced(interaction) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onInteractionTraced(interaction); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onInteractionScheduledWorkCompleted(interaction) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onInteractionScheduledWorkCompleted(interaction); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkScheduled(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkScheduled(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkStarted(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkStarted(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkStopped(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkStopped(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - function onWorkCanceled(interactions, threadID) { - var didCatchError = false; - var caughtError = null; - subscribers.forEach(function(subscriber) { - try { - subscriber.onWorkCanceled(interactions, threadID); - } catch (error) { - if (!didCatchError) { - didCatchError = true; - caughtError = error; - } - } - }); - if (didCatchError) { - throw caughtError; - } - } - exports.unstable_clear = unstable_clear; - exports.unstable_getCurrent = unstable_getCurrent; - exports.unstable_getThreadID = unstable_getThreadID; - exports.unstable_subscribe = unstable_subscribe; - exports.unstable_trace = unstable_trace; - exports.unstable_unsubscribe = unstable_unsubscribe; - exports.unstable_wrap = unstable_wrap; - })(); - } - } -}); - -// node_modules/scheduler/tracing.js -var require_tracing = __commonJS({ - "node_modules/scheduler/tracing.js"(exports, module2) { - "use strict"; - if (false) { - module2.exports = null; - } else { - module2.exports = require_scheduler_tracing_development(); - } - } -}); - -// node_modules/react-dom/cjs/react-dom.development.js -var require_react_dom_development = __commonJS({ - "node_modules/react-dom/cjs/react-dom.development.js"(exports) { - "use strict"; - if (true) { - (function() { - "use strict"; - var React5 = require_react(); - var _assign = require_object_assign(); - var Scheduler = require_scheduler(); - var tracing = require_tracing(); - var ReactSharedInternals = React5.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - function warn(format) { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - function error(format) { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame2.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function(item) { - return "" + item; - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - if (!React5) { - { - throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM."); - } - } - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; - var HostRoot = 3; - var HostPortal = 4; - var HostComponent = 5; - var HostText = 6; - var Fragment3 = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var FundamentalComponent = 20; - var ScopeComponent = 21; - var Block = 22; - var OffscreenComponent = 23; - var LegacyHiddenComponent = 24; - var enableProfilerTimer = true; - var enableFundamentalAPI = false; - var enableNewReconciler = false; - var warnAboutStringRefs = false; - var allNativeEvents = new Set(); - var registrationNameDependencies = {}; - var possibleRegistrationNames = {}; - function registerTwoPhaseEvent(registrationName, dependencies) { - registerDirectEvent(registrationName, dependencies); - registerDirectEvent(registrationName + "Capture", dependencies); - } - function registerDirectEvent(registrationName, dependencies) { - { - if (registrationNameDependencies[registrationName]) { - error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); - } - } - registrationNameDependencies[registrationName] = dependencies; - { - var lowerCasedName = registrationName.toLowerCase(); - possibleRegistrationNames[lowerCasedName] = registrationName; - if (registrationName === "onDoubleClick") { - possibleRegistrationNames.ondblclick = registrationName; - } - } - for (var i3 = 0; i3 < dependencies.length; i3++) { - allNativeEvents.add(dependencies[i3]); - } - } - var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); - var RESERVED = 0; - var STRING = 1; - var BOOLEANISH_STRING = 2; - var BOOLEAN = 3; - var OVERLOADED_BOOLEAN = 4; - var NUMERIC = 5; - var POSITIVE_NUMERIC = 6; - var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; - var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; - var ROOT_ATTRIBUTE_NAME = "data-reactroot"; - var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); - var hasOwnProperty2 = Object.prototype.hasOwnProperty; - var illegalAttributeNameCache = {}; - var validatedAttributeNameCache = {}; - function isAttributeNameSafe(attributeName) { - if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName)) { - return true; - } - if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName)) { - return false; - } - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true; - return true; - } - illegalAttributeNameCache[attributeName] = true; - { - error("Invalid attribute name: `%s`", attributeName); - } - return false; - } - function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null) { - return propertyInfo.type === RESERVED; - } - if (isCustomComponentTag) { - return false; - } - if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { - return true; - } - return false; - } - function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false; - } - switch (typeof value) { - case "function": - case "symbol": - return true; - case "boolean": { - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans; - } else { - var prefix2 = name.toLowerCase().slice(0, 5); - return prefix2 !== "data-" && prefix2 !== "aria-"; - } - } - default: - return false; - } - } - function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { - if (value === null || typeof value === "undefined") { - return true; - } - if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { - return true; - } - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - switch (propertyInfo.type) { - case BOOLEAN: - return !value; - case OVERLOADED_BOOLEAN: - return value === false; - case NUMERIC: - return isNaN(value); - case POSITIVE_NUMERIC: - return isNaN(value) || value < 1; - } - } - return false; - } - function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null; - } - function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { - this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; - this.attributeName = attributeName; - this.attributeNamespace = attributeNamespace; - this.mustUseProperty = mustUseProperty; - this.propertyName = name; - this.type = type; - this.sanitizeURL = sanitizeURL2; - this.removeEmptyString = removeEmptyString; - } - var properties = {}; - var reservedProps = [ - "children", - "dangerouslySetInnerHTML", - "defaultValue", - "defaultChecked", - "innerHTML", - "suppressContentEditableWarning", - "suppressHydrationWarning", - "style" - ]; - reservedProps.forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, RESERVED, false, name, null, false, false); - }); - [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { - var name = _ref[0], attributeName = _ref[1]; - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false); - }); - ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name.toLowerCase(), null, false, false); - }); - ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name, null, false, false); - }); - [ - "allowFullScreen", - "async", - "autoFocus", - "autoPlay", - "controls", - "default", - "defer", - "disabled", - "disablePictureInPicture", - "disableRemotePlayback", - "formNoValidate", - "hidden", - "loop", - "noModule", - "noValidate", - "open", - "playsInline", - "readOnly", - "required", - "reversed", - "scoped", - "seamless", - "itemScope" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, name.toLowerCase(), null, false, false); - }); - [ - "checked", - "multiple", - "muted", - "selected" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, name, null, false, false); - }); - [ - "capture", - "download" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, name, null, false, false); - }); - [ - "cols", - "rows", - "size", - "span" - ].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, name, null, false, false); - }); - ["rowSpan", "start"].forEach(function(name) { - properties[name] = new PropertyInfoRecord(name, NUMERIC, false, name.toLowerCase(), null, false, false); - }); - var CAMELIZE = /[\-\:]([a-z])/g; - var capitalize = function(token) { - return token[1].toUpperCase(); - }; - [ - "accent-height", - "alignment-baseline", - "arabic-form", - "baseline-shift", - "cap-height", - "clip-path", - "clip-rule", - "color-interpolation", - "color-interpolation-filters", - "color-profile", - "color-rendering", - "dominant-baseline", - "enable-background", - "fill-opacity", - "fill-rule", - "flood-color", - "flood-opacity", - "font-family", - "font-size", - "font-size-adjust", - "font-stretch", - "font-style", - "font-variant", - "font-weight", - "glyph-name", - "glyph-orientation-horizontal", - "glyph-orientation-vertical", - "horiz-adv-x", - "horiz-origin-x", - "image-rendering", - "letter-spacing", - "lighting-color", - "marker-end", - "marker-mid", - "marker-start", - "overline-position", - "overline-thickness", - "paint-order", - "panose-1", - "pointer-events", - "rendering-intent", - "shape-rendering", - "stop-color", - "stop-opacity", - "strikethrough-position", - "strikethrough-thickness", - "stroke-dasharray", - "stroke-dashoffset", - "stroke-linecap", - "stroke-linejoin", - "stroke-miterlimit", - "stroke-opacity", - "stroke-width", - "text-anchor", - "text-decoration", - "text-rendering", - "underline-position", - "underline-thickness", - "unicode-bidi", - "unicode-range", - "units-per-em", - "v-alphabetic", - "v-hanging", - "v-ideographic", - "v-mathematical", - "vector-effect", - "vert-adv-y", - "vert-origin-x", - "vert-origin-y", - "word-spacing", - "writing-mode", - "xmlns:xlink", - "x-height" - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false); - }); - [ - "xlink:actuate", - "xlink:arcrole", - "xlink:role", - "xlink:show", - "xlink:title", - "xlink:type" - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/1999/xlink", false, false); - }); - [ - "xml:base", - "xml:lang", - "xml:space" - ].forEach(function(attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/XML/1998/namespace", false, false); - }); - ["tabIndex", "crossOrigin"].forEach(function(attributeName) { - properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, false, false); - }); - var xlinkHref = "xlinkHref"; - properties[xlinkHref] = new PropertyInfoRecord("xlinkHref", STRING, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false); - ["src", "href", "action", "formAction"].forEach(function(attributeName) { - properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, true, true); - }); - var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; - var didWarn = false; - function sanitizeURL(url) { - { - if (!didWarn && isJavaScriptProtocol.test(url)) { - didWarn = true; - error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); - } - } - } - function getValueForProperty(node, name, expected, propertyInfo) { - { - if (propertyInfo.mustUseProperty) { - var propertyName = propertyInfo.propertyName; - return node[propertyName]; - } else { - if (propertyInfo.sanitizeURL) { - sanitizeURL("" + expected); - } - var attributeName = propertyInfo.attributeName; - var stringValue = null; - if (propertyInfo.type === OVERLOADED_BOOLEAN) { - if (node.hasAttribute(attributeName)) { - var value = node.getAttribute(attributeName); - if (value === "") { - return true; - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return value; - } - if (value === "" + expected) { - return expected; - } - return value; - } - } else if (node.hasAttribute(attributeName)) { - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return node.getAttribute(attributeName); - } - if (propertyInfo.type === BOOLEAN) { - return expected; - } - stringValue = node.getAttribute(attributeName); - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return stringValue === null ? expected : stringValue; - } else if (stringValue === "" + expected) { - return expected; - } else { - return stringValue; - } - } - } - } - function getValueForAttribute(node, name, expected) { - { - if (!isAttributeNameSafe(name)) { - return; - } - if (isOpaqueHydratingObject(expected)) { - return expected; - } - if (!node.hasAttribute(name)) { - return expected === void 0 ? void 0 : null; - } - var value = node.getAttribute(name); - if (value === "" + expected) { - return expected; - } - return value; - } - } - function setValueForProperty(node, name, value, isCustomComponentTag) { - var propertyInfo = getPropertyInfo(name); - if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { - return; - } - if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { - value = null; - } - if (isCustomComponentTag || propertyInfo === null) { - if (isAttributeNameSafe(name)) { - var _attributeName = name; - if (value === null) { - node.removeAttribute(_attributeName); - } else { - node.setAttribute(_attributeName, "" + value); - } - } - return; - } - var mustUseProperty = propertyInfo.mustUseProperty; - if (mustUseProperty) { - var propertyName = propertyInfo.propertyName; - if (value === null) { - var type = propertyInfo.type; - node[propertyName] = type === BOOLEAN ? false : ""; - } else { - node[propertyName] = value; - } - return; - } - var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; - if (value === null) { - node.removeAttribute(attributeName); - } else { - var _type = propertyInfo.type; - var attributeValue; - if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { - attributeValue = ""; - } else { - { - attributeValue = "" + value; - } - if (propertyInfo.sanitizeURL) { - sanitizeURL(attributeValue.toString()); - } - } - if (attributeNamespace) { - node.setAttributeNS(attributeNamespace, attributeName, attributeValue); - } else { - node.setAttribute(attributeName, attributeValue); - } - } - } - var REACT_ELEMENT_TYPE = 60103; - var REACT_PORTAL_TYPE = 60106; - var REACT_FRAGMENT_TYPE = 60107; - var REACT_STRICT_MODE_TYPE = 60108; - var REACT_PROFILER_TYPE = 60114; - var REACT_PROVIDER_TYPE = 60109; - var REACT_CONTEXT_TYPE = 60110; - var REACT_FORWARD_REF_TYPE = 60112; - var REACT_SUSPENSE_TYPE = 60113; - var REACT_SUSPENSE_LIST_TYPE = 60120; - var REACT_MEMO_TYPE = 60115; - var REACT_LAZY_TYPE = 60116; - var REACT_BLOCK_TYPE = 60121; - var REACT_SERVER_BLOCK_TYPE = 60122; - var REACT_FUNDAMENTAL_TYPE = 60117; - var REACT_SCOPE_TYPE = 60119; - var REACT_OPAQUE_ID_TYPE = 60128; - var REACT_DEBUG_TRACING_MODE_TYPE = 60129; - var REACT_OFFSCREEN_TYPE = 60130; - var REACT_LEGACY_HIDDEN_TYPE = 60131; - if (typeof Symbol === "function" && Symbol.for) { - var symbolFor = Symbol.for; - REACT_ELEMENT_TYPE = symbolFor("react.element"); - REACT_PORTAL_TYPE = symbolFor("react.portal"); - REACT_FRAGMENT_TYPE = symbolFor("react.fragment"); - REACT_STRICT_MODE_TYPE = symbolFor("react.strict_mode"); - REACT_PROFILER_TYPE = symbolFor("react.profiler"); - REACT_PROVIDER_TYPE = symbolFor("react.provider"); - REACT_CONTEXT_TYPE = symbolFor("react.context"); - REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref"); - REACT_SUSPENSE_TYPE = symbolFor("react.suspense"); - REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list"); - REACT_MEMO_TYPE = symbolFor("react.memo"); - REACT_LAZY_TYPE = symbolFor("react.lazy"); - REACT_BLOCK_TYPE = symbolFor("react.block"); - REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block"); - REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental"); - REACT_SCOPE_TYPE = symbolFor("react.scope"); - REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id"); - REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode"); - REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen"); - REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden"); - } - var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() { - } - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: _assign({}, props, { - value: prevLog - }), - info: _assign({}, props, { - value: prevInfo - }), - warn: _assign({}, props, { - value: prevWarn - }), - error: _assign({}, props, { - value: prevError - }), - group: _assign({}, props, { - value: prevGroup - }), - groupCollapsed: _assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: _assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === void 0) { - try { - throw Error(); - } catch (x3) { - var match = x3.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== void 0) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = void 0; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function() { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function() { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x3) { - control = x3; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x3) { - control = x3; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x3) { - control = x3; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s3 = sampleLines.length - 1; - var c3 = controlLines.length - 1; - while (s3 >= 1 && c3 >= 0 && sampleLines[s3] !== controlLines[c3]) { - c3--; - } - for (; s3 >= 1 && c3 >= 0; s3--, c3--) { - if (sampleLines[s3] !== controlLines[c3]) { - if (s3 !== 1 || c3 !== 1) { - do { - s3--; - c3--; - if (c3 < 0 || sampleLines[s3] !== controlLines[c3]) { - var _frame = "\n" + sampleLines[s3].replace(" at new ", " at "); - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s3 >= 1 && c3 >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component5) { - var prototype = Component5.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_BLOCK_TYPE: - return describeFunctionComponentFrame(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x3) { - } - } - } - } - return ""; - } - function describeFiber(fiber) { - var owner = fiber._debugOwner ? fiber._debugOwner.type : null; - var source = fiber._debugSource; - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - case LazyComponent: - return describeBuiltInComponentFrame("Lazy"); - case SuspenseComponent: - return describeBuiltInComponentFrame("Suspense"); - case SuspenseListComponent: - return describeBuiltInComponentFrame("SuspenseList"); - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - case Block: - return describeFunctionComponentFrame(fiber.type._render); - case ClassComponent: - return describeClassComponentFrame(fiber.type); - default: - return ""; - } - } - function getStackByFiberInDevAndProd(workInProgress2) { - try { - var info = ""; - var node = workInProgress2; - do { - info += describeFiber(node); - node = node.return; - } while (node); - return info; - } catch (x3) { - return "\nError generating stack: " + x3.message + "\n" + x3.stack; - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentName(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - return getComponentName(type.type); - case REACT_BLOCK_TYPE: - return getComponentName(type._render); - case REACT_LAZY_TYPE: { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentName(init(payload)); - } catch (x3) { - return null; - } - } - } - } - return null; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - var owner = current._debugOwner; - if (owner !== null && typeof owner !== "undefined") { - return getComponentName(owner.type); - } - } - return null; - } - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ""; - } - return getStackByFiberInDevAndProd(current); - } - } - function resetCurrentFiber() { - { - ReactDebugCurrentFrame.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - function getIsRendering() { - { - return isRendering; - } - } - function toString(value) { - return "" + value; - } - function getToStringValue(value) { - switch (typeof value) { - case "boolean": - case "number": - case "object": - case "string": - case "undefined": - return value; - default: - return ""; - } - } - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true - }; - function checkControlledValueProps(tagName, props) { - { - if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { - error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); - } - if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { - error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); - } - } - } - function isCheckable(elem) { - var type = elem.type; - var nodeName = elem.nodeName; - return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio"); - } - function getTracker(node) { - return node._valueTracker; - } - function detachTracker(node) { - node._valueTracker = null; - } - function getValueFromNode(node) { - var value = ""; - if (!node) { - return value; - } - if (isCheckable(node)) { - value = node.checked ? "true" : "false"; - } else { - value = node.value; - } - return value; - } - function trackValueOnNode(node) { - var valueField = isCheckable(node) ? "checked" : "value"; - var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); - var currentValue = "" + node[valueField]; - if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { - return; - } - var get2 = descriptor.get, set2 = descriptor.set; - Object.defineProperty(node, valueField, { - configurable: true, - get: function() { - return get2.call(this); - }, - set: function(value) { - currentValue = "" + value; - set2.call(this, value); - } - }); - Object.defineProperty(node, valueField, { - enumerable: descriptor.enumerable - }); - var tracker = { - getValue: function() { - return currentValue; - }, - setValue: function(value) { - currentValue = "" + value; - }, - stopTracking: function() { - detachTracker(node); - delete node[valueField]; - } - }; - return tracker; - } - function track(node) { - if (getTracker(node)) { - return; - } - node._valueTracker = trackValueOnNode(node); - } - function updateValueIfChanged(node) { - if (!node) { - return false; - } - var tracker = getTracker(node); - if (!tracker) { - return true; - } - var lastValue = tracker.getValue(); - var nextValue = getValueFromNode(node); - if (nextValue !== lastValue) { - tracker.setValue(nextValue); - return true; - } - return false; - } - function getActiveElement(doc) { - doc = doc || (typeof document !== "undefined" ? document : void 0); - if (typeof doc === "undefined") { - return null; - } - try { - return doc.activeElement || doc.body; - } catch (e3) { - return doc.body; - } - } - var didWarnValueDefaultValue = false; - var didWarnCheckedDefaultChecked = false; - var didWarnControlledToUncontrolled = false; - var didWarnUncontrolledToControlled = false; - function isControlled(props) { - var usesChecked = props.type === "checkbox" || props.type === "radio"; - return usesChecked ? props.checked != null : props.value != null; - } - function getHostProps(element, props) { - var node = element; - var checked = props.checked; - var hostProps = _assign({}, props, { - defaultChecked: void 0, - defaultValue: void 0, - value: void 0, - checked: checked != null ? checked : node._wrapperState.initialChecked - }); - return hostProps; - } - function initWrapperState(element, props) { - { - checkControlledValueProps("input", props); - if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) { - error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnCheckedDefaultChecked = true; - } - if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) { - error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnValueDefaultValue = true; - } - } - var node = element; - var defaultValue = props.defaultValue == null ? "" : props.defaultValue; - node._wrapperState = { - initialChecked: props.checked != null ? props.checked : props.defaultChecked, - initialValue: getToStringValue(props.value != null ? props.value : defaultValue), - controlled: isControlled(props) - }; - } - function updateChecked(element, props) { - var node = element; - var checked = props.checked; - if (checked != null) { - setValueForProperty(node, "checked", checked, false); - } - } - function updateWrapper(element, props) { - var node = element; - { - var controlled = isControlled(props); - if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { - error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnUncontrolledToControlled = true; - } - if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { - error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnControlledToUncontrolled = true; - } - } - updateChecked(element, props); - var value = getToStringValue(props.value); - var type = props.type; - if (value != null) { - if (type === "number") { - if (value === 0 && node.value === "" || node.value != value) { - node.value = toString(value); - } - } else if (node.value !== toString(value)) { - node.value = toString(value); - } - } else if (type === "submit" || type === "reset") { - node.removeAttribute("value"); - return; - } - { - if (props.hasOwnProperty("value")) { - setDefaultValue(node, props.type, value); - } else if (props.hasOwnProperty("defaultValue")) { - setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); - } - } - { - if (props.checked == null && props.defaultChecked != null) { - node.defaultChecked = !!props.defaultChecked; - } - } - } - function postMountWrapper(element, props, isHydrating2) { - var node = element; - if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { - var type = props.type; - var isButton = type === "submit" || type === "reset"; - if (isButton && (props.value === void 0 || props.value === null)) { - return; - } - var initialValue = toString(node._wrapperState.initialValue); - if (!isHydrating2) { - { - if (initialValue !== node.value) { - node.value = initialValue; - } - } - } - { - node.defaultValue = initialValue; - } - } - var name = node.name; - if (name !== "") { - node.name = ""; - } - { - node.defaultChecked = !node.defaultChecked; - node.defaultChecked = !!node._wrapperState.initialChecked; - } - if (name !== "") { - node.name = name; - } - } - function restoreControlledState(element, props) { - var node = element; - updateWrapper(node, props); - updateNamedCousins(node, props); - } - function updateNamedCousins(rootNode, props) { - var name = props.name; - if (props.type === "radio" && name != null) { - var queryRoot = rootNode; - while (queryRoot.parentNode) { - queryRoot = queryRoot.parentNode; - } - var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'); - for (var i3 = 0; i3 < group.length; i3++) { - var otherNode = group[i3]; - if (otherNode === rootNode || otherNode.form !== rootNode.form) { - continue; - } - var otherProps = getFiberCurrentPropsFromNode(otherNode); - if (!otherProps) { - { - throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); - } - } - updateValueIfChanged(otherNode); - updateWrapper(otherNode, otherProps); - } - } - } - function setDefaultValue(node, type, value) { - if (type !== "number" || getActiveElement(node.ownerDocument) !== node) { - if (value == null) { - node.defaultValue = toString(node._wrapperState.initialValue); - } else if (node.defaultValue !== toString(value)) { - node.defaultValue = toString(value); - } - } - } - var didWarnSelectedSetOnOption = false; - var didWarnInvalidChild = false; - function flattenChildren(children) { - var content = ""; - React5.Children.forEach(children, function(child) { - if (child == null) { - return; - } - content += child; - }); - return content; - } - function validateProps(element, props) { - { - if (typeof props.children === "object" && props.children !== null) { - React5.Children.forEach(props.children, function(child) { - if (child == null) { - return; - } - if (typeof child === "string" || typeof child === "number") { - return; - } - if (typeof child.type !== "string") { - return; - } - if (!didWarnInvalidChild) { - didWarnInvalidChild = true; - error("Only strings and numbers are supported as