@eliceio/cdk-cli 1.6.0 → 1.7.0
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/es/commands/create/scaffold.d.ts +1 -1
- package/es/commands/create/scaffold.js +1 -1
- package/es/commands/dev/index.d.ts +1 -1
- package/es/commands/dev/index.js +1 -1
- package/es/core/quiz-check.js +5 -5
- package/es/dev/host-page.js +19 -3
- package/es/dev/kv-public-mock.d.ts +101 -0
- package/es/dev/kv-public-mock.js +489 -0
- package/es/dev/mock-api.d.ts +28 -6
- package/es/dev/mock-api.js +57 -59
- package/es/dev/mock-http.d.ts +28 -0
- package/es/dev/mock-http.js +53 -0
- package/es/dev/server.js +8 -3
- package/package.json +8 -7
- package/skills/_shared/references/02-design-the-material.md +1 -1
- package/skills/_shared/references/06-using-the-quiz-template.md +1 -0
- package/templates/_shared/lib/cdk-mock.d.ts +37 -0
- package/templates/_shared/lib/cdk-mock.js +89 -1
- package/templates/_shared/lib/elice-content.d.ts +5 -0
- package/templates/_shared/lib/elice-content.js +7 -0
- package/templates/board/README.md +118 -0
- package/templates/board/commentary.txt +6 -0
- package/templates/board/core/board.d.ts +176 -0
- package/templates/board/core/board.js +732 -0
- package/templates/board/core/dom.d.ts +13 -0
- package/templates/board/core/dom.js +83 -0
- package/templates/board/core/model.d.ts +58 -0
- package/templates/board/core/model.js +217 -0
- package/templates/board/core/settings.d.ts +44 -0
- package/templates/board/core/settings.js +131 -0
- package/templates/board/edit.html +23 -0
- package/templates/board/gitignore +4 -0
- package/templates/board/index.html +22 -0
- package/templates/board/instructor.html +23 -0
- package/templates/board/metadata.json +9 -0
- package/templates/board/package.json +13 -0
- package/templates/board/screens/board.js +318 -0
- package/templates/board/screens/edit.js +631 -0
- package/templates/board/screens/instructor.js +16 -0
- package/templates/board/screens/learn.js +14 -0
- package/templates/board/template.json +14 -0
- package/templates/board/ui/background.css +8 -0
- package/templates/board/ui/board-bg.webp +0 -0
- package/templates/board/ui/board.css +1124 -0
- package/templates/board/ui/card.js +141 -0
- package/templates/board/ui/composer.js +329 -0
- package/templates/board/ui/dropdown.js +185 -0
- package/templates/board/ui/icons.js +36 -0
- package/templates/board/ui/learn.css +141 -0
- package/templates/board/ui/menu.js +104 -0
- package/templates/board/ui/texts.d.ts +3 -0
- package/templates/board/ui/texts.js +162 -0
- package/templates/quiz/README.md +16 -6
- package/templates/quiz/core/draft.d.ts +32 -0
- package/templates/quiz/core/draft.js +224 -0
- package/templates/quiz/core/model.d.ts +5 -8
- package/templates/quiz/core/model.js +11 -13
- package/templates/quiz/screens/edit.js +8 -18
- package/templates/quiz/screens/learn.js +62 -13
- package/templates/quiz/styles.css +3 -6
- package/templates/quiz/template.json +1 -1
- package/templates/quiz/ui/templates/page.js +1 -14
- package/templates/quiz/ui/texts.js +1 -5
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
2
|
+
import { fail, readClaims, body, send } from './mock-http.js';
|
|
3
|
+
|
|
4
|
+
const createPublicKvStore = () => ({
|
|
5
|
+
meta: new Map(),
|
|
6
|
+
tickets: new Map(),
|
|
7
|
+
connections: new Set(),
|
|
8
|
+
pingMs: 15_000,
|
|
9
|
+
ticketMs: 60_000,
|
|
10
|
+
rooms: new Map(),
|
|
11
|
+
messageTimes: new Map(),
|
|
12
|
+
presenceMs: 45_000,
|
|
13
|
+
publicWaiters: new Set()
|
|
14
|
+
});
|
|
15
|
+
/** 방 이름 (실제 서버 MATERIAL_ROOM_NAME_PATTERN) */
|
|
16
|
+
const ROOM_NAME = /^[a-z0-9_-]{1,32}$/;
|
|
17
|
+
/** 방 최대 인원 */
|
|
18
|
+
const ROOM_MAX_MEMBERS = 8;
|
|
19
|
+
/** 방 메시지 최대 크기 (압축 JSON `{"type":…,"data":…}` 바이트) */
|
|
20
|
+
const ROOM_MESSAGE_MAX_BYTES = 1024;
|
|
21
|
+
const ROOM_MESSAGE_TYPE_MAX = 32;
|
|
22
|
+
/** 1초에 보낼 수 있는 방 메시지 */
|
|
23
|
+
const ROOM_MESSAGE_RATE = 20;
|
|
24
|
+
const ROOM_LOG_MAX = 500;
|
|
25
|
+
const CURSOR = /^[0-9]{1,20}-[0-9]{1,20}$/;
|
|
26
|
+
/** 공개 줄 크기 제한 (JSON 바이트) */
|
|
27
|
+
const PUBLIC_MAX_BYTES = 16 * 1024;
|
|
28
|
+
/** `?account_ids=` 최대 인원 */
|
|
29
|
+
const MAX_ACCOUNT_IDS = 100;
|
|
30
|
+
const PUBLIC_KEY = 'public';
|
|
31
|
+
/** key가 public 줄을 건드리는가 (`public` 또는 `public.…`) */
|
|
32
|
+
const touchesPublic = key => key === PUBLIC_KEY || key.startsWith(`${PUBLIC_KEY}.`);
|
|
33
|
+
/** 열린 SSE 연결을 모두 닫는다 ('처음 상태로' · dev 종료). SDK는 새 입장권으로 다시 연결한다 */
|
|
34
|
+
function closePublicKv(store) {
|
|
35
|
+
for (const c of store.connections) {
|
|
36
|
+
clearInterval(c.timer);
|
|
37
|
+
c.res.end();
|
|
38
|
+
}
|
|
39
|
+
store.connections.clear();
|
|
40
|
+
for (const room of store.rooms.values()) for (const wake of room.waiters) wake();
|
|
41
|
+
for (const wake of [...store.publicWaiters]) wake(true);
|
|
42
|
+
store.rooms.clear();
|
|
43
|
+
store.messageTimes.clear();
|
|
44
|
+
}
|
|
45
|
+
/** public 줄이 바뀌었다: 저장 뒤 연결된 모두에게 "바뀜"만 보낸다 (쓴 사람 포함, SDK가 자기 것은 거름) */
|
|
46
|
+
function notifyPublicChange(store, accountId, role) {
|
|
47
|
+
store.meta.set(accountId, {
|
|
48
|
+
role,
|
|
49
|
+
updated_at: new Date().toISOString()
|
|
50
|
+
});
|
|
51
|
+
const message = `event: changed\ndata: ${JSON.stringify({
|
|
52
|
+
account_id: accountId
|
|
53
|
+
})}\n\n`;
|
|
54
|
+
for (const c of store.connections) c.res.write(message);
|
|
55
|
+
for (const wake of [...store.publicWaiters]) wake();
|
|
56
|
+
}
|
|
57
|
+
/** `/materials/{id}/kv/public` · `/kv/subscription` · `/kv/events`이면 처리하고 true */
|
|
58
|
+
async function handlePublicKvApi(req, res, path, opts) {
|
|
59
|
+
const roomMatch = path.match(/^\/materials\/([0-9a-f-]{36})\/rooms\/([^/]+)\/(messages|poll|leave)$/);
|
|
60
|
+
if (roomMatch) {
|
|
61
|
+
await handleRoomApi(req, res, roomMatch, opts);
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
const m = path.match(/^\/materials\/([0-9a-f-]{36})\/kv\/(public|subscription|events)$/);
|
|
65
|
+
if (!m) return false;
|
|
66
|
+
const [, materialId, route] = m;
|
|
67
|
+
const method = req.method ?? 'GET';
|
|
68
|
+
const url = new URL(req.url ?? '', 'http://x');
|
|
69
|
+
const {
|
|
70
|
+
store
|
|
71
|
+
} = opts;
|
|
72
|
+
const notAllowed = () => {
|
|
73
|
+
fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${path}`);
|
|
74
|
+
return true;
|
|
75
|
+
};
|
|
76
|
+
// SSE: EventSource는 Authorization을 못 보내므로 토큰 대신 입장권
|
|
77
|
+
if (route === 'events') {
|
|
78
|
+
if (method !== 'GET') return notAllowed();
|
|
79
|
+
// 실제 서버처럼 한 번만 쓴다
|
|
80
|
+
const key = url.searchParams.get('ticket') ?? '';
|
|
81
|
+
const ticket = store.tickets.get(key);
|
|
82
|
+
store.tickets.delete(key);
|
|
83
|
+
if (!ticket || ticket.expires <= Date.now()) {
|
|
84
|
+
fail(res, 401, 'AUTHENTICATION_INVALID', 'missing or expired ticket (dev)', [{
|
|
85
|
+
ctx: {
|
|
86
|
+
reason: 'invalid_ticket'
|
|
87
|
+
}
|
|
88
|
+
}]);
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
if (ticket.material_id !== materialId) {
|
|
92
|
+
fail(res, 403, 'AUTH_PERMISSION_DENIED', 'ticket of another material (dev)');
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
if (ticket.room && !joinRoom(store, materialId, ticket.room, ticket.account_id)) {
|
|
96
|
+
roomFull(res);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
openStream(req, res, store, {
|
|
100
|
+
material_id: materialId,
|
|
101
|
+
account_id: ticket.account_id,
|
|
102
|
+
room: ticket.room
|
|
103
|
+
});
|
|
104
|
+
if (ticket.room) publishMembers(store, materialId, ticket.room);
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
const claims = readClaims(req);
|
|
108
|
+
if (!claims) {
|
|
109
|
+
fail(res, 401, 'AUTHENTICATION_INVALID', 'missing or expired token (dev)');
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
if (materialId !== claims.material_id) {
|
|
113
|
+
fail(res, 403, 'AUTH_PERMISSION_DENIED', 'material mismatch');
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
if (route === 'subscription') {
|
|
117
|
+
if (method !== 'POST') return notAllowed();
|
|
118
|
+
const {
|
|
119
|
+
json
|
|
120
|
+
} = await body(req);
|
|
121
|
+
const room = json?.room ?? null;
|
|
122
|
+
if (room !== null && (typeof room !== 'string' || !ROOM_NAME.test(room))) {
|
|
123
|
+
fail(res, 422, 'VALIDATION_ERROR', 'room: ^[a-z0-9_-]{1,32}$', [{
|
|
124
|
+
type: 'string_pattern_mismatch',
|
|
125
|
+
loc: ['body', 'room']
|
|
126
|
+
}]);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
const ticket = randomBytes(16).toString('hex');
|
|
130
|
+
// 토큰보다 오래 살지 않는다
|
|
131
|
+
const expires = Math.min(Date.now() + store.ticketMs, claims.exp * 1000);
|
|
132
|
+
for (const [k, t] of store.tickets) if (t.expires <= Date.now()) store.tickets.delete(k);
|
|
133
|
+
store.tickets.set(ticket, {
|
|
134
|
+
material_id: materialId,
|
|
135
|
+
account_id: claims.account_id,
|
|
136
|
+
room: room,
|
|
137
|
+
expires
|
|
138
|
+
});
|
|
139
|
+
// 콘텐츠 iframe은 다른 출처라 상대 주소면 콘텐츠 출처로 풀린다: 흉내 API 출처를 붙인 절대 주소로 준다
|
|
140
|
+
const host = req.headers.host ?? 'localhost';
|
|
141
|
+
send(res, 200, {
|
|
142
|
+
url: `http://${host}/api/materials/${materialId}/kv/events`,
|
|
143
|
+
ticket,
|
|
144
|
+
expires_at: new Date(expires).toISOString()
|
|
145
|
+
});
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
// GET /kv/public
|
|
149
|
+
if (method !== 'GET') return notAllowed();
|
|
150
|
+
const idsRaw = url.searchParams.get('account_ids');
|
|
151
|
+
let ids = null;
|
|
152
|
+
if (idsRaw !== null) {
|
|
153
|
+
ids = idsRaw.split(',').map(Number);
|
|
154
|
+
if (ids.length > MAX_ACCOUNT_IDS || ids.some(id => !Number.isInteger(id) || id < 0)) {
|
|
155
|
+
fail(res, 422, 'VALIDATION_ERROR', `account_ids: up to ${MAX_ACCOUNT_IDS} integers`, [{
|
|
156
|
+
type: 'value_error',
|
|
157
|
+
loc: ['query', 'account_ids']
|
|
158
|
+
}]);
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// 실제 백엔드(elice-material feature/74 · 76 · 77)와 같은 모양: 이름 · 역할은 싣지 않는다.
|
|
163
|
+
// 쓴 사람 역할은 SDK가 자기 줄에 써 둔 value.role을 읽는다
|
|
164
|
+
const read = () => {
|
|
165
|
+
const rows = [...opts.kv.entries()].filter(([id, doc]) => Object.hasOwn(doc, PUBLIC_KEY) && (!ids || ids.includes(id))).sort(([a], [b]) => a - b).map(([id, doc]) => ({
|
|
166
|
+
account_id: id,
|
|
167
|
+
value: doc[PUBLIC_KEY],
|
|
168
|
+
updated_at: store.meta.get(id)?.updated_at ?? null
|
|
169
|
+
}));
|
|
170
|
+
const data = {
|
|
171
|
+
rows
|
|
172
|
+
};
|
|
173
|
+
const etag = `"${createHash('sha1').update(JSON.stringify(data)).digest('hex').slice(0, 16)}"`;
|
|
174
|
+
return {
|
|
175
|
+
data,
|
|
176
|
+
etag
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
const ifNoneMatch = req.headers['if-none-match'];
|
|
180
|
+
let current = read();
|
|
181
|
+
// 롱폴(#83): ETag가 같으면 public 줄이 바뀔 때까지 최대 wait초 기다린다
|
|
182
|
+
const waitRaw = url.searchParams.get('wait');
|
|
183
|
+
if (waitRaw !== null && ifNoneMatch === current.etag) {
|
|
184
|
+
const parsed = Number(waitRaw);
|
|
185
|
+
const waitSeconds = Math.min(Math.max(Number.isFinite(parsed) ? Math.trunc(parsed) : 1, 1), 20);
|
|
186
|
+
const before = current.etag;
|
|
187
|
+
await new Promise(resolve => {
|
|
188
|
+
const finish = () => {
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
store.publicWaiters.delete(wake);
|
|
191
|
+
res.off('close', finish);
|
|
192
|
+
resolve();
|
|
193
|
+
};
|
|
194
|
+
// 다른 사람 줄만 바뀌어 이 요청의 답이 그대로면(`account_ids`) 계속 기다린다
|
|
195
|
+
const wake = force => {
|
|
196
|
+
if (force || read().etag !== before) finish();
|
|
197
|
+
};
|
|
198
|
+
const timer = setTimeout(finish, waitSeconds * 1000);
|
|
199
|
+
timer.unref();
|
|
200
|
+
store.publicWaiters.add(wake);
|
|
201
|
+
res.on('close', finish);
|
|
202
|
+
});
|
|
203
|
+
if (res.destroyed) return true;
|
|
204
|
+
current = read();
|
|
205
|
+
}
|
|
206
|
+
if (ifNoneMatch === current.etag) {
|
|
207
|
+
res.writeHead(304, {
|
|
208
|
+
ETag: current.etag
|
|
209
|
+
});
|
|
210
|
+
res.end();
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
res.setHeader('ETag', current.etag);
|
|
214
|
+
send(res, 200, current.data);
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* SSE 연결. 압축 · 버퍼 없이 바로 쓰고(호스트 서버는 압축하지 않음), 15초마다 `: ping`.
|
|
219
|
+
* 지난 알림은 다시 보내지 않는다 (SDK가 연결이 열리면 GET /kv/public으로 전부 다시 읽음)
|
|
220
|
+
*/
|
|
221
|
+
function openStream(req, res, store, who) {
|
|
222
|
+
res.writeHead(200, {
|
|
223
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
224
|
+
'Cache-Control': 'no-cache',
|
|
225
|
+
Connection: 'keep-alive',
|
|
226
|
+
'X-Accel-Buffering': 'no'
|
|
227
|
+
});
|
|
228
|
+
res.flushHeaders();
|
|
229
|
+
res.write(': connected\n\n');
|
|
230
|
+
// 연결 성공 신호 (#83). SDK는 open이 아니라 이걸로 live가 되고, 5초 안에 안 오면 롱폴로 바꾼다
|
|
231
|
+
res.write('event: ready\ndata: {}\n\n');
|
|
232
|
+
const timer = setInterval(() => res.write(': ping\n\n'), store.pingMs);
|
|
233
|
+
timer.unref();
|
|
234
|
+
const conn = {
|
|
235
|
+
res,
|
|
236
|
+
timer,
|
|
237
|
+
...who
|
|
238
|
+
};
|
|
239
|
+
store.connections.add(conn);
|
|
240
|
+
req.socket.setKeepAlive(true);
|
|
241
|
+
req.socket.setNoDelay(true);
|
|
242
|
+
res.on('close', () => {
|
|
243
|
+
clearInterval(timer);
|
|
244
|
+
if (!store.connections.delete(conn) || !conn.room) return;
|
|
245
|
+
// 그 사람의 이 방 연결이 모두 닫혔으면 방에서 뺀다
|
|
246
|
+
const stillOpen = [...store.connections].some(c => c.material_id === conn.material_id && c.room === conn.room && c.account_id === conn.account_id);
|
|
247
|
+
const room = store.rooms.get(roomKey(conn.material_id, conn.room));
|
|
248
|
+
if (!stillOpen && room?.members.delete(conn.account_id)) {
|
|
249
|
+
publishMembers(store, conn.material_id, conn.room);
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
//
|
|
254
|
+
// ==================== 방 ====================
|
|
255
|
+
//
|
|
256
|
+
const roomKey = (materialId, room) => `${materialId}:${room}`;
|
|
257
|
+
function getRoom(store, materialId, name) {
|
|
258
|
+
const key = roomKey(materialId, name);
|
|
259
|
+
let room = store.rooms.get(key);
|
|
260
|
+
if (!room) {
|
|
261
|
+
room = {
|
|
262
|
+
members: new Map(),
|
|
263
|
+
log: [],
|
|
264
|
+
seq: 0,
|
|
265
|
+
waiters: new Set()
|
|
266
|
+
};
|
|
267
|
+
store.rooms.set(key, room);
|
|
268
|
+
}
|
|
269
|
+
return room;
|
|
270
|
+
}
|
|
271
|
+
/** 이 사람이 SSE로 이 방에 연결돼 있는가 (그러면 침묵해도 빠지지 않는다) */
|
|
272
|
+
const hasStream = (store, materialId, name, accountId) => [...store.connections].some(c => c.material_id === materialId && c.room === name && c.account_id === accountId);
|
|
273
|
+
/** 45초 조용한 poll 멤버를 빼고, 들어오거나(새로) 확인한다. 꽉 차 있으면 false. 이미 멤버면 자리 유지 */
|
|
274
|
+
function joinRoom(store, materialId, name, accountId) {
|
|
275
|
+
const room = getRoom(store, materialId, name);
|
|
276
|
+
const now = Date.now();
|
|
277
|
+
let removed = false;
|
|
278
|
+
for (const [id, member] of room.members) {
|
|
279
|
+
if (now - member.seen > store.presenceMs && !hasStream(store, materialId, name, id)) {
|
|
280
|
+
room.members.delete(id);
|
|
281
|
+
removed = true;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
const existing = room.members.get(accountId);
|
|
285
|
+
if (existing) {
|
|
286
|
+
existing.seen = now;
|
|
287
|
+
return {
|
|
288
|
+
removed,
|
|
289
|
+
added: false
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
if (room.members.size >= ROOM_MAX_MEMBERS) {
|
|
293
|
+
if (removed) publishMembers(store, materialId, name);
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
room.members.set(accountId, {
|
|
297
|
+
joined_at: now,
|
|
298
|
+
seen: now
|
|
299
|
+
});
|
|
300
|
+
return {
|
|
301
|
+
removed,
|
|
302
|
+
added: true
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function roomFull(res) {
|
|
306
|
+
fail(res, 409, 'RESOURCE_CONFLICT', 'The room is full (dev).', [{
|
|
307
|
+
ctx: {
|
|
308
|
+
reason: 'room_full',
|
|
309
|
+
limit: ROOM_MAX_MEMBERS
|
|
310
|
+
}
|
|
311
|
+
}]);
|
|
312
|
+
}
|
|
313
|
+
/** 방 이벤트를 기록에 붙이고, 방 SSE 연결에 보내고, 기다리는 poll을 깨운다 */
|
|
314
|
+
function appendRoomEvent(store, materialId, name, event, data) {
|
|
315
|
+
const room = getRoom(store, materialId, name);
|
|
316
|
+
room.seq += 1;
|
|
317
|
+
const entry = {
|
|
318
|
+
id: `${Date.now()}-${room.seq}`,
|
|
319
|
+
event,
|
|
320
|
+
data
|
|
321
|
+
};
|
|
322
|
+
room.log.push(entry);
|
|
323
|
+
if (room.log.length > ROOM_LOG_MAX) room.log.splice(0, room.log.length - ROOM_LOG_MAX);
|
|
324
|
+
const message = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
325
|
+
for (const c of store.connections) {
|
|
326
|
+
if (c.material_id === materialId && c.room === name) c.res.write(message);
|
|
327
|
+
}
|
|
328
|
+
for (const wake of [...room.waiters]) wake();
|
|
329
|
+
return entry;
|
|
330
|
+
}
|
|
331
|
+
/** 지금 멤버(들어온 순)를 `room_members`로 알린다 */
|
|
332
|
+
function publishMembers(store, materialId, name) {
|
|
333
|
+
const room = getRoom(store, materialId, name);
|
|
334
|
+
const members = [...room.members.entries()].sort(([, a], [, b]) => a.joined_at - b.joined_at).map(([account_id, {
|
|
335
|
+
joined_at
|
|
336
|
+
}]) => ({
|
|
337
|
+
account_id,
|
|
338
|
+
joined_at
|
|
339
|
+
}));
|
|
340
|
+
return appendRoomEvent(store, materialId, name, 'room_members', {
|
|
341
|
+
members
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
const parseCursor = cursor => cursor.split('-').map(Number);
|
|
345
|
+
const isAfter = (a, b) => {
|
|
346
|
+
const [am, as] = parseCursor(a);
|
|
347
|
+
const [bm, bs] = parseCursor(b);
|
|
348
|
+
return am > bm || am === bm && as > bs;
|
|
349
|
+
};
|
|
350
|
+
/** `/materials/{id}/rooms/{room}/messages|poll|leave` */
|
|
351
|
+
async function handleRoomApi(req, res, [, materialId, name, route], opts) {
|
|
352
|
+
const {
|
|
353
|
+
store
|
|
354
|
+
} = opts;
|
|
355
|
+
const method = req.method ?? 'GET';
|
|
356
|
+
const claims = readClaims(req);
|
|
357
|
+
if (!claims) return fail(res, 401, 'AUTHENTICATION_INVALID', 'missing or expired token (dev)');
|
|
358
|
+
if (materialId !== claims.material_id) return fail(res, 403, 'AUTH_PERMISSION_DENIED', 'material mismatch');
|
|
359
|
+
if (!ROOM_NAME.test(name)) return fail(res, 422, 'VALIDATION_ERROR', 'room: ^[a-z0-9_-]{1,32}$', [{
|
|
360
|
+
type: 'string_pattern_mismatch',
|
|
361
|
+
loc: ['path', 'room']
|
|
362
|
+
}]);
|
|
363
|
+
const expected = route === 'poll' ? 'GET' : 'POST';
|
|
364
|
+
if (method !== expected) return fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${route}`);
|
|
365
|
+
const accountId = claims.account_id;
|
|
366
|
+
if (route === 'leave') {
|
|
367
|
+
const room = store.rooms.get(roomKey(materialId, name));
|
|
368
|
+
if (room?.members.delete(accountId)) publishMembers(store, materialId, name);
|
|
369
|
+
res.writeHead(204).end();
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
if (route === 'messages') {
|
|
373
|
+
const {
|
|
374
|
+
json
|
|
375
|
+
} = await body(req);
|
|
376
|
+
const {
|
|
377
|
+
type,
|
|
378
|
+
data
|
|
379
|
+
} = json ?? {};
|
|
380
|
+
if (typeof type !== 'string' || type.length < 1 || type.length > ROOM_MESSAGE_TYPE_MAX || !json || !Object.hasOwn(json, 'data')) {
|
|
381
|
+
return fail(res, 422, 'VALIDATION_ERROR', 'type: 1..32 characters, data: JSON', [{
|
|
382
|
+
type: 'value_error',
|
|
383
|
+
loc: ['body']
|
|
384
|
+
}]);
|
|
385
|
+
}
|
|
386
|
+
const totalBytes = Buffer.byteLength(JSON.stringify({
|
|
387
|
+
type,
|
|
388
|
+
data
|
|
389
|
+
}));
|
|
390
|
+
if (totalBytes > ROOM_MESSAGE_MAX_BYTES) {
|
|
391
|
+
return fail(res, 422, 'VALIDATION_ERROR', 'message too large (dev)', [{
|
|
392
|
+
ctx: {
|
|
393
|
+
field: 'body',
|
|
394
|
+
reason: 'message_too_large',
|
|
395
|
+
limit_bytes: ROOM_MESSAGE_MAX_BYTES,
|
|
396
|
+
total_bytes: totalBytes
|
|
397
|
+
}
|
|
398
|
+
}]);
|
|
399
|
+
}
|
|
400
|
+
const now = Date.now();
|
|
401
|
+
const rateKey = `${materialId}:${accountId}`;
|
|
402
|
+
const times = (store.messageTimes.get(rateKey) ?? []).filter(t => now - t < 1000);
|
|
403
|
+
if (times.length >= ROOM_MESSAGE_RATE) {
|
|
404
|
+
store.messageTimes.set(rateKey, times);
|
|
405
|
+
return fail(res, 429, 'MATERIAL_TOO_MANY_ROOM_MESSAGES', 'Too many room messages (dev).', [{
|
|
406
|
+
ctx: {
|
|
407
|
+
reason: 'room_message_rate_limited',
|
|
408
|
+
limit: ROOM_MESSAGE_RATE
|
|
409
|
+
}
|
|
410
|
+
}]);
|
|
411
|
+
}
|
|
412
|
+
times.push(now);
|
|
413
|
+
store.messageTimes.set(rateKey, times);
|
|
414
|
+
appendRoomEvent(store, materialId, name, 'room_message', {
|
|
415
|
+
from: accountId,
|
|
416
|
+
t: now,
|
|
417
|
+
type,
|
|
418
|
+
data
|
|
419
|
+
});
|
|
420
|
+
res.writeHead(202, {
|
|
421
|
+
'Content-Type': 'application/json; charset=utf-8'
|
|
422
|
+
});
|
|
423
|
+
res.end(JSON.stringify({
|
|
424
|
+
data: {
|
|
425
|
+
t: now
|
|
426
|
+
},
|
|
427
|
+
meta: {}
|
|
428
|
+
}));
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
// poll
|
|
432
|
+
const url = new URL(req.url ?? '', 'http://x');
|
|
433
|
+
const after = url.searchParams.get('after');
|
|
434
|
+
if (after === null) {
|
|
435
|
+
if (!joinRoom(store, materialId, name, accountId)) return roomFull(res);
|
|
436
|
+
const snapshot = publishMembers(store, materialId, name);
|
|
437
|
+
return send(res, 200, {
|
|
438
|
+
events: [snapshot],
|
|
439
|
+
next: snapshot.id
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
if (!CURSOR.test(after)) {
|
|
443
|
+
return fail(res, 422, 'VALIDATION_ERROR', 'after: a cursor', [{
|
|
444
|
+
type: 'string_pattern_mismatch',
|
|
445
|
+
loc: ['query', 'after']
|
|
446
|
+
}]);
|
|
447
|
+
}
|
|
448
|
+
const waitRaw = Number(url.searchParams.get('wait') ?? 10);
|
|
449
|
+
const waitSeconds = Math.min(Math.max(Number.isFinite(waitRaw) ? Math.trunc(waitRaw) : 10, 1), 20);
|
|
450
|
+
const presence = joinRoom(store, materialId, name, accountId);
|
|
451
|
+
if (!presence) return roomFull(res);
|
|
452
|
+
if (presence.added || presence.removed) publishMembers(store, materialId, name);
|
|
453
|
+
const room = getRoom(store, materialId, name);
|
|
454
|
+
const read = () => {
|
|
455
|
+
const oldest = room.log[0];
|
|
456
|
+
if (!oldest || isAfter(oldest.id, after)) return null;
|
|
457
|
+
return room.log.filter(e => isAfter(e.id, after)).slice(0, 100);
|
|
458
|
+
};
|
|
459
|
+
let events = read();
|
|
460
|
+
if (events === null) {
|
|
461
|
+
return fail(res, 410, 'MATERIAL_ROOM_CURSOR_EXPIRED', 'The room events after this cursor are gone (dev).', [{
|
|
462
|
+
ctx: {
|
|
463
|
+
reason: 'room_cursor_expired',
|
|
464
|
+
cursor: after
|
|
465
|
+
}
|
|
466
|
+
}]);
|
|
467
|
+
}
|
|
468
|
+
if (events.length === 0) {
|
|
469
|
+
await new Promise(resolve => {
|
|
470
|
+
const timer = setTimeout(done, waitSeconds * 1000);
|
|
471
|
+
timer.unref();
|
|
472
|
+
function done() {
|
|
473
|
+
clearTimeout(timer);
|
|
474
|
+
room.waiters.delete(done);
|
|
475
|
+
resolve();
|
|
476
|
+
}
|
|
477
|
+
room.waiters.add(done);
|
|
478
|
+
res.on('close', done);
|
|
479
|
+
});
|
|
480
|
+
if (res.destroyed) return;
|
|
481
|
+
events = read() ?? [];
|
|
482
|
+
}
|
|
483
|
+
return send(res, 200, {
|
|
484
|
+
events,
|
|
485
|
+
next: events.at(-1)?.id ?? after
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export { PUBLIC_MAX_BYTES, ROOM_MAX_MEMBERS, ROOM_MESSAGE_MAX_BYTES, ROOM_MESSAGE_RATE, closePublicKv, createPublicKvStore, handlePublicKvApi, notifyPublicChange, touchesPublic };
|
package/es/dev/mock-api.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { type LocalGrading } from '../core/config.js';
|
|
2
2
|
import { type CompletionPolicy, type GradingFeedback } from './grading.js';
|
|
3
|
+
import { type PublicKvStore } from './kv-public-mock.js';
|
|
4
|
+
import { type MaterialScope, type MaterialViewer } from './mock-http.js';
|
|
3
5
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
6
|
+
export type { MaterialScope, MaterialViewer } from './mock-http.js';
|
|
4
7
|
/**
|
|
5
8
|
* elice-material API 흉내 (서버 설계 v25, @eliceio/cdk 1.x가 부르는 것만).
|
|
6
9
|
* 응답은 elib 형식 `{ data, meta }`, 필드는 snake_case. 오류는 `{ data: null, meta: { error } }`.
|
|
@@ -11,13 +14,28 @@ export declare const STUDENT: {
|
|
|
11
14
|
anonymous_id: string;
|
|
12
15
|
fullname: string;
|
|
13
16
|
};
|
|
17
|
+
/** 학생 여럿 (보드를 여러 탭에서 볼 때): 보기 `student:2` · `student:3` */
|
|
18
|
+
export declare const STUDENT_2: {
|
|
19
|
+
account_id: number;
|
|
20
|
+
anonymous_id: string;
|
|
21
|
+
fullname: string;
|
|
22
|
+
};
|
|
23
|
+
export declare const STUDENT_3: {
|
|
24
|
+
account_id: number;
|
|
25
|
+
anonymous_id: string;
|
|
26
|
+
fullname: string;
|
|
27
|
+
};
|
|
14
28
|
export declare const MANAGER: {
|
|
15
29
|
account_id: number;
|
|
16
30
|
anonymous_id: string;
|
|
17
31
|
fullname: string;
|
|
18
32
|
};
|
|
19
|
-
|
|
20
|
-
export
|
|
33
|
+
/** 계정 id → 익명 id · 이름. 모르는 계정은 첫 학생으로 본다 */
|
|
34
|
+
export declare const accountOf: (accountId: number) => {
|
|
35
|
+
account_id: number;
|
|
36
|
+
anonymous_id: string;
|
|
37
|
+
fullname: string;
|
|
38
|
+
};
|
|
21
39
|
/**
|
|
22
40
|
* dev 호스트 화면의 보기 (dev 전용). 토큰은 scope + viewer로 바뀐다.
|
|
23
41
|
* - student · instructor · tutor: `#token=…` (scope learn). 학습 페이지라 교육자도 학생 화면(learn)을 본다
|
|
@@ -32,11 +50,14 @@ export type MaterialViewer = 'student' | 'instructor' | 'tutor';
|
|
|
32
50
|
* edit 범위 응답에는 `grading`까지, 학생 · 튜터 · 교육자(learn scope) 응답에는 서버처럼 `grading`을 빼고 준다
|
|
33
51
|
*/
|
|
34
52
|
export type DevScenario = 'student' | 'instructor' | 'tutor' | 'edit';
|
|
35
|
-
/** 토큰을 발급하는
|
|
36
|
-
export type TokenScenario = DevScenario;
|
|
37
|
-
export declare const TOKEN_SCENARIOS: Readonly<Record<
|
|
53
|
+
/** 토큰을 발급하는 보기. `student:2` · `student:3`은 다른 학생(계정 · 익명 id · 이름이 다름), `student`는 첫 학생 그대로 */
|
|
54
|
+
export type TokenScenario = DevScenario | 'student:2' | 'student:3';
|
|
55
|
+
export declare const TOKEN_SCENARIOS: Readonly<Record<TokenScenario, {
|
|
38
56
|
scope: MaterialScope;
|
|
39
57
|
viewer: MaterialViewer;
|
|
58
|
+
subject: {
|
|
59
|
+
account_id: number;
|
|
60
|
+
};
|
|
40
61
|
}>>;
|
|
41
62
|
export declare const isTokenScenario: (v: unknown) => v is TokenScenario;
|
|
42
63
|
export declare function issueToken(scenario: TokenScenario, ttlSeconds?: number): string;
|
|
@@ -77,6 +98,8 @@ export interface MockState {
|
|
|
77
98
|
kv: Map<number, Record<string, unknown>>;
|
|
78
99
|
/** 호스트 화면에서 고른 완료 정책. null이면 권장값(recommendedCompletionPolicy). 처음 상태로 되돌려도 그대로 */
|
|
79
100
|
completionPolicy: CompletionPolicy | null;
|
|
101
|
+
/** 공개 kv(`public` 줄) 알림 · 입장권 · SSE 연결 (kv-public-mock.ts). 줄 자체는 `kv`에 있다 */
|
|
102
|
+
publicKv: PublicKvStore;
|
|
80
103
|
}
|
|
81
104
|
export declare const createState: () => MockState;
|
|
82
105
|
/** 지금 쓰는 완료 정책: 고른 값, 없으면 권장값 */
|
|
@@ -118,4 +141,3 @@ export interface MockApiOptions {
|
|
|
118
141
|
}
|
|
119
142
|
/** `/api` 아래 요청을 처리한다 */
|
|
120
143
|
export declare function handleMockApi(req: IncomingMessage, res: ServerResponse, path: string, opts: MockApiOptions): Promise<void | ServerResponse<IncomingMessage>>;
|
|
121
|
-
export {};
|