@quolu/lattice 0.52.2 → 0.52.4

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 (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,361 +1,361 @@
1
- import { createServer } from 'node:http';
2
-
3
- import { TODO_DASHBOARD_CODE_VERSION } from './todo-dashboard-registry.mjs';
4
-
5
- const LOOPBACK = '127.0.0.1';
6
- const POLL_MS = 500;
7
- const SSE_HEARTBEAT_MS = 25_000;
8
- const SSE_STALE_MS = 62_500;
9
- const SSE_WATCHDOG_MS = 12_500;
10
- const HTTP_ERROR_SCHEMA = 'lattice.todo_gantt_http_error.v1';
11
- const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
12
-
13
- function projectPath(projectId) {
14
- return `/projects/${encodeURIComponent(projectId)}/`;
15
- }
16
-
17
- /**
18
- * 注入点が消えていたら黙って注入をやめない。タブが出ない理由を後から追えるように、
19
- * 差せなかった事実をtyped errorとして立てる(差し込み位置は描画部品の実装に依る)。
20
- */
21
- function injectOnce(html, marker, replacement) {
22
- const at = html.indexOf(marker);
23
- if (at === -1 || html.indexOf(marker, at + marker.length) !== -1) {
24
- const error = new Error(`external pane injection point not unique: ${marker}`);
25
- error.code = 'EXTERNAL_PANE_INJECTION_FAILED';
26
- error.detail = { marker };
27
- throw error;
28
- }
29
- return `${html.slice(0, at)}${replacement}${html.slice(at + marker.length)}`;
30
- }
31
-
32
- const EXTERNAL_PANE_STYLE = '<style>.narrative-pane{display:flex;flex-direction:column}[data-right-panel="external"]{display:flex;flex:1 1 auto;min-height:0}[data-right-panel="external"]>iframe{flex:1 1 auto;width:100%;min-height:0;border:0;background:var(--surface-1)}</style>';
33
-
34
- /**
35
- * 生存判定は「非空の一覧を返すこと」だけを根拠にする。Latticeは差された先が何の
36
- * サービスかを知らないので、payloadの意味には触らない(非空配列、または配列値の
37
- * プロパティが1つ以上非空)。非200・fetch失敗・空一覧はすべて概要タブのままにする。
38
- */
39
- function externalPaneController(pane) {
40
- return `<script>(()=>{const root=document.querySelector('[data-gantt-root]');const panel=root.querySelector('[data-right-panel="external"]');const frame=panel.querySelector('iframe');const content=root.querySelector('.right-content');const button=root.querySelector('[data-show-external-pane]');const show=()=>{if(frame.getAttribute('src')===null)frame.setAttribute('src',frame.dataset.src);content.hidden=true;panel.hidden=false;button.setAttribute('aria-pressed','true');root.dataset.viewState='external';};const leave=()=>{if(root.dataset.viewState==='external')return;panel.hidden=true;content.hidden=false;button.setAttribute('aria-pressed','false');};new MutationObserver(leave).observe(root,{attributeFilter:['data-view-state']});button.addEventListener('click',show);const nonEmpty=value=>Array.isArray(value)&&value.length>0;fetch(${JSON.stringify(pane.probeUrl)},{cache:'no-store'}).then(response=>response.ok?response.json():null).then(payload=>{if(nonEmpty(payload)||(payload!==null&&typeof payload==='object'&&Object.values(payload).some(nonEmpty)))show();}).catch(()=>{});})();</script>`;
41
- }
42
-
43
- /**
44
- * projectに外部ペインが差してある時だけ、右ペインへタブ1枚とiframeを足す。
45
- * Latticeは題名・埋め込み先・生存probeの3つしか知らない(差す側が明示的に書く口)。
46
- */
47
- function withExternalPane(html, pane) {
48
- const tab = `<button type="button" data-show-external-pane aria-pressed="false">${escapeHtml(pane.title)}</button>`;
49
- const iframe = `<section data-right-panel="external" hidden><iframe data-src="${escapeHtml(pane.url)}" title="${escapeHtml(pane.title)}"></iframe></section>`;
50
- return injectOnce(
51
- injectOnce(
52
- injectOnce(
53
- injectOnce(html, "default-src 'none'; connect-src 'self';",
54
- `default-src 'none'; connect-src 'self' ${pane.probeOrigin}; frame-src ${pane.frameOrigin};`),
55
- '</head>', `${EXTERNAL_PANE_STYLE}</head>`,
56
- ),
57
- '<button type="button" data-show-overview>概要</button>', `${tab}<button type="button" data-show-overview>概要</button>`,
58
- ),
59
- '<div class="right-content">', `${iframe}<div class="right-content">`,
60
- ).replace('</body>', `${externalPaneController(pane)}</body>`);
61
- }
62
-
63
- function liveHtml(html, headDigest, eventsPath, externalPane = null) {
64
- const controller = `<script>(()=>{const badge=document.createElement('div');badge.setAttribute('role','status');badge.style.cssText='position:fixed;right:12px;bottom:12px;z-index:99;padding:6px 10px;border:1px solid #d9d8d4;border-radius:4px;background:#fcfcfb;font:600 12px system-ui';badge.textContent='進捗: 接続中';document.body.append(badge);const head=${JSON.stringify(headDigest)};let lastReceipt=Date.now();let stream=null;const receive=event=>{const next=JSON.parse(event.data);if(typeof next.head_digest!=='string')return;lastReceipt=Date.now();badge.textContent='進捗: 最新';if(next.head_digest!==head){badge.textContent='進捗: 更新を反映中';location.reload();}};const connect=()=>{if(stream)stream.close();badge.textContent='進捗: 接続中';stream=new EventSource(${JSON.stringify(eventsPath)});stream.onopen=()=>{lastReceipt=Date.now();};stream.addEventListener('state',receive);stream.addEventListener('ping',receive);stream.addEventListener('lattice-error',event=>{lastReceipt=Date.now();const detail=JSON.parse(event.data);badge.textContent='進捗: エラー '+detail.code;badge.style.borderColor='#d03b3b';});stream.onerror=()=>{badge.textContent='進捗: 再接続中';};};connect();setInterval(()=>{if(Date.now()-lastReceipt>${SSE_STALE_MS})connect();},${SSE_WATCHDOG_MS});})();</script>`;
65
- const publicMetadata = '<meta name="description" content="Latticeで管理しているプロジェクトの依存工程と進捗を確認できます。"><meta name="robots" content="noindex, nofollow"><meta name="theme-color" content="#f7f3ea">';
66
- const publicStyle = '<style>body[data-gantt-root]{grid-template-rows:auto minmax(0,1fr)}.lattice-live-brand{z-index:10;display:flex;align-items:center;gap:8px;min-width:0;padding:10px 16px;border-bottom:1px solid #d8d0c5;background:#f7f3ea;color:#6c655d;font:600 12px/1.5 system-ui,-apple-system,"Hiragino Sans","Yu Gothic UI",sans-serif}.lattice-live-brand a{color:#201d19;text-decoration:none}.lattice-live-brand a:hover{color:#315cbe}.lattice-live-brand strong{color:#201d19}.lattice-live-brand-note{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.lattice-live-back{margin-left:auto!important;color:#315cbe!important;font-weight:750}@media(max-width:560px){.lattice-live-brand{padding:9px 12px}.lattice-live-brand-note{display:none}}</style>';
67
- const publicHeader = '<header class="lattice-live-brand"><a href="https://kitepon.dev/">kitepon.dev</a><span aria-hidden="true">/</span><strong>Lattice</strong><span class="lattice-live-brand-note">公開工程表</span><a class="lattice-live-back" href="/projects/">一覧へ戻る</a></header>';
68
- const live = html
69
- .replace("default-src 'none';", "default-src 'none'; connect-src 'self';")
70
- .replace('</head>', `${publicMetadata}${publicStyle}</head>`)
71
- .replace(/<body([^>]*)>/u, `<body$1>${publicHeader}`)
72
- .replace('</body>', `${controller}</body>`);
73
- return externalPane === null ? live : withExternalPane(live, externalPane);
74
- }
75
-
76
- function escapeHtml(value) {
77
- return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;')
78
- .replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;');
79
- }
80
-
81
- function dashboardHtml(projects) {
82
- const rows = projects.map(({ projectId, displayName }) => {
83
- const href = projectPath(projectId);
84
- const projectIdentity = displayName === projectId
85
- ? '' : `<code>${escapeHtml(projectId)}</code>`;
86
- return `<li><a href="${escapeHtml(href)}"><strong>${escapeHtml(displayName)}</strong>${projectIdentity}<span aria-hidden="true">→</span></a></li>`;
87
- }).join('');
88
- const content = rows.length === 0 ? '<p>アクティブなプロジェクトはありません。</p>'
89
- : `<ul>${rows}</ul>`;
90
- return `<!doctype html><html lang="ja"><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Latticeが管理している公開中の工程と現在地を確認できます。"><meta name="robots" content="noindex, nofollow"><meta property="og:title" content="公開中の工程表 — Lattice"><meta property="og:description" content="Latticeが管理している公開中の工程と現在地を確認できます。"><meta name="theme-color" content="#f7f3ea"><title>公開中の工程表 — Lattice</title><style>:root{color-scheme:light;--paper:#f7f3ea;--panel:#fffdf8;--ink:#201d19;--soft:#6c655d;--line:#d8d0c5;--cobalt:#315cbe;--orange:#e85f2a}*{box-sizing:border-box}body{min-height:100vh;margin:0;color:var(--ink);background:var(--paper);font:16px/1.7 system-ui,-apple-system,sans-serif}.shell{max-width:880px;margin:0 auto;padding:28px 22px 40px}.brand{display:flex;align-items:center;gap:9px;padding-bottom:24px;border-bottom:1px solid var(--line);font-size:.88rem}.brand a,.footer a{color:var(--ink);font-weight:800;text-decoration:none}.brand a:hover,.footer a:hover{color:var(--cobalt)}.brand span{color:var(--soft)}main{padding:64px 0 72px}.eyebrow{margin:0 0 8px;color:var(--orange);font-size:.76rem;font-weight:800;letter-spacing:.14em}.lead{max-width:620px;margin:0 0 34px;color:var(--soft)}h1{margin:0 0 14px;font-size:clamp(2rem,6vw,3.4rem);line-height:1.12;letter-spacing:-.04em}ul{display:grid;gap:12px;margin:0;padding:0;list-style:none}li a{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:20px;padding:18px 20px;border:1px solid var(--line);border-radius:12px;color:inherit;background:var(--panel);text-decoration:none;box-shadow:0 8px 28px rgba(48,39,27,.04)}li a:hover{border-color:var(--cobalt);transform:translateY(-1px)}li strong{font-size:1.04rem}li code{color:var(--soft);font-size:.78rem}li span{color:var(--cobalt);font-weight:800}.note{margin:28px 0 0;padding:16px 18px;border-left:3px solid var(--orange);color:var(--soft);background:rgba(255,253,248,.72);font-size:.88rem}.footer{display:flex;flex-wrap:wrap;justify-content:space-between;gap:16px;padding-top:20px;border-top:1px solid var(--line);color:var(--soft);font-size:.82rem}.footer nav{display:flex;gap:18px}@media(max-width:560px){.shell{padding:20px 16px 32px}main{padding:44px 0 56px}li a{grid-template-columns:minmax(0,1fr) auto;padding:16px}li code{grid-column:1/-1;grid-row:2}.footer{display:block}.footer nav{margin-top:10px}}</style></head><body><div class="shell"><header class="brand"><a href="https://kitepon.dev/">kitepon.dev</a><span aria-hidden="true">/</span><strong>Lattice</strong></header><main><p class="eyebrow">LIVE DEVELOPMENT</p><h1>公開中の工程表</h1><p class="lead">Latticeが管理しているプロジェクトの工程と、いまどこまで進んでいるかを公開データから確認できます。</p>${content}<p class="note">表示内容はLatticeの記録から自動生成されます。製品の紹介や使い方はGitHubをご覧ください。</p></main><footer class="footer"><span>kitepon.dev の開発工程を、Latticeで可視化しています。</span><nav aria-label="関連リンク"><a href="https://kitepon.dev/">kitepon.dev</a><a href="https://github.com/kitepon-rgb/Lattice">GitHub</a></nav></footer></div></body></html>`;
91
- }
92
-
93
- function notFoundHtml(code, path) {
94
- const reason = code === 'PROJECT_NOT_FOUND'
95
- ? '指定された工程表は、公開を終了したかURLが変わった可能性があります。'
96
- : '指定されたページは、この公開工程表にはありません。';
97
- return `<!doctype html><html lang="ja"><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><meta name="theme-color" content="#f7f3ea"><title>ページが見つかりません — Lattice</title><style>:root{color-scheme:light;--paper:#f7f3ea;--panel:#fffdf8;--ink:#201d19;--soft:#6c655d;--line:#d8d0c5;--cobalt:#315cbe;--orange:#e85f2a}*{box-sizing:border-box}body{min-height:100vh;margin:0;color:var(--ink);background:var(--paper);font:16px/1.7 system-ui,-apple-system,"Hiragino Sans","Yu Gothic UI",sans-serif}.shell{width:min(720px,calc(100% - 32px));margin:0 auto;padding:28px 0 40px}.brand{display:flex;align-items:center;gap:9px;padding-bottom:24px;border-bottom:1px solid var(--line);font-size:.88rem}.brand a{color:var(--ink);font-weight:800;text-decoration:none}.brand a:hover{color:var(--cobalt)}.brand span{color:var(--soft)}main{padding:clamp(64px,12vw,112px) 0}.eyebrow{margin:0 0 10px;color:var(--orange);font-size:.76rem;font-weight:800;letter-spacing:.14em}h1{margin:0 0 16px;font-size:clamp(2.1rem,7vw,4rem);line-height:1.1;letter-spacing:-.045em}p{max-width:620px;margin:0;color:var(--soft)}code{display:block;margin-top:22px;padding:12px 14px;overflow-wrap:anywhere;border:1px solid var(--line);border-radius:8px;background:var(--panel);color:var(--soft);font-size:.78rem}.actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:28px}.actions a{display:inline-flex;align-items:center;min-height:44px;padding:0 16px;border:1px solid var(--line);border-radius:8px;color:var(--ink);background:var(--panel);font-weight:750;text-decoration:none}.actions a:first-child{border-color:var(--cobalt);color:#fff;background:var(--cobalt)}.actions a:hover{transform:translateY(-1px)}</style></head><body><div class="shell"><header class="brand"><a href="https://kitepon.dev/">kitepon.dev</a><span aria-hidden="true">/</span><strong>Lattice</strong></header><main><p class="eyebrow">404 · ${escapeHtml(code)}</p><h1>ページが見つかりません</h1><p>${reason}</p><code>${escapeHtml(path)}</code><nav class="actions" aria-label="戻り先"><a href="/projects/">公開工程表の一覧へ</a><a href="https://kitepon.dev/">kitepon.devへ</a></nav></main></div></body></html>`;
98
- }
99
-
100
- function validateProject(project) {
101
- if (project === null || typeof project !== 'object' || Array.isArray(project)
102
- || typeof project.projectId !== 'string' || !PROJECT_ID.test(project.projectId)
103
- || typeof project.displayName !== 'string' || project.displayName.length === 0
104
- || project.displayName !== project.displayName.trim()
105
- || typeof project.render !== 'function' || typeof project.readHead !== 'function') {
106
- throw new TypeError('project descriptor is invalid');
107
- }
108
- return Object.freeze({
109
- projectId: project.projectId,
110
- displayName: project.displayName,
111
- render: project.render,
112
- readHead: project.readHead,
113
- });
114
- }
115
-
116
- export function createTodoGanttProjectRegistry(initialProjects = []) {
117
- if (!Array.isArray(initialProjects)) throw new TypeError('initialProjects must be an array');
118
- const entries = new Map();
119
- const listeners = new Set();
120
- const notify = () => {
121
- for (const listener of listeners) listener();
122
- };
123
- const register = (project) => {
124
- const validated = validateProject(project);
125
- if (entries.has(validated.projectId)) {
126
- const error = new Error(`project already registered: ${validated.projectId}`);
127
- error.code = 'PROJECT_ALREADY_REGISTERED';
128
- throw error;
129
- }
130
- entries.set(validated.projectId, validated);
131
- notify();
132
- return validated;
133
- };
134
- for (const project of initialProjects) register(project);
135
- return Object.freeze({
136
- register,
137
- unregister(projectId) {
138
- const deleted = entries.delete(projectId);
139
- if (deleted) notify();
140
- return deleted;
141
- },
142
- get(projectId) { return entries.get(projectId) ?? null; },
143
- list() {
144
- return [...entries.values()].sort((left, right) => left.displayName.localeCompare(right.displayName, 'ja')
145
- || left.projectId.localeCompare(right.projectId, 'en'));
146
- },
147
- subscribe(listener) {
148
- if (typeof listener !== 'function') throw new TypeError('registry listener required');
149
- listeners.add(listener);
150
- return () => listeners.delete(listener);
151
- },
152
- });
153
- }
154
-
155
- function sendEvent(response, name, id, value) {
156
- response.write(`id: ${id}\nevent: ${name}\ndata: ${JSON.stringify(value)}\n\n`);
157
- }
158
-
159
- function sendHttpError(response, status, code, path) {
160
- response.writeHead(status, { 'content-type': 'application/json; charset=utf-8',
161
- 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
162
- response.end(`${JSON.stringify({ schema: HTTP_ERROR_SCHEMA, code, path })}\n`);
163
- }
164
-
165
- function sendNotFound(request, response, code, path) {
166
- if (!String(request.headers.accept ?? '').toLowerCase().includes('text/html')) {
167
- sendHttpError(response, 404, code, path);
168
- return;
169
- }
170
- const html = notFoundHtml(code, path);
171
- response.writeHead(404, { 'content-type': 'text/html; charset=utf-8',
172
- 'content-length': Buffer.byteLength(html), 'cache-control': 'no-store',
173
- 'x-content-type-options': 'nosniff' });
174
- response.end(html);
175
- }
176
-
177
- function finishRequestFailure(response, code, path) {
178
- try {
179
- if (!response.headersSent) sendHttpError(response, 500, code, path);
180
- else if (!response.writableEnded) response.end();
181
- } catch { response.destroy(); }
182
- }
183
-
184
- export async function startTodoGanttDashboardServer({ registry, port = 0, redirectSingleProject = false }) {
185
- if (!Number.isSafeInteger(port) || port < 0 || port > 65_535) throw new TypeError('port must be 0..65535');
186
- if (registry === null || typeof registry !== 'object' || typeof registry.get !== 'function'
187
- || typeof registry.list !== 'function') throw new TypeError('registry required');
188
- const clientsByProject = new Map();
189
- const lastHeads = new Map();
190
- const lastHeartbeats = new Map();
191
- let eventId = 0;
192
- let checking = false;
193
- let closed = false;
194
- const reconcileClients = () => {
195
- const active = new Set(registry.list().map(({ projectId }) => projectId));
196
- for (const [projectId, clients] of clientsByProject) {
197
- if (active.has(projectId)) continue;
198
- for (const client of clients) client.end();
199
- clientsByProject.delete(projectId);
200
- lastHeads.delete(projectId);
201
- lastHeartbeats.delete(projectId);
202
- }
203
- };
204
- const unsubscribe = typeof registry.subscribe === 'function'
205
- ? registry.subscribe(reconcileClients) : () => {};
206
- const handleRequest = async (request, response) => {
207
- let requestPath = request.url ?? '/';
208
- try {
209
- const url = new URL(requestPath, `http://${LOOPBACK}`);
210
- requestPath = url.pathname;
211
- if (request.method !== 'GET') {
212
- response.setHeader('allow', 'GET');
213
- sendHttpError(response, 405, 'METHOD_NOT_ALLOWED', requestPath);
214
- return;
215
- }
216
- if (url.pathname === '/__lattice/health') {
217
- response.writeHead(200, { 'content-type': 'application/json; charset=utf-8',
218
- 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
219
- // `version` is the package this process loaded at startup, not the one
220
- // installed on disk. That difference is the whole point: it is how a
221
- // caller learns the daemon is serving code that has been superseded.
222
- response.end(`${JSON.stringify({ schema: 'lattice.todo_dashboard_health.v1', pid: process.pid,
223
- port: actualPort, project_ids: registry.list().map(({ projectId }) => projectId),
224
- version: TODO_DASHBOARD_CODE_VERSION })}\n`);
225
- return;
226
- }
227
- if (url.pathname === '/' || url.pathname === '/projects/') {
228
- const projects = registry.list();
229
- if (url.pathname === '/' && redirectSingleProject && projects.length === 1) {
230
- response.writeHead(302, { location: projectPath(projects[0].projectId), 'cache-control': 'no-store' });
231
- response.end();
232
- return;
233
- }
234
- response.writeHead(200, { 'content-type': 'text/html; charset=utf-8',
235
- 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
236
- response.end(dashboardHtml(projects));
237
- return;
238
- }
239
- const match = /^\/projects\/([^/]+)\/(events)?$/u.exec(url.pathname);
240
- if (match === null) {
241
- sendNotFound(request, response, 'ROUTE_NOT_FOUND', url.pathname);
242
- return;
243
- }
244
- let requestedId;
245
- try { requestedId = decodeURIComponent(match[1]); } catch {
246
- sendHttpError(response, 400, 'PROJECT_ID_INVALID', url.pathname);
247
- return;
248
- }
249
- const project = registry.get(requestedId);
250
- if (project === null) {
251
- sendNotFound(request, response, 'PROJECT_NOT_FOUND', url.pathname);
252
- return;
253
- }
254
- if (match[2] === 'events') {
255
- response.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8',
256
- 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff' });
257
- if (!clientsByProject.has(project.projectId)) clientsByProject.set(project.projectId, new Set());
258
- clientsByProject.get(project.projectId).add(response);
259
- request.on('close', () => clientsByProject.get(project.projectId)?.delete(response));
260
- try {
261
- const head = await project.readHead();
262
- lastHeads.set(project.projectId, head);
263
- if (!lastHeartbeats.has(project.projectId)) lastHeartbeats.set(project.projectId, Date.now());
264
- sendEvent(response, 'state', ++eventId, { head_digest: head });
265
- } catch (error) {
266
- sendEvent(response, 'lattice-error', ++eventId, { code: error?.code ?? 'STORE_READ_FAILED' });
267
- clientsByProject.get(project.projectId)?.delete(response);
268
- response.end();
269
- }
270
- return;
271
- }
272
- const rendered = await project.render({
273
- projectId: project.projectId,
274
- displayName: project.displayName,
275
- });
276
- lastHeads.set(project.projectId, rendered.head_digest);
277
- // 外部ペイン設定は描画のたびにrender側が読み直す。差した/外した側は再起動を要さない。
278
- const html = liveHtml(rendered.html, rendered.head_digest,
279
- `${projectPath(project.projectId)}events`, rendered.external_pane ?? null);
280
- response.writeHead(200, { 'content-type': 'text/html; charset=utf-8',
281
- 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
282
- response.end(html);
283
- } catch (error) {
284
- finishRequestFailure(response, error?.code ?? 'GANTT_RENDER_FAILED', requestPath);
285
- }
286
- };
287
- const server = createServer((request, response) => {
288
- handleRequest(request, response).catch((error) => {
289
- finishRequestFailure(response, error?.code ?? 'GANTT_REQUEST_FAILED', request.url ?? '/');
290
- });
291
- });
292
- await new Promise((resolve, reject) => {
293
- server.once('error', reject);
294
- server.listen({ host: LOOPBACK, port }, resolve);
295
- });
296
- const timer = setInterval(async () => {
297
- if (checking) return;
298
- checking = true;
299
- try {
300
- reconcileClients();
301
- for (const project of registry.list()) {
302
- const clients = clientsByProject.get(project.projectId);
303
- if (clients === undefined || clients.size === 0) continue;
304
- try {
305
- const head = await project.readHead();
306
- if (lastHeads.get(project.projectId) !== head) {
307
- lastHeads.set(project.projectId, head);
308
- for (const client of clients) sendEvent(client, 'state', ++eventId, { head_digest: head });
309
- }
310
- const now = Date.now();
311
- if (now - (lastHeartbeats.get(project.projectId) ?? now) >= SSE_HEARTBEAT_MS) {
312
- lastHeartbeats.set(project.projectId, now);
313
- for (const client of clients) sendEvent(client, 'ping', ++eventId, { head_digest: head });
314
- }
315
- } catch (error) {
316
- for (const client of clients) sendEvent(client, 'lattice-error', ++eventId,
317
- { code: error?.code ?? 'STORE_READ_FAILED' });
318
- }
319
- }
320
- } finally { checking = false; }
321
- }, POLL_MS);
322
- timer.unref();
323
- const address = server.address();
324
- const actualPort = typeof address === 'object' && address !== null ? address.port : port;
325
- const close = async () => {
326
- if (closed) return;
327
- closed = true;
328
- clearInterval(timer);
329
- unsubscribe();
330
- for (const clients of clientsByProject.values()) for (const client of clients) client.end();
331
- clientsByProject.clear();
332
- await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
333
- };
334
- return Object.freeze({
335
- host: LOOPBACK,
336
- port: actualPort,
337
- url: `http://${LOOPBACK}:${actualPort}/`,
338
- projectsUrl: `http://${LOOPBACK}:${actualPort}/projects/`,
339
- registry,
340
- close,
341
- });
342
- }
343
-
344
- export async function startTodoGanttLiveServer({ projectId, displayName = projectId, port = 0, render, readHead }) {
345
- const registry = createTodoGanttProjectRegistry([{ projectId, displayName, render, readHead }]);
346
- const dashboard = await startTodoGanttDashboardServer({ registry, port, redirectSingleProject: true });
347
- const path = projectPath(projectId);
348
- return Object.freeze({
349
- projectId,
350
- displayName,
351
- host: dashboard.host,
352
- port: dashboard.port,
353
- projectPath: path,
354
- eventsPath: `${path}events`,
355
- url: `http://${dashboard.host}:${dashboard.port}${path}`,
356
- eventsUrl: `http://${dashboard.host}:${dashboard.port}${path}events`,
357
- projectsUrl: dashboard.projectsUrl,
358
- registry,
359
- close: dashboard.close,
360
- });
361
- }
1
+ import { createServer } from 'node:http';
2
+
3
+ import { TODO_DASHBOARD_CODE_VERSION } from './todo-dashboard-registry.mjs';
4
+
5
+ const LOOPBACK = '127.0.0.1';
6
+ const POLL_MS = 500;
7
+ const SSE_HEARTBEAT_MS = 25_000;
8
+ const SSE_STALE_MS = 62_500;
9
+ const SSE_WATCHDOG_MS = 12_500;
10
+ const HTTP_ERROR_SCHEMA = 'lattice.todo_gantt_http_error.v1';
11
+ const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
12
+
13
+ function projectPath(projectId) {
14
+ return `/projects/${encodeURIComponent(projectId)}/`;
15
+ }
16
+
17
+ /**
18
+ * 注入点が消えていたら黙って注入をやめない。タブが出ない理由を後から追えるように、
19
+ * 差せなかった事実をtyped errorとして立てる(差し込み位置は描画部品の実装に依る)。
20
+ */
21
+ function injectOnce(html, marker, replacement) {
22
+ const at = html.indexOf(marker);
23
+ if (at === -1 || html.indexOf(marker, at + marker.length) !== -1) {
24
+ const error = new Error(`external pane injection point not unique: ${marker}`);
25
+ error.code = 'EXTERNAL_PANE_INJECTION_FAILED';
26
+ error.detail = { marker };
27
+ throw error;
28
+ }
29
+ return `${html.slice(0, at)}${replacement}${html.slice(at + marker.length)}`;
30
+ }
31
+
32
+ const EXTERNAL_PANE_STYLE = '<style>.narrative-pane{display:flex;flex-direction:column}[data-right-panel="external"]{display:flex;flex:1 1 auto;min-height:0}[data-right-panel="external"]>iframe{flex:1 1 auto;width:100%;min-height:0;border:0;background:var(--surface-1)}</style>';
33
+
34
+ /**
35
+ * 生存判定は「非空の一覧を返すこと」だけを根拠にする。Latticeは差された先が何の
36
+ * サービスかを知らないので、payloadの意味には触らない(非空配列、または配列値の
37
+ * プロパティが1つ以上非空)。非200・fetch失敗・空一覧はすべて概要タブのままにする。
38
+ */
39
+ function externalPaneController(pane) {
40
+ return `<script>(()=>{const root=document.querySelector('[data-gantt-root]');const panel=root.querySelector('[data-right-panel="external"]');const frame=panel.querySelector('iframe');const content=root.querySelector('.right-content');const button=root.querySelector('[data-show-external-pane]');const show=()=>{if(frame.getAttribute('src')===null)frame.setAttribute('src',frame.dataset.src);content.hidden=true;panel.hidden=false;button.setAttribute('aria-pressed','true');root.dataset.viewState='external';};const leave=()=>{if(root.dataset.viewState==='external')return;panel.hidden=true;content.hidden=false;button.setAttribute('aria-pressed','false');};new MutationObserver(leave).observe(root,{attributeFilter:['data-view-state']});button.addEventListener('click',show);const nonEmpty=value=>Array.isArray(value)&&value.length>0;fetch(${JSON.stringify(pane.probeUrl)},{cache:'no-store'}).then(response=>response.ok?response.json():null).then(payload=>{if(nonEmpty(payload)||(payload!==null&&typeof payload==='object'&&Object.values(payload).some(nonEmpty)))show();}).catch(()=>{});})();</script>`;
41
+ }
42
+
43
+ /**
44
+ * projectに外部ペインが差してある時だけ、右ペインへタブ1枚とiframeを足す。
45
+ * Latticeは題名・埋め込み先・生存probeの3つしか知らない(差す側が明示的に書く口)。
46
+ */
47
+ function withExternalPane(html, pane) {
48
+ const tab = `<button type="button" data-show-external-pane aria-pressed="false">${escapeHtml(pane.title)}</button>`;
49
+ const iframe = `<section data-right-panel="external" hidden><iframe data-src="${escapeHtml(pane.url)}" title="${escapeHtml(pane.title)}"></iframe></section>`;
50
+ return injectOnce(
51
+ injectOnce(
52
+ injectOnce(
53
+ injectOnce(html, "default-src 'none'; connect-src 'self';",
54
+ `default-src 'none'; connect-src 'self' ${pane.probeOrigin}; frame-src ${pane.frameOrigin};`),
55
+ '</head>', `${EXTERNAL_PANE_STYLE}</head>`,
56
+ ),
57
+ '<button type="button" data-show-overview>概要</button>', `${tab}<button type="button" data-show-overview>概要</button>`,
58
+ ),
59
+ '<div class="right-content">', `${iframe}<div class="right-content">`,
60
+ ).replace('</body>', `${externalPaneController(pane)}</body>`);
61
+ }
62
+
63
+ function liveHtml(html, headDigest, eventsPath, externalPane = null) {
64
+ const controller = `<script>(()=>{const badge=document.createElement('div');badge.setAttribute('role','status');badge.style.cssText='position:fixed;right:12px;bottom:12px;z-index:99;padding:6px 10px;border:1px solid #d9d8d4;border-radius:4px;background:#fcfcfb;font:600 12px system-ui';badge.textContent='進捗: 接続中';document.body.append(badge);const head=${JSON.stringify(headDigest)};let lastReceipt=Date.now();let stream=null;const receive=event=>{const next=JSON.parse(event.data);if(typeof next.head_digest!=='string')return;lastReceipt=Date.now();badge.textContent='進捗: 最新';if(next.head_digest!==head){badge.textContent='進捗: 更新を反映中';location.reload();}};const connect=()=>{if(stream)stream.close();badge.textContent='進捗: 接続中';stream=new EventSource(${JSON.stringify(eventsPath)});stream.onopen=()=>{lastReceipt=Date.now();};stream.addEventListener('state',receive);stream.addEventListener('ping',receive);stream.addEventListener('lattice-error',event=>{lastReceipt=Date.now();const detail=JSON.parse(event.data);badge.textContent='進捗: エラー '+detail.code;badge.style.borderColor='#d03b3b';});stream.onerror=()=>{badge.textContent='進捗: 再接続中';};};connect();setInterval(()=>{if(Date.now()-lastReceipt>${SSE_STALE_MS})connect();},${SSE_WATCHDOG_MS});})();</script>`;
65
+ const publicMetadata = '<meta name="description" content="Latticeで管理しているプロジェクトの依存工程と進捗を確認できます。"><meta name="robots" content="noindex, nofollow"><meta name="theme-color" content="#f7f3ea">';
66
+ const publicStyle = '<style>body[data-gantt-root]{grid-template-rows:auto minmax(0,1fr)}.lattice-live-brand{z-index:10;display:flex;align-items:center;gap:8px;min-width:0;padding:10px 16px;border-bottom:1px solid #d8d0c5;background:#f7f3ea;color:#6c655d;font:600 12px/1.5 system-ui,-apple-system,"Hiragino Sans","Yu Gothic UI",sans-serif}.lattice-live-brand a{color:#201d19;text-decoration:none}.lattice-live-brand a:hover{color:#315cbe}.lattice-live-brand strong{color:#201d19}.lattice-live-brand-note{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.lattice-live-back{margin-left:auto!important;color:#315cbe!important;font-weight:750}@media(max-width:560px){.lattice-live-brand{padding:9px 12px}.lattice-live-brand-note{display:none}}</style>';
67
+ const publicHeader = '<header class="lattice-live-brand"><a href="https://kitepon.dev/">kitepon.dev</a><span aria-hidden="true">/</span><strong>Lattice</strong><span class="lattice-live-brand-note">公開工程表</span><a class="lattice-live-back" href="/projects/">一覧へ戻る</a></header>';
68
+ const live = html
69
+ .replace("default-src 'none';", "default-src 'none'; connect-src 'self';")
70
+ .replace('</head>', `${publicMetadata}${publicStyle}</head>`)
71
+ .replace(/<body([^>]*)>/u, `<body$1>${publicHeader}`)
72
+ .replace('</body>', `${controller}</body>`);
73
+ return externalPane === null ? live : withExternalPane(live, externalPane);
74
+ }
75
+
76
+ function escapeHtml(value) {
77
+ return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;')
78
+ .replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;');
79
+ }
80
+
81
+ function dashboardHtml(projects) {
82
+ const rows = projects.map(({ projectId, displayName }) => {
83
+ const href = projectPath(projectId);
84
+ const projectIdentity = displayName === projectId
85
+ ? '' : `<code>${escapeHtml(projectId)}</code>`;
86
+ return `<li><a href="${escapeHtml(href)}"><strong>${escapeHtml(displayName)}</strong>${projectIdentity}<span aria-hidden="true">→</span></a></li>`;
87
+ }).join('');
88
+ const content = rows.length === 0 ? '<p>アクティブなプロジェクトはありません。</p>'
89
+ : `<ul>${rows}</ul>`;
90
+ return `<!doctype html><html lang="ja"><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Latticeが管理している公開中の工程と現在地を確認できます。"><meta name="robots" content="noindex, nofollow"><meta property="og:title" content="公開中の工程表 — Lattice"><meta property="og:description" content="Latticeが管理している公開中の工程と現在地を確認できます。"><meta name="theme-color" content="#f7f3ea"><title>公開中の工程表 — Lattice</title><style>:root{color-scheme:light;--paper:#f7f3ea;--panel:#fffdf8;--ink:#201d19;--soft:#6c655d;--line:#d8d0c5;--cobalt:#315cbe;--orange:#e85f2a}*{box-sizing:border-box}body{min-height:100vh;margin:0;color:var(--ink);background:var(--paper);font:16px/1.7 system-ui,-apple-system,sans-serif}.shell{max-width:880px;margin:0 auto;padding:28px 22px 40px}.brand{display:flex;align-items:center;gap:9px;padding-bottom:24px;border-bottom:1px solid var(--line);font-size:.88rem}.brand a,.footer a{color:var(--ink);font-weight:800;text-decoration:none}.brand a:hover,.footer a:hover{color:var(--cobalt)}.brand span{color:var(--soft)}main{padding:64px 0 72px}.eyebrow{margin:0 0 8px;color:var(--orange);font-size:.76rem;font-weight:800;letter-spacing:.14em}.lead{max-width:620px;margin:0 0 34px;color:var(--soft)}h1{margin:0 0 14px;font-size:clamp(2rem,6vw,3.4rem);line-height:1.12;letter-spacing:-.04em}ul{display:grid;gap:12px;margin:0;padding:0;list-style:none}li a{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:20px;padding:18px 20px;border:1px solid var(--line);border-radius:12px;color:inherit;background:var(--panel);text-decoration:none;box-shadow:0 8px 28px rgba(48,39,27,.04)}li a:hover{border-color:var(--cobalt);transform:translateY(-1px)}li strong{font-size:1.04rem}li code{color:var(--soft);font-size:.78rem}li span{color:var(--cobalt);font-weight:800}.note{margin:28px 0 0;padding:16px 18px;border-left:3px solid var(--orange);color:var(--soft);background:rgba(255,253,248,.72);font-size:.88rem}.footer{display:flex;flex-wrap:wrap;justify-content:space-between;gap:16px;padding-top:20px;border-top:1px solid var(--line);color:var(--soft);font-size:.82rem}.footer nav{display:flex;gap:18px}@media(max-width:560px){.shell{padding:20px 16px 32px}main{padding:44px 0 56px}li a{grid-template-columns:minmax(0,1fr) auto;padding:16px}li code{grid-column:1/-1;grid-row:2}.footer{display:block}.footer nav{margin-top:10px}}</style></head><body><div class="shell"><header class="brand"><a href="https://kitepon.dev/">kitepon.dev</a><span aria-hidden="true">/</span><strong>Lattice</strong></header><main><p class="eyebrow">LIVE DEVELOPMENT</p><h1>公開中の工程表</h1><p class="lead">Latticeが管理しているプロジェクトの工程と、いまどこまで進んでいるかを公開データから確認できます。</p>${content}<p class="note">表示内容はLatticeの記録から自動生成されます。製品の紹介や使い方はGitHubをご覧ください。</p></main><footer class="footer"><span>kitepon.dev の開発工程を、Latticeで可視化しています。</span><nav aria-label="関連リンク"><a href="https://kitepon.dev/">kitepon.dev</a><a href="https://github.com/kitepon-rgb/Lattice">GitHub</a></nav></footer></div></body></html>`;
91
+ }
92
+
93
+ function notFoundHtml(code, path) {
94
+ const reason = code === 'PROJECT_NOT_FOUND'
95
+ ? '指定された工程表は、公開を終了したかURLが変わった可能性があります。'
96
+ : '指定されたページは、この公開工程表にはありません。';
97
+ return `<!doctype html><html lang="ja"><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex, nofollow"><meta name="theme-color" content="#f7f3ea"><title>ページが見つかりません — Lattice</title><style>:root{color-scheme:light;--paper:#f7f3ea;--panel:#fffdf8;--ink:#201d19;--soft:#6c655d;--line:#d8d0c5;--cobalt:#315cbe;--orange:#e85f2a}*{box-sizing:border-box}body{min-height:100vh;margin:0;color:var(--ink);background:var(--paper);font:16px/1.7 system-ui,-apple-system,"Hiragino Sans","Yu Gothic UI",sans-serif}.shell{width:min(720px,calc(100% - 32px));margin:0 auto;padding:28px 0 40px}.brand{display:flex;align-items:center;gap:9px;padding-bottom:24px;border-bottom:1px solid var(--line);font-size:.88rem}.brand a{color:var(--ink);font-weight:800;text-decoration:none}.brand a:hover{color:var(--cobalt)}.brand span{color:var(--soft)}main{padding:clamp(64px,12vw,112px) 0}.eyebrow{margin:0 0 10px;color:var(--orange);font-size:.76rem;font-weight:800;letter-spacing:.14em}h1{margin:0 0 16px;font-size:clamp(2.1rem,7vw,4rem);line-height:1.1;letter-spacing:-.045em}p{max-width:620px;margin:0;color:var(--soft)}code{display:block;margin-top:22px;padding:12px 14px;overflow-wrap:anywhere;border:1px solid var(--line);border-radius:8px;background:var(--panel);color:var(--soft);font-size:.78rem}.actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:28px}.actions a{display:inline-flex;align-items:center;min-height:44px;padding:0 16px;border:1px solid var(--line);border-radius:8px;color:var(--ink);background:var(--panel);font-weight:750;text-decoration:none}.actions a:first-child{border-color:var(--cobalt);color:#fff;background:var(--cobalt)}.actions a:hover{transform:translateY(-1px)}</style></head><body><div class="shell"><header class="brand"><a href="https://kitepon.dev/">kitepon.dev</a><span aria-hidden="true">/</span><strong>Lattice</strong></header><main><p class="eyebrow">404 · ${escapeHtml(code)}</p><h1>ページが見つかりません</h1><p>${reason}</p><code>${escapeHtml(path)}</code><nav class="actions" aria-label="戻り先"><a href="/projects/">公開工程表の一覧へ</a><a href="https://kitepon.dev/">kitepon.devへ</a></nav></main></div></body></html>`;
98
+ }
99
+
100
+ function validateProject(project) {
101
+ if (project === null || typeof project !== 'object' || Array.isArray(project)
102
+ || typeof project.projectId !== 'string' || !PROJECT_ID.test(project.projectId)
103
+ || typeof project.displayName !== 'string' || project.displayName.length === 0
104
+ || project.displayName !== project.displayName.trim()
105
+ || typeof project.render !== 'function' || typeof project.readHead !== 'function') {
106
+ throw new TypeError('project descriptor is invalid');
107
+ }
108
+ return Object.freeze({
109
+ projectId: project.projectId,
110
+ displayName: project.displayName,
111
+ render: project.render,
112
+ readHead: project.readHead,
113
+ });
114
+ }
115
+
116
+ export function createTodoGanttProjectRegistry(initialProjects = []) {
117
+ if (!Array.isArray(initialProjects)) throw new TypeError('initialProjects must be an array');
118
+ const entries = new Map();
119
+ const listeners = new Set();
120
+ const notify = () => {
121
+ for (const listener of listeners) listener();
122
+ };
123
+ const register = (project) => {
124
+ const validated = validateProject(project);
125
+ if (entries.has(validated.projectId)) {
126
+ const error = new Error(`project already registered: ${validated.projectId}`);
127
+ error.code = 'PROJECT_ALREADY_REGISTERED';
128
+ throw error;
129
+ }
130
+ entries.set(validated.projectId, validated);
131
+ notify();
132
+ return validated;
133
+ };
134
+ for (const project of initialProjects) register(project);
135
+ return Object.freeze({
136
+ register,
137
+ unregister(projectId) {
138
+ const deleted = entries.delete(projectId);
139
+ if (deleted) notify();
140
+ return deleted;
141
+ },
142
+ get(projectId) { return entries.get(projectId) ?? null; },
143
+ list() {
144
+ return [...entries.values()].sort((left, right) => left.displayName.localeCompare(right.displayName, 'ja')
145
+ || left.projectId.localeCompare(right.projectId, 'en'));
146
+ },
147
+ subscribe(listener) {
148
+ if (typeof listener !== 'function') throw new TypeError('registry listener required');
149
+ listeners.add(listener);
150
+ return () => listeners.delete(listener);
151
+ },
152
+ });
153
+ }
154
+
155
+ function sendEvent(response, name, id, value) {
156
+ response.write(`id: ${id}\nevent: ${name}\ndata: ${JSON.stringify(value)}\n\n`);
157
+ }
158
+
159
+ function sendHttpError(response, status, code, path) {
160
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8',
161
+ 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
162
+ response.end(`${JSON.stringify({ schema: HTTP_ERROR_SCHEMA, code, path })}\n`);
163
+ }
164
+
165
+ function sendNotFound(request, response, code, path) {
166
+ if (!String(request.headers.accept ?? '').toLowerCase().includes('text/html')) {
167
+ sendHttpError(response, 404, code, path);
168
+ return;
169
+ }
170
+ const html = notFoundHtml(code, path);
171
+ response.writeHead(404, { 'content-type': 'text/html; charset=utf-8',
172
+ 'content-length': Buffer.byteLength(html), 'cache-control': 'no-store',
173
+ 'x-content-type-options': 'nosniff' });
174
+ response.end(html);
175
+ }
176
+
177
+ function finishRequestFailure(response, code, path) {
178
+ try {
179
+ if (!response.headersSent) sendHttpError(response, 500, code, path);
180
+ else if (!response.writableEnded) response.end();
181
+ } catch { response.destroy(); }
182
+ }
183
+
184
+ export async function startTodoGanttDashboardServer({ registry, port = 0, redirectSingleProject = false }) {
185
+ if (!Number.isSafeInteger(port) || port < 0 || port > 65_535) throw new TypeError('port must be 0..65535');
186
+ if (registry === null || typeof registry !== 'object' || typeof registry.get !== 'function'
187
+ || typeof registry.list !== 'function') throw new TypeError('registry required');
188
+ const clientsByProject = new Map();
189
+ const lastHeads = new Map();
190
+ const lastHeartbeats = new Map();
191
+ let eventId = 0;
192
+ let checking = false;
193
+ let closed = false;
194
+ const reconcileClients = () => {
195
+ const active = new Set(registry.list().map(({ projectId }) => projectId));
196
+ for (const [projectId, clients] of clientsByProject) {
197
+ if (active.has(projectId)) continue;
198
+ for (const client of clients) client.end();
199
+ clientsByProject.delete(projectId);
200
+ lastHeads.delete(projectId);
201
+ lastHeartbeats.delete(projectId);
202
+ }
203
+ };
204
+ const unsubscribe = typeof registry.subscribe === 'function'
205
+ ? registry.subscribe(reconcileClients) : () => {};
206
+ const handleRequest = async (request, response) => {
207
+ let requestPath = request.url ?? '/';
208
+ try {
209
+ const url = new URL(requestPath, `http://${LOOPBACK}`);
210
+ requestPath = url.pathname;
211
+ if (request.method !== 'GET') {
212
+ response.setHeader('allow', 'GET');
213
+ sendHttpError(response, 405, 'METHOD_NOT_ALLOWED', requestPath);
214
+ return;
215
+ }
216
+ if (url.pathname === '/__lattice/health') {
217
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8',
218
+ 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
219
+ // `version` is the package this process loaded at startup, not the one
220
+ // installed on disk. That difference is the whole point: it is how a
221
+ // caller learns the daemon is serving code that has been superseded.
222
+ response.end(`${JSON.stringify({ schema: 'lattice.todo_dashboard_health.v1', pid: process.pid,
223
+ port: actualPort, project_ids: registry.list().map(({ projectId }) => projectId),
224
+ version: TODO_DASHBOARD_CODE_VERSION })}\n`);
225
+ return;
226
+ }
227
+ if (url.pathname === '/' || url.pathname === '/projects/') {
228
+ const projects = registry.list();
229
+ if (url.pathname === '/' && redirectSingleProject && projects.length === 1) {
230
+ response.writeHead(302, { location: projectPath(projects[0].projectId), 'cache-control': 'no-store' });
231
+ response.end();
232
+ return;
233
+ }
234
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8',
235
+ 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
236
+ response.end(dashboardHtml(projects));
237
+ return;
238
+ }
239
+ const match = /^\/projects\/([^/]+)\/(events)?$/u.exec(url.pathname);
240
+ if (match === null) {
241
+ sendNotFound(request, response, 'ROUTE_NOT_FOUND', url.pathname);
242
+ return;
243
+ }
244
+ let requestedId;
245
+ try { requestedId = decodeURIComponent(match[1]); } catch {
246
+ sendHttpError(response, 400, 'PROJECT_ID_INVALID', url.pathname);
247
+ return;
248
+ }
249
+ const project = registry.get(requestedId);
250
+ if (project === null) {
251
+ sendNotFound(request, response, 'PROJECT_NOT_FOUND', url.pathname);
252
+ return;
253
+ }
254
+ if (match[2] === 'events') {
255
+ response.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8',
256
+ 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff' });
257
+ if (!clientsByProject.has(project.projectId)) clientsByProject.set(project.projectId, new Set());
258
+ clientsByProject.get(project.projectId).add(response);
259
+ request.on('close', () => clientsByProject.get(project.projectId)?.delete(response));
260
+ try {
261
+ const head = await project.readHead();
262
+ lastHeads.set(project.projectId, head);
263
+ if (!lastHeartbeats.has(project.projectId)) lastHeartbeats.set(project.projectId, Date.now());
264
+ sendEvent(response, 'state', ++eventId, { head_digest: head });
265
+ } catch (error) {
266
+ sendEvent(response, 'lattice-error', ++eventId, { code: error?.code ?? 'STORE_READ_FAILED' });
267
+ clientsByProject.get(project.projectId)?.delete(response);
268
+ response.end();
269
+ }
270
+ return;
271
+ }
272
+ const rendered = await project.render({
273
+ projectId: project.projectId,
274
+ displayName: project.displayName,
275
+ });
276
+ lastHeads.set(project.projectId, rendered.head_digest);
277
+ // 外部ペイン設定は描画のたびにrender側が読み直す。差した/外した側は再起動を要さない。
278
+ const html = liveHtml(rendered.html, rendered.head_digest,
279
+ `${projectPath(project.projectId)}events`, rendered.external_pane ?? null);
280
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8',
281
+ 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
282
+ response.end(html);
283
+ } catch (error) {
284
+ finishRequestFailure(response, error?.code ?? 'GANTT_RENDER_FAILED', requestPath);
285
+ }
286
+ };
287
+ const server = createServer((request, response) => {
288
+ handleRequest(request, response).catch((error) => {
289
+ finishRequestFailure(response, error?.code ?? 'GANTT_REQUEST_FAILED', request.url ?? '/');
290
+ });
291
+ });
292
+ await new Promise((resolve, reject) => {
293
+ server.once('error', reject);
294
+ server.listen({ host: LOOPBACK, port }, resolve);
295
+ });
296
+ const timer = setInterval(async () => {
297
+ if (checking) return;
298
+ checking = true;
299
+ try {
300
+ reconcileClients();
301
+ for (const project of registry.list()) {
302
+ const clients = clientsByProject.get(project.projectId);
303
+ if (clients === undefined || clients.size === 0) continue;
304
+ try {
305
+ const head = await project.readHead();
306
+ if (lastHeads.get(project.projectId) !== head) {
307
+ lastHeads.set(project.projectId, head);
308
+ for (const client of clients) sendEvent(client, 'state', ++eventId, { head_digest: head });
309
+ }
310
+ const now = Date.now();
311
+ if (now - (lastHeartbeats.get(project.projectId) ?? now) >= SSE_HEARTBEAT_MS) {
312
+ lastHeartbeats.set(project.projectId, now);
313
+ for (const client of clients) sendEvent(client, 'ping', ++eventId, { head_digest: head });
314
+ }
315
+ } catch (error) {
316
+ for (const client of clients) sendEvent(client, 'lattice-error', ++eventId,
317
+ { code: error?.code ?? 'STORE_READ_FAILED' });
318
+ }
319
+ }
320
+ } finally { checking = false; }
321
+ }, POLL_MS);
322
+ timer.unref();
323
+ const address = server.address();
324
+ const actualPort = typeof address === 'object' && address !== null ? address.port : port;
325
+ const close = async () => {
326
+ if (closed) return;
327
+ closed = true;
328
+ clearInterval(timer);
329
+ unsubscribe();
330
+ for (const clients of clientsByProject.values()) for (const client of clients) client.end();
331
+ clientsByProject.clear();
332
+ await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
333
+ };
334
+ return Object.freeze({
335
+ host: LOOPBACK,
336
+ port: actualPort,
337
+ url: `http://${LOOPBACK}:${actualPort}/`,
338
+ projectsUrl: `http://${LOOPBACK}:${actualPort}/projects/`,
339
+ registry,
340
+ close,
341
+ });
342
+ }
343
+
344
+ export async function startTodoGanttLiveServer({ projectId, displayName = projectId, port = 0, render, readHead }) {
345
+ const registry = createTodoGanttProjectRegistry([{ projectId, displayName, render, readHead }]);
346
+ const dashboard = await startTodoGanttDashboardServer({ registry, port, redirectSingleProject: true });
347
+ const path = projectPath(projectId);
348
+ return Object.freeze({
349
+ projectId,
350
+ displayName,
351
+ host: dashboard.host,
352
+ port: dashboard.port,
353
+ projectPath: path,
354
+ eventsPath: `${path}events`,
355
+ url: `http://${dashboard.host}:${dashboard.port}${path}`,
356
+ eventsUrl: `http://${dashboard.host}:${dashboard.port}${path}events`,
357
+ projectsUrl: dashboard.projectsUrl,
358
+ registry,
359
+ close: dashboard.close,
360
+ });
361
+ }