Add Confluence import, a Slack app per workspace, and GitHub, Linear and Figma link previews

Link previews: link cards for GitHub issues, pull requests and
repositories, Linear issues and Figma files are read through the
services' APIs and show a status pill (Open, Merged, In Progress…) and a
line of details. Public items need nothing; a workspace's tokens, set by
its admins under Workspace settings → Integrations and checked with each
service before being sealed, reach private ones and Linear.
GET /link-preview takes the workspace; the link card stores kind,
status, state and meta.

Slack: each workspace connects its own Slack app, made from a manifest
the settings page fills in. Docwell posts chosen page and comment events
to a channel (edits at most every 30 minutes per page), previews links
to Docwell pages posted in Slack, and answers /docwell with a search as
the member whose email matches the Slack user, shown only to them. Only
pages every member can open are posted or previewed. Requests from Slack
are signature-checked; the webhook dispatcher gained listeners so Slack
follows the same events.

Confluence: a space's HTML export imports with its page tree (from
index.html, else breadcrumbs), links between pages, pictures and
attachments. Panels become callouts, code macros code blocks with their
language, expand macros toggles, task lists to-dos.

New collection workspace_integrations (schema snapshot regenerated),
OpenAPI and generated Go, TypeScript and Dart types, strings in all five
languages, the user guide, and a rebuilt mobile editor bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-16 20:42:11 +01:00
1 parent 7fa5df53e5
commit f1963f1391
36 files changed
+5091 -103

No files matched your search

@@ -0,0 +1,46 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// Workspace integrations (ADR-18): one record per workspace.
//
// - github, linear, figma: tokens (sealed by docwell-server) that let link
// previews read private issues, pull requests and files.
// - slack_*: the workspace's own Slack app. slack_bot and slack_signing are
// sealed; slack_team is the Slack workspace the bot belongs to;
// slack_channel gets the slack_events Docwell posts; slack_unfurl previews
// Docwell links in Slack, slack_search answers /docwell.
migrate(
(app) => {
const workspaces = app.findCollectionByNameOrId("workspaces");
app.save(
new Collection({
type: "base",
name: "workspace_integrations",
fields: [
{ name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true },
{ name: "github", type: "text", max: 2000 },
{ name: "linear", type: "text", max: 2000 },
{ name: "figma", type: "text", max: 2000 },
{ name: "slack_bot", type: "text", max: 2000 },
{ name: "slack_signing", type: "text", max: 2000 },
{ name: "slack_team", type: "text", max: 40 },
{ name: "slack_team_name", type: "text", max: 200 },
{ name: "slack_channel", type: "text", max: 40 },
{ name: "slack_channel_name", type: "text", max: 200 },
{ name: "slack_events", type: "json", maxSize: 4000 },
{ name: "slack_unfurl", type: "bool" },
{ name: "slack_search", type: "bool" },
{ name: "slack_error", type: "text", max: 1000 },
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE UNIQUE INDEX idx_workspace_integrations_workspace ON workspace_integrations (workspace)"],
}),
);
},
(app) => {
app.delete(app.findCollectionByNameOrId("workspace_integrations"));
},
);
+38
View File
@@ -251,6 +251,12 @@ from before a cleanup can show missing files.
between the pages, and stores images and files as attachments. Each database becomes a page with a database block of
its rows, with guessed property types, and the row pages under it. Tables in pages come in as tables; callouts and
to-do lists are kept.
- **From Confluence:** in Confluence, choose **Space settings → Export space → HTML** (Confluence Cloud or Data
Center) and import the `.zip` as it is. Docwell rebuilds the space's page tree, keeps links between its pages, and
stores pictures and attachments as attachments; each page's attached files are listed at its end. Info, note, tip
and warning panels become callouts, code blocks keep their language, expand blocks become toggles, task lists
to-dos, and status labels bold capitals. Comments, page history and macros that only work inside Confluence (page
trees, Jira lists) are left out.
- **From Obsidian, or any folder of Markdown:** zip the vault folder and import the `.zip`. Folders become pages with
their notes inside (a note named like its folder, such as `Projects/Projects.md`, is that folder's page),
`[[wikilinks]]` and `![[embeds]]` are found by name anywhere in the vault, images and files become attachments, and
@@ -276,6 +282,38 @@ from before a cleanup can show missing files.
- **CSV:** any other `.csv` becomes a page with a database of its rows.
- **To Notion:** export the page as Word or Markdown, then import that file with **Import** in Notion's sidebar.
### GitHub, Linear and Figma links
A link card (**/bookmark**, or **/embed** with an address that cannot be embedded) to a GitHub issue, pull request or
repository, a Linear issue or a Figma file shows the item's status (Open, Merged, In Progress…) and a line of details:
the repository and number, author and comments; the Linear team, assignee and priority; the kind of Figma file and
when it changed. Public GitHub items and publicly shared Figma files work as they are. For private ones, and for
Linear (which has no public pages), a workspace admin adds a token in **Workspace settings → Integrations → Link
previews**: a GitHub fine-grained token with read access to issues, pull requests and metadata, a Linear personal API
key, or a Figma personal access token. Everyone in the workspace then gets those previews; tokens are stored
encrypted and never shown again. A card keeps what it showed when it was made.
### Slack
**Workspace settings → Integrations → Slack** (workspace admins) connects a Slack app of your own:
1. Copy the manifest shown there and, at api.slack.com/apps, choose **Create New App → From a manifest**. It already
has Docwell's request URLs, the `/docwell` command and the scopes Docwell needs. Install the app to your Slack
workspace.
2. Paste its **Bot User OAuth Token** (OAuth & Permissions) and **Signing Secret** (Basic Information), and the public
channel news should go to (`#docs`, or its id).
Then:
- **News in the channel:** Docwell posts when pages are created or someone comments, and, if you tick them, when pages
are edited (at most once every 30 minutes per page), moved, archived or restored, or comments resolved.
- **Link previews:** a link to a Docwell page posted in Slack shows its title, space and first lines.
- **/docwell search:** `/docwell onboarding` lists the pages that match, as the person who typed it: Docwell finds the
member with their Slack email and searches what they can open. Only they see the answer.
Only pages everyone in the workspace can open are posted or previewed: nothing from private spaces, journals or
restricted pages. **Send a test message** checks the channel; a post that fails shows its error there.
### Web clipper
The Docwell Web Clipper (in `Web-Clipper/` of the source; Chrome, Edge and Firefox) saves the page you are reading as
+35 -2
View File
@@ -61,6 +61,10 @@ export type AuditEntry = Schemas["AuditEntry"];
export type AuditPage = Schemas["AuditPage"];
export type Webhook = Schemas["Webhook"];
export type WebhookInput = Schemas["WebhookInput"];
export type WorkspaceIntegrations = Schemas["WorkspaceIntegrations"];
export type SlackIntegration = Schemas["SlackIntegration"];
export type SlackIntegrationInput = Schemas["SlackIntegrationInput"];
export type IntegrationService = "github" | "linear" | "figma";
export type WebhookEvent = Schemas["WebhookEvent"];
export type WebhookDelivery = Schemas["WebhookDelivery"];
export type OAuthProviderSettings = Schemas["OAuthProviderSettings"];
@@ -407,6 +411,31 @@ export function createClient(opts: ClientOptions) {
stream(`/api/v1/workspaces/${enc(workspace)}/ai/write`, input, signal),
},
/** GitHub, Linear and Figma tokens for link previews, and the Slack app (workspace admins). */
workspaceIntegrations: {
get: (workspace: string) =>
request<WorkspaceIntegrations>("GET", `/api/v1/workspaces/${encodeURIComponent(workspace)}/integrations`),
setToken: (workspace: string, service: IntegrationService, token: string) =>
request<WorkspaceIntegrations>(
"PUT",
`/api/v1/workspaces/${encodeURIComponent(workspace)}/integrations/tokens/${service}`,
{ token },
),
setSlack: (workspace: string, input: SlackIntegrationInput) =>
request<WorkspaceIntegrations>(
"PUT",
`/api/v1/workspaces/${encodeURIComponent(workspace)}/integrations/slack`,
input,
),
deleteSlack: (workspace: string) =>
request<WorkspaceIntegrations>(
"DELETE",
`/api/v1/workspaces/${encodeURIComponent(workspace)}/integrations/slack`,
),
testSlack: (workspace: string) =>
post<void>(`/api/v1/workspaces/${encodeURIComponent(workspace)}/integrations/slack/test`),
},
webhooks: {
list: (workspace: string) =>
request<Webhook[]>("GET", `/api/v1/workspaces/${encodeURIComponent(workspace)}/webhooks`),
@@ -757,8 +786,12 @@ export function createClient(opts: ClientOptions) {
unarchive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/unarchive`),
pin: (id: string) => request<Page>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
unpin: (id: string) => request<Page>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
/** A web page's title, description and picture, read by docwell-server. */
preview: (url: string) => request<LinkPreview>("GET", `/api/v1/link-preview${query({ url })}`),
/**
* A web page's title, description and picture, read by docwell-server.
* With a workspace, its GitHub, Linear and Figma tokens reach private items.
*/
preview: (url: string, workspace?: string) =>
request<LinkPreview>("GET", `/api/v1/link-preview${query({ url, workspace })}`),
setFavorite: (id: string, on: boolean) =>
request<void>(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`),
attachments: (id: string) => request<Attachment[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/attachments`),
+382 -1
View File
@@ -1001,7 +1001,7 @@ export interface paths {
};
/**
* A web page's title, description and picture, for link cards
* @description docwell-server fetches the page itself (public addresses only: private, loopback and link-local ones are refused, redirects included). A page that can't be read still gets a preview with its address and site name.
* @description docwell-server fetches the page itself (public addresses only: private, loopback and link-local ones are refused, redirects included). A page that can't be read still gets a preview with its address and site name. GitHub issues, pull requests and repositories, Linear issues and Figma files are read through their APIs and get a kind, status and details; with workspace set (a workspace the caller belongs to), that workspace's tokens reach private items.
*/
get: operations["previewLink"];
put?: never;
@@ -2772,6 +2772,131 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/integrations": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The workspace's integrations (workspace admin) */
get: operations["getWorkspaceIntegrations"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/integrations/tokens/{service}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
service: "github" | "linear" | "figma";
};
cookie?: never;
};
get?: never;
/**
* Store a token for link previews (workspace admin); an empty token removes it
* @description The token is checked with the service first (GitHub /user, Linear viewer, Figma /v1/me), then sealed. Link previews of members of the workspace use it to read private items.
*/
put: operations["setIntegrationToken"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/integrations/slack": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
/** Connect or change the workspace's Slack app (workspace admin); missing fields stay as they are */
put: operations["setSlackIntegration"];
post?: never;
/** Disconnect Slack (workspace admin) */
delete: operations["deleteSlackIntegration"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/integrations/slack/test": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
/** Post a hello to the Slack channel (workspace admin) */
post: operations["testSlackIntegration"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/slack/{workspace}/events": {
parameters: {
query?: never;
header?: never;
path: {
workspace: string;
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Slack's Events API for one workspace's app: the URL check, and link_shared (Docwell link previews)
* @description Called by Slack, signed with the app's Signing Secret (X-Slack-Signature, at most five minutes old). Only pages every member of the workspace can open get a preview.
*/
post: operations["slackEvents"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/slack/{workspace}/commands": {
parameters: {
query?: never;
header?: never;
path: {
workspace: string;
};
cookie?: never;
};
get?: never;
put?: never;
/**
* The /docwell slash command: a search as the Docwell member with the Slack user's email
* @description Called by Slack, signed like the events. The answer is shown only to the person who asked.
*/
post: operations["slackCommands"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/webhooks": {
parameters: {
query?: never;
@@ -3693,6 +3818,63 @@ export interface components {
/** @description Address of the page's picture on its own site; empty when it has none */
image: string;
site: string;
/** @description For links read through a service's API (github.issue, github.pull, github.repo, linear.issue, figma.file) */
kind?: string;
/** @description The service's word for the item's state (Open, Merged, In Progress) */
status?: string;
/**
* @description The state for its colour
* @enum {string}
*/
state?: "open" | "started" | "draft" | "merged" | "done" | "closed" | "canceled";
/** @description A line of details (acme/app #12 · alice) */
meta?: string;
};
WorkspaceIntegrations: {
github: components["schemas"]["IntegrationToken"];
linear: components["schemas"]["IntegrationToken"];
figma: components["schemas"]["IntegrationToken"];
slack: components["schemas"]["SlackIntegration"];
};
IntegrationToken: {
/** @description A token is stored (it is never sent back) */
set: boolean;
};
SlackIntegration: {
/** @description A bot token is stored */
connected: boolean;
hasSigningSecret: boolean;
/** @description The Slack workspace id the bot belongs to */
team: string;
teamName: string;
/** @description The channel id posts go to; empty for none */
channel: string;
channelName: string;
/** @description Events posted to the channel */
events: string[];
/** @description Docwell links posted in Slack get a preview */
unfurl: boolean;
/** @description /docwell searches Docwell */
search: boolean;
/** @description The last post that failed; empty when the last one worked */
lastError: string;
/** @description Request URL for the Slack app's Event Subscriptions */
eventsUrl: string;
/** @description Request URL for the /docwell slash command */
commandsUrl: string;
/** @description A Slack app manifest (JSON) with those URLs and the scopes Docwell needs */
manifest: string;
};
SlackIntegrationInput: {
/** @description The app's Bot User OAuth Token (xoxb-…); checked with Slack */
botToken?: string;
/** @description The app's Signing Secret */
signingSecret?: string;
/** @description A public channel id or name (#news); empty for none */
channel?: string;
events?: ("page.created" | "page.updated" | "page.moved" | "page.archived" | "page.unarchived" | "page.restored" | "comment.created" | "comment.resolved")[];
unfurl?: boolean;
search?: boolean;
};
Session: {
token: string;
@@ -6461,6 +6643,7 @@ export interface operations {
parameters: {
query: {
url: string;
workspace?: string;
};
header?: never;
path?: never;
@@ -9561,6 +9744,204 @@ export interface operations {
404: components["responses"]["Error"];
};
};
getWorkspaceIntegrations: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["WorkspaceIntegrations"];
};
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
setIntegrationToken: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
service: "github" | "linear" | "figma";
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
token: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["WorkspaceIntegrations"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
setSlackIntegration: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["SlackIntegrationInput"];
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["WorkspaceIntegrations"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
deleteSlackIntegration: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["WorkspaceIntegrations"];
};
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
testSlackIntegration: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Posted */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
slackEvents: {
parameters: {
query?: never;
header?: never;
path: {
workspace: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
[key: string]: unknown;
};
};
};
responses: {
/** @description Taken (the URL check answers with its challenge) */
200: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description Bad or missing signature */
401: {
headers: {
[name: string]: unknown;
};
content?: never;
};
};
};
slackCommands: {
parameters: {
query?: never;
header?: never;
path: {
workspace: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/x-www-form-urlencoded": {
[key: string]: unknown;
};
};
};
responses: {
/** @description An ephemeral Slack message */
200: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description Bad or missing signature */
401: {
headers: {
[name: string]: unknown;
};
content?: never;
};
};
};
listWebhooks: {
parameters: {
query?: never;
+36 -36
View File
@@ -167,7 +167,7 @@ img.ProseMirror-separator {
`)}function gB(e,t,n){return hB([t.map(e=>e.name),...n.map(e=>t.map(t=>ZR(e,t)))])}function _B(e){let t=e.map(e=>e.trim()).filter(Boolean);if(!t.length)return`text`;if(t.every(e=>YR(e)!==null))return`number`;if(t.every(e=>/^\d{4}-\d{2}-\d{2}/.test(e)))return`date`;if(t.every(e=>/^(true|false|yes|no)$/i.test(e)))return`checkbox`;if(t.every(e=>/^https?:\/\/\S+$/.test(e)))return`link`;let n=new Set(t.map(e=>e.toLowerCase()));return t.length>=4&&n.size<=Math.max(2,t.length/3)&&t.every(e=>e.length<=40)?`select`:`text`}function vB(e,t,n){let r=e.trim();if(!r)return null;let i=e=>{let t=n.find(t=>t.name.toLowerCase()===e.toLowerCase());return t||(t={id:LR(),name:e,color:cz(n)},n.push(t)),t.id};switch(t.type){case`number`:return YR(r);case`progress`:{let e=YR(r.replace(`%`,``));return e===null?null:Math.max(0,Math.min(100,Math.round(e)))}case`checkbox`:return/^(true|yes|1|x|✓|done)$/i.test(r);case`date`:return qR(r)||null;case`select`:return i(r);case`multiSelect`:return[...new Set(r.split(/[,;]/).map(e=>e.trim()).filter(Boolean).map(i))];case`member`:case`attachment`:case`createdBy`:case`createdTime`:return null;default:return r}}function yB(e,t=`,`){let n=pB(e,t).filter(e=>e.some(e=>e.trim())),r=n[0]??[],i=n.slice(1),a=r.map((e,t)=>({id:LR(),name:e.trim()||`${t+1}`,type:t===0?`title`:_B(i.map(e=>e[t]??``))}));for(let e of a)e.type===`select`&&(e.options=[]);return{columns:a,rows:i.map(e=>{let t={};return a.forEach((n,r)=>{let i=vB(e[r]??``,n,n.options??[]);i!==null&&(!Array.isArray(i)||i.length)&&(t[n.id]=i)}),t})}}function bB(e,t){let n=[];return{index:e.map(e=>{let r=t.find(t=>t.name.trim().toLowerCase()===e.trim().toLowerCase());return!r&&e.trim()&&n.push(e.trim()),r??null}),missing:n}}function xB(e,t,n,r){let i=I(`select`,{class:`dw-db-select`,"aria-label":n});for(let n of t){let t=I(`option`,{value:n.value},n.label);n.value===e&&(t.selected=!0),i.append(t)}return i.addEventListener(`change`,()=>r(i.value)),i.addEventListener(`keydown`,e=>e.stopPropagation()),i}var SB=e=>e.map(e=>({value:e.id,label:e.name||`…`}));function CB(e,t,n,r){let i=e.labels;if(!$R(n.op))return null;if(t.type===`select`||t.type===`multiSelect`)return xB(typeof n.value==`string`?n.value:``,[{value:``,label:`—`},...(t.options??[]).map(e=>({value:e.id,label:e.name}))],i.value,r);let a=t.type===`date`||t.type===`createdTime`?`date`:t.type===`number`||t.type===`progress`?`number`:`text`,o=I(`input`,{class:`dw-db-input dw-db-input--small`,type:a,"aria-label":i.value,placeholder:i.value});return o.value=n.value===void 0||n.value===null?``:String(n.value),o.addEventListener(`keydown`,e=>e.stopPropagation()),o.addEventListener(`change`,()=>r(a===`number`?o.value===``?null:Number(o.value):o.value)),o}function wB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.filters),s=()=>r?.updateView(n.id,{filters:o}),c=()=>{t.replaceChildren(),o.length>1&&t.append(xB(n.filterMode,[{value:`and`,label:i.matchAll},{value:`or`,label:i.matchAny}],i.filter,e=>{n.filterMode=e,r?.updateView(n.id,{filterMode:n.filterMode})})),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noFilters)),o.forEach((n,r)=>{let l=a.find(e=>e.id===n.column);if(!l)return;let u=QR(l.type),d=I(`div`,{class:`dw-db-pop__line`},xB(n.column,SB(a),i.filter,e=>{let t=a.find(t=>t.id===e);o[r]={column:e,op:QR(t.type)[0]},s(),c()}),xB(n.op,u.map(e=>({value:e,label:OR(i,e)})),i.filter,e=>{o[r]={...n,op:e},$R(e)||delete o[r].value,s(),c()}),CB(e,l,n,e=>{o[r]={...o[r],value:e},s()}),kB(i.remove,()=>{o.splice(r,1),s(),c()}));t.append(d)}),r&&t.append(AB(i.addFilter,()=>{let e=a.find(e=>e.type!==`title`)??a[0];o.push({column:e.id,op:QR(e.type)[0]}),s(),c()}))};c()}function TB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.sorts),s=()=>r?.updateView(n.id,{sorts:o}),c=()=>{t.replaceChildren(),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noSorts)),o.forEach((e,n)=>{t.append(I(`div`,{class:`dw-db-pop__line`},xB(e.column,SB(a),i.sort,t=>{o[n]={...e,column:t},s()}),xB(e.desc?`desc`:`asc`,[{value:`asc`,label:i.ascending},{value:`desc`,label:i.descending}],i.sort,t=>{o[n]={...e,desc:t===`desc`},s()}),kB(i.remove,()=>{o.splice(n,1),s(),c()})))}),r&&t.append(AB(i.addSort,()=>{let e=new Set(o.map(e=>e.column)),t=a.find(t=>!e.has(t.id))??a[0];o.push({column:t.id,desc:!1}),s(),c()}))};c()}function EB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>zR.includes(e.type)),o=a.map(e=>({value:e.id,label:e.name||ER(i,e.type)}));n.type!==`kanban`&&o.unshift({value:``,label:i.noGrouping}),t.append(I(`label`,{class:`dw-db-pop__label`},i.groupBy),a.length||n.type!==`kanban`?xB(n.groupBy??``,o,i.groupBy,e=>r?.updateView(n.id,{groupBy:e||null})):I(`p`,{class:`dw-db-pop__empty`},i.noGroupColumn))}function DB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>e.type===`date`||e.type===`createdTime`);t.append(I(`label`,{class:`dw-db-pop__label`},i.dateColumn),a.length?xB(n.dateColumn??``,[{value:``,label:`—`},...a.map(e=>({value:e.id,label:e.name||ER(i,e.tyLine truncated
`)},onCreate(){let{doc:e,readOnlyDoc:t,undoScope:n}=this.options;e&&!t&&n&&(IS.getState(this.editor.state)?.undoManager)?.addToScope(Zz(e))},addCommands(){let e=e=>{let t=LR(),{doc:n,readOnlyDoc:r}=this.options;return!n||r?{id:t,data:e}:(fB(n,t,e,(e,t)=>ZB(this.editor,e,t)),{id:t,data:null})};return{insertDatabase:t=>({commands:n})=>n.insertContent([{type:this.name,attrs:e(t??sB(KB(this.options.labels)))},{type:`paragraph`}]),groupAsDatabase:()=>({state:t,dispatch:n,commands:r})=>{let i=eV(t.selection.$from,t.selection.$to);if(!i)return!1;if(!n)return!0;let a=GB(this.options.labels),o={id:LR(),name:a.typeTitle,type:`title`},s=[o],c=i.checks?{id:LR(),name:a.done,type:`checkbox`}:null;c&&s.push(c);let l=Date.now(),u={title:``,columns:s,rows:i.items.map((e,t)=>({id:LR(),cells:{[o.id]:e.text,...c&&e.checked?{[c.id]:!0}:{}},createdAt:l+t,createdBy:this.options.me?.()??null,body:e.rest.length?e.rest:void 0})),views:[RR(`table`,a.viewTable,s)]},d=this.type.create(e(u));return r.command(({tr:e})=>(e.replaceWith(i.from,i.to,d),e.setSelection(E.create(e.doc,i.from)),!0))}}},addKeyboardShortcuts(){return{"Mod-g":()=>this.editor.commands.groupAsDatabase()}},addProseMirrorPlugins(){let{doc:e,readOnlyDoc:t}=this.options,n=e&&!t?e:null,r=this.editor;return[new D({key:new Un(`databaseClipboard`),props:{transformCopied:t=>!e||!YB(t.content)?t:new p(JB(t.content,t=>{let n=Zz(e).get(String(t.attrs.id));return n instanceof Bb?t.type.create({...t.attrs,data:dB(n,qB)}):t}),t.openStart,t.openEnd),transformPasted:e=>YB(e.content)?new p(JB(e.content,e=>{let t=LR();if(!n)return e.type.create({...e.attrs,id:t});let i=e.attrs.data?BR(e.attrs.data):null,a=Zz(n).get(String(e.attrs.id)),o=i??(a instanceof Bb?dB(a,qB):sB(KB(this.options.labels)));return fB(n,t,$B(o),(e,t)=>ZB(r,e,t)),e.type.create({id:t,data:null})}),e.openStart,e.openEnd):e},appendTransaction:(e,t,i)=>{if(!n||!e.some(e=>e.docChanged&&!e.getMeta(FS))||!e.some(e=>e.steps.some(e=>YB(e.slice?.content??s.empty))))return null;let a=new Set,o=[];if(i.doc.descendants((e,t)=>{if(e.type.name!==`database`)return;let n=String(e.attrs.id);return n&&a.has(n)&&o.push({pos:t,node:e}),a.add(n),!1}),!o.length)return null;let c=i.tr;for(let{pos:e,node:t}of o){let i=Zz(n).get(String(t.attrs.id)),a=LR();i instanceof Bb&&fB(n,a,$B(dB(i,qB)),(e,t)=>ZB(r,e,t)),c.setNodeMarkup(e,void 0,{...t.attrs,id:a,data:null})}return c}})]},addNodeView(){let e=this.options;return({node:t,editor:n,getPos:r})=>{let i=t,a=e.labels??NR,o=e.doc,s=()=>n.isEditable&&!!o&&!e.readOnlyDoc,c=null,l=null,u=null,d=null,f=I(`div`,{class:`dw-db-node`}),p=()=>String(i.attrs.id),m=()=>{let e=o?Zz(o).get(p()):void 0;return e instanceof Bb?e:null},h=()=>{let t=m();return t?oB(t):i.attrs.data?BR(i.attrs.data):sB(KB(e.labels))},g=e=>{let t=o?Zz(o).get(e):void 0;if(t instanceof Bb)return oB(t);let r=null;return n.state.doc.descendants(t=>!r&&(t.type.name===`database`&&t.attrs.id===e&&t.attrs.data&&(r=BR(t.attrs.data)),!0)),r},_=new Map,v=t=>{let n=e.linkedPages;if(!n)return null;let r=_.get(t);if(!r){let e=n.open(t),i=e.onChange(re);e.doc.on(`update`,re),r={provider:e,stop:()=>{i(),e.doc.off(`update`,re),e.destroy()}},_.set(t,r)}return r.provider},y=t=>!t||t===e.linkedPages?.self,b=new Set,x=e=>{if(y(e.page))return b.add(e.database),e.database===p()?h():g(e.database);let t=v(e.page);if(!t?.synced)return null;let n=Zz(t.doc).get(e.database);return n instanceof Bb?oB(n):null},S=(e,t,n)=>{let r=[],i=e=>{for(let a of e.toArray())if(a instanceof lx){if(a.nodeName===`database`){let e=String(a.getAttribute(`id`)??``);e&&r.push({page:t,database:e,title:n(e)?.title??``})}else i(a)}};return i(e),r},C=t=>{if(!s()||!o||!y(t.page))return null;if(t.database===p())return c;let n=Zz(o).get(t.database);return n instanceof Bb?new lB(o,n,()=>e.me?.()??null):null},ee={local:()=>{let e=[];return n.state.doc.descendants(t=>(t.type.name===`database`&&t.attrs.id&&t.attrs.id!==p()&&e.push({page:``,database:String(t.attrs.id),title:g(String(t.attrs.id))?.title??``}),!0)),e},searchPages:e.pages?t=>e.pages.search(t).then(e=>e.filter(e=>!y(e.id)).map(e=>({id:e.id,title:e.title}))):void 0,databasesOn:e.linkedPages?e=>new Promise(t=>{let n=v(e),r=()=>{t(S(n.doc.getXmlFragment(`default`),e,e=>{let t=Zz(n.doc).get(e);return t instanceof Bb?oB(t):null}))};if(n.synced)return r();let i=setTimeout(()=>{a(),t([])},8e3),a=n.onChange(()=>{n.synced&&(clearTimeout(i),a(),r())})}):void 0,read:x,pointsHere:(t,n)=>n.database===p()?y(t.page)?y(n.page):!!e.linkedPages?.self&&n.page===e.linkedPages.self:!1,writable:e=>!!C(e),link:(e,t,n,r)=>{let i=C(e),a=e.back;if(!i||!a)return!1;let o=i.snapshot().rows.find(e=>e.id===n);if(!o)return!1;let s=gz(o.cells[a]).filter(e=>e!==t);return r&&s.push(t),i.setCell(n,a,s.length?s:null),!0},addBack:(e,t,n)=>{let r=C(e);return r?(r.tx(()=>{let e=r.addColumn(`relation`,n);r.setRelation(e,{page:``,database:p(),back:t})}),!0):!1},openRecord:(t,r)=>{y(t.page)?UB(n,t.database,r):e.onNavigate?.(`/p/${encodeURIComponent(t.page)}${BB(t.database,r)}Line truncated
`);return/\s/.test(n)}):!1}function xV(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function SV(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:xV(e)}function CV({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!bV(r)}function wV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function TV({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function EV({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function DV({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function OV({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[Mj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(Pj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function kV(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function AV({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&kV(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=jj(c,o,()=>{Fj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function jV({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=DV({editor:e,items:n}),v=OV({placLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=jj(e.anchor,t,()=>{Fj(e.anchor,t,{placement:`bottom-start`,middleware:[Mj(6),Pj(),Nj({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),eH===d&&(eH=null),n||e.onCancel?.())}let d=()=>u();return eH=d,n.focus(),e.multiline||n.select(),d}var nH=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function rH(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of nH){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function iH(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var aH=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function oH(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;tH({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(iH(t)),onCancel:()=>e(``)})})}async function sH(e,t,n,r){let i=await oH(e,t,t.blocks.embedUrl);i&&(rH(i)?e.chain().focus().insertEmbed(i).run():await lH(e,i,n,r))}async function cH(e,t,n,r){let i=await oH(e,t,t.blocks.linkUrl);i&&await lH(e,i,n,r)}async function lH(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var uH=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=iH(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=iH(e),i=rH(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${aH(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=jj(e.anchor,t,()=>{Fj(e.anchor,t,{placement:`bottom-start`,middleware:[Mj(6),Pj(),Nj({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),eH===d&&(eH=null),n||e.onCancel?.())}let d=()=>u();return eH=d,n.focus(),e.multiline||n.select(),d}var nH={open:`green`,started:`yellow`,draft:`gray`,merged:`purple`,done:`blue`,closed:`red`,canceled:`gray`},rH=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function iH(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of rH){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function aH(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var oH=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function sH(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;tH({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(aH(t)),onCancel:()=>e(``)})})}async function cH(e,t,n,r){let i=await sH(e,t,t.blocks.embedUrl);i&&(iH(i)?e.chain().focus().insertEmbed(i).run():await uH(e,i,n,r))}async function lH(e,t,n,r){let i=await sH(e,t,t.blocks.linkUrl);i&&await uH(e,i,n,r)}async function uH(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var dH=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=aH(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=aH(e),i=iH(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${oH(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.creatLine truncated
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
@@ -178,7 +178,7 @@ c5.3,-9.3,12,-14,20,-14
H400000v`+(40+e)+`H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},uU=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},dU=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120
c340,-704.7,510.7,-1060.3,512,-1067
l`+e/2.084+` -`+e+`
@@ -188,7 +188,7 @@ s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,
c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1
s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26
c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},dU=function(e,t){return`M983 `+(10+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},fU=function(e,t){return`M983 `+(10+e+t)+`
l`+e/3.13+` -`+e+`
c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+`
H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7
@@ -197,7 +197,7 @@ c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30
c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722
c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5
c53.7,-170.3,84.5,-266.8,92.5,-289.5z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},fU=function(e,t){return`M424,`+(2398+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},pU=function(e,t){return`M424,`+(2398+e+t)+`
c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514
c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20
s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121
@@ -207,18 +207,18 @@ v`+(40+e)+`H1014.6
s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185
c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+` `+t+`
h400000v`+(40+e)+`h-400000z`},pU=function(e,t){return`M473,`+(2713+e+t)+`
h400000v`+(40+e)+`h-400000z`},mU=function(e,t){return`M473,`+(2713+e+t)+`
c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+` -`+e+`
c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7
s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200
c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26
s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},mU=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},hU=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},hU=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},gU=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
H742v`+r+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1
h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170
c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},gU=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=lU(t,cU);break;case`sqrtSize1`:r=uU(t,cU);break;case`sqrtSize2`:r=dU(t,cU);break;case`sqrtSize3`:r=fU(t,cU);break;case`sqrtSize4`:r=pU(t,cU);break;case`sqrtTall`:r=hU(t,cU,n)}return r},_U=function(e,t){switch(e){case`⎜`:return sU(`M291 0 H417 V`+t+` H291z`);case`∣`:return sU(`M145 0 H188 V`+t+` H145z`);case`∥`:return sU(`M145 0 H188 V`+t+` H145z`)+sU(`M367 0 H410 V`+t+` H367z`);case`⎟`:return sU(`M457 0 H583 V`+t+` H457z`);case`⎢`:return sU(`M319 0 H403 V`+t+` H319z`);case`⎥`:return sU(`M263 0 H347 V`+t+` H263z`);case`⎪`:return sU(`M384 0 H504 V`+t+` H384z`);case`⏐`:return sU(`M312 0 H355 V`+t+` H312z`);case`‖`:return sU(`M257 0 H300 V`+t+` H257z`)+sU(`M478 0 H521 V`+t+` H478z`);default:return``}},vU={doubleleftarrow:`M262 157
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},_U=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=uU(t,lU);break;case`sqrtSize1`:r=dU(t,lU);break;case`sqrtSize2`:r=fU(t,lU);break;case`sqrtSize3`:r=pU(t,lU);break;case`sqrtSize4`:r=mU(t,lU);break;case`sqrtTall`:r=gU(t,lU,n)}return r},vU=function(e,t){switch(e){case`⎜`:return cU(`M291 0 H417 V`+t+` H291z`);case`∣`:return cU(`M145 0 H188 V`+t+` H145z`);case`∥`:return cU(`M145 0 H188 V`+t+` H145z`)+cU(`M367 0 H410 V`+t+` H367z`);case`⎟`:return cU(`M457 0 H583 V`+t+` H457z`);case`⎢`:return cU(`M319 0 H403 V`+t+` H319z`);case`⎥`:return cU(`M263 0 H347 V`+t+` H263z`);case`⎪`:return cU(`M384 0 H504 V`+t+` H384z`);case`⏐`:return cU(`M312 0 H355 V`+t+` H312z`);case`‖`:return cU(`M257 0 H300 V`+t+` H257z`)+cU(`M478 0 H521 V`+t+` H478z`);default:return``}},yU={doubleleftarrow:`M262 157
l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3
0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28
14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5
@@ -264,10 +264,10 @@ m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9
v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5
-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3
-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:sU(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:sU(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:sU(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:sU(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:cU(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:cU(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:cU(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:cU(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8
c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:sU(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:cU(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14
-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7
311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11
@@ -316,7 +316,7 @@ m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown
m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3
15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0
-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:sU(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:sU(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:sU(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:cU(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:cU(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:cU(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32
-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142
-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40
@@ -389,7 +389,7 @@ M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`
c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,
-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6
c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},yU=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},bU=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
H403z M403 1759 V0 H319 V1759 v`+t+` v1759 v84 h84z`;case`rbrack`:return`M347 1759 V0 H0 V84 H263 V1759 v`+t+` v1759 H0 v84 H347z
M347 1759 V0 H263 V1759 v`+t+` v1759 h84z`;case`vert`:return`M145 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15
c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15
@@ -417,20 +417,20 @@ c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6
c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17
c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558
l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function bU(e){return`toText`in e}var xU=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(bU(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},SU={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},CU={ex:!0,em:!0,mu:!0},wU=function(e){return typeof e!=`string`&&(e=e.unit),e in SU||e in CU||e===`ex`},TU=function(e,t){var n;if(e.unit in SU)n=SU[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},EU=function(e){return e.filter(e=>e).join(` `)},DU=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=OH(n)+`:`+r+`;`)}return t},OU=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},kU=function(e){var t=document.createElement(e);t.className=EU(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},AU=/[\s"'>/=\x00-\x1f]/,jU=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+jH(EU(this.classes))+`"`);var n=DU(this.style);n&&(t+=` style="`+jH(n)+`"`);for(var r of Object.keys(this.attributes)){if(AU.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+jH(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},MU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,OU.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return kU.call(this,`span`)}toMarkup(){return jU.call(this,`span`)}},NU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,OU.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return kU.call(this,`a`)}toMarkup(){return jU.call(this,`a`)}},PU=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+jH(this.src)+`"`+(` alt="`+jH(this.alt)+`"`),t=DU(this.style);return t&&(e+=` style="`+jH(t)+`"`),e+=`'/>`,e}},FU={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},IU=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=iU(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=FU[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=EU(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=jH(EU(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new LU([new RU(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=WW([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=z(o),a>0&&(i.style.minWidth=z(a)),i},$G=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new zU({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new zU({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=WW([],[new LU(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},eK=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],tK=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],nK=new Set(eK),rK=new Set(tK);function iK(e){return nK.has(e)}function aK(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function oK(e){var t=sK(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function sK(e){return e.type===`atom`||rK.has(e.type)?e:null}function cK(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new L(t,e);return r}var lK=e=>{if(e instanceof IU)return e;if(HU(e)&&e.children.length===1)return lK(e.children[0])},uK=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=aK(e.base,`accent`),n=r.base,e.base=n,i=VU(CG(e,t)),e.base=r):(r=aK(e,`accent`),n=r.base);var a=CG(n,t.havingCrampedStyle()),o=r.isShifty&&PH(n),s=0;o&&(s=lK(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=QG(r,t),u=XW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=tG(`vec`,t),f=eG.vec[1]):(d=BW({type:`textord`,mode:r.mode,text:r.label},t),d=BU(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=XW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},dK=(e,t)=>{var n=e.isStretchy?YG(e.label):new Q(`mo`,[jG(e.label,e.mode)]),r=new Q(`mover`,[RG(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},fK=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=dG(t[0]),r=!fK.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:uK,mathmlBuilder:dK}),Z({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),Z({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=CG(e.base,t),r=QG(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[XW({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=YG(e.label),r=new Q(`munder`,[RG(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var pK=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
]`,iJ=`\\\\[a-zA-Z@]+`,aJ=`\\\\[^\ud800-\udfff]`,oJ=`(`+iJ+`)`+rJ+`*`,sJ=`\\\\(
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function xU(e){return`toText`in e}var SU=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(xU(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},CU={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},wU={ex:!0,em:!0,mu:!0},TU=function(e){return typeof e!=`string`&&(e=e.unit),e in CU||e in wU||e===`ex`},EU=function(e,t){var n;if(e.unit in CU)n=CU[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},DU=function(e){return e.filter(e=>e).join(` `)},OU=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=kH(n)+`:`+r+`;`)}return t},kU=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},AU=function(e){var t=document.createElement(e);t.className=DU(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},jU=/[\s"'>/=\x00-\x1f]/,MU=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+MH(DU(this.classes))+`"`);var n=OU(this.style);n&&(t+=` style="`+MH(n)+`"`);for(var r of Object.keys(this.attributes)){if(jU.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+MH(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},NU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,kU.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return AU.call(this,`span`)}toMarkup(){return MU.call(this,`span`)}},PU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,kU.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return AU.call(this,`a`)}toMarkup(){return MU.call(this,`a`)}},FU=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+MH(this.src)+`"`+(` alt="`+MH(this.alt)+`"`),t=OU(this.style);return t&&(e+=` style="`+MH(t)+`"`),e+=`'/>`,e}},IU={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},LU=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=aU(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=IU[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=DU(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=MH(DU(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new RU([new zU(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=GW([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=z(o),a>0&&(i.style.minWidth=z(a)),i},eK=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new BU({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new BU({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=GW([],[new RU(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},tK=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],nK=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],rK=new Set(tK),iK=new Set(nK);function aK(e){return rK.has(e)}function oK(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function sK(e){var t=cK(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function cK(e){return e.type===`atom`||iK.has(e.type)?e:null}function lK(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new L(t,e);return r}var uK=e=>{if(e instanceof LU)return e;if(UU(e)&&e.children.length===1)return uK(e.children[0])},dK=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=oK(e.base,`accent`),n=r.base,e.base=n,i=HU(wG(e,t)),e.base=r):(r=oK(e,`accent`),n=r.base);var a=wG(n,t.havingCrampedStyle()),o=r.isShifty&&FH(n),s=0;o&&(s=uK(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=$G(r,t),u=ZW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=nG(`vec`,t),f=tG.vec[1]):(d=VW({type:`textord`,mode:r.mode,text:r.label},t),d=VU(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=ZW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},fK=(e,t)=>{var n=e.isStretchy?XG(e.label):new Q(`mo`,[MG(e.label,e.mode)]),r=new Q(`mover`,[zG(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},pK=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=fG(t[0]),r=!pK.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:dK,mathmlBuilder:fK}),Z({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),Z({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=wG(e.base,t),r=$G(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[ZW({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=XG(e.label),r=new Q(`munder`,[zG(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var mK=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
]`,aJ=`\\\\[a-zA-Z@]+`,oJ=`\\\\[^\ud800-\udfff]`,sJ=`(`+aJ+`)`+iJ+`*`,cJ=`\\\\(
|[ \r ]+
?)[ \r ]*`,cJ=`[̀-ͯ]`,lJ=RegExp(cJ+`+$`),uJ=`(`+rJ+`+)|`+(sJ+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(cJ+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(cJ+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+oJ)+(`|`+aJ+`)`),dJ=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(uJ,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new dq(`EOF`,new uq(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new dq(e[t],new uq(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(`
`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new dq(r,new uq(this,t,this.tokenRegex.lastIndex))}},fJ=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new L(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},pJ=lq;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var mJ={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new L("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=mJ[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=mJ[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var hJ=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new L(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new L(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new L(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new L(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>hJ(e,!1,!0,!1)),$(`\\renewcommand`,e=>hJ(e,!0,!1,!1)),$(`\\providecommand`,e=>hJ(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),nJ[n],XU.math[n],XU.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(EJ,t[0])&&!XU[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=EJ[t[0]]+t.slice(1));var i=lJ.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(XU[this.mode][t]){this.settings.strict&&this.mode===`math`&&vW.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=XU[this.mode][t].group,s=uq.range(e);a=iK(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&(oU(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:uq.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!TJ[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=TJ[l][this.mode]||TJ[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:uq.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};DJ.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var OJ=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new DJ(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new dq(`\\df@tag`)])}]}return r},kJ=function(e,t,n){t.textContent=``;var r=NJ(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),kJ=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var AJ=function(e,t){return NJ(e,t).toMarkup()},jJ=function(e,t){return OJ(e,new BH(t))},MJ=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new IU(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},NJ=function(e,t){var n=new BH(t);try{return KG(OJ(e,n),e,n)}catch(t){return MJ(t,e,n)}},PJ={version:`0.18.10`,render:kJ,renderToString:AJ,ParseError:L,SETTINGS_SCHEMA:IH,__parse:jJ,__renderToDomTree:NJ,__renderToHTMLTree:function(e,t){var n=new BH(t);try{return qG(OJ(e,n),e,n)}catch(t){return MJ(t,e,n)}},__setFontMetrics:KU,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:MU,Anchor:NU,SymbolNode:IU,SvgNode:LU,PathNode:RU,LineNode:zU}},FJ=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{PJ.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),IJ=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},LJ=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:IJ,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{PJ.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),RJ=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[FJ.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),LJ.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function zJ(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;tH({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return RJ.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function BJ({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new Un,command:({editor:e,range:t,props:i})=>{var a,o;let sLine truncated
Idea --> Draft --> Review --> Published`,KJ=null;function qJ(e){return KJ??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),KJ}var JJ=0;async function YJ(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await qJ(r)).render(`dw-mermaid-${++JJ}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var XJ=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=GJ)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return YJ(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;tH({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void YJ(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),YJ(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void YJ(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),YJ(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function ZJ(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function QJ(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`database`,`database`,[`kanban`,`board`,`calendar`,`records`,`tracker`,`notion`],(e,t)=>e.chain().focus().deleteRange(t).insertDatabase().run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().Line truncated
]`).replace(`lheading`,PY).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},YY=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,XY=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ZY=/^( {2,}|\\)\n(?!\s*$)/,QY=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,$Y=/[\p{P}\p{S}]/u,eX=/[\s\p{P}\p{S}]/u,tX=/[^\s\p{P}\p{S}]/u,nX=wY(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,eX).getRegex(),rX=/(?!~)[\p{P}\p{S}]/u,iX=/(?!~)[\s\p{P}\p{S}]/u,aX=/(?:[^\s\p{P}\p{S}]|~)/u,oX=wY(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,TY?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),sX=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,cX=wY(sX,`u`).replace(/punct/g,$Y).getRegex(),lX=wY(sX,`u`).replace(/punct/g,rX).getRegex(),uX=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,dX=wY(uX,`gu`).replace(/notPunctSpace/g,tX).replace(/punctSpace/g,eX).replace(/punct/g,$Y).getRegex(),fX=wY(uX,`gu`).replace(/notPunctSpace/g,aX).replace(/punctSpace/g,iX).replace(/punct/g,rX).getRegex(),pX=wY(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,tX).replace(/punctSpace/g,eX).replace(/punct/g,$Y).getRegex(),mX=wY(/\\(punct)/,`gu`).replace(/punct/g,$Y).getRegex(),hX=wY(/^<(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(),gX=wY(HY).replace(`(?:-->|$)`,`-->`).getRegex(),_X=wY(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,gX).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),vX=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,yX=wY(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace(`label`,vX).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),bX=wY(/^!?\[(label)\]\[(ref)\]/).replace(`label`,vX).replace(`ref`,RY).getRegex(),xX=wY(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,RY).getRegex(),SX=wY(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,bX).replace(`nolink`,xX).getRegex(),CX=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,wX={_backpedal:CY,anyPunctuation:mX,autolink:hX,blockSkip:oX,br:ZY,code:XY,del:CY,emStrongLDelim:cX,emStrongRDelimAst:dX,emStrongRDelimUnd:pX,escape:YY,link:yX,nolink:xX,punctuation:nX,reflink:bX,reflinkSearch:SX,tag:_X,text:QY,url:CY},TX={...wX,link:wY(/^!?\[(label)\]\((.*?)\)/).replace(`label`,vX).getRegex(),reflink:wY(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,vX).getRegex()},EX={...wX,emStrongRDelimAst:fX,emStrongLDelim:lX,url:wY(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,CX).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:wY(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,CX).getRegex()},DX={...EX,br:wY(ZY).replace(`{2,}`,`*`).getRegex(),text:wY(EX.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},OX={normal:GY,gfm:qY,pedantic:JY},kX={normal:wX,gfm:EX,breaks:DX,pedantic:TX},AX={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},jX=e=>AX[e];function MX(e,t){if(t){if(EY.escapeTest.test(e))return e.replace(EY.escapeReplace,jX)}else if(EY.escapeTestNoEncode.test(e))return e.replace(EY.escapeReplaceNoEncode,jX);return e}function NX(e){try{e=encodeURI(e).replace(EY.percentDecode,`%`)}catch{return null}return e}function PX(e,t){let n=e.replace(EY.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(EY.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(EY.slLine truncated
?)[ \r ]*`,lJ=`[̀-ͯ]`,uJ=RegExp(lJ+`+$`),dJ=`(`+iJ+`+)|`+(cJ+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(lJ+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(lJ+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+sJ)+(`|`+oJ+`)`),fJ=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(dJ,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new fq(`EOF`,new dq(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new fq(e[t],new dq(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(`
`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new fq(r,new dq(this,t,this.tokenRegex.lastIndex))}},pJ=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new L(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},mJ=uq;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var hJ={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new L("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=hJ[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=hJ[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var gJ=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new L(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new L(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new L(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new L(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>gJ(e,!1,!0,!1)),$(`\\renewcommand`,e=>gJ(e,!0,!1,!1)),$(`\\providecommand`,e=>gJ(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),rJ[n],ZU.math[n],ZU.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(DJ,t[0])&&!ZU[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=DJ[t[0]]+t.slice(1));var i=uJ.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(ZU[this.mode][t]){this.settings.strict&&this.mode===`math`&&yW.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=ZU[this.mode][t].group,s=dq.range(e);a=aK(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&(sU(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:dq.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!EJ[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=EJ[l][this.mode]||EJ[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:dq.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};OJ.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var kJ=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new OJ(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new fq(`\\df@tag`)])}]}return r},AJ=function(e,t,n){t.textContent=``;var r=PJ(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),AJ=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var jJ=function(e,t){return PJ(e,t).toMarkup()},MJ=function(e,t){return kJ(e,new VH(t))},NJ=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new LU(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},PJ=function(e,t){var n=new VH(t);try{return qG(kJ(e,n),e,n)}catch(t){return NJ(t,e,n)}},FJ={version:`0.18.10`,render:AJ,renderToString:jJ,ParseError:L,SETTINGS_SCHEMA:LH,__parse:MJ,__renderToDomTree:PJ,__renderToHTMLTree:function(e,t){var n=new VH(t);try{return JG(kJ(e,n),e,n)}catch(t){return NJ(t,e,n)}},__setFontMetrics:qU,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:NU,Anchor:PU,SymbolNode:LU,SvgNode:RU,PathNode:zU,LineNode:BU}},IJ=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{FJ.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),LJ=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},RJ=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:LJ,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{FJ.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),zJ=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[IJ.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),RJ.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function BJ(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;tH({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return zJ.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function VJ({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new Un,command:({editor:e,range:t,props:i})=>{var a,o;let sLine truncated
Idea --> Draft --> Review --> Published`,qJ=null;function JJ(e){return qJ??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),qJ}var YJ=0;async function XJ(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await JJ(r)).render(`dw-mermaid-${++YJ}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var ZJ=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=KJ)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return XJ(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;tH({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void XJ(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),XJ(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void XJ(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),XJ(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function QJ(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function $J(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`database`,`database`,[`kanban`,`board`,`calendar`,`records`,`tracker`,`notion`],(e,t)=>e.chain().focus().deleteRange(t).insertDatabase().run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().Line truncated
]`).replace(`lheading`,FY).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},XY=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ZY=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,QY=/^( {2,}|\\)\n(?!\s*$)/,$Y=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,eX=/[\p{P}\p{S}]/u,tX=/[\s\p{P}\p{S}]/u,nX=/[^\s\p{P}\p{S}]/u,rX=TY(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,tX).getRegex(),iX=/(?!~)[\p{P}\p{S}]/u,aX=/(?!~)[\s\p{P}\p{S}]/u,oX=/(?:[^\s\p{P}\p{S}]|~)/u,sX=TY(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,EY?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),cX=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,lX=TY(cX,`u`).replace(/punct/g,eX).getRegex(),uX=TY(cX,`u`).replace(/punct/g,iX).getRegex(),dX=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,fX=TY(dX,`gu`).replace(/notPunctSpace/g,nX).replace(/punctSpace/g,tX).replace(/punct/g,eX).getRegex(),pX=TY(dX,`gu`).replace(/notPunctSpace/g,oX).replace(/punctSpace/g,aX).replace(/punct/g,iX).getRegex(),mX=TY(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,nX).replace(/punctSpace/g,tX).replace(/punct/g,eX).getRegex(),hX=TY(/\\(punct)/,`gu`).replace(/punct/g,eX).getRegex(),gX=TY(/^<(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(),_X=TY(UY).replace(`(?:-->|$)`,`-->`).getRegex(),vX=TY(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,_X).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),yX=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,bX=TY(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace(`label`,yX).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xX=TY(/^!?\[(label)\]\[(ref)\]/).replace(`label`,yX).replace(`ref`,zY).getRegex(),SX=TY(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,zY).getRegex(),CX=TY(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,xX).replace(`nolink`,SX).getRegex(),wX=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,TX={_backpedal:wY,anyPunctuation:hX,autolink:gX,blockSkip:sX,br:QY,code:ZY,del:wY,emStrongLDelim:lX,emStrongRDelimAst:fX,emStrongRDelimUnd:mX,escape:XY,link:bX,nolink:SX,punctuation:rX,reflink:xX,reflinkSearch:CX,tag:vX,text:$Y,url:wY},EX={...TX,link:TY(/^!?\[(label)\]\((.*?)\)/).replace(`label`,yX).getRegex(),reflink:TY(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,yX).getRegex()},DX={...TX,emStrongRDelimAst:pX,emStrongLDelim:uX,url:TY(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,wX).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:TY(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,wX).getRegex()},OX={...DX,br:TY(QY).replace(`{2,}`,`*`).getRegex(),text:TY(DX.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},kX={normal:KY,gfm:JY,pedantic:YY},AX={normal:TX,gfm:DX,breaks:OX,pedantic:EX},jX={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},MX=e=>jX[e];function NX(e,t){if(t){if(DY.escapeTest.test(e))return e.replace(DY.escapeReplace,MX)}else if(DY.escapeTestNoEncode.test(e))return e.replace(DY.escapeReplaceNoEncode,MX);return e}function PX(e){try{e=encodeURI(e).replace(DY.percentDecode,`%`)}catch{return null}return e}function FX(e,t){let n=e.replace(DY.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(DY.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(DY.slLine truncated
`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
`)}var zX=class{options;rules;lexer;constructor(e){this.options=e||xY}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 e=t[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t[0],codeBlockStyle:`indented`,text:this.options.pedantic?e:FX(e,`
`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=RX(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=FX(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:FX(t[0],`
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=FX(t[0],`
`)}var BX=class{options;rules;lexer;constructor(e){this.options=e||SY}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 e=t[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t[0],codeBlockStyle:`indented`,text:this.options.pedantic?e:IX(e,`
`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=zX(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=IX(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:IX(t[0],`
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=IX(t[0],`
`).split(`
`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o=0;for(;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
@@ -448,10 +448,10 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
`,1)[0],p;if(l=f,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),p=l):p=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||t.test(l)||n.test(l))break;if(p.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
`+p.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
`+l}!u&&!l.trim()&&(u=!0),r+=f+`
`,e=e.substring(f.length+1),c=p.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0));let f=null,p;this.options.gfm&&(f=this.rules.other.listIsTask.exec(s),f&&(p=f[0]!==`[ ] `,s=s.replace(this.rules.other.listReplaceTask,``))),i.items.push({type:`list_item`,raw:r,task:!!f,checked:p,loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e=0;e<i.items.length;e++)if(this.lexer.state.top=!1,i.items[e].tokens=this.lexer.blockTokens(i.items[e].text,[]),!i.loose){let t=i.items[e].tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}if(i.loose)for(let e=0;e<i.items.length;e++)i.items[e].loose=!0;return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:`html`,block:!0,raw:t[0],pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=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:e,raw:t[0],href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=PX(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
`):[],a={type:`table`,raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(PX(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:`heading`,raw:t[0],depth:t[2].charAt(0)===`=`?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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 e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=FX(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=IX(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),LX(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.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 e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return LX(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:`del`,raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},BX=class e{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||xY,this.options.tokenizer=this.options.tokenizer||new zX,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:EY,block:OX.normal,inline:kX.normal};this.options.pedantic?(t.block=OX.pedantic,t.inline=kX.pedantic):this.options.gfm&&(t.block=OX.gfm,t.inline=this.options.breaks?kX.breaks:kX.gfm),this.tokenizer.rules=t}static get rules(){return{block:OX,inline:kX}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(EY.carriageReturn,`
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(EY.tabCharGlobal,` `).replace(EY.spaceLine,``));e;){let r;if(this.options.extensions?.block?.some(n=>(r=n.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 n=t.at(-1);r.raw.length===1&&n!==void 0?n.raw+=`
`,e=e.substring(f.length+1),c=p.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0));let f=null,p;this.options.gfm&&(f=this.rules.other.listIsTask.exec(s),f&&(p=f[0]!==`[ ] `,s=s.replace(this.rules.other.listReplaceTask,``))),i.items.push({type:`list_item`,raw:r,task:!!f,checked:p,loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e=0;e<i.items.length;e++)if(this.lexer.state.top=!1,i.items[e].tokens=this.lexer.blockTokens(i.items[e].text,[]),!i.loose){let t=i.items[e].tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}if(i.loose)for(let e=0;e<i.items.length;e++)i.items[e].loose=!0;return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:`html`,block:!0,raw:t[0],pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=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:e,raw:t[0],href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=FX(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
`):[],a={type:`table`,raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(FX(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:`heading`,raw:t[0],depth:t[2].charAt(0)===`=`?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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 e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=IX(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=LX(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),RX(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.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 e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return RX(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:`del`,raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},VX=class e{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||SY,this.options.tokenizer=this.options.tokenizer||new BX,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:DY,block:kX.normal,inline:AX.normal};this.options.pedantic?(t.block=kX.pedantic,t.inline=AX.pedantic):this.options.gfm&&(t.block=kX.gfm,t.inline=this.options.breaks?AX.breaks:AX.gfm),this.tokenizer.rules=t}static get rules(){return{block:kX,inline:AX}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(DY.carriageReturn,`
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(DY.tabCharGlobal,` `).replace(DY.spaceLine,``));e;){let r;if(this.options.extensions?.block?.some(n=>(r=n.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 n=t.at(-1);r.raw.length===1&&n!==void 0?n.raw+=`
`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
`)?``:`
`)+r.raw,n.text+=`
@@ -464,16 +464,16 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length)}else if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
`)?``:`
`)+r.raw,n.text+=`
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(r)}else if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``;for(;e;){a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if((r=this.tokenizer.escape(e))||(r=this.tokenizer.tag(e))||(r=this.tokenizer.link(e))){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if((r=this.tokenizer.emStrong(e,n,o))||(r=this.tokenizer.codespan(e))||(r=this.tokenizer.br(e))||(r=this.tokenizer.del(e))||(r=this.tokenizer.autolink(e))||!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r)}else if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw Error(t)}}return t}},VX=class{options;parser;constructor(e){this.options=e||xY}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(EY.notSpaceStart)?.[0],i=e.replace(EY.endingNewline,``)+`
`;return r?`<pre><code class="language-`+MX(r)+`">`+(n?i:MX(i,!0))+`</code></pre>
`:`<pre><code>`+(n?i:MX(i,!0))+`</code></pre>
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(r)}else if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``;for(;e;){a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if((r=this.tokenizer.escape(e))||(r=this.tokenizer.tag(e))||(r=this.tokenizer.link(e))){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if((r=this.tokenizer.emStrong(e,n,o))||(r=this.tokenizer.codespan(e))||(r=this.tokenizer.br(e))||(r=this.tokenizer.del(e))||(r=this.tokenizer.autolink(e))||!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r)}else if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw Error(t)}}return t}},HX=class{options;parser;constructor(e){this.options=e||SY}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(DY.notSpaceStart)?.[0],i=e.replace(DY.endingNewline,``)+`
`;return r?`<pre><code class="language-`+NX(r)+`">`+(n?i:NX(i,!0))+`</code></pre>
`:`<pre><code>`+(n?i:NX(i,!0))+`</code></pre>
`}blockquote({tokens:e}){return`<blockquote>
${this.parser.parse(e)}</blockquote>
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
`}hr(e){return`<hr>
`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t<e.items.length;t++){let n=e.items[t];r+=this.listitem(n)}let i=t?`ol`:`ul`,a=t&&n!==1?` start="`+n+`"`:``;return`<`+i+a+`>
`+r+`</`+i+`>
`}listitem(e){let t=``;if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type===`paragraph`?(e.tokens[0].text=n+` `+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type===`text`&&(e.tokens[0].tokens[0].text=n+` `+MX(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:`text`,raw:n+` `,text:n+` `,escaped:!0}):t+=n+` `}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>
`}listitem(e){let t=``;if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type===`paragraph`?(e.tokens[0].text=n+` `+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type===`text`&&(e.tokens[0].tokens[0].text=n+` `+NX(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:`text`,raw:n+` `,text:n+` `,escaped:!0}):t+=n+` `}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>
`}checkbox({checked:e}){return`<input `+(e?`checked="" `:``)+`disabled="" type="checkbox">`}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
`}table(e){let t=``,n=``;for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let r=``;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n=``;for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);r+=this.tablerow({text:n})}return r&&=`<tbody>${r}</tbody>`,`<table>
<thead>
@@ -482,15 +482,15 @@ ${this.parser.parse(e)}</blockquote>
`}tablerow({text:e}){return`<tr>
${e}</tr>
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${MX(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=NX(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+MX(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=NX(e);if(i===null)return MX(n);e=i;let a=`<img src="${e}" alt="${n}"`;return t&&(a+=` title="${MX(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:MX(e.text)}},HX=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}},UX=class e{options;renderer;textRenderer;constructor(e){this.options=e||xY,this.options.renderer=this.options.renderer||new VX,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new HX}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e,t=!0){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=i,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(t!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){n+=t||``;continue}}let a=i;switch(a.type){case`space`:n+=this.renderer.space(a);continue;case`hr`:n+=this.renderer.hr(a);continue;case`heading`:n+=this.renderer.heading(a);continue;case`code`:n+=this.renderer.code(a);continue;case`table`:n+=this.renderer.table(a);continue;case`blockquote`:n+=this.renderer.blockquote(a);continue;case`list`:n+=this.renderer.list(a);continue;case`html`:n+=this.renderer.html(a);continue;case`def`:n+=this.renderer.def(a);continue;case`paragraph`:n+=this.renderer.paragraph(a);continue;case`text`:{let i=a,o=this.renderer.text(i);for(;r+1<e.length&&e[r+1].type===`text`;)i=e[++r],o+=`
`+this.renderer.text(i);n+=t?this.renderer.paragraph({type:`paragraph`,raw:o,text:o,tokens:[{type:`text`,raw:o,text:o,escaped:!0}]}):o;continue}default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}parseInline(e,t=this.renderer){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},WX=class{options;block;constructor(e){this.options=e||xY}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?BX.lex:BX.lexInline}provideParser(){return this.block?UX.parse:UX.parseInline}},GX=new class{defaults=bY();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=UX;Renderer=VX;TextRenderer=HX;Lexer=BX;Tokenizer=zX;Hooks=WX;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new VX(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new zX(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new WX;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=WX.passThroughHooks.has(n)?e=>{if(this.defaults.async&&WX.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return BX.lex(e,t??this.defaults)}parser(e,t){return UX.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async:Line truncated
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+MX(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function KX(e,t){return GX.parse(e,t)}KX.options=KX.setOptions=function(e){return GX.setOptions(e),KX.defaults=GX.defaults,SY(KX.defaults),KX},KX.getDefaults=bY,KX.defaults=xY,KX.use=function(...e){return GX.use(...e),KX.defaults=GX.defaults,SY(KX.defaults),KX},KX.walkTokens=function(e,t){return GX.walkTokens(e,t)},KX.parseInline=GX.parseInline,KX.Parser=UX,KX.parser=UX.parse,KX.Renderer=VX,KX.TextRenderer=HX,KX.Lexer=BX,KX.lexer=BX.lex,KX.Tokenizer=zX,KX.Hooks=WX,KX.parse=KX,KX.options,KX.setOptions,KX.use,KX.walkTokens,KX.parseInline,UX.parse,BX.lex;function qX(e){let t=e??NR;return{...mF,...t.edgeless,colors:{...mF.colors,...t.colors}}}function JX(e){let t=e?.surface;return Array.isArray(t?.elements)?t.elements:[]}function YX(e,t,n){let r={...n,placeholder:n.placeholder??``},i=new Vp({element:e,editable:t.kind!==`json`&&t.editable,content:t.kind===`json`?t.content:void 0,extensions:t.kind===`page`?vY({...r,collab:{provider:t.provider,user:t.user}}):t.kind===`body`?vY({...r,rowBody:{doc:t.doc,fragment:t.fragment}}):vY(r),editorProps:{attributes:{class:`dw-prose`}}});return{destroy:()=>i.destroy(),focus:()=>i.commands.focus(`end`),setEditable:e=>i.setEditable(e&&t.kind!==`json`)}}function XX(e,t){let n=!!t.provider,r,i=null;if(t.provider)r=t.provider.doc;else{i=new Cv,r=i;let e=t.content;i.transact(()=>ZL(i.getXmlFragment(`default`),e?.content??[]));let n=JX(e);if(n.length){let e=new iR(i,{undo:!1});e.load(n),e.destroy()}}let a={...t};delete a.provider,delete a.content;let o=new SR(e,{doc:r,editable:n&&t.editable,notes:{mount:(e,r)=>{let i=n?r.page?{kind:`page`,provider:t.provider,user:t.user??{name:`?`,color:`#888`},editable:r.editable}:{kind:`body`,doc:r.doc,fragment:r.fragment,editable:r.editable}:{kind:`json`,content:r.page&&t.content?t.content:{type:`doc`,content:XL(r.fragment)}};return t.mountNote?t.mountNote(e,i):YX(e,i,a)}},labels:qX(t.labels),files:t.files,links:t.links,embedSource:rH,styles:t.styles,onStyles:t.onStyles,viewKey:t.viewKey,pageTitle:t.pageTitle,undo:n,onError:t.onError,onComment:t.onComment,onCommentSelect:t.onCommentSelect});return{view:o,setEditable:e=>o.setEditable(n&&e),destroy:()=>{o.destroy(),i?.destroy()}}}function ZX(e,t,n){let r=Zj(t),i=VB(t);if(!r&&!i)return()=>{};let a=()=>i?UB(e,i.database,i.row):rM(e,r),o=!1,s,c=()=>{clearTimeout(s),s=setTimeout(()=>{o||e.isDestroyed||!a()||(o=!0,l(),n?.())},50)},l=()=>{e.off(`transaction`,c),clearTimeout(u)},u=setTimeout(l,5e3);return e.on(`transaction`,c),c(),()=>{l(),clearTimeout(s)}}var QX=3e4,$X=class extends pm{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Fh();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&eZ(this,t,`timeout`)},mm(QX/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Fh()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),tg(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},eZ=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:Fh()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},tZ=(e,t,n=e.states)=>{let r=t.length,i=Fm();j(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;j(i,r),j(i,s),Gm(i,JSON.stringify(o))}return Rm(i)},nZ=(e,t,n)=>{let r=hh(t),i=Fh(),a=[],o=[],s=[],c=[],l=M(r);for(let t=0;t<l;t++){let t=M(r),n=M(r),l=JSON.parse(xh(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(tg(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},nLine truncated
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${NX(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=PX(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+NX(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=PX(e);if(i===null)return NX(n);e=i;let a=`<img src="${e}" alt="${n}"`;return t&&(a+=` title="${NX(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:NX(e.text)}},UX=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}},WX=class e{options;renderer;textRenderer;constructor(e){this.options=e||SY,this.options.renderer=this.options.renderer||new HX,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new UX}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e,t=!0){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=i,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(t!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){n+=t||``;continue}}let a=i;switch(a.type){case`space`:n+=this.renderer.space(a);continue;case`hr`:n+=this.renderer.hr(a);continue;case`heading`:n+=this.renderer.heading(a);continue;case`code`:n+=this.renderer.code(a);continue;case`table`:n+=this.renderer.table(a);continue;case`blockquote`:n+=this.renderer.blockquote(a);continue;case`list`:n+=this.renderer.list(a);continue;case`html`:n+=this.renderer.html(a);continue;case`def`:n+=this.renderer.def(a);continue;case`paragraph`:n+=this.renderer.paragraph(a);continue;case`text`:{let i=a,o=this.renderer.text(i);for(;r+1<e.length&&e[r+1].type===`text`;)i=e[++r],o+=`
`+this.renderer.text(i);n+=t?this.renderer.paragraph({type:`paragraph`,raw:o,text:o,tokens:[{type:`text`,raw:o,text:o,escaped:!0}]}):o;continue}default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}parseInline(e,t=this.renderer){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},GX=class{options;block;constructor(e){this.options=e||SY}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?VX.lex:VX.lexInline}provideParser(){return this.block?WX.parse:WX.parseInline}},KX=new class{defaults=xY();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=WX;Renderer=HX;TextRenderer=UX;Lexer=VX;Tokenizer=BX;Hooks=GX;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new HX(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new BX(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new GX;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];t[r]=GX.passThroughHooks.has(n)?e=>{if(this.defaults.async&&GX.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return VX.lex(e,t??this.defaults)}parser(e,t){return WX.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async:Line truncated
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+NX(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function qX(e,t){return KX.parse(e,t)}qX.options=qX.setOptions=function(e){return KX.setOptions(e),qX.defaults=KX.defaults,CY(qX.defaults),qX},qX.getDefaults=xY,qX.defaults=SY,qX.use=function(...e){return KX.use(...e),qX.defaults=KX.defaults,CY(qX.defaults),qX},qX.walkTokens=function(e,t){return KX.walkTokens(e,t)},qX.parseInline=KX.parseInline,qX.Parser=WX,qX.parser=WX.parse,qX.Renderer=HX,qX.TextRenderer=UX,qX.Lexer=VX,qX.lexer=VX.lex,qX.Tokenizer=BX,qX.Hooks=GX,qX.parse=qX,qX.options,qX.setOptions,qX.use,qX.walkTokens,qX.parseInline,WX.parse,VX.lex;function JX(e){let t=e??NR;return{...mF,...t.edgeless,colors:{...mF.colors,...t.colors}}}function YX(e){let t=e?.surface;return Array.isArray(t?.elements)?t.elements:[]}function XX(e,t,n){let r={...n,placeholder:n.placeholder??``},i=new Vp({element:e,editable:t.kind!==`json`&&t.editable,content:t.kind===`json`?t.content:void 0,extensions:t.kind===`page`?yY({...r,collab:{provider:t.provider,user:t.user}}):t.kind===`body`?yY({...r,rowBody:{doc:t.doc,fragment:t.fragment}}):yY(r),editorProps:{attributes:{class:`dw-prose`}}});return{destroy:()=>i.destroy(),focus:()=>i.commands.focus(`end`),setEditable:e=>i.setEditable(e&&t.kind!==`json`)}}function ZX(e,t){let n=!!t.provider,r,i=null;if(t.provider)r=t.provider.doc;else{i=new Cv,r=i;let e=t.content;i.transact(()=>ZL(i.getXmlFragment(`default`),e?.content??[]));let n=YX(e);if(n.length){let e=new iR(i,{undo:!1});e.load(n),e.destroy()}}let a={...t};delete a.provider,delete a.content;let o=new SR(e,{doc:r,editable:n&&t.editable,notes:{mount:(e,r)=>{let i=n?r.page?{kind:`page`,provider:t.provider,user:t.user??{name:`?`,color:`#888`},editable:r.editable}:{kind:`body`,doc:r.doc,fragment:r.fragment,editable:r.editable}:{kind:`json`,content:r.page&&t.content?t.content:{type:`doc`,content:XL(r.fragment)}};return t.mountNote?t.mountNote(e,i):XX(e,i,a)}},labels:JX(t.labels),files:t.files,links:t.links,embedSource:iH,styles:t.styles,onStyles:t.onStyles,viewKey:t.viewKey,pageTitle:t.pageTitle,undo:n,onError:t.onError,onComment:t.onComment,onCommentSelect:t.onCommentSelect});return{view:o,setEditable:e=>o.setEditable(n&&e),destroy:()=>{o.destroy(),i?.destroy()}}}function QX(e,t,n){let r=Zj(t),i=VB(t);if(!r&&!i)return()=>{};let a=()=>i?UB(e,i.database,i.row):rM(e,r),o=!1,s,c=()=>{clearTimeout(s),s=setTimeout(()=>{o||e.isDestroyed||!a()||(o=!0,l(),n?.())},50)},l=()=>{e.off(`transaction`,c),clearTimeout(u)},u=setTimeout(l,5e3);return e.on(`transaction`,c),c(),()=>{l(),clearTimeout(s)}}var $X=3e4,eZ=class extends pm{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Fh();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&tZ(this,t,`timeout`)},mm($X/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Fh()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),tg(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},tZ=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:Fh()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},nZ=(e,t,n=e.states)=>{let r=t.length,i=Fm();j(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;j(i,r),j(i,s),Gm(i,JSON.stringify(o))}return Rm(i)},rZ=(e,t,n)=>{let r=hh(t),i=Fh(),a=[],o=[],s=[],c=[],l=M(r);for(let t=0;t<l;t++){let t=M(r),n=M(r),l=JSON.parse(xh(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(tg(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},nLine truncated
`),before:e.state.doc.textBetween(Math.max(0,t-4e3),t,`
`)});return}case`insertMarkdown`:this.insertMarkdown(e.markdown,e.mode);return;case`transcribed`:{let t=this.pendingTranscripts.get(e.id);if(!t)return;this.pendingTranscripts.delete(e.id),e.result&&this.words?t.resolve(Qp(e.result,this.words,bZ)):t.reject(Error(e.error||this.labels.blocks.transcribeFailed));return}default:throw Error(`unknown message ${e.type}`)}}requestTranscript(e,t){let n=this.nextTranscript++;return new Promise((r,i)=>{this.pendingTranscripts.set(n,{resolve:r,reject:i}),this.send({type:`transcribe`,id:n,src:e,name:t})})}insertMarkdown(e,t){let n=this.picked,r=n&&!n.editor.isDestroyed?n.editor:this.target,i=bZ(e);if(!i.trim())return;let a=r.state.doc.content.size,o=Math.min(n?.from??r.state.selection.from,a),s=Math.min(n?.to??r.state.selection.to,a);if(t===`replace`)r.chain().focus().insertContentAt({from:o,to:s},i).run();else{let e=r.state.doc.resolve(s);r.chain().focus().insertContentAt(e.depth>=1?e.after(1):s,i).run()}this.picked=null}connect(e){this.provider?.destroy();let t=new hZ({url:e.url,page:e.page,token:()=>e.token});t.onChange(()=>this.send({type:`collab`,status:t.status})),this.provider=t,this.editor.destroy(),this.editor=this.create({collab:{provider:t,user:e.user}}),this.mode===`edgeless`&&this.openCanvas()}openCanvas(){this.closeCanvas();let e=document.createElement(`div`);e.className=`dw-bridge-canvas`,document.body.append(e),this.canvasEl=e,this.el.hidden=!0,this.canvas=XX(e,{provider:this.provider??void 0,content:this.provider?void 0:this.lastContent??this.editor.getJSON(),editable:this.editable&&!!this.provider,pageTitle:()=>this.title,onNavigate:e=>this.send({type:`navigate`,path:e}),onError:e=>this.send({type:`error`,message:e instanceof Error?e.message:String(e)})})}closeCanvas(){this.canvas?.destroy(),this.canvas=null,this.canvasEl?.remove(),this.canvasEl=null,this.el.hidden=!1}create(e){return this.el.replaceChildren(),new Vp({element:this.el,editable:this.editable,extensions:vY({...e,files:this.files,labels:this.labels,onNavigate:e=>this.send({type:`navigate`,path:e})}),editorProps:{attributes:{class:`dw-prose`}},onUpdate:({editor:e})=>this.send({type:`change`,content:e.getJSON()}),onSelectionUpdate:()=>this.reportState(),onTransaction:()=>this.reportState(),onFocus:()=>this.reportState(),onBlur:()=>this.reportState()})}get target(){return this.inner&&!this.inner.isDestroyed?this.inner:this.editor}track(e){let t=(e instanceof Element?e.closest(`.ProseMirror`):null)?.editor;t&&(this.setInner(t===this.editor?null:t),this.reportState())}innerChanged=()=>this.reportState();innerGone=()=>{this.setInner(null),this.reportState()};setInner(e){if(e!==this.inner){if(this.inner){for(let e of[`selectionUpdate`,`transaction`,`focus`,`blur`])this.inner.off(e,this.innerChanged);this.inner.off(`destroy`,this.innerGone)}if(this.inner=e,e){for(let t of[`selectionUpdate`,`transaction`,`focus`,`blur`])e.on(t,this.innerChanged);e.on(`destroy`,this.innerGone)}}}reportOverlay(){let e=document.querySelector(gZ)!==null;e!==this.overlay&&(this.overlay=e,this.send({type:`overlay`,open:e}))}reportState(){let e=this.target;if(e.isDestroyed)return;let t={active:vZ.filter(([,t])=>t(e)).map(([e])=>e),canUndo:e.can().undo(),canRedo:e.can().redo(),focused:e.isFocused},n=JSON.stringify(t);n!==this.lastState&&(this.lastState=n,this.send({type:`state`,state:t}))}};function bZ(e){return KX.parse(e.trim(),{async:!1,gfm:!0})}function xZ(e){if(e.isDestroyed)return;let t=e.view.props.nodeViews??{},n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,(...e)=>t(...e)]));e.view.setProps({nodeViews:n})}function SZ(e){let t=JSON.stringify(e);window.DocwellNative?window.DocwellNative.postMessage(t):(window.parent.postMessage(t,`*`),console.debug(`[docwell bridge]`,e))}var CZ=new yZ(document.getElementById(`editor`),SZ);window.docwell={receive:e=>CZ.receive(e)};</script>
`)});return}case`insertMarkdown`:this.insertMarkdown(e.markdown,e.mode);return;case`transcribed`:{let t=this.pendingTranscripts.get(e.id);if(!t)return;this.pendingTranscripts.delete(e.id),e.result&&this.words?t.resolve(Qp(e.result,this.words,xZ)):t.reject(Error(e.error||this.labels.blocks.transcribeFailed));return}default:throw Error(`unknown message ${e.type}`)}}requestTranscript(e,t){let n=this.nextTranscript++;return new Promise((r,i)=>{this.pendingTranscripts.set(n,{resolve:r,reject:i}),this.send({type:`transcribe`,id:n,src:e,name:t})})}insertMarkdown(e,t){let n=this.picked,r=n&&!n.editor.isDestroyed?n.editor:this.target,i=xZ(e);if(!i.trim())return;let a=r.state.doc.content.size,o=Math.min(n?.from??r.state.selection.from,a),s=Math.min(n?.to??r.state.selection.to,a);if(t===`replace`)r.chain().focus().insertContentAt({from:o,to:s},i).run();else{let e=r.state.doc.resolve(s);r.chain().focus().insertContentAt(e.depth>=1?e.after(1):s,i).run()}this.picked=null}connect(e){this.provider?.destroy();let t=new gZ({url:e.url,page:e.page,token:()=>e.token});t.onChange(()=>this.send({type:`collab`,status:t.status})),this.provider=t,this.editor.destroy(),this.editor=this.create({collab:{provider:t,user:e.user}}),this.mode===`edgeless`&&this.openCanvas()}openCanvas(){this.closeCanvas();let e=document.createElement(`div`);e.className=`dw-bridge-canvas`,document.body.append(e),this.canvasEl=e,this.el.hidden=!0,this.canvas=ZX(e,{provider:this.provider??void 0,content:this.provider?void 0:this.lastContent??this.editor.getJSON(),editable:this.editable&&!!this.provider,pageTitle:()=>this.title,onNavigate:e=>this.send({type:`navigate`,path:e}),onError:e=>this.send({type:`error`,message:e instanceof Error?e.message:String(e)})})}closeCanvas(){this.canvas?.destroy(),this.canvas=null,this.canvasEl?.remove(),this.canvasEl=null,this.el.hidden=!1}create(e){return this.el.replaceChildren(),new Vp({element:this.el,editable:this.editable,extensions:yY({...e,files:this.files,labels:this.labels,onNavigate:e=>this.send({type:`navigate`,path:e})}),editorProps:{attributes:{class:`dw-prose`}},onUpdate:({editor:e})=>this.send({type:`change`,content:e.getJSON()}),onSelectionUpdate:()=>this.reportState(),onTransaction:()=>this.reportState(),onFocus:()=>this.reportState(),onBlur:()=>this.reportState()})}get target(){return this.inner&&!this.inner.isDestroyed?this.inner:this.editor}track(e){let t=(e instanceof Element?e.closest(`.ProseMirror`):null)?.editor;t&&(this.setInner(t===this.editor?null:t),this.reportState())}innerChanged=()=>this.reportState();innerGone=()=>{this.setInner(null),this.reportState()};setInner(e){if(e!==this.inner){if(this.inner){for(let e of[`selectionUpdate`,`transaction`,`focus`,`blur`])this.inner.off(e,this.innerChanged);this.inner.off(`destroy`,this.innerGone)}if(this.inner=e,e){for(let t of[`selectionUpdate`,`transaction`,`focus`,`blur`])e.on(t,this.innerChanged);e.on(`destroy`,this.innerGone)}}}reportOverlay(){let e=document.querySelector(_Z)!==null;e!==this.overlay&&(this.overlay=e,this.send({type:`overlay`,open:e}))}reportState(){let e=this.target;if(e.isDestroyed)return;let t={active:yZ.filter(([,t])=>t(e)).map(([e])=>e),canUndo:e.can().undo(),canRedo:e.can().redo(),focused:e.isFocused},n=JSON.stringify(t);n!==this.lastState&&(this.lastState=n,this.send({type:`state`,state:t}))}};function xZ(e){return qX.parse(e.trim(),{async:!1,gfm:!0})}function SZ(e){if(e.isDestroyed)return;let t=e.view.props.nodeViews??{},n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,(...e)=>t(...e)]));e.view.setProps({nodeViews:n})}function CZ(e){let t=JSON.stringify(e);window.DocwellNative?window.DocwellNative.postMessage(t):(window.parent.postMessage(t,`*`),console.debug(`[docwell bridge]`,e))}var wZ=new bZ(document.getElementById(`editor`),CZ);window.docwell={receive:e=>wZ.receive(e)};</script>
<style rel="stylesheet" crossorigin>/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--shadow-dialog:var(--dw-shadow-dialog);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-varLine truncated
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--shadow-dialog:var(--dw-shadow-dialog);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-varLine truncated
/*$vite$:1*/</style>
</head>
<body>
+23
View File
@@ -642,6 +642,29 @@
max-height: 120px;
object-fit: cover;
}
.dw-prose .dw-linkcard__head {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.dw-prose .dw-linkcard__status {
flex: none;
padding: 1px 8px;
border-radius: 999px;
background: var(--dw-bg);
color: var(--dw-c);
font-size: var(--text-ui-xs);
font-weight: 600;
white-space: nowrap;
}
.dw-prose .dw-linkcard__image--avatar {
width: 40px;
height: 40px;
margin: 12px 14px 12px 0;
border-radius: var(--radius-sm);
object-fit: cover;
}
.dw-prose .ProseMirror-selectednode:is(.dw-embed, .dw-linkcard) {
outline: 2px solid var(--color-focus-ring);
outline-offset: 2px;
+47 -3
View File
@@ -20,8 +20,27 @@ export interface LinkPreview {
description?: string;
image?: string;
site?: string;
/** From a service's API: "github.pull", "linear.issue", "figma.file"… */
kind?: string;
/** The service's word for the item's state ("Merged", "In Progress"). */
status?: string;
/** open, started, draft, merged, done, closed or canceled: the status's colour. */
state?: string;
/** A line of details ("acme/app #12 · alice"). */
meta?: string;
}
/** The palette colour of a link card's status. */
const stateColors: Record<string, string> = {
open: "green",
started: "yellow",
draft: "gray",
merged: "purple",
done: "blue",
closed: "red",
canceled: "gray",
};
/**
* Fetches a page's title, description and picture for a link card. Pages on
* other sites can't be read from the browser, so hosts ask docwell-server.
@@ -276,6 +295,10 @@ export const LinkCard = Node.create<{ labels: EditorLabels | null }>({
description: attr("description"),
image: attr("image"),
site: attr("site"),
kind: attr("kind"),
status: attr("status"),
state: attr("state"),
meta: attr("meta"),
};
},
@@ -305,6 +328,10 @@ export const LinkCard = Node.create<{ labels: EditorLabels | null }>({
description: card.description ?? "",
image: card.image ?? "",
site: card.site ?? "",
kind: card.kind ?? "",
status: card.status ?? "",
state: card.state ?? "",
meta: card.meta ?? "",
},
}),
};
@@ -327,7 +354,19 @@ export const LinkCard = Node.create<{ labels: EditorLabels | null }>({
const title = document.createElement("span");
title.className = "dw-linkcard__title";
title.textContent = String(attrs.title || "") || hostOf(url);
text.append(title);
const kind = String(attrs.kind || "");
dom.dataset.kind = kind;
if (attrs.status) {
// GitHub, Linear and Figma items carry their state.
const head = document.createElement("span");
head.className = "dw-linkcard__head";
const pill = document.createElement("span");
pill.className = "dw-linkcard__status";
pill.dataset.color = stateColors[String(attrs.state)] ?? "gray";
pill.textContent = String(attrs.status);
head.append(pill, title);
text.append(head);
} else text.append(title);
if (attrs.description) {
const desc = document.createElement("span");
desc.className = "dw-linkcard__desc";
@@ -336,13 +375,18 @@ export const LinkCard = Node.create<{ labels: EditorLabels | null }>({
}
const site = document.createElement("span");
site.className = "dw-linkcard__site";
site.textContent = String(attrs.site || "") || hostOf(url);
site.textContent = [String(attrs.site || "") || hostOf(url), String(attrs.meta || "")]
.filter(Boolean)
.join(" · ");
text.append(site);
dom.append(text);
const image = webUrl(String(attrs.image || ""));
if (image.startsWith("https:")) {
const img = document.createElement("img");
img.className = "dw-linkcard__image";
// GitHub sends its author's or owner's picture: a small avatar, not a cover.
img.className = kind.startsWith("github.")
? "dw-linkcard__image dw-linkcard__image--avatar"
: "dw-linkcard__image";
img.src = image;
img.alt = "";
img.loading = "lazy";
+253
View File
@@ -1276,6 +1276,27 @@ class PinnedPage {
};
}
/// The state for its colour
enum LinkPreviewState {
open('open'),
started('started'),
draft('draft'),
merged('merged'),
done('done'),
closed('closed'),
canceled('canceled');
const LinkPreviewState(this.value);
final String value;
static LinkPreviewState fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown LinkPreviewState', value),
);
String toJson() => value;
}
class LinkPreview {
const LinkPreview({
required this.url,
@@ -1283,6 +1304,10 @@ class LinkPreview {
required this.description,
required this.image,
required this.site,
this.kind,
this.status,
this.state,
this.meta,
});
factory LinkPreview.fromJson(Map<String, dynamic> json) => LinkPreview(
@@ -1291,6 +1316,12 @@ class LinkPreview {
description: json['description'] as String,
image: json['image'] as String,
site: json['site'] as String,
kind: json['kind'] == null ? null : json['kind'] as String,
status: json['status'] == null ? null : json['status'] as String,
state: json['state'] == null
? null
: LinkPreviewState.fromJson(json['state'] as String),
meta: json['meta'] == null ? null : json['meta'] as String,
);
final String url;
@@ -1304,12 +1335,234 @@ class LinkPreview {
final String site;
/// For links read through a service's API (github.issue, github.pull, github.repo, linear.issue, figma.file)
final String? kind;
/// The service's word for the item's state (Open, Merged, In Progress)
final String? status;
/// The state for its colour
final LinkPreviewState? state;
/// A line of details (acme/app #12 · alice)
final String? meta;
Map<String, dynamic> toJson() => {
'url': url,
'title': title,
'description': description,
'image': image,
'site': site,
'kind': ?kind,
'status': ?status,
'state': ?state?.toJson(),
'meta': ?meta,
};
}
class WorkspaceIntegrations {
const WorkspaceIntegrations({
required this.github,
required this.linear,
required this.figma,
required this.slack,
});
factory WorkspaceIntegrations.fromJson(
Map<String, dynamic> json,
) => WorkspaceIntegrations(
github: IntegrationToken.fromJson(json['github'] as Map<String, dynamic>),
linear: IntegrationToken.fromJson(json['linear'] as Map<String, dynamic>),
figma: IntegrationToken.fromJson(json['figma'] as Map<String, dynamic>),
slack: SlackIntegration.fromJson(json['slack'] as Map<String, dynamic>),
);
final IntegrationToken github;
final IntegrationToken linear;
final IntegrationToken figma;
final SlackIntegration slack;
Map<String, dynamic> toJson() => {
'github': github.toJson(),
'linear': linear.toJson(),
'figma': figma.toJson(),
'slack': slack.toJson(),
};
}
class IntegrationToken {
const IntegrationToken({required this.set});
factory IntegrationToken.fromJson(Map<String, dynamic> json) =>
IntegrationToken(set: json['set'] as bool);
/// A token is stored (it is never sent back)
final bool set;
Map<String, dynamic> toJson() => {'set': set};
}
class SlackIntegration {
const SlackIntegration({
required this.connected,
required this.hasSigningSecret,
required this.team,
required this.teamName,
required this.channel,
required this.channelName,
required this.events,
required this.unfurl,
required this.search,
required this.lastError,
required this.eventsUrl,
required this.commandsUrl,
required this.manifest,
});
factory SlackIntegration.fromJson(Map<String, dynamic> json) =>
SlackIntegration(
connected: json['connected'] as bool,
hasSigningSecret: json['hasSigningSecret'] as bool,
team: json['team'] as String,
teamName: json['teamName'] as String,
channel: json['channel'] as String,
channelName: json['channelName'] as String,
events: (json['events'] as List).map((e) => e as String).toList(),
unfurl: json['unfurl'] as bool,
search: json['search'] as bool,
lastError: json['lastError'] as String,
eventsUrl: json['eventsUrl'] as String,
commandsUrl: json['commandsUrl'] as String,
manifest: json['manifest'] as String,
);
/// A bot token is stored
final bool connected;
final bool hasSigningSecret;
/// The Slack workspace id the bot belongs to
final String team;
final String teamName;
/// The channel id posts go to; empty for none
final String channel;
final String channelName;
/// Events posted to the channel
final List<String> events;
/// Docwell links posted in Slack get a preview
final bool unfurl;
/// /docwell searches Docwell
final bool search;
/// The last post that failed; empty when the last one worked
final String lastError;
/// Request URL for the Slack app's Event Subscriptions
final String eventsUrl;
/// Request URL for the /docwell slash command
final String commandsUrl;
/// A Slack app manifest (JSON) with those URLs and the scopes Docwell needs
final String manifest;
Map<String, dynamic> toJson() => {
'connected': connected,
'hasSigningSecret': hasSigningSecret,
'team': team,
'teamName': teamName,
'channel': channel,
'channelName': channelName,
'events': events.map((e) => e).toList(),
'unfurl': unfurl,
'search': search,
'lastError': lastError,
'eventsUrl': eventsUrl,
'commandsUrl': commandsUrl,
'manifest': manifest,
};
}
enum SlackIntegrationInputEvents {
pageCreated('page.created'),
pageUpdated('page.updated'),
pageMoved('page.moved'),
pageArchived('page.archived'),
pageUnarchived('page.unarchived'),
pageRestored('page.restored'),
commentCreated('comment.created'),
commentResolved('comment.resolved');
const SlackIntegrationInputEvents(this.value);
final String value;
static SlackIntegrationInputEvents fromJson(String value) =>
values.firstWhere(
(e) => e.value == value,
orElse: () =>
throw FormatException('unknown SlackIntegrationInputEvents', value),
);
String toJson() => value;
}
class SlackIntegrationInput {
const SlackIntegrationInput({
this.botToken,
this.signingSecret,
this.channel,
this.events,
this.unfurl,
this.search,
});
factory SlackIntegrationInput.fromJson(Map<String, dynamic> json) =>
SlackIntegrationInput(
botToken: json['botToken'] == null ? null : json['botToken'] as String,
signingSecret: json['signingSecret'] == null
? null
: json['signingSecret'] as String,
channel: json['channel'] == null ? null : json['channel'] as String,
events: json['events'] == null
? null
: (json['events'] as List)
.map((e) => SlackIntegrationInputEvents.fromJson(e as String))
.toList(),
unfurl: json['unfurl'] == null ? null : json['unfurl'] as bool,
search: json['search'] == null ? null : json['search'] as bool,
);
/// The app's Bot User OAuth Token (xoxb-…); checked with Slack
final String? botToken;
/// The app's Signing Secret
final String? signingSecret;
/// A public channel id or name (#news); empty for none
final String? channel;
final List<SlackIntegrationInputEvents>? events;
final bool? unfurl;
final bool? search;
Map<String, dynamic> toJson() => {
'botToken': ?botToken,
'signingSecret': ?signingSecret,
'channel': ?channel,
'events': ?events?.map((e) => e.toJson()).toList(),
'unfurl': ?unfurl,
'search': ?search,
};
}
+21 -14
View File
@@ -26,6 +26,7 @@ import (
"docwell/server/internal/directory"
"docwell/server/internal/httpapi"
"docwell/server/internal/instance"
"docwell/server/internal/integrations"
"docwell/server/internal/jobs"
"docwell/server/internal/mail"
"docwell/server/internal/oauth"
@@ -200,6 +201,11 @@ func run(log *slog.Logger) error {
readwiseSvc := readwise.New(db, dirSvc, readwise.Options{Secret: secret, AllowLocal: cfg.WebhooksAllowLocal})
reg.Register("readwise.sync", "Adds new Readwise highlights to people's pages", 10*time.Minute, readwiseSvc.SyncDue)
go reg.Every(indexCtx, "readwise.sync", 10*time.Minute)
// Workspace integrations (ADR-18): service tokens for link previews, and
// Slack, which follows the same events as webhooks.
previews := unfurl.New()
integrationsSvc := integrations.New(db, dirSvc, previews, integrations.Options{Secret: secret, WebURL: cfg.WebURL, Log: log})
hooks.Listen(integrationsSvc.Listen)
dirSvc.SetPublicURL(cfg.PublicURL)
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
@@ -218,20 +224,21 @@ func run(log *slog.Logger) error {
Settings: settingsSvc,
// Derived from the PocketBase password, so links survive restarts
// without another secret to configure.
FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
MaxUpload: int64(cfg.MaxUploadMB) << 20,
Instance: instance.New(db, Version, hub, index, reg),
Collab: hub,
Audit: auditLog,
Previews: unfurl.New(),
Calendars: calSvc,
OAuth: oauthRouter,
OneNote: oneNoteSvc,
Readwise: readwiseSvc,
Push: pushSvc,
AI: aiSvc,
Admin: admin.Handler("/admin"),
Log: log,
FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
MaxUpload: int64(cfg.MaxUploadMB) << 20,
Instance: instance.New(db, Version, hub, index, reg),
Collab: hub,
Audit: auditLog,
Previews: previews,
Calendars: calSvc,
OAuth: oauthRouter,
OneNote: oneNoteSvc,
Readwise: readwiseSvc,
Integrations: integrationsSvc,
Push: pushSvc,
AI: aiSvc,
Admin: admin.Handler("/admin"),
Log: log,
}),
ReadHeaderTimeout: 10 * time.Second,
}
+211 -34
View File
@@ -432,6 +432,39 @@ func (e LabelColor) Valid() bool {
}
}
// Defines values for LinkPreviewState.
const (
LinkPreviewStateCanceled LinkPreviewState = "canceled"
LinkPreviewStateClosed LinkPreviewState = "closed"
LinkPreviewStateDone LinkPreviewState = "done"
LinkPreviewStateDraft LinkPreviewState = "draft"
LinkPreviewStateMerged LinkPreviewState = "merged"
LinkPreviewStateOpen LinkPreviewState = "open"
LinkPreviewStateStarted LinkPreviewState = "started"
)
// Valid indicates whether the value is a known member of the LinkPreviewState enum.
func (e LinkPreviewState) Valid() bool {
switch e {
case LinkPreviewStateCanceled:
return true
case LinkPreviewStateClosed:
return true
case LinkPreviewStateDone:
return true
case LinkPreviewStateDraft:
return true
case LinkPreviewStateMerged:
return true
case LinkPreviewStateOpen:
return true
case LinkPreviewStateStarted:
return true
default:
return false
}
}
// Defines values for NewApiTokenScope.
const (
NewApiTokenScopeRead NewApiTokenScope = "read"
@@ -708,6 +741,42 @@ func (e Role) Valid() bool {
}
}
// Defines values for SlackIntegrationInputEvents.
const (
SlackIntegrationInputEventsCommentCreated SlackIntegrationInputEvents = "comment.created"
SlackIntegrationInputEventsCommentResolved SlackIntegrationInputEvents = "comment.resolved"
SlackIntegrationInputEventsPageArchived SlackIntegrationInputEvents = "page.archived"
SlackIntegrationInputEventsPageCreated SlackIntegrationInputEvents = "page.created"
SlackIntegrationInputEventsPageMoved SlackIntegrationInputEvents = "page.moved"
SlackIntegrationInputEventsPageRestored SlackIntegrationInputEvents = "page.restored"
SlackIntegrationInputEventsPageUnarchived SlackIntegrationInputEvents = "page.unarchived"
SlackIntegrationInputEventsPageUpdated SlackIntegrationInputEvents = "page.updated"
)
// Valid indicates whether the value is a known member of the SlackIntegrationInputEvents enum.
func (e SlackIntegrationInputEvents) Valid() bool {
switch e {
case SlackIntegrationInputEventsCommentCreated:
return true
case SlackIntegrationInputEventsCommentResolved:
return true
case SlackIntegrationInputEventsPageArchived:
return true
case SlackIntegrationInputEventsPageCreated:
return true
case SlackIntegrationInputEventsPageMoved:
return true
case SlackIntegrationInputEventsPageRestored:
return true
case SlackIntegrationInputEventsPageUnarchived:
return true
case SlackIntegrationInputEventsPageUpdated:
return true
default:
return false
}
}
// Defines values for SpaceCallerRole.
const (
SpaceCallerRoleAdmin SpaceCallerRole = "admin"
@@ -782,16 +851,16 @@ func (e SpaceRole) Valid() bool {
// Defines values for SpaceVisibility.
const (
Open SpaceVisibility = "open"
Private SpaceVisibility = "private"
SpaceVisibilityOpen SpaceVisibility = "open"
SpaceVisibilityPrivate SpaceVisibility = "private"
)
// Valid indicates whether the value is a known member of the SpaceVisibility enum.
func (e SpaceVisibility) Valid() bool {
switch e {
case Open:
case SpaceVisibilityOpen:
return true
case Private:
case SpaceVisibilityPrivate:
return true
default:
return false
@@ -881,49 +950,49 @@ func (e WebhookDeliveryStatus) Valid() bool {
// Defines values for WebhookEvent.
const (
Asterisk WebhookEvent = "*"
CommentCreated WebhookEvent = "comment.created"
CommentResolved WebhookEvent = "comment.resolved"
PageArchived WebhookEvent = "page.archived"
PageCreated WebhookEvent = "page.created"
PageDeleted WebhookEvent = "page.deleted"
PageMoved WebhookEvent = "page.moved"
PageRestored WebhookEvent = "page.restored"
PageTrashed WebhookEvent = "page.trashed"
PageUnarchived WebhookEvent = "page.unarchived"
PageUpdated WebhookEvent = "page.updated"
SpaceCreated WebhookEvent = "space.created"
SpaceDeleted WebhookEvent = "space.deleted"
WebhookEventAsterisk WebhookEvent = "*"
WebhookEventCommentCreated WebhookEvent = "comment.created"
WebhookEventCommentResolved WebhookEvent = "comment.resolved"
WebhookEventPageArchived WebhookEvent = "page.archived"
WebhookEventPageCreated WebhookEvent = "page.created"
WebhookEventPageDeleted WebhookEvent = "page.deleted"
WebhookEventPageMoved WebhookEvent = "page.moved"
WebhookEventPageRestored WebhookEvent = "page.restored"
WebhookEventPageTrashed WebhookEvent = "page.trashed"
WebhookEventPageUnarchived WebhookEvent = "page.unarchived"
WebhookEventPageUpdated WebhookEvent = "page.updated"
WebhookEventSpaceCreated WebhookEvent = "space.created"
WebhookEventSpaceDeleted WebhookEvent = "space.deleted"
)
// Valid indicates whether the value is a known member of the WebhookEvent enum.
func (e WebhookEvent) Valid() bool {
switch e {
case Asterisk:
case WebhookEventAsterisk:
return true
case CommentCreated:
case WebhookEventCommentCreated:
return true
case CommentResolved:
case WebhookEventCommentResolved:
return true
case PageArchived:
case WebhookEventPageArchived:
return true
case PageCreated:
case WebhookEventPageCreated:
return true
case PageDeleted:
case WebhookEventPageDeleted:
return true
case PageMoved:
case WebhookEventPageMoved:
return true
case PageRestored:
case WebhookEventPageRestored:
return true
case PageTrashed:
case WebhookEventPageTrashed:
return true
case PageUnarchived:
case WebhookEventPageUnarchived:
return true
case PageUpdated:
case WebhookEventPageUpdated:
return true
case SpaceCreated:
case WebhookEventSpaceCreated:
return true
case SpaceDeleted:
case WebhookEventSpaceDeleted:
return true
default:
return false
@@ -1741,6 +1810,12 @@ type InstanceSettingsUpdate struct {
Storage *StorageSettings `json:"storage,omitempty"`
}
// IntegrationToken defines model for IntegrationToken.
type IntegrationToken struct {
// Set A token is stored (it is never sent back)
Set bool `json:"set"`
}
// Integrations defines model for Integrations.
type Integrations struct {
// Google People can connect Google Calendar
@@ -1904,11 +1979,26 @@ type LinkPreview struct {
// Image Address of the page's picture on its own site; empty when it has none
Image string `json:"image"`
Site string `json:"site"`
Title string `json:"title"`
Url string `json:"url"`
// Kind For links read through a service's API (github.issue, github.pull, github.repo, linear.issue, figma.file)
Kind *string `json:"kind,omitempty"`
// Meta A line of details (acme/app #12 · alice)
Meta *string `json:"meta,omitempty"`
Site string `json:"site"`
// State The state for its colour
State *LinkPreviewState `json:"state,omitempty"`
// Status The service's word for the item's state (Open, Merged, In Progress)
Status *string `json:"status,omitempty"`
Title string `json:"title"`
Url string `json:"url"`
}
// LinkPreviewState The state for its colour
type LinkPreviewState string
// LoginRequest defines model for LoginRequest.
type LoginRequest struct {
Email openapi_types.Email `json:"email"`
@@ -2475,6 +2565,60 @@ type SignupSettings struct {
Enabled bool `json:"enabled"`
}
// SlackIntegration defines model for SlackIntegration.
type SlackIntegration struct {
// Channel The channel id posts go to; empty for none
Channel string `json:"channel"`
ChannelName string `json:"channelName"`
// CommandsUrl Request URL for the /docwell slash command
CommandsUrl string `json:"commandsUrl"`
// Connected A bot token is stored
Connected bool `json:"connected"`
// Events Events posted to the channel
Events []string `json:"events"`
// EventsUrl Request URL for the Slack app's Event Subscriptions
EventsUrl string `json:"eventsUrl"`
HasSigningSecret bool `json:"hasSigningSecret"`
// LastError The last post that failed; empty when the last one worked
LastError string `json:"lastError"`
// Manifest A Slack app manifest (JSON) with those URLs and the scopes Docwell needs
Manifest string `json:"manifest"`
// Search /docwell searches Docwell
Search bool `json:"search"`
// Team The Slack workspace id the bot belongs to
Team string `json:"team"`
TeamName string `json:"teamName"`
// Unfurl Docwell links posted in Slack get a preview
Unfurl bool `json:"unfurl"`
}
// SlackIntegrationInput defines model for SlackIntegrationInput.
type SlackIntegrationInput struct {
// BotToken The app's Bot User OAuth Token (xoxb-…); checked with Slack
BotToken *string `json:"botToken,omitempty"`
// Channel A public channel id or name (#news); empty for none
Channel *string `json:"channel,omitempty"`
Events *[]SlackIntegrationInputEvents `json:"events,omitempty"`
Search *bool `json:"search,omitempty"`
// SigningSecret The app's Signing Secret
SigningSecret *string `json:"signingSecret,omitempty"`
Unfurl *bool `json:"unfurl,omitempty"`
}
// SlackIntegrationInputEvents defines model for SlackIntegrationInput.Events.
type SlackIntegrationInputEvents string
// SmtpSettings defines model for SmtpSettings.
type SmtpSettings struct {
Enabled bool `json:"enabled"`
@@ -2775,6 +2919,14 @@ type Workspace struct {
UrlPreview bool `json:"urlPreview"`
}
// WorkspaceIntegrations defines model for WorkspaceIntegrations.
type WorkspaceIntegrations struct {
Figma IntegrationToken `json:"figma"`
Github IntegrationToken `json:"github"`
Linear IntegrationToken `json:"linear"`
Slack SlackIntegration `json:"slack"`
}
// WorkspaceMember defines model for WorkspaceMember.
type WorkspaceMember struct {
Role WorkspaceRole `json:"role"`
@@ -2910,7 +3062,8 @@ type ListInvitesParams struct {
// PreviewLinkParams defines parameters for PreviewLink.
type PreviewLinkParams struct {
Url string `form:"url" json:"url"`
Url string `form:"url" json:"url"`
Workspace *string `form:"workspace,omitempty" json:"workspace,omitempty"`
}
// RegisterDeviceJSONBody defines parameters for RegisterDevice.
@@ -3090,6 +3243,13 @@ type GetSharePreviewParams struct {
Page *string `form:"page,omitempty" json:"page,omitempty"`
}
// SlackCommandsFormdataBody defines parameters for SlackCommands.
type SlackCommandsFormdataBody struct {
}
// SlackEventsJSONBody defines parameters for SlackEvents.
type SlackEventsJSONBody map[string]interface{}
// UpdateSpaceJSONBody defines parameters for UpdateSpace.
type UpdateSpaceJSONBody struct {
// DefaultRole Role that workspace members (not guests) get in an open space without an explicit role.
@@ -3208,6 +3368,11 @@ type ListDocsParams struct {
Filter *string `form:"filter,omitempty" json:"filter,omitempty"`
}
// SetIntegrationTokenJSONBody defines parameters for SetIntegrationToken.
type SetIntegrationTokenJSONBody struct {
Token string `json:"token"`
}
// SetInviteLinkJSONBody defines parameters for SetInviteLink.
type SetInviteLinkJSONBody struct {
// Approval Joining needs an admin's approval
@@ -3464,6 +3629,12 @@ type UpdatePropertyJSONRequestBody = PropertyInput
// SaveReadwiseJSONRequestBody defines body for SaveReadwise for application/json ContentType.
type SaveReadwiseJSONRequestBody = ReadwiseInput
// SlackCommandsFormdataRequestBody defines body for SlackCommands for application/x-www-form-urlencoded ContentType.
type SlackCommandsFormdataRequestBody SlackCommandsFormdataBody
// SlackEventsJSONRequestBody defines body for SlackEvents for application/json ContentType.
type SlackEventsJSONRequestBody SlackEventsJSONBody
// UpdateSpaceJSONRequestBody defines body for UpdateSpace for application/json ContentType.
type UpdateSpaceJSONRequestBody UpdateSpaceJSONBody
@@ -3527,6 +3698,12 @@ type CreateCollectionJSONRequestBody = CollectionInput
// CreateGroupJSONRequestBody defines body for CreateGroup for application/json ContentType.
type CreateGroupJSONRequestBody = GroupRequest
// SetSlackIntegrationJSONRequestBody defines body for SetSlackIntegration for application/json ContentType.
type SetSlackIntegrationJSONRequestBody = SlackIntegrationInput
// SetIntegrationTokenJSONRequestBody defines body for SetIntegrationToken for application/json ContentType.
type SetIntegrationTokenJSONRequestBody SetIntegrationTokenJSONBody
// SetInviteLinkJSONRequestBody defines body for SetInviteLink for application/json ContentType.
type SetInviteLinkJSONRequestBody SetInviteLinkJSONBody
+541
View File
@@ -0,0 +1,541 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
// Confluence: a space exported as HTML (Space settings → Export space →
// HTML) is a zip with one folder holding index.html (the space's page
// tree), one HTML file per page, attachments/<page id>/<file> and the
// export's styles. The page tree comes from index.html (or, for a page it
// leaves out, the page's breadcrumbs); each page's #main-content is
// cleaned of Confluence's macro markup (info panels, code, expand,
// task lists, status lozenges, emoticons) into HTML FromHTML reads, and
// files listed under the page's Attachments become links at its end.
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"path"
"regexp"
"sort"
"strings"
"unicode/utf8"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// VaultConfluence is a Confluence space export (HTML).
const VaultConfluence VaultKind = "confluence"
// ErrNoConfluence is returned for a zip that is not a Confluence HTML export.
var ErrNoConfluence = errors.New("the archive is not a Confluence HTML export")
// isConfluence reports whether the names in a zip look like a Confluence
// HTML export: a folder with index.html and styles/site.css.
func isConfluence(names []string) bool {
has := map[string]bool{}
for _, n := range names {
has[n] = true
}
for _, n := range names {
if path.Base(n) == "index.html" && has[path.Join(path.Dir(n), "styles", "site.css")] {
return true
}
}
return false
}
// ReadConfluence reads a Confluence space export. Pages come parents first.
func ReadConfluence(data []byte) ([]NotionPage, []Asset, error) {
n := &notionReader{files: map[string]*zip.File{}, assetAt: map[string]string{}, pageAt: map[string]int{}}
if err := n.open(data, false); err != nil {
return nil, nil, err
}
// The export's folder: the one with index.html next to styles/site.css.
root := ""
names := make([]string, 0, len(n.files))
for name := range n.files {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if path.Base(name) == "index.html" {
if _, ok := n.files[path.Join(path.Dir(name), "styles", "site.css")]; ok {
root = path.Dir(name)
break
}
}
}
if root == "" {
return nil, nil, ErrNoConfluence
}
index := path.Join(root, "index.html")
var files []string
for _, name := range names {
if path.Dir(name) == root && name != index && strings.EqualFold(path.Ext(name), ".html") {
files = append(files, name)
}
}
if len(files) == 0 {
return nil, nil, ErrNoConfluence
}
if len(files) > maxNotionPages {
return nil, nil, fmt.Errorf("the export has more than %d pages", maxNotionPages)
}
// The page tree from index.html: each listed page's parent and order.
parentFile := map[string]string{}
order := map[string]int{}
if raw, err := n.read(n.files[index]); err == nil {
if doc, err := html.Parse(bytes.NewReader(raw)); err == nil {
seq := 0
var walk func(el *html.Node, parent string)
walk = func(el *html.Node, parent string) {
for c := el.FirstChild; c != nil; c = c.NextSibling {
if c.Type != html.ElementNode {
continue
}
if c.DataAtom == atom.Li {
self := ""
for a := c.FirstChild; a != nil; a = a.NextSibling {
if a.Type == html.ElementNode && a.DataAtom == atom.A {
self = pageFileOf(root, attrOf(a, "href"))
break
}
}
if self != "" {
if _, seen := order[self]; !seen {
order[self], parentFile[self] = seq, parent
seq++
}
walk(c, self)
continue
}
}
walk(c, parent)
}
}
walk(doc, "")
}
}
type page struct {
file string
doc *html.Node
title string
parent string
}
pages := make([]*page, 0, len(files))
byFile := map[string]*page{}
for _, f := range files {
raw, err := n.read(n.files[f])
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", f, err)
}
if !utf8.Valid(raw) {
return nil, nil, fmt.Errorf("%s is not UTF-8 text", f)
}
doc, err := html.Parse(bytes.NewReader(raw))
if err != nil {
return nil, nil, fmt.Errorf("%s could not be read: %w", f, err)
}
p := &page{file: f, doc: doc, title: confluenceTitle(doc)}
if parent, ok := parentFile[f]; ok {
p.parent = parent
} else {
p.parent = breadcrumbParent(doc, root, index)
}
pages = append(pages, p)
byFile[f] = p
}
// A parent that is not in the export, or a loop, puts the page at the top.
depth := map[string]int{}
var depthOf func(f string, seen map[string]bool) int
depthOf = func(f string, seen map[string]bool) int {
if d, ok := depth[f]; ok {
return d
}
p := byFile[f]
if p.parent == "" || byFile[p.parent] == nil || seen[p.parent] {
p.parent = ""
depth[f] = 0
return 0
}
seen[f] = true
d := depthOf(p.parent, seen) + 1
depth[f] = d
return d
}
for _, p := range pages {
depthOf(p.file, map[string]bool{})
}
sort.SliceStable(pages, func(i, j int) bool {
a, b := pages[i], pages[j]
if depth[a.file] != depth[b.file] {
return depth[a.file] < depth[b.file]
}
oa, okA := order[a.file]
ob, okB := order[b.file]
if okA != okB {
return okA
}
if oa != ob {
return oa < ob
}
return a.file < b.file
})
for i, p := range pages {
n.pageAt[p.file] = i
}
out := make([]NotionPage, len(pages))
for i, p := range pages {
body := confluenceBody(p.doc)
var buf bytes.Buffer
if err := html.Render(&buf, body); err != nil {
return nil, nil, err
}
opts := ImportOptions{Resolve: func(u string) (string, bool) { return n.resolve(root, u) }}
doc, err := FromHTMLWith(buf.String(), opts)
if err != nil {
return nil, nil, fmt.Errorf("%s could not be read: %w", p.file, err)
}
if n.err != nil {
return nil, nil, n.err
}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
}
parent := -1
if p.parent != "" {
parent = n.pageAt[p.parent]
}
title := p.title
if title == "" {
title = strings.TrimSuffix(path.Base(p.file), path.Ext(p.file))
}
out[i] = NotionPage{Title: title, Parent: parent, Doc: doc}
}
return out, n.assets, nil
}
// pageFileOf is the page file a relative link in the export points to.
func pageFileOf(root, href string) string {
if href == "" || strings.Contains(href, ":") || strings.HasPrefix(href, "#") || strings.HasPrefix(href, "/") {
return ""
}
if i := strings.IndexAny(href, "?#"); i >= 0 {
href = href[:i]
}
if !strings.EqualFold(path.Ext(href), ".html") || strings.Contains(href, "/") {
return ""
}
return path.Join(root, href)
}
// confluenceTitle is the page title without the space name before it.
func confluenceTitle(doc *html.Node) string {
t := ""
if el := byID(doc, "title-text"); el != nil {
t = textOf(el)
} else if el := find(doc, atom.Title); el != nil {
t = textOf(el)
}
t = strings.Join(strings.Fields(t), " ")
if i := strings.Index(t, " : "); i >= 0 {
t = t[i+3:]
}
return t
}
// breadcrumbParent is the last page in the breadcrumbs (the parent), if any.
func breadcrumbParent(doc *html.Node, root, index string) string {
bc := byID(doc, "breadcrumbs")
if bc == nil {
return ""
}
last := ""
var walk func(*html.Node)
walk = func(el *html.Node) {
for c := el.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.DataAtom == atom.A {
if f := pageFileOf(root, attrOf(c, "href")); f != "" && f != index {
last = f
}
}
walk(c)
}
}
walk(bc)
return last
}
func byID(n *html.Node, id string) *html.Node {
if n.Type == html.ElementNode && attrOf(n, "id") == id {
return n
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if found := byID(c, id); found != nil {
return found
}
}
return nil
}
// confluenceBody is the page's content, cleaned of Confluence's macro
// markup, with its attachments listed at the end.
func confluenceBody(doc *html.Node) *html.Node {
main := byID(doc, "main-content")
if main == nil {
if main = find(doc, atom.Body); main == nil {
main = doc
}
}
out := &html.Node{Type: html.ElementNode, Data: "div", DataAtom: atom.Div}
for c := main.FirstChild; c != nil; {
next := c.NextSibling
main.RemoveChild(c)
out.AppendChild(c)
c = next
}
cleanConfluence(out)
if files := attachmentLinks(doc); len(files) > 0 {
out.AppendChild(element("h2", atom.H2, nil, textNode("Attachments")))
list := element("ul", atom.Ul, nil)
for _, a := range files {
list.AppendChild(element("li", atom.Li, nil, element("a", atom.A, []html.Attribute{{Key: "href", Val: a.href}}, textNode(a.name))))
}
out.AppendChild(list)
}
return out
}
type fileLink struct{ href, name string }
// attachmentLinks are the files in the page's Attachments section.
func attachmentLinks(doc *html.Node) []fileLink {
h := byID(doc, "attachments")
if h == nil {
return nil
}
// The section is the header's enclosing .pageSection.
sec := h.Parent
for sec != nil && (sec.Type != html.ElementNode || !hasClass(sec, "pageSection")) {
sec = sec.Parent
}
if sec == nil {
return nil
}
var out []fileLink
seen := map[string]bool{}
var walk func(*html.Node)
walk = func(el *html.Node) {
for c := el.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.DataAtom == atom.A {
href := attrOf(c, "href")
if strings.HasPrefix(href, "attachments/") && !seen[href] {
seen[href] = true
name := strings.TrimSpace(textOf(c))
if name == "" {
name = path.Base(href)
}
out = append(out, fileLink{href: href, name: name})
}
}
walk(c)
}
}
walk(sec)
return out
}
var brushParam = regexp.MustCompile(`(?:^|;)\s*brush:\s*([A-Za-z0-9_+#.-]+)`)
// confluenceLanguages maps Confluence's code brushes to editor languages.
var confluenceLanguages = map[string]string{
"js": "javascript", "jscript": "javascript", "py": "python", "sh": "bash", "shell": "bash", "ps": "powershell",
"c#": "csharp", "csharp": "csharp", "cpp": "cpp", "c++": "cpp", "text": "", "plain": "", "none": "", "xml": "xml",
"html": "html", "yml": "yaml", "rb": "ruby", "ts": "typescript", "golang": "go",
}
// calloutKinds are Confluence's information macros as callout emoji and colour.
var calloutKinds = map[string][2]string{
"confluence-information-macro-information": {"ℹ️", "blue"},
"confluence-information-macro-note": {"📝", "yellow"},
"confluence-information-macro-tip": {"✅", "green"},
"confluence-information-macro-warning": {"⚠️", "red"},
}
// cleanConfluence rewrites Confluence's markup under el into plain HTML.
func cleanConfluence(el *html.Node) {
for c := el.FirstChild; c != nil; {
next := c.NextSibling
if c.Type == html.ElementNode {
if repl := confluenceNode(c); repl != c {
if repl == nil {
el.RemoveChild(c)
} else {
el.InsertBefore(repl, c)
el.RemoveChild(c)
cleanConfluence(repl)
}
c = next
continue
}
cleanConfluence(c)
}
c = next
}
}
// confluenceNode returns the replacement for one element: itself when it
// stays, nil to drop it.
func confluenceNode(c *html.Node) *html.Node {
switch {
case hasClass(c, "confluence-information-macro"):
emoji, color := "💡", "gray"
for _, cls := range strings.Fields(attrOf(c, "class")) {
if k, ok := calloutKinds[cls]; ok {
emoji, color = k[0], k[1]
}
}
body := element("div", atom.Div, []html.Attribute{{Key: "class", Val: "callout-body"}})
if t := childWithClass(c, "title"); t != nil {
body.AppendChild(element("p", atom.P, nil, element("strong", atom.Strong, nil, textNode(strings.TrimSpace(textOf(t))))))
}
src := childWithClass(c, "confluence-information-macro-body")
if src == nil {
src = c
}
moveChildren(src, body)
return element("aside", atom.Aside, []html.Attribute{{Key: "data-type", Val: "callout"}, {Key: "data-emoji", Val: emoji}, {Key: "data-color", Val: color}}, body)
case hasClass(c, "confluence-embedded-file-wrapper"):
// The picture (or file link) itself, without the wrapper.
if img := find(c, atom.Img); img != nil {
img.Parent.RemoveChild(img)
// A thumbnail becomes the full picture.
return confluenceNode(img)
}
return c
case hasClass(c, "panel") && c.DataAtom == atom.Div && !hasClass(c, "code"):
body := element("div", atom.Div, []html.Attribute{{Key: "class", Val: "callout-body"}})
if t := childWithClass(c, "panelHeader"); t != nil && strings.TrimSpace(textOf(t)) != "" {
body.AppendChild(element("p", atom.P, nil, element("strong", atom.Strong, nil, textNode(strings.TrimSpace(textOf(t))))))
}
src := childWithClass(c, "panelContent")
if src == nil {
src = c
}
moveChildren(src, body)
return element("aside", atom.Aside, []html.Attribute{{Key: "data-type", Val: "callout"}, {Key: "data-emoji", Val: "📌"}, {Key: "data-color", Val: "gray"}}, body)
case c.DataAtom == atom.Pre && (hasClass(c, "syntaxhighlighter-pre") || attrOf(c, "data-syntaxhighlighter-params") != ""):
lang := ""
if m := brushParam.FindStringSubmatch(attrOf(c, "data-syntaxhighlighter-params")); m != nil {
lang = strings.ToLower(m[1])
if l, ok := confluenceLanguages[lang]; ok {
lang = l
}
}
code := element("code", atom.Code, nil, textNode(textOf(c)))
if lang != "" {
code.Attr = []html.Attribute{{Key: "class", Val: "language-" + lang}}
}
return element("pre", atom.Pre, nil, code)
case hasClass(c, "expand-container"):
title := "Details"
if t := childWithClass(c, "expand-control-text"); t != nil && strings.TrimSpace(textOf(t)) != "" {
title = strings.TrimSpace(textOf(t))
}
d := element("details", atom.Details, nil, element("summary", atom.Summary, nil, textNode(title)))
if body := childWithClass(c, "expand-content"); body != nil {
moveChildren(body, d)
}
return d
case c.DataAtom == atom.Ul && hasClass(c, "inline-task-list"):
c.Attr = append(c.Attr, html.Attribute{Key: "data-type", Val: "taskList"})
for li := c.FirstChild; li != nil; li = li.NextSibling {
if li.Type == html.ElementNode && li.DataAtom == atom.Li {
checked := "false"
if hasClass(li, "checked") {
checked = "true"
}
li.Attr = append(li.Attr, html.Attribute{Key: "data-type", Val: "taskItem"}, html.Attribute{Key: "data-checked", Val: checked})
}
}
return c
case c.DataAtom == atom.Img && hasClass(c, "emoticon"):
alt := attrOf(c, "data-emoji-fallback")
if alt == "" {
alt = attrOf(c, "alt")
}
if alt == "" {
return nil
}
return textNode(alt)
case c.DataAtom == atom.Img && attrOf(c, "data-image-src") != "" && !strings.HasPrefix(attrOf(c, "src"), "attachments/"):
// Thumbnails point at the full picture through data-image-src.
src := attrOf(c, "data-image-src")
if i := strings.Index(src, "attachments/"); i >= 0 {
src = src[i:]
}
setAttr(c, "src", src)
return c
case hasClass(c, "status-macro") || hasClass(c, "aui-lozenge"):
return element("strong", atom.Strong, nil, textNode(strings.ToUpper(strings.TrimSpace(textOf(c)))))
case hasClass(c, "confluence-userlink") || hasClass(c, "user-mention"):
return textNode("@" + strings.TrimSpace(textOf(c)))
case attrOf(c, "id") == "likes-and-labels-container" || hasClass(c, "page-metadata") || hasClass(c, "plugin_pagetree") ||
c.DataAtom == atom.Script || c.DataAtom == atom.Style:
return nil
}
return c
}
func childWithClass(n *html.Node, class string) *html.Node {
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type != html.ElementNode {
continue
}
if hasClass(c, class) {
return c
}
if found := childWithClass(c, class); found != nil {
return found
}
}
return nil
}
func moveChildren(from, to *html.Node) {
for c := from.FirstChild; c != nil; {
next := c.NextSibling
from.RemoveChild(c)
to.AppendChild(c)
c = next
}
}
func element(tag string, a atom.Atom, attrs []html.Attribute, children ...*html.Node) *html.Node {
el := &html.Node{Type: html.ElementNode, Data: tag, DataAtom: a, Attr: attrs}
for _, c := range children {
if c.Parent != nil {
c.Parent.RemoveChild(c)
}
el.AppendChild(c)
}
return el
}
func textNode(s string) *html.Node { return &html.Node{Type: html.TextNode, Data: s} }
func setAttr(n *html.Node, key, val string) {
for i := range n.Attr {
if n.Attr[i].Key == key {
n.Attr[i].Val = val
return
}
}
n.Attr = append(n.Attr, html.Attribute{Key: key, Val: val})
}
+176
View File
@@ -0,0 +1,176 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"errors"
"strings"
"testing"
)
func confluenceZip(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, body := range files {
w, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
_, _ = w.Write([]byte(body))
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func confluencePage(title, crumbs, main, after string) string {
return `<!DOCTYPE html><html><head><title>DOCS : ` + title + `</title></head><body><div id="page"><div id="main">
<div id="main-header"><div id="breadcrumb-section"><ol id="breadcrumbs"><li class="first"><span><a href="index.html">Docs</a></span></li>` + crumbs + `</ol></div>
<h1 id="title-heading" class="pagetitle"><span id="title-text"> Docs : ` + title + ` </span></h1></div>
<div id="content" class="view"><div class="page-metadata">Created by Ann, last modified on Nov 02, 2026</div>
<div id="main-content" class="wiki-content group">` + main + `</div>` + after + `</div></div></div></body></html>`
}
func findNodes(n Node, typ string) []Node {
var out []Node
if n.Type == typ {
out = append(out, n)
}
for _, c := range n.Content {
out = append(out, findNodes(c, typ)...)
}
return out
}
func plain(n Node) string {
if n.Type == "text" {
return n.Text
}
var b strings.Builder
for _, c := range n.Content {
b.WriteString(plain(c))
}
return b.String()
}
func linkTargets(n Node) []string {
var out []string
for _, m := range n.Marks {
if m.Type == "link" {
out = append(out, m.Attrs["href"].(string))
}
}
for _, c := range n.Content {
out = append(out, linkTargets(c)...)
}
return out
}
func TestReadConfluence(t *testing.T) {
home := confluencePage("Home", "", `
<div class="confluence-information-macro confluence-information-macro-information"><p class="title">Read me</p>
<span class="aui-icon confluence-information-macro-icon"></span>
<div class="confluence-information-macro-body"><p>Start <a href="Child_2.html">here</a>.</p></div></div>
<div class="code panel pdl"><div class="codeContent panelContent pdl">
<pre class="syntaxhighlighter-pre" data-syntaxhighlighter-params="brush: java; gutter: false" data-theme="Confluence">class A {}
</pre></div></div>
<div id="expander-1" class="expand-container"><div class="expand-control"><span class="expand-control-text">More</span></div>
<div class="expand-content"><p>Hidden text</p></div></div>
<ul class="inline-task-list"><li class="checked" data-inline-task-id="1"><span>Done thing</span></li><li data-inline-task-id="2"><span>Open thing</span></li></ul>
<p>State: <span class="status-macro aui-lozenge aui-lozenge-success">done</span> <img class="emoticon emoticon-smile" alt="(smile)" data-emoji-fallback="🙂" src="images/icons/emoticons/smile.svg">
by <a href="/display/~ann" class="confluence-userlink user-mention">Ann Lee</a></p>
<p><span class="confluence-embedded-file-wrapper"><img class="confluence-embedded-image" src="https://docs.example/download/thumbnails/1/pic.png" data-image-src="/download/attachments/1/pic.png"></span></p>`,
`<div class="pageSection group"><div class="pageSectionHeader"><h2 id="attachments" class="pageSectionTitle">Attachments:</h2></div>
<div class="greybox" align="left"><img src="images/icons/bullet_blue.gif"> <a href="attachments/1/spec.pdf">spec.pdf</a> (application/pdf)<br/>
<img src="images/icons/bullet_blue.gif"> <a href="attachments/1/pic.png">pic.png</a> (image/png)<br/></div></div>`)
files := map[string]string{
"DOCS/index.html": `<html><body><div id="main-content"><div class="pageSection"><h2>Available Pages:</h2>
<ul><li><a href="Home_1.html">Home</a><ul><li><a href="Child_2.html">Child</a><ul><li><a href="Grandchild_3.html">Grandchild</a></li></ul></li></ul></li></ul></div></div></body></html>`,
"DOCS/styles/site.css": "body{}",
"DOCS/Home_1.html": home,
"DOCS/Child_2.html": confluencePage("Child", `<li><a href="Home_1.html">Home</a></li>`, `<p>Child body</p>`, ""),
"DOCS/Grandchild_3.html": confluencePage("Grandchild", "", `<p>Deep</p>`, ""),
// Left out of index.html: its breadcrumbs name the parent.
"DOCS/Orphan_4.html": confluencePage("Orphan", `<li><a href="Home_1.html">Home</a></li>`, `<p>Lost</p>`, ""),
"DOCS/attachments/1/pic.png": "PNG",
"DOCS/attachments/1/spec.pdf": "%PDF",
}
data := confluenceZip(t, files)
if kind, err := DetectArchive(data); err != nil || kind != VaultConfluence {
t.Fatalf("detected %q, %v", kind, err)
}
pages, assets, err := ReadConfluence(data)
if err != nil {
t.Fatal(err)
}
var got []string
for _, p := range pages {
parent := "-"
if p.Parent >= 0 {
parent = pages[p.Parent].Title
}
got = append(got, p.Title+"<"+parent)
}
if strings.Join(got, ", ") != "Home<-, Child<Home, Orphan<Home, Grandchild<Child" {
t.Fatalf("pages %v", got)
}
doc := pages[0].Doc
callouts := findNodes(doc, "callout")
if len(callouts) != 1 || callouts[0].Attrs["emoji"] != "ℹ️" || callouts[0].Attrs["color"] != "blue" ||
!strings.Contains(plain(callouts[0]), "Read me") || !strings.Contains(plain(callouts[0]), "Start here.") {
t.Errorf("callout %+v", callouts)
}
if links := linkTargets(callouts[0]); len(links) != 1 || links[0] != PageRef(1) {
t.Errorf("page link %v", links)
}
code := findNodes(doc, "codeBlock")
if len(code) != 1 || code[0].Attrs["language"] != "java" || plain(code[0]) != "class A {}" {
t.Errorf("code %+v", code)
}
if d := findNodes(doc, "details"); len(d) != 1 || !strings.Contains(plain(d[0]), "More") || !strings.Contains(plain(d[0]), "Hidden text") {
t.Errorf("expand %+v", d)
}
tasks := findNodes(doc, "taskItem")
if len(tasks) != 2 || tasks[0].Attrs["checked"] != true || tasks[1].Attrs["checked"] != false || plain(tasks[1]) != "Open thing" {
t.Errorf("tasks %+v", tasks)
}
text := plain(doc)
for _, want := range []string{"State: DONE 🙂 by @Ann Lee", "Attachments"} {
if !strings.Contains(text, want) {
t.Errorf("text lacks %q:\n%s", want, text)
}
}
imgs := findNodes(doc, "image")
if len(imgs) != 1 || !strings.HasPrefix(imgs[0].Attrs["src"].(string), "asset:") {
t.Errorf("images %+v", imgs)
}
// The attachment list links both files; the picture is one asset, not two.
if len(assets) != 2 {
t.Errorf("assets %d", len(assets))
}
names := map[string]bool{}
for _, a := range assets {
names[a.Name] = true
}
if !names["pic.png"] || !names["spec.pdf"] {
t.Errorf("asset names %v", names)
}
lists := findNodes(doc, "bulletList")
if last := lists[len(lists)-1]; len(linkTargets(last)) != 2 {
t.Errorf("attachment list %+v", last)
}
// A zip of HTML pages without Confluence's layout is not Confluence.
other := confluenceZip(t, map[string]string{"a.html": "<p>x</p>"})
if kind, _ := DetectArchive(other); kind == VaultConfluence {
t.Error("plain HTML zip detected as Confluence")
}
if _, _, err := ReadConfluence(other); !errors.Is(err, ErrNoConfluence) {
t.Errorf("plain zip: %v", err)
}
}
+7
View File
@@ -51,6 +51,13 @@ func DetectArchive(data []byte) (VaultKind, error) {
if err != nil {
return "", fmt.Errorf("not a zip file: %w", err)
}
names := make([]string, 0, len(zr.File))
for _, f := range zr.File {
names = append(names, path.Clean(strings.TrimPrefix(strings.ReplaceAll(f.Name, "\\", "/"), "/")))
}
if isConfluence(names) {
return VaultConfluence, nil
}
notion, markdown := 0, 0
kind := VaultMarkdown
for _, f := range zr.File {
+110
View File
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"strings"
"unicode/utf8"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/convert"
"docwell/server/internal/store/pocketbase"
)
// ---- What chat integrations (Slack) need from the directory ------------------
// ChatPage is a page as a chat app may show it: only pages every member of
// the workspace can open (see OpenToMembers).
type ChatPage struct {
ID string
Workspace string
Title string
Icon string
SpaceName string
URL string
// Excerpt is the start of the page's text, one line.
Excerpt string
}
// OpenToMembers returns the page when everyone in workspace wsID can open
// it: it is not deleted, its space is open (not private, not a journal),
// and neither it nor a page above it is restricted. Anything else is
// reported as not shared, so a chat channel never shows what some members
// of the workspace could not read.
func (s *Service) OpenToMembers(ctx context.Context, wsID, pageID string) (ChatPage, bool) {
if !validID(pageID) {
return ChatPage{}, false
}
p, err := s.getPage(ctx, pageID)
if err != nil || p.Workspace != wsID || p.DeletedAt != "" {
return ChatPage{}, false
}
sp, err := pocketbase.Get[spaceRecord](ctx, s.pb, "spaces", p.Space)
if err != nil || sp.Visibility != "open" || sp.JournalOwner != "" {
return ChatPage{}, false
}
// The chain up to the space root; a cycle or a missing parent stops it.
seen := map[string]bool{}
for cur := p; ; {
if cur.Restricted {
return ChatPage{}, false
}
if cur.Parent == "" || seen[cur.Parent] {
break
}
seen[cur.ID] = true
next, err := s.getPage(ctx, cur.Parent)
if err != nil {
return ChatPage{}, false
}
cur = next
}
out := ChatPage{
ID: p.ID, Workspace: p.Workspace, Title: p.Title, Icon: p.Icon, SpaceName: sp.Name,
URL: strings.TrimRight(s.mailer.WebURL, "/") + "/p/" + p.ID,
}
if doc, err := s.docs.Content(ctx, p.ID); err == nil {
if node, err := convert.Parse(doc); err == nil {
out.Excerpt = chatExcerpt(convert.Markdown(node, convert.Options{}), 240)
}
}
return out, true
}
// chatExcerpt is the start of Markdown as one line of plain-ish text.
func chatExcerpt(md string, n int) string {
var parts []string
for _, line := range strings.Split(md, "\n") {
line = strings.TrimSpace(strings.TrimLeft(strings.TrimSpace(line), "#>*-+ "))
if line != "" && !strings.HasPrefix(line, "```") && !strings.HasPrefix(line, "|") {
parts = append(parts, line)
}
if len(parts) > 6 {
break
}
}
s := strings.Join(strings.Fields(strings.Join(parts, " ")), " ")
if utf8.RuneCountInString(s) <= n {
return s
}
return strings.TrimSpace(string([]rune(s)[:n-1])) + "…"
}
// MemberByEmail is the member of workspace wsID with this email, as a caller
// for work done on their behalf (a search from a chat app).
func (s *Service) MemberByEmail(ctx context.Context, wsID, email string) (access.Caller, error) {
u, err := s.findUserByEmail(ctx, email)
if err != nil {
return access.Caller{}, err
}
if u.Status == "disabled" {
return access.Caller{}, apperr.Forbidden("the account is disabled")
}
c := u.Caller()
if _, err := s.WorkspaceRole(ctx, c, wsID); err != nil {
return access.Caller{}, err
}
return c, nil
}
+6 -3
View File
@@ -385,13 +385,16 @@ func readImport(f ImportFile) (importBatch, error) {
var pages []convert.NotionPage
var assets []convert.Asset
var err error
if kind == convert.VaultNotion {
switch kind {
case convert.VaultNotion:
pages, assets, err = convert.ReadNotion(f.Data)
} else {
case convert.VaultConfluence:
pages, assets, err = convert.ReadConfluence(f.Data)
default:
pages, assets, err = convert.ReadVault(f.Data, kind)
}
switch {
case errors.Is(err, convert.ErrNotNotion), errors.Is(err, convert.ErrNoNotes):
case errors.Is(err, convert.ErrNotNotion), errors.Is(err, convert.ErrNoNotes), errors.Is(err, convert.ErrNoConfluence):
return bad(" holds no Markdown, HTML or CSV pages.")
case errors.Is(err, convert.ErrTooLarge):
return bad(" unpacks to more than 512 MB, or holds a file larger than 50 MB.")
+4 -1
View File
@@ -73,7 +73,9 @@ type api struct {
oauth OAuthCallbacks
onenote OneNoteService
readwise ReadwiseService
log *slog.Logger
// wsIntegrations: GitHub, Linear, Figma and Slack per workspace.
wsIntegrations WorkspaceIntegrations
log *slog.Logger
}
// requireUser lets in a signed-in user, or an API token acting as its owner
@@ -231,6 +233,7 @@ func (a *api) routes(mux *routeMux) {
a.aiRoutes(mux)
a.calendarRoutes(mux)
a.integrationRoutes(mux)
a.wsIntegrationRoutes(mux)
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
+6
View File
@@ -30,6 +30,12 @@ func (a *api) linkRoutes(mux *routeMux) {
a.respond(w, nil, apperr.NotFound("link previews are off"))
return
}
// With a workspace, its tokens reach private GitHub, Linear and Figma items.
if ws := r.URL.Query().Get("workspace"); ws != "" && a.wsIntegrations != nil {
p, err := a.wsIntegrations.Preview(r.Context(), caller(r), ws, r.URL.Query().Get("url"))
a.respond(w, p, err)
return
}
p, err := a.previews.Preview(r.Context(), r.URL.Query().Get("url"))
a.respond(w, p, err)
}))
+8 -2
View File
@@ -49,8 +49,11 @@ type Deps struct {
OAuth OAuthCallbacks
OneNote OneNoteService
Readwise ReadwiseService
Admin http.Handler
Log *slog.Logger
// Integrations connects workspaces to GitHub, Linear, Figma and Slack;
// nil turns them off (link previews then read public data only).
Integrations WorkspaceIntegrations
Admin http.Handler
Log *slog.Logger
}
// routeMux is a ServeMux that remembers its patterns, so a test can compare
@@ -100,6 +103,9 @@ func newMux(d Deps) *routeMux {
if d.Readwise != nil {
a.readwise = d.Readwise
}
if d.Integrations != nil {
a.wsIntegrations = d.Integrations
}
a.routes(mux)
a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
a.collabRoute(mux, d.CORSOrigins)
+95
View File
@@ -0,0 +1,95 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"net/http"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/integrations"
"docwell/server/internal/unfurl"
)
// WorkspaceIntegrations connects a workspace to GitHub, Linear, Figma and
// Slack (integrations.Service).
type WorkspaceIntegrations interface {
Get(ctx context.Context, c access.Caller, wsID string) (integrations.View, error)
SetToken(ctx context.Context, c access.Caller, wsID, service, token string) (integrations.View, error)
SetSlack(ctx context.Context, c access.Caller, wsID string, in integrations.SlackInput) (integrations.View, error)
DeleteSlack(ctx context.Context, c access.Caller, wsID string) (integrations.View, error)
TestSlack(ctx context.Context, c access.Caller, wsID string) error
Preview(ctx context.Context, c access.Caller, wsID, url string) (unfurl.Preview, error)
Events(w http.ResponseWriter, r *http.Request, wsID string)
Commands(w http.ResponseWriter, r *http.Request, wsID string)
}
var errNoWsIntegrations = apperr.NotFound("integrations are off on this server")
func (a *api) wsIntegrationRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/workspaces/{id}/integrations", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
a.respond(w, nil, errNoWsIntegrations)
return
}
v, err := a.wsIntegrations.Get(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, v, err)
}))
mux.HandleFunc("PUT /api/v1/workspaces/{id}/integrations/tokens/{service}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
a.respond(w, nil, errNoWsIntegrations)
return
}
var in struct {
Token string `json:"token"`
}
if !a.decode(w, r, &in) {
return
}
v, err := a.wsIntegrations.SetToken(r.Context(), caller(r), r.PathValue("id"), r.PathValue("service"), in.Token)
a.respond(w, v, err)
}))
mux.HandleFunc("PUT /api/v1/workspaces/{id}/integrations/slack", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
a.respond(w, nil, errNoWsIntegrations)
return
}
var in integrations.SlackInput
if !a.decode(w, r, &in) {
return
}
v, err := a.wsIntegrations.SetSlack(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, v, err)
}))
mux.HandleFunc("DELETE /api/v1/workspaces/{id}/integrations/slack", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
a.respond(w, nil, errNoWsIntegrations)
return
}
v, err := a.wsIntegrations.DeleteSlack(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, v, err)
}))
mux.HandleFunc("POST /api/v1/workspaces/{id}/integrations/slack/test", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
a.respond(w, nil, errNoWsIntegrations)
return
}
a.respondNoContent(w, a.wsIntegrations.TestSlack(r.Context(), caller(r), r.PathValue("id")))
}))
// Called by Slack, which signs every request (integrations.verify).
mux.HandleFunc("POST /api/v1/slack/{workspace}/events", func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
http.NotFound(w, r)
return
}
a.wsIntegrations.Events(w, r, r.PathValue("workspace"))
})
mux.HandleFunc("POST /api/v1/slack/{workspace}/commands", func(w http.ResponseWriter, r *http.Request) {
if a.wsIntegrations == nil {
http.NotFound(w, r)
return
}
a.wsIntegrations.Commands(w, r, r.PathValue("workspace"))
})
}
@@ -0,0 +1,397 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package integrations connects a workspace to outside services (ADR-18):
// tokens that let link previews read private GitHub, Linear and Figma items,
// and a Slack app that gets page and comment news in a channel, previews of
// Docwell links, and a /docwell search command. One record per workspace
// holds it all; tokens are sealed with the server secret, and only
// workspace admins see or change them.
package integrations
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strings"
"sync"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/directory"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/unfurl"
)
const collection = "workspace_integrations"
// Directory is what the service needs from directory.Service.
type Directory interface {
WorkspaceRole(ctx context.Context, c access.Caller, wsID string) (string, error)
OpenToMembers(ctx context.Context, wsID, pageID string) (directory.ChatPage, bool)
MemberByEmail(ctx context.Context, wsID, email string) (access.Caller, error)
Search(ctx context.Context, c access.Caller, wsID string, q directory.SearchQuery) (directory.SearchResult, error)
}
// Options configure the service.
type Options struct {
// Secret seals the tokens (the server secret).
Secret string
// WebURL is where people open Docwell; Slack links and request URLs use it.
WebURL string
// APIs and SlackAPI point at the real services unless set (tests).
APIs *unfurl.APIs
SlackAPI string
// Client calls the services; nil makes one with a timeout.
Client *http.Client
Log *slog.Logger
}
type Service struct {
pb *pocketbase.Client
dir Directory
previews *unfurl.Fetcher
apis unfurl.APIs
slackAPI string
webURL string
client *http.Client
aead cipher.AEAD
log *slog.Logger
// recent remembers page.updated posts, so a page being edited is posted
// once in a while rather than on every save.
mu sync.Mutex
recent map[string]time.Time
}
// New makes the service. previews reads link previews (unfurl.New()).
func New(pb *pocketbase.Client, dir Directory, previews *unfurl.Fetcher, o Options) *Service {
key := sha256.Sum256([]byte("docwell-integrations:" + o.Secret))
block, _ := aes.NewCipher(key[:])
aead, _ := cipher.NewGCM(block)
s := &Service{
pb: pb, dir: dir, previews: previews, apis: unfurl.DefaultAPIs, slackAPI: "https://slack.com/api",
webURL: strings.TrimRight(o.WebURL, "/"), client: o.Client, aead: aead, log: o.Log, recent: map[string]time.Time{},
}
if o.APIs != nil {
s.apis = *o.APIs
if previews != nil {
s.previews = previews.WithAPIs(*o.APIs)
}
}
if o.SlackAPI != "" {
s.slackAPI = strings.TrimRight(o.SlackAPI, "/")
}
if s.client == nil {
s.client = &http.Client{Timeout: 10 * time.Second}
}
if s.log == nil {
s.log = slog.Default()
}
return s
}
// ---- Sealing ---------------------------------------------------------------
func (s *Service) seal(plain string) string {
if plain == "" {
return ""
}
nonce := make([]byte, s.aead.NonceSize())
_, _ = rand.Read(nonce)
return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil))
}
var errUnreadable = errors.New("a stored token cannot be decrypted (the server secret changed); enter it again")
func (s *Service) open(sealed string) (string, error) {
if sealed == "" {
return "", nil
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:"))
n := s.aead.NonceSize()
if err != nil || len(raw) < n {
return "", errUnreadable
}
plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil)
if err != nil {
return "", errUnreadable
}
return string(plain), nil
}
// ---- The record ------------------------------------------------------------
type record struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
GitHub string `json:"github"`
Linear string `json:"linear"`
Figma string `json:"figma"`
SlackBot string `json:"slack_bot"`
SlackSigning string `json:"slack_signing"`
SlackTeam string `json:"slack_team"`
SlackTeamName string `json:"slack_team_name"`
SlackChannel string `json:"slack_channel"`
SlackChannelName string `json:"slack_channel_name"`
SlackEvents []string `json:"slack_events"`
SlackUnfurl bool `json:"slack_unfurl"`
SlackSearch bool `json:"slack_search"`
SlackError string `json:"slack_error"`
}
func (s *Service) find(ctx context.Context, wsID string) (*record, error) {
res, err := pocketbase.List[record](ctx, s.pb, collection, pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("workspace = '%s'", wsID)})
if err != nil {
return nil, err
}
if len(res.Items) == 0 {
return nil, nil
}
return &res.Items[0], nil
}
// save writes fields into the workspace's record, making it when needed.
func (s *Service) save(ctx context.Context, wsID string, r *record, body map[string]any) (*record, error) {
if r == nil {
body["workspace"] = wsID
out, err := pocketbase.Create[record](ctx, s.pb, collection, body)
return &out, err
}
out, err := pocketbase.Update[record](ctx, s.pb, collection, r.ID, body)
return &out, err
}
func (s *Service) requireAdmin(ctx context.Context, c access.Caller, wsID string) error {
if wsID == "" {
return apperr.NotFound("workspace not found")
}
role, err := s.dir.WorkspaceRole(ctx, c, wsID)
if err != nil {
return err
}
if !access.AtLeast(role, access.WorkspaceAdmin) {
return apperr.Forbidden("workspace admin role required")
}
return nil
}
// ---- What workspace settings show -----------------------------------------
// Token says whether a service's token is stored.
type Token struct {
Set bool `json:"set"`
}
// Slack is the workspace's Slack connection as its settings show it.
type Slack struct {
Connected bool `json:"connected"`
HasSigning bool `json:"hasSigningSecret"`
Team string `json:"team"`
TeamName string `json:"teamName"`
Channel string `json:"channel"`
ChannelName string `json:"channelName"`
Events []string `json:"events"`
Unfurl bool `json:"unfurl"`
Search bool `json:"search"`
LastError string `json:"lastError"`
// EventsURL and CommandsURL go into the Slack app's settings; Manifest
// makes such an app in one step (api.slack.com/apps → From a manifest).
EventsURL string `json:"eventsUrl"`
CommandsURL string `json:"commandsUrl"`
Manifest string `json:"manifest"`
}
// View is a workspace's integrations.
type View struct {
GitHub Token `json:"github"`
Linear Token `json:"linear"`
Figma Token `json:"figma"`
Slack Slack `json:"slack"`
}
func (s *Service) view(wsID string, r *record) View {
v := View{Slack: Slack{
EventsURL: s.webURL + "/api/v1/slack/" + wsID + "/events",
CommandsURL: s.webURL + "/api/v1/slack/" + wsID + "/commands",
Events: DefaultSlackEvents,
}}
v.Slack.Manifest = s.manifest(v.Slack.EventsURL, v.Slack.CommandsURL)
if r == nil {
return v
}
v.GitHub.Set, v.Linear.Set, v.Figma.Set = r.GitHub != "", r.Linear != "", r.Figma != ""
v.Slack.Connected = r.SlackBot != ""
v.Slack.HasSigning = r.SlackSigning != ""
v.Slack.Team, v.Slack.TeamName = r.SlackTeam, r.SlackTeamName
v.Slack.Channel, v.Slack.ChannelName = r.SlackChannel, r.SlackChannelName
if r.SlackEvents != nil {
v.Slack.Events = r.SlackEvents
}
v.Slack.Unfurl, v.Slack.Search, v.Slack.LastError = r.SlackUnfurl, r.SlackSearch, r.SlackError
return v
}
// Get returns a workspace's integrations (workspace admins).
func (s *Service) Get(ctx context.Context, c access.Caller, wsID string) (View, error) {
if err := s.requireAdmin(ctx, c, wsID); err != nil {
return View{}, err
}
r, err := s.find(ctx, wsID)
if err != nil {
return View{}, err
}
return s.view(wsID, r), nil
}
// ---- Tokens for link previews ----------------------------------------------
// Services whose tokens SetToken takes.
const (
GitHub = "github"
Linear = "linear"
Figma = "figma"
)
// SetToken checks a token with its service and stores it; an empty token
// removes the stored one.
func (s *Service) SetToken(ctx context.Context, c access.Caller, wsID, service, token string) (View, error) {
if service != GitHub && service != Linear && service != Figma {
return View{}, apperr.NotFound("unknown service")
}
if err := s.requireAdmin(ctx, c, wsID); err != nil {
return View{}, err
}
token = strings.TrimSpace(token)
if len(token) > 500 {
return View{}, apperr.InvalidFields(map[string]string{"token": "The token is too long."})
}
if token != "" {
if err := s.checkToken(ctx, service, token); err != nil {
return View{}, apperr.InvalidFields(map[string]string{"token": err.Error()})
}
}
r, err := s.find(ctx, wsID)
if err != nil {
return View{}, err
}
r, err = s.save(ctx, wsID, r, map[string]any{service: s.seal(token)})
if err != nil {
return View{}, err
}
return s.view(wsID, r), nil
}
// checkToken asks the service who the token belongs to.
func (s *Service) checkToken(ctx context.Context, service, token string) error {
var req *http.Request
var err error
switch service {
case GitHub:
req, err = http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(s.apis.GitHub, "/")+"/user", nil)
if err == nil {
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
}
case Linear:
body := strings.NewReader(`{"query":"{ viewer { id } }"}`)
req, err = http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(s.apis.Linear, "/")+"/graphql", body)
if err == nil {
req.Header.Set("Authorization", token)
req.Header.Set("Content-Type", "application/json")
}
case Figma:
req, err = http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(s.apis.Figma, "/")+"/v1/me", nil)
if err == nil {
req.Header.Set("X-Figma-Token", token)
}
}
if err != nil {
return err
}
name := map[string]string{GitHub: "GitHub", Linear: "Linear", Figma: "Figma"}[service]
res, err := s.client.Do(req)
if err != nil {
return fmt.Errorf("%s could not be reached", name)
}
defer func() { _ = res.Body.Close() }()
data, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
if res.StatusCode != http.StatusOK || (service == Linear && bytes.Contains(data, []byte(`"errors"`))) {
return fmt.Errorf("%s did not accept the token", name)
}
return nil
}
// Preview reads a link preview with the tokens of workspace wsID when the
// caller is a member of it; without a workspace only public data is read.
func (s *Service) Preview(ctx context.Context, c access.Caller, wsID, raw string) (unfurl.Preview, error) {
t := unfurl.Tokens{}
if wsID != "" {
if _, err := s.dir.WorkspaceRole(ctx, c, wsID); err != nil {
return unfurl.Preview{}, err
}
r, err := s.find(ctx, wsID)
if err != nil {
return unfurl.Preview{}, err
}
if r != nil {
// A token that no longer opens is left out, not an error.
t.GitHub, _ = s.open(r.GitHub)
t.Linear, _ = s.open(r.Linear)
t.Figma, _ = s.open(r.Figma)
}
}
return s.previews.PreviewWith(ctx, raw, t)
}
// ---- Small helpers ----------------------------------------------------------
func postJSON(ctx context.Context, client *http.Client, u, bearer string, body, out any) error {
data, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
return do(client, req, out)
}
func getForm(ctx context.Context, client *http.Client, u, bearer string, q url.Values, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u+"?"+q.Encode(), nil)
if err != nil {
return err
}
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
return do(client, req, out)
}
func do(client *http.Client, req *http.Request, out any) error {
res, err := client.Do(req)
if err != nil {
return err
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode >= 300 {
return fmt.Errorf("HTTP %d", res.StatusCode)
}
return json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(out)
}
@@ -0,0 +1,411 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package integrations
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync"
"testing"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/directory"
"docwell/server/internal/search"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/unfurl"
"docwell/server/internal/webhooks"
)
const ws = "ws0000000000001"
// ---- Fakes -----------------------------------------------------------------------
type fakeDir struct {
roles map[string]string // caller id -> workspace role
pages map[string]directory.ChatPage
people map[string]string // email -> caller id
hits []directory.SearchHit
asked access.Caller
}
func (d *fakeDir) WorkspaceRole(_ context.Context, c access.Caller, wsID string) (string, error) {
if r, ok := d.roles[c.ID]; ok && wsID == ws {
return r, nil
}
return "", apperr.NotFound("workspace not found")
}
func (d *fakeDir) OpenToMembers(_ context.Context, wsID, id string) (directory.ChatPage, bool) {
p, ok := d.pages[id]
return p, ok && wsID == ws
}
func (d *fakeDir) MemberByEmail(_ context.Context, _ string, email string) (access.Caller, error) {
if id, ok := d.people[email]; ok {
return access.Caller{ID: id}, nil
}
return access.Caller{}, apperr.NotFound("no such member")
}
func (d *fakeDir) Search(_ context.Context, c access.Caller, _ string, q directory.SearchQuery) (directory.SearchResult, error) {
d.asked = c
if q.Text == "nothing" {
return directory.SearchResult{}, nil
}
return directory.SearchResult{Items: d.hits, Total: 9}, nil
}
// fakePB keeps workspace_integrations records in memory.
func fakePB(t *testing.T) *pocketbase.Client {
t.Helper()
var mu sync.Mutex
recs := map[string]map[string]any{}
n := 0
reply := func(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(v)
}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
reply(w, map[string]string{"token": "su"})
})
mux.HandleFunc("GET /api/collections/workspace_integrations/records", func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
items := []map[string]any{}
for _, rec := range recs {
if r.URL.Query().Get("filter") == "workspace = '"+rec["workspace"].(string)+"'" {
items = append(items, rec)
}
}
reply(w, map[string]any{"items": items, "totalItems": len(items), "totalPages": 1})
})
mux.HandleFunc("POST /api/collections/workspace_integrations/records", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
mu.Lock()
n++
body["id"] = "int" + strconv.Itoa(n)
recs[body["id"].(string)] = body
mu.Unlock()
reply(w, body)
})
mux.HandleFunc("PATCH /api/collections/workspace_integrations/records/{id}", func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
mu.Lock()
rec := recs[r.PathValue("id")]
for k, v := range body {
rec[k] = v
}
mu.Unlock()
reply(w, rec)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return pocketbase.New(srv.URL, "su@x.test", "pw")
}
// fakeServices answers as GitHub, Linear, Figma and Slack would.
type fakeServices struct {
mu sync.Mutex
posts []map[string]any // chat.postMessage and chat.unfurl bodies, with "method"
}
func (f *fakeServices) start(t *testing.T) *httptest.Server {
t.Helper()
reply := func(w http.ResponseWriter, s string) { _, _ = io.WriteString(w, s) }
mux := http.NewServeMux()
mux.HandleFunc("GET /gh/user", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer good" {
w.WriteHeader(http.StatusUnauthorized)
return
}
reply(w, `{"login":"me"}`)
})
mux.HandleFunc("GET /gh/repos/acme/secret/issues/1", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer good" {
http.NotFound(w, r)
return
}
reply(w, `{"title":"Hidden","state":"open","user":{"login":"x"}}`)
})
mux.HandleFunc("POST /slack/auth.test", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer xoxb-good" {
reply(w, `{"ok":false,"error":"invalid_auth"}`)
return
}
reply(w, `{"ok":true,"team_id":"T1","team":"Acme"}`)
})
mux.HandleFunc("GET /slack/conversations.list", func(w http.ResponseWriter, r *http.Request) {
reply(w, `{"ok":true,"channels":[{"id":"C0RANDOM1","name":"random"},{"id":"C0DOCS001","name":"docs"}]}`)
})
mux.HandleFunc("GET /slack/users.info", func(w http.ResponseWriter, r *http.Request) {
email := map[string]string{"U1": "ann@x.test", "U2": "stranger@x.test"}[r.URL.Query().Get("user")]
reply(w, `{"ok":true,"user":{"profile":{"email":"`+email+`"}}}`)
})
record := func(method string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
body["method"] = method
f.mu.Lock()
f.posts = append(f.posts, body)
f.mu.Unlock()
reply(w, `{"ok":true}`)
}
}
mux.HandleFunc("POST /slack/chat.postMessage", record("chat.postMessage"))
mux.HandleFunc("POST /slack/chat.unfurl", record("chat.unfurl"))
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func (f *fakeServices) sent() []map[string]any {
f.mu.Lock()
defer f.mu.Unlock()
return append([]map[string]any(nil), f.posts...)
}
// onlyTo keeps link previews off the network.
type onlyTo struct{ host string }
func (o onlyTo) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Host != o.host {
return nil, errors.New("blocked in tests")
}
return http.DefaultTransport.RoundTrip(r)
}
var (
admin = access.Caller{ID: "admin00000000001"}
member = access.Caller{ID: "member0000000001"}
)
func setup(t *testing.T) (*Service, *fakeDir, *fakeServices) {
t.Helper()
fs := &fakeServices{}
srv := fs.start(t)
host, _ := url.Parse(srv.URL)
dir := &fakeDir{
roles: map[string]string{admin.ID: access.WorkspaceAdmin, member.ID: access.WorkspaceMember},
pages: map[string]directory.ChatPage{
"page00000000001": {ID: "page00000000001", Workspace: ws, Title: "Roadmap", Icon: "🗺️", SpaceName: "Product",
URL: "https://docs.test/p/page00000000001", Excerpt: "What we build next"},
},
people: map[string]string{"ann@x.test": member.ID},
hits: []directory.SearchHit{{Hit: search.Hit{ID: "page00000000001", Title: "Roadmap", Snippet: "What we <b>build</b>"}, SpaceName: "Product"}},
}
apis := unfurl.APIs{GitHub: srv.URL + "/gh", Linear: srv.URL + "/linear", Figma: srv.URL + "/figma", FigmaWeb: srv.URL + "/figweb"}
previews := unfurl.NewWithClient(&http.Client{Transport: onlyTo{host: host.Host}})
s := New(fakePB(t), dir, previews, Options{Secret: "s3cret", WebURL: "https://docs.test", APIs: &apis, SlackAPI: srv.URL + "/slack"})
return s, dir, fs
}
func ptr[T any](v T) *T { return &v }
func isKind(err error, k apperr.Kind) bool {
e, ok := apperr.As(err)
return ok && e.Kind == k
}
// ---- Tests -----------------------------------------------------------------------
func TestTokensAndPreviews(t *testing.T) {
s, _, _ := setup(t)
ctx := context.Background()
if _, err := s.SetToken(ctx, member, ws, GitHub, "good"); !isKind(err, apperr.KindForbidden) {
t.Fatalf("a member set a token: %v", err)
}
if _, err := s.SetToken(ctx, admin, ws, GitHub, "bad"); err == nil {
t.Fatal("a bad token was stored")
}
v, err := s.SetToken(ctx, admin, ws, GitHub, "good")
if err != nil || !v.GitHub.Set || v.Linear.Set {
t.Fatalf("view %+v, %v", v, err)
}
// Members' previews use the workspace's token; without a workspace, none.
p, err := s.Preview(ctx, member, ws, "https://github.com/acme/secret/issues/1")
if err != nil || p.Kind != unfurl.KindGitHubIssue || p.Title != "Hidden" {
t.Fatalf("with token: %+v, %v", p, err)
}
if p, _ := s.Preview(ctx, member, "", "https://github.com/acme/secret/issues/1"); p.Kind != "" {
t.Fatalf("without workspace: %+v", p)
}
if _, err := s.Preview(ctx, access.Caller{ID: "outsider0000001"}, ws, "https://github.com/acme/secret/issues/1"); err == nil {
t.Fatal("an outsider used the workspace's tokens")
}
if v, _ := s.SetToken(ctx, admin, ws, GitHub, ""); v.GitHub.Set {
t.Fatal("the token was not removed")
}
}
func connect(t *testing.T, s *Service) {
t.Helper()
ctx := context.Background()
if _, err := s.SetSlack(ctx, admin, ws, SlackInput{BotToken: ptr("xoxb-bad")}); err == nil {
t.Fatal("a rejected bot token was stored")
}
v, err := s.SetSlack(ctx, admin, ws, SlackInput{BotToken: ptr("xoxb-good"), SigningSecret: ptr("0123456789abcdef0123"), Channel: ptr("#Docs")})
if err != nil {
t.Fatal(err)
}
if !v.Slack.Connected || v.Slack.Team != "T1" || v.Slack.Channel != "C0DOCS001" || v.Slack.ChannelName != "docs" || !v.Slack.Unfurl || !v.Slack.Search {
t.Fatalf("slack %+v", v.Slack)
}
if !strings.Contains(v.Slack.Manifest, "https://docs.test/api/v1/slack/"+ws+"/commands") || !strings.Contains(v.Slack.Manifest, `"docs.test"`) {
t.Fatalf("manifest %s", v.Slack.Manifest)
}
}
func TestSlackPosts(t *testing.T) {
s, _, fs := setup(t)
connect(t, s)
page := map[string]any{"page": map[string]any{"id": "page00000000001"}, "actor": map[string]any{"name": "Ann <a>"}}
s.Listen(webhooks.Payload{Event: "page.created", Workspace: ws, Data: page})
// Not open to every member: never posted.
s.Listen(webhooks.Payload{Event: "page.created", Workspace: ws, Data: map[string]any{"page": map[string]any{"id": "secret000000001"}}})
// Not among the chosen events (the defaults are created and commented).
s.Listen(webhooks.Payload{Event: "page.moved", Workspace: ws, Data: page})
s.Listen(webhooks.Payload{Event: "comment.created", Workspace: ws, Data: map[string]any{
"page": map[string]any{"id": "page00000000001"}, "actor": map[string]any{"name": "Bo"},
"comment": map[string]any{"body": `{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Looks good"}]}]}`},
}})
posts := fs.sent()
if len(posts) != 2 {
t.Fatalf("posts %v", posts)
}
if got := posts[0]["text"]; got != "*Ann &lt;a&gt;* created <https://docs.test/p/page00000000001|🗺️ Roadmap> in _Product_" || posts[0]["channel"] != "C0DOCS001" {
t.Errorf("first post %v", posts[0])
}
if got := posts[1]["text"].(string); !strings.HasSuffix(got, "\n>Looks good") || !strings.HasPrefix(got, "*Bo* commented on") {
t.Errorf("comment post %q", got)
}
// Edits are posted once in a while, not on every save.
if _, err := s.SetSlack(context.Background(), admin, ws, SlackInput{Events: ptr([]string{"page.updated"})}); err != nil {
t.Fatal(err)
}
s.Listen(webhooks.Payload{Event: "page.updated", Workspace: ws, Data: page})
s.Listen(webhooks.Payload{Event: "page.updated", Workspace: ws, Data: page})
if n := len(fs.sent()); n != 3 {
t.Fatalf("after two edits: %d posts", n)
}
}
func slackRequest(t *testing.T, path, contentType, body, secret string, at time.Time) *http.Request {
t.Helper()
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
r.Header.Set("Content-Type", contentType)
ts := strconv.FormatInt(at.Unix(), 10)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte("v0:" + ts + ":" + body))
r.Header.Set("X-Slack-Request-Timestamp", ts)
r.Header.Set("X-Slack-Signature", "v0="+hex.EncodeToString(mac.Sum(nil)))
return r
}
func TestSlackEvents(t *testing.T) {
s, _, fs := setup(t)
connect(t, s)
const secret = "0123456789abcdef0123"
w := httptest.NewRecorder()
s.Events(w, slackRequest(t, "/", "application/json", `{"type":"url_verification","challenge":"abc"}`, "wrong", time.Now()), ws)
if w.Code != http.StatusUnauthorized {
t.Fatalf("bad signature: %d", w.Code)
}
w = httptest.NewRecorder()
s.Events(w, slackRequest(t, "/", "application/json", `{"type":"url_verification","challenge":"abc"}`, secret, time.Now().Add(-10*time.Minute)), ws)
if w.Code != http.StatusUnauthorized {
t.Fatalf("old request: %d", w.Code)
}
w = httptest.NewRecorder()
s.Events(w, slackRequest(t, "/", "application/json", `{"type":"url_verification","challenge":"abc"}`, secret, time.Now()), ws)
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"challenge":"abc"`) {
t.Fatalf("challenge: %d %s", w.Code, w.Body)
}
event := `{"type":"event_callback","team_id":"T1","event":{"type":"link_shared","channel":"C9","message_ts":"1.2",
"links":[{"url":"https://docs.test/p/page00000000001"},{"url":"https://docs.test/p/secret000000001"},{"url":"https://other.test/p/page00000000001"}]}}`
w = httptest.NewRecorder()
s.Events(w, slackRequest(t, "/", "application/json", event, secret, time.Now()), ws)
if w.Code != http.StatusOK {
t.Fatalf("event: %d", w.Code)
}
var unfurl map[string]any
for range 100 {
for _, p := range fs.sent() {
if p["method"] == "chat.unfurl" {
unfurl = p
}
}
if unfurl != nil {
break
}
time.Sleep(10 * time.Millisecond)
}
if unfurl == nil || unfurl["channel"] != "C9" || unfurl["ts"] != "1.2" {
t.Fatalf("unfurl %v", unfurl)
}
links := unfurl["unfurls"].(map[string]any)
if len(links) != 1 {
t.Fatalf("unfurled %v", links)
}
card := links["https://docs.test/p/page00000000001"].(map[string]any)
if card["title"] != "🗺️ Roadmap" || card["text"] != "What we build next" || card["footer"] != "Docwell · Product" {
t.Errorf("card %v", card)
}
}
func TestSlackCommands(t *testing.T) {
s, dir, _ := setup(t)
connect(t, s)
const secret = "0123456789abcdef0123"
run := func(form url.Values) string {
w := httptest.NewRecorder()
s.Commands(w, slackRequest(t, "/", "application/x-www-form-urlencoded", form.Encode(), secret, time.Now()), ws)
var out struct {
Type string `json:"response_type"`
Text string `json:"text"`
}
_ = json.Unmarshal(w.Body.Bytes(), &out)
if out.Type != "ephemeral" {
t.Fatalf("answer %d %s", w.Code, w.Body)
}
return out.Text
}
got := run(url.Values{"team_id": {"T1"}, "user_id": {"U1"}, "text": {"road map"}})
want := "Docwell pages for “road map”:\n• <https://docs.test/p/page00000000001|Roadmap> — _Product_\n What we &lt;b&gt;build&lt;/b&gt;\n<https://docs.test/search?q=road+map|All 9 results in Docwell>"
if got != want {
t.Errorf("search answer:\n%s\nwant\n%s", got, want)
}
if dir.asked != member {
t.Errorf("searched as %+v", dir.asked)
}
if got := run(url.Values{"team_id": {"T1"}, "user_id": {"U2"}, "text": {"x"}}); !strings.Contains(got, "not a member") {
t.Errorf("stranger: %q", got)
}
if got := run(url.Values{"team_id": {"T1"}, "user_id": {"U1"}, "text": {"nothing"}}); !strings.HasPrefix(got, "Nothing in Docwell") {
t.Errorf("no hits: %q", got)
}
if _, err := s.SetSlack(context.Background(), admin, ws, SlackInput{Search: ptr(false)}); err != nil {
t.Fatal(err)
}
if got := run(url.Values{"team_id": {"T1"}, "user_id": {"U1"}, "text": {"x"}}); !strings.Contains(got, "turned off") {
t.Errorf("search off: %q", got)
}
}
+706
View File
@@ -0,0 +1,706 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package integrations
// Slack: each workspace connects its own Slack app (made from the manifest
// its settings show). Docwell posts chosen page and comment events to one
// channel, answers Slack's link_shared events with a preview of Docwell
// pages, and runs /docwell as a search for the person who typed it (found
// by their Slack email). Only pages every member of the workspace can open
// are ever posted or previewed (directory.OpenToMembers); search results
// are what that one person can open, and only they see them.
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/directory"
"docwell/server/internal/webhooks"
)
// SlackEvents are the events a workspace can have posted to Slack.
var SlackEvents = []string{
"page.created", "page.updated", "page.moved", "page.archived", "page.unarchived", "page.restored",
"comment.created", "comment.resolved",
}
// DefaultSlackEvents are posted until an admin picks others.
var DefaultSlackEvents = []string{"page.created", "comment.created"}
// updateQuiet is how long a page's edits stay quiet after one was posted.
const updateQuiet = 30 * time.Minute
// SlackInput changes the Slack connection; nil fields stay as they are.
type SlackInput struct {
BotToken *string `json:"botToken"`
SigningSecret *string `json:"signingSecret"`
Channel *string `json:"channel"`
Events *[]string `json:"events"`
Unfurl *bool `json:"unfurl"`
Search *bool `json:"search"`
}
// slackOK is the envelope of every Slack Web API answer.
type slackOK struct {
OK bool `json:"ok"`
Error string `json:"error"`
}
func (s *Service) slack(ctx context.Context, method, token string, body, out any) error {
var env struct {
slackOK
Raw json.RawMessage `json:"-"`
}
var raw json.RawMessage
if err := postJSON(ctx, s.client, s.slackAPI+"/"+method, token, body, &raw); err != nil {
return fmt.Errorf("Slack could not be reached (%w)", err) //nolint:staticcheck // shown to admins as is
}
if err := json.Unmarshal(raw, &env); err != nil {
return fmt.Errorf("Slack sent an answer Docwell could not read") //nolint:staticcheck
}
if !env.OK {
return fmt.Errorf("Slack said: %s", env.Error) //nolint:staticcheck
}
if out != nil {
return json.Unmarshal(raw, out)
}
return nil
}
func (s *Service) slackGet(ctx context.Context, method, token string, q url.Values, out any) error {
var raw json.RawMessage
if err := getForm(ctx, s.client, s.slackAPI+"/"+method, token, q, &raw); err != nil {
return fmt.Errorf("Slack could not be reached (%w)", err) //nolint:staticcheck
}
var env slackOK
if err := json.Unmarshal(raw, &env); err != nil || !env.OK {
return fmt.Errorf("Slack said: %s", env.Error) //nolint:staticcheck
}
return json.Unmarshal(raw, out)
}
var channelID = regexp.MustCompile(`^[CG][A-Z0-9]{6,}$`)
// resolveChannel finds a public channel by id or name ("#general").
func (s *Service) resolveChannel(ctx context.Context, token, ch string) (id, name string, err error) {
ch = strings.TrimSpace(ch)
if channelID.MatchString(ch) {
var out struct {
Channel struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"channel"`
}
if err := s.slackGet(ctx, "conversations.info", token, url.Values{"channel": {ch}}, &out); err != nil {
return "", "", err
}
return out.Channel.ID, out.Channel.Name, nil
}
want := strings.ToLower(strings.TrimPrefix(ch, "#"))
cursor := ""
for range 20 {
var out struct {
Channels []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"channels"`
Meta struct {
Next string `json:"next_cursor"`
} `json:"response_metadata"`
}
q := url.Values{"types": {"public_channel"}, "exclude_archived": {"true"}, "limit": {"1000"}}
if cursor != "" {
q.Set("cursor", cursor)
}
if err := s.slackGet(ctx, "conversations.list", token, q, &out); err != nil {
return "", "", err
}
for _, c := range out.Channels {
if strings.ToLower(c.Name) == want {
return c.ID, c.Name, nil
}
}
if cursor = out.Meta.Next; cursor == "" {
break
}
}
return "", "", fmt.Errorf("no public channel named #%s", want)
}
// SetSlack connects or changes the workspace's Slack app.
func (s *Service) SetSlack(ctx context.Context, c access.Caller, wsID string, in SlackInput) (View, error) {
if err := s.requireAdmin(ctx, c, wsID); err != nil {
return View{}, err
}
r, err := s.find(ctx, wsID)
if err != nil {
return View{}, err
}
body := map[string]any{"slack_error": ""}
token := ""
if r != nil {
token, _ = s.open(r.SlackBot)
}
if in.BotToken != nil {
t := strings.TrimSpace(*in.BotToken)
if !strings.HasPrefix(t, "xoxb-") || len(t) > 300 {
return View{}, apperr.InvalidFields(map[string]string{"botToken": "Paste the app's Bot User OAuth Token (it starts with xoxb-)."}) //nolint:gosec // a message, not a credential
}
var who struct {
TeamID string `json:"team_id"`
Team string `json:"team"`
}
if err := s.slack(ctx, "auth.test", t, map[string]any{}, &who); err != nil {
return View{}, apperr.InvalidFields(map[string]string{"botToken": err.Error()})
}
token = t
body["slack_bot"], body["slack_team"], body["slack_team_name"] = s.seal(t), who.TeamID, who.Team
if r == nil || r.SlackBot == "" {
// A first connection previews links and searches unless turned off.
body["slack_unfurl"], body["slack_search"] = true, true
body["slack_events"] = DefaultSlackEvents
}
}
if in.SigningSecret != nil {
sec := strings.TrimSpace(*in.SigningSecret)
if len(sec) < 16 || len(sec) > 200 {
return View{}, apperr.InvalidFields(map[string]string{"signingSecret": "Paste the app's Signing Secret (Basic Information → App Credentials)."}) //nolint:gosec // a message, not a credential
}
body["slack_signing"] = s.seal(sec)
}
if in.Channel != nil {
if strings.TrimSpace(*in.Channel) == "" {
body["slack_channel"], body["slack_channel_name"] = "", ""
} else {
if token == "" {
return View{}, apperr.InvalidFields(map[string]string{"channel": "Connect the bot token first."})
}
id, name, err := s.resolveChannel(ctx, token, *in.Channel)
if err != nil {
return View{}, apperr.InvalidFields(map[string]string{"channel": err.Error()})
}
body["slack_channel"], body["slack_channel_name"] = id, name
}
}
if in.Events != nil {
events := []string{}
for _, e := range *in.Events {
if !slices.Contains(SlackEvents, e) {
return View{}, apperr.InvalidFields(map[string]string{"events": "Unknown event: " + e})
}
if !slices.Contains(events, e) {
events = append(events, e)
}
}
body["slack_events"] = events
}
if in.Unfurl != nil {
body["slack_unfurl"] = *in.Unfurl
}
if in.Search != nil {
body["slack_search"] = *in.Search
}
r, err = s.save(ctx, wsID, r, body)
if err != nil {
return View{}, err
}
return s.view(wsID, r), nil
}
// DeleteSlack disconnects Slack (the app itself stays in Slack).
func (s *Service) DeleteSlack(ctx context.Context, c access.Caller, wsID string) (View, error) {
if err := s.requireAdmin(ctx, c, wsID); err != nil {
return View{}, err
}
r, err := s.find(ctx, wsID)
if err != nil || r == nil {
return s.view(wsID, r), err
}
r, err = s.save(ctx, wsID, r, map[string]any{
"slack_bot": "", "slack_signing": "", "slack_team": "", "slack_team_name": "", "slack_channel": "",
"slack_channel_name": "", "slack_events": nil, "slack_unfurl": false, "slack_search": false, "slack_error": "",
})
if err != nil {
return View{}, err
}
return s.view(wsID, r), nil
}
// TestSlack posts a hello to the channel.
func (s *Service) TestSlack(ctx context.Context, c access.Caller, wsID string) error {
if err := s.requireAdmin(ctx, c, wsID); err != nil {
return err
}
r, err := s.find(ctx, wsID)
if err != nil {
return err
}
if r == nil || r.SlackBot == "" || r.SlackChannel == "" {
return apperr.Invalid("Connect the bot token and choose a channel first.")
}
token, err := s.open(r.SlackBot)
if err != nil {
return apperr.Invalid(err.Error())
}
err = s.slack(ctx, "chat.postMessage", token, map[string]any{
"channel": r.SlackChannel, "text": "👋 Docwell is connected. Page and comment news will show up here.",
"unfurl_links": false,
}, nil)
if err != nil {
return apperr.Invalid(err.Error())
}
return nil
}
func (s *Service) manifest(eventsURL, commandsURL string) string {
host := ""
if u, err := url.Parse(s.webURL); err == nil {
host = u.Hostname()
}
m := map[string]any{
"display_information": map[string]any{"name": "Docwell", "description": "Docwell pages in Slack"},
"features": map[string]any{
"bot_user": map[string]any{"display_name": "Docwell", "always_online": false},
"slash_commands": []any{map[string]any{
"command": "/docwell", "url": commandsURL, "description": "Search Docwell", "usage_hint": "[words to find]", "should_escape": false,
}},
"unfurl_domains": []string{host},
},
"oauth_config": map[string]any{"scopes": map[string]any{"bot": []string{
"chat:write", "chat:write.public", "channels:read", "commands", "links:read", "links:write", "users:read", "users:read.email",
}}},
"settings": map[string]any{
"event_subscriptions": map[string]any{"request_url": eventsURL, "bot_events": []string{"link_shared"}},
"org_deploy_enabled": false,
"socket_mode_enabled": false,
"token_rotation_enabled": false,
},
}
data, _ := json.MarshalIndent(m, "", " ")
return string(data)
}
// ---- Channel posts -----------------------------------------------------------
// Listen posts webhook events to Slack; give it to webhooks.Dispatcher.Listen.
func (s *Service) Listen(p webhooks.Payload) {
if !slices.Contains(SlackEvents, p.Event) {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
r, err := s.find(ctx, p.Workspace)
if err != nil || r == nil || r.SlackBot == "" || r.SlackChannel == "" {
return
}
events := r.SlackEvents
if events == nil {
events = DefaultSlackEvents
}
if !slices.Contains(events, p.Event) {
return
}
// The event's data, read through JSON whatever its Go type.
var data struct {
Page struct {
ID string `json:"id"`
} `json:"page"`
Actor *struct {
Name string `json:"name"`
} `json:"actor"`
Comment *struct {
Body string `json:"body"`
} `json:"comment"`
}
raw, _ := json.Marshal(p.Data)
if json.Unmarshal(raw, &data) != nil || data.Page.ID == "" {
return
}
page, ok := s.dir.OpenToMembers(ctx, p.Workspace, data.Page.ID)
if !ok {
return
}
if p.Event == "page.updated" && !s.quietEnough(p.Workspace+"/"+page.ID) {
return
}
who := "Someone"
if data.Actor != nil && data.Actor.Name != "" {
who = data.Actor.Name
}
text := fmt.Sprintf("*%s* %s %s", escape(who), verb(p.Event), pageLink(page))
if page.SpaceName != "" {
text += " in _" + escape(page.SpaceName) + "_"
}
if data.Comment != nil && p.Event == "comment.created" {
if body := commentText(data.Comment.Body); body != "" {
text += "\n>" + escape(body)
}
}
token, err := s.open(r.SlackBot)
if err == nil {
err = s.slack(ctx, "chat.postMessage", token, map[string]any{"channel": r.SlackChannel, "text": text, "unfurl_links": false}, nil)
}
s.noteError(ctx, r, err)
}
func (s *Service) quietEnough(key string) bool {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
if t, ok := s.recent[key]; ok && now.Sub(t) < updateQuiet {
return false
}
s.recent[key] = now
if len(s.recent) > 5000 {
for k, t := range s.recent {
if now.Sub(t) >= updateQuiet {
delete(s.recent, k)
}
}
}
return true
}
// noteError keeps the last delivery error for the settings page (and clears it).
func (s *Service) noteError(ctx context.Context, r *record, err error) {
msg := ""
if err != nil {
msg = err.Error()
s.log.Warn("slack: post", "workspace", r.Workspace, "err", err)
}
if msg != r.SlackError {
_, _ = s.save(ctx, r.Workspace, r, map[string]any{"slack_error": msg})
}
}
func verb(event string) string {
switch event {
case "page.created":
return "created"
case "page.updated":
return "edited"
case "page.moved":
return "moved"
case "page.archived":
return "archived"
case "page.unarchived":
return "brought back"
case "page.restored":
return "restored"
case "comment.created":
return "commented on"
case "comment.resolved":
return "resolved a comment on"
}
return event
}
func pageLink(p directory.ChatPage) string {
title := p.Title
if title == "" {
title = "Untitled"
}
if p.Icon != "" && len([]rune(p.Icon)) <= 4 {
title = p.Icon + " " + title
}
return "<" + p.URL + "|" + escape(title) + ">"
}
// escape keeps text from being read as Slack markup.
func escape(s string) string {
return strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;").Replace(s)
}
// commentText is a comment body (Tiptap JSON or text) as one short line.
func commentText(body string) string {
text := body
if strings.HasPrefix(strings.TrimSpace(body), "{") {
var parts []string
var walk func(any)
walk = func(v any) {
switch n := v.(type) {
case map[string]any:
if t, ok := n["text"].(string); ok {
parts = append(parts, t)
}
if a, ok := n["attrs"].(map[string]any); ok {
if l, ok := a["label"].(string); ok && n["type"] == "mention" {
parts = append(parts, "@"+l)
}
}
walk(n["content"])
case []any:
for _, c := range n {
walk(c)
}
}
}
var doc any
if json.Unmarshal([]byte(body), &doc) == nil {
walk(doc)
text = strings.Join(parts, " ")
}
}
text = strings.Join(strings.Fields(text), " ")
if r := []rune(text); len(r) > 280 {
text = string(r[:279]) + "…"
}
return text
}
// ---- Requests from Slack -------------------------------------------------------
// maxSlackBody caps what Slack sends.
const maxSlackBody = 1 << 20
// verify checks Slack's signature on a request body (5 minutes of leeway).
func verify(secret string, h http.Header, body []byte, now time.Time) bool {
ts, err := strconv.ParseInt(h.Get("X-Slack-Request-Timestamp"), 10, 64)
if err != nil || secret == "" {
return false
}
if d := now.Unix() - ts; d > 300 || d < -300 {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte("v0:" + strconv.FormatInt(ts, 10) + ":"))
mac.Write(body)
want := "v0=" + hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(want), []byte(h.Get("X-Slack-Signature")))
}
// signed reads a request from Slack for workspace wsID and checks its
// signature; the record comes back for the caller to use.
func (s *Service) signed(r *http.Request, wsID string) (*record, []byte, bool) {
body, err := io.ReadAll(io.LimitReader(r.Body, maxSlackBody))
if err != nil || wsID == "" || strings.ContainsAny(wsID, "'\"\\ ") {
return nil, nil, false
}
rec, err := s.find(r.Context(), wsID)
if err != nil || rec == nil || rec.SlackBot == "" {
return nil, nil, false
}
secret, err := s.open(rec.SlackSigning)
if err != nil || !verify(secret, r.Header, body, time.Now()) {
return nil, nil, false
}
return rec, body, true
}
// Events answers Slack's Events API for workspace wsID: the URL check, and
// link_shared, which gets previews of Docwell pages.
func (s *Service) Events(w http.ResponseWriter, r *http.Request, wsID string) {
rec, body, ok := s.signed(r, wsID)
if !ok {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
var in struct {
Type string `json:"type"`
Challenge string `json:"challenge"`
TeamID string `json:"team_id"`
Event struct {
Type string `json:"type"`
Channel string `json:"channel"`
MessageTS string `json:"message_ts"`
UnfurlID string `json:"unfurl_id"`
Source string `json:"source"`
Links []struct {
URL string `json:"url"`
} `json:"links"`
} `json:"event"`
}
if json.Unmarshal(body, &in) != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if in.Type == "url_verification" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"challenge": in.Challenge})
return
}
w.WriteHeader(http.StatusOK)
// Slack resends what it thinks was missed; the first try did the work.
if r.Header.Get("X-Slack-Retry-Num") != "" || in.Type != "event_callback" || in.Event.Type != "link_shared" {
return
}
if !rec.SlackUnfurl || (rec.SlackTeam != "" && in.TeamID != "" && in.TeamID != rec.SlackTeam) {
return
}
var urls []string
for _, l := range in.Event.Links {
urls = append(urls, l.URL)
}
ev := in.Event
go s.unfurl(rec, ev.Channel, ev.MessageTS, ev.UnfurlID, ev.Source, urls)
}
var pagePath = regexp.MustCompile(`^/p/([a-z0-9]{15})(?:[/?#]|$)`)
// unfurl sends Slack previews of the Docwell pages among urls.
func (s *Service) unfurl(rec *record, channel, ts, unfurlID, source string, urls []string) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
base, err := url.Parse(s.webURL)
if err != nil {
return
}
unfurls := map[string]any{}
for _, raw := range urls {
u, err := url.Parse(raw)
if err != nil || !strings.EqualFold(u.Host, base.Host) {
continue
}
m := pagePath.FindStringSubmatch(u.Path)
if m == nil {
continue
}
page, ok := s.dir.OpenToMembers(ctx, rec.Workspace, m[1])
if !ok {
continue
}
title := page.Title
if title == "" {
title = "Untitled"
}
if page.Icon != "" && len([]rune(page.Icon)) <= 4 {
title = page.Icon + " " + title
}
block := map[string]any{"title": title, "title_link": raw, "footer": "Docwell · " + page.SpaceName}
if page.Excerpt != "" {
block["text"] = page.Excerpt
}
unfurls[raw] = block
}
if len(unfurls) == 0 {
return
}
token, err := s.open(rec.SlackBot)
if err != nil {
return
}
body := map[string]any{"unfurls": unfurls}
if unfurlID != "" && source != "" {
body["unfurl_id"], body["source"] = unfurlID, source
} else {
body["channel"], body["ts"] = channel, ts
}
if err := s.slack(ctx, "chat.unfurl", token, body, nil); err != nil {
s.log.Warn("slack: unfurl", "workspace", rec.Workspace, "err", err)
}
}
// Commands answers /docwell for workspace wsID: a search as the person who
// typed it, shown only to them.
func (s *Service) Commands(w http.ResponseWriter, r *http.Request, wsID string) {
rec, body, ok := s.signed(r, wsID)
if !ok {
http.Error(w, "bad signature", http.StatusUnauthorized)
return
}
form, err := url.ParseQuery(string(body))
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if form.Get("ssl_check") == "1" {
return
}
reply := func(text string) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"response_type": "ephemeral", "text": text})
}
if !rec.SlackSearch {
reply("Searching Docwell from Slack is turned off for this workspace.")
return
}
if rec.SlackTeam != "" && form.Get("team_id") != "" && form.Get("team_id") != rec.SlackTeam {
reply("This Slack workspace is not the one connected to Docwell.")
return
}
q := strings.TrimSpace(form.Get("text"))
if q == "" {
reply("Type what to find, like `/docwell onboarding checklist`.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 2500*time.Millisecond)
defer cancel()
c, err := s.slackCaller(ctx, rec, form.Get("user_id"))
if err != nil {
reply(err.Error())
return
}
res, err := s.dir.Search(ctx, c, rec.Workspace, directory.SearchQuery{Text: q, Limit: 5})
if err != nil {
reply("The search did not work: " + err.Error())
return
}
if len(res.Items) == 0 {
reply("Nothing in Docwell matches “" + escape(q) + "”.")
return
}
var b strings.Builder
fmt.Fprintf(&b, "Docwell pages for “%s”:", escape(q))
for _, h := range res.Items {
title := h.Title
if title == "" {
title = "Untitled"
}
fmt.Fprintf(&b, "\n• <%s/p/%s|%s>", s.webURL, h.ID, escape(title))
if h.SpaceName != "" {
b.WriteString(" — _" + escape(h.SpaceName) + "_")
}
if sn := strings.Join(strings.Fields(h.Snippet), " "); sn != "" {
if r := []rune(sn); len(r) > 160 {
sn = string(r[:159]) + "…"
}
b.WriteString("\n " + escape(sn))
}
}
if res.Total > len(res.Items) {
fmt.Fprintf(&b, "\n<%s/search?q=%s|All %d results in Docwell>", s.webURL, url.QueryEscape(q), res.Total)
}
reply(b.String())
}
// slackCaller is the Docwell member with the Slack user's email.
func (s *Service) slackCaller(ctx context.Context, rec *record, slackUser string) (access.Caller, error) {
token, err := s.open(rec.SlackBot)
if err != nil || slackUser == "" {
return access.Caller{}, fmt.Errorf("Docwell cannot reach Slack right now") //nolint:staticcheck
}
var out struct {
User struct {
Deleted bool `json:"deleted"`
IsBot bool `json:"is_bot"`
Profile struct {
Email string `json:"email"`
} `json:"profile"`
} `json:"user"`
}
if err := s.slackGet(ctx, "users.info", token, url.Values{"user": {slackUser}}, &out); err != nil || out.User.Profile.Email == "" {
return access.Caller{}, fmt.Errorf("Docwell could not read your Slack email; ask an admin to give the app the users:read.email scope") //nolint:staticcheck
}
if out.User.Deleted || out.User.IsBot {
return access.Caller{}, fmt.Errorf("Only people can search Docwell") //nolint:staticcheck
}
c, err := s.dir.MemberByEmail(ctx, rec.Workspace, out.User.Profile.Email)
if err != nil {
return access.Caller{}, fmt.Errorf("Your Slack email is not a member of this Docwell workspace") //nolint:staticcheck
}
return c, nil
}
+246
View File
@@ -6185,5 +6185,251 @@
"type": "base",
"updateRule": null,
"viewRule": null
},
{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"help": "",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": true,
"collectionId": "pbc_2170078043",
"help": "",
"hidden": false,
"id": "relation2375286809",
"maxSelect": 1,
"minSelect": 0,
"name": "workspace",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1669114857",
"max": 2000,
"min": 0,
"name": "github",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text232700083",
"max": 2000,
"min": 0,
"name": "linear",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text822105336",
"max": 2000,
"min": 0,
"name": "figma",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text2282807364",
"max": 2000,
"min": 0,
"name": "slack_bot",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text2979431149",
"max": 2000,
"min": 0,
"name": "slack_signing",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text3748138112",
"max": 40,
"min": 0,
"name": "slack_team",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text3092398719",
"max": 200,
"min": 0,
"name": "slack_team_name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text3812437728",
"max": 40,
"min": 0,
"name": "slack_channel",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text853526307",
"max": 200,
"min": 0,
"name": "slack_channel_name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"help": "",
"hidden": false,
"id": "json2472382689",
"maxSize": 4000,
"name": "slack_events",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"help": "",
"hidden": false,
"id": "bool428803893",
"name": "slack_unfurl",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
},
{
"help": "",
"hidden": false,
"id": "bool1948916748",
"name": "slack_search",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1031191054",
"max": 1000,
"min": 0,
"name": "slack_error",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_4221958247",
"indexes": [
"CREATE UNIQUE INDEX idx_workspace_integrations_workspace ON workspace_integrations (workspace)"
],
"listRule": null,
"name": "workspace_integrations",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
}
]
+363
View File
@@ -0,0 +1,363 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package unfurl
// Rich previews: a few services describe their links better through their
// APIs than through the page's meta tags (which, for private items, are a
// sign-in page). GitHub issues, pull requests and repositories, Linear issues
// and Figma files get a status and a line of details. A workspace's tokens
// reach private items; without them only public data is read, and Linear
// (which has no public API) falls back to the page itself.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
// Tokens are a workspace's keys for the services; each may be empty.
type Tokens struct {
GitHub string
Linear string
Figma string
}
// APIs are the services' addresses (tests point them at a local server).
type APIs struct {
GitHub string // https://api.github.com
Linear string // https://api.linear.app
Figma string // https://api.figma.com
FigmaWeb string // https://www.figma.com (oEmbed for public files)
}
// DefaultAPIs are the services' real addresses.
var DefaultAPIs = APIs{
GitHub: "https://api.github.com",
Linear: "https://api.linear.app",
Figma: "https://api.figma.com",
FigmaWeb: "https://www.figma.com",
}
// Kinds of rich preview.
const (
KindGitHubIssue = "github.issue"
KindGitHubPull = "github.pull"
KindGitHubRepo = "github.repo"
KindLinearIssue = "linear.issue"
KindFigmaFile = "figma.file"
)
// WithAPIs returns a copy of f that calls apis instead of the real services.
func (f *Fetcher) WithAPIs(apis APIs) *Fetcher {
c := *f
c.apis = &apis
return &c
}
func (f *Fetcher) api() APIs {
if f.apis != nil {
return *f.apis
}
return DefaultAPIs
}
var (
githubItem = regexp.MustCompile(`^/([\w.-]+)/([\w.-]+)/(issues|pull)/(\d+)(?:/.*)?$`)
githubRepo = regexp.MustCompile(`^/([\w.-]+)/([\w.-]+)/?$`)
linearItem = regexp.MustCompile(`^/[\w-]+/issue/([A-Za-z][A-Za-z0-9]*-\d+)(?:/.*)?$`)
figmaFile = regexp.MustCompile(`^/(file|design|proto|board|slides|deck)/([A-Za-z0-9]{10,})(?:/.*)?$`)
)
// GitHub paths that look like a repository but are pages of the site.
var githubReserved = map[string]bool{
"settings": true, "orgs": true, "marketplace": true, "explore": true, "topics": true, "notifications": true,
"login": true, "join": true, "features": true, "pricing": true, "sponsors": true, "about": true, "search": true,
"pulls": true, "issues": true, "new": true, "organizations": true, "apps": true, "collections": true, "trending": true,
}
// rich returns the service's preview of u; ok is false when u is not one of
// theirs or the service could not describe it.
func (f *Fetcher) rich(ctx context.Context, u *url.URL, t Tokens) (Preview, bool) {
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
switch host {
case "github.com":
if m := githubItem.FindStringSubmatch(u.Path); m != nil {
return f.githubItem(ctx, u, t.GitHub, m[1], m[2], m[4])
}
if m := githubRepo.FindStringSubmatch(u.Path); m != nil && !githubReserved[strings.ToLower(m[1])] {
return f.githubRepo(ctx, u, t.GitHub, m[1], m[2])
}
case "linear.app":
if m := linearItem.FindStringSubmatch(u.Path); m != nil && t.Linear != "" {
return f.linearIssue(ctx, u, t.Linear, strings.ToUpper(m[1]))
}
case "figma.com":
if m := figmaFile.FindStringSubmatch(u.Path); m != nil {
return f.figmaFile(ctx, u, t.Figma, m[2])
}
}
return Preview{}, false
}
// getJSON reads a JSON answer into out; ok is false for anything but 200.
func (f *Fetcher) getJSON(req *http.Request, out any) bool {
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "DocwellLinkPreview/1.0 (+https://docwell.app)")
res, err := f.client.Do(req)
if err != nil {
return false
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode != http.StatusOK {
return false
}
return json.NewDecoder(io.LimitReader(res.Body, maxBody)).Decode(out) == nil
}
func (f *Fetcher) github(ctx context.Context, token, path string, out any) bool {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(f.api().GitHub, "/")+path, nil)
if err != nil {
return false
}
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
return f.getJSON(req, out)
}
func (f *Fetcher) githubItem(ctx context.Context, u *url.URL, token, owner, repo, num string) (Preview, bool) {
var it struct {
Title string `json:"title"`
Body string `json:"body"`
State string `json:"state"`
StateReason string `json:"state_reason"`
Draft bool `json:"draft"`
Comments int `json:"comments"`
User struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
} `json:"user"`
PullRequest *struct {
MergedAt *string `json:"merged_at"`
} `json:"pull_request"`
}
if !f.github(ctx, token, fmt.Sprintf("/repos/%s/%s/issues/%s", url.PathEscape(owner), url.PathEscape(repo), num), &it) {
return Preview{}, false
}
p := Preview{URL: u.String(), Site: "GitHub", Title: clip(it.Title, 300), Description: clip(plainText(it.Body), 300)}
p.Kind = KindGitHubIssue
switch {
case it.PullRequest != nil && it.PullRequest.MergedAt != nil:
p.State, p.Status = "merged", "Merged"
case it.State == "closed" && it.StateReason == "not_planned":
p.State, p.Status = "canceled", "Closed"
case it.State == "closed":
p.State, p.Status = "closed", "Closed"
case it.Draft:
p.State, p.Status = "draft", "Draft"
default:
p.State, p.Status = "open", "Open"
}
if it.PullRequest != nil {
p.Kind = KindGitHubPull
}
meta := []string{fmt.Sprintf("%s/%s #%s", owner, repo, num)}
if it.User.Login != "" {
meta = append(meta, it.User.Login)
}
if it.Comments > 0 {
meta = append(meta, fmt.Sprintf("💬 %d", it.Comments))
}
p.Meta = strings.Join(meta, " · ")
p.Image = safeImage(it.User.AvatarURL)
return p, true
}
func (f *Fetcher) githubRepo(ctx context.Context, u *url.URL, token, owner, repo string) (Preview, bool) {
var r struct {
FullName string `json:"full_name"`
Description string `json:"description"`
Stars int `json:"stargazers_count"`
Language string `json:"language"`
Archived bool `json:"archived"`
Private bool `json:"private"`
Owner struct {
AvatarURL string `json:"avatar_url"`
} `json:"owner"`
}
if !f.github(ctx, token, fmt.Sprintf("/repos/%s/%s", url.PathEscape(owner), url.PathEscape(repo)), &r) || r.FullName == "" {
return Preview{}, false
}
p := Preview{URL: u.String(), Site: "GitHub", Title: clip(r.FullName, 300), Description: clip(r.Description, 300), Kind: KindGitHubRepo}
meta := []string{"★ " + shortCount(r.Stars)}
if r.Language != "" {
meta = append(meta, r.Language)
}
p.Meta = strings.Join(meta, " · ")
switch {
case r.Archived:
p.State, p.Status = "closed", "Archived"
case r.Private:
p.State, p.Status = "draft", "Private"
}
p.Image = safeImage(r.Owner.AvatarURL)
return p, true
}
func (f *Fetcher) linearIssue(ctx context.Context, u *url.URL, key, id string) (Preview, bool) {
body, _ := json.Marshal(map[string]any{
"query": `query($id: String!) { issue(id: $id) { identifier title description priorityLabel state { name type } assignee { name } team { name } } }`,
"variables": map[string]string{"id": id},
})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(f.api().Linear, "/")+"/graphql", bytes.NewReader(body))
if err != nil {
return Preview{}, false
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", key)
var out struct {
Data struct {
Issue *struct {
Identifier string `json:"identifier"`
Title string `json:"title"`
Description string `json:"description"`
PriorityLabel string `json:"priorityLabel"`
State struct {
Name string `json:"name"`
Type string `json:"type"`
} `json:"state"`
Assignee *struct {
Name string `json:"name"`
} `json:"assignee"`
Team struct {
Name string `json:"name"`
} `json:"team"`
} `json:"issue"`
} `json:"data"`
}
if !f.getJSON(req, &out) || out.Data.Issue == nil {
return Preview{}, false
}
is := out.Data.Issue
p := Preview{URL: u.String(), Site: "Linear", Title: clip(is.Title, 300), Description: clip(plainText(is.Description), 300), Kind: KindLinearIssue}
p.Status = clip(is.State.Name, 40)
p.State = linearState(is.State.Type)
meta := []string{is.Identifier}
if is.Team.Name != "" {
meta = append(meta, is.Team.Name)
}
if is.Assignee != nil && is.Assignee.Name != "" {
meta = append(meta, is.Assignee.Name)
}
if is.PriorityLabel != "" && is.PriorityLabel != "No priority" {
meta = append(meta, is.PriorityLabel)
}
p.Meta = clip(strings.Join(meta, " · "), 200)
return p, true
}
// linearState maps Linear's workflow state types onto the preview's states.
func linearState(t string) string {
switch t {
case "started":
return "started"
case "completed":
return "done"
case "canceled":
return "canceled"
case "backlog", "triage":
return "draft"
default:
return "open"
}
}
func (f *Fetcher) figmaFile(ctx context.Context, u *url.URL, token, key string) (Preview, bool) {
p := Preview{URL: u.String(), Site: "Figma", Kind: KindFigmaFile}
if token != "" {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(f.api().Figma, "/")+"/v1/files/"+url.PathEscape(key)+"?depth=1", nil)
if err == nil {
req.Header.Set("X-Figma-Token", token)
var file struct {
Name string `json:"name"`
ThumbnailURL string `json:"thumbnailUrl"`
LastModified string `json:"lastModified"`
EditorType string `json:"editorType"`
}
if f.getJSON(req, &file) && file.Name != "" {
p.Title = clip(file.Name, 300)
p.Image = safeImage(file.ThumbnailURL)
p.Meta = figmaMeta(file.EditorType, file.LastModified)
return p, true
}
}
}
// Public files describe themselves through oEmbed.
q := url.Values{"url": {u.String()}}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(f.api().FigmaWeb, "/")+"/api/oembed?"+q.Encode(), nil)
if err != nil {
return Preview{}, false
}
var oe struct {
Title string `json:"title"`
ThumbnailURL string `json:"thumbnail_url"`
}
if !f.getJSON(req, &oe) || oe.Title == "" {
return Preview{}, false
}
p.Title = clip(oe.Title, 300)
p.Image = safeImage(oe.ThumbnailURL)
p.Meta = figmaMeta("", "")
return p, true
}
func figmaMeta(editor, modified string) string {
kind := "Figma design"
switch editor {
case "figjam":
kind = "FigJam board"
case "slides":
kind = "Figma Slides"
}
if t, err := time.Parse(time.RFC3339, modified); err == nil {
return kind + " · " + t.UTC().Format("2006-01-02")
}
return kind
}
// safeImage keeps an https picture address and drops anything else.
func safeImage(s string) string {
u, err := url.Parse(s)
if err != nil || u.Scheme != "https" || u.Host == "" || len(s) > 2000 {
return ""
}
return s
}
// markup is what plainText strips from Markdown bodies.
var markup = regexp.MustCompile("(?m)^#+\\s*|[*_`>]+|!?\\[([^\\]]*)\\]\\([^)]*\\)|<[^>]+>")
// plainText is the start of a Markdown body as one line of text.
func plainText(md string) string {
return markup.ReplaceAllString(md, "$1")
}
// shortCount writes 1234 as 1.2k.
func shortCount(n int) string {
switch {
case n >= 1_000_000:
return strconv.FormatFloat(float64(n)/1e6, 'f', 1, 64) + "M"
case n >= 1000:
return strconv.FormatFloat(float64(n)/1e3, 'f', 1, 64) + "k"
}
return strconv.Itoa(n)
}
+124
View File
@@ -0,0 +1,124 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package unfurl
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
// onlyTo lets requests reach srv and fails every other one, so a test never
// goes to the real services.
type onlyTo struct{ host string }
func (o onlyTo) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Host != o.host {
return nil, errors.New("blocked in tests: " + r.URL.String())
}
return http.DefaultTransport.RoundTrip(r)
}
func fakeServices(t *testing.T) *Fetcher {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("GET /gh/repos/acme/app/issues/7", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"title":"Fix the login","body":"## Steps\n**Click** [here](https://x)","state":"closed","comments":3,
"user":{"login":"alice","avatar_url":"https://avatars.githubusercontent.com/u/1"},"pull_request":{"merged_at":"2026-11-01T10:00:00Z"}}`)
})
mux.HandleFunc("GET /gh/repos/acme/app/issues/8", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer ghtok" {
http.NotFound(w, r)
return
}
_, _ = io.WriteString(w, `{"title":"Private bug","state":"open","user":{"login":"bob","avatar_url":"javascript:x"}}`)
})
mux.HandleFunc("GET /gh/repos/acme/app", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"full_name":"acme/app","description":"The app","stargazers_count":1234,"language":"Go","owner":{"avatar_url":"https://avatars.githubusercontent.com/u/2"}}`)
})
mux.HandleFunc("POST /linear/graphql", func(w http.ResponseWriter, r *http.Request) {
var in struct {
Variables map[string]string `json:"variables"`
}
_ = json.NewDecoder(r.Body).Decode(&in)
if r.Header.Get("Authorization") != "lin_key" || in.Variables["id"] != "ENG-42" {
_, _ = io.WriteString(w, `{"data":{"issue":null}}`)
return
}
_, _ = io.WriteString(w, `{"data":{"issue":{"identifier":"ENG-42","title":"Ship search","description":"Do it","priorityLabel":"High",
"state":{"name":"In Progress","type":"started"},"assignee":{"name":"Carol"},"team":{"name":"Engineering"}}}}`)
})
mux.HandleFunc("GET /figma/v1/files/AbCdEfGhIjKl", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Figma-Token") != "figtok" {
w.WriteHeader(http.StatusForbidden)
return
}
_, _ = io.WriteString(w, `{"name":"Checkout flow","thumbnailUrl":"https://s3.figma.com/t.png","lastModified":"2026-11-02T08:00:00Z","editorType":"figma"}`)
})
mux.HandleFunc("GET /figweb/api/oembed", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"title":"Public board","thumbnail_url":"https://s3.figma.com/p.png"}`)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
host, _ := url.Parse(srv.URL)
f := NewWithClient(&http.Client{Transport: onlyTo{host: host.Host}})
return f.WithAPIs(APIs{GitHub: srv.URL + "/gh", Linear: srv.URL + "/linear", Figma: srv.URL + "/figma", FigmaWeb: srv.URL + "/figweb"})
}
func TestRichPreviews(t *testing.T) {
f := fakeServices(t)
ctx := context.Background()
tokens := Tokens{GitHub: "ghtok", Linear: "lin_key", Figma: "figtok"}
cases := []struct {
url string
tokens Tokens
want Preview
}{
{"https://github.com/acme/app/pull/7/files", Tokens{}, Preview{Kind: KindGitHubPull, Title: "Fix the login", Status: "Merged", State: "merged",
Meta: "acme/app #7 · alice · 💬 3", Description: "Steps Click here", Image: "https://avatars.githubusercontent.com/u/1", Site: "GitHub"}},
{"https://github.com/acme/app/issues/8", tokens, Preview{Kind: KindGitHubIssue, Title: "Private bug", Status: "Open", State: "open",
Meta: "acme/app #8 · bob", Site: "GitHub"}},
{"https://www.github.com/acme/app", Tokens{}, Preview{Kind: KindGitHubRepo, Title: "acme/app", Description: "The app", Meta: "★ 1.2k · Go",
Image: "https://avatars.githubusercontent.com/u/2", Site: "GitHub"}},
{"https://linear.app/acme/issue/eng-42/ship-search", tokens, Preview{Kind: KindLinearIssue, Title: "Ship search", Description: "Do it",
Status: "In Progress", State: "started", Meta: "ENG-42 · Engineering · Carol · High", Site: "Linear"}},
{"https://www.figma.com/design/AbCdEfGhIjKl/Checkout", tokens, Preview{Kind: KindFigmaFile, Title: "Checkout flow",
Image: "https://s3.figma.com/t.png", Meta: "Figma design · 2026-11-02", Site: "Figma"}},
{"https://www.figma.com/board/ZyXwVuTsRqPo/Board", Tokens{}, Preview{Kind: KindFigmaFile, Title: "Public board",
Image: "https://s3.figma.com/p.png", Meta: "Figma design", Site: "Figma"}},
}
for _, c := range cases {
got, err := f.PreviewWith(ctx, c.url, c.tokens)
if err != nil {
t.Fatalf("%s: %v", c.url, err)
}
c.want.URL = c.url
if got != c.want {
t.Errorf("%s:\n got %+v\nwant %+v", c.url, got, c.want)
}
}
}
func TestRichPreviewFallsBack(t *testing.T) {
f := fakeServices(t)
ctx := context.Background()
for _, raw := range []string{
"https://github.com/acme/app/issues/8", // private without a token
"https://linear.app/acme/issue/ENG-42/ship-search", // Linear needs a key
"https://github.com/settings/profile", // a page of the site, not a repository
} {
got, err := f.PreviewWith(ctx, raw, Tokens{})
if err != nil {
t.Fatal(err)
}
if got.Kind != "" || !strings.Contains(got.Site, ".") {
t.Errorf("%s: want the plain preview, got %+v", raw, got)
}
}
}
+18
View File
@@ -31,6 +31,14 @@ type Preview struct {
Description string `json:"description"`
Image string `json:"image"`
Site string `json:"site"`
// Kind, Status, State and Meta come from a service's API (rich.go):
// Kind like "github.pull", Status the service's word for it ("Merged",
// "In Progress"), State one of open, started, draft, merged, done,
// closed, canceled (for its colour), and Meta a line of details.
Kind string `json:"kind,omitempty"`
Status string `json:"status,omitempty"`
State string `json:"state,omitempty"`
Meta string `json:"meta,omitempty"`
}
// maxBody caps how much of a page is read; the tags are in its head.
@@ -38,6 +46,7 @@ const maxBody = 1 << 20
type Fetcher struct {
client *http.Client
apis *APIs // nil: the real services
}
// New returns a fetcher that refuses private, loopback and link-local
@@ -89,11 +98,20 @@ func Public(ip net.IP) bool {
// Preview fetches raw and reads its preview. Pages that are not HTML, or
// can't be reached, still get a preview with the address and site name.
func (f *Fetcher) Preview(ctx context.Context, raw string) (Preview, error) {
return f.PreviewWith(ctx, raw, Tokens{})
}
// PreviewWith is Preview with a workspace's tokens for the services that
// rich.go reads through their APIs.
func (f *Fetcher) PreviewWith(ctx context.Context, raw string, t Tokens) (Preview, error) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || len(raw) > 2000 {
return Preview{}, apperr.InvalidFields(map[string]string{"url": "Enter a web address (http or https)."})
}
u.Fragment = ""
if p, ok := f.rich(ctx, u, t); ok {
return p, nil
}
out := Preview{URL: u.String(), Site: siteName(u)}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
+13
View File
@@ -73,6 +73,16 @@ type Dispatcher struct {
opts Options
client *http.Client
queue chan job
// listeners see every event too (the Slack integration); set before Run.
listeners []func(Payload)
}
// Listen calls fn, on its own goroutine, for every event emitted from now on.
// Call it while setting up, before events flow.
func (d *Dispatcher) Listen(fn func(Payload)) {
if d != nil {
d.listeners = append(d.listeners, fn)
}
}
type job struct {
@@ -164,6 +174,9 @@ func (d *Dispatcher) Emit(workspace, event string, data any) {
return
}
p := Payload{ID: newID(), Event: event, Workspace: workspace, Created: time.Now().UTC().Format(time.RFC3339), Data: data}
for _, fn := range d.listeners {
go fn(p)
}
select {
case d.queue <- job{workspace: workspace, payload: p}:
default:
@@ -0,0 +1,295 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { IntegrationService, SlackIntegrationInput, WorkspaceIntegrations } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import { useFormErrors } from "../composables/useFormErrors";
// Workspace admins: tokens that let link previews read private GitHub,
// Linear and Figma items, and the workspace's own Slack app.
const props = defineProps<{ workspace: string }>();
const api = useApi();
const { t } = useI18n();
const errors = useFormErrors();
const view = ref<WorkspaceIntegrations | null>(null);
const busy = ref(false);
const notice = ref("");
const services: IntegrationService[] = ["github", "linear", "figma"];
const tokens = reactive<Record<IntegrationService, string>>({ github: "", linear: "", figma: "" });
const slackForm = reactive({ botToken: "", signingSecret: "", channel: "" });
const copied = ref("");
const slackEvents = [
"page.created",
"page.updated",
"page.moved",
"page.archived",
"page.unarchived",
"page.restored",
"comment.created",
"comment.resolved",
] as const;
const slack = computed(() => view.value?.slack);
// Checks that fail (a token the service refuses) come back per field.
const errorText = computed(() => errors.message.value || Object.values(errors.fields.value).join(" "));
async function load() {
const v = await api.workspaceIntegrations.get(props.workspace);
view.value = v;
slackForm.channel = v.slack.channelName ? `#${v.slack.channelName}` : "";
}
onMounted(() => load().catch(errors.show));
async function run(action: () => Promise<WorkspaceIntegrations | void>, done?: string) {
busy.value = true;
errors.reset();
notice.value = "";
try {
const v = await action();
if (v) view.value = v;
if (done) notice.value = done;
} catch (e) {
errors.show(e);
} finally {
busy.value = false;
}
}
const saveToken = (s: IntegrationService) =>
run(async () => {
const v = await api.workspaceIntegrations.setToken(props.workspace, s, tokens[s]);
tokens[s] = "";
return v;
}, t("integrations.saved"));
const removeToken = (s: IntegrationService) => run(() => api.workspaceIntegrations.setToken(props.workspace, s, ""));
function setSlack(input: SlackIntegrationInput, done?: string) {
return run(async () => {
const v = await api.workspaceIntegrations.setSlack(props.workspace, input);
if (input.botToken) slackForm.botToken = "";
if (input.signingSecret) slackForm.signingSecret = "";
if (v.slack.channelName) slackForm.channel = `#${v.slack.channelName}`;
return v;
}, done);
}
function connect() {
const input: SlackIntegrationInput = {};
if (slackForm.botToken.trim()) input.botToken = slackForm.botToken.trim();
if (slackForm.signingSecret.trim()) input.signingSecret = slackForm.signingSecret.trim();
if (slackForm.channel.trim() !== (slack.value?.channelName ? `#${slack.value.channelName}` : ""))
input.channel = slackForm.channel.trim();
void setSlack(input, t("integrations.saved"));
}
function toggleEvent(e: string, on: boolean) {
const list = new Set(slack.value?.events ?? []);
if (on) list.add(e);
else list.delete(e);
void setSlack({ events: slackEvents.filter((x) => list.has(x)) });
}
const test = () => run(() => api.workspaceIntegrations.testSlack(props.workspace), t("integrations.slackTested"));
function disconnect() {
if (!confirm(t("integrations.slackConfirmOff"))) return;
void run(() => api.workspaceIntegrations.deleteSlack(props.workspace));
}
async function copy(what: string, text: string) {
await navigator.clipboard.writeText(text);
copied.value = what;
setTimeout(() => (copied.value = ""), 2000);
}
</script>
<template>
<section class="dw-card" data-testid="workspace-integrations">
<h2 class="text-ui-lg">{{ $t("integrations.title") }}</h2>
<DwCallout v-if="errorText" tone="danger" size="ui" class="mt-3" data-testid="integrations-error">{{
errorText
}}</DwCallout>
<DwCallout v-else-if="notice" tone="success" size="ui" class="mt-3">{{ notice }}</DwCallout>
<template v-if="view">
<!-- Link previews -->
<h3 class="mt-4 text-ui-md font-semibold">{{ $t("integrations.previewsTitle") }}</h3>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("integrations.previewsHint") }}</p>
<div v-for="s in services" :key="s" class="mt-3" :data-testid="`token-${s}`">
<div class="flex items-center gap-2 text-ui-md">
<span class="font-medium">{{ $t(`integrations.${s}`) }}</span>
<span class="text-ui-sm" :class="view[s].set ? 'text-success' : 'text-ink-faint'">
{{ view[s].set ? $t("integrations.tokenSet") : $t("integrations.tokenNotSet") }}
</span>
</div>
<p class="text-ui-xs text-ink-faint">{{ $t(`integrations.${s}Hint`) }}</p>
<form class="mt-1 flex flex-wrap items-center gap-2" @submit.prevent="saveToken(s)">
<input
v-model="tokens[s]"
type="password"
autocomplete="off"
class="dw-input min-w-0 flex-1"
:placeholder="view[s].set ? $t('integrations.replaceToken') : $t('integrations.pasteToken')"
:aria-label="$t(`integrations.${s}`)"
/>
<DwButton type="submit" size="sm" :disabled="busy || !tokens[s].trim()">{{
$t("integrations.save")
}}</DwButton>
<DwButton v-if="view[s].set" type="button" size="sm" variant="ghost" :disabled="busy" @click="removeToken(s)">
{{ $t("integrations.remove") }}
</DwButton>
</form>
</div>
<!-- Slack -->
<h3 class="mt-6 text-ui-md font-semibold">{{ $t("integrations.slackTitle") }}</h3>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("integrations.slackHint") }}</p>
<div v-if="slack?.connected" class="mt-3 text-ui-md" data-testid="slack-connected">
{{ $t("integrations.slackConnected", { team: slack.teamName || slack.team }) }}
<span v-if="slack.channelName"> · #{{ slack.channelName }}</span>
</div>
<DwCallout v-if="slack?.lastError" tone="warning" size="ui" class="mt-2">
{{ $t("integrations.slackLastError", { error: slack.lastError }) }}
</DwCallout>
<ol class="mt-3 list-decimal space-y-3 pl-5 text-ui-sm">
<li>
{{ $t("integrations.slackStep1") }}
<a
href="https://api.slack.com/apps?new_app=1"
target="_blank"
rel="noopener noreferrer"
class="text-primary underline"
>
api.slack.com/apps
</a>
<div class="mt-1 flex items-start gap-2">
<textarea
readonly
class="dw-input h-24 min-w-0 flex-1 font-mono text-ui-xs"
:value="slack?.manifest"
:aria-label="$t('integrations.manifest')"
data-testid="slack-manifest"
/>
<DwButton type="button" size="sm" variant="ghost" @click="copy('manifest', slack?.manifest ?? '')">
{{ copied === "manifest" ? $t("integrations.copied") : $t("integrations.copy") }}
</DwButton>
</div>
</li>
<li>
{{ $t("integrations.slackStep2") }}
<form class="mt-1 grid gap-2" @submit.prevent="connect">
<input
v-model="slackForm.botToken"
type="password"
autocomplete="off"
class="dw-input"
:placeholder="slack?.connected ? $t('integrations.botTokenKeep') : 'xoxb-…'"
:aria-label="$t('integrations.botToken')"
data-testid="slack-bot-token"
/>
<input
v-model="slackForm.signingSecret"
type="password"
autocomplete="off"
class="dw-input"
:placeholder="slack?.hasSigningSecret ? $t('integrations.signingKeep') : $t('integrations.signingSecret')"
:aria-label="$t('integrations.signingSecret')"
data-testid="slack-signing-secret"
/>
<input
v-model="slackForm.channel"
class="dw-input"
:placeholder="$t('integrations.channelPlaceholder')"
:aria-label="$t('integrations.channel')"
data-testid="slack-channel"
/>
<div class="flex flex-wrap gap-2">
<DwButton type="submit" size="sm" :disabled="busy" data-testid="slack-save">{{
$t("integrations.save")
}}</DwButton>
<DwButton
v-if="slack?.connected && slack.channel"
type="button"
size="sm"
variant="ghost"
:disabled="busy"
@click="test"
>
{{ $t("integrations.slackTest") }}
</DwButton>
<DwButton
v-if="slack?.connected"
type="button"
size="sm"
variant="ghost"
:disabled="busy"
@click="disconnect"
>
{{ $t("integrations.slackDisconnect") }}
</DwButton>
</div>
</form>
</li>
</ol>
<div v-if="slack?.connected" class="mt-4 grid gap-2 text-ui-md" data-testid="slack-options">
<label class="flex items-start gap-3">
<input
type="checkbox"
class="mt-1 accent-primary"
:checked="slack.unfurl"
:disabled="busy"
@change="setSlack({ unfurl: ($event.target as HTMLInputElement).checked })"
/>
<span>
{{ $t("integrations.slackUnfurl") }}
<span class="block text-ui-sm text-ink-muted">{{ $t("integrations.slackUnfurlHint") }}</span>
</span>
</label>
<label class="flex items-start gap-3">
<input
type="checkbox"
class="mt-1 accent-primary"
:checked="slack.search"
:disabled="busy"
@change="setSlack({ search: ($event.target as HTMLInputElement).checked })"
/>
<span>
{{ $t("integrations.slackSearch") }}
<span class="block text-ui-sm text-ink-muted">{{ $t("integrations.slackSearchHint") }}</span>
</span>
</label>
<fieldset class="mt-2">
<legend class="text-ui-sm font-medium">{{ $t("integrations.slackEvents") }}</legend>
<p class="text-ui-xs text-ink-faint">{{ $t("integrations.slackEventsHint") }}</p>
<div class="mt-1 grid gap-1 sm:grid-cols-2">
<label v-for="e in slackEvents" :key="e" class="flex items-center gap-2 text-ui-sm">
<input
type="checkbox"
class="accent-primary"
:checked="slack.events.includes(e)"
:disabled="busy"
@change="toggleEvent(e, ($event.target as HTMLInputElement).checked)"
/>
{{ $t(`integrations.event.${e.replace(".", "_")}`) }}
</label>
</div>
</fieldset>
<details class="mt-2 text-ui-sm">
<summary class="cursor-pointer text-ink-muted">{{ $t("integrations.requestUrls") }}</summary>
<dl class="mt-1 grid gap-1 font-mono text-ui-xs">
<dt class="font-sans text-ink-muted">{{ $t("integrations.eventsUrl") }}</dt>
<dd class="break-all">{{ slack.eventsUrl }}</dd>
<dt class="font-sans text-ink-muted">{{ $t("integrations.commandsUrl") }}</dt>
<dd class="break-all">{{ slack.commandsUrl }}</dd>
</dl>
</details>
</div>
</template>
</section>
</template>
+57 -1
View File
@@ -235,7 +235,7 @@
},
"import": "Importieren",
"importing": "Wird importiert…",
"importHint": "Markdown, HTML, Word (.docx), CSV oder Readwise-CSV, OneNote (.mht), ein Bear-Backup (.bear2bk) oder ein Zip: Notion-Export, Obsidian-Vault, Bear-Notizen, Markdown-Ordner",
"importHint": "Markdown, HTML, Word (.docx), CSV oder Readwise-CSV, OneNote (.mht), ein Bear-Backup (.bear2bk) oder ein Zip: Confluence-Bereich (HTML-Export), Notion-Export, Obsidian-Vault, Bear-Notizen, Markdown-Ordner",
"sharedWithYou": "Mit dir geteilt",
"export": "Bereich exportieren",
"exporting": "Wird exportiert…",
@@ -1586,5 +1586,61 @@
"nobody": "Niemand Angemeldetes hat sie in diesem Zeitraum geöffnet.",
"timesOpened": "{n}-mal geöffnet | {n}-mal geöffnet",
"failed": "Aufrufe konnten nicht geladen werden."
},
"integrations": {
"title": "Integrationen",
"previewsTitle": "Linkvorschauen",
"previewsHint": "Links zu GitHub-Issues, Pull Requests und Repositorys, Linear-Issues und Figma-Dateien zeigen ihren Status und Details. Öffentliche Inhalte gehen ohne Token; mit einem sehen alle in diesem Workspace auch private.",
"github": "GitHub",
"githubHint": "Ein fein abgestuftes persönliches Zugriffstoken mit Lesezugriff auf Issues, Pull Requests und Metadaten der Repositorys.",
"linear": "Linear",
"linearHint": "Ein persönlicher API-Schlüssel (Linear → Settings → Security & access). Linear-Links brauchen ihn: Linear hat keine öffentlichen Seiten.",
"figma": "Figma",
"figmaHint": "Ein persönliches Zugriffstoken mit Lesezugriff auf Dateiinhalte. Ohne es haben nur öffentlich geteilte Dateien eine Vorschau.",
"tokenSet": "Token gespeichert",
"tokenNotSet": "Kein Token",
"pasteToken": "Token einfügen",
"replaceToken": "Neues Token einfügen, um es zu ersetzen",
"save": "Speichern",
"remove": "Entfernen",
"saved": "Gespeichert.",
"slackTitle": "Slack",
"slackHint": "Verbinde deine eigene Slack-App: Docwell meldet Seiten und Kommentare in einem Kanal, zeigt Vorschauen von Docwell-Links und beantwortet /docwell-Suchen. Gemeldet oder gezeigt werden nur Seiten, die alle in diesem Workspace öffnen können.",
"slackStep1": "Erstelle eine Slack-App aus diesem Manifest (Create New App → From a manifest) und installiere sie in deinem Slack:",
"slackStep2": "Füge das Bot User OAuth Token (OAuth & Permissions) und das Signing Secret (Basic Information) der App sowie den Kanal für Meldungen ein.",
"manifest": "Slack-App-Manifest",
"copy": "Kopieren",
"copied": "Kopiert",
"botToken": "Bot-Token",
"botTokenKeep": "Bot-Token gespeichert (neues einfügen, um es zu ersetzen)",
"signingSecret": "Signing Secret",
"signingKeep": "Signing Secret gespeichert (neues einfügen, um es zu ersetzen)",
"channel": "Kanal",
"channelPlaceholder": "#Kanal für Meldungen (optional)",
"slackConnected": "Verbunden mit {team}",
"slackLastError": "Die letzte Nachricht an Slack ging nicht durch: {error}",
"slackTest": "Testnachricht senden",
"slackTested": "Ein Hallo wurde in den Kanal gesendet.",
"slackDisconnect": "Trennen",
"slackConfirmOff": "Slack trennen? Docwell meldet, zeigt Vorschauen und beantwortet /docwell nicht mehr. Die App bleibt in Slack, bis du sie dort entfernst.",
"slackUnfurl": "Docwell-Links in Slack als Vorschau zeigen",
"slackUnfurlHint": "Slack zeigt Titel, Bereich und erste Zeilen der Seite – für Seiten, die alle in diesem Workspace öffnen können.",
"slackSearch": "Suche mit /docwell",
"slackSearchHint": "Wer mit seiner Slack-E-Mail Mitglied dieses Workspace ist, findet die Seiten, die er öffnen kann. Nur er sieht die Antwort.",
"slackEvents": "Im Kanal melden, wenn",
"slackEventsHint": "Änderungen werden pro Seite höchstens alle 30 Minuten gemeldet.",
"requestUrls": "Request-URLs (schon im Manifest)",
"eventsUrl": "Event Subscriptions",
"commandsUrl": "Befehl /docwell",
"event": {
"page_created": "eine Seite erstellt wird",
"page_updated": "eine Seite bearbeitet wird",
"page_moved": "eine Seite verschoben wird",
"page_archived": "eine Seite archiviert wird",
"page_unarchived": "eine Seite aus dem Archiv geholt wird",
"page_restored": "eine Seite aus dem Papierkorb geholt wird",
"comment_created": "jemand kommentiert",
"comment_resolved": "ein Kommentar erledigt wird"
}
}
}
+57 -1
View File
@@ -235,7 +235,7 @@
},
"import": "Import",
"importing": "Importing…",
"importHint": "Markdown, HTML, Word (.docx), CSV or Readwise CSV, OneNote (.mht), a Bear backup (.bear2bk), or a zip: Notion export, Obsidian vault, Bear notes, Markdown folder",
"importHint": "Markdown, HTML, Word (.docx), CSV or Readwise CSV, OneNote (.mht), a Bear backup (.bear2bk), or a zip: Confluence space (HTML export), Notion export, Obsidian vault, Bear notes, Markdown folder",
"sharedWithYou": "Shared with you",
"export": "Export space",
"exporting": "Exporting…",
@@ -1586,5 +1586,61 @@
"nobody": "Nobody signed in opened it in this period.",
"timesOpened": "Opened {n} time | Opened {n} times",
"failed": "Views could not be loaded."
},
"integrations": {
"title": "Integrations",
"previewsTitle": "Link previews",
"previewsHint": "Links to GitHub issues, pull requests and repositories, Linear issues and Figma files show their status and details. Public items work without a token; add one to preview private ones for everyone in this workspace.",
"github": "GitHub",
"githubHint": "A fine-grained personal access token with read access to issues, pull requests and metadata of the repositories to preview.",
"linear": "Linear",
"linearHint": "A personal API key (Linear → Settings → Security & access). Linear links need it: Linear has no public pages.",
"figma": "Figma",
"figmaHint": "A personal access token with read access to file content. Without it, only files shared publicly show a preview.",
"tokenSet": "Token saved",
"tokenNotSet": "No token",
"pasteToken": "Paste a token",
"replaceToken": "Paste a new token to replace it",
"save": "Save",
"remove": "Remove",
"saved": "Saved.",
"slackTitle": "Slack",
"slackHint": "Connect your own Slack app: Docwell posts page and comment news to a channel, shows previews of Docwell links, and answers /docwell searches. Only pages everyone in this workspace can open are posted or previewed.",
"slackStep1": "Create a Slack app from this manifest (Create New App → From a manifest), then install it to your Slack workspace:",
"slackStep2": "Paste the app's Bot User OAuth Token (OAuth & Permissions) and Signing Secret (Basic Information), and the channel for news.",
"manifest": "Slack app manifest",
"copy": "Copy",
"copied": "Copied",
"botToken": "Bot token",
"botTokenKeep": "Bot token saved (paste a new one to replace it)",
"signingSecret": "Signing Secret",
"signingKeep": "Signing Secret saved (paste a new one to replace it)",
"channel": "Channel",
"channelPlaceholder": "#channel for news (optional)",
"slackConnected": "Connected to {team}",
"slackLastError": "The last post to Slack failed: {error}",
"slackTest": "Send a test message",
"slackTested": "Posted a hello to the channel.",
"slackDisconnect": "Disconnect",
"slackConfirmOff": "Disconnect Slack? Docwell stops posting, previewing and answering /docwell. The app stays in Slack until you remove it there.",
"slackUnfurl": "Preview Docwell links in Slack",
"slackUnfurlHint": "Slack shows the page's title, space and first lines, for pages everyone in this workspace can open.",
"slackSearch": "Search with /docwell",
"slackSearchHint": "People whose Slack email belongs to a member of this workspace find the pages they can open. Only they see the answer.",
"slackEvents": "Post to the channel when",
"slackEventsHint": "Edits are posted at most once every 30 minutes per page.",
"requestUrls": "Request URLs (already in the manifest)",
"eventsUrl": "Event Subscriptions",
"commandsUrl": "Slash command /docwell",
"event": {
"page_created": "a page is created",
"page_updated": "a page is edited",
"page_moved": "a page is moved",
"page_archived": "a page is archived",
"page_unarchived": "a page is brought back from the archive",
"page_restored": "a page is restored from the trash",
"comment_created": "someone comments",
"comment_resolved": "a comment is resolved"
}
}
}
+57 -1
View File
@@ -235,7 +235,7 @@
},
"import": "Importar",
"importing": "Importando…",
"importHint": "Markdown, HTML, Word (.docx), CSV o CSV de Readwise, OneNote (.mht), una copia de Bear (.bear2bk) o un zip: exportación de Notion, bóveda de Obsidian, notas de Bear, carpeta de Markdown",
"importHint": "Markdown, HTML, Word (.docx), CSV o CSV de Readwise, OneNote (.mht), una copia de Bear (.bear2bk) o un zip: espacio de Confluence (exportación HTML), exportación de Notion, bóveda de Obsidian, notas de Bear, carpeta de Markdown",
"sharedWithYou": "Compartidas contigo",
"export": "Exportar espacio",
"exporting": "Exportando…",
@@ -1586,5 +1586,61 @@
"nobody": "Nadie con sesión iniciada la abrió en este periodo.",
"timesOpened": "Abierta {n} vez | Abierta {n} veces",
"failed": "No se pudieron cargar las vistas."
},
"integrations": {
"title": "Integraciones",
"previewsTitle": "Vistas previas de enlaces",
"previewsHint": "Los enlaces a incidencias, pull requests y repositorios de GitHub, incidencias de Linear y archivos de Figma muestran su estado y detalles. Lo público funciona sin token; añade uno para que todo el espacio de trabajo vea también lo privado.",
"github": "GitHub",
"githubHint": "Un token de acceso personal detallado con lectura de incidencias, pull requests y metadatos de los repositorios.",
"linear": "Linear",
"linearHint": "Una clave de API personal (Linear → Settings → Security & access). Los enlaces de Linear la necesitan: Linear no tiene páginas públicas.",
"figma": "Figma",
"figmaHint": "Un token de acceso personal con lectura del contenido de archivos. Sin él, solo los archivos compartidos públicamente tienen vista previa.",
"tokenSet": "Token guardado",
"tokenNotSet": "Sin token",
"pasteToken": "Pega un token",
"replaceToken": "Pega un token nuevo para reemplazarlo",
"save": "Guardar",
"remove": "Quitar",
"saved": "Guardado.",
"slackTitle": "Slack",
"slackHint": "Conecta tu propia app de Slack: Docwell publica novedades de páginas y comentarios en un canal, muestra vistas previas de enlaces a Docwell y responde búsquedas /docwell. Solo se publican o muestran páginas que todo el espacio de trabajo puede abrir.",
"slackStep1": "Crea una app de Slack con este manifiesto (Create New App → From a manifest) e instálala en tu Slack:",
"slackStep2": "Pega el Bot User OAuth Token (OAuth & Permissions) y el Signing Secret (Basic Information) de la app, y el canal de novedades.",
"manifest": "Manifiesto de la app de Slack",
"copy": "Copiar",
"copied": "Copiado",
"botToken": "Token del bot",
"botTokenKeep": "Token del bot guardado (pega uno nuevo para reemplazarlo)",
"signingSecret": "Signing Secret",
"signingKeep": "Signing Secret guardado (pega uno nuevo para reemplazarlo)",
"channel": "Canal",
"channelPlaceholder": "#canal de novedades (opcional)",
"slackConnected": "Conectado a {team}",
"slackLastError": "El último mensaje a Slack falló: {error}",
"slackTest": "Enviar un mensaje de prueba",
"slackTested": "Se publicó un saludo en el canal.",
"slackDisconnect": "Desconectar",
"slackConfirmOff": "¿Desconectar Slack? Docwell deja de publicar, mostrar vistas previas y responder a /docwell. La app sigue en Slack hasta que la quites allí.",
"slackUnfurl": "Vistas previas de enlaces de Docwell en Slack",
"slackUnfurlHint": "Slack muestra el título, el espacio y las primeras líneas de la página, para páginas que todo el espacio de trabajo puede abrir.",
"slackSearch": "Buscar con /docwell",
"slackSearchHint": "Quien tenga en Slack el correo de un miembro de este espacio de trabajo encuentra las páginas que puede abrir. Solo esa persona ve la respuesta.",
"slackEvents": "Publicar en el canal cuando",
"slackEventsHint": "Los cambios se publican como mucho una vez cada 30 minutos por página.",
"requestUrls": "URL de solicitud (ya están en el manifiesto)",
"eventsUrl": "Event Subscriptions",
"commandsUrl": "Comando /docwell",
"event": {
"page_created": "se crea una página",
"page_updated": "se edita una página",
"page_moved": "se mueve una página",
"page_archived": "se archiva una página",
"page_unarchived": "una página vuelve del archivo",
"page_restored": "una página vuelve de la papelera",
"comment_created": "alguien comenta",
"comment_resolved": "se resuelve un comentario"
}
}
}
+57 -1
View File
@@ -235,7 +235,7 @@
},
"import": "Importer",
"importing": "Importation…",
"importHint": "Markdown, HTML, Word (.docx), CSV ou CSV Readwise, OneNote (.mht), une sauvegarde Bear (.bear2bk) ou un zip : export Notion, coffre Obsidian, notes Bear, dossier Markdown",
"importHint": "Markdown, HTML, Word (.docx), CSV ou CSV Readwise, OneNote (.mht), une sauvegarde Bear (.bear2bk) ou un zip : espace Confluence (export HTML), export Notion, coffre Obsidian, notes Bear, dossier Markdown",
"sharedWithYou": "Partagées avec vous",
"export": "Exporter l’espace",
"exporting": "Exportation…",
@@ -1586,5 +1586,61 @@
"nobody": "Personne de connecté ne l'a ouverte sur cette période.",
"timesOpened": "Ouverte {n} fois | Ouverte {n} fois",
"failed": "Impossible de charger les vues."
},
"integrations": {
"title": "Intégrations",
"previewsTitle": "Aperçus de liens",
"previewsHint": "Les liens vers des tickets, pull requests et dépôts GitHub, des tickets Linear et des fichiers Figma montrent leur état et leurs détails. Les éléments publics marchent sans jeton ; ajoutez-en un pour que tout l’espace de travail voie aussi les privés.",
"github": "GitHub",
"githubHint": "Un jeton d’accès personnel à granularité fine, en lecture sur les tickets, pull requests et métadonnées des dépôts.",
"linear": "Linear",
"linearHint": "Une clé d’API personnelle (Linear → Settings → Security & access). Les liens Linear en ont besoin : Linear n’a pas de pages publiques.",
"figma": "Figma",
"figmaHint": "Un jeton d’accès personnel en lecture sur le contenu des fichiers. Sans lui, seuls les fichiers partagés publiquement ont un aperçu.",
"tokenSet": "Jeton enregistré",
"tokenNotSet": "Aucun jeton",
"pasteToken": "Collez un jeton",
"replaceToken": "Collez un nouveau jeton pour le remplacer",
"save": "Enregistrer",
"remove": "Retirer",
"saved": "Enregistré.",
"slackTitle": "Slack",
"slackHint": "Connectez votre propre app Slack : Docwell publie les nouvelles des pages et commentaires dans un canal, montre l’aperçu des liens Docwell et répond aux recherches /docwell. Seules les pages que tout l’espace de travail peut ouvrir sont publiées ou montrées.",
"slackStep1": "Créez une app Slack à partir de ce manifeste (Create New App → From a manifest), puis installez-la dans votre Slack :",
"slackStep2": "Collez le Bot User OAuth Token (OAuth & Permissions) et le Signing Secret (Basic Information) de l’app, et le canal des nouvelles.",
"manifest": "Manifeste de l’app Slack",
"copy": "Copier",
"copied": "Copié",
"botToken": "Jeton du bot",
"botTokenKeep": "Jeton du bot enregistré (collez-en un nouveau pour le remplacer)",
"signingSecret": "Signing Secret",
"signingKeep": "Signing Secret enregistré (collez-en un nouveau pour le remplacer)",
"channel": "Canal",
"channelPlaceholder": "#canal des nouvelles (facultatif)",
"slackConnected": "Connecté à {team}",
"slackLastError": "Le dernier message à Slack a échoué : {error}",
"slackTest": "Envoyer un message de test",
"slackTested": "Un bonjour a été publié dans le canal.",
"slackDisconnect": "Déconnecter",
"slackConfirmOff": "Déconnecter Slack ? Docwell arrête de publier, de montrer des aperçus et de répondre à /docwell. L’app reste dans Slack tant que vous ne l’y retirez pas.",
"slackUnfurl": "Aperçu des liens Docwell dans Slack",
"slackUnfurlHint": "Slack montre le titre, l’espace et les premières lignes de la page, pour les pages que tout l’espace de travail peut ouvrir.",
"slackSearch": "Recherche avec /docwell",
"slackSearchHint": "Les personnes dont l’e-mail Slack est celui d’un membre de cet espace de travail trouvent les pages qu’elles peuvent ouvrir. Elles seules voient la réponse.",
"slackEvents": "Publier dans le canal quand",
"slackEventsHint": "Les modifications sont publiées au plus une fois toutes les 30 minutes par page.",
"requestUrls": "URL de requête (déjà dans le manifeste)",
"eventsUrl": "Event Subscriptions",
"commandsUrl": "Commande /docwell",
"event": {
"page_created": "une page est créée",
"page_updated": "une page est modifiée",
"page_moved": "une page est déplacée",
"page_archived": "une page est archivée",
"page_unarchived": "une page sort des archives",
"page_restored": "une page sort de la corbeille",
"comment_created": "quelqu’un commente",
"comment_resolved": "un commentaire est résolu"
}
}
}
+57 -1
View File
@@ -235,7 +235,7 @@
},
"import": "Importuj",
"importing": "Importowanie…",
"importHint": "Markdown, HTML, Word (.docx), CSV lub CSV z Readwise, OneNote (.mht), kopia Bear (.bear2bk) albo zip: eksport z Notion, sejf Obsidian, notatki Bear, folder Markdown",
"importHint": "Markdown, HTML, Word (.docx), CSV lub CSV z Readwise, OneNote (.mht), kopia Bear (.bear2bk) albo zip: przestrzeń Confluence (eksport HTML), eksport z Notion, sejf Obsidian, notatki Bear, folder Markdown",
"sharedWithYou": "Udostępnione Tobie",
"export": "Eksportuj przestrzeń",
"exporting": "Eksportowanie…",
@@ -1586,5 +1586,61 @@
"nobody": "Nikt zalogowany nie otworzył jej w tym okresie.",
"timesOpened": "Otwarta {n} raz | Otwarta {n} razy | Otwarta {n} razy",
"failed": "Nie udało się wczytać wyświetleń."
},
"integrations": {
"title": "Integracje",
"previewsTitle": "Podglądy linków",
"previewsHint": "Linki do zgłoszeń, pull requestów i repozytoriów GitHub, zgłoszeń Linear i plików Figma pokazują swój stan i szczegóły. Publiczne elementy działają bez tokenu; dodaj go, by wszyscy w tym obszarze roboczym widzieli podgląd prywatnych.",
"github": "GitHub",
"githubHint": "Szczegółowy osobisty token dostępu z odczytem zgłoszeń, pull requestów i metadanych podglądanych repozytoriów.",
"linear": "Linear",
"linearHint": "Osobisty klucz API (Linear → Settings → Security & access). Linki Linear go wymagają: Linear nie ma publicznych stron.",
"figma": "Figma",
"figmaHint": "Osobisty token dostępu z odczytem zawartości plików. Bez niego podgląd mają tylko pliki udostępnione publicznie.",
"tokenSet": "Token zapisany",
"tokenNotSet": "Brak tokenu",
"pasteToken": "Wklej token",
"replaceToken": "Wklej nowy token, by go zastąpić",
"save": "Zapisz",
"remove": "Usuń",
"saved": "Zapisano.",
"slackTitle": "Slack",
"slackHint": "Podłącz własną aplikację Slack: Docwell wysyła na kanał wiadomości o stronach i komentarzach, pokazuje podglądy linków do Docwell i odpowiada na wyszukiwania /docwell. Wysyłane i podglądane są tylko strony, które może otworzyć każdy w tym obszarze roboczym.",
"slackStep1": "Utwórz aplikację Slack z tego manifestu (Create New App → From a manifest), a potem zainstaluj ją w swoim Slacku:",
"slackStep2": "Wklej Bot User OAuth Token aplikacji (OAuth & Permissions), Signing Secret (Basic Information) i kanał na wiadomości.",
"manifest": "Manifest aplikacji Slack",
"copy": "Kopiuj",
"copied": "Skopiowano",
"botToken": "Token bota",
"botTokenKeep": "Token bota zapisany (wklej nowy, by go zastąpić)",
"signingSecret": "Signing Secret",
"signingKeep": "Signing Secret zapisany (wklej nowy, by go zastąpić)",
"channel": "Kanał",
"channelPlaceholder": "#kanał na wiadomości (opcjonalnie)",
"slackConnected": "Połączono z {team}",
"slackLastError": "Ostatnia wiadomość do Slacka nie dotarła: {error}",
"slackTest": "Wyślij wiadomość testową",
"slackTested": "Wysłano powitanie na kanał.",
"slackDisconnect": "Odłącz",
"slackConfirmOff": "Odłączyć Slacka? Docwell przestanie wysyłać wiadomości, pokazywać podglądy i odpowiadać na /docwell. Aplikacja zostaje w Slacku, dopóki jej tam nie usuniesz.",
"slackUnfurl": "Podglądy linków do Docwell w Slacku",
"slackUnfurlHint": "Slack pokazuje tytuł strony, przestrzeń i pierwsze linijki — dla stron, które może otworzyć każdy w tym obszarze roboczym.",
"slackSearch": "Wyszukiwanie przez /docwell",
"slackSearchHint": "Osoby, których e-mail w Slacku należy do członka tego obszaru roboczego, znajdują strony, które mogą otworzyć. Odpowiedź widzą tylko one.",
"slackEvents": "Wysyłaj na kanał, gdy",
"slackEventsHint": "Zmiany strony są wysyłane najwyżej raz na 30 minut.",
"requestUrls": "Adresy żądań (już są w manifeście)",
"eventsUrl": "Event Subscriptions",
"commandsUrl": "Polecenie /docwell",
"event": {
"page_created": "powstaje strona",
"page_updated": "strona jest edytowana",
"page_moved": "strona jest przenoszona",
"page_archived": "strona trafia do archiwum",
"page_unarchived": "strona wraca z archiwum",
"page_restored": "strona wraca z kosza",
"comment_created": "ktoś komentuje",
"comment_resolved": "komentarz jest rozwiązany"
}
}
}
+1 -1
View File
@@ -88,7 +88,7 @@ const pageLinks = usePageLinks(
() => (page.value && editable.value ? { space: page.value.space, id: page.value.id } : undefined),
);
// Link cards: docwell-server reads the linked page's title and picture.
const linkHost = { preview: (url: string) => api.pages.preview(url) };
const linkHost = { preview: (url: string) => api.pages.preview(url, page.value?.workspace) };
// Links to one block: "#b-<id>" after the page's address. The margin button
// copies one; opening one scrolls to the block once the text has loaded.
@@ -14,6 +14,7 @@ import WorkspaceSharing from "../../components/WorkspaceSharing.vue";
import WorkspaceProperties from "../../components/WorkspaceProperties.vue";
import WorkspaceTags from "../../components/WorkspaceTags.vue";
import WorkspaceWebhooks from "../../components/WorkspaceWebhooks.vue";
import WorkspaceIntegrations from "../../components/WorkspaceIntegrations.vue";
import { useFormErrors } from "../../composables/useFormErrors";
import { useAuthStore } from "../../stores/auth";
import { atLeast, grantableRoles, useWorkspacesStore } from "../../stores/workspaces";
@@ -275,6 +276,7 @@ async function removeWorkspace() {
<WorkspaceGroups v-if="atLeast(myRole, 'member')" :workspace="ws.id" :can-manage="canManage" />
<WorkspaceProperties :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
<WorkspaceTags :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
<WorkspaceIntegrations v-if="canManage" :workspace="ws.id" />
<WorkspaceWebhooks v-if="canManage" :workspace="ws.id" />
<WorkspaceAI v-if="canManage" :workspace="ws.id" />
+185 -1
View File
@@ -1251,10 +1251,14 @@ paths:
description: >-
docwell-server fetches the page itself (public addresses only: private, loopback
and link-local ones are refused, redirects included). A page that can't be read
still gets a preview with its address and site name.
still gets a preview with its address and site name. GitHub issues, pull requests and
repositories, Linear issues and Figma files are read through their APIs and get a kind,
status and details; with workspace set (a workspace the caller belongs to), that
workspace's tokens reach private items.
security: [{ bearer: [] }]
parameters:
- { name: url, in: query, required: true, schema: { type: string, maxLength: 2000 } }
- { name: workspace, in: query, required: false, schema: { type: string } }
responses:
"200":
description: OK
@@ -3396,6 +3400,134 @@ paths:
"401": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/integrations:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getWorkspaceIntegrations
tags: [integrations]
summary: The workspace's integrations (workspace admin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/WorkspaceIntegrations" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/integrations/tokens/{service}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
- { name: service, in: path, required: true, schema: { type: string, enum: [github, linear, figma] } }
put:
operationId: setIntegrationToken
tags: [integrations]
summary: Store a token for link previews (workspace admin); an empty token removes it
description: >-
The token is checked with the service first (GitHub /user, Linear viewer, Figma /v1/me), then
sealed. Link previews of members of the workspace use it to read private items.
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [token]
properties:
token: { type: string, maxLength: 500 }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/WorkspaceIntegrations" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/integrations/slack:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
put:
operationId: setSlackIntegration
tags: [integrations]
summary: Connect or change the workspace's Slack app (workspace admin); missing fields stay as they are
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/SlackIntegrationInput" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/WorkspaceIntegrations" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteSlackIntegration
tags: [integrations]
summary: Disconnect Slack (workspace admin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/WorkspaceIntegrations" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/integrations/slack/test:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: testSlackIntegration
tags: [integrations]
summary: Post a hello to the Slack channel (workspace admin)
security: [{ bearer: [] }]
responses:
"204": { description: Posted }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/slack/{workspace}/events:
parameters:
- { name: workspace, in: path, required: true, schema: { type: string } }
post:
operationId: slackEvents
tags: [integrations]
summary: "Slack's Events API for one workspace's app: the URL check, and link_shared (Docwell link previews)"
description: >-
Called by Slack, signed with the app's Signing Secret (X-Slack-Signature, at most five minutes
old). Only pages every member of the workspace can open get a preview.
requestBody:
required: true
content:
application/json:
schema: { type: object, additionalProperties: true }
responses:
"200": { description: Taken (the URL check answers with its challenge) }
"401": { description: Bad or missing signature }
/api/v1/slack/{workspace}/commands:
parameters:
- { name: workspace, in: path, required: true, schema: { type: string } }
post:
operationId: slackCommands
tags: [integrations]
summary: "The /docwell slash command: a search as the Docwell member with the Slack user's email"
description: Called by Slack, signed like the events. The answer is shown only to the person who asked.
requestBody:
required: true
content:
application/x-www-form-urlencoded:
schema: { type: object, additionalProperties: true }
responses:
"200": { description: An ephemeral Slack message }
"401": { description: Bad or missing signature }
/api/v1/workspaces/{id}/webhooks:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
@@ -4463,6 +4595,58 @@ components:
description: { type: string }
image: { type: string, description: Address of the page's picture on its own site; empty when it has none }
site: { type: string }
kind:
type: string
description: For links read through a service's API (github.issue, github.pull, github.repo, linear.issue, figma.file)
status: { type: string, description: "The service's word for the item's state (Open, Merged, In Progress)" }
state:
type: string
description: The state for its colour
enum: [open, started, draft, merged, done, closed, canceled]
meta: { type: string, description: "A line of details (acme/app #12 · alice)" }
WorkspaceIntegrations:
type: object
required: [github, linear, figma, slack]
properties:
github: { $ref: "#/components/schemas/IntegrationToken" }
linear: { $ref: "#/components/schemas/IntegrationToken" }
figma: { $ref: "#/components/schemas/IntegrationToken" }
slack: { $ref: "#/components/schemas/SlackIntegration" }
IntegrationToken:
type: object
required: [set]
properties:
set: { type: boolean, description: A token is stored (it is never sent back) }
SlackIntegration:
type: object
required: [connected, hasSigningSecret, team, teamName, channel, channelName, events, unfurl, search, lastError, eventsUrl, commandsUrl, manifest]
properties:
connected: { type: boolean, description: A bot token is stored }
hasSigningSecret: { type: boolean }
team: { type: string, description: The Slack workspace id the bot belongs to }
teamName: { type: string }
channel: { type: string, description: The channel id posts go to; empty for none }
channelName: { type: string }
events: { type: array, items: { type: string }, description: Events posted to the channel }
unfurl: { type: boolean, description: Docwell links posted in Slack get a preview }
search: { type: boolean, description: /docwell searches Docwell }
lastError: { type: string, description: The last post that failed; empty when the last one worked }
eventsUrl: { type: string, description: Request URL for the Slack app's Event Subscriptions }
commandsUrl: { type: string, description: Request URL for the /docwell slash command }
manifest: { type: string, description: A Slack app manifest (JSON) with those URLs and the scopes Docwell needs }
SlackIntegrationInput:
type: object
properties:
botToken: { type: string, description: The app's Bot User OAuth Token (xoxb-…); checked with Slack }
signingSecret: { type: string, description: The app's Signing Secret }
channel: { type: string, description: "A public channel id or name (#news); empty for none" }
events:
type: array
items:
type: string
enum: [page.created, page.updated, page.moved, page.archived, page.unarchived, page.restored, comment.created, comment.resolved]
unfurl: { type: boolean }
search: { type: boolean }
Session:
type: object
required: [token, user]