@kubohiroya/turbowarp-http-server 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +346 -0
  3. package/README.md +874 -0
  4. package/dist/auth/digest-file.d.ts +17 -0
  5. package/dist/auth/digest-file.js +90 -0
  6. package/dist/auth/digest-file.js.map +1 -0
  7. package/dist/auth/digest.d.ts +23 -0
  8. package/dist/auth/digest.js +139 -0
  9. package/dist/auth/digest.js.map +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.js +156 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/community.d.ts +81 -0
  14. package/dist/community.js +689 -0
  15. package/dist/community.js.map +1 -0
  16. package/dist/digest-cli.d.ts +1 -0
  17. package/dist/digest-cli.js +159 -0
  18. package/dist/digest-cli.js.map +1 -0
  19. package/dist/extension-manifest.json +441 -0
  20. package/dist/protocol.d.ts +59 -0
  21. package/dist/protocol.js +71 -0
  22. package/dist/protocol.js.map +1 -0
  23. package/dist/server.d.ts +89 -0
  24. package/dist/server.js +650 -0
  25. package/dist/server.js.map +1 -0
  26. package/dist/turbowarp-http-server.js +1110 -0
  27. package/docs/deployment-targets.ja.md +274 -0
  28. package/docs/turbowarp-http-server.architecture.html +15149 -0
  29. package/docs/turbowarp-http-server.architecture.json +1014 -0
  30. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.dark.png +0 -0
  31. package/docs/turbowarp-http-server.architecture.visual-check.1440x900.light.png +0 -0
  32. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.dark.png +0 -0
  33. package/docs/turbowarp-http-server.architecture.visual-check.2048x1320.light.png +0 -0
  34. package/docs/turbowarp-http-server.architecture.visual-check.html +32 -0
  35. package/docs/turbowarp-http-server.architecture.visual-check.json +547 -0
  36. package/examples/01-hello-form/README.ja.md +46 -0
  37. package/examples/01-hello-form/server.mjs +59 -0
  38. package/examples/02-visitor-counter/README.ja.md +39 -0
  39. package/examples/02-visitor-counter/server.mjs +44 -0
  40. package/examples/03-message-board/README.ja.md +47 -0
  41. package/examples/03-message-board/server.mjs +72 -0
  42. package/examples/04-image-upload/README.ja.md +46 -0
  43. package/examples/04-image-upload/server.mjs +149 -0
  44. package/examples/05-live-camera/README.ja.md +47 -0
  45. package/examples/05-live-camera/server.mjs +147 -0
  46. package/examples/06-scratch-like-community/README.ja.md +82 -0
  47. package/examples/06-scratch-like-community/server.mjs +17 -0
  48. package/examples/README.ja.md +20 -0
  49. package/package.json +75 -0
  50. package/schemas/extension-manifest.schema.json +49 -0
  51. package/src/auth/digest-file.ts +115 -0
  52. package/src/auth/digest.ts +170 -0
  53. package/src/block-definitions.json +417 -0
  54. package/src/cli.ts +172 -0
  55. package/src/community.ts +815 -0
  56. package/src/config.ts +12 -0
  57. package/src/digest-cli.ts +178 -0
  58. package/src/extension-manifest.ts +149 -0
  59. package/src/extension.ts +713 -0
  60. package/src/globals.d.ts +30 -0
  61. package/src/index.ts +8 -0
  62. package/src/protocol.ts +132 -0
  63. package/src/server.ts +880 -0
@@ -0,0 +1,59 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {Hono} from 'hono';
3
+ import {secureHeaders} from 'hono/secure-headers';
4
+
5
+ const app = new Hono();
6
+
7
+ app.use('*', secureHeaders());
8
+
9
+ app.get('/', (c) =>
10
+ c.html(page('Hello form', `
11
+ <h1>Hello form</h1>
12
+ <form method="post" action="/hello">
13
+ <label>名前 <input name="name" autocomplete="name" required maxlength="40"></label>
14
+ <button type="submit">送信</button>
15
+ </form>
16
+ `))
17
+ );
18
+
19
+ app.post('/hello', async (c) => {
20
+ const body = await c.req.parseBody();
21
+ const name = sanitizeName(String(body.name ?? ''));
22
+ return c.html(page('Hello', `
23
+ <h1>こんにちは、${escapeHtml(name)}!</h1>
24
+ <p><a href="/">戻る</a></p>
25
+ `));
26
+ });
27
+
28
+ function sanitizeName(value) {
29
+ const trimmed = value.trim();
30
+ return trimmed.length > 0 ? trimmed.slice(0, 40) : 'ゲスト';
31
+ }
32
+
33
+ function page(title, body) {
34
+ return `<!doctype html>
35
+ <html lang="ja">
36
+ <head>
37
+ <meta charset="utf-8">
38
+ <title>${escapeHtml(title)}</title>
39
+ <style>
40
+ body{font-family:system-ui,sans-serif;line-height:1.6;max-width:720px;margin:40px auto;padding:0 16px}
41
+ input,button{font:inherit;padding:8px}
42
+ </style>
43
+ </head>
44
+ <body>${body}</body>
45
+ </html>`;
46
+ }
47
+
48
+ function escapeHtml(value) {
49
+ return String(value)
50
+ .replaceAll('&', '&amp;')
51
+ .replaceAll('<', '&lt;')
52
+ .replaceAll('>', '&gt;')
53
+ .replaceAll('"', '&quot;')
54
+ .replaceAll("'", '&#39;');
55
+ }
56
+
57
+ const port = Number.parseInt(process.env.PORT ?? '9101', 10);
58
+ serve({fetch: app.fetch, hostname: '127.0.0.1', port});
59
+ console.log(`01-hello-form: http://127.0.0.1:${port}/`);
@@ -0,0 +1,39 @@
1
+ # 02-visitor-counter
2
+
3
+ 日付単位でカウントを分け、`あなたは本日100人目の訪問者です` 形式で表示するサンプルです。
4
+
5
+ ## 起動
6
+
7
+ ```bash
8
+ corepack pnpm exec tsx examples/02-visitor-counter/server.mjs
9
+ ```
10
+
11
+ ブラウザで `http://127.0.0.1:9102/` を開きます。
12
+
13
+ ## HTTP route
14
+
15
+ | Method | Path | 期待されるレスポンス |
16
+ |---|---|---|
17
+ | `GET` | `/` | 今日の訪問者番号を 1 増やして HTML で表示 |
18
+ | `GET` | `/api/count` | 今日の日付と現在カウントを JSON で返す |
19
+
20
+ ## TurboWarp 側のブロック構成
21
+
22
+ ```text
23
+ when HTTP request received
24
+ use HTTP request [current request ID]
25
+ if <current request path = [/]> then
26
+ 今日の日付 key を作る
27
+ その key の変数を 1 増やす
28
+ respond with HTML [あなたは本日 N 人目の訪問者です]
29
+ end
30
+ ```
31
+
32
+ TurboWarp で日付ごとに変数を分けにくい場合は、JSON 文字列のリストや cloud variable ではなく、まずローカル学習用の通常変数で動きを確認します。
33
+
34
+ ## 動作確認
35
+
36
+ ```bash
37
+ curl http://127.0.0.1:9102/
38
+ curl http://127.0.0.1:9102/api/count
39
+ ```
@@ -0,0 +1,44 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {Hono} from 'hono';
3
+ import {secureHeaders} from 'hono/secure-headers';
4
+
5
+ const countsByDate = new Map();
6
+ const app = new Hono();
7
+
8
+ app.use('*', secureHeaders());
9
+
10
+ app.get('/', (c) => {
11
+ const today = todayKey();
12
+ const count = (countsByDate.get(today) ?? 0) + 1;
13
+ countsByDate.set(today, count);
14
+ return c.html(page('Visitor counter', `
15
+ <h1>あなたは本日${count}人目の訪問者です</h1>
16
+ <p>日付: ${today}</p>
17
+ <p><a href="/api/count">JSON を見る</a></p>
18
+ `));
19
+ });
20
+
21
+ app.get('/api/count', (c) => {
22
+ const today = todayKey();
23
+ return c.json({date: today, count: countsByDate.get(today) ?? 0});
24
+ });
25
+
26
+ function todayKey() {
27
+ return new Date().toLocaleDateString('sv-SE', {timeZone: 'Asia/Tokyo'});
28
+ }
29
+
30
+ function page(title, body) {
31
+ return `<!doctype html>
32
+ <html lang="ja">
33
+ <head>
34
+ <meta charset="utf-8">
35
+ <title>${title}</title>
36
+ <style>body{font-family:system-ui,sans-serif;line-height:1.6;max-width:720px;margin:40px auto;padding:0 16px}</style>
37
+ </head>
38
+ <body>${body}</body>
39
+ </html>`;
40
+ }
41
+
42
+ const port = Number.parseInt(process.env.PORT ?? '9102', 10);
43
+ serve({fetch: app.fetch, hostname: '127.0.0.1', port});
44
+ console.log(`02-visitor-counter: http://127.0.0.1:${port}/`);
@@ -0,0 +1,47 @@
1
+ # 03-message-board
2
+
3
+ `名前:メッセージ` を時系列で積み重ねて表示する簡易掲示板です。
4
+
5
+ ## 起動
6
+
7
+ ```bash
8
+ corepack pnpm exec tsx examples/03-message-board/server.mjs
9
+ ```
10
+
11
+ ブラウザで `http://127.0.0.1:9103/` を開きます。
12
+
13
+ ## HTTP route
14
+
15
+ | Method | Path | 期待されるレスポンス |
16
+ |---|---|---|
17
+ | `GET` | `/` | 投稿フォームとメッセージ一覧 |
18
+ | `POST` | `/messages` | 投稿を保存して `/` へ redirect |
19
+ | `GET` | `/api/messages` | メッセージ一覧 JSON |
20
+
21
+ ## TurboWarp 側のブロック構成
22
+
23
+ ```text
24
+ when HTTP request received
25
+ use HTTP request [current request ID]
26
+ if <GET /> then
27
+ HTML builder で form と message list を作る
28
+ respond with HTML [render HTML document ...]
29
+ end
30
+
31
+ if <POST /messages> then
32
+ request body から name/message を読む
33
+ list に [name:message] を追加する
34
+ set HTTP status [303]
35
+ set response header [location] to [/]
36
+ send response []
37
+ end
38
+ ```
39
+
40
+ ## 動作確認
41
+
42
+ ```bash
43
+ curl -i -X POST http://127.0.0.1:9103/messages \
44
+ -H 'content-type: application/x-www-form-urlencoded' \
45
+ --data 'name=Alice&message=こんにちは'
46
+ curl http://127.0.0.1:9103/api/messages
47
+ ```
@@ -0,0 +1,72 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {Hono} from 'hono';
3
+ import {secureHeaders} from 'hono/secure-headers';
4
+
5
+ const messages = [];
6
+ const app = new Hono();
7
+
8
+ app.use('*', secureHeaders());
9
+
10
+ app.get('/', (c) =>
11
+ c.html(page('Message board', `
12
+ <h1>Message board</h1>
13
+ <form method="post" action="/messages">
14
+ <label>名前 <input name="name" required maxlength="40"></label>
15
+ <label>メッセージ <textarea name="message" required maxlength="240"></textarea></label>
16
+ <button type="submit">投稿</button>
17
+ </form>
18
+ <ol>${messages.map(renderMessage).join('')}</ol>
19
+ `))
20
+ );
21
+
22
+ app.post('/messages', async (c) => {
23
+ const body = await c.req.parseBody();
24
+ const name = clampText(String(body.name ?? 'ゲスト'), 40);
25
+ const message = clampText(String(body.message ?? ''), 240);
26
+ if (message.length > 0) {
27
+ messages.push({name, message, createdAt: new Date().toISOString()});
28
+ }
29
+ return c.redirect('/', 303);
30
+ });
31
+
32
+ app.get('/api/messages', (c) => c.json({messages}));
33
+
34
+ function renderMessage(entry) {
35
+ return `<li><strong>${escapeHtml(entry.name)}</strong>:${escapeHtml(entry.message)} <time>${entry.createdAt}</time></li>`;
36
+ }
37
+
38
+ function clampText(value, maxLength) {
39
+ return value.trim().slice(0, maxLength);
40
+ }
41
+
42
+ function page(title, body) {
43
+ return `<!doctype html>
44
+ <html lang="ja">
45
+ <head>
46
+ <meta charset="utf-8">
47
+ <title>${escapeHtml(title)}</title>
48
+ <style>
49
+ body{font-family:system-ui,sans-serif;line-height:1.6;max-width:760px;margin:40px auto;padding:0 16px}
50
+ form{display:grid;gap:12px;margin-bottom:24px}
51
+ input,textarea,button{font:inherit;padding:8px}
52
+ textarea{min-height:96px}
53
+ li{margin:8px 0}
54
+ time{color:#666;font-size:.875rem}
55
+ </style>
56
+ </head>
57
+ <body>${body}</body>
58
+ </html>`;
59
+ }
60
+
61
+ function escapeHtml(value) {
62
+ return String(value)
63
+ .replaceAll('&', '&amp;')
64
+ .replaceAll('<', '&lt;')
65
+ .replaceAll('>', '&gt;')
66
+ .replaceAll('"', '&quot;')
67
+ .replaceAll("'", '&#39;');
68
+ }
69
+
70
+ const port = Number.parseInt(process.env.PORT ?? '9103', 10);
71
+ serve({fetch: app.fetch, hostname: '127.0.0.1', port});
72
+ console.log(`03-message-board: http://127.0.0.1:${port}/`);
@@ -0,0 +1,46 @@
1
+ # 04-image-upload
2
+
3
+ 画像を upload し、upload 後に `@assets` named resource として参照する流れを示します。
4
+
5
+ ## 起動
6
+
7
+ ```bash
8
+ corepack pnpm exec tsx examples/04-image-upload/server.mjs
9
+ ```
10
+
11
+ ブラウザで `http://127.0.0.1:9104/` を開きます。
12
+
13
+ ## HTTP route
14
+
15
+ | Method | Path | 期待されるレスポンス |
16
+ |---|---|---|
17
+ | `GET` | `/` | upload form と asset 一覧 |
18
+ | `POST` | `/upload` | 画像を検証して named resource として保存 |
19
+ | `GET` | `/@assets/` | asset metadata JSON |
20
+ | `GET` | `/@assets/<name>` | 画像 bytes |
21
+ | `HEAD` | `/@assets/<name>` | metadata headers |
22
+
23
+ upload は `image/png`、`image/jpeg`、`image/gif`、`image/webp` のみ許可し、2 MiB を上限にしています。
24
+
25
+ ## TurboWarp 側のブロック構成
26
+
27
+ ```text
28
+ when green flag clicked
29
+ set [asset name v] to [uploaded-image]
30
+ upload した画像 bytes を Asset Manager へ保存する
31
+ replace asset [asset name] with [画像 bytes]
32
+
33
+ when HTTP request received
34
+ use HTTP request [current request ID]
35
+ if <GET /> then
36
+ HTML builder で <img src="/@assets/uploaded-image"> を含む page を返す
37
+ end
38
+ ```
39
+
40
+ ## 動作確認
41
+
42
+ ```bash
43
+ curl -i -F 'name=sample' -F 'image=@./some-image.png;type=image/png' \
44
+ http://127.0.0.1:9104/upload
45
+ curl -i http://127.0.0.1:9104/@assets/sample
46
+ ```
@@ -0,0 +1,149 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {Hono} from 'hono';
3
+ import {secureHeaders} from 'hono/secure-headers';
4
+
5
+ const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
6
+ const ALLOWED_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
7
+ const assets = new Map();
8
+ const app = new Hono();
9
+
10
+ app.use('*', secureHeaders());
11
+
12
+ app.get('/', (c) =>
13
+ c.html(page('Image upload', `
14
+ <h1>Image upload</h1>
15
+ <form method="post" action="/upload" enctype="multipart/form-data">
16
+ <label>Resource name <input name="name" value="uploaded-image" pattern="[a-zA-Z0-9._-]{1,64}" required></label>
17
+ <label>Image <input name="image" type="file" accept="image/png,image/jpeg,image/gif,image/webp" required></label>
18
+ <button type="submit">Upload</button>
19
+ </form>
20
+ <h2>@assets</h2>
21
+ <ul>${Array.from(assets.values()).map(renderAsset).join('')}</ul>
22
+ `))
23
+ );
24
+
25
+ app.post('/upload', async (c) => {
26
+ const body = await c.req.parseBody();
27
+ const file = body.image;
28
+ const name = normalizeResourceName(String(body.name ?? 'uploaded-image'));
29
+ if (!(file instanceof File)) return c.text('image file is required', 400);
30
+ if (!ALLOWED_IMAGE_TYPES.has(file.type)) return c.text('unsupported image type', 415);
31
+ if (file.size > MAX_IMAGE_BYTES) return c.text('image is too large', 413);
32
+
33
+ const bytes = new Uint8Array(await file.arrayBuffer());
34
+ if (!matchesImageSignature(bytes, file.type)) return c.text('image signature does not match content type', 415);
35
+ putAsset(name, file.type, bytes);
36
+ return c.redirect(`/@assets/${encodeURIComponent(name)}`, 303);
37
+ });
38
+
39
+ app.get('/@assets/', (c) => c.json({assets: Array.from(assets.values()).map(toMetadata)}));
40
+ app.get('/@assets/:name', (c) => serveAsset(c, true));
41
+ app.on('HEAD', '/@assets/:name', (c) => serveAsset(c, false));
42
+
43
+ function putAsset(name, mimeType, bytes) {
44
+ const previous = assets.get(name);
45
+ const version = (previous?.version ?? 0) + 1;
46
+ assets.set(name, {
47
+ name,
48
+ mimeType,
49
+ bytes,
50
+ version,
51
+ etag: `"${name}-${version}-${bytes.byteLength}"`,
52
+ updatedAt: new Date()
53
+ });
54
+ }
55
+
56
+ function serveAsset(c, includeBody) {
57
+ const name = normalizeResourceName(c.req.param('name'));
58
+ const asset = assets.get(name);
59
+ if (!asset) return c.json({error: 'not_found'}, 404);
60
+ const headers = new Headers({
61
+ 'content-type': asset.mimeType,
62
+ 'content-length': String(asset.bytes.byteLength),
63
+ etag: asset.etag,
64
+ 'last-modified': asset.updatedAt.toUTCString(),
65
+ 'cache-control': 'no-cache'
66
+ });
67
+ return new Response(includeBody ? asset.bytes : null, {status: 200, headers});
68
+ }
69
+
70
+ function renderAsset(asset) {
71
+ const name = escapeHtml(asset.name);
72
+ const href = `/@assets/${encodeURIComponent(asset.name)}`;
73
+ return `<li><a href="${href}">${name}</a> <small>${asset.mimeType}, ${asset.bytes.byteLength} bytes</small><br><img src="${href}" alt="${name}"></li>`;
74
+ }
75
+
76
+ function toMetadata(asset) {
77
+ return {
78
+ name: asset.name,
79
+ mimeType: asset.mimeType,
80
+ byteLength: asset.bytes.byteLength,
81
+ etag: asset.etag,
82
+ updatedAt: asset.updatedAt.toISOString()
83
+ };
84
+ }
85
+
86
+ function normalizeResourceName(value) {
87
+ const normalized = value.trim().replaceAll(/[^a-zA-Z0-9._-]/g, '-').slice(0, 64);
88
+ return normalized.length > 0 ? normalized : 'uploaded-image';
89
+ }
90
+
91
+ function matchesImageSignature(bytes, mimeType) {
92
+ if (mimeType === 'image/png') {
93
+ return (
94
+ bytes[0] === 0x89 &&
95
+ bytes[1] === 0x50 &&
96
+ bytes[2] === 0x4e &&
97
+ bytes[3] === 0x47 &&
98
+ bytes[4] === 0x0d &&
99
+ bytes[5] === 0x0a &&
100
+ bytes[6] === 0x1a &&
101
+ bytes[7] === 0x0a
102
+ );
103
+ }
104
+ if (mimeType === 'image/jpeg') return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
105
+ if (mimeType === 'image/gif') return bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46;
106
+ if (mimeType === 'image/webp') {
107
+ return (
108
+ bytes[0] === 0x52 &&
109
+ bytes[1] === 0x49 &&
110
+ bytes[2] === 0x46 &&
111
+ bytes[3] === 0x46 &&
112
+ bytes[8] === 0x57 &&
113
+ bytes[9] === 0x45 &&
114
+ bytes[10] === 0x42 &&
115
+ bytes[11] === 0x50
116
+ );
117
+ }
118
+ return false;
119
+ }
120
+
121
+ function page(title, body) {
122
+ return `<!doctype html>
123
+ <html lang="ja">
124
+ <head>
125
+ <meta charset="utf-8">
126
+ <title>${escapeHtml(title)}</title>
127
+ <style>
128
+ body{font-family:system-ui,sans-serif;line-height:1.6;max-width:760px;margin:40px auto;padding:0 16px}
129
+ form{display:grid;gap:12px;margin-bottom:24px}
130
+ input,button{font:inherit;padding:8px}
131
+ img{display:block;max-width:320px;max-height:220px;margin-top:8px;border:1px solid #ddd}
132
+ </style>
133
+ </head>
134
+ <body>${body}</body>
135
+ </html>`;
136
+ }
137
+
138
+ function escapeHtml(value) {
139
+ return String(value)
140
+ .replaceAll('&', '&amp;')
141
+ .replaceAll('<', '&lt;')
142
+ .replaceAll('>', '&gt;')
143
+ .replaceAll('"', '&quot;')
144
+ .replaceAll("'", '&#39;');
145
+ }
146
+
147
+ const port = Number.parseInt(process.env.PORT ?? '9104', 10);
148
+ serve({fetch: app.fetch, hostname: '127.0.0.1', port});
149
+ console.log(`04-image-upload: http://127.0.0.1:${port}/`);
@@ -0,0 +1,47 @@
1
+ # 05-live-camera
2
+
3
+ 10 秒に 1 回カメラからの静止画を更新するライブカメラの形を、stable asset URL の atomic replace として示します。
4
+
5
+ このサンプルではブラウザや `curl` から `POST /camera/frame` へ画像を送ると、同じ `@assets/live-camera` URL が新しい bytes へ置き換わります。閲覧側の `/camera` は 10 秒ごとに同じ URL を再読込します。
6
+
7
+ ## 起動
8
+
9
+ ```bash
10
+ corepack pnpm exec tsx examples/05-live-camera/server.mjs
11
+ ```
12
+
13
+ ブラウザで `http://127.0.0.1:9105/camera` を開きます。
14
+
15
+ ## HTTP route
16
+
17
+ | Method | Path | 期待されるレスポンス |
18
+ |---|---|---|
19
+ | `GET` | `/camera` | 10 秒ごとに `/@assets/live-camera` を読み直す HTML |
20
+ | `POST` | `/camera/frame` | 画像 bytes を `live-camera` として atomic replace |
21
+ | `GET` | `/@assets/live-camera` | 現在の静止画 |
22
+ | `HEAD` | `/@assets/live-camera` | ETag/Last-Modified などの metadata |
23
+
24
+ ## TurboWarp 側のブロック構成
25
+
26
+ ```text
27
+ forever
28
+ capture current camera frame
29
+ replace asset [live-camera] with captured JPEG bytes
30
+ wait [10] seconds
31
+ end
32
+
33
+ when HTTP request received
34
+ use HTTP request [current request ID]
35
+ if <current request path = [/camera]> then
36
+ respond with HTML [<img src="/@assets/live-camera"> を含む page]
37
+ end
38
+ ```
39
+
40
+ ## 動作確認
41
+
42
+ ```bash
43
+ curl -i -X POST http://127.0.0.1:9105/camera/frame \
44
+ -H 'content-type: image/jpeg' \
45
+ --data-binary @./frame.jpg
46
+ curl -i http://127.0.0.1:9105/@assets/live-camera
47
+ ```
@@ -0,0 +1,147 @@
1
+ import {serve} from '@hono/node-server';
2
+ import {Hono} from 'hono';
3
+ import {secureHeaders} from 'hono/secure-headers';
4
+
5
+ const MAX_FRAME_BYTES = 2 * 1024 * 1024;
6
+ const ALLOWED_FRAME_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
7
+ const app = new Hono();
8
+ let liveCamera = makeSvgPlaceholder();
9
+ let liveCameraVersion = 1;
10
+ let liveCameraUpdatedAt = new Date();
11
+
12
+ app.use('*', secureHeaders());
13
+
14
+ app.get('/', (c) => c.redirect('/camera', 302));
15
+
16
+ app.get('/camera', (c) =>
17
+ c.html(page('Live camera', `
18
+ <h1>Live camera</h1>
19
+ <img id="frame" src="/@assets/live-camera" alt="live camera frame">
20
+ <p>stable URL: <code>/@assets/live-camera</code></p>
21
+ <form method="post" action="/camera/frame" enctype="multipart/form-data">
22
+ <label>Manual frame <input name="frame" type="file" accept="image/png,image/jpeg,image/webp" required></label>
23
+ <button type="submit">Replace frame</button>
24
+ </form>
25
+ <script>
26
+ const image = document.getElementById('frame');
27
+ setInterval(() => {
28
+ image.src = '/@assets/live-camera';
29
+ }, 10000);
30
+ </script>
31
+ `))
32
+ );
33
+
34
+ app.post('/camera/frame', async (c) => {
35
+ const contentType = c.req.header('content-type') ?? '';
36
+ if (contentType.startsWith('multipart/form-data')) {
37
+ const body = await c.req.parseBody();
38
+ const file = body.frame;
39
+ if (!(file instanceof File)) return c.text('frame file is required', 400);
40
+ return replaceFrame(c, file.type, new Uint8Array(await file.arrayBuffer()));
41
+ }
42
+
43
+ const mimeType = contentType.split(';', 1)[0] || 'application/octet-stream';
44
+ const bytes = new Uint8Array(await c.req.arrayBuffer());
45
+ return replaceFrame(c, mimeType, bytes);
46
+ });
47
+
48
+ app.get('/@assets/', (c) =>
49
+ c.json({
50
+ assets: [
51
+ {
52
+ name: 'live-camera',
53
+ mimeType: liveCamera.mimeType,
54
+ byteLength: liveCamera.bytes.byteLength,
55
+ etag: etag(),
56
+ updatedAt: liveCameraUpdatedAt.toISOString()
57
+ }
58
+ ]
59
+ })
60
+ );
61
+ app.get('/@assets/live-camera', () => serveFrame(true));
62
+ app.on('HEAD', '/@assets/live-camera', () => serveFrame(false));
63
+
64
+ function replaceFrame(c, mimeType, bytes) {
65
+ if (!ALLOWED_FRAME_TYPES.has(mimeType)) return c.text('unsupported frame type', 415);
66
+ if (bytes.byteLength > MAX_FRAME_BYTES) return c.text('frame is too large', 413);
67
+ if (!matchesImageSignature(bytes, mimeType)) return c.text('frame signature does not match content type', 415);
68
+ liveCamera = {mimeType, bytes};
69
+ liveCameraVersion += 1;
70
+ liveCameraUpdatedAt = new Date();
71
+ return c.redirect('/camera', 303);
72
+ }
73
+
74
+ function serveFrame(includeBody) {
75
+ return new Response(includeBody ? liveCamera.bytes : null, {
76
+ status: 200,
77
+ headers: {
78
+ 'content-type': liveCamera.mimeType,
79
+ 'content-length': String(liveCamera.bytes.byteLength),
80
+ etag: etag(),
81
+ 'last-modified': liveCameraUpdatedAt.toUTCString(),
82
+ 'cache-control': 'no-cache'
83
+ }
84
+ });
85
+ }
86
+
87
+ function etag() {
88
+ return `"live-camera-${liveCameraVersion}-${liveCamera.bytes.byteLength}"`;
89
+ }
90
+
91
+ function makeSvgPlaceholder() {
92
+ const text = `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360">
93
+ <rect width="640" height="360" fill="#f4f4f4"/>
94
+ <text x="320" y="180" text-anchor="middle" font-family="sans-serif" font-size="28" fill="#333">waiting for frame</text>
95
+ </svg>`;
96
+ return {mimeType: 'image/svg+xml', bytes: new TextEncoder().encode(text)};
97
+ }
98
+
99
+ function matchesImageSignature(bytes, mimeType) {
100
+ if (mimeType === 'image/png') {
101
+ return (
102
+ bytes[0] === 0x89 &&
103
+ bytes[1] === 0x50 &&
104
+ bytes[2] === 0x4e &&
105
+ bytes[3] === 0x47 &&
106
+ bytes[4] === 0x0d &&
107
+ bytes[5] === 0x0a &&
108
+ bytes[6] === 0x1a &&
109
+ bytes[7] === 0x0a
110
+ );
111
+ }
112
+ if (mimeType === 'image/jpeg') return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
113
+ if (mimeType === 'image/webp') {
114
+ return (
115
+ bytes[0] === 0x52 &&
116
+ bytes[1] === 0x49 &&
117
+ bytes[2] === 0x46 &&
118
+ bytes[3] === 0x46 &&
119
+ bytes[8] === 0x57 &&
120
+ bytes[9] === 0x45 &&
121
+ bytes[10] === 0x42 &&
122
+ bytes[11] === 0x50
123
+ );
124
+ }
125
+ return false;
126
+ }
127
+
128
+ function page(title, body) {
129
+ return `<!doctype html>
130
+ <html lang="ja">
131
+ <head>
132
+ <meta charset="utf-8">
133
+ <title>${title}</title>
134
+ <style>
135
+ body{font-family:system-ui,sans-serif;line-height:1.6;max-width:760px;margin:40px auto;padding:0 16px}
136
+ img{display:block;width:min(100%,640px);aspect-ratio:16/9;object-fit:contain;border:1px solid #ddd;background:#f7f7f7}
137
+ form{display:grid;gap:12px;margin-top:24px}
138
+ input,button{font:inherit;padding:8px}
139
+ </style>
140
+ </head>
141
+ <body>${body}</body>
142
+ </html>`;
143
+ }
144
+
145
+ const port = Number.parseInt(process.env.PORT ?? '9105', 10);
146
+ serve({fetch: app.fetch, hostname: '127.0.0.1', port});
147
+ console.log(`05-live-camera: http://127.0.0.1:${port}/camera`);