@infodb/p3 0.4.0 → 0.5.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 (208) hide show
  1. package/bin/p3.mjs +11 -5
  2. package/dist/web/assets/Outputs-C83ZDXvs.js +1 -0
  3. package/dist/web/assets/RequestStatus-GmiWYEcL.js +1 -0
  4. package/dist/web/assets/Tabs-CJn0Qy7W.js +1 -0
  5. package/dist/web/assets/TagInput-CtM8HM8Z.js +1 -0
  6. package/dist/web/assets/TaskDrawer-D5v36QoF.js +3 -0
  7. package/dist/web/assets/_requestId-BHUqLO-j.js +1 -0
  8. package/dist/web/assets/_requestId-DxwxbXY2.js +30 -0
  9. package/dist/web/assets/{ui-DdOGYj9z.js → appCtx-B-VRVOyv.js} +1 -1
  10. package/dist/web/assets/board-DAaVR04x.js +1 -0
  11. package/dist/web/assets/done-CaqB_qTH.js +1 -0
  12. package/dist/web/assets/index-BF1xMdJo.css +2 -0
  13. package/dist/web/assets/index-BQYvKpjF.js +12 -0
  14. package/dist/web/assets/new-DLVnRvrB.js +1 -0
  15. package/dist/web/assets/{preflightInput-DMxqnvF8.js → preflightInput-BAeEJYUK.js} +1 -1
  16. package/dist/web/assets/preload-helper-B74h5i3O.js +1 -0
  17. package/dist/web/assets/progressTree-wp9mH4VF.js +1 -0
  18. package/dist/web/assets/release-notes-MTLcOcvZ.js +3 -0
  19. package/dist/web/assets/requestData-D-HXu-cy.js +1 -0
  20. package/dist/web/assets/routes-CI4Qfkjs.js +3 -0
  21. package/dist/web/assets/settings-CJMNgzi6.js +1 -0
  22. package/dist/web/index.html +4 -4
  23. package/docs/architecture.md +220 -3
  24. package/docs/development.md +16 -9
  25. package/docs/how-to-use.md +72 -7
  26. package/docs/installation.md +8 -6
  27. package/docs/publishing.md +4 -2
  28. package/lib/cli/args.js +172 -0
  29. package/lib/cli/chatgpt.js +70 -0
  30. package/lib/cli/codex.js +30 -0
  31. package/lib/cli/format.js +9 -0
  32. package/{src/cli/help.ts → lib/cli/help.js} +8 -8
  33. package/lib/cli/main.js +326 -0
  34. package/lib/cli/output.js +110 -0
  35. package/lib/cli/preflightCommands.js +301 -0
  36. package/lib/cli/project.js +649 -0
  37. package/lib/cli/readOnly.js +36 -0
  38. package/lib/cli/releaseNotesCommands.js +197 -0
  39. package/lib/cli/render.js +58 -0
  40. package/lib/cli/requestCommands.js +180 -0
  41. package/lib/cli/showView.js +100 -0
  42. package/lib/cli/taskCommands.js +152 -0
  43. package/lib/cli/userConfig.js +64 -0
  44. package/{src/core/chatgpt.ts → lib/core/chatgpt.js} +10 -16
  45. package/lib/core/context.js +41 -0
  46. package/lib/core/hierarchy.js +128 -0
  47. package/lib/core/machineSettings.js +146 -0
  48. package/lib/core/machineSettingsEdit.js +148 -0
  49. package/lib/core/ops.js +120 -0
  50. package/lib/core/preflight/carryover.js +105 -0
  51. package/lib/core/preflight/codexEngine.js +687 -0
  52. package/lib/core/preflight/codexImage.js +61 -0
  53. package/lib/core/preflight/diagnose.js +95 -0
  54. package/lib/core/preflight/engine.js +58 -0
  55. package/lib/core/preflight/input.js +83 -0
  56. package/lib/core/preflight/launch.js +68 -0
  57. package/lib/core/preflight/mockEngine.js +175 -0
  58. package/lib/core/preflight/render.js +304 -0
  59. package/lib/core/preflight/service.js +868 -0
  60. package/lib/core/preflight/split.js +83 -0
  61. package/lib/core/preflight/uiMaterials.js +281 -0
  62. package/lib/core/preflight/uiRender.js +89 -0
  63. package/lib/core/preflight/wireframe.js +63 -0
  64. package/lib/core/preflight/xlsx.js +324 -0
  65. package/lib/core/projectRegistry.js +207 -0
  66. package/lib/core/redact.js +28 -0
  67. package/lib/core/releaseNotes/completeRequests.js +106 -0
  68. package/lib/core/releaseNotes/generate.js +266 -0
  69. package/lib/core/releaseNotes/material.js +141 -0
  70. package/lib/core/releaseNotes/mockSummarizer.js +26 -0
  71. package/lib/core/releaseNotes/service.js +83 -0
  72. package/lib/core/releaseNotes/store.js +209 -0
  73. package/lib/core/repoAdmin.js +82 -0
  74. package/lib/core/repoRefs.js +72 -0
  75. package/lib/core/requestOps.js +154 -0
  76. package/lib/core/requestStatus.js +171 -0
  77. package/lib/core/store/attachments.js +242 -0
  78. package/lib/core/store/collection.js +254 -0
  79. package/lib/core/store/frontmatter.js +18 -0
  80. package/lib/core/store/fsutil.js +84 -0
  81. package/lib/core/store/locate.js +162 -0
  82. package/lib/core/store/normalize.js +150 -0
  83. package/lib/core/store/noteStore.js +59 -0
  84. package/lib/core/store/preflightStore.js +161 -0
  85. package/lib/core/store/projectFile.js +99 -0
  86. package/lib/core/store/workspace.js +320 -0
  87. package/lib/core/supersede.js +69 -0
  88. package/lib/core/userConfig.js +158 -0
  89. package/{src/core/userTheme.ts → lib/core/userTheme.js} +11 -13
  90. package/lib/core/workTargets.js +106 -0
  91. package/lib/server/api/chatgptRoutes.js +46 -0
  92. package/{src/server/api/local.ts → lib/server/api/local.js} +23 -22
  93. package/lib/server/api/manifest.js +140 -0
  94. package/lib/server/api/projectsRoutes.js +82 -0
  95. package/lib/server/api/releaseNoteRoutes.js +88 -0
  96. package/lib/server/api/repoRoutes.js +67 -0
  97. package/lib/server/api/routes.js +404 -0
  98. package/lib/server/api/userThemeRoutes.js +60 -0
  99. package/lib/server/server.js +85 -0
  100. package/lib/shared/dates.js +10 -0
  101. package/{src/shared/directTask.ts → lib/shared/directTask.js} +3 -11
  102. package/lib/shared/hierarchy.js +120 -0
  103. package/lib/shared/milestoneOrder.js +45 -0
  104. package/lib/shared/preflightInput.js +19 -0
  105. package/lib/shared/refs.js +44 -0
  106. package/lib/shared/repos.js +69 -0
  107. package/lib/shared/scopeView.js +39 -0
  108. package/{src/shared/tags.ts → lib/shared/tags.js} +9 -14
  109. package/lib/shared/types.js +74 -0
  110. package/lib/shared/workTarget.js +31 -0
  111. package/package.json +4 -7
  112. package/skills/p3/SKILL.md +10 -0
  113. package/dist/web/assets/Outputs-5Hby-S5Q.js +0 -1
  114. package/dist/web/assets/RequestStatus-CTkGjT02.js +0 -1
  115. package/dist/web/assets/TagInput-Rj3PNOAF.js +0 -1
  116. package/dist/web/assets/TaskDrawer-DtPhiYxP.js +0 -3
  117. package/dist/web/assets/_requestId-CGvAfIkB.js +0 -30
  118. package/dist/web/assets/_requestId-DxfYhgAq.js +0 -1
  119. package/dist/web/assets/board-wt47lfrE.js +0 -1
  120. package/dist/web/assets/done-C9Ct7ssb.js +0 -1
  121. package/dist/web/assets/index-BTFL2rpp.js +0 -12
  122. package/dist/web/assets/index-DAyBsvua.css +0 -2
  123. package/dist/web/assets/new-e4ID2vQV.js +0 -1
  124. package/dist/web/assets/preload-helper-DhIyFaOW.js +0 -1
  125. package/dist/web/assets/release-notes-CQ0d2r0k.js +0 -3
  126. package/dist/web/assets/requestData-BDZqyl35.js +0 -1
  127. package/dist/web/assets/routes-Bipv3lwJ.js +0 -2
  128. package/dist/web/assets/settings-Dwh8fj6p.js +0 -1
  129. package/src/cli/args.ts +0 -186
  130. package/src/cli/chatgpt.ts +0 -74
  131. package/src/cli/codex.ts +0 -28
  132. package/src/cli/format.ts +0 -9
  133. package/src/cli/main.ts +0 -337
  134. package/src/cli/output.ts +0 -117
  135. package/src/cli/preflightCommands.ts +0 -245
  136. package/src/cli/project.ts +0 -675
  137. package/src/cli/readOnly.ts +0 -36
  138. package/src/cli/releaseNotesCommands.ts +0 -198
  139. package/src/cli/render.ts +0 -60
  140. package/src/cli/requestCommands.ts +0 -172
  141. package/src/cli/showView.ts +0 -110
  142. package/src/cli/taskCommands.ts +0 -167
  143. package/src/cli/userConfig.ts +0 -58
  144. package/src/core/context.ts +0 -58
  145. package/src/core/machineSettings.ts +0 -207
  146. package/src/core/machineSettingsEdit.ts +0 -156
  147. package/src/core/ops.ts +0 -114
  148. package/src/core/preflight/carryover.ts +0 -133
  149. package/src/core/preflight/codexEngine.ts +0 -703
  150. package/src/core/preflight/codexImage.ts +0 -98
  151. package/src/core/preflight/diagnose.ts +0 -124
  152. package/src/core/preflight/engine.ts +0 -92
  153. package/src/core/preflight/input.ts +0 -65
  154. package/src/core/preflight/launch.ts +0 -86
  155. package/src/core/preflight/mockEngine.ts +0 -145
  156. package/src/core/preflight/render.ts +0 -339
  157. package/src/core/preflight/service.ts +0 -707
  158. package/src/core/preflight/uiMaterials.ts +0 -272
  159. package/src/core/preflight/uiRender.ts +0 -84
  160. package/src/core/preflight/wireframe.ts +0 -69
  161. package/src/core/preflight/xlsx.ts +0 -328
  162. package/src/core/projectRegistry.ts +0 -264
  163. package/src/core/redact.ts +0 -31
  164. package/src/core/releaseNotes/completeRequests.ts +0 -102
  165. package/src/core/releaseNotes/generate.ts +0 -283
  166. package/src/core/releaseNotes/material.ts +0 -114
  167. package/src/core/releaseNotes/mockSummarizer.ts +0 -28
  168. package/src/core/releaseNotes/service.ts +0 -110
  169. package/src/core/releaseNotes/store.ts +0 -216
  170. package/src/core/repoAdmin.ts +0 -81
  171. package/src/core/repoRefs.ts +0 -90
  172. package/src/core/requestOps.ts +0 -140
  173. package/src/core/requestStatus.ts +0 -58
  174. package/src/core/store/attachments.ts +0 -228
  175. package/src/core/store/collection.ts +0 -282
  176. package/src/core/store/frontmatter.ts +0 -22
  177. package/src/core/store/fsutil.ts +0 -90
  178. package/src/core/store/locate.ts +0 -181
  179. package/src/core/store/normalize.ts +0 -155
  180. package/src/core/store/noteStore.ts +0 -56
  181. package/src/core/store/preflightStore.ts +0 -136
  182. package/src/core/store/projectFile.ts +0 -101
  183. package/src/core/store/workspace.ts +0 -328
  184. package/src/core/supersede.ts +0 -74
  185. package/src/core/userConfig.ts +0 -205
  186. package/src/core/workTargets.ts +0 -120
  187. package/src/server/api/chatgptRoutes.ts +0 -49
  188. package/src/server/api/manifest.ts +0 -135
  189. package/src/server/api/projectsRoutes.ts +0 -89
  190. package/src/server/api/releaseNoteRoutes.ts +0 -89
  191. package/src/server/api/repoRoutes.ts +0 -67
  192. package/src/server/api/routes.ts +0 -382
  193. package/src/server/api/userThemeRoutes.ts +0 -62
  194. package/src/server/server.ts +0 -108
  195. package/src/shared/dates.ts +0 -12
  196. package/src/shared/milestoneOrder.ts +0 -44
  197. package/src/shared/preflightInput.ts +0 -27
  198. package/src/shared/refs.ts +0 -55
  199. package/src/shared/repos.ts +0 -113
  200. package/src/shared/scopeView.ts +0 -48
  201. package/src/shared/types.ts +0 -730
  202. package/src/shared/workTarget.ts +0 -44
  203. /package/{src → lib}/core/preflight/launcher.mjs +0 -0
  204. /package/{src → lib}/core/preflight/mock-ui.html +0 -0
  205. /package/{src → lib}/core/preflight/mock-ui.png +0 -0
  206. /package/{src → lib}/core/preflight/render-image/Dockerfile +0 -0
  207. /package/{src → lib}/core/preflight/render-image/fonts-ja.conf +0 -0
  208. /package/{src → lib}/core/preflight/render-image/render.mjs +0 -0
@@ -1,328 +0,0 @@
1
- import { inflateRawSync } from "node:zlib";
2
- import { posix } from "node:path";
3
- import { imageInfo, UI_LIMITS } from "./uiMaterials.ts";
4
-
5
- /**
6
- * xlsx から、セルの文字・保存済みの値と、標準の埋め込み画像(PNG / JPEG)を取り出す(補助の仕様書として Preflight に渡す)。
7
- *
8
- * - 数式は計算しない。保存済みの値があればそれを、無ければ「未確認」とする
9
- * - 外部のブックや URL は取りに行かない。マクロ・OLE は動かさない(見つけたら未対応として記録する)
10
- * - XML の DOCTYPE(外部実体)は断る。実体は XML の決まった5つと数値の参照だけを戻す
11
- * - 図形・グラフ・リンクの画像・EMF などは描かない(見つけたら未対応として記録する)。Excel の見た目は再現しない
12
- * - ZIP の展開後の大きさ・項目数・セル数・画像の数と大きさ・処理時間に上限があり、超えたら打ち切りを記録する
13
- */
14
- export const XLSX_LIMITS = {
15
- entries: 10_000,
16
- /** 1つの項目の展開後の大きさ */
17
- entryBytes: 30 * 1024 * 1024,
18
- /** 展開した合計 */
19
- totalBytes: 200 * 1024 * 1024,
20
- cells: 50_000,
21
- /** 取り出した文字の合計 */
22
- textChars: 1_000_000,
23
- images: 20,
24
- timeMs: 10_000,
25
- } as const;
26
-
27
- export class XlsxError extends Error {}
28
-
29
- export interface XlsxImage {
30
- /** シートの名前 */
31
- sheet: string;
32
- /** 置いてある位置(左上のセル。例: B3) */
33
- anchor: string;
34
- format: "png" | "jpeg";
35
- width: number;
36
- height: number;
37
- data: Buffer;
38
- }
39
-
40
- export interface XlsxExtract {
41
- /** 取り出した内容(Markdown) */
42
- text: string;
43
- sheets: number;
44
- cells: number;
45
- images: XlsxImage[];
46
- /** 値が保存されていない数式など、確かめられなかったセルの数 */
47
- unknownCells: number;
48
- /** 打ち切ったもの */
49
- truncated: string[];
50
- /** 見つけたが扱わないもの(図形・グラフ・OLE・リンクの画像・外部参照など) */
51
- unsupported: string[];
52
- }
53
-
54
- interface Entry {
55
- name: string;
56
- method: number;
57
- compressed: number;
58
- uncompressed: number;
59
- offset: number;
60
- }
61
-
62
- function readEntries(buf: Buffer): Map<string, Entry> {
63
- let eocd = -1;
64
- for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65_557); i--) {
65
- if (buf.readUInt32LE(i) === 0x06054b50) {
66
- eocd = i;
67
- break;
68
- }
69
- }
70
- if (eocd < 0) throw new XlsxError("ZIP の終わりが見つかりません");
71
- const count = buf.readUInt16LE(eocd + 10);
72
- if (count > XLSX_LIMITS.entries) throw new XlsxError(`中のファイルが多すぎます(${count})`);
73
- let at = buf.readUInt32LE(eocd + 16);
74
- const map = new Map<string, Entry>();
75
- for (let i = 0; i < count; i++) {
76
- if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) throw new XlsxError("ZIP の一覧が壊れています");
77
- const nameLen = buf.readUInt16LE(at + 28);
78
- const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
79
- map.set(name, {
80
- name,
81
- method: buf.readUInt16LE(at + 10),
82
- compressed: buf.readUInt32LE(at + 20),
83
- uncompressed: buf.readUInt32LE(at + 24),
84
- offset: buf.readUInt32LE(at + 42),
85
- });
86
- at += 46 + nameLen + buf.readUInt16LE(at + 30) + buf.readUInt16LE(at + 32);
87
- }
88
- return map;
89
- }
90
-
91
- class Zip {
92
- private entries: Map<string, Entry>;
93
- private used = 0;
94
- constructor(private buf: Buffer) {
95
- this.entries = readEntries(buf);
96
- }
97
- has(name: string) {
98
- return this.entries.has(name);
99
- }
100
- names() {
101
- return [...this.entries.keys()];
102
- }
103
- read(name: string): Buffer | undefined {
104
- const e = this.entries.get(name);
105
- if (!e) return undefined;
106
- const at = e.offset;
107
- if (at + 30 > this.buf.length || this.buf.readUInt32LE(at) !== 0x04034b50) throw new XlsxError(`${name}: ZIP の項目が壊れています`);
108
- const start = at + 30 + this.buf.readUInt16LE(at + 26) + this.buf.readUInt16LE(at + 28);
109
- const raw = this.buf.subarray(start, start + e.compressed);
110
- const limit = Math.min(XLSX_LIMITS.entryBytes, XLSX_LIMITS.totalBytes - this.used);
111
- let out: Buffer;
112
- if (e.method === 0) out = Buffer.from(raw);
113
- else if (e.method === 8) {
114
- try {
115
- out = inflateRawSync(raw, { maxOutputLength: limit + 1 });
116
- } catch (err) {
117
- if ((err as NodeJS.ErrnoException).code === "ERR_BUFFER_TOO_LARGE" || /too large|maxOutputLength/i.test((err as Error).message)) {
118
- throw new XlsxError(`${name}: 展開すると大きすぎます`);
119
- }
120
- throw new XlsxError(`${name}: 展開できません`);
121
- }
122
- } else throw new XlsxError(`${name}: 対応していない圧縮方式です(${e.method})`);
123
- if (out.length > limit) throw new XlsxError(`${name}: 展開すると大きすぎます`);
124
- this.used += out.length;
125
- return out;
126
- }
127
- text(name: string): string | undefined {
128
- const b = this.read(name);
129
- if (!b) return undefined;
130
- const s = b.toString("utf8");
131
- // 外部実体を使わせない(DOCTYPE があれば読まない)
132
- if (/<!DOCTYPE/i.test(s)) throw new XlsxError(`${name}: DOCTYPE を含む XML は読みません`);
133
- // 要素の名前空間の接頭辞(xdr: a: x: など。書いたソフトで違う)を外す。属性(r:id など)はそのまま
134
- return s.replace(/<(\/?)[A-Za-z_][\w.-]*:(?=[A-Za-z_])/g, "<$1");
135
- }
136
- }
137
-
138
- /** XML の文字を戻す(決まった5つと数値の参照だけ) */
139
- export function unescapeXml(s: string): string {
140
- return s.replace(/&(#x[0-9a-f]+|#\d+|lt|gt|amp|quot|apos);/gi, (_, e: string) => {
141
- const k = e.toLowerCase();
142
- if (k === "lt") return "<";
143
- if (k === "gt") return ">";
144
- if (k === "amp") return "&";
145
- if (k === "quot") return '"';
146
- if (k === "apos") return "'";
147
- const n = k.startsWith("#x") ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10);
148
- return Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : "";
149
- });
150
- }
151
-
152
- const attr = (tag: string, name: string) => {
153
- const m = new RegExp(`\\s${name.replace(":", "\\:")}\\s*=\\s*("([^"]*)"|'([^']*)')`).exec(tag);
154
- return m ? unescapeXml(m[2] ?? m[3] ?? "") : undefined;
155
- };
156
-
157
- /** <t> の文字を全部つなぐ(リッチテキストの断片を含む。ふりがな rPh は除く) */
158
- const texts = (xml: string) =>
159
- [...xml.replace(/<rPh\b[\s\S]*?<\/rPh>/g, "").matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>|<t(?:\s[^>]*)?\/>/g)].map((m) => unescapeXml(m[1] ?? "")).join("");
160
-
161
- /** 関係(rels): Id → { target(ZIP の中のパス), type, external } */
162
- function rels(zip: Zip, base: string): Map<string, { target: string; type: string; external: boolean }> {
163
- const file = posix.join(posix.dirname(base), "_rels", `${posix.basename(base)}.rels`);
164
- const xml = zip.text(file);
165
- const map = new Map<string, { target: string; type: string; external: boolean }>();
166
- if (!xml) return map;
167
- for (const m of xml.matchAll(/<Relationship\b[^>]*>/g)) {
168
- const id = attr(m[0], "Id");
169
- const target = attr(m[0], "Target") ?? "";
170
- const external = attr(m[0], "TargetMode") === "External";
171
- if (!id) continue;
172
- const resolved = external ? target : target.startsWith("/") ? target.slice(1) : posix.normalize(posix.join(posix.dirname(base), target));
173
- map.set(id, { target: resolved, type: attr(m[0], "Type") ?? "", external });
174
- }
175
- return map;
176
- }
177
-
178
- const colName = (n: number) => {
179
- let s = "";
180
- for (let x = n + 1; x > 0; x = Math.floor((x - 1) / 26)) s = String.fromCharCode(65 + ((x - 1) % 26)) + s;
181
- return s;
182
- };
183
-
184
- const md = (s: string) => s.replace(/\r\n?/g, "\n").replace(/\n/g, " ⏎ ").trim();
185
-
186
- /** xlsx(固定した原本)から取り出す。ブックとして読めなければ XlsxError */
187
- export function extractXlsx(data: Buffer, title: string, now: () => number = Date.now): XlsxExtract {
188
- const started = now();
189
- const zip = new Zip(data);
190
- if (!zip.has("xl/workbook.xml")) throw new XlsxError("xl/workbook.xml がありません(xlsx のブックではありません)");
191
- const truncated: string[] = [];
192
- const unsupported = new Set<string>();
193
- const out: string[] = [];
194
- const images: XlsxImage[] = [];
195
- let cells = 0;
196
- let unknownCells = 0;
197
- let chars = 0;
198
- const timeUp = () => now() - started > XLSX_LIMITS.timeMs;
199
-
200
- if (zip.names().some((n) => /vbaProject\.bin$/i.test(n))) unsupported.add("マクロ(実行しません)");
201
- if (zip.names().some((n) => n.startsWith("xl/embeddings/"))) unsupported.add("埋め込みのオブジェクト(OLE。開きません)");
202
- if (zip.names().some((n) => n.startsWith("xl/externalLinks/"))) unsupported.add("外部のブックへの参照(取りに行きません)");
203
- if (zip.names().some((n) => n.startsWith("xl/charts/"))) unsupported.add("グラフ(描きません)");
204
-
205
- const shared: string[] = [];
206
- const ss = zip.text("xl/sharedStrings.xml");
207
- if (ss) for (const m of ss.matchAll(/<si>([\s\S]*?)<\/si>|<si\/>/g)) shared.push(texts(m[1] ?? ""));
208
-
209
- const wbXml = zip.text("xl/workbook.xml")!;
210
- const wbRels = rels(zip, "xl/workbook.xml");
211
- const sheets = [...wbXml.matchAll(/<sheet\b[^>]*>/g)].map((m) => ({ name: attr(m[0], "name") ?? "?", rid: attr(m[0], "r:id") ?? "", state: attr(m[0], "state") }));
212
-
213
- let done = 0;
214
- for (const sheet of sheets) {
215
- if (timeUp()) {
216
- truncated.push(`時間の上限(${XLSX_LIMITS.timeMs / 1000} 秒)で、シート「${sheet.name}」から先を読んでいません`);
217
- break;
218
- }
219
- const rel = wbRels.get(sheet.rid);
220
- if (!rel || rel.external || !rel.target.startsWith("xl/")) {
221
- out.push(`## シート「${sheet.name}」\n(読めません: シートの場所が分かりません)`);
222
- continue;
223
- }
224
- const xml = zip.text(rel.target);
225
- if (!xml) {
226
- out.push(`## シート「${sheet.name}」\n(読めません: ${rel.target} がありません)`);
227
- continue;
228
- }
229
- done++;
230
- const lines: string[] = [`## シート「${sheet.name}」${sheet.state === "hidden" || sheet.state === "veryHidden" ? "(非表示のシート)" : ""}`];
231
- const merges = [...xml.matchAll(/<mergeCell\b[^>]*>/g)].map((m) => attr(m[0], "ref")).filter(Boolean);
232
- if (merges.length) lines.push(`結合セル: ${merges.slice(0, 200).join(", ")}${merges.length > 200 ? ` ほか ${merges.length - 200}` : ""}`);
233
- let stopped = false;
234
- for (const m of xml.matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
235
- if (cells >= XLSX_LIMITS.cells || chars >= XLSX_LIMITS.textChars || timeUp()) {
236
- truncated.push(`${cells >= XLSX_LIMITS.cells ? `セル数の上限(${XLSX_LIMITS.cells})` : chars >= XLSX_LIMITS.textChars ? "文字数の上限" : "時間の上限"}で、シート「${sheet.name}」の途中から先を読んでいません`);
237
- stopped = true;
238
- break;
239
- }
240
- const head = `<c${m[1]}>`;
241
- const body = m[2] ?? "";
242
- const ref = attr(head, "r") ?? "?";
243
- const t = attr(head, "t");
244
- const f = /<f\b[^>]*>([\s\S]*?)<\/f>|<f\b[^>]*\/>/.exec(body);
245
- const v = /<v>([\s\S]*?)<\/v>/.exec(body)?.[1];
246
- let value: string | undefined;
247
- if (t === "s") value = v !== undefined ? shared[Number(v)] : undefined;
248
- else if (t === "inlineStr") value = texts(/<is>([\s\S]*?)<\/is>/.exec(body)?.[1] ?? "");
249
- else if (t === "b") value = v === undefined ? undefined : v === "1" ? "TRUE" : "FALSE";
250
- else if (t === "e") value = v === undefined ? undefined : `エラー ${unescapeXml(v)}`;
251
- else value = v === undefined ? undefined : unescapeXml(v);
252
- if (f) {
253
- const formula = f[1] ? unescapeXml(f[1]) : "(共有の数式)";
254
- if (value === undefined || value === "") {
255
- unknownCells++;
256
- lines.push(`- ${ref}: =${md(formula)} → (値が保存されていません。未確認)`);
257
- } else lines.push(`- ${ref}: =${md(formula)} → ${md(value)}(保存済みの値)`);
258
- } else if (value !== undefined && value !== "") lines.push(`- ${ref}: ${md(value)}`);
259
- else continue;
260
- cells++;
261
- chars += lines.at(-1)!.length;
262
- }
263
- // 標準の図(drawing)の画像
264
- const sheetRels = rels(zip, rel.target);
265
- for (const r of sheetRels.values()) {
266
- if (r.external) unsupported.add(`シート「${sheet.name}」の外部への参照(取りに行きません)`);
267
- if (r.type.endsWith("/oleObject")) unsupported.add(`シート「${sheet.name}」の埋め込みのオブジェクト(OLE)`);
268
- }
269
- const drawing = [...sheetRels.values()].find((r) => r.type.endsWith("/drawing") && !r.external);
270
- if (drawing && !stopped) lines.push(...readDrawing(zip, drawing.target, sheet.name, images, truncated, unsupported));
271
- out.push(lines.join("\n"));
272
- }
273
-
274
- const head = [
275
- `# ${title} から取り出した内容`,
276
- `範囲: シート ${done}/${sheets.length}・セル ${cells}・画像 ${images.length}${unknownCells ? `・値が保存されていない数式 ${unknownCells}(未確認)` : ""}`,
277
- "セルの文字と保存済みの値だけです。数式は計算していません。書式・図形・グラフなど見た目は再現していません。",
278
- ...(truncated.length ? ["打ち切り:", ...truncated.map((x) => `- ${x}`)] : []),
279
- ...(unsupported.size ? ["扱っていないもの(中身は未確認):", ...[...unsupported].map((x) => `- ${x}`)] : []),
280
- ];
281
- return { text: `${[head.join("\n"), ...out].join("\n\n")}\n`, sheets: done, cells, images, unknownCells, truncated, unsupported: [...unsupported] };
282
- }
283
-
284
- function readDrawing(zip: Zip, path: string, sheet: string, images: XlsxImage[], truncated: string[], unsupported: Set<string>): string[] {
285
- const xml = zip.text(path);
286
- if (!xml) return [];
287
- const dRels = rels(zip, path);
288
- const lines: string[] = [];
289
- for (const m of xml.matchAll(/<(twoCellAnchor|oneCellAnchor|absoluteAnchor)\b[\s\S]*?<\/\1>/g)) {
290
- const a = m[0];
291
- const col = /<from>[\s\S]*?<col>(\d+)<\/col>[\s\S]*?<row>(\d+)<\/row>/.exec(a);
292
- const anchor = col ? `${colName(Number(col[1]))}${Number(col[2]) + 1}` : "(位置不明)";
293
- if (/<pic\b/.test(a)) {
294
- const embed = /<blip\b[^>]*r:embed\s*=\s*"([^"]+)"/.exec(a)?.[1];
295
- const link = /<blip\b[^>]*r:link\s*=\s*"([^"]+)"/.exec(a)?.[1];
296
- if (link && !embed) {
297
- unsupported.add(`シート「${sheet}」${anchor} のリンクの画像(取りに行きません)`);
298
- continue;
299
- }
300
- const r = embed ? dRels.get(embed) : undefined;
301
- if (!r || r.external) {
302
- unsupported.add(`シート「${sheet}」${anchor} の画像(場所が分かりません)`);
303
- continue;
304
- }
305
- if (images.length >= XLSX_LIMITS.images) {
306
- truncated.push(`画像の数の上限(${XLSX_LIMITS.images})で、シート「${sheet}」${anchor} から先の画像を取り出していません`);
307
- break;
308
- }
309
- const data = zip.read(r.target);
310
- const info = data && imageInfo(data);
311
- if (!data || !info) {
312
- unsupported.add(`シート「${sheet}」${anchor} の画像(${posix.extname(r.target).slice(1) || "形式不明"}。PNG / JPEG ではありません)`);
313
- continue;
314
- }
315
- if (data.length > UI_LIMITS.bytes || info.width > UI_LIMITS.width || info.height > UI_LIMITS.height) {
316
- unsupported.add(`シート「${sheet}」${anchor} の画像(大きすぎます)`);
317
- continue;
318
- }
319
- images.push({ sheet, anchor, ...info, data });
320
- lines.push(`- 画像 ${images.length}: ${anchor} に置かれた ${info.format.toUpperCase()}(${info.width}x${info.height})`);
321
- } else if (/<graphicFrame\b/.test(a)) unsupported.add(`シート「${sheet}」${anchor} のグラフ・図表(描きません)`);
322
- else if (/<(sp|grpSp|cxnSp)\b/.test(a)) {
323
- const label = texts(a);
324
- unsupported.add(`シート「${sheet}」${anchor} の図形(描きません${label ? `。中の文字: ${md(label).slice(0, 80)}` : ""})`);
325
- }
326
- }
327
- return lines;
328
- }
@@ -1,264 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { realpath } from "node:fs/promises";
3
- import type { ChatGptAccount } from "./chatgpt.ts";
4
- import { openProject, type P3Context } from "./context.ts";
5
- import type { SettingsSource } from "./machineSettings.ts";
6
- import { inspectUserProjects, PROJECT_NAME, userConfigPath, type InvalidProjectEntry, type UserProject } from "./userConfig.ts";
7
-
8
- /**
9
- * プロジェクトを跨ぐ serve(p3 serve --all-projects)が扱うプロジェクト。個人設定に登録した名前だけを対象にし、
10
- * 任意のパスは開かない。
11
- *
12
- * - 一覧は refresh(明示の再取得)で個人設定から読み直す。壊れた・読めない個人設定は登録0件と区別して configError に、
13
- * 形の違う登録は invalid に理由を付けて出し、ほかの登録は使えるようにする
14
- * - 開くのは使うとき(open)。同時に開こうとしたら1回にまとめ、失敗したら覚えずに次の open でやり直す(直したら戻る)
15
- * - 同じデータのフォルダ(実体のパス)を複数の名前で登録していたら、どれも開かない(Preflight・生成を二重に動かさない)
16
- * - 登録世代(generation): 読み直したときに登録が無くなっていた・データのフォルダが変わっていたら変わる(読み直すまでの間に
17
- * 外して同じフォルダで付け直したものは同じ登録。書く先は同じ)。画面は変える操作に世代を添え、違えば断る(古い画面の保存を
18
- * 新しい登録先へ流さない)。参照先のパスだけの変更は今の文脈に反映して世代は変えない
19
- * - 登録から外れた文脈には新しい要求を渡さず、実行中の Preflight・生成が終わるのを待ってから閉じる(取り消さない)
20
- */
21
-
22
- export type RegistryErrorCode = "unknown" | "changed" | "duplicate" | "unavailable";
23
-
24
- /** 開けない(unknown: 登録に無い / changed: 登録世代が違う / duplicate: 同じデータを複数の名前で登録 / unavailable: 開けない) */
25
- export class RegistryError extends Error {
26
- constructor(
27
- readonly code: RegistryErrorCode,
28
- message: string,
29
- ) {
30
- super(message);
31
- }
32
- }
33
-
34
- export interface ProjectListItem {
35
- name: string;
36
- generation: string;
37
- /** ok: 開ける(開いていなくてもよい) / error: 開けない(理由は error) */
38
- state: "ok" | "error";
39
- error?: string;
40
- /** 文脈を開いている */
41
- open: boolean;
42
- }
43
-
44
- export interface ProjectListing {
45
- projects: ProjectListItem[];
46
- invalid: InvalidProjectEntry[];
47
- /** 個人設定を読めない・壊れている(登録0件とは別) */
48
- configError?: string;
49
- }
50
-
51
- interface Entry {
52
- name: string;
53
- dir: string;
54
- repos: Record<string, string>;
55
- generation: string;
56
- /** 同じデータを別の名前でも登録している */
57
- duplicate?: string;
58
- ctx?: Promise<P3Context>;
59
- /** 直前に開けなかった理由(次の open でやり直す) */
60
- error?: string;
61
- }
62
-
63
- export interface RegistryOptions {
64
- settings: SettingsSource;
65
- /** サインインの待ち受け(全プロジェクトで1つ) */
66
- chatgpt: ChatGptAccount;
67
- configPath?: string;
68
- /** 開き方(テストで差し替える) */
69
- open?: typeof openProject;
70
- }
71
-
72
- export class ProjectRegistry {
73
- private entries = new Map<string, Entry>();
74
- private invalid: InvalidProjectEntry[] = [];
75
- private configError?: string;
76
- private counter = 0;
77
- private refreshing: Promise<ProjectListing> = Promise.resolve({ projects: [], invalid: [] });
78
- /** 登録から外れて、実行中の処理が終わるのを待っている文脈 */
79
- private retiring = new Set<Promise<void>>();
80
- private listeners = new Set<(kind: "projects" | "user" | "chatgpt") => void>();
81
- private closed = false;
82
-
83
- constructor(private opts: RegistryOptions) {}
84
-
85
- get chatgpt(): ChatGptAccount {
86
- return this.opts.chatgpt;
87
- }
88
-
89
- /** 個人設定から一覧を読み直す(同時に呼ばれたら順に) */
90
- refresh(): Promise<ProjectListing> {
91
- this.refreshing = this.refreshing.then(
92
- () => this.load(),
93
- () => this.load(),
94
- );
95
- return this.refreshing;
96
- }
97
-
98
- list(): ProjectListing {
99
- const projects = [...this.entries.values()]
100
- .sort((a, b) => a.name.localeCompare(b.name))
101
- .map((e): ProjectListItem => {
102
- const error = e.duplicate ?? e.error;
103
- return { name: e.name, generation: e.generation, state: error ? "error" : "ok", ...(error ? { error } : {}), open: !!e.ctx };
104
- });
105
- return { projects, invalid: this.invalid, ...(this.configError ? { configError: this.configError } : {}) };
106
- }
107
-
108
- /** 登録した名前の文脈(必要なら開く)。generation を渡したら、今の登録世代と同じときだけ */
109
- async open(name: string, generation?: string): Promise<P3Context> {
110
- if (this.closed) throw new RegistryError("unavailable", "serve を止めています");
111
- const e = PROJECT_NAME.test(name) ? this.entries.get(name) : undefined;
112
- if (!e) throw new RegistryError("unknown", `プロジェクト「${name}」は個人設定に登録されていません(p3 project ls で確かめ、画面の一覧を読み直してください)`);
113
- if (generation !== undefined && generation !== e.generation) {
114
- throw new RegistryError("changed", `プロジェクト「${name}」の登録が変わりました(外した・付け直した・データのフォルダを変えた)。一覧を読み直して選び直してください(入力は送っていません)`);
115
- }
116
- if (e.duplicate) throw new RegistryError("duplicate", e.duplicate);
117
- if (!e.ctx) {
118
- e.ctx = (this.opts.open ?? openProject)(e.dir, { repos: e.repos, settings: this.opts.settings, projectName: e.name, chatgpt: this.opts.chatgpt });
119
- e.ctx.then(
120
- (ctx) => {
121
- e.error = undefined;
122
- void ctx.ws.watch();
123
- // 開いている間に登録から外れた・変わった: 新しい要求には使わせず閉じる
124
- if (this.entries.get(name) !== e || this.closed) this.retire(ctx);
125
- },
126
- (err: Error) => {
127
- // 覚えずに次の open でやり直す(フォルダを戻した・共有ドライブをつないだら使える)
128
- if (this.entries.get(name) === e) {
129
- e.ctx = undefined;
130
- e.error = err.message;
131
- }
132
- },
133
- );
134
- }
135
- try {
136
- const ctx = await e.ctx;
137
- if (this.entries.get(name) !== e) throw new RegistryError("changed", `プロジェクト「${name}」の登録が変わりました。一覧を読み直して選び直してください`);
138
- return ctx;
139
- } catch (err) {
140
- if (err instanceof RegistryError) throw err;
141
- throw new RegistryError("unavailable", `プロジェクト「${name}」を開けません: ${(err as Error).message}`);
142
- }
143
- }
144
-
145
- /** 開いている文脈(変更の知らせを全部へ流すため) */
146
- async openContexts(): Promise<P3Context[]> {
147
- const opened = await Promise.allSettled([...this.entries.values()].flatMap((e) => (e.ctx ? [e.ctx] : [])));
148
- return opened.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
149
- }
150
-
151
- /** プロジェクトに属さない変更(一覧・テーマ・ChatGPT の接続)を知らせる。開いている全プロジェクトの画面にも流す */
152
- notify(kind: "projects" | "user" | "chatgpt") {
153
- for (const l of this.listeners) l(kind);
154
- if (kind === "projects") return;
155
- void this.openContexts().then((all) => all.forEach((ctx) => ctx.ws.emit({ type: "changed", kind })));
156
- }
157
-
158
- on(listener: (kind: "projects" | "user" | "chatgpt") => void): () => void {
159
- this.listeners.add(listener);
160
- return () => this.listeners.delete(listener);
161
- }
162
-
163
- /**
164
- * 止める。新しい要求は断り、実行中の Preflight・生成を取り消して終わるまで待つ(timeoutMs まで)。監視を外す。
165
- * 待ちきれなかった数を返す
166
- */
167
- async close(opts: { timeoutMs?: number } = {}): Promise<{ pending: number }> {
168
- this.closed = true;
169
- const all = await this.openContexts();
170
- for (const e of this.entries.values()) e.ctx = undefined;
171
- const settle = Promise.all([
172
- ...all.map(async (ctx) => {
173
- await Promise.all([ctx.preflight.settle({ cancel: true }), ctx.releaseGenerator.settle({ cancel: true })]);
174
- ctx.ws.close();
175
- }),
176
- ...this.retiring,
177
- ]).then(() => false);
178
- const timedOut = await Promise.race([settle, new Promise<boolean>((r) => setTimeout(() => r(true), opts.timeoutMs ?? 10_000).unref())]);
179
- for (const ctx of all) ctx.ws.close();
180
- return { pending: timedOut ? all.reduce((n, c) => n + c.preflight.running() + c.releaseGenerator.running(), 0) : 0 };
181
- }
182
-
183
- private async load(): Promise<ProjectListing> {
184
- let projects: Record<string, UserProject>;
185
- try {
186
- const r = await inspectUserProjects(this.opts.configPath ?? userConfigPath());
187
- projects = r.projects;
188
- this.invalid = r.invalid;
189
- this.configError = undefined;
190
- } catch (e) {
191
- // 読めない・壊れている: 今の一覧と開いている文脈はそのまま(直して読み直せば戻る)
192
- this.configError = (e as Error).message;
193
- return this.list();
194
- }
195
- const before = this.list();
196
- for (const [name, e] of this.entries) {
197
- const next = projects[name];
198
- if (!next || next.dir !== e.dir) this.drop(name, e);
199
- }
200
- for (const [name, p] of Object.entries(projects)) {
201
- const cur = this.entries.get(name);
202
- if (cur) {
203
- // 参照先のパスだけの変更は今の文脈に反映する(次の Preflight から使う)
204
- if (JSON.stringify(cur.repos) !== JSON.stringify(p.repos)) {
205
- const old = cur.repos;
206
- cur.repos = { ...p.repos };
207
- void cur.ctx?.then((ctx) => {
208
- for (const k of Object.keys(old)) if (!(k in p.repos)) ctx.ws.setLocalRepo(k, null);
209
- for (const [k, v] of Object.entries(p.repos)) if (old[k] !== v) ctx.ws.setLocalRepo(k, v);
210
- }, () => undefined);
211
- }
212
- continue;
213
- }
214
- this.entries.set(name, { name, dir: p.dir, repos: { ...p.repos }, generation: this.nextGeneration(p.dir) });
215
- }
216
- await this.markDuplicates();
217
- const after = this.list();
218
- if (JSON.stringify(before) !== JSON.stringify(after)) this.notify("projects");
219
- return after;
220
- }
221
-
222
- /** 登録から外す。新しい要求には使わせず、実行中の処理が終わってから閉じる */
223
- private drop(name: string, e: Entry) {
224
- this.entries.delete(name);
225
- void e.ctx?.then((ctx) => this.retire(ctx), () => undefined);
226
- }
227
-
228
- private retire(ctx: P3Context) {
229
- const p = Promise.all([ctx.preflight.settle(), ctx.releaseGenerator.settle()]).then(() => ctx.ws.close());
230
- this.retiring.add(p);
231
- void p.finally(() => this.retiring.delete(p));
232
- }
233
-
234
- /** 同じ実体のフォルダを指す登録は、どれも開かない(どれを使うかは人が個人設定で決める) */
235
- private async markDuplicates() {
236
- const real = new Map<string, string[]>();
237
- for (const e of this.entries.values()) {
238
- const key = await realpath(e.dir).catch(() => e.dir);
239
- real.set(key, [...(real.get(key) ?? []), e.name]);
240
- }
241
- for (const names of real.values()) {
242
- for (const name of names) {
243
- const e = this.entries.get(name)!;
244
- const was = e.duplicate;
245
- e.duplicate =
246
- names.length > 1
247
- ? `同じデータのフォルダを複数の名前で登録しています: ${names.join(", ")}(二重に動かさないため、どれも開きません。p3 project rm <名前> で1つにしてください)`
248
- : undefined;
249
- // 重なりを外して開けるようになったら、別の登録として世代を変える
250
- if (was && !e.duplicate) e.generation = this.nextGeneration(e.dir);
251
- if (!was && e.duplicate && e.ctx) {
252
- const ctx = e.ctx;
253
- e.ctx = undefined;
254
- void ctx.then((c) => this.retire(c), () => undefined);
255
- }
256
- }
257
- }
258
- }
259
-
260
- private nextGeneration(dir: string): string {
261
- this.counter += 1;
262
- return `${createHash("sha256").update(dir).digest("hex").slice(0, 8)}-${this.counter}`;
263
- }
264
- }
@@ -1,31 +0,0 @@
1
- /**
2
- * Preflight のログ・エラーに残す前に、トークンらしいものを伏せる。
3
- * - Codex がエラーで一部だけ見せるキー(例: `Incorrect API key provided: eyJhbGci***xyz`)
4
- * - JWT(ChatGPT の access token / ID トークンの形)
5
- * - Authorization: Bearer の値
6
- * 本物の値を知っている呼び出し側は、secrets に渡せばそれも伏せる。
7
- */
8
- export const REDACTED = "[伏せました]";
9
-
10
- const PATTERNS: RegExp[] = [
11
- // 一部を *** で隠した値(前後の残りも消す)
12
- /[A-Za-z0-9._~+/=-]*\*{3,}[A-Za-z0-9._~+/=-]*/g,
13
- // JWT
14
- /eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
15
- // Bearer の値
16
- /(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,
17
- ];
18
-
19
- export function redact(text: string, secrets: (string | undefined)[] = []): string {
20
- let out = text;
21
- for (const s of secrets) if (s && s.length >= 8) out = out.split(s).join(REDACTED);
22
- return PATTERNS.reduce(
23
- (t, re) =>
24
- t.replace(re, (m, bearer?: string) => {
25
- if (typeof bearer === "string" && /^Bearer/i.test(m)) return `${bearer}${REDACTED}`;
26
- // 文の終わりの「.」は値の一部ではないので残す
27
- return `${REDACTED}${/\.+$/.exec(m)?.[0] ?? ""}`;
28
- }),
29
- out,
30
- );
31
- }