@alexsun-top/opencode-chat-room 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/LICENSE +2 -2
- package/README.md +40 -8
- package/README.zh-CN.md +40 -8
- package/cli.ts +27 -1
- package/dist/cli.js +5406 -3088
- package/package.json +25 -5
- package/packages/chat-room-channeld/README.md +111 -33
- package/packages/chat-room-channeld/src/adapter.ts +179 -7
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +142 -9
- package/packages/chat-room-channeld/src/inbound.ts +35 -0
- package/packages/chat-room-channeld/src/protocol.ts +52 -1
- package/packages/chat-room-channeld/src/rules.ts +7 -2
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/plugin.ts +1 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +21 -9
- package/server/assets/chat/admin.js +0 -2
- package/server/assets/chat/announcements.js +69 -8
- package/server/assets/chat/chat-background.js +177 -0
- package/server/assets/chat/confirm-dialog.js +0 -1
- package/server/assets/chat/create-room-dialog.js +0 -1
- package/server/assets/chat/diagram-viewer.js +7 -1
- package/server/assets/chat/doc-preview.js +251 -46
- package/server/assets/chat/events.js +16 -5
- package/server/assets/chat/files.js +53 -7
- package/server/assets/chat/image-zoom.js +8 -1
- package/server/assets/chat/index.js +6 -2
- package/server/assets/chat/integration-account-schema.js +99 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +648 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown-footnotes.js +1 -1
- package/server/assets/chat/markdown.js +45 -8
- package/server/assets/chat/messages.js +6 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/palette.js +6 -1
- package/server/assets/chat/panels.js +56 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +17 -6
- package/server/assets/chat/reminders.js +68 -9
- package/server/assets/chat/replies.js +0 -6
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/rooms.js +1 -6
- package/server/assets/chat/settings.js +98 -4
- package/server/assets/chat/shortcuts.js +0 -3
- package/server/assets/chat/side-pane.js +34 -10
- package/server/assets/chat/state.js +125 -12
- package/server/assets/chat/system-events.js +58 -0
- package/server/assets/chat/system-messages.js +32 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +119 -37
- package/server/assets/chat/window-controls.js +37 -0
- package/server/assets/code-highlight.css +71 -32
- package/server/assets/conversation.css +174 -31
- package/server/assets/doc-preview.css +40 -3
- package/server/assets/files.css +8 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1605 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +80 -11
- package/server/assets/settings.css +185 -9
- package/server/assets/tasks.css +57 -7
- package/server/assets/window-controls.css +36 -0
- package/server/channel-attachments.ts +133 -0
- package/server/channel-integration.ts +572 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +274 -21
- package/server/chat-server.ts +32 -580
- package/server/chat.html +234 -34
- package/server/http-server.ts +3 -182
- package/server/manifest.webmanifest +1 -0
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +5 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +3 -11
- package/src/config/file-config.ts +7 -54
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/watch.ts +1 -1
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +133 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +130 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +194 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +34 -0
- package/src/state/sqlite-state.ts +15 -897
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +573 -0
- package/src/web/integration-rules.ts +26 -0
- package/src/web/integration-schema.ts +229 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
- package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -499
- package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -473
- package/server/assets/chat/forward.js +0 -69
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
|
|
3
|
+
// JSON Schema shared by the Monaco JSON language service and the plain-text fallback.
|
|
4
|
+
export type RuleAccount = { id: string; platform: string };
|
|
5
|
+
|
|
6
|
+
export type JsonSchema = {
|
|
7
|
+
type?: "array" | "object" | "string" | "integer" | "number" | "boolean";
|
|
8
|
+
title?: string;
|
|
9
|
+
description?: string;
|
|
10
|
+
required?: string[];
|
|
11
|
+
properties?: Record<string, JsonSchema>;
|
|
12
|
+
additionalProperties?: boolean;
|
|
13
|
+
items?: JsonSchema;
|
|
14
|
+
minItems?: number;
|
|
15
|
+
enum?: unknown[];
|
|
16
|
+
const?: unknown;
|
|
17
|
+
minLength?: number;
|
|
18
|
+
minimum?: number;
|
|
19
|
+
anyOf?: JsonSchema[];
|
|
20
|
+
oneOf?: JsonSchema[];
|
|
21
|
+
allOf?: JsonSchema[];
|
|
22
|
+
if?: JsonSchema;
|
|
23
|
+
then?: JsonSchema;
|
|
24
|
+
errorMessage?: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type SchemaIssue = { path: Array<string | number>; message: string; keyword: string };
|
|
28
|
+
|
|
29
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
30
|
+
Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
31
|
+
|
|
32
|
+
const accountEnum = (accounts: RuleAccount[]): JsonSchema => ({
|
|
33
|
+
type: "string",
|
|
34
|
+
enum: accounts.map((account) => account.id),
|
|
35
|
+
errorMessage: accounts.length
|
|
36
|
+
? "Account does not exist. Add it under Accounts first."
|
|
37
|
+
: "Add an account under Accounts first.",
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const platformEnum = (accounts: RuleAccount[]): JsonSchema => ({
|
|
41
|
+
type: "string",
|
|
42
|
+
enum: [...new Set(accounts.map((account) => account.platform))],
|
|
43
|
+
errorMessage: "Use the platform of the selected account.",
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
function target(accounts: RuleAccount[]): JsonSchema {
|
|
47
|
+
return {
|
|
48
|
+
type: "object",
|
|
49
|
+
additionalProperties: false,
|
|
50
|
+
required: ["platform", "account", "room"],
|
|
51
|
+
properties: {
|
|
52
|
+
platform: platformEnum(accounts),
|
|
53
|
+
account: accountEnum(accounts),
|
|
54
|
+
room: { type: "string", minLength: 1, description: "Target room ID." },
|
|
55
|
+
},
|
|
56
|
+
allOf: accounts.map((account) => ({
|
|
57
|
+
if: { required: ["account"], properties: { account: { const: account.id } } },
|
|
58
|
+
then: { properties: { platform: { const: account.platform, errorMessage: `Account "${account.id}" uses platform "${account.platform}".` } } },
|
|
59
|
+
})),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const transformSchema: JsonSchema = {
|
|
64
|
+
anyOf: [
|
|
65
|
+
{ type: "object", additionalProperties: false, required: ["op"], properties: { op: { const: "prefix-source" } } },
|
|
66
|
+
{ type: "object", additionalProperties: false, required: ["op"], properties: { op: { const: "trim" } } },
|
|
67
|
+
{ type: "object", additionalProperties: false, required: ["op"], properties: { op: { const: "quote-preview" } } },
|
|
68
|
+
{
|
|
69
|
+
type: "object",
|
|
70
|
+
additionalProperties: false,
|
|
71
|
+
required: ["op", "max"],
|
|
72
|
+
properties: { op: { const: "truncate" }, max: { type: "integer", minimum: 1 } },
|
|
73
|
+
},
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export function buildRulesSchema(accounts: RuleAccount[]): JsonSchema {
|
|
78
|
+
return {
|
|
79
|
+
$schema: "http://json-schema.org/draft-07/schema#",
|
|
80
|
+
title: "Integration rules",
|
|
81
|
+
type: "array",
|
|
82
|
+
items: {
|
|
83
|
+
type: "object",
|
|
84
|
+
additionalProperties: false,
|
|
85
|
+
required: ["id", "version", "from", "to"],
|
|
86
|
+
properties: {
|
|
87
|
+
id: { type: "string", minLength: 1, description: "Rule name, unique with its version." },
|
|
88
|
+
version: { type: "integer", minimum: 1, description: "Bump the version to replace this rule." },
|
|
89
|
+
from: {
|
|
90
|
+
type: "object",
|
|
91
|
+
description: "Where the rule reads events from.",
|
|
92
|
+
additionalProperties: false,
|
|
93
|
+
required: ["platform", "account", "room"],
|
|
94
|
+
properties: {
|
|
95
|
+
platform: { const: "chatroom", description: "Source platform; room messages always use chatroom.", errorMessage: "The source platform must be chatroom." },
|
|
96
|
+
account: { const: "center", description: "Source account; room messages always use center.", errorMessage: "The source account must be center." },
|
|
97
|
+
room: { type: "string", minLength: 1, description: "Room ID to watch." },
|
|
98
|
+
event: {
|
|
99
|
+
enum: ["message.created", "message.forward_requested"],
|
|
100
|
+
description: "Event to match; all supported events when omitted.",
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
transforms: { type: "array", description: "Transformations applied to the message before delivery.", items: transformSchema },
|
|
105
|
+
to: { type: "array", description: "External accounts and rooms that receive matching messages.", minItems: 1, items: target(accounts) },
|
|
106
|
+
onMissingParent: { enum: ["quote_or_unthreaded", "drop"], description: "What to do when the replied-to parent message is unavailable on the target." },
|
|
107
|
+
onUnsupported: { enum: ["text_with_notice", "drop"], description: "What to do when the target cannot render the message content." },
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
} as JsonSchema;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function buildInboundSchema(accounts: RuleAccount[]): JsonSchema {
|
|
114
|
+
return {
|
|
115
|
+
$schema: "http://json-schema.org/draft-07/schema#",
|
|
116
|
+
title: "Inbound routes",
|
|
117
|
+
type: "array",
|
|
118
|
+
items: {
|
|
119
|
+
type: "object",
|
|
120
|
+
required: ["from", "to"],
|
|
121
|
+
properties: {
|
|
122
|
+
from: {
|
|
123
|
+
type: "object",
|
|
124
|
+
required: ["platform", "account", "room"],
|
|
125
|
+
properties: {
|
|
126
|
+
platform: platformEnum(accounts),
|
|
127
|
+
account: accountEnum(accounts),
|
|
128
|
+
room: { type: "string", minLength: 1, description: "Room ID on the external platform." },
|
|
129
|
+
event: { type: "string", description: "Optional external event filter." },
|
|
130
|
+
},
|
|
131
|
+
allOf: accounts.map((account) => ({
|
|
132
|
+
if: { required: ["account"], properties: { account: { const: account.id } } },
|
|
133
|
+
then: { properties: { platform: { const: account.platform, errorMessage: `Account "${account.id}" uses platform "${account.platform}".` } } },
|
|
134
|
+
})),
|
|
135
|
+
},
|
|
136
|
+
to: {
|
|
137
|
+
type: "object",
|
|
138
|
+
required: ["room"],
|
|
139
|
+
properties: { room: { type: "string", minLength: 1, description: "Chat room ID that receives the message." } },
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
} as JsonSchema;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function matchesType(value: unknown, type: JsonSchema["type"]): boolean {
|
|
147
|
+
switch (type) {
|
|
148
|
+
case undefined: return true;
|
|
149
|
+
case "object": return isRecord(value);
|
|
150
|
+
case "array": return Array.isArray(value);
|
|
151
|
+
case "string": return typeof value === "string";
|
|
152
|
+
case "integer": return typeof value === "number" && Number.isInteger(value);
|
|
153
|
+
case "number": return typeof value === "number" && Number.isFinite(value);
|
|
154
|
+
case "boolean": return typeof value === "boolean";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function sameValue(left: unknown, right: unknown): boolean {
|
|
159
|
+
return Object.is(left, right);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function validateAgainstSchema(
|
|
163
|
+
value: unknown,
|
|
164
|
+
schema: JsonSchema,
|
|
165
|
+
path: Array<string | number> = [],
|
|
166
|
+
issues: SchemaIssue[] = [],
|
|
167
|
+
): SchemaIssue[] {
|
|
168
|
+
const fail = (message: string, keyword: string, at = path) => {
|
|
169
|
+
issues.push({ path: at, message: schema.errorMessage || message, keyword });
|
|
170
|
+
};
|
|
171
|
+
if (!matchesType(value, schema.type)) {
|
|
172
|
+
fail(`Expected ${schema.type ?? "a supported value"}.`, "type");
|
|
173
|
+
return issues;
|
|
174
|
+
}
|
|
175
|
+
if (schema.const !== undefined && !sameValue(value, schema.const)) {
|
|
176
|
+
fail(`Must be ${JSON.stringify(schema.const)}.`, "const");
|
|
177
|
+
}
|
|
178
|
+
if (schema.enum && !schema.enum.some((item) => sameValue(item, value))) {
|
|
179
|
+
fail(`Must be one of: ${schema.enum.map((item) => JSON.stringify(item)).join(", ")}.`, "enum");
|
|
180
|
+
}
|
|
181
|
+
if (typeof value === "string" && schema.minLength !== undefined && value.length < schema.minLength) {
|
|
182
|
+
fail("Must not be empty.", "minLength");
|
|
183
|
+
}
|
|
184
|
+
if (typeof value === "number" && schema.minimum !== undefined && value < schema.minimum) {
|
|
185
|
+
fail(`Must be at least ${schema.minimum}.`, "minimum");
|
|
186
|
+
}
|
|
187
|
+
if (Array.isArray(value)) {
|
|
188
|
+
if (schema.minItems !== undefined && value.length < schema.minItems) {
|
|
189
|
+
fail(`Add at least ${schema.minItems} item.`, "minItems");
|
|
190
|
+
}
|
|
191
|
+
if (schema.items) value.forEach((item, index) => validateAgainstSchema(item, schema.items!, [...path, index], issues));
|
|
192
|
+
}
|
|
193
|
+
if (isRecord(value)) {
|
|
194
|
+
for (const key of schema.required ?? []) {
|
|
195
|
+
if (!Object.hasOwn(value, key)) fail(`Missing required field "${key}".`, "required", [...path, key]);
|
|
196
|
+
}
|
|
197
|
+
for (const [key, child] of Object.entries(value)) {
|
|
198
|
+
const childSchema = schema.properties?.[key];
|
|
199
|
+
if (childSchema) validateAgainstSchema(child, childSchema, [...path, key], issues);
|
|
200
|
+
else if (schema.additionalProperties === false) fail(`Unknown field "${key}".`, "additionalProperties", [...path, key]);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
for (const branch of schema.allOf ?? []) validateAgainstSchema(value, branch, path, issues);
|
|
204
|
+
if (schema.if && schema.then && validateAgainstSchema(value, schema.if, path, []).length === 0) {
|
|
205
|
+
validateAgainstSchema(value, schema.then, path, issues);
|
|
206
|
+
}
|
|
207
|
+
for (const keyword of ["anyOf", "oneOf"] as const) {
|
|
208
|
+
const branches = schema[keyword];
|
|
209
|
+
if (!branches?.length) continue;
|
|
210
|
+
const runs = branches.map((branch) => validateAgainstSchema(value, branch, path, []));
|
|
211
|
+
const passed = runs.filter((run) => run.length === 0).length;
|
|
212
|
+
if (keyword === "anyOf" ? passed === 0 : passed !== 1) {
|
|
213
|
+
if (keyword === "oneOf" && passed > 1) {
|
|
214
|
+
fail("Matches more than one allowed shape.", keyword);
|
|
215
|
+
} else {
|
|
216
|
+
const best = runs.filter((run) => run.length > 0).sort((left, right) => left.length - right.length)[0];
|
|
217
|
+
if (best) issues.push(...best);
|
|
218
|
+
else fail("Does not match any allowed shape.", keyword);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return issues;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function formatPath(root: string, path: Array<string | number>): string {
|
|
226
|
+
let text = root;
|
|
227
|
+
for (const part of path) text += typeof part === "number" ? `[${part}]` : `.${part}`;
|
|
228
|
+
return text;
|
|
229
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "monaco-editor/languages/features/json/json.worker";
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
// Renderers bundled by scripts/build-office.ts. Each public function is imported by
|
|
3
|
+
// its own entry file, so a preview downloads only the library it needs.
|
|
4
|
+
import type { CellObject, WorkSheet } from "xlsx";
|
|
5
|
+
|
|
6
|
+
// A single sheet can claim the full Excel grid; keep the DOM bounded.
|
|
7
|
+
const MAX_SHEET_ROWS = 2000;
|
|
8
|
+
const MAX_SHEET_COLUMNS = 100;
|
|
9
|
+
|
|
10
|
+
type Sanitizer = {
|
|
11
|
+
sanitize: (dirty: string | Node, config?: Record<string, unknown>) => string | Node;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export class OfficePreviewError extends Error {
|
|
15
|
+
override name = "OfficePreviewError";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function requireSanitizer(): Sanitizer {
|
|
19
|
+
const purify = (globalThis as { DOMPurify?: Sanitizer }).DOMPurify;
|
|
20
|
+
if (!purify || typeof purify.sanitize !== "function") {
|
|
21
|
+
throw new OfficePreviewError("This document needs the page sanitizer to render safely.");
|
|
22
|
+
}
|
|
23
|
+
return purify;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const SAFE_CSS_URL = /^(?:data:image\/|data:font\/|blob:|#)/i;
|
|
27
|
+
|
|
28
|
+
// docx-preview emits generated CSS. Drop imports and any URL that is not embedded
|
|
29
|
+
// data or a blob, while keeping the layout and colour declarations untouched.
|
|
30
|
+
export function sanitizeCss(css: string): string {
|
|
31
|
+
return css
|
|
32
|
+
.replace(/@import[^;]*(?:;|$)/gi, "")
|
|
33
|
+
.replace(/url\(\s*(?:(["'])([\s\S]*?)\1|([^)]*))\s*\)/gi, (_match, _quote: string, quoted: string, bare: string) => {
|
|
34
|
+
const value = String(quoted ?? bare ?? "").trim();
|
|
35
|
+
return SAFE_CSS_URL.test(value) && !value.includes("\\") ? `url("${value.replaceAll('"', '\\"')}")` : "none";
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// docx-preview renders its own nodes. Style nodes are generated CSS and must stay,
|
|
40
|
+
// while every content node is passed through the page's DOMPurify.
|
|
41
|
+
export async function renderDocx(blob: Blob, container: HTMLElement): Promise<void> {
|
|
42
|
+
const purify = requireSanitizer();
|
|
43
|
+
const { parseAsync, renderDocument } = await import("docx-preview");
|
|
44
|
+
const options = { useBase64URL: true, ignoreLastRenderedPageBreak: true, renderAltChunks: false };
|
|
45
|
+
const parsed = await parseAsync(blob, options);
|
|
46
|
+
const nodes = await renderDocument(parsed, options);
|
|
47
|
+
container.replaceChildren();
|
|
48
|
+
for (const node of nodes) {
|
|
49
|
+
if (node.nodeName === "STYLE") {
|
|
50
|
+
(node as HTMLStyleElement).textContent = sanitizeCss(node.textContent || "");
|
|
51
|
+
container.append(node);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
55
|
+
container.append(node);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const template = window.document.createElement("template");
|
|
59
|
+
template.innerHTML = String(purify.sanitize((node as Element).outerHTML));
|
|
60
|
+
container.append(template.content);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function element<K extends keyof HTMLElementTagNameMap>(tag: K, className: string): HTMLElementTagNameMap[K] {
|
|
65
|
+
const node = document.createElement(tag);
|
|
66
|
+
node.className = className;
|
|
67
|
+
return node;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function renderSheet(XLSX: typeof import("xlsx"), sheet: WorkSheet): HTMLElement {
|
|
71
|
+
const wrapper = element("div", "office-xlsx-sheet");
|
|
72
|
+
const ref = sheet["!ref"];
|
|
73
|
+
const range = ref ? XLSX.utils.decode_range(ref) : null;
|
|
74
|
+
if (!range) {
|
|
75
|
+
wrapper.textContent = "This sheet is empty.";
|
|
76
|
+
return wrapper;
|
|
77
|
+
}
|
|
78
|
+
const startRow = range.s.r, startColumn = range.s.c;
|
|
79
|
+
const endRow = Math.min(range.e.r, startRow + MAX_SHEET_ROWS - 1);
|
|
80
|
+
const endColumn = Math.min(range.e.c, startColumn + MAX_SHEET_COLUMNS - 1);
|
|
81
|
+
const spans = new Map<string, { rowSpan: number; colSpan: number }>();
|
|
82
|
+
const covered = new Set<string>();
|
|
83
|
+
for (const merge of sheet["!merges"] || []) {
|
|
84
|
+
const rowStart = Math.max(merge.s.r, startRow), rowEnd = Math.min(merge.e.r, endRow);
|
|
85
|
+
const columnStart = Math.max(merge.s.c, startColumn), columnEnd = Math.min(merge.e.c, endColumn);
|
|
86
|
+
if (rowEnd < rowStart || columnEnd < columnStart) continue;
|
|
87
|
+
spans.set(`${rowStart}:${columnStart}`, { rowSpan: rowEnd - rowStart + 1, colSpan: columnEnd - columnStart + 1 });
|
|
88
|
+
for (let row = rowStart; row <= rowEnd; row++) {
|
|
89
|
+
for (let column = columnStart; column <= columnEnd; column++) {
|
|
90
|
+
if (row !== rowStart || column !== columnStart) covered.add(`${row}:${column}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const table = element("table", "office-xlsx-table");
|
|
95
|
+
const body = document.createElement("tbody");
|
|
96
|
+
for (let row = startRow; row <= endRow; row++) {
|
|
97
|
+
const tr = document.createElement("tr");
|
|
98
|
+
for (let column = startColumn; column <= endColumn; column++) {
|
|
99
|
+
const key = `${row}:${column}`;
|
|
100
|
+
if (covered.has(key)) continue;
|
|
101
|
+
const cell = element("td", "");
|
|
102
|
+
const span = spans.get(key);
|
|
103
|
+
if (span) {
|
|
104
|
+
if (span.rowSpan > 1) cell.rowSpan = span.rowSpan;
|
|
105
|
+
if (span.colSpan > 1) cell.colSpan = span.colSpan;
|
|
106
|
+
}
|
|
107
|
+
const source = sheet[XLSX.utils.encode_cell({ r: row, c: column })] as CellObject | undefined;
|
|
108
|
+
// textContent keeps cell text inert; cell.h (rich HTML) is never used.
|
|
109
|
+
const text = source ? XLSX.utils.format_cell(source) : "";
|
|
110
|
+
if (text) cell.textContent = text;
|
|
111
|
+
tr.append(cell);
|
|
112
|
+
}
|
|
113
|
+
body.append(tr);
|
|
114
|
+
}
|
|
115
|
+
table.append(body);
|
|
116
|
+
wrapper.append(table);
|
|
117
|
+
if (range.e.r > endRow || range.e.c > endColumn) {
|
|
118
|
+
const note = element("p", "office-xlsx-note");
|
|
119
|
+
note.textContent = `Showing the first ${endRow - startRow + 1} rows and ${endColumn - startColumn + 1} columns.`;
|
|
120
|
+
wrapper.append(note);
|
|
121
|
+
}
|
|
122
|
+
return wrapper;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function renderXlsx(blob: Blob, container: HTMLElement): Promise<void> {
|
|
126
|
+
const XLSX = await import("xlsx");
|
|
127
|
+
const book = XLSX.read(new Uint8Array(await blob.arrayBuffer()), {
|
|
128
|
+
type: "array", cellFormula: false, cellHTML: false, cellStyles: false, cellNF: false, bookVBA: false, bookFiles: false,
|
|
129
|
+
});
|
|
130
|
+
const names = book.SheetNames.filter((name) => Boolean(book.Sheets[name]));
|
|
131
|
+
if (!names.length) throw new Error("The workbook has no readable sheets.");
|
|
132
|
+
const root = element("div", "office-xlsx");
|
|
133
|
+
const tabs = element("div", "office-xlsx-tabs");
|
|
134
|
+
tabs.setAttribute("role", "tablist");
|
|
135
|
+
const panel = element("div", "office-xlsx-panel");
|
|
136
|
+
const buttons: HTMLButtonElement[] = [];
|
|
137
|
+
const show = (index: number) => {
|
|
138
|
+
const sheet = book.Sheets[names[index] as string];
|
|
139
|
+
if (!sheet) return;
|
|
140
|
+
panel.replaceChildren(renderSheet(XLSX, sheet));
|
|
141
|
+
buttons.forEach((button, position) => {
|
|
142
|
+
const active = position === index;
|
|
143
|
+
button.setAttribute("aria-selected", String(active));
|
|
144
|
+
button.tabIndex = active ? 0 : -1;
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
names.forEach((name, index) => {
|
|
148
|
+
const button = element("button", "office-xlsx-tab");
|
|
149
|
+
button.type = "button";
|
|
150
|
+
button.textContent = name;
|
|
151
|
+
button.setAttribute("role", "tab");
|
|
152
|
+
button.addEventListener("click", () => show(index));
|
|
153
|
+
buttons.push(button);
|
|
154
|
+
tabs.append(button);
|
|
155
|
+
});
|
|
156
|
+
tabs.hidden = names.length < 2;
|
|
157
|
+
root.append(tabs, panel);
|
|
158
|
+
container.replaceChildren(root);
|
|
159
|
+
show(0);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const FORBIDDEN_TAGS = ["script", "iframe", "object", "embed", "form", "input", "button", "link", "meta", "base", "frame", "frameset", "applet"];
|
|
163
|
+
const SAFE_URI = /^(?:(?:https?|mailto):|#|data:|blob:)/i;
|
|
164
|
+
const SAFE_RESOURCE = /^(?:data:|blob:)/i;
|
|
165
|
+
|
|
166
|
+
// pptx-preview builds live DOM and may chart into canvases, so sanitize in place:
|
|
167
|
+
// string round-trips would erase canvas pixels and drop library event listeners.
|
|
168
|
+
export function sanitizeRendered(root: HTMLElement): void {
|
|
169
|
+
const purify = requireSanitizer();
|
|
170
|
+
// Moving a canvas keeps its bitmap, while DOMPurify drops its width/height
|
|
171
|
+
// attributes (resizing and clearing it). Set canvases aside during the pass.
|
|
172
|
+
const canvases = Array.from(root.querySelectorAll("canvas")).map((canvas) => {
|
|
173
|
+
const parent = canvas.parentNode;
|
|
174
|
+
const next = canvas.nextSibling;
|
|
175
|
+
canvas.remove();
|
|
176
|
+
return { canvas, parent, next };
|
|
177
|
+
});
|
|
178
|
+
purify.sanitize(root, {
|
|
179
|
+
IN_PLACE: true,
|
|
180
|
+
FORBID_TAGS: FORBIDDEN_TAGS,
|
|
181
|
+
FORBID_ATTR: ["srcset", "background", "srcdoc", "action", "formaction"],
|
|
182
|
+
ALLOWED_URI_REGEXP: SAFE_URI,
|
|
183
|
+
});
|
|
184
|
+
for (const { canvas, parent, next } of canvases) {
|
|
185
|
+
if (!parent || !root.contains(parent)) continue;
|
|
186
|
+
parent.insertBefore(canvas, next && next.parentNode === parent ? next : null);
|
|
187
|
+
}
|
|
188
|
+
for (const node of [root as Element, ...Array.from(root.querySelectorAll("*"))]) {
|
|
189
|
+
const tag = node.tagName.toLowerCase();
|
|
190
|
+
for (const attribute of Array.from(node.attributes)) {
|
|
191
|
+
const name = attribute.name.toLowerCase();
|
|
192
|
+
const value = attribute.value.trim();
|
|
193
|
+
if (name.startsWith("on")) node.removeAttribute(attribute.name);
|
|
194
|
+
else if (name === "style") node.setAttribute("style", sanitizeCss(attribute.value));
|
|
195
|
+
else if (name === "href" || name === "xlink:href") {
|
|
196
|
+
const allowed = tag === "a" ? /^(?:https?:|mailto:|#)/i : /^(?:#|data:|blob:)/i;
|
|
197
|
+
if (!allowed.test(value)) node.removeAttribute(attribute.name);
|
|
198
|
+
} else if ((name === "src" || name === "poster") && !SAFE_RESOURCE.test(value)) {
|
|
199
|
+
node.removeAttribute(attribute.name);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
for (const style of Array.from(root.querySelectorAll("style"))) style.textContent = sanitizeCss(style.textContent || "");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export async function renderPptx(blob: Blob, container: HTMLElement, options: { width?: number } = {}): Promise<void> {
|
|
207
|
+
requireSanitizer();
|
|
208
|
+
const { init } = await import("pptx-preview");
|
|
209
|
+
const width = Math.max(320, Math.round(options.width || container.clientWidth || 960));
|
|
210
|
+
// No fixed height: list mode stacks every slide and lets the preview pane scroll.
|
|
211
|
+
const viewer = init(container, { width, mode: "list" });
|
|
212
|
+
container.replaceChildren(viewer.wrapper);
|
|
213
|
+
try {
|
|
214
|
+
await viewer.preview(await blob.arrayBuffer());
|
|
215
|
+
sanitizeRendered(viewer.wrapper);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
viewer.destroy();
|
|
218
|
+
container.replaceChildren();
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
}
|