forked from superdoc-dev/superdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
188 lines (161 loc) · 5.48 KB
/
Copy pathserver.mjs
File metadata and controls
188 lines (161 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { createReadStream } from 'node:fs';
import { mkdir, readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { basename, dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { SuperDocClient } from '@superdoc-dev/sdk';
const EXAMPLE_ROOT = dirname(fileURLToPath(import.meta.url));
// Reuse FastAPI sample assets to keep this example bare-bones.
const DOC_PATH = join(EXAMPLE_ROOT, '../fastapi/assets/doc-template.docx');
const MARKDOWN_PATH = join(EXAMPLE_ROOT, '../fastapi/assets/fake-nda.md');
const DOWNLOAD_PATH = join(EXAMPLE_ROOT, '.superdoc-state', 'download.docx');
const COLLAB_PROVIDER = 'y-websocket';
const COLLAB_URL = 'ws://127.0.0.1:8081/v1/collaboration';
const COLLAB_DOCUMENT_ID = 'superdoc-dev-room';
const COLLAB_TOKEN_ENV = 'YHUB_AUTH_TOKEN';
const COLLAB_TOKEN_DEFAULT = 'YOUR_PRIVATE_TOKEN';
const COLLAB_SYNC_TIMEOUT_MS = 60_000;
const OPEN_TIMEOUT_MS = 90_000;
const WATCHDOG_TIMEOUT_MS = 120_000;
const PORT = Number(process.env.PORT ?? 8001);
/** @type {SuperDocClient | null} */
let client = null;
/** @type {import('@superdoc-dev/sdk').SuperDocDocument | null} */
let doc = null;
let openResult = null;
let initialized = false;
let shuttingDown = false;
function sendJson(res, statusCode, payload) {
const body = JSON.stringify(payload, null, 2);
res.writeHead(statusCode, { 'content-type': 'application/json; charset=utf-8' });
res.end(body);
}
function escapeHtml(value) {
return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
}
async function ensureInitialized() {
if (initialized) return;
process.env[COLLAB_TOKEN_ENV] ??= COLLAB_TOKEN_DEFAULT;
client = new SuperDocClient({ watchdogTimeoutMs: WATCHDOG_TIMEOUT_MS });
await client.connect();
doc = await client.open(
{
doc: DOC_PATH,
collaboration: {
providerType: COLLAB_PROVIDER,
url: COLLAB_URL,
documentId: COLLAB_DOCUMENT_ID,
tokenEnv: COLLAB_TOKEN_ENV,
syncTimeoutMs: COLLAB_SYNC_TIMEOUT_MS,
},
},
{ timeoutMs: OPEN_TIMEOUT_MS },
);
openResult = doc.openResult;
const markdownContent = await readFile(MARKDOWN_PATH, 'utf8');
await doc.insert({ value: markdownContent, type: 'markdown' });
initialized = true;
}
async function shutdown() {
if (shuttingDown) return;
shuttingDown = true;
if (!doc) return;
try {
await doc.close({});
} catch (error) {
console.error('[node-sdk] doc.close failed:', error);
}
try {
await client.dispose();
} catch (error) {
console.error('[node-sdk] dispose failed:', error);
}
}
function listenSignals(server) {
const handleSignal = (signal) => {
console.log(`[node-sdk] received ${signal}, shutting down...`);
server.close(async () => {
await shutdown();
process.exit(0);
});
};
process.once('SIGINT', () => handleSignal('SIGINT'));
process.once('SIGTERM', () => handleSignal('SIGTERM'));
}
async function handleRequest(req, res) {
if (req.method !== 'GET') {
sendJson(res, 405, { ok: false, error: 'Only GET is supported in this demo.' });
return;
}
await ensureInitialized();
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? `127.0.0.1:${PORT}`}`);
if (url.pathname === '/') {
sendJson(res, 200, {
ok: true,
openResult,
collab: {
providerType: COLLAB_PROVIDER,
url: COLLAB_URL,
documentId: COLLAB_DOCUMENT_ID,
tokenEnv: COLLAB_TOKEN_ENV,
},
});
return;
}
if (url.pathname === '/status') {
sendJson(res, 200, { ok: true, sessionId: doc.sessionId });
return;
}
if (url.pathname === '/insert') {
const text = url.searchParams.get('text');
if (!text) {
sendJson(res, 400, { ok: false, error: 'Missing query param: text' });
return;
}
sendJson(res, 200, await doc.insert({ value: text }));
return;
}
if (url.pathname === '/markdown') {
const markdown = await doc.getMarkdown({});
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Document Markdown</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 48rem; margin: 2rem auto; padding: 0 1rem; }
pre { background: #f5f5f5; padding: 1rem; border-radius: 6px; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word; }
</style>
</head>
<body>
<h1>Document as Markdown</h1>
<pre>${escapeHtml(String(markdown))}</pre>
</body>
</html>`;
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(html);
return;
}
if (url.pathname === '/download') {
await mkdir(dirname(DOWNLOAD_PATH), { recursive: true });
await doc.save({ out: DOWNLOAD_PATH, force: true });
res.writeHead(200, {
'content-type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'content-disposition': `attachment; filename="${basename(DOWNLOAD_PATH)}"`,
});
createReadStream(DOWNLOAD_PATH).pipe(res);
return;
}
sendJson(res, 404, { ok: false, error: `Not found: ${url.pathname}` });
}
const server = createServer((req, res) => {
handleRequest(req, res).catch((error) => {
console.error('[node-sdk] request failed:', error);
sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
});
});
listenSignals(server);
server.listen(PORT, () => {
console.log(`[node-sdk] server running at http://127.0.0.1:${PORT}`);
console.log(`[node-sdk] collaboration room: ${COLLAB_URL}/${COLLAB_DOCUMENT_ID}`);
});