diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..2752eb9 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.DS_Store diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..61e179b --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,92 @@ +# Confluence Research - Web UI + +Minimalist, secure Web UI for Confluence Research, designed to operate against the backend API contracts specified in `docs/SPECIFICATION.md` and `docs/implementation/CONTRACTS.md`. + +## Directory Layout + +```text +frontend/ +├── index.html # Main HTML entrypoint (clean white minimalist theme) +├── css/ +│ └── style.css # Responsive styling, accessible components, gear animation +├── js/ +│ ├── app.js # State transitions, keyboard handling, memory credentials, staleness guards +│ ├── api.js # Relative /api/v1/... fetch boundary with UTF-8 byte validation +│ ├── render.js # marked.js + DOMPurify, fail-safe render, bounded sectioning +│ └── history.js # Sources, lazy bounded history serialization, artifacts listing +├── vendor/ # Pinned vendor libraries & licenses (locally served) +│ ├── marked.min.js +│ ├── marked.LICENSE +│ ├── purify.min.js +│ └── dompurify.LICENSE +├── dev/ +│ ├── mock-server.js # Zero-dependency same-origin mock server & scenario runner +│ ├── scenario-toolbar.js # External dev toolbar script (CSP compliant, no inline scripts) +│ └── scenario-toolbar.css # External dev toolbar styling (CSP compliant, no inline styles) +├── tests/ +│ ├── contract.test.js # Wire format, status code, header, & scenario tests (14 tests) +│ ├── api.test.js # UTF-8 byte boundary and credential validation tests (6 tests) +│ ├── render.test.js # Markdown section partitioning and fallback tests (10 tests) +│ └── e2e_runner.js # End-to-end browser test runner connecting to Chrome (9444) via CDP (16 tests) +├── package.json +├── package-lock.json +├── .gitignore +├── README.md +└── HANDOFF.md +``` + +## Security & Architecture Highlights + +1. **In-Memory Credentials**: + - Confluence Base URL and Personal Access Token (PAT) reside strictly in browser JavaScript memory. + - Never written to `localStorage`, `sessionStorage`, cookies, query parameters, console logs, or exported files. + - A `cw_session` HttpOnly cookie is set by the origin for artifact download ownership. +2. **Content Security Policy (CSP)**: + - `default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'none'; media-src 'none'; font-src 'self'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'` + - Completely prevents automatic third-party network requests, tracking pixels, and unauthorized script injection. + - Verified via browser network tracing (zero automatic external requests). +3. **Markdown Sanitization & Link Safety**: + - Restricted element allowlist using locally vendored DOMPurify. + - Fail-safe rendering: if parser or sanitizer are absent or fail, displays a safe notice without ever injecting raw untrusted HTML. + - All links rewritten to require explicit user clicks with `target="_blank"` and `rel="noopener noreferrer"`. + - Disallowed protocols (`javascript:`, `data:`, `file:`) have `href` stripped. +4. **Large Result Handling & Memory Bounding**: + - Large answers partitioned into bounded sections (~48 KiB soft target, ~64 KiB hard cap) rendered on demand. + - Giant code fences (e.g. 12 MB) are safely split and re-opened so every section is a valid Markdown code block. + - Tables preserve row boundaries and repeat column headers across sections. + - Pathological blocks fall back to a bounded plain-text preview with full export available. + - "Export to MD" always exports the complete, untouched raw Markdown client-side via Blob. + - Tool call results in history are rendered lazily with bounded serialization buffers (`serializeBounded`). + +## Development & Testing + +### Running the Dev Mock Server + +The mock server runs entirely with Node.js built-ins (zero dependencies) on loopback: + +```bash +cd frontend +npm run dev +# Or custom port: +node dev/mock-server.js --port 5173 +``` + +Open `http://127.0.0.1:5173/` in your browser. A floating dev toolbar in the bottom-right corner allows toggling between all 13 deterministic mock scenarios (e.g. normal shared example, 403 verify, 409 busy, 504 timeout, malicious content, large output, delayed cancellation). + +### Running Unit & Contract Tests + +Tests verify API limits, wire contracts, headers, cookies, and markdown partitioning (30 tests): + +```bash +cd frontend +npm test +``` + +### Running E2E Browser Tests + +Runs comprehensive browser tests against Chrome on port 9444 via CDP (16 tests): + +```bash +cd frontend +npm run test:e2e +``` diff --git a/frontend/assets/book.gif b/frontend/assets/book.gif new file mode 100644 index 0000000..40ae435 Binary files /dev/null and b/frontend/assets/book.gif differ diff --git a/frontend/assets/key.svg b/frontend/assets/key.svg new file mode 100644 index 0000000..23a71c2 --- /dev/null +++ b/frontend/assets/key.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/css/style.css b/frontend/css/style.css new file mode 100644 index 0000000..1445e67 --- /dev/null +++ b/frontend/css/style.css @@ -0,0 +1,1085 @@ +/* Confluence Research Web UI - Clean White Minimalist Theme */ +:root { + --color-bg-primary: #FFFFFF; + --color-bg-secondary: #FAFAFA; + --color-border: #E5E7EB; + --color-border-hover: #D1D5DB; + --color-text-primary: #111827; + --color-text-secondary: #6B7280; + --color-accent: #2563EB; + --color-accent-hover: #1D4ED8; + --color-accent-light: #EFF6FF; + --color-error: #DC2626; + --color-error-bg: #FEF2F2; + --color-error-border: #FCA5A5; + --color-success: #16A34A; + --color-success-bg: #F0FDF4; + --color-success-border: #86EFAC; + --color-warning: #D97706; + --color-warning-bg: #FFFBEB; + --color-warning-border: #FCD34D; + --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif; + --font-mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + --max-width: 860px; + --radius-sm: 4px; + --radius-md: 8px; + --radius-lg: 12px; +} + +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +body { + font-family: var(--font-sans); + font-size: 15px; + line-height: 1.6; + color: var(--color-text-primary); + background-color: var(--color-bg-primary); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + min-height: 100vh; + display: flex; + flex-direction: column; +} + +/* Accessibility */ +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +:focus-visible { + outline: 2px solid var(--color-accent); + outline-offset: 2px; +} + +.hidden { + display: none !important; +} + +/* Header */ +.app-header { + position: relative; + width: 100%; + max-width: var(--max-width); + margin: 0 auto; + padding: 16px 24px; + display: flex; + justify-content: space-between; + align-items: center; +} + +.app-brand { + display: flex; + align-items: center; + gap: 8px; + font-weight: 600; + font-size: 17px; + color: var(--color-text-primary); + letter-spacing: -0.01em; +} + +.key-btn { + position: relative; + background: transparent; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + width: 38px; + height: 38px; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + color: var(--color-text-secondary); + transition: all 0.15s ease-in-out; +} + +.key-btn:hover { + background-color: var(--color-bg-secondary); + border-color: var(--color-border-hover); + color: var(--color-text-primary); +} + +.cred-indicator { + position: absolute; + top: 5px; + right: 5px; + width: 8px; + height: 8px; + border-radius: 50%; + background-color: #9CA3AF; /* Gray outline/unset state */ + transition: background-color 0.2s ease; +} + +.cred-indicator.active { + background-color: var(--color-success); /* Green dot when active */ + box-shadow: 0 0 0 1.5px var(--color-bg-primary); +} + +/* App Main Container */ +.app-main { + flex: 1; + width: 100%; + max-width: var(--max-width); + margin: 0 auto; + padding: 0 24px 48px 24px; + display: flex; + flex-direction: column; +} + +/* Alert Boxes */ +.alert-box { + width: 100%; + padding: 12px 16px; + border-radius: var(--radius-md); + font-size: 14px; + margin-bottom: 16px; +} + +.error-box { + background-color: var(--color-error-bg); + border: 1px solid var(--color-error-border); + color: var(--color-error); +} + +.warning-box { + background-color: var(--color-warning-bg); + border: 1px solid var(--color-warning-border); + color: var(--color-warning); +} + +.success-box { + background-color: var(--color-success-bg); + border: 1px solid var(--color-success-border); + color: var(--color-success); +} + +/* State 1: Prompt View */ +.view-prompt { + flex: 1; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: calc(80vh - 120px); + padding: 24px 0; +} + +.prompt-wrapper { + width: 100%; + max-width: 680px; + display: flex; + flex-direction: column; + align-items: center; +} + +.prompt-title { + font-size: 28px; + font-weight: 700; + letter-spacing: -0.02em; + margin-bottom: 24px; + text-align: center; + color: var(--color-text-primary); +} + +.prompt-box { + width: 100%; + position: relative; + background-color: var(--color-bg-primary); + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04), 0 4px 6px -1px rgba(0, 0, 0, 0.03); + transition: border-color 0.15s ease, box-shadow 0.15s ease; + padding: 14px 16px 10px 16px; +} + +.prompt-box:focus-within { + border-color: var(--color-accent); + box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15); +} + +.prompt-input { + width: 100%; + border: none; + background: transparent; + outline: none; + font-family: var(--font-sans); + font-size: 16px; + line-height: 1.5; + color: var(--color-text-primary); + resize: none; + min-height: 72px; + max-height: 280px; + overflow-y: auto; + display: block; +} + +.prompt-input::placeholder { + color: #9CA3AF; +} + +.prompt-footer { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 10px; + padding-top: 8px; + border-top: 1px solid #F3F4F6; +} + +.prompt-helper { + font-size: 12px; + color: var(--color-text-secondary); + user-select: none; +} + +.submit-btn { + background-color: var(--color-accent); + color: #FFFFFF; + border: none; + border-radius: var(--radius-md); + padding: 6px 14px; + font-size: 14px; + font-weight: 500; + display: inline-flex; + align-items: center; + gap: 6px; + cursor: pointer; + transition: background-color 0.15s ease; +} + +.submit-btn:hover:not(:disabled) { + background-color: var(--color-accent-hover); +} + +.submit-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +/* State 3: Loading View */ +.view-loading { + flex: 1; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + min-height: calc(80vh - 120px); + text-align: center; +} + +.spinner-wrapper { + margin-bottom: 20px; +} + +.gear-spinner { + width: 48px; + height: 48px; + color: var(--color-accent); + stroke-width: 2px; + animation: spin 1.8s cubic-bezier(0.4, 0, 0.2, 1) infinite; +} + +@keyframes spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: reduce) { + .gear-spinner { + animation: none; + } +} + +.loading-status { + font-size: 16px; + font-weight: 500; + color: var(--color-text-primary); + margin-bottom: 24px; +} + +.cancel-btn { + background: transparent; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 8px 18px; + font-size: 14px; + color: var(--color-text-secondary); + cursor: pointer; + transition: all 0.15s ease; +} + +.cancel-btn:hover { + background-color: var(--color-bg-secondary); + color: var(--color-text-primary); + border-color: var(--color-border-hover); +} + +/* State 4: Result View */ +.view-result { + width: 100%; +} + +.action-bar { + position: sticky; + top: 0; + background-color: var(--color-bg-primary); + border-bottom: 1px solid var(--color-border); + padding: 12px 0; + margin-bottom: 24px; + display: flex; + justify-content: space-between; + align-items: center; + z-index: 20; +} + +.action-btn { + background: transparent; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 7px 14px; + font-size: 14px; + font-weight: 500; + color: var(--color-text-primary); + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 6px; + transition: all 0.15s ease; +} + +.action-btn:hover { + background-color: var(--color-bg-secondary); + border-color: var(--color-border-hover); +} + +.export-btn { + background-color: var(--color-bg-secondary); +} + +.export-btn:hover { + background-color: #F3F4F6; +} + +/* Rendered Markdown Output */ +.output-content { + line-height: 1.7; + color: var(--color-text-primary); + word-break: break-word; + margin-bottom: 32px; +} + +.output-content h1, +.output-content h2, +.output-content h3, +.output-content h4, +.output-content h5, +.output-content h6 { + margin-top: 28px; + margin-bottom: 12px; + font-weight: 600; + line-height: 1.3; + color: var(--color-text-primary); +} + +.output-content h1 { font-size: 24px; border-bottom: 1px solid var(--color-border); padding-bottom: 8px; } +.output-content h2 { font-size: 20px; border-bottom: 1px solid var(--color-border); padding-bottom: 6px; } +.output-content h3 { font-size: 17px; } +.output-content h4 { font-size: 15px; } + +.output-content p { + margin-bottom: 16px; +} + +.output-content ul, +.output-content ol { + margin-bottom: 16px; + padding-left: 24px; +} + +.output-content li { + margin-bottom: 6px; +} + +.output-content blockquote { + border-left: 3px solid var(--color-border-hover); + padding-left: 16px; + margin: 16px 0; + color: var(--color-text-secondary); + font-style: italic; +} + +.output-content hr { + border: 0; + border-top: 1px solid var(--color-border); + margin: 24px 0; +} + +.output-content a { + color: var(--color-accent); + text-decoration: underline; + text-underline-offset: 2px; +} + +.output-content a:hover { + color: var(--color-accent-hover); +} + +.output-content code { + font-family: var(--font-mono); + font-size: 13.5px; + background-color: var(--color-bg-secondary); + border: 1px solid var(--color-border); + padding: 2px 5px; + border-radius: var(--radius-sm); +} + +.output-content pre { + font-family: var(--font-mono); + font-size: 13.5px; + background-color: var(--color-bg-secondary); + border: 1px solid var(--color-border); + padding: 14px 16px; + border-radius: var(--radius-md); + overflow-x: auto; + margin-bottom: 18px; +} + +.output-content pre code { + background: transparent; + border: none; + padding: 0; +} + +.output-content table { + width: 100%; + border-collapse: collapse; + margin: 18px 0; + font-size: 14px; +} + +.output-content th, +.output-content td { + border: 1px solid var(--color-border); + padding: 8px 12px; + text-align: left; +} + +.output-content th { + background-color: var(--color-bg-secondary); + font-weight: 600; +} + +.output-content tr:nth-child(even) td { + background-color: #FCFCFC; +} + +/* Pathological Fallback & Bounded Section Controls */ +.pathological-banner, +.section-nav-banner { + background-color: var(--color-warning-bg); + border: 1px solid var(--color-warning-border); + border-radius: var(--radius-md); + padding: 10px 14px; + font-size: 13px; + color: var(--color-warning); + margin-bottom: 16px; + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; +} + +.section-nav-controls { + display: flex; + gap: 8px; + align-items: center; +} + +.section-btn { + background: #FFFFFF; + border: 1px solid var(--color-warning-border); + border-radius: var(--radius-sm); + padding: 4px 10px; + font-size: 12px; + font-weight: 500; + cursor: pointer; +} + +.section-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.pathological-preview { + background-color: var(--color-bg-subtle); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 12px; + font-family: var(--font-mono); + font-size: 13px; + line-height: 1.5; + white-space: pre-wrap; + word-break: break-all; + max-height: 400px; + overflow-y: auto; + margin-bottom: 16px; +} + +.render-error-notice { + background-color: var(--color-error-bg); + border: 1px solid var(--color-error-border); + border-radius: var(--radius-md); + padding: 12px 16px; + font-size: 14px; + color: var(--color-error); + margin-bottom: 16px; +} + +/* Warnings Area */ +.warnings-container { + margin-bottom: 20px; +} + +.warning-item { + display: flex; + gap: 8px; + align-items: flex-start; + padding: 8px 12px; + border-radius: var(--radius-sm); + background-color: var(--color-warning-bg); + border: 1px solid var(--color-warning-border); + font-size: 13px; + color: var(--color-warning); + margin-bottom: 6px; +} + +.warning-code { + font-family: var(--font-mono); + font-weight: 600; + font-size: 12px; +} + +/* Artifacts Section */ +.artifacts-section { + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 16px 20px; + margin-bottom: 24px; + background-color: var(--color-bg-secondary); +} + +.artifacts-heading { + font-size: 15px; + font-weight: 600; + margin-bottom: 12px; + color: var(--color-text-primary); +} + +.artifacts-list { + list-style: none; + display: flex; + flex-direction: column; + gap: 8px; +} + +.artifact-item { + display: flex; + justify-content: space-between; + align-items: center; + background-color: #FFFFFF; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 10px 14px; +} + +.artifact-info { + display: flex; + flex-direction: column; + gap: 2px; +} + +.artifact-name { + font-weight: 500; + font-size: 14px; + color: var(--color-text-primary); + font-family: var(--font-mono); +} + +.artifact-meta { + font-size: 12px; + color: var(--color-text-secondary); +} + +.download-btn { + background-color: #FFFFFF; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 6px 12px; + font-size: 13px; + font-weight: 500; + color: var(--color-text-primary); + cursor: pointer; + transition: all 0.15s ease; +} + +.download-btn:hover { + background-color: var(--color-bg-secondary); + border-color: var(--color-border-hover); +} + +/* Sources & Request History */ +.history-section { + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + margin-top: 24px; + overflow: hidden; + background-color: #FFFFFF; +} + +.history-toggle-btn { + width: 100%; + padding: 14px 18px; + background: transparent; + border: none; + display: flex; + align-items: center; + justify-content: space-between; + cursor: pointer; + font-size: 15px; + font-weight: 600; + color: var(--color-text-primary); + text-align: left; + transition: background-color 0.15s ease; +} + +.history-toggle-btn:hover { + background-color: var(--color-bg-secondary); +} + +.toggle-icon { + font-size: 12px; + color: var(--color-text-secondary); + transition: transform 0.2s ease; +} + +.history-toggle-btn[aria-expanded="true"] .toggle-icon { + transform: rotate(90deg); +} + +.history-content { + padding: 0 18px 18px 18px; + border-top: 1px solid var(--color-border); +} + +.history-subheading { + font-size: 13px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--color-text-secondary); + margin: 16px 0 10px 0; +} + +/* Pages Accessed Cards */ +.pages-list { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 20px; +} + +.page-card { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 14px; + background-color: var(--color-bg-secondary); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); +} + +.page-card-left { + display: flex; + align-items: center; + gap: 10px; + overflow: hidden; +} + +.badge-space { + font-size: 11px; + font-weight: 600; + background-color: var(--color-accent-light); + color: var(--color-accent); + border: 1px solid #BFDBFE; + padding: 2px 6px; + border-radius: var(--radius-sm); + font-family: var(--font-mono); +} + +.page-title-link { + font-weight: 500; + font-size: 14px; + color: var(--color-text-primary); + text-decoration: none; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.page-title-link:hover { + text-decoration: underline; + color: var(--color-accent); +} + +.page-card-meta { + font-size: 12px; + color: var(--color-text-secondary); + white-space: nowrap; +} + +/* Tool History Cards */ +.tool-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.tool-card { + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + background-color: #FFFFFF; + overflow: hidden; +} + +.tool-card-header { + padding: 10px 14px; + display: flex; + justify-content: space-between; + align-items: center; + background-color: var(--color-bg-secondary); + border-bottom: 1px solid var(--color-border); + font-size: 13px; +} + +.tool-card-header-left { + display: flex; + align-items: center; + gap: 8px; +} + +.tool-id { + font-family: var(--font-mono); + font-weight: 600; + font-size: 12px; + color: var(--color-text-secondary); +} + +.tool-name { + font-weight: 600; + color: var(--color-text-primary); +} + +.tool-badges { + display: flex; + gap: 6px; + align-items: center; +} + +.badge { + font-size: 11px; + padding: 2px 6px; + border-radius: var(--radius-sm); + font-weight: 500; +} + +.badge-success { + background-color: var(--color-success-bg); + color: var(--color-success); + border: 1px solid var(--color-success-border); +} + +.badge-error { + background-color: var(--color-error-bg); + color: var(--color-error); + border: 1px solid var(--color-error-border); +} + +.badge-cache { + background-color: #F3F4F6; + color: #4B5563; + border: 1px solid #D1D5DB; +} + +.badge-truncated { + background-color: var(--color-warning-bg); + color: var(--color-warning); + border: 1px solid var(--color-warning-border); +} + +.tool-card-body { + padding: 10px 14px; + font-size: 13px; +} + +.tool-meta-row { + display: flex; + gap: 16px; + color: var(--color-text-secondary); + font-size: 12px; + margin-bottom: 8px; +} + +.tool-expand-btn { + background: transparent; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + padding: 3px 8px; + font-size: 12px; + cursor: pointer; + color: var(--color-text-secondary); +} + +.tool-expand-btn:hover { + background-color: var(--color-bg-secondary); + color: var(--color-text-primary); +} + +.tool-result-box { + margin-top: 8px; + background-color: var(--color-bg-secondary); + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + padding: 10px; + font-family: var(--font-mono); + font-size: 12px; + max-height: 240px; + overflow-y: auto; + white-space: pre-wrap; + word-break: break-all; +} + +/* Modal View */ +.modal-backdrop { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background-color: rgba(0, 0, 0, 0.35); + backdrop-filter: blur(4px); + display: flex; + justify-content: center; + align-items: center; + z-index: 100; +} + +.modal-dialog { + background-color: #FFFFFF; + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1); + width: 90%; + max-width: 480px; + padding: 24px; + position: relative; +} + +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; +} + +.modal-title { + font-size: 18px; + font-weight: 600; + color: var(--color-text-primary); +} + +.modal-close-btn { + background: transparent; + border: none; + font-size: 20px; + line-height: 1; + color: var(--color-text-secondary); + cursor: pointer; + padding: 4px; +} + +.modal-close-btn:hover { + color: var(--color-text-primary); +} + +.form-group { + margin-bottom: 16px; +} + +.form-label { + display: block; + font-size: 13px; + font-weight: 500; + margin-bottom: 6px; + color: var(--color-text-primary); +} + +.modal-input { + width: 100%; + padding: 8px 12px; + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + font-size: 14px; + font-family: var(--font-sans); + outline: none; + transition: border-color 0.15s ease, box-shadow 0.15s ease; +} + +.modal-input:focus { + border-color: var(--color-accent); + box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15); +} + +.password-input-wrapper { + position: relative; + display: flex; + align-items: center; +} + +.toggle-password-btn { + position: absolute; + right: 8px; + background: transparent; + border: none; + color: var(--color-text-secondary); + cursor: pointer; + padding: 4px; + display: flex; + align-items: center; + justify-content: center; +} + +.toggle-password-btn:hover { + color: var(--color-text-primary); +} + +.field-hint { + display: block; + font-size: 11px; + color: var(--color-text-secondary); + margin-top: 4px; +} + +.modal-feedback { + margin-bottom: 16px; + padding: 8px 12px; + border-radius: var(--radius-sm); + font-size: 13px; +} + +.modal-actions { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 24px; + padding-top: 16px; + border-top: 1px solid var(--color-border); + flex-wrap: wrap; + gap: 8px; +} + +.modal-actions-right { + display: flex; + gap: 8px; +} + +.btn-primary { + background-color: var(--color-accent); + color: #FFFFFF; + border: none; + border-radius: var(--radius-md); + padding: 8px 14px; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: background-color 0.15s ease; +} + +.btn-primary:hover { + background-color: var(--color-accent-hover); +} + +.btn-secondary { + background-color: transparent; + color: var(--color-text-primary); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 8px 14px; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all 0.15s ease; +} + +.btn-secondary:hover { + background-color: var(--color-bg-secondary); + border-color: var(--color-border-hover); +} + +.btn-secondary.danger { + color: var(--color-error); + border-color: var(--color-error-border); +} + +.btn-secondary.danger:hover { + background-color: var(--color-error-bg); +} + +/* Mobile responsive adjustments */ +@media (max-width: 640px) { + .app-main { + padding: 0 16px 32px 16px; + } + .prompt-title { + font-size: 22px; + } + .modal-actions { + flex-direction: column-reverse; + align-items: stretch; + } + .modal-actions-right { + flex-direction: column; + } + .modal-actions-left { + margin-top: 8px; + display: flex; + justify-content: center; + } + .page-card { + flex-direction: column; + align-items: flex-start; + gap: 6px; + } + .page-card-meta { + font-size: 11px; + } + .tool-card-header { + flex-direction: column; + align-items: flex-start; + gap: 6px; + } +} diff --git a/frontend/dev/mock-server.js b/frontend/dev/mock-server.js new file mode 100644 index 0000000..c5a201e --- /dev/null +++ b/frontend/dev/mock-server.js @@ -0,0 +1,823 @@ +/** + * Same-origin Mock HTTP Server for the Confluence Research Web UI. + * Implements exact HTTP contracts, security headers, cookie sessions, and deterministic scenarios. + * Strictly binds loopback (default 5173). Zero external dependencies. + */ + +import http from 'node:http'; +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const FRONTEND_ROOT = path.resolve(__dirname, '..'); + +const DEFAULT_PORT = 5173; +const HOST = '127.0.0.1'; + +// Active state +let currentGlobalScenario = 'normal'; +let isQueryBusy = false; + +// Predefined available scenarios +export const SCENARIOS = [ + 'normal', + 'empty_search', + 'no_artifacts', + 'repeated_cached_view', + 'failed_tool', + 'warning_truncated_history', + '403_verify', + '409_busy', + '504_timeout', + 'delayed_cancellation', + 'unknown_expired_download', + 'malicious_content', + 'large_output' +]; + +/** + * Standard Security Headers + */ +const SECURITY_HEADERS = { + 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'none'; media-src 'none'; font-src 'self'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", + 'Referrer-Policy': 'no-referrer', + 'X-Content-Type-Options': 'nosniff' +}; + +const MIME_TYPES = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', + '.md': 'text/markdown; charset=utf-8', + '.map': 'application/json' +}; + +/** + * Parses cookies from request. + */ +function parseCookies(cookieHeader) { + const list = {}; + if (!cookieHeader) return list; + cookieHeader.split(';').forEach((cookie) => { + const parts = cookie.split('='); + if (parts.length >= 2) { + list[parts[0].trim()] = decodeURIComponent(parts.slice(1).join('=').trim()); + } + }); + return list; +} + +/** + * Determines the active scenario for a request. + */ +function getScenarioForRequest(req, urlObj) { + // 1. Query parameter + const qScenario = urlObj.searchParams.get('scenario'); + if (qScenario && SCENARIOS.includes(qScenario)) return qScenario; + + // 2. Custom header + const hScenario = req.headers['x-mock-scenario']; + if (hScenario && SCENARIOS.includes(hScenario)) return hScenario; + + // 3. Cookie + const cookies = parseCookies(req.headers.cookie); + if (cookies.mock_scenario && SCENARIOS.includes(cookies.mock_scenario)) { + return cookies.mock_scenario; + } + + // 4. Global fallback + return currentGlobalScenario; +} + +/** + * Generates fixture data for the requested scenario. + */ +function buildScenarioResponse(scenario, prompt) { + const now = new Date(); + const nowIso = now.toISOString(); + const expiresAtIso = new Date(now.getTime() + 15 * 60 * 1000).toISOString(); + + switch (scenario) { + case 'empty_search': + return { + session_id: 'mock-session-empty', + markdown: '# Research Results\n\nNo Confluence documentation matched your query.', + pages_accessed: [], + tool_history: [ + { + tool_call_id: 'b_search_01', + tool: 'confluence_search', + parameters: { query: prompt || 'empty query', limit: 10 }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + pages: [], + pagination: { offset: 0, limit: 10, has_more: false } + }, + error: null, + result_truncated: false + } + ], + artifacts: [], + warnings: [], + duration_seconds: 1.1 + }; + + case 'no_artifacts': + return { + session_id: 'mock-session-no-art', + markdown: '# Research Summary\n\nInformation gathered from [Deployment Guide](https://approved.example.com/pages/viewpage.action?pageId=847291).\n\nNo artifacts produced.', + pages_accessed: [ + { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + accessed_at: nowIso + } + ], + tool_history: [ + { + tool_call_id: 'b_view_01', + tool: 'confluence_view', + parameters: { page_id: '847291' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + markdown: 'Deploy service X.', + truncated: false + }, + error: null, + result_truncated: false + } + ], + artifacts: [], + warnings: [], + duration_seconds: 2.3 + }; + + case 'repeated_cached_view': + return { + session_id: 'mock-session-cached', + markdown: '# Deployment Summary\n\nReferenced [Deployment Guide](https://approved.example.com/pages/viewpage.action?pageId=847291) across multiple steps.', + pages_accessed: [ + { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + accessed_at: nowIso + } + ], + tool_history: [ + { + tool_call_id: 'b_call_01', + tool: 'confluence_view', + parameters: { page_id: '847291' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + markdown: 'Initial view.', + truncated: false + }, + error: null, + result_truncated: false + }, + { + tool_call_id: 'b_call_02', + tool: 'confluence_view', + parameters: { page_id: '847291' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: true, + result: { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + markdown: 'Initial view (from cache).', + truncated: false + }, + error: null, + result_truncated: false + } + ], + artifacts: [], + warnings: [], + duration_seconds: 1.8 + }; + + case 'failed_tool': + return { + session_id: 'mock-session-failed-tool', + markdown: '# Partial Summary\n\nSearch succeeded, but page 999999 could not be accessed due to an upstream error.', + pages_accessed: [], + tool_history: [ + { + tool_call_id: 'b_search_01', + tool: 'confluence_search', + parameters: { query: 'archived docs', limit: 5 }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + pages: [{ page_id: '999999', title: 'Archived Page', space: 'ARCH', url: 'https://approved.example.com/pages/viewpage.action?pageId=999999', snippet: 'Missing page' }], + pagination: { offset: 0, limit: 5, has_more: false } + }, + error: null, + result_truncated: false + }, + { + tool_call_id: 'b_view_02', + tool: 'confluence_view', + parameters: { page_id: '999999' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'error', + cache_hit: false, + result: null, + error: { + code: 'page_not_found', + message: 'Confluence page 999999 was not found or has been deleted.' + }, + result_truncated: false + } + ], + artifacts: [], + warnings: [ + { code: 'page_not_found', message: 'Page 999999 access failed', tool_call_id: 'b_view_02' } + ], + duration_seconds: 2.7 + }; + + case 'warning_truncated_history': + return { + session_id: 'mock-session-warn-trunc', + markdown: '# Bounded Results\n\nExtensive data retrieved with truncated history logs.', + pages_accessed: [ + { + page_id: '12345', + title: 'Large Architecture Document', + space: 'ARCH', + url: 'https://approved.example.com/pages/viewpage.action?pageId=12345', + accessed_at: nowIso + } + ], + tool_history: [ + { + tool_call_id: 'b_call_trunc_01', + tool: 'confluence_view', + parameters: { page_id: '12345', details: 'A'.repeat(500) }, + parameters_truncated: true, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + page_id: '12345', + summary: 'Summary preserved while large raw content was truncated.' + }, + error: null, + result_truncated: true + } + ], + artifacts: [], + warnings: [ + { + code: 'history_truncated', + message: 'History result budget exceeded; 1 entry truncated.', + tool_call_id: 'b_call_trunc_01' + }, + { + code: 'unknown_custom_warning', + message: 'Custom backend warning code test.' + } + ], + duration_seconds: 4.1 + }; + + case 'malicious_content': + return { + session_id: 'mock-session-malicious', + markdown: [ + '# Malicious Input Test', + '', + 'Attempting XSS and unsafe content:', + '', + '', + '', + '', + '
', + '', + 'Harmful links:', + '- [JavaScript link](javascript:alert("xss-link"))', + '- [Data URI link](data:text/html,)', + '- [Safe citation link](https://approved.example.com/safe/page)', + '', + '```html', + '', + '```' + ].join('\n'), + pages_accessed: [ + { + page_id: '777', + title: ' Safe Title', + space: 'SEC', + url: 'https://approved.example.com/page/777', + accessed_at: nowIso + } + ], + tool_history: [ + { + tool_call_id: 'b_xss_01', + tool: 'confluence_view', + parameters: { page_id: '' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + raw_payload: '', + nested: { malicious: '' } + }, + error: null, + result_truncated: false + } + ], + artifacts: [], + warnings: [], + duration_seconds: 1.0 + }; + + case 'large_output': { + // Dynamically generate multi-megabyte markdown with sections, tables, and code blocks + const sectionCount = 40; + const mdParts = ['# Large Document Benchmark\n\nGenerated large output to test bounded section rendering and responsive UI.\n']; + for (let i = 1; i <= sectionCount; i++) { + mdParts.push(`\n## Section ${i}: Architectural Components\n`); + mdParts.push(`This is paragraph content for section ${i} detailing deployment topologies, container security, and protocol isolation.\n`); + mdParts.push('```bash\n# Simulated shell commands\necho "Running container isolation check for section ' + i + '"\nfind /work -type f -ls\n```\n'); + mdParts.push('| Component | Status | Metric |\n|---|---|---|\n| Bridge | Active | 100% |\n| Storage | Bounded | 50 MiB |\n| Latency | Nominal | 12ms |\n'); + // Repeat text to bulk up section size (~50 KiB per section) + mdParts.push('Confluence documentation analysis paragraph '.repeat(200) + '\n'); + } + + return { + session_id: 'mock-session-large', + markdown: mdParts.join('\n'), + pages_accessed: [ + { + page_id: '99991', + title: 'Enterprise Architecture Overview', + space: 'ARCH', + url: 'https://approved.example.com/pages/viewpage.action?pageId=99991', + accessed_at: nowIso + } + ], + tool_history: [ + { + tool_call_id: 'b_large_01', + tool: 'confluence_view', + parameters: { page_id: '99991' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + page_id: '99991', + title: 'Enterprise Architecture Overview', + space: 'ARCH', + status: 'ok' + }, + error: null, + result_truncated: false + } + ], + artifacts: [ + { + id: 'art-large-export', + name: 'full_architecture.md', + size_bytes: 32, + expires_at: expiresAtIso + } + ], + warnings: [], + duration_seconds: 5.4 + }; + } + + case 'normal': + default: + // Shared example scenario from CONTRACTS.md Section 7 + return { + session_id: 'a0f2b3c4-1234-5678-9abc-def012345678', + markdown: '# Deployment Guide for Service X\n\nTo deploy **Service X**, follow the steps outlined in the [Deployment Guide](https://approved.example.com/pages/viewpage.action?pageId=847291).\n\n### Key Steps:\n1. Verify container runtime prerequisites.\n2. Review the checklist exported to `checklist.md`.\n3. Execute staged rollout.\n', + pages_accessed: [ + { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + accessed_at: nowIso + } + ], + tool_history: [ + { + tool_call_id: 'b_call_01', + tool: 'confluence_search', + parameters: { query: 'deploy service X', limit: 10 }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + pages: [ + { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + snippet: 'Deployment steps for service X' + } + ], + pagination: { offset: 0, limit: 10, has_more: false } + }, + error: null, + result_truncated: false + }, + { + tool_call_id: 'b_call_02', + tool: 'confluence_view', + parameters: { page_id: '847291' }, + parameters_truncated: false, + started_at: nowIso, + completed_at: nowIso, + status: 'success', + cache_hit: false, + result: { + page_id: '847291', + title: 'Deployment Guide', + space: 'OPS', + url: 'https://approved.example.com/pages/viewpage.action?pageId=847291', + markdown: 'Deploy service X using the release checklist.', + truncated: false + }, + error: null, + result_truncated: false + } + ], + artifacts: [ + { + id: 'art-checklist-01', + name: 'checklist.md', + size_bytes: 32, + expires_at: expiresAtIso + } + ], + warnings: [], + duration_seconds: 3.2 + }; + } +} + +/** + * Validates that credentials in mock mode are synthetic/dummy credentials. + */ +function validateMockCredentials(url, pat) { + if (!url || !pat) return false; + // Prevent common production token patterns + if (pat.startsWith('ghp_') || pat.startsWith('glpat-') || pat.startsWith('xoxb-')) { + return false; + } + return true; +} + +/** + * Creates the HTTP server. + */ +export function createMockServer() { + const server = http.createServer(async (req, res) => { + const urlObj = new URL(req.url, `http://${req.headers.host || `${HOST}:${DEFAULT_PORT}`}`); + const pathname = urlObj.pathname; + const method = req.method.toUpperCase(); + + // Attach security headers to all responses + Object.entries(SECURITY_HEADERS).forEach(([key, val]) => { + res.setHeader(key, val); + }); + + // Session cookie: cw_session + const cookies = parseCookies(req.headers.cookie); + if (!cookies.cw_session) { + const newSession = crypto.randomBytes(16).toString('hex'); + res.setHeader('Set-Cookie', `cw_session=${newSession}; Path=/; HttpOnly; SameSite=Strict`); + } + + // Origin check for mutation requests + if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(method)) { + const origin = req.headers.origin; + if (origin) { + try { + const origUrl = new URL(origin); + if (!['127.0.0.1', 'localhost'].includes(origUrl.hostname)) { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { code: 'origin_denied', message: 'Cross-origin request denied.' } })); + return; + } + } catch { + res.writeHead(403, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { code: 'origin_denied', message: 'Malformed origin.' } })); + return; + } + } + } + + // Dev Scenario API (development tooling outside user flow) + if (pathname === '/dev/scenario') { + if (method === 'GET') { + res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ scenario: currentGlobalScenario, available: SCENARIOS })); + return; + } + if (method === 'POST') { + let body = ''; + req.on('data', (chunk) => { body += chunk; }); + req.on('end', () => { + try { + const data = JSON.parse(body); + if (data.scenario && SCENARIOS.includes(data.scenario)) { + currentGlobalScenario = data.scenario; + res.writeHead(200, { + 'Content-Type': 'application/json', + 'Cache-Control': 'no-store', + 'Set-Cookie': `mock_scenario=${data.scenario}; Path=/; SameSite=Strict` + }); + res.end(JSON.stringify({ ok: true, scenario: currentGlobalScenario })); + } else { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Unknown scenario' } })); + } + } catch { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Invalid JSON' } })); + } + }); + return; + } + } + + // API Endpoint 1: POST /api/v1/auth/verify + if (pathname === '/api/v1/auth/verify' && method === 'POST') { + let body = ''; + req.on('data', (chunk) => { body += chunk; }); + req.on('end', () => { + try { + const data = JSON.parse(body); + if (!data.url || !data.pat) { + res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Missing URL or PAT' } })); + return; + } + + if (!validateMockCredentials(data.url, data.pat)) { + res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'confluence_auth_failed', message: 'Invalid mock credentials' } })); + return; + } + + const scenario = getScenarioForRequest(req, urlObj); + if (scenario === '403_verify') { + res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'confluence_auth_failed', message: 'Confluence authentication failed: invalid PAT.' } })); + return; + } + + res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ valid: true })); + } catch { + res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Invalid JSON body' } })); + } + }); + return; + } + + // API Endpoint 2: POST /api/v1/query + if (pathname === '/api/v1/query' && method === 'POST') { + let body = ''; + req.on('data', (chunk) => { body += chunk; }); + req.on('end', async () => { + try { + const data = JSON.parse(body); + if (!data.prompt || !data.credentials || !data.credentials.url || !data.credentials.pat) { + res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Missing required query parameters' } })); + return; + } + + if (!validateMockCredentials(data.credentials.url, data.credentials.pat)) { + res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'confluence_auth_failed', message: 'Invalid mock credentials' } })); + return; + } + + const scenario = getScenarioForRequest(req, urlObj); + + // 409 Busy check + if (scenario === '409_busy' || isQueryBusy) { + res.writeHead(409, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'busy', message: 'A query is currently executing or prior cleanup is in progress' } })); + return; + } + + // 504 Timeout check + if (scenario === '504_timeout') { + res.writeHead(504, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'query_timeout', message: 'The query deadline of 180 seconds was exceeded' } })); + return; + } + + // Delayed cancellation test scenario + if (scenario === 'delayed_cancellation') { + isQueryBusy = true; + let aborted = false; + + const cancelTimeout = setTimeout(() => { + isQueryBusy = false; + if (!aborted && !res.writableEnded) { + const responseData = buildScenarioResponse('normal', data.prompt); + res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify(responseData)); + } + }, 30000); // 30s delay + + req.on('close', () => { + if (!res.writableEnded) { + aborted = true; + clearTimeout(cancelTimeout); + // Simulate backend cleanup budget + setTimeout(() => { + isQueryBusy = false; + }, 400); + } + }); + return; + } + + // Normal response + const responseData = buildScenarioResponse(scenario, data.prompt); + res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify(responseData)); + } catch { + res.writeHead(400, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'invalid_input', message: 'Malformed JSON query body' } })); + } + }); + return; + } + + // API Endpoint 3: GET /api/v1/artifacts/{id} + if (pathname.startsWith('/api/v1/artifacts/') && method === 'GET') { + const scenario = getScenarioForRequest(req, urlObj); + const artifactId = pathname.slice('/api/v1/artifacts/'.length); + + if (scenario === 'unknown_expired_download' || artifactId === 'expired' || artifactId === 'non-existent') { + res.writeHead(404, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: { code: 'artifact_not_found', message: 'Artifact has expired or does not exist.' } })); + return; + } + + // Exact 32 bytes from CONTRACTS.md Section 7 + const artifactContent = '# Checklist\n\n- Deploy service X\n'; + const buffer = Buffer.from(artifactContent, 'utf-8'); + + res.writeHead(200, { + 'Content-Type': 'application/octet-stream', + 'Content-Length': buffer.length, + 'Content-Disposition': 'attachment; filename="checklist.md"', + 'Cache-Control': 'no-store' + }); + res.end(buffer); + return; + } + + // Static File Serving + if (method === 'GET' || method === 'HEAD') { + let relativePath = pathname === '/' ? 'index.html' : pathname.slice(1); + const safePath = path.normalize(relativePath).replace(/^(\.\.[/\\])+/, ''); + const filePath = path.join(FRONTEND_ROOT, safePath); + + // Security check: ensure path is within FRONTEND_ROOT + if (!filePath.startsWith(FRONTEND_ROOT)) { + res.writeHead(403); + res.end('Forbidden'); + return; + } + + fs.stat(filePath, (err, stats) => { + if (err || !stats.isFile()) { + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('Not Found'); + return; + } + + const ext = path.extname(filePath).toLowerCase(); + const contentType = MIME_TYPES[ext] || 'application/octet-stream'; + + // For index.html in dev mode, inject a dev scenario selector bar + if (ext === '.html') { + fs.readFile(filePath, 'utf8', (readErr, htmlContent) => { + if (readErr) { + res.writeHead(500); + res.end('Server Error'); + return; + } + + const activeScenario = getScenarioForRequest(req, urlObj); + + // Dev scenario selector toolbar (external CSS and JS to satisfy CSP script-src 'self' style-src 'self') + const devBar = ` + + + + +`; + const modifiedHtml = htmlContent.replace('', `${devBar}`); + res.writeHead(200, { + 'Content-Type': contentType, + 'Content-Length': Buffer.byteLength(modifiedHtml) + }); + res.end(modifiedHtml); + }); + return; + } + + // Other static files + res.writeHead(200, { + 'Content-Type': contentType, + 'Content-Length': stats.size + }); + if (method === 'HEAD') { + res.end(); + return; + } + const stream = fs.createReadStream(filePath); + stream.pipe(res); + }); + return; + } + + res.writeHead(405, { 'Content-Type': 'text/plain' }); + res.end('Method Not Allowed'); + }); + + return server; +} + +// If run directly from CLI +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const portArgIdx = process.argv.indexOf('--port'); + const port = portArgIdx !== -1 ? parseInt(process.argv[portArgIdx + 1], 10) : (parseInt(process.env.PORT, 10) || DEFAULT_PORT); + + const server = createMockServer(); + server.listen(port, HOST, () => { + console.log(`Mock server running at http://${HOST}:${port}/`); + console.log(`Current default scenario: ${currentGlobalScenario}`); + }); +} diff --git a/frontend/dev/scenario-toolbar.css b/frontend/dev/scenario-toolbar.css new file mode 100644 index 0000000..87ea28d --- /dev/null +++ b/frontend/dev/scenario-toolbar.css @@ -0,0 +1,32 @@ +#dev-scenario-bar { + position: fixed; + bottom: 12px; + right: 12px; + z-index: 9999; + background: #111827; + color: #F9FAFB; + padding: 8px 12px; + border-radius: 8px; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + font-size: 12px; + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3); + display: flex; + align-items: center; + gap: 8px; +} + +#dev-scenario-label { + font-weight: 600; + color: #9CA3AF; +} + +#dev-scenario-select { + background: #1F2937; + color: #FFFFFF; + border: 1px solid #374151; + border-radius: 4px; + padding: 4px 8px; + font-size: 12px; + outline: none; + cursor: pointer; +} diff --git a/frontend/dev/scenario-toolbar.js b/frontend/dev/scenario-toolbar.js new file mode 100644 index 0000000..5603fba --- /dev/null +++ b/frontend/dev/scenario-toolbar.js @@ -0,0 +1,21 @@ +/** + * Mock Server Dev Toolbar client logic. + * External module to comply with strict CSP (script-src 'self'). + */ +(function() { + const sel = document.getElementById('dev-scenario-select'); + if (sel) { + sel.addEventListener('change', async function() { + try { + await fetch('/dev/scenario', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ scenario: sel.value }) + }); + } catch (err) { + console.error('Failed to change scenario:', err); + } + window.location.reload(); + }); + } +})(); diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..0d0e1b0 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,168 @@ + + + + + + Confluence Research + + + + + + + +
+
+ + Confluence Research +
+ +
+ + +
+ +
+
+

What would you like to research?

+ +
+ + +
+
+
+ + + + + + +
+ + + + + diff --git a/frontend/js/api.js b/frontend/js/api.js new file mode 100644 index 0000000..deb710b --- /dev/null +++ b/frontend/js/api.js @@ -0,0 +1,237 @@ +/** + * API client boundary for same-origin backend communication. + * Strictly uses relative URLs (/api/v1/...) with no mock toggles or hardcoded origins. + */ + +const MAX_PROMPT_BYTES = 16 * 1024 * 1024; // 16 MiB +const MAX_FIELD_BYTES = 8 * 1024; // 8 KiB for Confluence URL / PAT + +/** + * Returns the UTF-8 byte length of a string. + * @param {string} str + * @returns {number} + */ +export function getUtf8ByteLength(str) { + if (typeof str !== 'string') return 0; + return new TextEncoder().encode(str).length; +} + +/** + * Validates Confluence URL and PAT strings according to contract limits. + * @param {{ url: string, pat: string }} credentials + * @throws {Error} If credentials fail validation + */ +export function validateCredentials({ url, pat }) { + if (!url || typeof url !== 'string' || !url.trim()) { + const err = new Error('Confluence URL is required.'); + err.code = 'invalid_input'; + throw err; + } + if (!pat || typeof pat !== 'string' || !pat.trim()) { + const err = new Error('Personal Access Token (PAT) is required.'); + err.code = 'invalid_input'; + throw err; + } + + const urlBytes = getUtf8ByteLength(url); + if (urlBytes > MAX_FIELD_BYTES) { + const err = new Error('Confluence URL exceeds the 8 KiB limit.'); + err.code = 'invalid_input'; + throw err; + } + + const patBytes = getUtf8ByteLength(pat); + if (patBytes > MAX_FIELD_BYTES) { + const err = new Error('Personal Access Token exceeds the 8 KiB limit.'); + err.code = 'invalid_input'; + throw err; + } + + try { + const parsed = new URL(url); + if (!['http:', 'https:'].includes(parsed.protocol)) { + throw new Error(); + } + } catch { + const err = new Error('Confluence URL must be a valid HTTP or HTTPS URL.'); + err.code = 'invalid_input'; + throw err; + } +} + +/** + * Parses and normalizes API error responses. + * @param {Response} response + * @returns {Promise} + */ +async function parseApiError(response) { + let code = 'execution_failed'; + let message = `Request failed with status ${response.status}`; + + let rawText = ''; + try { + rawText = await response.text(); + if (rawText) { + const data = JSON.parse(rawText); + if (data && data.error) { + if (typeof data.error.code === 'string') { + code = data.error.code; + } + if (typeof data.error.message === 'string') { + message = data.error.message; + } + const err = new Error(message); + err.code = code; + err.status = response.status; + return err; + } + } + } catch { + // Non-JSON body fallback + } + + // Non-JSON or empty error body fallback based on HTTP status + if (response.status === 400) { + code = 'invalid_input'; + } else if (response.status === 403) { + // Differentiate origin / destination denials from PAT failures per CONTRACTS §2 + const lower = (rawText || response.statusText || '').toLowerCase(); + if (lower.includes('origin')) { + code = 'origin_denied'; + message = 'Request forbidden: origin denied.'; + } else if (lower.includes('destination') || lower.includes('host')) { + code = 'destination_denied'; + message = 'Request forbidden: destination URL not permitted.'; + } else if (lower.includes('auth') || lower.includes('pat') || lower.includes('token') || lower.includes('credential')) { + code = 'confluence_auth_failed'; + message = 'Confluence authentication failed.'; + } else { + // Ingress / reverse proxy 403 rejection + code = 'origin_denied'; + message = 'Request forbidden by server policy.'; + } + } else if (response.status === 404) { + code = 'artifact_not_found'; + } else if (response.status === 409) { + code = 'busy'; + } else if (response.status === 413) { + code = 'request_too_large'; + } else if (response.status === 502) { + code = 'upstream_failed'; + } else if (response.status === 504) { + code = 'query_timeout'; + } + + const err = new Error(message); + err.code = code; + err.status = response.status; + return err; +} + +/** + * Verifies credentials against the backend. + * @param {{ url: string, pat: string }} credentials + * @param {{ signal?: AbortSignal }} [options] + * @returns {Promise<{ valid: boolean }>} + */ +export async function verifyCredentials(credentials, { signal } = {}) { + validateCredentials(credentials); + + const response = await fetch('/api/v1/auth/verify', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + url: credentials.url.trim(), + pat: credentials.pat.trim() + }), + signal + }); + + if (!response.ok) { + throw await parseApiError(response); + } + + return await response.json(); +} + +/** + * Submits a research prompt with credentials. + * @param {{ prompt: string, credentials: { url: string, pat: string } }} params + * @param {{ signal?: AbortSignal }} [options] + * @returns {Promise} Query result object + */ +export async function submitQuery({ prompt, credentials }, { signal } = {}) { + if (!prompt || typeof prompt !== 'string' || !prompt.trim()) { + const err = new Error('Prompt cannot be empty.'); + err.code = 'invalid_input'; + throw err; + } + + const promptBytes = getUtf8ByteLength(prompt); + if (promptBytes > MAX_PROMPT_BYTES) { + const err = new Error(`Prompt exceeds the 16 MiB UTF-8 limit (${promptBytes} bytes).`); + err.code = 'invalid_input'; + throw err; + } + + validateCredentials(credentials); + + const response = await fetch('/api/v1/query', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + prompt: prompt, // Preserve original untrimmed text inside payload while verifying trimmed was non-empty + credentials: { + url: credentials.url.trim(), + pat: credentials.pat.trim() + } + }), + signal + }); + + if (!response.ok) { + throw await parseApiError(response); + } + + return await response.json(); +} + +/** + * Downloads an artifact by its backend-issued ID. + * @param {string} artifactId + * @param {{ signal?: AbortSignal }} [options] + * @returns {Promise<{ blob: Blob, filename: string }>} + */ +export async function downloadArtifact(artifactId, { signal } = {}) { + if (!artifactId || typeof artifactId !== 'string') { + const err = new Error('Invalid artifact ID.'); + err.code = 'invalid_input'; + throw err; + } + + const response = await fetch(`/api/v1/artifacts/${encodeURIComponent(artifactId)}`, { + method: 'GET', + signal + }); + + if (!response.ok) { + throw await parseApiError(response); + } + + // Extract filename from Content-Disposition if present + let filename = 'download'; + const disposition = response.headers.get('Content-Disposition'); + if (disposition) { + const match = disposition.match(/filename=["']?([^"';]+)["']?/i); + if (match && match[1]) { + filename = match[1].trim(); + } + } + + const blob = await response.blob(); + return { blob, filename }; +} diff --git a/frontend/js/app.js b/frontend/js/app.js new file mode 100644 index 0000000..481e149 --- /dev/null +++ b/frontend/js/app.js @@ -0,0 +1,538 @@ +/** + * Main application wiring and state management. + * Credentials remain strictly in browser memory and are never persisted or logged. + */ + +import { verifyCredentials, submitQuery, downloadArtifact, validateCredentials } from './api.js'; +import { MarkdownRenderer, exportToMarkdown, renderWarnings } from './render.js'; +import { renderPagesAccessed, renderToolHistory, renderArtifacts } from './history.js'; + +// Application memory state +let committedCredentials = null; // { url: string, pat: string } | null +let draftCredentials = { url: '', pat: '' }; +let activeAbortController = null; +let currentRequestGeneration = 0; +let activeVerifyAbortController = null; +let currentVerifyGeneration = 0; +let currentResult = null; +let lastSubmittedPrompt = ''; + +// DOM Elements +let viewPrompt, viewLoading, viewResult; +let promptInput, submitBtn, promptError; +let keyBtn, credIndicator, credStatusSr; +let modalBackdrop, modalDialog, modalCloseBtn, credentialsForm; +let credUrlInput, credPatInput, togglePatBtn, modalFeedback; +let btnTestCred, btnSaveCred, btnCancelCred, btnClearCred; +let cancelBtn, backBtn, exportBtn; +let outputContent, sectionNav, resultWarnings; +let artifactsSection, artifactsList, artifactsError; +let historySection, historyToggleBtn, historyToggleTitle, historyContent; +let pagesAccessedList, toolHistoryList; + +let markdownRenderer = null; + +/** + * Initializes DOM element references and event listeners. + */ +document.addEventListener('DOMContentLoaded', () => { + // Views + viewPrompt = document.getElementById('view-prompt'); + viewLoading = document.getElementById('view-loading'); + viewResult = document.getElementById('view-result'); + + // Prompt View + promptInput = document.getElementById('prompt-input'); + submitBtn = document.getElementById('submit-btn'); + promptError = document.getElementById('prompt-error'); + + // Header / Credentials + keyBtn = document.getElementById('key-btn'); + credIndicator = document.getElementById('cred-indicator'); + credStatusSr = document.getElementById('cred-status-sr'); + + // Modal + modalBackdrop = document.getElementById('modal-backdrop'); + modalDialog = document.getElementById('modal-dialog'); + modalCloseBtn = document.getElementById('modal-close-btn'); + credentialsForm = document.getElementById('credentials-form'); + credUrlInput = document.getElementById('cred-url'); + credPatInput = document.getElementById('cred-pat'); + togglePatBtn = document.getElementById('toggle-pat-btn'); + modalFeedback = document.getElementById('modal-feedback'); + btnTestCred = document.getElementById('btn-test-cred'); + btnSaveCred = document.getElementById('btn-save-cred'); + btnCancelCred = document.getElementById('btn-cancel-cred'); + btnClearCred = document.getElementById('btn-clear-cred'); + + // Loading & Result Controls + cancelBtn = document.getElementById('cancel-btn'); + backBtn = document.getElementById('back-btn'); + exportBtn = document.getElementById('export-btn'); + + // Result Area + outputContent = document.getElementById('output-content'); + sectionNav = document.getElementById('section-nav'); + resultWarnings = document.getElementById('result-warnings'); + + // Artifacts Area + artifactsSection = document.getElementById('artifacts-section'); + artifactsList = document.getElementById('artifacts-list'); + artifactsError = document.getElementById('artifacts-error'); + + // History Area + historySection = document.getElementById('history-section'); + historyToggleBtn = document.getElementById('history-toggle-btn'); + historyToggleTitle = document.getElementById('history-toggle-title'); + historyContent = document.getElementById('history-content'); + pagesAccessedList = document.getElementById('pages-accessed-list'); + toolHistoryList = document.getElementById('tool-history-list'); + + // Markdown renderer + markdownRenderer = new MarkdownRenderer(outputContent, sectionNav); + + // Wire events + setupPromptEvents(); + setupModalEvents(); + setupResultEvents(); + updateCredentialIndicator(); +}); + +/** + * Updates textarea height dynamically up to 280px. + */ +function autoResizeTextarea() { + if (!promptInput) return; + promptInput.style.height = 'auto'; + const newHeight = Math.min(promptInput.scrollHeight, 280); + promptInput.style.height = `${newHeight}px`; +} + +/** + * Sets up prompt input and submission listeners. + */ +function setupPromptEvents() { + promptInput.addEventListener('input', autoResizeTextarea); + + // Enter to submit (outside IME), Shift+Enter for newline + promptInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + if (e.isComposing || e.keyCode === 229) { + return; // IME composition in progress + } + if (!e.shiftKey) { + e.preventDefault(); + handleSubmitQuery(); + } + } + }); + + submitBtn.addEventListener('click', (e) => { + e.preventDefault(); + handleSubmitQuery(); + }); +} + +/** + * Handles query submission. + */ +async function handleSubmitQuery() { + const prompt = promptInput.value; + if (!prompt || !prompt.trim()) { + showPromptError('Please enter a research prompt.'); + return; + } + + // Ensure credentials are configured + if (!committedCredentials || !committedCredentials.url || !committedCredentials.pat) { + showPromptError('Confluence credentials required. Click the key icon to configure URL and PAT.'); + openCredentialsModal(); + return; + } + + hidePromptError(); + lastSubmittedPrompt = prompt; + + // Transition to loading view + switchView('loading'); + + const generation = ++currentRequestGeneration; + activeAbortController = new AbortController(); + + try { + const result = await submitQuery( + { prompt, credentials: committedCredentials }, + { signal: activeAbortController.signal } + ); + + // Stale check + if (generation !== currentRequestGeneration) { + return; + } + + currentResult = result; + renderResultView(result); + switchView('result'); + } catch (err) { + // Stale check + if (generation !== currentRequestGeneration) { + return; + } + + if (err.name === 'AbortError') { + // User cancelled, smoothly return to prompt view + switchView('prompt'); + return; + } + + // Switch back to prompt view and display error + switchView('prompt'); + if (err.code === 'confluence_auth_failed') { + showPromptError('Confluence authentication failed. Please verify your URL and PAT in the credentials modal.'); + } else if (err.code === 'origin_denied') { + showPromptError('Request forbidden: Origin denied by server policy.'); + } else if (err.code === 'destination_denied') { + showPromptError('Request forbidden: Confluence destination URL is not permitted by server policy.'); + } else if (err.code === 'busy') { + showPromptError('The server is currently busy processing another query or cleaning up. Please try again shortly.'); + } else if (err.code === 'query_timeout') { + showPromptError('The query timed out. The operation exceeded the allowed execution time.'); + } else if (err.code === 'request_too_large') { + showPromptError('The request exceeds the maximum allowed payload size.'); + } else { + showPromptError(`Query failed [${err.code || 'error'}]: ${err.message || 'An unexpected error occurred.'}`); + } + } finally { + if (generation === currentRequestGeneration) { + activeAbortController = null; + } + } +} + +/** + * Sets up credentials modal and actions. + */ +function setupModalEvents() { + keyBtn.addEventListener('click', openCredentialsModal); + modalCloseBtn.addEventListener('click', closeCredentialsModal); + btnCancelCred.addEventListener('click', closeCredentialsModal); + + // Close modal on Escape + window.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && !modalBackdrop.classList.contains('hidden')) { + closeCredentialsModal(); + } + }); + + // Close on backdrop click outside dialog + modalBackdrop.addEventListener('click', (e) => { + if (e.target === modalBackdrop) { + closeCredentialsModal(); + } + }); + + // Focus trap inside modal dialog + modalDialog.addEventListener('keydown', (e) => { + if (e.key !== 'Tab') return; + const focusable = modalDialog.querySelectorAll( + 'button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])' + ); + if (focusable.length === 0) return; + + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + + if (e.shiftKey && document.activeElement === first) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && document.activeElement === last) { + e.preventDefault(); + first.focus(); + } + }); + + // Password visibility toggle + togglePatBtn.addEventListener('click', () => { + const isPassword = credPatInput.type === 'password'; + credPatInput.type = isPassword ? 'text' : 'password'; + togglePatBtn.setAttribute('aria-label', isPassword ? 'Hide token' : 'Show token'); + }); + + // Typing in inputs invalidates any in-flight test connection + credUrlInput.addEventListener('input', () => { + abortActiveVerify(); + btnTestCred.disabled = false; + }); + credPatInput.addEventListener('input', () => { + abortActiveVerify(); + btnTestCred.disabled = false; + }); + + // Test connection button (draft credentials only, does NOT commit; guarded against staleness) + btnTestCred.addEventListener('click', async () => { + draftCredentials.url = credUrlInput.value.trim(); + draftCredentials.pat = credPatInput.value.trim(); + + try { + validateCredentials(draftCredentials); + } catch (err) { + showModalFeedback(err.message, 'error'); + return; + } + + const verifyGen = ++currentVerifyGeneration; + if (activeVerifyAbortController) { + activeVerifyAbortController.abort(); + } + activeVerifyAbortController = new AbortController(); + + btnTestCred.disabled = true; + showModalFeedback('Testing connection...', 'info'); + + try { + await verifyCredentials(draftCredentials, { signal: activeVerifyAbortController.signal }); + if (verifyGen !== currentVerifyGeneration) return; + showModalFeedback('Connection successful! Credentials are valid.', 'success'); + } catch (err) { + if (verifyGen !== currentVerifyGeneration) return; + if (err.name === 'AbortError') return; + showModalFeedback(`Connection failed [${err.code || 'error'}]: ${err.message}`, 'error'); + } finally { + if (verifyGen === currentVerifyGeneration) { + btnTestCred.disabled = false; + activeVerifyAbortController = null; + } + } + }); + + // Save & Close form submit + credentialsForm.addEventListener('submit', (e) => { + e.preventDefault(); + abortActiveVerify(); + draftCredentials.url = credUrlInput.value.trim(); + draftCredentials.pat = credPatInput.value.trim(); + + try { + validateCredentials(draftCredentials); + } catch (err) { + showModalFeedback(err.message, 'error'); + return; + } + + // Commit credentials to memory + committedCredentials = { + url: draftCredentials.url, + pat: draftCredentials.pat + }; + + updateCredentialIndicator(); + closeCredentialsModal(); + hidePromptError(); + }); + + // Clear credentials + btnClearCred.addEventListener('click', () => { + abortActiveVerify(); + // If a query is active, abort it + if (activeAbortController) { + currentRequestGeneration++; + activeAbortController.abort(); + activeAbortController = null; + switchView('prompt'); + } + + committedCredentials = null; + draftCredentials = { url: '', pat: '' }; + credUrlInput.value = ''; + credPatInput.value = ''; + updateCredentialIndicator(); + showModalFeedback('Credentials cleared from browser memory.', 'info'); + }); +} + +/** + * Aborts any pending verify connection request and increments generation counter. + */ +function abortActiveVerify() { + currentVerifyGeneration++; + if (activeVerifyAbortController) { + activeVerifyAbortController.abort(); + activeVerifyAbortController = null; + } +} + +/** + * Opens credentials modal and restores draft from committed state. + */ +function openCredentialsModal() { + modalFeedback.className = 'modal-feedback hidden'; + modalFeedback.textContent = ''; + + if (committedCredentials) { + credUrlInput.value = committedCredentials.url; + credPatInput.value = committedCredentials.pat; + } else { + credUrlInput.value = draftCredentials.url || ''; + credPatInput.value = draftCredentials.pat || ''; + } + + modalBackdrop.classList.remove('hidden'); + credUrlInput.focus(); +} + +/** + * Closes credentials modal and restores focus to key button. + */ +function closeCredentialsModal() { + abortActiveVerify(); + modalBackdrop.classList.add('hidden'); + keyBtn.focus(); +} + +/** + * Displays modal feedback messages. + * @param {string} msg + * @param {'error'|'success'|'info'} type + */ +function showModalFeedback(msg, type) { + modalFeedback.className = `modal-feedback ${type === 'error' ? 'error-box' : type === 'success' ? 'success-box' : 'warning-box'}`; + modalFeedback.textContent = msg; +} + +/** + * Updates the key icon indicator state. + */ +function updateCredentialIndicator() { + if (committedCredentials && committedCredentials.url && committedCredentials.pat) { + credIndicator.classList.add('active'); + credStatusSr.textContent = 'Credentials active in memory'; + keyBtn.title = 'Credentials active (Click to edit)'; + } else { + credIndicator.classList.remove('active'); + credStatusSr.textContent = 'Credentials not set'; + keyBtn.title = 'Configure Confluence Credentials'; + } +} + +/** + * Sets up result view buttons and interactions. + */ +function setupResultEvents() { + // Cancel button during loading + cancelBtn.addEventListener('click', () => { + if (activeAbortController) { + currentRequestGeneration++; + activeAbortController.abort(); + activeAbortController = null; + } + switchView('prompt'); + }); + + // Back to prompt button + backBtn.addEventListener('click', () => { + switchView('prompt'); + promptInput.focus(); + }); + + // Export to MD button + exportBtn.addEventListener('click', () => { + if (currentResult && typeof currentResult.markdown === 'string') { + exportToMarkdown(currentResult.markdown, lastSubmittedPrompt); + } + }); + + // History toggle button + historyToggleBtn.addEventListener('click', () => { + const expanded = historyToggleBtn.getAttribute('aria-expanded') === 'true'; + historyToggleBtn.setAttribute('aria-expanded', String(!expanded)); + if (expanded) { + historyContent.classList.add('hidden'); + } else { + historyContent.classList.remove('hidden'); + } + }); +} + +/** + * Renders the query result view. + * @param {object} result + */ +function renderResultView(result) { + // 1. Warnings + renderWarnings(resultWarnings, result.warnings || []); + + // 2. Markdown output (with bounded section renderer) + markdownRenderer.load(result.markdown || ''); + + // 3. Artifacts + artifactsError.classList.add('hidden'); + artifactsError.textContent = ''; + if (Array.isArray(result.artifacts) && result.artifacts.length > 0) { + artifactsSection.classList.remove('hidden'); + renderArtifacts(artifactsList, result.artifacts, async (id, name) => { + try { + artifactsError.classList.add('hidden'); + const { blob, filename } = await downloadArtifact(id); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename || name; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + } catch (err) { + artifactsError.classList.remove('hidden'); + artifactsError.textContent = `Download failed [${err.code || 'error'}]: ${err.message || 'Artifact not found or expired.'}`; + } + }); + } else { + artifactsSection.classList.add('hidden'); + artifactsList.replaceChildren(); + } + + // 4. Sources and Tool History + const pages = result.pages_accessed || []; + historyToggleTitle.textContent = `Sources & Request History (${pages.length} page${pages.length === 1 ? '' : 's'} accessed)`; + renderPagesAccessed(pagesAccessedList, pages); + renderToolHistory(toolHistoryList, result.tool_history || []); + + // Collapse history by default + historyToggleBtn.setAttribute('aria-expanded', 'false'); + historyContent.classList.add('hidden'); +} + +/** + * Switches the active view. + * @param {'prompt'|'loading'|'result'} viewName + */ +function switchView(viewName) { + viewPrompt.classList.add('hidden'); + viewLoading.classList.add('hidden'); + viewResult.classList.add('hidden'); + + if (viewName === 'prompt') { + viewPrompt.classList.remove('hidden'); + } else if (viewName === 'loading') { + viewLoading.classList.remove('hidden'); + } else if (viewName === 'result') { + viewResult.classList.remove('hidden'); + } +} + +/** + * Shows prompt error message. + * @param {string} msg + */ +function showPromptError(msg) { + promptError.textContent = msg; + promptError.classList.remove('hidden'); +} + +/** + * Hides prompt error message. + */ +function hidePromptError() { + promptError.textContent = ''; + promptError.classList.add('hidden'); +} diff --git a/frontend/js/history.js b/frontend/js/history.js new file mode 100644 index 0000000..669a07e --- /dev/null +++ b/frontend/js/history.js @@ -0,0 +1,419 @@ +/** + * Sources, Request History, and Artifacts rendering module. + * Provides bounded lazy expansion of huge tool results, sanitized textContent rendering, + * and distinct display of repeated/cache-hit calls. + */ + +const MAX_HISTORY_RESULT_DISPLAY_BYTES = 32 * 1024; // 32 KiB display limit per entry + +/** + * Formats byte counts into human-readable strings. + * @param {number} bytes + * @returns {string} + */ +export function formatBytes(bytes) { + if (typeof bytes !== 'number' || isNaN(bytes) || bytes < 0) return '0 B'; + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +/** + * Bounded JSON serializer that traverses data structures lazily and terminates + * immediately when maxBytes is exceeded, avoiding full serialization memory cost. + * @param {any} value + * @param {number} [maxBytes] + * @returns {string} + */ +export function serializeBounded(value, maxBytes = MAX_HISTORY_RESULT_DISPLAY_BYTES) { + if (value === undefined) return 'undefined'; + if (value === null) return 'null'; + if (typeof value !== 'object') { + const s = String(value); + if (s.length > maxBytes) { + return s.slice(0, maxBytes) + `\n\n... [Truncated: ${formatBytes(s.length)} total]`; + } + return JSON.stringify(value); + } + + let totalChars = 0; + let truncated = false; + const parts = []; + + function append(str) { + if (!str) return; + if (totalChars + str.length > maxBytes) { + const allowed = Math.max(0, maxBytes - totalChars); + if (allowed > 0) { + parts.push(str.slice(0, allowed)); + totalChars += allowed; + } + truncated = true; + } else { + parts.push(str); + totalChars += str.length; + } + } + + function walk(val, indent) { + if (totalChars >= maxBytes) { + truncated = true; + return; + } + + if (val === null) { + append('null'); + return; + } + + const type = typeof val; + if (type !== 'object') { + if (type === 'string') { + const remaining = maxBytes - totalChars; + if (val.length > remaining) { + truncated = true; + const sliced = val.slice(0, Math.max(0, remaining - 15)); + append(JSON.stringify(sliced).slice(0, -1) + '... [truncated]"'); + } else { + append(JSON.stringify(val)); + } + } else { + append(JSON.stringify(val)); + } + return; + } + + const spaces = ' '.repeat(indent); + const nextSpaces = ' '.repeat(indent + 1); + + if (Array.isArray(val)) { + if (val.length === 0) { + append('[]'); + return; + } + append('[\n'); + for (let i = 0; i < val.length; i++) { + if (totalChars >= maxBytes) { + truncated = true; + append(`${nextSpaces}... [${val.length - i} more items truncated]\n`); + break; + } + append(nextSpaces); + walk(val[i], indent + 1); + if (i < val.length - 1) append(','); + append('\n'); + } + append(`${spaces}]`); + return; + } + + // Object + const keys = Object.keys(val); + if (keys.length === 0) { + append('{}'); + return; + } + append('{\n'); + for (let i = 0; i < keys.length; i++) { + if (totalChars >= maxBytes) { + truncated = true; + append(`${nextSpaces}... [${keys.length - i} more properties truncated]\n`); + break; + } + const key = keys[i]; + append(`${nextSpaces}${JSON.stringify(key)}: `); + walk(val[key], indent + 1); + if (i < keys.length - 1) append(','); + append('\n'); + } + append(`${spaces}}`); + } + + walk(value, 0); + + let result = parts.join(''); + if (truncated) { + result += `\n\n... [Result display bounded to ${formatBytes(maxBytes)}; click Export to MD for full output]`; + } + return result; +} + +/** + * Formats ISO timestamp into readable UTC string. + * @param {string} isoString + * @returns {string} + */ +export function formatTimestamp(isoString) { + if (!isoString) return 'Unknown'; + try { + const d = new Date(isoString); + if (isNaN(d.getTime())) return isoString; + return d.toISOString().replace('T', ' ').replace('Z', ' UTC'); + } catch { + return isoString; + } +} + +/** + * Renders the list of accessed Confluence pages. + * @param {HTMLElement} container + * @param {Array<{ page_id: string, title: string, space: string, url: string, accessed_at: string }>} pages + */ +export function renderPagesAccessed(container, pages) { + container.replaceChildren(); + + if (!Array.isArray(pages) || pages.length === 0) { + const emptyMsg = document.createElement('p'); + emptyMsg.className = 'page-card-meta'; + emptyMsg.textContent = 'No Confluence pages were read during this query.'; + container.appendChild(emptyMsg); + return; + } + + pages.forEach((page) => { + const card = document.createElement('div'); + card.className = 'page-card'; + + const left = document.createElement('div'); + left.className = 'page-card-left'; + + const spaceBadge = document.createElement('span'); + spaceBadge.className = 'badge-space'; + spaceBadge.textContent = page.space || 'PAGE'; + + const link = document.createElement('a'); + link.className = 'page-title-link'; + link.textContent = page.title || `Page ${page.page_id}`; + if (page.url) { + try { + const u = new URL(page.url, window.location.href); + if (['http:', 'https:'].includes(u.protocol)) { + link.href = u.href; + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + } + } catch { + // Leave link without href if invalid + } + } + + left.appendChild(spaceBadge); + left.appendChild(link); + + const meta = document.createElement('div'); + meta.className = 'page-card-meta'; + meta.textContent = `ID: ${page.page_id} · Accessed: ${formatTimestamp(page.accessed_at)}`; + + card.appendChild(left); + card.appendChild(meta); + container.appendChild(card); + }); +} + +/** + * Renders the authoritative tool history with bounded lazy result expansion. + * @param {HTMLElement} container + * @param {Array} toolHistory + */ +export function renderToolHistory(container, toolHistory) { + container.replaceChildren(); + + if (!Array.isArray(toolHistory) || toolHistory.length === 0) { + const emptyMsg = document.createElement('p'); + emptyMsg.className = 'page-card-meta'; + emptyMsg.textContent = 'No remote tool operations recorded.'; + container.appendChild(emptyMsg); + return; + } + + toolHistory.forEach((entry) => { + const card = document.createElement('div'); + card.className = 'tool-card'; + + // Header + const header = document.createElement('div'); + header.className = 'tool-card-header'; + + const headerLeft = document.createElement('div'); + headerLeft.className = 'tool-card-header-left'; + + const idSpan = document.createElement('span'); + idSpan.className = 'tool-id'; + idSpan.textContent = `#${entry.tool_call_id || 'call'}`; + + const nameSpan = document.createElement('span'); + nameSpan.className = 'tool-name'; + nameSpan.textContent = entry.tool || 'unknown_tool'; + + headerLeft.appendChild(idSpan); + headerLeft.appendChild(nameSpan); + + const badges = document.createElement('div'); + badges.className = 'tool-badges'; + + // Status badge + const statusBadge = document.createElement('span'); + const isSuccess = entry.status === 'success'; + statusBadge.className = `badge ${isSuccess ? 'badge-success' : 'badge-error'}`; + statusBadge.textContent = isSuccess ? 'Success' : 'Error'; + badges.appendChild(statusBadge); + + // Cache hit badge + if (entry.cache_hit) { + const cacheBadge = document.createElement('span'); + cacheBadge.className = 'badge badge-cache'; + cacheBadge.textContent = 'Cache Hit'; + badges.appendChild(cacheBadge); + } + + // Truncation badges + if (entry.parameters_truncated) { + const paramTrunc = document.createElement('span'); + paramTrunc.className = 'badge badge-truncated'; + paramTrunc.textContent = 'Params Truncated'; + badges.appendChild(paramTrunc); + } + + if (entry.result_truncated) { + const resTrunc = document.createElement('span'); + resTrunc.className = 'badge badge-truncated'; + resTrunc.textContent = 'Result Truncated'; + badges.appendChild(resTrunc); + } + + header.appendChild(headerLeft); + header.appendChild(badges); + card.appendChild(header); + + // Body + const body = document.createElement('div'); + body.className = 'tool-card-body'; + + const metaRow = document.createElement('div'); + metaRow.className = 'tool-meta-row'; + const timeText = `Started: ${formatTimestamp(entry.started_at)} · Completed: ${formatTimestamp(entry.completed_at)}`; + metaRow.textContent = timeText; + body.appendChild(metaRow); + + // Expandable toggle button + const toggleBtn = document.createElement('button'); + toggleBtn.type = 'button'; + toggleBtn.className = 'tool-expand-btn'; + toggleBtn.textContent = 'Show details'; + toggleBtn.setAttribute('aria-expanded', 'false'); + + let detailsRendered = false; + let detailsContainer = null; + + toggleBtn.addEventListener('click', () => { + const isExpanded = toggleBtn.getAttribute('aria-expanded') === 'true'; + if (isExpanded) { + toggleBtn.setAttribute('aria-expanded', 'false'); + toggleBtn.textContent = 'Show details'; + if (detailsContainer) { + detailsContainer.classList.add('hidden'); + } + } else { + toggleBtn.setAttribute('aria-expanded', 'true'); + toggleBtn.textContent = 'Hide details'; + + if (!detailsRendered) { + detailsContainer = document.createElement('div'); + detailsContainer.className = 'tool-details'; + + // Parameters section + const paramLabel = document.createElement('div'); + paramLabel.className = 'history-subheading'; + paramLabel.textContent = 'Parameters'; + detailsContainer.appendChild(paramLabel); + + const paramBox = document.createElement('pre'); + paramBox.className = 'tool-result-box'; + paramBox.textContent = serializeBounded(entry.parameters || {}, MAX_HISTORY_RESULT_DISPLAY_BYTES); + detailsContainer.appendChild(paramBox); + + // Result or Error section + const resultLabel = document.createElement('div'); + resultLabel.className = 'history-subheading'; + resultLabel.textContent = entry.error ? 'Error' : 'Result'; + detailsContainer.appendChild(resultLabel); + + const resultBox = document.createElement('pre'); + resultBox.className = 'tool-result-box'; + + if (entry.error) { + resultBox.textContent = serializeBounded(entry.error, MAX_HISTORY_RESULT_DISPLAY_BYTES); + } else { + // Lazy bounded serialization without paying full in-memory stringification cost + resultBox.textContent = serializeBounded(entry.result, MAX_HISTORY_RESULT_DISPLAY_BYTES); + } + + detailsContainer.appendChild(resultBox); + body.appendChild(detailsContainer); + detailsRendered = true; + } else if (detailsContainer) { + detailsContainer.classList.remove('hidden'); + } + } + }); + + body.appendChild(toggleBtn); + card.appendChild(body); + container.appendChild(card); + }); +} + +/** + * Renders the list of exported artifacts. + * @param {HTMLElement} container + * @param {Array<{ id: string, name: string, size_bytes: number, expires_at: string }>} artifacts + * @param {(id: string, name: string) => Promise} onDownload + */ +export function renderArtifacts(container, artifacts, onDownload) { + container.replaceChildren(); + + if (!Array.isArray(artifacts) || artifacts.length === 0) { + return; + } + + artifacts.forEach((art) => { + const item = document.createElement('li'); + item.className = 'artifact-item'; + + const info = document.createElement('div'); + info.className = 'artifact-info'; + + const nameSpan = document.createElement('span'); + nameSpan.className = 'artifact-name'; + nameSpan.textContent = art.name || 'unnamed_artifact'; + + const metaSpan = document.createElement('span'); + metaSpan.className = 'artifact-meta'; + metaSpan.textContent = `${formatBytes(art.size_bytes)} · Expires: ${formatTimestamp(art.expires_at)}`; + + info.appendChild(nameSpan); + info.appendChild(metaSpan); + + const dlBtn = document.createElement('button'); + dlBtn.type = 'button'; + dlBtn.className = 'download-btn'; + dlBtn.textContent = 'Download'; + dlBtn.setAttribute('aria-label', `Download ${art.name}`); + + dlBtn.addEventListener('click', async () => { + dlBtn.disabled = true; + const originalText = dlBtn.textContent; + dlBtn.textContent = 'Downloading...'; + try { + await onDownload(art.id, art.name); + } finally { + dlBtn.disabled = false; + dlBtn.textContent = originalText; + } + }); + + item.appendChild(info); + item.appendChild(dlBtn); + container.appendChild(item); + }); +} diff --git a/frontend/js/render.js b/frontend/js/render.js new file mode 100644 index 0000000..cfe40b0 --- /dev/null +++ b/frontend/js/render.js @@ -0,0 +1,464 @@ +/** + * Markdown rendering and bounded sectioning pipeline. + * Uses pinned marked.js and DOMPurify with strict tag allowlist and link normalization. + */ + +// Target maximum size for a single rendered Markdown section +export const SECTION_TARGET_BYTES = 48 * 1024; // ~48 KiB soft target +export const SECTION_HARD_LIMIT_BYTES = 64 * 1024; // ~64 KiB hard cap per section +export const PATHOLOGICAL_BLOCK_LIMIT = 128 * 1024; // 128 KiB fallback threshold + +const textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null; + +/** + * Calculates UTF-8 byte length for a string. + * @param {string} str + * @returns {number} + */ +export function getUtf8Bytes(str) { + if (!str) return 0; + if (textEncoder) { + return textEncoder.encode(str).length; + } + let bytes = 0; + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i); + if (code <= 0x7f) bytes += 1; + else if (code <= 0x7ff) bytes += 2; + else if (code >= 0xd800 && code <= 0xdbff) { + bytes += 4; + i++; + } else bytes += 3; + } + return bytes; +} + +/** + * Configure marked options once. + */ +if (typeof window !== 'undefined' && window.marked) { + window.marked.setOptions({ + gfm: true, + breaks: true + }); +} + +/** + * Normalizes and sanitizes a single bounded markdown section into HTML. + * Fails safe: never injects raw untrusted markdown if parser or sanitizer is absent. + * @param {string} rawMd + * @returns {DocumentFragment} + */ +export function renderMarkdownSectionToFragment(rawMd) { + if (typeof rawMd !== 'string') { + return document.createDocumentFragment(); + } + + // Fail-safe render: if marked or DOMPurify are absent, fail safe with an empty fragment + notice. + // Never inject raw untrusted markdown as innerHTML. + if (typeof window === 'undefined' || typeof document === 'undefined' || !window.marked || !window.DOMPurify) { + if (typeof document === 'undefined') { + return { + textContent: 'Markdown renderer or sanitizer is unavailable. Content cannot be displayed safely.', + isFailSafe: true + }; + } + const fragment = document.createDocumentFragment(); + const notice = document.createElement('div'); + notice.className = 'render-error-notice'; + notice.textContent = 'Markdown renderer or sanitizer is unavailable. Content cannot be displayed safely.'; + fragment.appendChild(notice); + return fragment; + } + + // Parse Markdown using locally vendored marked + let rawHtml = ''; + try { + rawHtml = window.marked.parse(rawMd); + } catch { + const fragment = document.createDocumentFragment(); + const notice = document.createElement('div'); + notice.className = 'render-error-notice'; + notice.textContent = 'Failed to parse Markdown section.'; + fragment.appendChild(notice); + return fragment; + } + + // Sanitize with strict allowlist + const cleanHtml = window.DOMPurify.sanitize(rawHtml, { + ALLOWED_TAGS: [ + 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', + 'strong', 'em', 'del', 's', 'blockquote', 'pre', 'code', + 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'a' + ], + ALLOWED_ATTR: ['href', 'title', 'colspan', 'rowspan', 'start'], + ALLOW_DATA_ATTR: false, + ALLOW_ARIA_ATTR: false + }); + + // Build template and normalize links + const template = document.createElement('template'); + template.innerHTML = cleanHtml; + + template.content.querySelectorAll('a').forEach((link) => { + try { + const href = link.getAttribute('href'); + if (!href) throw new Error('Empty href'); + const url = new URL(href, window.location.href); + if (!['https:', 'http:'].includes(url.protocol)) { + throw new Error('Disallowed protocol'); + } + link.href = url.href; + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + } catch { + // Strip unsafe/invalid hrefs (e.g. javascript:, data:, relative file URLs) + link.removeAttribute('href'); + } + }); + + return template.content; +} + +/** + * Partitions large markdown documents into bounded sections to prevent DOM exhaustion. + * Preserves code fences and table boundaries where feasible. + * Forces section splits even inside large code fences by safely closing and re-opening the fence. + * Keeps table rows together and repeats table headers if forced to split. + * Dense lists without blank lines split cleanly at item or line boundaries. + * Falls back to bounded plain-text preview for single pathological blocks. + * @param {string} rawMd + * @returns {Array<{ text: string, isPathologicalFallback?: boolean }>} + */ +export function partitionMarkdown(rawMd) { + if (!rawMd) return []; + const totalBytes = getUtf8Bytes(rawMd); + if (totalBytes <= SECTION_TARGET_BYTES) { + if (totalBytes > PATHOLOGICAL_BLOCK_LIMIT) { + return [{ + text: rawMd.slice(0, 32 * 1024) + '\n\n... [Block truncated for performance; click Export to MD for full document]', + isPathologicalFallback: true + }]; + } + return [{ text: rawMd }]; + } + + const sections = []; + const lines = rawMd.split('\n'); + let currentChunk = []; + let currentSize = 0; + + let inCodeFence = false; + let fenceIndent = ''; + let fenceChar = '`'; + let fenceLen = 3; + let fenceInfo = ''; + + let inTable = false; + let tableHeader = null; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const lineBytes = getUtf8Bytes(line) + 1; // +1 for newline + + // Check for single pathological line/block exceeding safety limit + if (lineBytes > PATHOLOGICAL_BLOCK_LIMIT) { + if (currentChunk.length > 0) { + if (inCodeFence) { + currentChunk.push(`${fenceIndent}${fenceChar.repeat(fenceLen)}`); + } + const chunkText = currentChunk.join('\n'); + if (chunkText.trim().length > 0) { + sections.push({ text: chunkText }); + } + currentChunk = []; + currentSize = 0; + } + // Pathological chunk fallback: bounded slice + sections.push({ + text: line.slice(0, 32 * 1024) + '\n\n... [Block truncated for performance; click Export to MD for full document]', + isPathologicalFallback: true + }); + if (inCodeFence) { + const reopen = `${fenceIndent}${fenceChar.repeat(fenceLen)}${fenceInfo || ''}`; + currentChunk.push(reopen); + currentSize = getUtf8Bytes(reopen) + 1; + } + continue; + } + + // Code fence detection + const fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})(.*)$/); + if (!inCodeFence && fenceMatch) { + inCodeFence = true; + fenceIndent = fenceMatch[1]; + fenceChar = fenceMatch[2][0]; + fenceLen = fenceMatch[2].length; + fenceInfo = fenceMatch[3].trim(); + } else if (inCodeFence) { + const closeRegex = new RegExp(`^\\s*${fenceChar === '`' ? '`' : '~'}{${fenceLen},}\\s*$`); + if (closeRegex.test(line)) { + inCodeFence = false; + } + } + + // Table detection (GFM tables) + const isTableRow = /^\s*\|.*\|\s*$/.test(line); + const isTableSep = /^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/.test(line); + + if (!inCodeFence) { + if (isTableRow && !inTable && i + 1 < lines.length && /^\s*\|(?:\s*:?-+:?\s*\|)+\s*$/.test(lines[i + 1])) { + inTable = true; + tableHeader = `${line}\n${lines[i + 1]}`; + } else if (inTable && (line.trim() === '' || !isTableRow)) { + inTable = false; + tableHeader = null; + } + } + + // Split decision when inside code fence: + // Force split if current chunk exceeds hard limit + if (inCodeFence) { + if (currentSize + lineBytes > SECTION_HARD_LIMIT_BYTES && currentChunk.length > 0) { + // Safely close fence in current chunk + const closeFence = `${fenceIndent}${fenceChar.repeat(fenceLen)}`; + currentChunk.push(closeFence); + sections.push({ text: currentChunk.join('\n') }); + + // Re-open fence in new chunk + const reopenFence = `${fenceIndent}${fenceChar.repeat(fenceLen)}${fenceInfo || ''}`; + currentChunk = [reopenFence]; + currentSize = getUtf8Bytes(reopenFence) + 1; + } + currentChunk.push(line); + currentSize += lineBytes; + continue; + } + + // Split decision when inside table: + if (inTable) { + if (currentSize + lineBytes > SECTION_HARD_LIMIT_BYTES && currentChunk.length > 0 && !isTableSep) { + sections.push({ text: currentChunk.join('\n') }); + currentChunk = []; + currentSize = 0; + if (tableHeader) { + currentChunk.push(tableHeader); + currentSize = getUtf8Bytes(tableHeader) + 1; + } + } + currentChunk.push(line); + currentSize += lineBytes; + continue; + } + + // Outside code fences and tables: + const isHeading = /^\s*#{1,3}\s/.test(line); + const isEmptyLine = line.trim() === ''; + const isListItem = /^\s*([*+-]|\d+\.)\s/.test(line); + + const shouldSplit = ( + (isHeading && currentSize >= 16 * 1024) || + ((isHeading || isEmptyLine) && currentSize >= SECTION_TARGET_BYTES) || + (isListItem && currentSize >= SECTION_TARGET_BYTES) || + (currentSize + lineBytes > SECTION_HARD_LIMIT_BYTES) + ); + + if (shouldSplit && currentChunk.length > 0) { + const chunkText = currentChunk.join('\n'); + if (chunkText.trim().length > 0) { + sections.push({ text: chunkText }); + } + currentChunk = []; + currentSize = 0; + } + + currentChunk.push(line); + currentSize += lineBytes; + } + + if (currentChunk.length > 0) { + if (inCodeFence) { + currentChunk.push(`${fenceIndent}${fenceChar.repeat(fenceLen)}`); + } + const chunkText = currentChunk.join('\n'); + if (chunkText.trim().length > 0) { + sections.push({ text: chunkText }); + } + } + + return sections.length > 0 ? sections : [{ text: rawMd }]; +} + +/** + * State container for bounded section rendering in the UI. + */ +export class MarkdownRenderer { + /** + * @param {HTMLElement} containerElement + * @param {HTMLElement} navElement + */ + constructor(containerElement, navElement) { + this.container = containerElement; + this.nav = navElement; + this.sections = []; + this.currentIndex = 0; + } + + /** + * Loads and partitions new markdown text. + * @param {string} rawMd + */ + load(rawMd) { + this.sections = partitionMarkdown(rawMd); + this.currentIndex = 0; + this.renderCurrentSection(); + } + + /** + * Renders the current active section, limiting retained rendered DOM nodes. + */ + renderCurrentSection() { + this.container.replaceChildren(); + + if (this.sections.length === 0) { + this.nav.classList.add('hidden'); + return; + } + + const current = this.sections[this.currentIndex]; + + // If pathological fallback was triggered, render plain-text preview (never raw to marked) + if (current.isPathologicalFallback) { + const banner = document.createElement('div'); + banner.className = 'pathological-banner'; + banner.textContent = 'Pathological large block detected. Display bounded for performance; use "Export to MD" to download the full document.'; + this.container.appendChild(banner); + + const pre = document.createElement('pre'); + pre.className = 'pathological-preview'; + pre.textContent = current.text; + this.container.appendChild(pre); + } else { + // Normal section: parse and sanitize + const fragment = renderMarkdownSectionToFragment(current.text); + this.container.appendChild(fragment); + } + + // Update section navigation controls (show for multiple sections OR single pathological section) + if (this.sections.length > 1 || current.isPathologicalFallback) { + this.nav.classList.remove('hidden'); + this.updateNavUI(); + } else { + this.nav.classList.add('hidden'); + } + } + + /** + * Updates navigation buttons and indicators. + */ + updateNavUI() { + this.nav.replaceChildren(); + + const banner = document.createElement('div'); + banner.className = 'section-nav-banner'; + + const info = document.createElement('span'); + if (this.sections.length === 1 && this.sections[0].isPathologicalFallback) { + info.textContent = 'Showing bounded plain-text preview (pathological input; click Export to MD for full document)'; + } else { + info.textContent = `Showing section ${this.currentIndex + 1} of ${this.sections.length} (bounded for responsiveness)`; + } + + const controls = document.createElement('div'); + controls.className = 'section-nav-controls'; + + if (this.sections.length > 1) { + const prevBtn = document.createElement('button'); + prevBtn.type = 'button'; + prevBtn.className = 'section-btn'; + prevBtn.textContent = '← Previous'; + prevBtn.disabled = this.currentIndex === 0; + prevBtn.addEventListener('click', () => { + if (this.currentIndex > 0) { + this.currentIndex--; + this.renderCurrentSection(); + this.container.scrollIntoView({ behavior: 'smooth', block: 'start' }); + } + }); + + const nextBtn = document.createElement('button'); + nextBtn.type = 'button'; + nextBtn.className = 'section-btn'; + nextBtn.textContent = 'Next →'; + nextBtn.disabled = this.currentIndex >= this.sections.length - 1; + nextBtn.addEventListener('click', () => { + if (this.currentIndex < this.sections.length - 1) { + this.currentIndex++; + this.renderCurrentSection(); + this.container.scrollIntoView({ behavior: 'smooth', block: 'start' }); + } + }); + + controls.appendChild(prevBtn); + controls.appendChild(nextBtn); + } + + banner.appendChild(info); + if (this.sections.length > 1) { + banner.appendChild(controls); + } + this.nav.appendChild(banner); + } +} + +/** + * Downloads raw Markdown content client-side via Blob. + * Uses exact specification naming: confluence_summary__.md + * Revokes object URL after dispatch. + * @param {string} rawMarkdown + * @param {string} queryText + */ +export function exportToMarkdown(rawMarkdown, queryText) { + const slug = (queryText || '').slice(0, 30).replace(/[^a-zA-Z0-9]/g, '_').toLowerCase(); + const filename = `confluence_summary_${slug || 'export'}_${Date.now()}.md`; + const blob = new Blob([rawMarkdown], { type: 'text/markdown;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +/** + * Renders warning items safely into the warnings container. + * @param {HTMLElement} container + * @param {Array<{ code: string, message: string, tool_call_id?: string, name?: string }>} warnings + */ +export function renderWarnings(container, warnings) { + container.replaceChildren(); + if (!Array.isArray(warnings) || warnings.length === 0) { + container.classList.add('hidden'); + return; + } + + container.classList.remove('hidden'); + warnings.forEach((w) => { + const item = document.createElement('div'); + item.className = 'warning-item'; + + const codeSpan = document.createElement('span'); + codeSpan.className = 'warning-code'; + codeSpan.textContent = `[${w.code || 'warning'}]`; + + const msgSpan = document.createElement('span'); + msgSpan.className = 'warning-msg'; + msgSpan.textContent = w.message || 'An unknown warning occurred.'; + + item.appendChild(codeSpan); + item.appendChild(msgSpan); + container.appendChild(item); + }); +} diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000..3bda0a0 --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,45 @@ +{ + "name": "frontend", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "dompurify": "^3.4.15", + "marked": "^18.0.13" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, + "node_modules/dompurify": { + "version": "3.4.15", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz", + "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/marked": { + "version": "18.0.13", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.13.tgz", + "integrity": "sha512-xTxVzZsBFwunP6HDmtBkabUQEYArnP7/rMDGmPj9SlrKlQ4i8MdYVow+nJL0eOqwpUqhzBoTBRADGN6uYwPyOw==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..547fed1 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,17 @@ +{ + "name": "frontend", + "version": "1.0.0", + "description": "Confluence Research Web UI and Mock Server", + "main": "js/app.js", + "type": "module", + "scripts": { + "dev": "node dev/mock-server.js", + "start": "node dev/mock-server.js", + "test": "node --test tests/*.test.js", + "test:e2e": "node tests/e2e_runner.js" + }, + "dependencies": { + "dompurify": "3.4.15", + "marked": "18.0.13" + } +} diff --git a/frontend/tests/api.test.js b/frontend/tests/api.test.js new file mode 100644 index 0000000..f1f174f --- /dev/null +++ b/frontend/tests/api.test.js @@ -0,0 +1,110 @@ +/** + * Unit tests for api.js validation logic and boundaries. + */ + +import { test, describe } from 'node:test'; +import assert from 'node:assert/strict'; +import { getUtf8ByteLength, validateCredentials, submitQuery } from '../js/api.js'; + +describe('API validation and boundaries', () => { + test('getUtf8ByteLength correctly calculates ASCII and multibyte UTF-8 lengths', () => { + assert.equal(getUtf8ByteLength('hello'), 5); + // Multibyte characters: + // '€' is 3 bytes (0xE2 0x82 0xAC) + // '🚀' is 4 bytes (0xF0 0x9F 0x99 0x80) + assert.equal(getUtf8ByteLength('€'), 3); + assert.equal(getUtf8ByteLength('🚀'), 4); + assert.equal(getUtf8ByteLength('こんにちは'), 15); // 5 x 3 bytes + }); + + test('validateCredentials validates valid HTTP and HTTPS URLs', () => { + assert.doesNotThrow(() => { + validateCredentials({ + url: 'https://confluence.example.com', + pat: 'valid-pat-string' + }); + }); + + assert.doesNotThrow(() => { + validateCredentials({ + url: 'http://localhost:8080/confluence', + pat: 'pat-token' + }); + }); + }); + + test('validateCredentials rejects empty or missing fields', () => { + assert.throws( + () => validateCredentials({ url: '', pat: 'pat' }), + (err) => err.code === 'invalid_input' + ); + + assert.throws( + () => validateCredentials({ url: 'https://example.com', pat: ' ' }), + (err) => err.code === 'invalid_input' + ); + }); + + test('validateCredentials rejects invalid protocols like javascript: or file:', () => { + assert.throws( + () => validateCredentials({ url: 'javascript:alert(1)', pat: 'pat' }), + (err) => err.code === 'invalid_input' + ); + + assert.throws( + () => validateCredentials({ url: 'file:///etc/passwd', pat: 'pat' }), + (err) => err.code === 'invalid_input' + ); + }); + + test('validateCredentials exact 8 KiB boundary check', () => { + // Exactly 8192 bytes (8 KiB) passes + const exact8KiBPat = 'a'.repeat(8192); + assert.doesNotThrow(() => { + validateCredentials({ url: 'https://example.com', pat: exact8KiBPat }); + }); + + // 8193 bytes fails + const over8KiBPat = 'a'.repeat(8193); + assert.throws( + () => validateCredentials({ url: 'https://example.com', pat: over8KiBPat }), + (err) => err.code === 'invalid_input' && err.message.includes('8 KiB') + ); + + // Multibyte 8 KiB boundary: 2048 emojis = 8192 bytes (passes) + const exact8KiBEmoji = '🚀'.repeat(2048); + assert.equal(getUtf8ByteLength(exact8KiBEmoji), 8192); + assert.doesNotThrow(() => { + validateCredentials({ url: 'https://example.com', pat: exact8KiBEmoji }); + }); + + // 2049 emojis = 8196 bytes (fails) + const over8KiBEmoji = exact8KiBEmoji + '🚀'; + assert.throws( + () => validateCredentials({ url: 'https://example.com', pat: over8KiBEmoji }), + (err) => err.code === 'invalid_input' && err.message.includes('8 KiB') + ); + }); + + test('runtime 16 MiB multibyte UTF-8 boundary validation on prompt', async () => { + const validCredentials = { url: 'https://approved.example.com', pat: 'dummy-pat-123' }; + + // Construct a real 16 MiB string containing 4-byte multibyte emojis at runtime + // 4 bytes * 4,194,304 = 16,777,216 bytes (exactly 16 MiB) + const chunk = '🚀'.repeat(1024); // 4096 bytes + const exactly16MiBPrompt = chunk.repeat(4096); // 16 MiB + assert.equal(getUtf8ByteLength(exactly16MiBPrompt), 16 * 1024 * 1024); + + // Prompt exceeding 16 MiB by 1 byte + const over16MiBPrompt = exactly16MiBPrompt + 'a'; + assert.equal(getUtf8ByteLength(over16MiBPrompt), 16 * 1024 * 1024 + 1); + + // Rejection above 16 MiB + await assert.rejects( + async () => { + await submitQuery({ prompt: over16MiBPrompt, credentials: validCredentials }); + }, + (err) => err.code === 'invalid_input' && err.message.includes('16 MiB') + ); + }); +}); diff --git a/frontend/tests/contract.test.js b/frontend/tests/contract.test.js new file mode 100644 index 0000000..7163163 --- /dev/null +++ b/frontend/tests/contract.test.js @@ -0,0 +1,303 @@ +/** + * Contract and Mock Server tests. + * Validates wire formats, security headers, session cookies, and scenarios against CONTRACTS.md. + */ + +import { test, describe, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { createMockServer, SCENARIOS } from '../dev/mock-server.js'; + +const TEST_PORT = 5199; +const BASE_URL = `http://127.0.0.1:${TEST_PORT}`; + +describe('Mock Server and Wire Contract Tests', () => { + let server; + + before(async () => { + server = createMockServer(); + await new Promise((resolve) => { + server.listen(TEST_PORT, '127.0.0.1', resolve); + }); + }); + + after(async () => { + await new Promise((resolve) => { + server.close(resolve); + }); + }); + + test('GET / sets cw_session cookie and serves security headers', async () => { + const res = await fetch(`${BASE_URL}/`); + assert.equal(res.status, 200); + + // Security headers + assert.equal(res.headers.get('x-content-type-options'), 'nosniff'); + assert.equal(res.headers.get('referrer-policy'), 'no-referrer'); + const csp = res.headers.get('content-security-policy'); + assert.ok(csp.includes("default-src 'none'")); + assert.ok(csp.includes("script-src 'self'")); + assert.ok(csp.includes("style-src 'self'")); + assert.ok(csp.includes("connect-src 'self'")); + assert.ok(csp.includes("img-src 'none'")); + + // Session cookie + const cookie = res.headers.get('set-cookie'); + assert.ok(cookie, 'Set-Cookie header must be present'); + assert.ok(cookie.includes('cw_session='), 'Cookie name must be cw_session'); + assert.ok(cookie.includes('HttpOnly'), 'Cookie must be HttpOnly'); + assert.ok(cookie.includes('SameSite=Strict'), 'Cookie must be SameSite=Strict'); + }); + + test('POST /api/v1/auth/verify succeeds with dummy credentials', async () => { + const res = await fetch(`${BASE_URL}/api/v1/auth/verify`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + url: 'https://confluence.example.com', + pat: 'dummy-pat-token-123' + }) + }); + + assert.equal(res.status, 200); + assert.equal(res.headers.get('cache-control'), 'no-store'); + const body = await res.json(); + assert.deepEqual(body, { valid: true }); + }); + + test('POST /api/v1/auth/verify fails with 403 in 403_verify scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/auth/verify?scenario=403_verify`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + url: 'https://confluence.example.com', + pat: 'dummy-pat-token-123' + }) + }); + + assert.equal(res.status, 403); + const body = await res.json(); + assert.ok(body.error); + assert.equal(body.error.code, 'confluence_auth_failed'); + }); + + test('POST /api/v1/query handles normal scenario matching section 7 shared contract', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=normal`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'deploy service X', + credentials: { + url: 'https://approved.example.com', + pat: 'dummy-pat-123' + } + }) + }); + + assert.equal(res.status, 200); + assert.equal(res.headers.get('cache-control'), 'no-store'); + const data = await res.json(); + + assert.ok(data.session_id); + assert.ok(data.markdown.includes('Deployment Guide')); + assert.equal(data.pages_accessed.length, 1); + assert.equal(data.pages_accessed[0].page_id, '847291'); + assert.equal(data.pages_accessed[0].space, 'OPS'); + assert.ok(data.pages_accessed[0].accessed_at); + + assert.equal(data.tool_history.length, 2); + assert.equal(data.tool_history[0].tool, 'confluence_search'); + assert.equal(data.tool_history[1].tool, 'confluence_view'); + assert.equal(data.tool_history[1].cache_hit, false); + + assert.equal(data.artifacts.length, 1); + assert.equal(data.artifacts[0].name, 'checklist.md'); + assert.equal(data.artifacts[0].size_bytes, 32); + assert.ok(data.artifacts[0].expires_at); + }); + + test('GET /api/v1/artifacts/:id downloads exact 32 bytes for checklist.md', async () => { + const res = await fetch(`${BASE_URL}/api/v1/artifacts/art-checklist-01`); + assert.equal(res.status, 200); + assert.equal(res.headers.get('content-type'), 'application/octet-stream'); + assert.equal(res.headers.get('x-content-type-options'), 'nosniff'); + assert.ok(res.headers.get('content-disposition').includes('attachment; filename="checklist.md"')); + + const text = await res.text(); + assert.equal(text, '# Checklist\n\n- Deploy service X\n'); + assert.equal(Buffer.byteLength(text, 'utf-8'), 32); + }); + + test('GET /api/v1/artifacts/:id returns 404 in unknown_expired_download scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/artifacts/art-checklist-01?scenario=unknown_expired_download`); + assert.equal(res.status, 404); + const body = await res.json(); + assert.equal(body.error.code, 'artifact_not_found'); + }); + + test('POST /api/v1/query handles 409 busy scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=409_busy`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'test prompt', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 409); + const body = await res.json(); + assert.equal(body.error.code, 'busy'); + }); + + test('POST /api/v1/query handles 504 timeout scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=504_timeout`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'test prompt', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 504); + const body = await res.json(); + assert.equal(body.error.code, 'query_timeout'); + }); + + test('POST /api/v1/query handles empty_search scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=empty_search`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'non-existent query', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.pages_accessed.length, 0); + assert.equal(body.artifacts.length, 0); + assert.equal(body.tool_history.length, 1); + assert.equal(body.tool_history[0].result.pages.length, 0); + }); + + test('POST /api/v1/query handles repeated_cached_view scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=repeated_cached_view`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'cache test', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.pages_accessed.length, 1); + assert.equal(body.tool_history.length, 2); + assert.equal(body.tool_history[0].cache_hit, false); + assert.equal(body.tool_history[1].cache_hit, true); + }); + + test('POST /api/v1/query handles failed_tool scenario with status="error"', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=failed_tool`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'failed tool test', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 200); + const body = await res.json(); + const errorTool = body.tool_history.find((t) => t.status === 'error'); + assert.ok(errorTool); + assert.equal(errorTool.result, null); + assert.equal(errorTool.error.code, 'page_not_found'); + }); + + test('POST /api/v1/query handles warning_truncated_history scenario', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query?scenario=warning_truncated_history`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': BASE_URL + }, + body: JSON.stringify({ + prompt: 'truncation test', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 200); + const body = await res.json(); + assert.ok(body.warnings.length > 0); + assert.equal(body.tool_history[0].parameters_truncated, true); + assert.equal(body.tool_history[0].result_truncated, true); + }); + + test('Origin check rejects untrusted external origins', async () => { + const res = await fetch(`${BASE_URL}/api/v1/query`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Origin': 'https://evil-attacker.example.com' + }, + body: JSON.stringify({ + prompt: 'attack', + credentials: { url: 'https://example.com', pat: 'dummy' } + }) + }); + + assert.equal(res.status, 403); + const body = await res.json(); + assert.equal(body.error.code, 'origin_denied'); + }); + + test('Mock dev toolbar external assets served with correct headers and zero inline script/style', async () => { + // CSS asset + const cssRes = await fetch(`${BASE_URL}/dev/scenario-toolbar.css`); + assert.equal(cssRes.status, 200); + assert.ok(cssRes.headers.get('content-type').includes('text/css')); + assert.equal(cssRes.headers.get('x-content-type-options'), 'nosniff'); + + // JS asset + const jsRes = await fetch(`${BASE_URL}/dev/scenario-toolbar.js`); + assert.equal(jsRes.status, 200); + assert.ok(jsRes.headers.get('content-type').includes('javascript')); + assert.equal(jsRes.headers.get('x-content-type-options'), 'nosniff'); + + // Root HTML page must not contain inline scripts or inline style attributes + const htmlRes = await fetch(`${BASE_URL}/`); + const html = await htmlRes.text(); + assert.ok(!/]*src=)[^>]*>/i.test(html), 'Root HTML in dev mode must not contain inline '; + const fragment = renderMarkdownSectionToFragment(rawUntrusted); + + // Must return a safe DocumentFragment containing the render error notice, NEVER raw innerHTML + assert.ok(fragment); + if (typeof document !== 'undefined') { + const notice = fragment.querySelector('.render-error-notice'); + assert.ok(notice, 'Must contain error notice when parser/sanitizer is absent'); + assert.ok(!fragment.querySelector('script'), 'Must never inject script tags'); + assert.ok(!fragment.querySelector('img'), 'Must never inject img tags'); + } + }); + + test('serializeBounded bounds huge 10 MB objects to <= 32 KiB without memory exhaustion', () => { + const hugeObject = { + title: 'Large Tool Result', + markdown: 'x'.repeat(10 * 1024 * 1024), // 10 MB string + items: Array.from({ length: 50000 }, (_, i) => ({ id: i, name: `item_${i}` })) + }; + + const serialized = serializeBounded(hugeObject, 32 * 1024); + assert.ok(serialized.length <= 34 * 1024, `Serialized result length ${serialized.length} must be bounded around 32 KB`); + assert.ok(serialized.includes('Result display bounded to 32.0 KB'), 'Must include truncation indicator'); + }); +}); diff --git a/frontend/vendor/dompurify.LICENSE b/frontend/vendor/dompurify.LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/frontend/vendor/dompurify.LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/frontend/vendor/marked.LICENSE b/frontend/vendor/marked.LICENSE new file mode 100644 index 0000000..4bd2d4a --- /dev/null +++ b/frontend/vendor/marked.LICENSE @@ -0,0 +1,44 @@ +# License information + +## Contribution License Agreement + +If you contribute code to this project, you are implicitly allowing your code +to be distributed under the MIT license. You are also implicitly verifying that +all code is your original work. `` + +## Marked + +Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) +Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## Markdown + +Copyright © 2004, John Gruber +http://daringfireball.net/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. diff --git a/frontend/vendor/marked.min.js b/frontend/vendor/marked.min.js new file mode 100644 index 0000000..567f4bd --- /dev/null +++ b/frontend/vendor/marked.min.js @@ -0,0 +1,80 @@ +/** + * marked v18.0.13 - a markdown parser + * Copyright (c) 2018-2026, MarkedJS. (MIT License) + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ +(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; +"use strict";var U=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var $e=(l,e)=>{for(var t in e)U(l,t,{get:e[t],enumerable:!0})},Le=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Se(e))!_e.call(l,s)&&s!==t&&U(l,s,{get:()=>e[s],enumerable:!(n=Pe(e,s))||n.enumerable});return l};var ze=l=>Le(U({},"__esModule",{value:!0}),l);var It={};$e(It,{Hooks:()=>P,Lexer:()=>x,Marked:()=>q,Parser:()=>b,Renderer:()=>y,TextRenderer:()=>_,Tokenizer:()=>w,defaults:()=>R,getDefaults:()=>E,lexer:()=>At,marked:()=>g,options:()=>_t,parse:()=>Et,parseInline:()=>zt,parser:()=>Mt,setOptions:()=>$t,use:()=>Oe,walkTokens:()=>Lt});module.exports=ze(It);function E(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var R=E();function F(l){R=l}var M={exec:()=>null};function I(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l(n),e[n]=s),s}}function d(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(s,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(m.caret,"$1"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}var Ee=((l="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(l=>new RegExp(`^ {0,${l}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(l=>new RegExp(`^ {0,${l}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:I(l=>new RegExp(`^ {0,${l}}(?:)|<(?:script|pre|style|textarea|!--))`,"i")),blockquoteBeginRegex:I(l=>new RegExp(`^ {0,${l}}>`))},Me=/^(?:[ \t]*(?:\n|$))+/,Ae=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ie=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,H=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ce=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,W=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ue=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,pe=d(ue).replace(/bull/g,W).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Be=d(ue).replace(/bull/g,W).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),X=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,De=/^[^\n]+/,J=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,qe=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",J).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ve=d(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,W).getRegex(),Z="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",V=/|$))/,He=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|[^\\n]*\\n*|$)|[^\\n]*\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",V).replace("tag",Z).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ce=l=>d(X).replace("hr",H).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l).replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Z).getRegex(),Ze=ce(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ge=ce(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Qe=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ge).getRegex(),Y={blockquote:Qe,code:Ae,def:qe,fences:Ie,heading:Ce,hr:H,html:He,lheading:pe,list:ve,newline:Me,paragraph:Ze,table:M,text:De},oe=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",H).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Z).getRegex(),Ne={...Y,lheading:Be,table:oe,paragraph:d(X).replace("hr",H).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",oe).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Z).getRegex()},je={...Y,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",V).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:M,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(X).replace("hr",H).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",pe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ue=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Fe=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,he=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Ke=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Ee?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ke=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,et=d(ke,"u").replace(/punct/g,$).getRegex(),tt=d(ke,"u").replace(/punct/g,de).getRegex(),nt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,rt=d(nt,"u").replace(/openQuote/g,Xe).replace(/punct/g,$).getRegex(),ge="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",st=d(ge,"gu").replace(/notPunctSpace/g,G).replace(/punctSpace/g,C).replace(/punct/g,$).getRegex(),it=d(ge,"gu").replace(/notPunctSpace/g,Ve).replace(/punctSpace/g,Je).replace(/punct/g,de).getRegex(),ot="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",at=d(ot,"gu").replace(/notPunctSpace/g,G).replace(/punctSpace/g,C).replace(/punct/g,$).getRegex(),lt=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,G).replace(/punctSpace/g,C).replace(/punct/g,$).getRegex(),ut="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",pt=d(ut,"gu").replace(/notPunctSpace/g,G).replace(/punctSpace/g,C).replace(/punct/g,$).getRegex(),ct=d(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,$).getRegex(),ht="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",dt=d(ht,"gu").replace(/notPunctSpace/g,G).replace(/punctSpace/g,C).replace(/punct/g,$).getRegex(),kt=d(/\\(punct)/,"gu").replace(/punct/g,$).getRegex(),gt=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ft=d(V).replace("(?:-->|$)","-->").getRegex(),mt=d("^comment|^|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",ft).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),fe=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,N=d(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",fe).getRegex(),xt=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",N).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),bt=d(/^!?\[(label)\]\[(ref)\]/).replace("label",N).replace("ref",J).getRegex(),Rt=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",J).getRegex(),ae=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Tt=d(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",fe).getRegex(),Ot=d("reflink|nolink(?!\\()","g").replace("reflink",d(/^!?\[(label)\]\[(ref)\]/).replace("label",Tt).replace("ref",ae).getRegex()).replace("nolink",d(/^!?\[(ref)\](?:\[\])?/).replace("ref",ae).getRegex()).getRegex(),le=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ee={_backpedal:M,anyPunctuation:kt,autolink:gt,blockSkip:Ye,br:he,code:Fe,del:M,delLDelim:M,delRDelim:M,emStrongLDelim:et,emStrongRDelimAst:st,emStrongRDelimUnd:lt,escape:Ue,link:xt,nolink:Rt,punctuation:We,reflink:bt,reflinkSearch:Ot,tag:mt,text:Ke,url:M},wt={...ee,emStrongLDelim:rt,emStrongRDelimAst:at,emStrongRDelimUnd:pt,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",N).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",N).getRegex()},K={...ee,emStrongRDelimAst:it,emStrongLDelim:tt,delLDelim:ct,delRDelim:dt,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",le).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},me=l=>Pt[l];function T(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,me)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,me);return l}function te(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function ne(l,e){let t=l.replace(m.findPipe,(r,o,i)=>{let u=!1,a=o;for(;--a>=0&&i[a]==="\\";)u=!u;return u?"|":" |"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(` +`)}function D(l){return l.toLowerCase().toUpperCase().toLowerCase()}function xe(l,e){if(l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n0?-2:-1}function be(l,e=0){let t=e,n="";for(let s of l)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function Re(l,e,t,n,s){let r=e.href,o=e.title||null,i=l[1].replace(s.other.outputLinkReplace,"$1"),u=l[0].charAt(0)==="!";n.state.inLink=!0;let a=n.state.linkEmitted,p=n.state.inRawBlock;n.state.linkEmitted=!1;let c=n.inlineTokens(i),h=n.state.linkEmitted;if(n.state.linkEmitted=a,n.state.inLink=!1,!u){if(h){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:u?"image":"link",raw:t,href:r,title:o,text:i,tokens:c}}function St(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(` +`).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[i]=o;return r.slice(Math.min(i.length,s.length))}).join(` +`)}function Te(l,e,t,n){if(!e.includes("<"))return!1;for(let s=0;se.length-s)return!0;s+=o[0].length-1}}return!1}var w=class{options;rules;lexer;constructor(e){this.options=e||R}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:re(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=St(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=L(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:"heading",raw:L(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:L(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],` +`).split(` +`),s="",r="",o=[];for(;n.length>0;){let i=!1,u=[],a;for(a=0;a1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let o=this.rules.other.listItemRegex(n),i=!1;for(;e;){let a=!1,p="",c="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=be(t[2].split(` +`,1)[0],t[1].length),k=e.split(` +`,1)[0],O=!h.trim(),f=0;if(this.options.pedantic?(f=2,c=h.trimStart()):O?f=t[1].length+1:(f=h.search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=h.slice(f),f+=t[1].length),O&&this.rules.other.blankLine.test(k)&&(p+=k+` +`,e=e.substring(k.length+1),a=!0),!a){let S=this.rules.other.nextBulletRegex(f),z=this.rules.other.hrRegex(f),se=this.rules.other.fencesBeginRegex(f),ie=this.rules.other.headingBeginRegex(f),we=this.rules.other.htmlBeginRegex(f),ye=this.rules.other.blockquoteBeginRegex(f);for(;e;){let j=e.split(` +`,1)[0],v;if(k=j,this.options.pedantic?(k=k.replace(this.rules.other.listReplaceNesting," "),v=k):v=k.replace(this.rules.other.tabCharGlobal," "),se.test(k)||ie.test(k)||we.test(k)||ye.test(k)||S.test(k)||z.test(k))break;if(v.search(this.rules.other.nonSpaceChar)>=f||!k.trim())c+=` +`+v.slice(f);else{if(O||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||se.test(h)||ie.test(h)||z.test(h))break;c+=` +`+k}O=!k.trim(),p+=j+` +`,e=e.substring(j.length+1),h=v.slice(f)}}r.loose||(i?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(i=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),r.raw+=p}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items)if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),!r.loose){let p=a.tokens.filter(h=>h.type==="space"),c=p.length>0&&p.some(h=>this.rules.other.anyLine.test(h.raw));r.loose=c}for(let a of r.items){let p=a.tokens[0];if(a.task&&(p?.type==="text"||p?.type==="paragraph")){a.text=a.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let h={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};a.checked=h.checked,r.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=h.raw+a.tokens[0].raw,a.tokens[0].text=h.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(h)):a.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):a.tokens.unshift(h)}}else a.task&&(a.task=!1)}if(r.loose)for(let a of r.items){a.loose=!0;for(let p of a.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=re(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=D(t[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:L(t[0],` +`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ne(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],o={type:"table",raw:L(t[0],` +`),header:[],align:[],rows:[]};if(n.length===s.length){for(let i of s)this.rules.other.tableAlignRight.test(i)?o.align.push("right"):this.rules.other.tableAlignCenter.test(i)?o.align.push("center"):this.rules.other.tableAlignLeft.test(i)?o.align.push("left"):o.align.push(null);for(let i=0;i({text:u,tokens:this.lexer.inline(u),header:!1,align:o.align[a]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:L(t[0],` +`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Te(e,t[1],n,this.rules))return;let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let i=L(s.slice(0,-1),"\\");if((s.length-i.length)%2===0)return}else{let i=xe(t[2],"()");if(i===-2)return;if(i>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),Re(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Te(e,n[1],s,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[D(r)];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Re(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[3]||"")||!n||this.rules.inline.punctuation.exec(n)){let o=[...s[0]].length-1,i,u,a=o,p=0,c=s[0][0],h=n===c,k=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(k.lastIndex=0,t=t.slice(-1*e.length+o);(s=k.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(u=[...i].length,s[3]||s[4]){a+=u;continue}else if(s[5]||s[6]){if(o%3&&!((o+u)%3)){p+=u;continue}if(h)break}if(a-=u,a>0)continue;u=Math.min(u,u+a+p);let O=[...s[0]][0].length,f=e.slice(0,o+s.index+O+u);if(Math.min(o,u)%2){let z=f.slice(1,-1);return{type:"em",raw:f,text:z,tokens:this.lexer.inlineTokens(z)}}let S=f.slice(2,-2);return{type:"strong",raw:f,text:S,tokens:this.lexer.inlineTokens(S)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(!s)return;if(!(s[1]||"")||!n||this.rules.inline.punctuation.exec(n)){let o=[...s[0]].length-1,i,u,a=o,p=this.rules.inline.delRDelim;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(u=[...i].length,u!==o))continue;if(s[3]||s[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let c=[...s[0]][0].length,h=e.slice(0,o+s.index+c+u),k=h.slice(o,-o);return{type:"del",raw:h,text:k,tokens:this.lexer.inlineTokens(k)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||R,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let t={other:m,block:Q.normal,inline:B.normal};this.options.pedantic?(t.block=Q.pedantic,t.inline=B.pedantic):this.options.gfm&&(t.block=Q.gfm,this.options.breaks?t.inline=B.breaks:t.inline=B.gfm),this.tokenizer.rules=t}static get rules(){return{block:Q,inline:B}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(r=i.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let i=t.at(-1);r.raw.length===1&&i!==void 0?i.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.text,this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.raw,this.inlineQueue.at(-1).src=i.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let i=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(p=>{a=p.call({lexer:this},u),typeof a=="number"&&a>=0&&(i=Math.min(i,a))}),i<1/0&&i>=0&&(o=e.substring(0,i+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let i=t.at(-1);n&&i?.type==="paragraph"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let s=n[0],r=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,D(s.slice(r+1,-1))))&&!(r>1&&this.linkInText(s.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e;if(this.tokens.links&&e.includes("[")){let i=this.tokenizer.rules.inline.reflinkSearch,u=a=>{let p=a.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,D(a.slice(p+1,-1))))return a;if(p>1&&a.charAt(0)!=="!"){let c=a.slice(1,p-1);if(this.linkInText(c))return"["+c.replace(i,u)+"]["+"a".repeat(a.length-p-2)+"]"}return"["+"a".repeat(a.length-2)+"]"};n=n.replace(i,u)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,i=>"+".repeat(i.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(i,u,a)=>{let p=a?a.length:0;return i.slice(0,p)+"["+"a".repeat(i.length-p-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,r="",o=1/0;for(;e;){if(e.length(i=a.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let a=t.at(-1);i.type==="text"&&a?.type==="text"?(a.raw+=i.raw,a.text+=i.text):t.push(i);continue}if(i=this.tokenizer.emStrong(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.del(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),t.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),t.push(i);continue}let u=e;if(this.options.extensions?.startInline){let a=1/0,p=e.slice(1),c;this.options.extensions.startInline.forEach(h=>{c=h.call({lexer:this},p),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(u=e.substring(0,a+1))}if(i=this.tokenizer.inlineText(u)){e=e.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(r=i.raw.slice(-1)),s=!0;let a=t.at(-1);a?.type==="text"?(a.raw+=i.raw,a.text+=i.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var y=class{options;parser;constructor(e){this.options=e||R}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(m.notSpaceStart)?.[0],r=e?e.replace(m.endingNewline,"")+` +`:"";return s?'
'+(n?r:T(r,!0))+`
+`:"
"+(n?r:T(r,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,s="";for(let i=0;i +`+s+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let r=0;r${s}`),` + +`+t+` +`+s+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${T(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,text:n,tokens:s,autolink:r}){let o=r?T(n,!0):this.parser.parseInline(s),i=te(e);if(i===null)return o;e=T(i,r);let u='
    ",u}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=te(e);if(r===null)return T(n);e=r;let o=`${T(n)}{let i=r[o].flat(1/0);n=n.concat(this.walkTokens(i,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...i){let u=r.renderer.apply(this,i);return u===!1&&(u=o.apply(this,i)),u}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new y(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let i=o,u=n.renderer[i],a=r[i];r[i]=(...p)=>{let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new w(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let i=o,u=n.tokenizer[i],a=r[i];r[i]=(...p)=>{let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new P;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let i=o,u=n.hooks[i],a=r[i];P.passThroughHooks.has(o)?r[i]=p=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await u.call(r,p);return a.call(r,h)})();let c=u.call(r,p);return a.call(r,c)}:r[i]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await u.apply(r,p);return h===!1&&(h=await a.apply(r,p)),h})();let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(i){let u=[];return u.push(o.call(this,i)),r&&(u=u.concat(r.call(this,i))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let u=o.hooks?await o.hooks.preprocess(n):n,p=await(o.hooks?await o.hooks.provideLexer(e):e?x.lex:x.lexInline)(u,o),c=o.hooks?await o.hooks.processAllTokens(p):p;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let k=await(o.hooks?await o.hooks.provideParser(e):e?b.parse:b.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(k):k})().catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let a=(o.hooks?o.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let c=(o.hooks?o.hooks.provideParser(e):e?b.parse:b.parseInline)(a,o);return o.hooks&&(c=o.hooks.postprocess(c)),c}catch(u){return i(u)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+T(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var A=new q;function g(l,e){return A.parse(l,e)}g.options=g.setOptions=function(l){return A.setOptions(l),g.defaults=A.defaults,F(g.defaults),g};g.getDefaults=E;g.defaults=R;function Oe(...l){return A.use(...l),g.defaults=A.defaults,F(g.defaults),g}g.use=Oe;g.walkTokens=function(l,e){return A.walkTokens(l,e)};g.parseInline=A.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=_;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var _t=g.options,$t=g.setOptions,Lt=g.walkTokens,zt=g.parseInline,Et=g,Mt=b.parse,At=x.lex; + +if(__exports != exports)module.exports = exports;return module.exports})); +//# sourceMappingURL=marked.umd.js.map diff --git a/frontend/vendor/purify.min.js b/frontend/vendor/purify.min.js new file mode 100644 index 0000000..d6d097b --- /dev/null +++ b/frontend/vendor/purify.min.js @@ -0,0 +1,3 @@ +/*! @license DOMPurify 3.4.15 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.15/LICENSE */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).DOMPurify=e()}(this,function(){"use strict";function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=Array(e);n2?n-2:0),r=2;r1?e-1:0),o=1;o1?n-1:0),r=1;r2&&void 0!==arguments[2]?arguments[2]:S;if(o&&o(t,null),!b(e))return t;let i=e.length;for(;i--;){let o=e[i];if("string"==typeof o){const t=n(o);t!==o&&(r(e)||(e[i]=t),o=t)}t[o]=!0}return t}function M(t){for(let e=0;e/g),J=c(/\${[\w\W]*/g),Q=c(/^data-[\-\w.\u00B7-\uFFFF]+$/),tt=c(/^aria-[\-\w]+$/),et=c(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),nt=c(/^(?:\w+script|data):/i),ot=c(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),rt=c(/^html$/i),it=c(/^[a-z][.\w]*(-[.\w]+)+$/i),at=c(/<[/\w!]/g),lt=c(/<[/\w]/g),ct=c(/<\/no(script|embed|frames)/i),st=c(/\/>/i),ut=1,ft=3,pt=7,mt=8,dt=9,ht=11,yt=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],gt=l(z({},yt)),bt=function(){const t={};return m(yt,e=>{t[e]=c(new RegExp("])","i"))}),l(t)}(),St=function(){return"undefined"==typeof window?null:window},Tt=function(t,e,n,o){return D(t,e)&&b(t[e])?z(o.base?P(o.base):{},t[e],o.transform):n},At=function(t,e,n){const o=D(t,e)?t[e]:void 0;return o&&"object"==typeof o?P(o):n()};var Et=function t(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:St();const o=e=>t(e);if(o.version="3.4.15",o.removed=[],!e||!e.document||e.document.nodeType!==dt||!e.Element)return o.isSupported=!1,o;let r=e.document;const i=r,a=i.currentScript;e.DocumentFragment;const u=e.HTMLTemplateElement,f=e.Node,p=e.Element,I=e.NodeFilter,L=e.NamedNodeMap;void 0===L&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const M=e.DOMParser,yt=e.trustedTypes,Et=p.prototype,wt=U(Et,"cloneNode"),vt=U(Et,"remove"),Ot=U(Et,"removeAttributeNode"),Nt=U(Et,"nextSibling"),xt=U(Et,"childNodes"),_t=U(Et,"parentNode"),Dt=U(Et,"shadowRoot"),Rt=U(Et,"attributes"),kt=f&&f.prototype?U(f.prototype,"nodeType"):null,Ct=f&&f.prototype?U(f.prototype,"nodeName"):null,It=f&&f.prototype?U(f.prototype,"ownerDocument"):null,Lt=function(t){return kt?kt(t):t.nodeType},zt=function(t){return Ct?Ct(t):t.nodeName};if("function"==typeof u){const t=r.createElement("template");t.content&&t.content.ownerDocument&&(r=t.content.ownerDocument)}let Mt,Pt,Ut="",Ft=!1,Ht=0;const jt=function(){if(Ht>0)throw C('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},Bt=function(t){jt(),Ht++;try{return Mt.createHTML(t)}finally{Ht--}},Wt=function(){return Ft||(Pt=function(t,e){if("object"!=typeof t||"function"!=typeof t.createPolicy)return null;let n=null;const o="data-tt-policy-suffix";e&&e.hasAttribute(o)&&(n=e.getAttribute(o));const r="dompurify"+(n?"#"+n:"");try{return t.createPolicy(r,{createHTML:t=>t,createScriptURL:t=>t})}catch(t){return console.warn("TrustedTypes policy "+r+" could not be created."),null}}(yt,a),Ft=!0),Pt},Yt=r,Gt=Yt.implementation,qt=Yt.createNodeIterator,$t=Yt.createDocumentFragment,Xt=Yt.getElementsByTagName,Kt=i.importNode;let Vt={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};o.isSupported="function"==typeof n&&"function"==typeof _t&&Gt&&void 0!==Gt.createHTMLDocument;const Zt=V,Jt=Z,Qt=J,te=Q,ee=tt,ne=nt,oe=ot,re=it;let ie=et,ae=null;const le=z({},[...F,...H,...j,...W,...G]);let ce=null;const se=z({},[...q,...$,...X,...K]);let ue=Object.seal(s(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),fe=null,pe=null;const me=Object.seal(s(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let de=!0,he=!0,ye=!1,ge=!0,be=!1,Se=!0,Te=!1,Ae=!1,Ee=null,we=null,ve=!1,Oe=!1,Ne=!1,xe=!1,_e=!0,De=!1;const Re="user-content-";let ke=!0,Ce=!1,Ie={},Le=null;const ze=z({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Me=null;const Pe=z({},["audio","video","img","source","image","track"]);let Ue=null;const Fe=z({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),He="http://www.w3.org/1998/Math/MathML",je="http://www.w3.org/2000/svg",Be="http://www.w3.org/1999/xhtml";let We=Be,Ye=!1,Ge=null;const qe=z({},[He,je,Be],T),$e=l(["mi","mo","mn","ms","mtext"]);let Xe=z({},$e);const Ke=l(["annotation-xml"]);let Ve=z({},Ke);const Ze=z({},["title","style","font","a","script"]);let Je=null;const Qe=["application/xhtml+xml","text/html"];let tn=null,en=null;const nn=r.createElement("form"),on=function(t){return t instanceof RegExp||t instanceof Function},rn=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(en&&en===t)return;t&&"object"==typeof t||(t={}),t=P(t),Je=-1===Qe.indexOf(t.PARSER_MEDIA_TYPE)?"text/html":t.PARSER_MEDIA_TYPE,tn="application/xhtml+xml"===Je?T:S,ae=Tt(t,"ALLOWED_TAGS",le,{transform:tn}),ce=Tt(t,"ALLOWED_ATTR",se,{transform:tn}),Ge=Tt(t,"ALLOWED_NAMESPACES",qe,{transform:T}),Ue=Tt(t,"ADD_URI_SAFE_ATTR",Fe,{transform:tn,base:Fe}),Me=Tt(t,"ADD_DATA_URI_TAGS",Pe,{transform:tn,base:Pe}),Le=Tt(t,"FORBID_CONTENTS",ze,{transform:tn}),fe=Tt(t,"FORBID_TAGS",P({}),{transform:tn}),pe=Tt(t,"FORBID_ATTR",P({}),{transform:tn}),Ie=!!D(t,"USE_PROFILES")&&(t.USE_PROFILES&&"object"==typeof t.USE_PROFILES?P(t.USE_PROFILES):t.USE_PROFILES),de=!1!==t.ALLOW_ARIA_ATTR,he=!1!==t.ALLOW_DATA_ATTR,ye=t.ALLOW_UNKNOWN_PROTOCOLS||!1,ge=!1!==t.ALLOW_SELF_CLOSE_IN_ATTR,be=t.SAFE_FOR_TEMPLATES||!1,Se=!1!==t.SAFE_FOR_XML,Te=t.WHOLE_DOCUMENT||!1,Oe=t.RETURN_DOM||!1,Ne=t.RETURN_DOM_FRAGMENT||!1,xe=t.RETURN_TRUSTED_TYPE||!1,ve=t.FORCE_BODY||!1,_e=!1!==t.SANITIZE_DOM,De=t.SANITIZE_NAMED_PROPS||!1,ke=!1!==t.KEEP_CONTENT,Ce=t.IN_PLACE||!1,ie=function(t){try{return k(t,""),!0}catch(t){return!1}}(t.ALLOWED_URI_REGEXP)?t.ALLOWED_URI_REGEXP:et,We="string"==typeof t.NAMESPACE?t.NAMESPACE:Be,Xe=At(t,"MATHML_TEXT_INTEGRATION_POINTS",()=>z({},$e)),Ve=At(t,"HTML_INTEGRATION_POINTS",()=>z({},Ke));const e=At(t,"CUSTOM_ELEMENT_HANDLING",()=>s(null));if(ue=s(null),D(e,"tagNameCheck")&&on(e.tagNameCheck)&&(ue.tagNameCheck=e.tagNameCheck),D(e,"attributeNameCheck")&&on(e.attributeNameCheck)&&(ue.attributeNameCheck=e.attributeNameCheck),D(e,"allowCustomizedBuiltInElements")&&"boolean"==typeof e.allowCustomizedBuiltInElements&&(ue.allowCustomizedBuiltInElements=e.allowCustomizedBuiltInElements),c(ue),be&&(he=!1),Ne&&(Oe=!0),Ie&&(ae=z({},G),ce=s(null),!0===Ie.html&&(z(ae,F),z(ce,q)),!0===Ie.svg&&(z(ae,H),z(ce,$),z(ce,K)),!0===Ie.svgFilters&&(z(ae,j),z(ce,$),z(ce,K)),!0===Ie.mathMl&&(z(ae,W),z(ce,X),z(ce,K))),me.tagCheck=null,me.attributeCheck=null,D(t,"ADD_TAGS")&&("function"==typeof t.ADD_TAGS?me.tagCheck=t.ADD_TAGS:b(t.ADD_TAGS)&&(ae===le&&(ae=P(ae)),z(ae,t.ADD_TAGS,tn))),D(t,"ADD_ATTR")&&("function"==typeof t.ADD_ATTR?me.attributeCheck=t.ADD_ATTR:b(t.ADD_ATTR)&&(ce===se&&(ce=P(ce)),z(ce,t.ADD_ATTR,tn))),D(t,"ADD_FORBID_CONTENTS")&&b(t.ADD_FORBID_CONTENTS)&&(Le===ze&&(Le=P(Le)),z(Le,t.ADD_FORBID_CONTENTS,tn)),ke&&(ae["#text"]=!0),Te&&z(ae,["html","head","body"]),ae.table&&(z(ae,["tbody"]),delete fe.tbody),t.TRUSTED_TYPES_POLICY){if("function"!=typeof t.TRUSTED_TYPES_POLICY.createHTML)throw C('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof t.TRUSTED_TYPES_POLICY.createScriptURL)throw C('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const e=Mt;Mt=t.TRUSTED_TYPES_POLICY;try{Ut=Bt("")}catch(t){throw Mt=e,t}}else null===t.TRUSTED_TYPES_POLICY?(Mt=void 0,Ut=""):(void 0===Mt&&(Mt=Wt()),Mt&&"string"==typeof Ut&&(Ut=Bt("")));l&&l(t),en=t},an=z({},[...H,...j,...B]),ln=z({},[...W,...Y]),cn=function(t){let e=_t(t);e&&e.tagName||(e={namespaceURI:We,tagName:"template"});const n=S(t.tagName),o=S(e.tagName);return!!Ge[t.namespaceURI]&&(t.namespaceURI===je?function(t,e,n){return e.namespaceURI===Be?"svg"===t:e.namespaceURI===He?"svg"===t&&("annotation-xml"===n||Xe[n]):Boolean(an[t])}(n,e,o):t.namespaceURI===He?function(t,e,n){return e.namespaceURI===Be?"math"===t:e.namespaceURI===je?"math"===t&&Ve[n]:Boolean(ln[t])}(n,e,o):t.namespaceURI===Be?function(t,e,n){return!(e.namespaceURI===je&&!Ve[n])&&!(e.namespaceURI===He&&!Xe[n])&&!ln[t]&&(Ze[t]||!an[t])}(n,e,o):!("application/xhtml+xml"!==Je||!Ge[t.namespaceURI]))},sn=function(t){y(o.removed,{element:t});try{_t(t).removeChild(t)}catch(e){if(vt(t),!_t(t))throw C("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},un=function(t,e,n){try{Ot(t,e)}catch(e){try{t.removeAttribute(n)}catch(t){}}},fn=function(t){dn(t);const e=xt(t);if(e){const t=[];m(e,e=>{y(t,e)}),m(t,t=>{try{vt(t)}catch(t){}})}const n=Rt(t);if(n)for(let e=n.length-1;e>=0;--e){const o=n[e],r=o&&o.name;"string"==typeof r&&un(t,o,r)}},pn=function(t,e,n){if(!n)try{n=e.getAttributeNode(t)}catch(t){n=null}y(o.removed,{attribute:n||null,from:e});try{n?Ot(e,n):e.removeAttribute(t)}catch(n){try{e.removeAttribute(t)}catch(t){}}if("is"===t)if(Oe||Ne)try{sn(e)}catch(t){}else try{e.setAttribute(t,"")}catch(t){}},mn=function(t){const e=Rt(t);if(e)for(let n=e.length-1;n>=0;--n){const o=e[n],r=o&&o.name;"string"!=typeof r||ce[tn(r)]||un(t,o,r)}},dn=function(t){const e=[t];for(;e.length>0;){const t=e.pop();Lt(t)===ut&&mn(t);const n=xt(t);if(n)for(let t=n.length-1;t>=0;--t)e.push(n[t])}},hn=function(t,e){return!!Se&&("patchsrc"===t||"for"===t&&"label"!==e&&"output"!==e)},yn=function(t){let e=null,n=null;if(ve)t=""+t;else{const e=A(t,/^[\r\n\t ]+/);n=e&&e[0]}"application/xhtml+xml"===Je&&We===Be&&(t=''+t+"");const o=Mt?Bt(t):t;if(We===Be)try{e=(new M).parseFromString(o,Je)}catch(t){}if(!e||!e.documentElement){e=Gt.createDocument(We,"template",null);try{e.documentElement.innerHTML=Ye?Ut:o}catch(t){}}const i=e.body||e.documentElement;return t&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),We===Be?Xt.call(e,Te?"html":"body")[0]:Te?e.documentElement:i},gn=function(t){const e=It?It(t):t.ownerDocument;return qt.call(e||t,t,I.SHOW_ELEMENT|I.SHOW_COMMENT|I.SHOW_TEXT|I.SHOW_PROCESSING_INSTRUCTION|I.SHOW_CDATA_SECTION,null)},bn=function(t){return t=E(t,Zt," "),t=E(t,Jt," "),t=E(t,Qt," ")},Sn=function(t){var e;t.normalize();const n=It?It(t):t.ownerDocument,o=qt.call(n||t,t,I.SHOW_TEXT|I.SHOW_COMMENT|I.SHOW_CDATA_SECTION|I.SHOW_PROCESSING_INSTRUCTION,null);let r=o.nextNode();for(;r;)r.data=bn(r.data),r=o.nextNode();const i=null===(e=t.querySelectorAll)||void 0===e?void 0:e.call(t,"template");i&&m(i,t=>{An(t.content)&&Sn(t.content)})},Tn=function(t){const e=Ct?Ct(t):null;return"string"==typeof e&&("form"===tn(e)&&("string"!=typeof t.nodeName||"string"!=typeof t.textContent||"function"!=typeof t.removeChild||t.attributes!==Rt(t)||"function"!=typeof t.removeAttribute||"function"!=typeof t.removeAttributeNode||"function"!=typeof t.getAttributeNode||"function"!=typeof t.setAttribute||"string"!=typeof t.namespaceURI||"function"!=typeof t.insertBefore||"function"!=typeof t.hasChildNodes||t.nodeType!==kt(t)||t.childNodes!==xt(t)))},An=function(t){if(!kt||"object"!=typeof t||null===t)return!1;try{return kt(t)===ht}catch(t){return!1}},En=function(t){if(!kt||"object"!=typeof t||null===t)return!1;try{return"number"==typeof kt(t)}catch(t){return!1}};function wn(t,e,n){0!==t.length&&m(t,t=>{t.call(o,e,n,en)})}const vn=function(t,e){if(t instanceof RegExp)return k(t,e);if(t instanceof Function){for(var n=arguments.length,o=new Array(n>2?n-2:0),r=2;r=0;--r){const i=t===n?wt(o[r],!0):o[r];e.insertBefore(i,Nt(t))}}return sn(t),!0}(t,n,e);return!1===o&&wn(Vt.afterSanitizeElements,t,null),o}if(Lt(t)===ut&&!cn(t))return sn(t),!0;if(("noscript"===n||"noembed"===n||"noframes"===n)&&k(ct,t.innerHTML))return sn(t),!0;if(be&&t.nodeType===ft){const e=bn(t.textContent);t.textContent!==e&&(y(o.removed,{element:t.cloneNode()}),t.textContent=e)}return wn(Vt.afterSanitizeElements,t,null),!1},_n=function(t,e,n){if(pe[e])return!1;if(hn(e,t))return!1;if(_e&&("id"===e||"name"===e)&&(n in r||n in nn))return!1;const o=ce[e]||me.attributeCheck instanceof Function&&me.attributeCheck(e,t);return!(!he||!k(te,e))||(!(!de||!k(ee,e))||(o?!!Ue[e]||(!!k(ie,E(n,oe,""))||(!("src"!==e&&"xlink:href"!==e&&"href"!==e||"script"===t||0!==w(n,"data:")||!Me[t])||(!(!ye||k(ne,E(n,oe,"")))||!n))):Rn(t)&&vn(ue.tagNameCheck,t)&&vn(ue.attributeNameCheck,e,t)||"is"===e&&ue.allowCustomizedBuiltInElements&&vn(ue.tagNameCheck,n)))},Dn=z({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Rn=function(t){return!Dn[S(t)]&&k(re,t)},kn=function(t,e,n,o){if(Mt&&"object"==typeof yt&&"function"==typeof yt.getAttributeType&&!n)switch(yt.getAttributeType(t,e)){case"TrustedHTML":return Bt(o);case"TrustedScriptURL":return function(t){jt(),Ht++;try{return Mt.createScriptURL(t)}finally{Ht--}}(o)}return o},Cn=function(t,e,n,o){try{return n?t.setAttributeNS(n,e,o):t.setAttribute(e,o),!Tn(t)||(sn(t),!1)}catch(n){return pn(e,t),!1}},In=function(t){wn(Vt.beforeSanitizeAttributes,t,null);const e=t.attributes;if(!e||Tn(t))return;ce=On(Vt.uponSanitizeAttribute,ce,se,we);const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ce,forceKeepAttr:void 0};let r=e.length;const i=tn(t.nodeName);for(;r--;){const a=e[r],l=a.name,c=a.namespaceURI,s=a.value,u=tn(l),f=s;let p="value"===l?f:v(f),m=!1;if(n.attrName=u,n.attrValue=p,n.keepAttr=!0,n.forceKeepAttr=void 0,wn(Vt.uponSanitizeAttribute,t,n),p=n.attrValue,!De||"id"!==u&&"name"!==u||0===w(p,Re)||(pn(l,t,a),p=Re+p,m=!0),Se&&k(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,p))pn(l,t,a);else if("attributename"===u&&A(p,"href"))pn(l,t,a);else if(!n.forceKeepAttr)if(n.keepAttr)if(ge||!k(st,p))if(be&&(p=bn(p)),_n(i,u,p)){if(p=kn(i,u,c,p),p!==f){Cn(t,l,c,p)&&m&&h(o.removed)}}else pn(l,t,a);else pn(l,t,a);else pn(l,t,a)}wn(Vt.afterSanitizeAttributes,t,null)},Ln=function(t){let e=null;const n=gn(t);for(wn(Vt.beforeSanitizeShadowDOM,t,null);e=n.nextNode();)if(wn(Vt.uponSanitizeShadowNode,e,null),xn(e,t),In(e),An(e.content)&&Ln(e.content),Lt(e)===ut){const t=Dt(e);An(t)&&(zn(t),Ln(t))}wn(Vt.afterSanitizeShadowDOM,t,null)},zn=function(t){const e=[{node:t,shadow:null}];for(;e.length>0;){const t=e.pop();if(t.shadow){Ln(t.shadow);continue}const n=t.node,o=Lt(n)===ut,r=xt(n);if(r)for(let t=r.length-1;t>=0;--t)e.push({node:r[t],shadow:null});if(o){const t=Ct?Ct(n):null;if("string"==typeof t&&"template"===tn(t)){const t=n.content;An(t)&&e.push({node:t,shadow:null})}}if(o){const t=Dt(n);An(t)&&e.push({node:null,shadow:t},{node:t,shadow:null})}}};return o.sanitize=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,a=null,l=null;if(Ye=!t,Ye&&(t="\x3c!--\x3e"),"string"!=typeof t&&!En(t)&&"string"!=typeof(t=function(t){switch(typeof t){case"string":return t;case"number":return O(t);case"boolean":return N(t);case"bigint":return x?x(t):"0";case"symbol":return _?_(t):"Symbol()";case"undefined":default:return R(t);case"function":case"object":{if(null===t)return R(t);const e=t,n=U(e,"toString");if("function"==typeof n){const t=n(e);return"string"==typeof t?t:R(t)}return R(t)}}}(t)))throw C("dirty is not a string, aborting");if(!o.isSupported)return t;Ae?(ae=Ee,ce=we):rn(e),(Vt.uponSanitizeElement.length>0||Vt.uponSanitizeAttribute.length>0)&&(ae=P(ae)),Vt.uponSanitizeAttribute.length>0&&(ce=P(ce)),o.removed=[];const c=Ce&&"string"!=typeof t&&En(t);if(c){!function(t){if(!Se)return;const e=[t];for(;e.length>0;){const t=e.pop(),n=Lt(t);if(n===pt||n===mt&&k(lt,t.data)){try{vt(t)}catch(t){}continue}if(n===ut){const e=t,n=tn(zt(t));try{e.hasAttribute&&e.hasAttribute("patchsrc")&&e.removeAttribute("patchsrc"),e.hasAttribute&&e.hasAttribute("for")&&hn("for",n)&&e.removeAttribute("for")}catch(t){}}const o=xt(t);if(o)for(let t=o.length-1;t>=0;--t)e.push(o[t])}}(t);const e=zt(t);if("string"==typeof e){const n=tn(e);if(!ae[n]||fe[n])throw fn(t),C("root node is forbidden and cannot be sanitized in-place")}if(Tn(t))throw fn(t),C("root node is clobbered and cannot be sanitized in-place");try{zn(t)}catch(e){throw fn(t),e}}else if(En(t))n=yn("\x3c!----\x3e"),r=n.ownerDocument.importNode(t,!0),r.nodeType===ut&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r),zn(n);else{if(!Oe&&!be&&!Te&&-1===t.indexOf("<"))return Mt&&xe?Bt(t):t;if(n=yn(t),!n)return Oe?null:xe?Ut:""}n&&ve&&sn(n.firstChild);const s=c?t:n;try{const t=gn(s);for(;a=t.nextNode();)xn(a,s),In(a),An(a.content)&&Ln(a.content)}catch(e){throw c&&(fn(t),m(o.removed,t=>{t.element&&dn(t.element)})),e}if(c)return m(o.removed,t=>{t.element&&dn(t.element)}),be&&Sn(t),t;if(Oe){if(be&&Sn(n),Ne)for(l=$t.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(ce.shadowroot||ce.shadowrootmode)&&(l=Kt.call(i,l,!0)),l}let u=Te?n.outerHTML:n.innerHTML;return Te&&ae["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&k(rt,n.ownerDocument.doctype.name)&&(u="\n"+u),be&&(u=bn(u)),Mt&&xe?Bt(u):u},o.setConfig=function(){rn(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Ae=!0,Ee=ae,we=ce},o.clearConfig=function(){en=null,Ae=!1,Ee=null,we=null,Mt=Pt,Ut=""},o.isValidAttribute=function(t,e,n){en||rn({});const o=tn(t),r=tn(e);return _n(o,r,n)},o.addHook=function(t,e){"function"==typeof e&&D(Vt,t)&&y(Vt[t],e)},o.removeHook=function(t,e){if(D(Vt,t)){if(void 0!==e){const n=d(Vt[t],e);return-1===n?void 0:g(Vt[t],n,1)[0]}return h(Vt[t])}},o.removeHooks=function(t){D(Vt,t)&&(Vt[t]=[])},o.removeAllHooks=function(){Vt={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},o}();return Et}); +//# sourceMappingURL=purify.min.js.map