diff --git a/chat-history.js b/chat-history.js index 9f8e28c..83902bc 100644 --- a/chat-history.js +++ b/chat-history.js @@ -3,6 +3,7 @@ // 可被 index.js 及其他模块安全导入。 import { clampInt } from "./ui-status.js"; +import { sanitizePlannerMessageText } from "./planner-tag-utils.js"; import { rollbackBatch } from "./runtime-state.js"; export function isAssistantChatMessage(message) { @@ -40,7 +41,7 @@ export function buildExtractionMessages(chat, startIdx, endIdx, settings) { messages.push({ seq: index, role: msg.is_user ? "user" : "assistant", - content: msg.mes || "", + content: sanitizePlannerMessageText(msg), }); } diff --git a/ena-planner/ena-planner-presets.js b/ena-planner/ena-planner-presets.js new file mode 100644 index 0000000..5125e09 --- /dev/null +++ b/ena-planner/ena-planner-presets.js @@ -0,0 +1,53 @@ +export const DEFAULT_PROMPT_BLOCKS = [ + { + id: "ena-default-system-001", + role: "system", + name: "Ena Planner System", + content: `你是一位剧情规划师(Story Planner)。你的工作是在幕后为互动叙事提供方向指引,而不是直接扮演角色或撰写正文。 + +## 你会收到的信息 +- 角色卡:当前角色的设定(描述、性格、场景) +- 世界书:世界观设定和规则 +- 结构化记忆(BME):由记忆图谱整理出的长期记忆 + - [Memory - Core]:规则、摘要、长期约束 + - [Memory - Recalled]:与当前情境相关的人物状态、事件、地点、剧情线 +- 聊天历史:最近的 AI 回复片段 +- 历史规划:之前生成的 块 +- 玩家输入:玩家刚刚发出的指令或行动 + +## 你的任务 +根据以上信息,为下一轮 AI 回复规划剧情走向。 + +## 输出格式(严格遵守) +只输出以下两个标签,不要输出任何其他内容: + + +(剧情走向指引:接下来应该发生什么。包括场景推进、NPC 反应、事件触发、伏笔推进等。写给 AI 看的导演指令,不是给玩家看的正文。简洁、具体、可执行。) + + + +(写作注意事项:这一轮回复应该怎么写。包括叙事节奏、情绪基调、应避免的问题、需要保持的连贯性等。同样是给 AI 的元指令,不是正文。) + + +## 规划原则 +1. 尊重玩家意图:玩家输入是最高优先级。 +2. 保持连贯:与 BME 记忆、历史规划和世界规则一致。 +3. 推进而非重复:每轮规划都应推动剧情前进。 +4. 留有余地:给方向,不要把正文细节写死。 +5. 遵守世界观:世界书中的规则和设定属于硬约束。 + +如有思考过程,请放在 中(会被自动剔除)。`, + }, + { + id: "ena-default-assistant-001", + role: "assistant", + name: "Assistant Seed", + content: ` +先梳理玩家意图、当前局势、BME 记忆里的关键约束和最近的剧情推进,再给出下一步 plot 与 note。 +`, + }, +]; + +export const BUILTIN_TEMPLATES = { + 默认模板: DEFAULT_PROMPT_BLOCKS, +}; diff --git a/ena-planner/ena-planner-storage.js b/ena-planner/ena-planner-storage.js new file mode 100644 index 0000000..345984f --- /dev/null +++ b/ena-planner/ena-planner-storage.js @@ -0,0 +1,168 @@ +import { getRequestHeaders } from "../../../../../script.js"; + +function debounce(fn, ms) { + let timer = null; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), ms); + }; +} + +const toBase64 = (text) => btoa(unescape(encodeURIComponent(text))); + +class StorageFile { + constructor(filename, opts = {}) { + this.filename = filename; + this.cache = null; + this._loading = null; + this._dirtyVersion = 0; + this._savedVersion = 0; + this._saving = false; + this._pendingSave = false; + this._retryCount = 0; + this._retryTimer = null; + this._maxRetries = Number.isFinite(opts.maxRetries) ? opts.maxRetries : 5; + const debounceMs = Number.isFinite(opts.debounceMs) ? opts.debounceMs : 2000; + this._saveDebounced = debounce(() => this.saveNow({ silent: true }), debounceMs); + } + + async load() { + if (this.cache !== null) return this.cache; + if (this._loading) return this._loading; + + this._loading = (async () => { + try { + const res = await fetch(`/user/files/${this.filename}`, { + headers: getRequestHeaders(), + cache: "no-cache", + }); + if (!res.ok) { + this.cache = {}; + return this.cache; + } + const text = await res.text(); + this.cache = text ? JSON.parse(text) || {} : {}; + } catch { + this.cache = {}; + } finally { + this._loading = null; + } + return this.cache; + })(); + + return this._loading; + } + + async get(key, defaultValue = null) { + const data = await this.load(); + return data[key] ?? defaultValue; + } + + async set(key, value) { + const data = await this.load(); + data[key] = value; + this._dirtyVersion++; + this._saveDebounced(); + } + + async saveNow({ silent = true } = {}) { + if (this._saving) { + this._pendingSave = true; + if (!silent) { + await this._waitForSaveComplete(); + if (this._dirtyVersion > this._savedVersion) { + return this.saveNow({ silent }); + } + return this._dirtyVersion === this._savedVersion; + } + return true; + } + + if (!this.cache || this._dirtyVersion === this._savedVersion) { + return true; + } + + this._saving = true; + this._pendingSave = false; + const versionToSave = this._dirtyVersion; + + try { + const json = JSON.stringify(this.cache); + const base64 = toBase64(json); + const res = await fetch("/api/files/upload", { + method: "POST", + headers: getRequestHeaders(), + body: JSON.stringify({ name: this.filename, data: base64 }), + }); + if (!res.ok) { + throw new Error(`Server returned ${res.status}`); + } + + this._savedVersion = Math.max(this._savedVersion, versionToSave); + this._retryCount = 0; + if (this._retryTimer) { + clearTimeout(this._retryTimer); + this._retryTimer = null; + } + return true; + } catch (error) { + console.error("[EnaPlannerStorage] Save failed:", error); + this._retryCount++; + const delay = Math.min(30000, 2000 * (2 ** Math.max(0, this._retryCount - 1))); + if (!this._retryTimer && this._retryCount <= this._maxRetries) { + this._retryTimer = setTimeout(() => { + this._retryTimer = null; + this.saveNow({ silent: true }); + }, delay); + } + + if (!silent) { + throw error; + } + return false; + } finally { + this._saving = false; + if (this._pendingSave || this._dirtyVersion > this._savedVersion) { + this._saveDebounced(); + } + } + } + + _waitForSaveComplete() { + return new Promise((resolve) => { + const check = () => { + if (!this._saving) resolve(); + else setTimeout(check, 50); + }; + check(); + }); + } +} + +export const EnaPlannerStorage = new StorageFile("STBME_EnaPlanner.json", { + debounceMs: 800, +}); + +export async function migrateFromLWBIfNeeded() { + const existing = await EnaPlannerStorage.get("config", null); + if (existing) return false; + + try { + const res = await fetch("/user/files/LittleWhiteBox_EnaPlanner.json", { + headers: getRequestHeaders(), + cache: "no-cache", + }); + if (!res.ok) return false; + const text = await res.text(); + const old = text ? JSON.parse(text) : null; + if (!old?.config) return false; + + await EnaPlannerStorage.set("config", old.config); + await EnaPlannerStorage.set("logs", Array.isArray(old.logs) ? old.logs : []); + await EnaPlannerStorage.saveNow({ silent: false }); + return true; + } catch (error) { + console.warn("[Ena] LWB config migration failed:", error); + return false; + } +} diff --git a/ena-planner/ena-planner.css b/ena-planner/ena-planner.css new file mode 100644 index 0000000..52dec9c --- /dev/null +++ b/ena-planner/ena-planner.css @@ -0,0 +1,888 @@ +/* ═══════════════════════════════════════════════════════════════════════════ + Ena Planner — Settings UI + ═══════════════════════════════════════════════════════════════════════════ */ + +*, +*::before, +*::after { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +:root { + --bg: #121212; + --bg2: #1e1e1e; + --bg3: #2a2a2a; + --txt: #e0e0e0; + --txt2: #b0b0b0; + --txt3: #808080; + --bdr: #3a3a3a; + --bdr2: #333; + --acc: #e0e0e0; + --hl: #e8928a; + --hl2: #d87a7a; + --hl-soft: rgba(232, 146, 138, .1); + --inv: #1e1e1e; + --success: #4caf50; + --warn: #ffb74d; + --error: #ef5350; + --code-bg: #0d0d0d; + --code-txt: #d4d4d4; + --radius: 4px; +} + +html, +body { + height: auto; + overflow-y: auto; + -webkit-overflow-scrolling: touch; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', Roboto, sans-serif; + background: var(--bg); + color: var(--txt); + font-size: 14px; + line-height: 1.6; + min-height: 100vh; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Layout + ═══════════════════════════════════════════════════════════════════════════ */ + +.container { + display: flex; + flex-direction: column; + min-height: 100vh; + padding: 24px 40px; + max-width: 860px; + margin: 0 auto; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Header + ═══════════════════════════════════════════════════════════════════════════ */ + +header { + display: flex; + justify-content: space-between; + align-items: flex-start; + padding-bottom: 24px; + border-bottom: 1px solid var(--bdr); + margin-bottom: 24px; +} + +.header-left h1 { + font-size: 2rem; + font-weight: 300; + letter-spacing: -.02em; + margin-bottom: 4px; + color: var(--txt); +} + +.header-left h1 span { + font-weight: 600; +} + +.subtitle { + font-size: .75rem; + color: var(--txt3); + letter-spacing: .08em; + text-transform: uppercase; +} + +.stats { + display: flex; + gap: 40px; + align-items: center; + text-align: right; +} + +.stat-val { + font-size: 1.125rem; + font-weight: 500; + line-height: 1.2; + color: var(--txt); +} + +.stat-val .hl { + color: var(--hl); +} + +.stat-lbl { + font-size: .6875rem; + color: var(--txt3); + text-transform: uppercase; + letter-spacing: .1em; + margin-top: 4px; +} + +.modal-close { + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + border: 1px solid var(--bdr); + border-radius: var(--radius); + cursor: pointer; + transition: border-color .2s; + margin-left: 16px; +} + +.modal-close:hover { + border-color: var(--txt2); +} + +.modal-close svg { + width: 16px; + height: 16px; + color: var(--txt2); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Nav Tabs (desktop) + ═══════════════════════════════════════════ */ + +.nav-tabs { + display: flex; + gap: 24px; + border-bottom: 1px solid var(--bdr); + margin-bottom: 24px; +} + +.nav-item { + font-size: .8125rem; + font-weight: 500; + color: var(--txt3); + text-transform: uppercase; + letter-spacing: .08em; + padding-bottom: 12px; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + cursor: pointer; + transition: color .2s, border-color .2s; + user-select: none; +} + +.nav-item:hover { + color: var(--txt2); +} + +.nav-item.active { + color: var(--hl); + border-bottom-color: var(--hl); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Mobile Nav (bottom) + ═══════════════════════════════════════════════════════════════════════════ */ + +.mobile-nav { + display: none; + position: fixed; + bottom: 0; + left: 0; + right: 0; + height: 56px; + background: var(--bg2); + border-top: 1px solid var(--bdr); + z-index: 100; +} + +.mobile-nav-inner { + display: flex; + height: 100%; +} + +.mobile-nav-item { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 2px; + color: var(--txt3); + font-size: .625rem; + text-transform: uppercase; + letter-spacing: .05em; + cursor: pointer; + user-select: none; + transition: color .2s; +} + +.mobile-nav-item span { + line-height: 1; +} + +.mobile-nav-item .nav-dot { + width: 4px; + height: 4px; + border-radius: 50%; + background: transparent; + transition: background .2s; + margin-bottom: 2px; +} + +.mobile-nav-item.active { + color: var(--hl); +} + +.mobile-nav-item.active .nav-dot { + background: var(--hl); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Views + ═══════════════════════════════════════════════════════════════════════════ */ + +.view { + display: none; +} + +.view.active { + display: block; + animation: fadeIn .25s ease; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(4px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Cards + ═══════════════════════════════════════════════════════════════════════════ */ + +.card { + background: var(--bg2); + border: 1px solid var(--bdr); + border-radius: var(--radius); + padding: 24px; + margin-bottom: 20px; +} + +.card-title { + font-size: .75rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: .12em; + color: var(--txt2); + margin-bottom: 20px; + padding-bottom: 10px; + border-bottom: 1px dashed var(--bdr2); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Forms + ═══════════════════════════════════════════════════════════════════════════ */ + +.form-row { + display: flex; + gap: 16px; + flex-wrap: wrap; +} + +.form-group { + display: flex; + flex-direction: column; + gap: 6px; + flex: 1; + min-width: 180px; + margin-bottom: 16px; +} + +.form-row .form-group { + margin-bottom: 0; +} + +.form-row+.form-row { + margin-top: 16px; +} + +.form-label { + font-size: .6875rem; + color: var(--txt3); + text-transform: uppercase; + letter-spacing: .06em; +} + +.form-hint { + font-size: .75rem; + color: var(--txt3); + line-height: 1.5; + margin-top: 4px; +} + +.input { + width: 100%; + padding: 9px 12px; + background: var(--bg3); + border: 1px solid var(--bdr); + border-radius: var(--radius); + font-size: .8125rem; + color: var(--txt); + font-family: inherit; + outline: none; + transition: border-color .2s; +} + +.input:focus { + border-color: var(--txt2); +} + +.input::placeholder { + color: var(--txt3); +} + +select.input { + appearance: none; + -webkit-appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' fill='none' stroke='%23808080' stroke-width='2'%3E%3Cpolyline points='2 3.5 5 6.5 8 3.5'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 10px center; + padding-right: 28px; + cursor: pointer; +} + +textarea.input { + min-height: 80px; + resize: vertical; +} + +.input-row { + display: flex; + gap: 8px; +} + +.input-row .input { + flex: 1; + min-width: 0; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Buttons + ═══════════════════════════════════════════ */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + padding: 9px 18px; + background: var(--bg2); + color: var(--txt); + border: 1px solid var(--bdr); + border-radius: var(--radius); + font-size: .8125rem; + font-weight: 500; + font-family: inherit; + cursor: pointer; + transition: border-color .2s, background .2s; + white-space: nowrap; +} + +.btn:hover { + border-color: var(--txt3); + background: var(--bg3); +} + +.btn:disabled { + opacity: .35; + cursor: not-allowed; +} + +.btn-p { + background: var(--acc); + color: var(--inv); + border-color: var(--acc); +} + +.btn-p:hover { + background: var(--txt2); + border-color: var(--txt2); +} + +.btn-del { + color: var(--hl); + border-color: rgba(232, 146, 138, .3); +} + +.btn-del:hover { + background: var(--hl-soft); + border-color: var(--hl); +} + +.btn-sm { + padding: 5px 12px; + font-size: .75rem; +} + +.btn-group { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Tip Box + ═══════════════════════════════════════════════════════════════════════════ */ + +.tip-box { + display: flex; + gap: 12px; + align-items: flex-start; + padding: 14px 16px; + background: var(--hl-soft); + border: 1px solid var(--bdr); + border-left: 3px solid var(--hl); + border-radius: var(--radius); + margin-bottom: 20px; +} + +.tip-icon { + flex-shrink: 0; + font-size: .875rem; + line-height: 1.6; +} + +.tip-text { + font-size: .8125rem; + color: var(--txt2); + line-height: 1.6; +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Prompt Blocks + ═══════════════════════════════════════════════════════════════════════════ */ + +.prompt-block { + background: var(--bg3); + border: 1px solid var(--bdr); + border-radius: var(--radius); + padding: 16px; + margin-bottom: 10px; +} + +.prompt-head { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 10px; + margin-bottom: 10px; + flex-wrap: wrap; +} + +.prompt-head-left { + display: flex; + gap: 8px; + flex: 1; + min-width: 200px; +} + +.prompt-head-right { + display: flex; + gap: 6px; +} + +.prompt-block textarea.input { + min-height: 120px; + font-family: 'SF Mono', Monaco, Consolas, 'Liberation Mono', monospace; + font-size: .75rem; + line-height: 1.5; +} + +.prompt-empty { + text-align: center; + padding: 36px 20px; + color: var(--txt3); + font-size: .8125rem; + border: 1px dashed var(--bdr); + border-radius: var(--radius); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Undo Bar + ═══════════════════════════════════════════════════════════════════════════ */ + +.undo-bar { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + margin-top: 12px; + background: var(--hl-soft); + border: 1px solid var(--bdr); + border-radius: var(--radius); + font-size: .8125rem; + color: var(--txt2); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Status Text + ═══════════════════════════════════════════ */ + +.status-text { + font-size: .75rem; + color: var(--txt3); + margin-top: 10px; + min-height: 1em; +} + +.status-text.success { + color: var(--success); +} + +.status-text.error { + color: var(--error); +} + +.status-text.loading { + color: var(--warn); +} + +/* ═══════════════════════════════════════════ + Logs + ═══════════════════════════════════════════════════════════════════════════ */ + +.log-list { + max-height: 60vh; + overflow-y: auto; + border: 1px solid var(--bdr); + border-radius: var(--radius); + background: var(--bg3); +} + +.log-item { + padding: 14px 16px; + border-bottom: 1px solid var(--bdr2); +} + +.log-item:last-child { + border-bottom: none; +} + +.log-meta { + display: flex; + justify-content: space-between; + font-size: .6875rem; + color: var(--txt3); + text-transform: uppercase; + letter-spacing: .04em; + margin-bottom: 8px; +} + +.log-meta .success { + color: var(--success); +} + +.log-meta .error { + color: var(--error); +} + +.log-error { + color: var(--error); + font-size: .8125rem; + margin-bottom: 8px; + white-space: pre-wrap; +} + +.log-pre { + background: var(--code-bg); + color: var(--code-txt); + padding: 12px; + border-radius: var(--radius); + font-family: 'SF Mono', Monaco, Consolas, 'Liberation Mono', monospace; + font-size: .6875rem; + line-height: 1.5; + white-space: pre-wrap; + word-break: break-word; + max-height: 280px; + overflow-y: auto; + margin-top: 6px; +} + +.log-empty { + text-align: center; + padding: 36px 20px; + color: var(--txt3); + font-size: .8125rem; +} + +/* Message cards inside log */ +.msg-list { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 8px; +} + +.msg-card { + border-radius: var(--radius); + border-left: 3px solid var(--bdr); + background: var(--code-bg); + padding: 8px 12px; +} + +.msg-card.msg-system { border-left-color: #6b8afd; } +.msg-card.msg-user { border-left-color: #4ecdc4; } +.msg-card.msg-assistant { border-left-color: #f7a046; } + +.msg-role { + font-size: .6875rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: .04em; + margin-bottom: 4px; + color: var(--txt3); +} + +.msg-system .msg-role { color: #6b8afd; } +.msg-user .msg-role { color: #4ecdc4; } +.msg-assistant .msg-role { color: #f7a046; } + +.msg-content { + font-family: 'SF Mono', Monaco, Consolas, 'Liberation Mono', monospace; + font-size: .6875rem; + line-height: 1.6; + white-space: pre-wrap; + word-break: break-word; + color: var(--code-txt); + margin: 0; + max-height: 300px; + overflow-y: auto; +} + +details { + margin-bottom: 6px; +} + +details:last-child { + margin-bottom: 0; +} + +details summary { + cursor: pointer; + font-size: .75rem; + font-weight: 500; + color: var(--txt3); + user-select: none; + padding: 4px 0; + transition: color .15s; +} + +details summary:hover { + color: var(--txt); +} + +/* ═══════════════════════════════════════════════════════════════════════════ + Debug Output + ═══════════════════════════════════════════════════════════════════════════ */ + +.debug-output { + background: var(--code-bg); + color: var(--code-txt); + padding: 14px; + border-radius: var(--radius); + font-family: 'SF Mono', Monaco, Consolas, 'Liberation Mono', monospace; + font-size: .6875rem; + line-height: 1.6; + margin-top: 16px; + max-height: 400px; + overflow-y: auto; + white-space: pre-wrap; + word-break: break-word; + display: none; +} + +.debug-output.visible { + display: block; +} + +/* ═══════════════════════════════════════════ + Utilities + ═══════════════════════════════════════════════════════════════════════════ */ + +.hidden { + display: none !important; +} + +::-webkit-scrollbar { + width: 5px; + height: 5px; +} + +::-webkit-scrollbar-track { + background: transparent; +} + +::-webkit-scrollbar-thumb { + background: var(--bdr); + border-radius: 3px; +} + +::-webkit-scrollbar-thumb:hover { + background: var(--txt3); +} + +/* ═══════════════════════════════════════════ + Responsive — Tablet + ═══════════════════════════════════════════ */ + +@media (max-width: 768px) { + .container { + padding: 16px; + } + + header { + flex-direction: column; + gap: 16px; + } + + .header-left h1 { + font-size: 1.5rem; + } + + .stats { + width: 100%; + justify-content: flex-start; + gap: 24px; + } + + .modal-close { + position: absolute; + top: 16px; + right: 16px; + margin-left: 0; + } + + .nav-tabs { + display: none; + } + + .mobile-nav { + display: block; + } + + .container { + padding-bottom: 72px; + } + + .form-row { + flex-direction: column; + gap: 0; + } + + .card { + padding: 16px; + } + + .prompt-head { + flex-direction: column; + } + + .prompt-head-left { + min-width: 0; + flex-direction: column; + } +} + +/* ═══════════════════════════════════════════ + Responsive — Small phone + ═══════════════════════════════════════════════════════════════════════════ */ + +@media (max-width: 480px) { + .container { + padding: 12px; + padding-bottom: 68px; + } + + header { + gap: 12px; + padding-bottom: 16px; + margin-bottom: 16px; + } + + .header-left h1 { + font-size: 1.25rem; + } + + .subtitle { + font-size: .625rem; + } + + .stats { + gap: 16px; + } + + .stat-val { + font-size: 1rem; + } + + .card { + padding: 14px; + margin-bottom: 14px; + } + + .btn-group { + flex-direction: column; + } + + .btn-group .btn { + width: 100%; + } + + .mobile-nav { + height: 52px; + } + + .mobile-nav-item { + font-size: .5625rem; + } +} + +/* ═══════════════════════════════════════════ + Touch devices — 44px minimum target + ═══════════════════════════════════════════════════════════════════════════ */ + +@media (hover: none) and (pointer: coarse) { + .btn { + min-height: 44px; + padding: 10px 18px; + } + + .btn-sm { + min-height: 40px; + } + + .input { + min-height: 44px; + padding: 10px 12px; + } + + .nav-item { + padding-bottom: 14px; + } + + .mobile-nav-item { + min-height: 44px; + } + + .modal-close { + width: 44px; + height: 44px; + } + + details summary { + padding: 8px 0; + } +} diff --git a/ena-planner/ena-planner.html b/ena-planner/ena-planner.html new file mode 100644 index 0000000..9ef87e5 --- /dev/null +++ b/ena-planner/ena-planner.html @@ -0,0 +1,965 @@ + + + + + + + + + Ena Planner + + + + +
+ +
+
+

EnaPlanner

+
Story Planning · LLM Integration —— Created by Hao19911125
+
+
+
+
未启用
+
状态
+
+
+
就绪
+
保存
+
+ +
+
+ + + + +
+ + +
+
+
+
+ 工作流程:点击发送 → 拦截 → 收集上下文(角色卡、世界书、BME 记忆、历史 plot、最近 AI 回复)→ 发给规划 LLM → 提取 <plot> 和 + <note> → 追加到你的输入 → 放行发送 +
+
+ +
+
基本设置
+
+
+ + +
+
+ + +
+
+

输入中已有 <plot> 标签时跳过自动规划。

+
+ +
+
快速测试
+
+ + +
+
+ +
+
+
+
+ + +
+
+
连接设置
+
+
+ + +
+
+ + +
+
+
+ + +
+ +
+
+ +
+ + +
+
+
+ + +
+
+ +
+ + +
+
+
+ +
+
生成参数
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
💡
+
+ 系统会自动在提示词之后注入:角色卡、世界书、BME 结构化记忆、聊天历史和历史 plot 等上下文。你只需专注编写"规划指令"。 +
+
+ +
+
模板管理
+
+
+ +
+
+
+ + + +
+
+
+ +
+ +
+
提示词块
+
+ +
+ + +
+
+
+ + +
+
+
世界书
+
+
+ + +
+
+ + +
+
+
+ + +
+
+ +
+
聊天与历史
+
+ + +

仅支持英文标签(如 plot, note, memory)。留空表示不按标签过滤(仅去除 think)。无效标签会自动忽略。

+
+
+ + +
+
+ + +
+
+
+ + +
+
+
诊断工具
+
+ + + +
+

+        
+ +
+
日志
+
+
+ + +
+
+ + +
+
+
+ + + +
+
+
暂无日志
+
+
+
+ +
+ + + + +
+ + + + + diff --git a/ena-planner/ena-planner.js b/ena-planner/ena-planner.js new file mode 100644 index 0000000..106fc3f --- /dev/null +++ b/ena-planner/ena-planner.js @@ -0,0 +1,1517 @@ +import { extension_settings } from '../../../../extensions.js'; +import { getRequestHeaders, saveSettingsDebounced, substituteParamsExtended } from '../../../../../script.js'; +import { EnaPlannerStorage, migrateFromLWBIfNeeded } from './ena-planner-storage.js'; +import { DEFAULT_PROMPT_BLOCKS, BUILTIN_TEMPLATES } from './ena-planner-presets.js'; +import jsyaml from '../vendor/js-yaml.mjs'; + +const EXT_NAME = 'ena-planner'; +const OVERLAY_ID = 'xiaobaix-ena-planner-overlay'; +const VECTOR_RECALL_TIMEOUT_MS = 15000; +const PLANNER_REQUEST_TIMEOUT_MS = 90000; +const _currentModuleUrl = import.meta.url; + +let _bmeRuntime = null; + +function getTrustedOrigin() { return window.location.origin; } + +function postToIframe(iframe, payload) { + if (!iframe?.contentWindow) return false; + iframe.contentWindow.postMessage(payload, getTrustedOrigin()); + return true; +} + +function isTrustedIframeEvent(event, iframe) { + return !!iframe && event.origin === getTrustedOrigin() + && event.source === iframe.contentWindow; +} + +function getPluginBasePath() { + try { + const url = new URL(_currentModuleUrl); + const parts = url.pathname.split('/'); + const idx = parts.lastIndexOf('ena-planner'); + if (idx > 0) { + return parts.slice(0, idx).join('/'); + } + } catch { } + return _bmeRuntime?.getExtensionPath?.() + || 'scripts/extensions/third-party/ST-Bionic-Memory-Ecology-main'; +} + +function getHtmlPath() { + return `${getPluginBasePath()}/ena-planner/ena-planner.html`; +} + +/** + * ------------------------- + * Default settings + * -------------------------- + */ +function getDefaultSettings() { + return { + enabled: true, + skipIfPlotPresent: true, + + // Chat history: tags to strip from AI responses (besides ) + chatExcludeTags: ['行动选项', 'UpdateVariable', 'StatusPlaceHolderImpl'], + + // Worldbook: always read character-linked lorebooks by default + // User can also opt-in to include global worldbooks + includeGlobalWorldbooks: false, + excludeWorldbookPosition4: true, + // Worldbook entry names containing these strings will be excluded + worldbookExcludeNames: ['mvu_update'], + + // Plot extraction + plotCount: 2, + // Planner response tags to keep, in source order (empty = keep full response) + responseKeepTags: ['plot', 'note', 'plot-log', 'state'], + + // Planner prompts (designer) + promptBlocks: structuredClone(DEFAULT_PROMPT_BLOCKS), + // Saved prompt templates: { name: promptBlocks[] } + promptTemplates: structuredClone(BUILTIN_TEMPLATES), + // Currently selected prompt template name in UI + activePromptTemplate: '', + + // Planner API + api: { + channel: 'openai', + baseUrl: '', + prefixMode: 'auto', + customPrefix: '', + apiKey: '', + model: '', + stream: true, + temperature: 1, + top_p: 1, + top_k: 0, + presence_penalty: '', + frequency_penalty: '', + max_tokens: '' + }, + + // Logs + logsPersist: true, + logsMax: 20 + }; +} + +/** + * ------------------------- + * Local state + * -------------------------- + */ +const state = { + isPlanning: false, + bypassNextSend: false, + lastInjectedText: '', + logs: [] +}; + +let config = null; +let overlay = null; +let iframeMessageBound = false; +let sendListenersInstalled = false; +let sendClickHandler = null; +let sendKeydownHandler = null; + +/** + * ------------------------- + * Helpers + * -------------------------- + */ +function ensureSettings() { + const d = getDefaultSettings(); + const s = config || structuredClone(d); + + function deepMerge(target, src) { + for (const k of Object.keys(src)) { + if (src[k] && typeof src[k] === 'object' && !Array.isArray(src[k])) { + target[k] = target[k] ?? {}; + deepMerge(target[k], src[k]); + } else if (target[k] === undefined) { + target[k] = src[k]; + } + } + } + deepMerge(s, d); + if (!Array.isArray(s.responseKeepTags)) s.responseKeepTags = structuredClone(d.responseKeepTags); + else s.responseKeepTags = normalizeResponseKeepTags(s.responseKeepTags); + + // Migration: remove old keys that are no longer needed + delete s.includeCharacterLorebooks; + delete s.includeCharDesc; + delete s.includeCharPersonality; + delete s.includeCharScenario; + delete s.includeVectorRecall; + delete s.historyMessageCount; + delete s.worldbookActivationMode; + + config = s; + return s; +} + +function normalizeResponseKeepTags(tags) { + const src = Array.isArray(tags) ? tags : []; + const cleaned = []; + for (const raw of src) { + const t = String(raw || '') + .trim() + .replace(/^<+|>+$/g, '') + .toLowerCase(); + if (!/^[a-z][a-z0-9_-]*$/.test(t)) continue; + if (!cleaned.includes(t)) cleaned.push(t); + } + return cleaned; +} + +async function loadConfig() { + const loaded = await EnaPlannerStorage.get('config', null); + config = (loaded && typeof loaded === 'object') ? loaded : getDefaultSettings(); + ensureSettings(); + state.logs = Array.isArray(await EnaPlannerStorage.get('logs', [])) ? await EnaPlannerStorage.get('logs', []) : []; + + if (extension_settings?.[EXT_NAME]) { + delete extension_settings[EXT_NAME]; + saveSettingsDebounced?.(); + } + return config; +} + +async function saveConfigNow() { + ensureSettings(); + await EnaPlannerStorage.set('config', config); + await EnaPlannerStorage.set('logs', state.logs); + try { + return await EnaPlannerStorage.saveNow({ silent: false }); + } catch { + return false; + } +} + +function toastInfo(msg) { + if (window.toastr?.info) return window.toastr.info(msg); + console.log('[EnaPlanner]', msg); +} +function toastErr(msg) { + if (window.toastr?.error) return window.toastr.error(msg); + console.error('[EnaPlanner]', msg); +} + +function clampLogs() { + const s = ensureSettings(); + if (state.logs.length > s.logsMax) state.logs = state.logs.slice(0, s.logsMax); +} + +function persistLogsMaybe() { + const s = ensureSettings(); + if (!s.logsPersist) return; + state.logs = state.logs.slice(0, s.logsMax); + EnaPlannerStorage.set('logs', state.logs).catch(() => {}); +} + +function loadPersistedLogsMaybe() { + const s = ensureSettings(); + if (!s.logsPersist) state.logs = []; +} + +function nowISO() { + return new Date().toISOString(); +} + +function runWithTimeout(taskFactory, timeoutMs, timeoutMessage) { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs); + Promise.resolve() + .then(taskFactory) + .then(resolve) + .catch(reject) + .finally(() => clearTimeout(timer)); + }); +} + +function normalizeUrlBase(u) { + if (!u) return ''; + return u.replace(/\/+$/g, ''); +} + +function getDefaultPrefixByChannel(channel) { + if (channel === 'gemini') return '/v1beta'; + return '/v1'; +} + +function buildApiPrefix() { + const s = ensureSettings(); + if (s.api.prefixMode === 'custom' && s.api.customPrefix?.trim()) return s.api.customPrefix.trim(); + return getDefaultPrefixByChannel(s.api.channel); +} + +function buildUrl(path) { + const s = ensureSettings(); + const base = normalizeUrlBase(s.api.baseUrl); + const prefix = buildApiPrefix(); + const p = prefix.startsWith('/') ? prefix : `/${prefix}`; + const finalPrefix = p.replace(/\/+$/g, ''); + const finalPath = path.startsWith('/') ? path : `/${path}`; + const escapedPrefix = finalPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const hasSameSuffix = !!finalPrefix && new RegExp(`${escapedPrefix}$`, 'i').test(base); + const normalizedBase = hasSameSuffix ? base.slice(0, -finalPrefix.length) : base; + return `${normalizedBase}${finalPrefix}${finalPath}`; +} + +function setSendUIBusy(busy) { + const sendBtn = document.getElementById('send_but') || document.getElementById('send_button'); + const textarea = document.getElementById('send_textarea'); + if (sendBtn) sendBtn.disabled = !!busy; + if (textarea) textarea.disabled = !!busy; +} + +function safeStringify(val) { + if (val == null) return ''; + if (typeof val === 'string') return val; + try { return JSON.stringify(val, null, 2); } catch { return String(val); } +} + +/** + * ------------------------- + * ST context helpers + * -------------------------- + */ +function getContextSafe() { + try { return window.SillyTavern?.getContext?.() ?? null; } catch { return null; } +} + +function getCurrentCharSafe() { + try { + // Method 1: via getContext() + const ctx = getContextSafe(); + if (ctx) { + const cid = ctx.characterId ?? ctx.this_chid; + const chars = ctx.characters; + if (chars && cid != null && chars[cid]) return chars[cid]; + } + // Method 2: global this_chid + characters + const st = window.SillyTavern; + if (st) { + const chid = st.this_chid ?? window.this_chid; + const chars = st.characters ?? window.characters; + if (chars && chid != null && chars[chid]) return chars[chid]; + } + // Method 3: bare globals (some ST versions) + if (window.this_chid != null && window.characters) { + return window.characters[window.this_chid] ?? null; + } + } catch { } + return null; +} + +/** + * ------------------------- + * Character card — always include desc/personality/scenario + * -------------------------- + */ +function formatCharCardBlock(charObj) { + if (!charObj) return ''; + const name = charObj?.name ?? ''; + const description = charObj?.description ?? ''; + const personality = charObj?.personality ?? ''; + const scenario = charObj?.scenario ?? ''; + + const parts = []; + parts.push(`【角色卡】${name}`.trim()); + if (description) parts.push(`【description】\n${description}`); + if (personality) parts.push(`【personality】\n${personality}`); + if (scenario) parts.push(`【scenario】\n${scenario}`); + return parts.join('\n\n'); +} + +/** + * ------------------------- + * Chat history — ALL unhidden, AI responses ONLY + * Strip: unclosed think blocks, configurable tags + * -------------------------- + */ +function cleanAiMessageText(text) { + let out = String(text ?? ''); + + // 1) Strip everything before and including (handles unclosed think blocks) + out = out.replace(/^[\s\S]*?<\/think>/i, ''); + out = out.replace(/]*>[\s\S]*?<\/think>/gi, ''); + out = out.replace(/]*>[\s\S]*?<\/thinking>/gi, ''); + + // 2) Strip user-configured exclude tags + // NOTE: JS \b does NOT work after CJK characters, so we use [^>]*> instead. + // Order matters: try block match first (greedy), then mop up orphan open/close tags. + const s = ensureSettings(); + const tags = s.chatExcludeTags ?? []; + for (const tag of tags) { + if (!tag) continue; + const escaped = tag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + // First: match full block ... + const blockRe = new RegExp(`<${escaped}[^>]*>[\\s\\S]*?<\\/${escaped}>`, 'gi'); + out = out.replace(blockRe, ''); + // Then: mop up any orphan closing tags + const closeRe = new RegExp(`<\\/${escaped}>`, 'gi'); + out = out.replace(closeRe, ''); + // Finally: mop up orphan opening or self-closing tags or + const openRe = new RegExp(`<${escaped}(?:[^>]*)\\/?>`, 'gi'); + out = out.replace(openRe, ''); + } + + return out.trim(); +} + +function collectRecentChatSnippet(chat, maxMessages) { + if (!Array.isArray(chat) || chat.length === 0) return ''; + + // Filter: not system, not hidden, and NOT user messages (AI only) + const aiMessages = chat.filter(m => + !m?.is_system && !m?.is_user && !m?.extra?.hidden + ); + + if (!aiMessages.length) return ''; + + // If maxMessages specified, only take the last N + const selected = (maxMessages && maxMessages > 0) + ? aiMessages.slice(-maxMessages) + : aiMessages; + + const lines = []; + for (const m of selected) { + const name = m?.name ? `${m.name}` : 'assistant'; + const raw = (m?.mes ?? '').trim(); + if (!raw) continue; + const cleaned = cleanAiMessageText(raw); + if (!cleaned) continue; + lines.push(`[${name}] ${cleaned}`); + } + + if (!lines.length) return ''; + return `\n${lines.join('\n')}\n`; +} + +/** + * ------------------------- + * Plot extraction + * -------------------------- + */ +function extractLastNPlots(chat, n) { + if (!Array.isArray(chat) || chat.length === 0) return []; + const want = Math.max(0, Number(n) || 0); + if (!want) return []; + + const plots = []; + const plotRe = /]*>[\s\S]*?<\/plot>/gi; + + for (let i = chat.length - 1; i >= 0; i--) { + const text = chat[i]?.mes ?? ''; + if (!text) continue; + const matches = [...text.matchAll(plotRe)]; + for (let j = matches.length - 1; j >= 0; j--) { + plots.push(matches[j][0]); + if (plots.length >= want) return plots; + } + } + return plots; +} + +function formatPlotsBlock(plotList) { + if (!Array.isArray(plotList) || plotList.length === 0) return ''; + // plotList is [newest, ..., oldest] from extractLastNPlots + // Reverse to chronological: oldest first, newest last + const chrono = [...plotList].reverse(); + const lines = []; + chrono.forEach((p, idx) => { + lines.push(`【plot -${chrono.length - idx}】\n${p}`); + }); + return `\n${lines.join('\n\n')}\n`; +} + +/** + * ------------------------- + * Worldbook — read via ST API (like idle-watcher) + * Always read character-linked worldbooks. + * Optionally include global worldbooks. + * Activation: constant (blue) + keyword scan (green) only. + * -------------------------- + */ + +async function getCharacterWorldbooks() { + const ctx = getContextSafe(); + const charObj = getCurrentCharSafe(); + const worldNames = []; + + // From character object (multiple paths) + if (charObj) { + const paths = [ + charObj?.data?.extensions?.world, + charObj?.world, + charObj?.data?.character_book?.name, + ]; + for (const w of paths) { + if (w && !worldNames.includes(w)) worldNames.push(w); + } + } + + // From context + if (ctx) { + try { + const cid = ctx.characterId ?? ctx.this_chid; + const chars = ctx.characters ?? window.characters; + if (chars && cid != null) { + const c = chars[cid]; + const paths = [ + c?.data?.extensions?.world, + c?.world, + ]; + for (const w of paths) { + if (w && !worldNames.includes(w)) worldNames.push(w); + } + } + } catch { } + + // ST context may expose chat-linked worldbooks via world_names + try { + if (ctx.worldNames && Array.isArray(ctx.worldNames)) { + for (const w of ctx.worldNames) { + if (w && !worldNames.includes(w)) worldNames.push(w); + } + } + } catch { } + } + + // Fallback: try ST's selected character world info + try { + const sw = window.selected_world_info; + if (typeof sw === 'string' && sw && !worldNames.includes(sw)) { + worldNames.push(sw); + } + } catch { } + + // Fallback: try reading from chat metadata + try { + const chat = ctx?.chat ?? []; + if (chat.length > 0 && chat[0]?.extra?.world) { + const w = chat[0].extra.world; + if (!worldNames.includes(w)) worldNames.push(w); + } + } catch { } + + console.log('[EnaPlanner] Character worldbook names found:', worldNames); + return worldNames.filter(Boolean); +} + +async function getGlobalWorldbooks() { + // Try to get the list of currently active global worldbooks + try { + // ST stores active worldbooks in world_info settings + const ctx = getContextSafe(); + if (ctx?.world_info?.globalSelect) { + return Array.isArray(ctx.world_info.globalSelect) ? ctx.world_info.globalSelect : []; + } + } catch { } + + // Fallback: try window.selected_world_info + try { + if (window.selected_world_info && Array.isArray(window.selected_world_info)) { + return window.selected_world_info; + } + } catch { } + + return []; +} + +async function getWorldbookData(worldName) { + if (!worldName) return null; + try { + const response = await fetch('/api/worldinfo/get', { + method: 'POST', + headers: getRequestHeaders(), + body: JSON.stringify({ name: worldName }), + }); + if (response.ok) { + const data = await response.json(); + // ST returns { entries: {...} } or { entries: [...] } + let entries = data?.entries; + if (entries && !Array.isArray(entries)) { + entries = Object.values(entries); + } + return { name: worldName, entries: entries || [] }; + } + } catch (e) { + console.warn(`[EnaPlanner] Failed to load worldbook "${worldName}":`, e); + } + return null; +} + +function keywordPresent(text, kw) { + if (!kw) return false; + return text.toLowerCase().includes(kw.toLowerCase()); +} + +function matchSelective(entry, scanText) { + const keys = Array.isArray(entry?.key) ? entry.key.filter(Boolean) : []; + const keys2 = Array.isArray(entry?.keysecondary) ? entry.keysecondary.filter(Boolean) : []; + + const total = keys.length; + if (total === 0) return false; + const hit = keys.reduce((acc, kw) => acc + (keywordPresent(scanText, kw) ? 1 : 0), 0); + + let ok = false; + const logic = entry?.selectiveLogic ?? 0; + if (logic === 0) ok = (total === 0) ? true : hit > 0; // and_any + else if (logic === 1) ok = (total === 0) ? true : hit < total; // not_all + else if (logic === 2) ok = (total === 0) ? true : hit === 0; // not_any + else if (logic === 3) ok = (total === 0) ? true : hit === total; // and_all + + if (!ok) return false; + + if (keys2.length) { + const hit2 = keys2.reduce((acc, kw) => acc + (keywordPresent(scanText, kw) ? 1 : 0), 0); + if (hit2 <= 0) return false; + } + return true; +} + +function sortWorldEntries(entries) { + // Sort to mimic ST insertion order within our worldbook block. + // Position priority: 0 (before char def) → 1 (after char def) → 4 (system depth) + // Within pos=4: depth descending (bigger depth = further from chat = earlier) + // Same position+depth: order ascending (higher order = closer to chat_history = later) + const posPriority = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4 }; + return [...entries].sort((a, b) => { + const pa = posPriority[Number(a?.position ?? 0)] ?? 99; + const pb = posPriority[Number(b?.position ?? 0)] ?? 99; + if (pa !== pb) return pa - pb; + // For same position (especially pos=4): bigger depth = earlier + const da = Number(a?.depth ?? 0); + const db = Number(b?.depth ?? 0); + if (da !== db) return db - da; + // Same position+depth: order ascending (smaller order first, bigger order later) + const oa = Number(a?.order ?? 0); + const ob = Number(b?.order ?? 0); + return oa - ob; + }); +} + +async function buildWorldbookBlock(scanText) { + const s = ensureSettings(); + + // 1. Always get character-linked worldbooks + const charWorldNames = await getCharacterWorldbooks(); + + // 2. Optionally get global worldbooks + let globalWorldNames = []; + if (s.includeGlobalWorldbooks) { + globalWorldNames = await getGlobalWorldbooks(); + } + + // Deduplicate + const allWorldNames = [...new Set([...charWorldNames, ...globalWorldNames])]; + + if (!allWorldNames.length) { + console.log('[EnaPlanner] No worldbooks to load'); + return ''; + } + + console.log('[EnaPlanner] Loading worldbooks:', allWorldNames); + + // Fetch all worldbook data + const worldbookResults = await Promise.all(allWorldNames.map(name => getWorldbookData(name))); + const allEntries = []; + + for (const wb of worldbookResults) { + if (!wb || !wb.entries) continue; + for (const entry of wb.entries) { + if (!entry) continue; + allEntries.push({ ...entry, _worldName: wb.name }); + } + } + + // Filter: not disabled + let entries = allEntries.filter(e => !e?.disable && !e?.disabled); + + // Filter: exclude entries whose name contains any of the configured exclude patterns + const nameExcludes = s.worldbookExcludeNames ?? ['mvu_update']; + entries = entries.filter(e => { + const comment = String(e?.comment || e?.name || e?.title || ''); + for (const pat of nameExcludes) { + if (pat && comment.includes(pat)) return false; + } + return true; + }); + + // Filter: exclude position=4 if configured + if (s.excludeWorldbookPosition4) { + entries = entries.filter(e => Number(e?.position) !== 4); + } + + if (!entries.length) return ''; + + // Activation: constant (blue) + keyword scan (green) only + const active = []; + for (const e of entries) { + // Blue light: constant entries always included + if (e?.constant) { + active.push(e); + continue; + } + // Green light: keyword-triggered entries + if (matchSelective(e, scanText)) { + active.push(e); + continue; + } + } + + if (!active.length) return ''; + + // Build EJS context for rendering worldbook templates + const ejsCtx = buildEjsContext(); + + const sorted = sortWorldEntries(active); + const parts = []; + for (const e of sorted) { + const comment = e?.comment || e?.name || e?.title || ''; + const head = `【WorldBook:${e._worldName}】${comment ? ' ' + comment : ''}`.trim(); + let body = String(e?.content ?? '').trim(); + if (!body) continue; + + // Try EJS rendering if the entry contains EJS tags + if (body.includes('<%')) { + body = renderEjsTemplate(body, ejsCtx); + } + + parts.push(`${head}\n${body}`); + } + + if (!parts.length) return ''; + return `\n${parts.join('\n\n---\n\n')}\n`; +} + +/** + * ------------------------- + * EJS rendering for worldbook entries + * -------------------------- + */ +function getChatVariables() { + let vars = {}; + + // 1) Chat-level variables + try { + const ctx = getContextSafe(); + if (ctx?.chatMetadata?.variables) vars = { ...ctx.chatMetadata.variables }; + } catch {} + if (!Object.keys(vars).length) { + try { + if (window.chat_metadata?.variables) vars = { ...window.chat_metadata.variables }; + } catch {} + } + if (!Object.keys(vars).length) { + try { + const ctx = getContextSafe(); + if (ctx?.chat_metadata?.variables) vars = { ...ctx.chat_metadata.variables }; + } catch {} + } + + // 2) Always merge message-level variables (some presets store vars here instead of chat-level) + try { + const msgVars = getLatestMessageVarTable(); + if (msgVars && typeof msgVars === 'object') { + for (const key of Object.keys(msgVars)) { + // Skip MVU internal metadata keys + if (key === 'schema' || key === 'display_data' || key === 'delta_data') continue; + if (vars[key] === undefined) { + // Chat-level doesn't have this key at all — take from message-level + vars[key] = msgVars[key]; + } else if ( + vars[key] && typeof vars[key] === 'object' && !Array.isArray(vars[key]) && + msgVars[key] && typeof msgVars[key] === 'object' && !Array.isArray(msgVars[key]) + ) { + // Both have this key as objects — shallow merge (message-level fills gaps) + for (const subKey of Object.keys(msgVars[key])) { + if (vars[key][subKey] === undefined) { + vars[key][subKey] = msgVars[key][subKey]; + } + } + } + } + } + } catch {} + + return vars; +} + +function buildEjsContext() { + const vars = getChatVariables(); + + // getvar: read a chat variable (supports dot-path for nested objects) + function getvar(name) { + if (!name) return ''; + let val; + if (vars[name] !== undefined) { + val = vars[name]; + } else { + const parts = String(name).split('.'); + let cur = vars; + for (const p of parts) { + if (cur == null || typeof cur !== 'object') return ''; + cur = cur[p]; + } + val = cur ?? ''; + } + // 字符串布尔值转为真正的布尔值 + if (val === 'false' || val === 'False' || val === 'FALSE') return false; + if (val === 'true' || val === 'True' || val === 'TRUE') return true; + return val; + } + + // setvar: write a chat variable (no-op for our purposes, just to avoid errors) + function setvar(name, value) { + if (name) vars[name] = value; + return value; + } + + return { + getvar, setvar, + vars, + Number, Math, JSON, String, Array, Object, parseInt, parseFloat, + console: { log: () => { }, warn: () => { }, error: () => { } }, + }; +} + +function renderEjsTemplate(template, ctx) { + // Try window.ejs first (ST loads this library) + if (window.ejs?.render) { + try { + return window.ejs.render(template, ctx, { async: false }); + } catch (e) { + console.warn('[EnaPlanner] EJS render failed, trying fallback:', e?.message); + } + } + + // Safe degradation when ejs is not available. + console.warn('[EnaPlanner] window.ejs not available, skipping EJS rendering. Template returned as-is.'); + return template; +} + +/** + * ------------------------- + * Template rendering helpers + * -------------------------- + */ +async function prepareEjsEnv() { + try { + const et = window.EjsTemplate; + if (!et) return null; + const fn = et.prepareContext || et.preparecontext; + if (typeof fn !== 'function') return null; + return await fn.call(et, {}); + } catch { return null; } +} + +async function evalEjsIfPossible(text, env) { + try { + const et = window.EjsTemplate; + if (!et || !env) return text; + const fn = et.evalTemplate || et.evaltemplate; + if (typeof fn !== 'function') return text; + return await fn.call(et, text, env); + } catch { return text; } +} + +function substituteMacrosViaST(text) { + try { return substituteParamsExtended(text); } catch { return text; } +} + +function deepGet(obj, path) { + if (!obj || !path) return undefined; + const parts = path.split('.').filter(Boolean); + let cur = obj; + for (const p of parts) { + if (cur == null) return undefined; + cur = cur[p]; + } + return cur; +} + +function resolveGetMessageVariableMacros(text, messageVars) { + return text.replace(/{{\s*get_message_variable::([^}]+)\s*}}/g, (_, rawPath) => { + const path = String(rawPath || '').trim(); + if (!path) return ''; + return safeStringify(deepGet(messageVars, path)); + }); +} + +function resolveFormatMessageVariableMacros(text, messageVars) { + return text.replace(/{{\s*format_message_variable::([^}]+)\s*}}/g, (_, rawPath) => { + const path = String(rawPath || '').trim(); + if (!path) return ''; + const val = deepGet(messageVars, path); + if (val == null) return ''; + if (typeof val === 'string') return val; + try { return jsyaml.dump(val, { lineWidth: -1, noRefs: true }); } catch { return safeStringify(val); } + }); +} + +function getLatestMessageVarTable() { + try { + if (window.Mvu?.getMvuData) { + return window.Mvu.getMvuData({ type: 'message', message_id: 'latest' }); + } + } catch { } + try { + const getVars = window.TavernHelper?.getVariables || window.Mvu?.getMvuData; + if (typeof getVars === 'function') { + return getVars({ type: 'message', message_id: 'latest' }); + } + } catch { } + return {}; +} + +async function renderTemplateAll(text, env, messageVars) { + let out = String(text ?? ''); + out = await evalEjsIfPossible(out, env); + out = substituteMacrosViaST(out); + out = resolveGetMessageVariableMacros(out, messageVars); + out = resolveFormatMessageVariableMacros(out, messageVars); + return out; +} + +/** + * ------------------------- + * Planner response filtering + * -------------------------- + */ +function stripThinkBlocks(text) { + let out = String(text ?? ''); + out = out.replace(/]*>[\s\S]*?<\/think>/gi, ''); + out = out.replace(/]*>[\s\S]*?<\/thinking>/gi, ''); + return out.trim(); +} + +function extractSelectedBlocksInOrder(text, tagNames) { + const names = normalizeResponseKeepTags(tagNames); + if (!Array.isArray(names) || names.length === 0) return ''; + const src = String(text ?? ''); + const blocks = []; + const escapedNames = names.map(n => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); + const re = new RegExp(`<(${escapedNames.join('|')})\\b[^>]*>[\\s\\S]*?<\\/\\1>`, 'gi'); + let m; + while ((m = re.exec(src)) !== null) { + blocks.push(m[0]); + } + return blocks.join('\n\n').trim(); +} + +function filterPlannerForInput(rawFull) { + const noThink = stripThinkBlocks(rawFull); + const tags = ensureSettings().responseKeepTags; + const selected = extractSelectedBlocksInOrder(noThink, tags); + if (selected) return selected; + return noThink; +} + +function filterPlannerPreview(rawPartial) { + return stripThinkBlocks(rawPartial); +} + +/** + * ------------------------- + * Planner API calls + * -------------------------- + */ +async function callPlanner(messages, options = {}) { + const s = ensureSettings(); + if (!s.api.baseUrl) throw new Error('未配置 API URL'); + if (!s.api.apiKey) throw new Error('未配置 API KEY'); + if (!s.api.model) throw new Error('未选择模型'); + + const url = buildUrl('/chat/completions'); + + const body = { + model: s.api.model, + messages, + stream: !!s.api.stream + }; + + const t = Number(s.api.temperature); + if (!Number.isNaN(t)) body.temperature = t; + const tp = Number(s.api.top_p); + if (!Number.isNaN(tp)) body.top_p = tp; + const tk = Number(s.api.top_k); + if (!Number.isNaN(tk) && tk > 0) body.top_k = tk; + const pp = s.api.presence_penalty === '' ? null : Number(s.api.presence_penalty); + if (pp != null && !Number.isNaN(pp)) body.presence_penalty = pp; + const fp = s.api.frequency_penalty === '' ? null : Number(s.api.frequency_penalty); + if (fp != null && !Number.isNaN(fp)) body.frequency_penalty = fp; + const mt = s.api.max_tokens === '' ? null : Number(s.api.max_tokens); + if (mt != null && !Number.isNaN(mt) && mt > 0) body.max_tokens = mt; + + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), PLANNER_REQUEST_TIMEOUT_MS); + try { + const res = await fetch(url, { + method: 'POST', + headers: { + ...getRequestHeaders(), + Authorization: `Bearer ${s.api.apiKey}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(body), + signal: controller.signal + }); + + if (!res.ok) { + const text = await res.text().catch(() => ''); + throw new Error(`规划请求失败: ${res.status} ${text}`.slice(0, 500)); + } + + if (!s.api.stream) { + const data = await res.json(); + const text = String(data?.choices?.[0]?.message?.content ?? data?.choices?.[0]?.text ?? ''); + if (text) options?.onDelta?.(text, text); + return text; + } + + // SSE stream + const reader = res.body.getReader(); + const decoder = new TextDecoder('utf-8'); + let buf = ''; + let full = ''; + + while (true) { + const { value, done } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + const chunks = buf.split('\n\n'); + buf = chunks.pop() ?? ''; + + for (const ch of chunks) { + const lines = ch.split('\n').map(x => x.trim()).filter(Boolean); + for (const line of lines) { + if (!line.startsWith('data:')) continue; + const payload = line.slice(5).trim(); + if (payload === '[DONE]') continue; + try { + const j = JSON.parse(payload); + const delta = j?.choices?.[0]?.delta; + const piece = delta?.content ?? delta?.text ?? ''; + if (piece) { + full += piece; + options?.onDelta?.(piece, full); + } + } catch { } + } + } + } + return full; + } catch (err) { + if (controller.signal.aborted || err?.name === 'AbortError') { + throw new Error(`规划请求超时(>${Math.floor(PLANNER_REQUEST_TIMEOUT_MS / 1000)}s)`); + } + throw err; + } finally { + clearTimeout(timeoutId); + } +} + +async function fetchModelsForUi() { + const s = ensureSettings(); + if (!s.api.baseUrl) throw new Error('请先填写 API URL'); + if (!s.api.apiKey) throw new Error('请先填写 API KEY'); + const url = buildUrl('/models'); + const res = await fetch(url, { + method: 'GET', + headers: { + ...getRequestHeaders(), + Authorization: `Bearer ${s.api.apiKey}` + } + }); + if (!res.ok) { + const text = await res.text().catch(() => ''); + throw new Error(`拉取模型失败: ${res.status} ${text}`.slice(0, 300)); + } + const data = await res.json(); + const list = Array.isArray(data?.data) ? data.data : []; + return list.map(x => x?.id).filter(Boolean); +} + +async function debugWorldbookForUi() { + let out = '正在诊断世界书读取...\n'; + const charWb = await getCharacterWorldbooks(); + out += `角色世界书名称: ${JSON.stringify(charWb)}\n`; + const globalWb = await getGlobalWorldbooks(); + out += `全局世界书名称: ${JSON.stringify(globalWb)}\n`; + const all = [...new Set([...charWb, ...globalWb])]; + for (const name of all) { + const data = await getWorldbookData(name); + const count = data?.entries?.length ?? 0; + const enabled = data?.entries?.filter(e => !e?.disable && !e?.disabled)?.length ?? 0; + out += ` "${name}": ${count} 条目, ${enabled} 已启用\n`; + } + if (!all.length) { + out += '⚠️ 未找到任何世界书。请检查角色卡是否绑定了世界书。\n'; + const charObj = getCurrentCharSafe(); + out += `charObj存在: ${!!charObj}\n`; + if (charObj) { + out += `charObj.world: ${charObj?.world}\n`; + out += `charObj.data.extensions.world: ${charObj?.data?.extensions?.world}\n`; + } + const ctx = getContextSafe(); + out += `ctx存在: ${!!ctx}\n`; + if (ctx) { + out += `ctx.characterId: ${ctx?.characterId}\n`; + out += `ctx.this_chid: ${ctx?.this_chid}\n`; + } + } + return out; +} + +function debugCharForUi() { + const charObj = getCurrentCharSafe(); + if (!charObj) { + const ctx = getContextSafe(); + return [ + '⚠️ 未检测到角色。', + `ctx: ${!!ctx}, ctx.characterId: ${ctx?.characterId}, ctx.this_chid: ${ctx?.this_chid}`, + `window.this_chid: ${window.this_chid}`, + `window.characters count: ${window.characters?.length ?? 'N/A'}` + ].join('\n'); + } + const block = formatCharCardBlock(charObj); + return [ + `角色名: ${charObj?.name}`, + `desc长度: ${(charObj?.description ?? '').length}`, + `personality长度: ${(charObj?.personality ?? '').length}`, + `scenario长度: ${(charObj?.scenario ?? '').length}`, + `world: ${charObj?.world ?? charObj?.data?.extensions?.world ?? '(无)'}`, + `---\n${block.slice(0, 500)}...` + ].join('\n'); +} + +/** + * ------------------------- + * Build planner messages + * -------------------------- + */ +function getPromptBlocksByRole(role) { + const s = ensureSettings(); + return (s.promptBlocks || []).filter(b => b?.role === role && String(b?.content ?? '').trim()); +} + +async function buildPlannerMessages(rawUserInput) { + const s = ensureSettings(); + const ctx = getContextSafe(); + const chat = ctx?.chat ?? window.SillyTavern?.chat ?? []; + const charObj = getCurrentCharSafe(); + const env = await prepareEjsEnv(); + const messageVars = getLatestMessageVarTable(); + + const enaSystemBlocks = getPromptBlocksByRole('system'); + const enaAssistantBlocks = getPromptBlocksByRole('assistant'); + const enaUserBlocks = getPromptBlocksByRole('user'); + + const charBlockRaw = formatCharCardBlock(charObj); + + // --- BME memory: planner-safe recall with history/vector guards --- + let memoryBlock = ''; + let memorySource = 'none'; + if (_bmeRuntime?.runPlannerRecallForEna) { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), VECTOR_RECALL_TIMEOUT_MS); + try { + const recall = await _bmeRuntime.runPlannerRecallForEna({ + rawUserInput, + signal: controller.signal, + disableLlmRecall: true, + }); + if (recall?.ok && recall.memoryBlock) { + memoryBlock = recall.memoryBlock; + memorySource = 'bme'; + } + } catch (e) { + if (e?.name === 'AbortError') { + console.warn(`[Ena] BME recall timed out (> ${Math.floor(VECTOR_RECALL_TIMEOUT_MS / 1000)}s)`); + } else { + console.warn('[Ena] BME planner recall failed:', e); + } + } finally { + clearTimeout(timeoutId); + } + } + console.log(`[Ena] Memory source: ${memorySource}`); + + // --- Chat history: last 2 AI messages (floors N-1 & N-3) --- + // Two messages instead of one to avoid cross-device cache miss: + // Keep two recent assistant messages so planner prompt still has + // a little continuity even when memory recall returns empty. + const recentChatRaw = collectRecentChatSnippet(chat, 2); + + const plotsRaw = formatPlotsBlock(extractLastNPlots(chat, s.plotCount)); + + // Build scanText for worldbook keyword activation + const scanText = [charBlockRaw, recentChatRaw, plotsRaw, rawUserInput].join('\n\n'); + + const worldbookRaw = await buildWorldbookBlock(scanText); + + // Render templates/macros + const charBlock = await renderTemplateAll(charBlockRaw, env, messageVars); + const recentChat = await renderTemplateAll(recentChatRaw, env, messageVars); + const plots = await renderTemplateAll(plotsRaw, env, messageVars); + const bmeMemory = memoryBlock || ''; + const worldbook = await renderTemplateAll(worldbookRaw, env, messageVars); + const userInput = await renderTemplateAll(rawUserInput, env, messageVars); + + const messages = []; + + // 1) Ena system prompts + for (const b of enaSystemBlocks) { + const content = await renderTemplateAll(b.content, env, messageVars); + messages.push({ role: 'system', content }); + } + + // 2) Character card + if (String(charBlock).trim()) messages.push({ role: 'system', content: charBlock }); + + // 3) Worldbook + if (String(worldbook).trim()) messages.push({ role: 'system', content: worldbook }); + + // 4) Chat history (last 2 AI responses — floors N-1 & N-3) + if (String(recentChat).trim()) messages.push({ role: 'system', content: recentChat }); + + // 4.5) BME memory — after chat context, before plots + if (bmeMemory.trim()) { + messages.push({ role: 'system', content: `\n${bmeMemory}\n` }); + } + + // 5) Previous plots + if (String(plots).trim()) messages.push({ role: 'system', content: plots }); + + // 6) User input (with friendly framing) + const userMsgContent = `以下是玩家的最新指令哦~:\n[${userInput}]`; + messages.push({ role: 'user', content: userMsgContent }); + + // Extra user blocks before user message + for (const b of enaUserBlocks) { + const content = await renderTemplateAll(b.content, env, messageVars); + messages.splice(Math.max(0, messages.length - 1), 0, { role: 'system', content: `【extra-user-block】\n${content}` }); + } + + // 7) Assistant blocks + for (const b of enaAssistantBlocks) { + const content = await renderTemplateAll(b.content, env, messageVars); + messages.push({ role: 'assistant', content }); + } + + return { messages, meta: { charBlockRaw, worldbookRaw, recentChatRaw, memoryBlockLen: memoryBlock.length, plotsRaw } }; +} + +/** + * ------------------------- + * Planning runner + logging + * -------------------------- + */ +async function runPlanningOnce(rawUserInput, silent = false, options = {}) { + const s = ensureSettings(); + + const log = { + time: nowISO(), ok: false, model: s.api.model, + requestMessages: [], rawReply: '', filteredReply: '', error: '' + }; + + try { + const { messages } = await buildPlannerMessages(rawUserInput); + log.requestMessages = messages; + + const rawReply = await callPlanner(messages, options); + log.rawReply = rawReply; + + const filtered = filterPlannerForInput(rawReply); + log.filteredReply = filtered; + log.ok = true; + + state.logs.unshift(log); clampLogs(); persistLogsMaybe(); + return { rawReply, filtered }; + } catch (e) { + log.error = String(e?.message ?? e); + state.logs.unshift(log); clampLogs(); persistLogsMaybe(); + if (!silent) toastErr(log.error); + throw e; + } +} + +/** + * ------------------------- + * Intercept send + * -------------------------- + */ +function getSendTextarea() { return document.getElementById('send_textarea'); } +function getSendButton() { return document.getElementById('send_but') || document.getElementById('send_button'); } + +function shouldInterceptNow() { + const s = ensureSettings(); + if (!s.enabled || state.isPlanning) return false; + const ta = getSendTextarea(); + if (!ta) return false; + const txt = String(ta.value ?? '').trim(); + if (!txt) return false; + if (state.bypassNextSend) return false; + if (s.skipIfPlotPresent && / { state.bypassNextSend = false; }, 800); + } +} + +function installSendInterceptors() { + if (sendListenersInstalled) return; + sendClickHandler = (e) => { + const btn = getSendButton(); + if (!btn) return; + if (e.target !== btn && !btn.contains(e.target)) return; + if (!shouldInterceptNow()) return; + e.preventDefault(); + e.stopImmediatePropagation(); + doInterceptAndPlanThenSend().catch(err => toastErr(String(err?.message ?? err))); + }; + sendKeydownHandler = (e) => { + const ta = getSendTextarea(); + if (!ta || e.target !== ta) return; + if (e.key === 'Enter' && !e.shiftKey) { + if (!shouldInterceptNow()) return; + e.preventDefault(); + e.stopImmediatePropagation(); + doInterceptAndPlanThenSend().catch(err => toastErr(String(err?.message ?? err))); + } + }; + document.addEventListener('click', sendClickHandler, true); + document.addEventListener('keydown', sendKeydownHandler, true); + sendListenersInstalled = true; +} + +function uninstallSendInterceptors() { + if (!sendListenersInstalled) return; + if (sendClickHandler) document.removeEventListener('click', sendClickHandler, true); + if (sendKeydownHandler) document.removeEventListener('keydown', sendKeydownHandler, true); + sendClickHandler = null; + sendKeydownHandler = null; + sendListenersInstalled = false; +} + +function getIframeConfigPayload() { + const s = ensureSettings(); + return { + ...s, + logs: state.logs, + }; +} + +function openSettings() { + if (document.getElementById(OVERLAY_ID)) return; + + overlay = document.createElement('div'); + overlay.id = OVERLAY_ID; + overlay.style.cssText = ` + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: ${window.innerHeight}px; + background: rgba(0,0,0,0.5); + z-index: 99999; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + `; + + const iframe = document.createElement('iframe'); + iframe.src = getHtmlPath(); + iframe.style.cssText = ` + width: min(1200px, 96vw); + height: min(980px, 94vh); + max-height: calc(100% - 24px); + border: none; + border-radius: 12px; + background: #1a1a1a; + `; + + overlay.appendChild(iframe); + document.body.appendChild(overlay); + + if (!iframeMessageBound) { + // Guarded by isTrustedIframeEvent (origin + source). + // eslint-disable-next-line no-restricted-syntax + window.addEventListener('message', handleIframeMessage); + iframeMessageBound = true; + } +} + +function closeSettings() { + const overlayEl = document.getElementById(OVERLAY_ID); + if (overlayEl) overlayEl.remove(); + overlay = null; +} + +async function handleIframeMessage(ev) { + const iframe = overlay?.querySelector('iframe'); + if (!isTrustedIframeEvent(ev, iframe)) return; + if (!ev.data?.type?.startsWith('xb-ena:')) return; + + const { type, payload } = ev.data; + switch (type) { + case 'xb-ena:ready': + postToIframe(iframe, { type: 'xb-ena:config', payload: getIframeConfigPayload() }); + break; + case 'xb-ena:close': + closeSettings(); + break; + case 'xb-ena:save-config': { + const requestId = payload?.requestId || ''; + const patch = (payload && typeof payload.patch === 'object') ? payload.patch : payload; + Object.assign(ensureSettings(), patch || {}); + const ok = await saveConfigNow(); + if (ok) { + postToIframe(iframe, { + type: 'xb-ena:config-saved', + payload: { + ...getIframeConfigPayload(), + requestId + } + }); + } else { + postToIframe(iframe, { + type: 'xb-ena:config-save-error', + payload: { + message: '保存失败', + requestId + } + }); + } + break; + } + case 'xb-ena:reset-prompt-default': { + const requestId = payload?.requestId || ''; + const s = ensureSettings(); + s.promptBlocks = getDefaultSettings().promptBlocks; + const ok = await saveConfigNow(); + if (ok) { + postToIframe(iframe, { + type: 'xb-ena:config-saved', + payload: { + ...getIframeConfigPayload(), + requestId + } + }); + } else { + postToIframe(iframe, { + type: 'xb-ena:config-save-error', + payload: { + message: '重置失败', + requestId + } + }); + } + break; + } + case 'xb-ena:run-test': { + try { + const fake = payload?.text || '(测试输入)我想让你帮我规划下一步剧情。'; + await runPlanningOnce(fake, true); + postToIframe(iframe, { type: 'xb-ena:test-done' }); + postToIframe(iframe, { type: 'xb-ena:logs', payload: { logs: state.logs } }); + } catch (err) { + postToIframe(iframe, { type: 'xb-ena:test-error', payload: { message: String(err?.message ?? err) } }); + } + break; + } + case 'xb-ena:logs-request': + postToIframe(iframe, { type: 'xb-ena:logs', payload: { logs: state.logs } }); + break; + case 'xb-ena:logs-clear': + state.logs = []; + await saveConfigNow(); + postToIframe(iframe, { type: 'xb-ena:logs', payload: { logs: state.logs } }); + break; + case 'xb-ena:fetch-models': { + try { + const models = await fetchModelsForUi(); + postToIframe(iframe, { type: 'xb-ena:models', payload: { models } }); + } catch (err) { + postToIframe(iframe, { type: 'xb-ena:models-error', payload: { message: String(err?.message ?? err) } }); + } + break; + } + case 'xb-ena:debug-worldbook': { + try { + const output = await debugWorldbookForUi(); + postToIframe(iframe, { type: 'xb-ena:debug-output', payload: { output } }); + } catch (err) { + postToIframe(iframe, { type: 'xb-ena:debug-output', payload: { output: String(err?.message ?? err) } }); + } + break; + } + case 'xb-ena:debug-char': { + const output = debugCharForUi(); + postToIframe(iframe, { type: 'xb-ena:debug-output', payload: { output } }); + break; + } + } +} + +export async function initEnaPlanner(bmeRuntime) { + _bmeRuntime = bmeRuntime || null; + await migrateFromLWBIfNeeded(); + await loadConfig(); + loadPersistedLogsMaybe(); + installSendInterceptors(); + window.stBmeEnaPlanner = { openSettings, closeSettings }; +} + +export function cleanupEnaPlanner() { + uninstallSendInterceptors(); + closeSettings(); + if (iframeMessageBound) { + window.removeEventListener('message', handleIframeMessage); + iframeMessageBound = false; + } + delete window.stBmeEnaPlanner; + _bmeRuntime = null; +} + diff --git a/index.js b/index.js index bbb05fe..1897b56 100644 --- a/index.js +++ b/index.js @@ -7408,6 +7408,120 @@ function buildRecallRetrieveOptions(settings, context) { }; } +async function runPlannerRecallForEna({ + rawUserInput, + signal = undefined, + disableLlmRecall = true, +} = {}) { + const userMessage = normalizeRecallInputText(rawUserInput || ""); + if (!userMessage) { + return { + ok: false, + reason: "empty-user-input", + memoryBlock: "", + recentMessages: [], + result: null, + }; + } + + const settings = getSettings(); + if (!settings.enabled || !settings.recallEnabled) { + return { + ok: false, + reason: "recall-disabled", + memoryBlock: "", + recentMessages: [], + result: null, + }; + } + + if (signal?.aborted) { + throw signal.reason instanceof Error + ? signal.reason + : createAbortError("Ena Planner recall aborted"); + } + + if (!currentGraph || !isGraphReadableForRecall()) { + return { + ok: false, + reason: "graph-not-readable", + memoryBlock: "", + recentMessages: [], + result: null, + }; + } + + if ( + !Array.isArray(currentGraph.nodes) || + currentGraph.nodes.length === 0 + ) { + return { + ok: false, + reason: "graph-empty", + memoryBlock: "", + recentMessages: [], + result: null, + }; + } + + if (isGraphMetadataWriteAllowed()) { + const recovered = await recoverHistoryIfNeeded("pre-ena-planner-recall"); + if (!recovered) { + return { + ok: false, + reason: "history-recovery-not-ready", + memoryBlock: "", + recentMessages: [], + result: null, + }; + } + } + + if (signal?.aborted) { + throw signal.reason instanceof Error + ? signal.reason + : createAbortError("Ena Planner recall aborted"); + } + + await ensureVectorReadyIfNeeded("pre-ena-planner-recall", signal); + + const context = getContext(); + const chat = context?.chat ?? []; + const recentMessages = buildRecallRecentMessages( + chat, + clampInt(settings.recallLlmContextMessages, 4, 0, 20), + userMessage, + ); + const schema = getSchema(); + const baseOptions = buildRecallRetrieveOptions(settings, context); + const options = { + ...baseOptions, + enableLLMRecall: disableLlmRecall + ? false + : baseOptions.enableLLMRecall, + }; + + const result = await retrieve({ + graph: currentGraph, + userMessage, + recentMessages, + embeddingConfig: getEmbeddingConfig(), + schema, + settings, + signal, + options, + }); + const memoryBlock = formatInjection(result, schema).trim(); + + return { + ok: Boolean(memoryBlock), + reason: memoryBlock ? "completed" : "empty-memory-block", + memoryBlock, + recentMessages, + result, + }; +} + /** * 召回管线:检索并注入记忆 */ @@ -8054,5 +8168,16 @@ async function onReembedDirect() { }); schedulePersistedRecallMessageUiRefresh(120); + try { + const { initEnaPlanner } = await import("./ena-planner/ena-planner.js"); + await initEnaPlanner({ + getContext, + getExtensionPath: () => `scripts/extensions/third-party/${MODULE_NAME}`, + runPlannerRecallForEna, + }); + console.log("[ST-BME] Ena Planner module loaded"); + } catch (error) { + console.warn("[ST-BME] Ena Planner module load failed:", error); + } console.log("[ST-BME] 初始化完成"); })(); diff --git a/planner-tag-utils.js b/planner-tag-utils.js new file mode 100644 index 0000000..9831578 --- /dev/null +++ b/planner-tag-utils.js @@ -0,0 +1,25 @@ +const DEFAULT_PLANNER_TAGS = ["plot", "note", "plot-log", "state"]; + +export function stripPlannerTags(text, tags = DEFAULT_PLANNER_TAGS) { + let output = String(text ?? ""); + + for (const rawTag of Array.isArray(tags) ? tags : DEFAULT_PLANNER_TAGS) { + const tag = String(rawTag || "").trim().toLowerCase(); + if (!tag) continue; + const escaped = tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + output = output.replace( + new RegExp(`<${escaped}\\b[^>]*>[\\s\\S]*?<\\/${escaped}>`, "gi"), + "", + ); + } + + return output.trim(); +} + +export function sanitizePlannerMessageText(message, tags = DEFAULT_PLANNER_TAGS) { + if (!message) return ""; + const text = String(message.mes ?? ""); + return message.is_user ? stripPlannerTags(text, tags) : text; +} + +export { DEFAULT_PLANNER_TAGS }; diff --git a/ui-status.js b/ui-status.js index 54449a7..4bd9634 100644 --- a/ui-status.js +++ b/ui-status.js @@ -1,6 +1,7 @@ // ST-BME: UI 状态工厂、纯工具函数 // 此模块中的函数均不依赖 index.js 模块级可变状态, // 可被 index.js 及其他模块安全导入。 +import { sanitizePlannerMessageText } from "./planner-tag-utils.js"; // ═══════════════════════════════════════════════════════════ // 常量 @@ -309,7 +310,7 @@ export function shouldRunRecallForTransaction(transaction, hookName) { } export function formatRecallContextLine(message) { - return `[${message.is_user ? "user" : "assistant"}]: ${message.mes || ""}`; + return `[${message.is_user ? "user" : "assistant"}]: ${sanitizePlannerMessageText(message)}`; } // ═══════════════════════════════════════════════════════════ diff --git a/vendor/js-yaml.mjs b/vendor/js-yaml.mjs new file mode 100644 index 0000000..be71cad --- /dev/null +++ b/vendor/js-yaml.mjs @@ -0,0 +1,3851 @@ + +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +var isNothing_1 = isNothing; +var isObject_1 = isObject; +var toArray_1 = toArray; +var repeat_1 = repeat; +var isNegativeZero_1 = isNegativeZero; +var extend_1 = extend; + +var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; + +// YAML error class. http://stackoverflow.com/questions/8458984 + + +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; +} + + +function YAMLException$1(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException$1.prototype = Object.create(Error.prototype); +YAMLException$1.prototype.constructor = YAMLException$1; + + +YAMLException$1.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; + + +var exception = YAMLException$1; + +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +var snippet = makeSnippet; + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type = Type$1; + +/*eslint-disable max-len*/ + + + + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema$1(definition) { + return this.extend(definition); +} + + +Schema$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new exception('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +var schema = Schema$1; + +var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] +}); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +var int = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +var float = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json = failsafe.extend({ + implicit: [ + _null, + bool, + int, + float + ] +}); + +var core = json; + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; +var _toString$2 = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString$2.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var _toString$1 = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var _default = core.extend({ + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = snippet(mark); + + return new exception(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load$1(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); +} + + +var loadAll_1 = loadAll$1; +var load_1 = load$1; + +var loader = { + loadAll: loadAll_1, + load: load_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || _default; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump$1(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +var dump_1 = dump$1; + +var dumper = { + dump: dump_1 +}; + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +var Type = type; +var Schema = schema; +var FAILSAFE_SCHEMA = failsafe; +var JSON_SCHEMA = json; +var CORE_SCHEMA = core; +var DEFAULT_SCHEMA = _default; +var load = loader.load; +var loadAll = loader.loadAll; +var dump = dumper.dump; +var YAMLException = exception; + +// Re-export all types in case user wants to create custom schema +var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str +}; + +// Removed functions from JS-YAML 3.0.x +var safeLoad = renamed('safeLoad', 'load'); +var safeLoadAll = renamed('safeLoadAll', 'loadAll'); +var safeDump = renamed('safeDump', 'dump'); + +var jsYaml = { + Type: Type, + Schema: Schema, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump +}; + +export default jsYaml; +export { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types };