@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.
- package/bin/p3.mjs +11 -5
- package/dist/web/assets/Outputs-C83ZDXvs.js +1 -0
- package/dist/web/assets/RequestStatus-GmiWYEcL.js +1 -0
- package/dist/web/assets/Tabs-CJn0Qy7W.js +1 -0
- package/dist/web/assets/TagInput-CtM8HM8Z.js +1 -0
- package/dist/web/assets/TaskDrawer-D5v36QoF.js +3 -0
- package/dist/web/assets/_requestId-BHUqLO-j.js +1 -0
- package/dist/web/assets/_requestId-DxwxbXY2.js +30 -0
- package/dist/web/assets/{ui-DdOGYj9z.js → appCtx-B-VRVOyv.js} +1 -1
- package/dist/web/assets/board-DAaVR04x.js +1 -0
- package/dist/web/assets/done-CaqB_qTH.js +1 -0
- package/dist/web/assets/index-BF1xMdJo.css +2 -0
- package/dist/web/assets/index-BQYvKpjF.js +12 -0
- package/dist/web/assets/new-DLVnRvrB.js +1 -0
- package/dist/web/assets/{preflightInput-DMxqnvF8.js → preflightInput-BAeEJYUK.js} +1 -1
- package/dist/web/assets/preload-helper-B74h5i3O.js +1 -0
- package/dist/web/assets/progressTree-wp9mH4VF.js +1 -0
- package/dist/web/assets/release-notes-MTLcOcvZ.js +3 -0
- package/dist/web/assets/requestData-D-HXu-cy.js +1 -0
- package/dist/web/assets/routes-CI4Qfkjs.js +3 -0
- package/dist/web/assets/settings-CJMNgzi6.js +1 -0
- package/dist/web/index.html +4 -4
- package/docs/architecture.md +220 -3
- package/docs/development.md +16 -9
- package/docs/how-to-use.md +72 -7
- package/docs/installation.md +8 -6
- package/docs/publishing.md +4 -2
- package/lib/cli/args.js +172 -0
- package/lib/cli/chatgpt.js +70 -0
- package/lib/cli/codex.js +30 -0
- package/lib/cli/format.js +9 -0
- package/{src/cli/help.ts → lib/cli/help.js} +8 -8
- package/lib/cli/main.js +326 -0
- package/lib/cli/output.js +110 -0
- package/lib/cli/preflightCommands.js +301 -0
- package/lib/cli/project.js +649 -0
- package/lib/cli/readOnly.js +36 -0
- package/lib/cli/releaseNotesCommands.js +197 -0
- package/lib/cli/render.js +58 -0
- package/lib/cli/requestCommands.js +180 -0
- package/lib/cli/showView.js +100 -0
- package/lib/cli/taskCommands.js +152 -0
- package/lib/cli/userConfig.js +64 -0
- package/{src/core/chatgpt.ts → lib/core/chatgpt.js} +10 -16
- package/lib/core/context.js +41 -0
- package/lib/core/hierarchy.js +128 -0
- package/lib/core/machineSettings.js +146 -0
- package/lib/core/machineSettingsEdit.js +148 -0
- package/lib/core/ops.js +120 -0
- package/lib/core/preflight/carryover.js +105 -0
- package/lib/core/preflight/codexEngine.js +687 -0
- package/lib/core/preflight/codexImage.js +61 -0
- package/lib/core/preflight/diagnose.js +95 -0
- package/lib/core/preflight/engine.js +58 -0
- package/lib/core/preflight/input.js +83 -0
- package/lib/core/preflight/launch.js +68 -0
- package/lib/core/preflight/mockEngine.js +175 -0
- package/lib/core/preflight/render.js +304 -0
- package/lib/core/preflight/service.js +868 -0
- package/lib/core/preflight/split.js +83 -0
- package/lib/core/preflight/uiMaterials.js +281 -0
- package/lib/core/preflight/uiRender.js +89 -0
- package/lib/core/preflight/wireframe.js +63 -0
- package/lib/core/preflight/xlsx.js +324 -0
- package/lib/core/projectRegistry.js +207 -0
- package/lib/core/redact.js +28 -0
- package/lib/core/releaseNotes/completeRequests.js +106 -0
- package/lib/core/releaseNotes/generate.js +266 -0
- package/lib/core/releaseNotes/material.js +141 -0
- package/lib/core/releaseNotes/mockSummarizer.js +26 -0
- package/lib/core/releaseNotes/service.js +83 -0
- package/lib/core/releaseNotes/store.js +209 -0
- package/lib/core/repoAdmin.js +82 -0
- package/lib/core/repoRefs.js +72 -0
- package/lib/core/requestOps.js +154 -0
- package/lib/core/requestStatus.js +171 -0
- package/lib/core/store/attachments.js +242 -0
- package/lib/core/store/collection.js +254 -0
- package/lib/core/store/frontmatter.js +18 -0
- package/lib/core/store/fsutil.js +84 -0
- package/lib/core/store/locate.js +162 -0
- package/lib/core/store/normalize.js +150 -0
- package/lib/core/store/noteStore.js +59 -0
- package/lib/core/store/preflightStore.js +161 -0
- package/lib/core/store/projectFile.js +99 -0
- package/lib/core/store/workspace.js +320 -0
- package/lib/core/supersede.js +69 -0
- package/lib/core/userConfig.js +158 -0
- package/{src/core/userTheme.ts → lib/core/userTheme.js} +11 -13
- package/lib/core/workTargets.js +106 -0
- package/lib/server/api/chatgptRoutes.js +46 -0
- package/{src/server/api/local.ts → lib/server/api/local.js} +23 -22
- package/lib/server/api/manifest.js +140 -0
- package/lib/server/api/projectsRoutes.js +82 -0
- package/lib/server/api/releaseNoteRoutes.js +88 -0
- package/lib/server/api/repoRoutes.js +67 -0
- package/lib/server/api/routes.js +404 -0
- package/lib/server/api/userThemeRoutes.js +60 -0
- package/lib/server/server.js +85 -0
- package/lib/shared/dates.js +10 -0
- package/{src/shared/directTask.ts → lib/shared/directTask.js} +3 -11
- package/lib/shared/hierarchy.js +120 -0
- package/lib/shared/milestoneOrder.js +45 -0
- package/lib/shared/preflightInput.js +19 -0
- package/lib/shared/refs.js +44 -0
- package/lib/shared/repos.js +69 -0
- package/lib/shared/scopeView.js +39 -0
- package/{src/shared/tags.ts → lib/shared/tags.js} +9 -14
- package/lib/shared/types.js +74 -0
- package/lib/shared/workTarget.js +31 -0
- package/package.json +4 -7
- package/skills/p3/SKILL.md +10 -0
- package/dist/web/assets/Outputs-5Hby-S5Q.js +0 -1
- package/dist/web/assets/RequestStatus-CTkGjT02.js +0 -1
- package/dist/web/assets/TagInput-Rj3PNOAF.js +0 -1
- package/dist/web/assets/TaskDrawer-DtPhiYxP.js +0 -3
- package/dist/web/assets/_requestId-CGvAfIkB.js +0 -30
- package/dist/web/assets/_requestId-DxfYhgAq.js +0 -1
- package/dist/web/assets/board-wt47lfrE.js +0 -1
- package/dist/web/assets/done-C9Ct7ssb.js +0 -1
- package/dist/web/assets/index-BTFL2rpp.js +0 -12
- package/dist/web/assets/index-DAyBsvua.css +0 -2
- package/dist/web/assets/new-e4ID2vQV.js +0 -1
- package/dist/web/assets/preload-helper-DhIyFaOW.js +0 -1
- package/dist/web/assets/release-notes-CQ0d2r0k.js +0 -3
- package/dist/web/assets/requestData-BDZqyl35.js +0 -1
- package/dist/web/assets/routes-Bipv3lwJ.js +0 -2
- package/dist/web/assets/settings-Dwh8fj6p.js +0 -1
- package/src/cli/args.ts +0 -186
- package/src/cli/chatgpt.ts +0 -74
- package/src/cli/codex.ts +0 -28
- package/src/cli/format.ts +0 -9
- package/src/cli/main.ts +0 -337
- package/src/cli/output.ts +0 -117
- package/src/cli/preflightCommands.ts +0 -245
- package/src/cli/project.ts +0 -675
- package/src/cli/readOnly.ts +0 -36
- package/src/cli/releaseNotesCommands.ts +0 -198
- package/src/cli/render.ts +0 -60
- package/src/cli/requestCommands.ts +0 -172
- package/src/cli/showView.ts +0 -110
- package/src/cli/taskCommands.ts +0 -167
- package/src/cli/userConfig.ts +0 -58
- package/src/core/context.ts +0 -58
- package/src/core/machineSettings.ts +0 -207
- package/src/core/machineSettingsEdit.ts +0 -156
- package/src/core/ops.ts +0 -114
- package/src/core/preflight/carryover.ts +0 -133
- package/src/core/preflight/codexEngine.ts +0 -703
- package/src/core/preflight/codexImage.ts +0 -98
- package/src/core/preflight/diagnose.ts +0 -124
- package/src/core/preflight/engine.ts +0 -92
- package/src/core/preflight/input.ts +0 -65
- package/src/core/preflight/launch.ts +0 -86
- package/src/core/preflight/mockEngine.ts +0 -145
- package/src/core/preflight/render.ts +0 -339
- package/src/core/preflight/service.ts +0 -707
- package/src/core/preflight/uiMaterials.ts +0 -272
- package/src/core/preflight/uiRender.ts +0 -84
- package/src/core/preflight/wireframe.ts +0 -69
- package/src/core/preflight/xlsx.ts +0 -328
- package/src/core/projectRegistry.ts +0 -264
- package/src/core/redact.ts +0 -31
- package/src/core/releaseNotes/completeRequests.ts +0 -102
- package/src/core/releaseNotes/generate.ts +0 -283
- package/src/core/releaseNotes/material.ts +0 -114
- package/src/core/releaseNotes/mockSummarizer.ts +0 -28
- package/src/core/releaseNotes/service.ts +0 -110
- package/src/core/releaseNotes/store.ts +0 -216
- package/src/core/repoAdmin.ts +0 -81
- package/src/core/repoRefs.ts +0 -90
- package/src/core/requestOps.ts +0 -140
- package/src/core/requestStatus.ts +0 -58
- package/src/core/store/attachments.ts +0 -228
- package/src/core/store/collection.ts +0 -282
- package/src/core/store/frontmatter.ts +0 -22
- package/src/core/store/fsutil.ts +0 -90
- package/src/core/store/locate.ts +0 -181
- package/src/core/store/normalize.ts +0 -155
- package/src/core/store/noteStore.ts +0 -56
- package/src/core/store/preflightStore.ts +0 -136
- package/src/core/store/projectFile.ts +0 -101
- package/src/core/store/workspace.ts +0 -328
- package/src/core/supersede.ts +0 -74
- package/src/core/userConfig.ts +0 -205
- package/src/core/workTargets.ts +0 -120
- package/src/server/api/chatgptRoutes.ts +0 -49
- package/src/server/api/manifest.ts +0 -135
- package/src/server/api/projectsRoutes.ts +0 -89
- package/src/server/api/releaseNoteRoutes.ts +0 -89
- package/src/server/api/repoRoutes.ts +0 -67
- package/src/server/api/routes.ts +0 -382
- package/src/server/api/userThemeRoutes.ts +0 -62
- package/src/server/server.ts +0 -108
- package/src/shared/dates.ts +0 -12
- package/src/shared/milestoneOrder.ts +0 -44
- package/src/shared/preflightInput.ts +0 -27
- package/src/shared/refs.ts +0 -55
- package/src/shared/repos.ts +0 -113
- package/src/shared/scopeView.ts +0 -48
- package/src/shared/types.ts +0 -730
- package/src/shared/workTarget.ts +0 -44
- /package/{src → lib}/core/preflight/launcher.mjs +0 -0
- /package/{src → lib}/core/preflight/mock-ui.html +0 -0
- /package/{src → lib}/core/preflight/mock-ui.png +0 -0
- /package/{src → lib}/core/preflight/render-image/Dockerfile +0 -0
- /package/{src → lib}/core/preflight/render-image/fonts-ja.conf +0 -0
- /package/{src → lib}/core/preflight/render-image/render.mjs +0 -0
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
-
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { ATTACHMENT_FILE_LIMITS, type Attachment, type AttachmentFormat, type FixedAttachment } from "../../shared/types.ts";
|
|
5
|
-
import { imageInfo, UI_LIMITS } from "../preflight/uiMaterials.ts";
|
|
6
|
-
import { nowIso, writeFileAtomic } from "./fsutil.ts";
|
|
7
|
-
|
|
8
|
-
export const ATTACHMENT_ID = /^A-\d{8}-\d{6}-[0-9a-f]{4}$/;
|
|
9
|
-
|
|
10
|
-
/** 上限(1つの要望あたり) */
|
|
11
|
-
export const ATTACHMENT_LIMITS = {
|
|
12
|
-
...ATTACHMENT_FILE_LIMITS,
|
|
13
|
-
/** xlsx(ZIP)の項目数と、展開したときの合計(中身は読まない。一覧だけで断る) */
|
|
14
|
-
zipEntries: 10_000,
|
|
15
|
-
zipUncompressed: 200 * 1024 * 1024,
|
|
16
|
-
} as const;
|
|
17
|
-
|
|
18
|
-
export class AttachmentError extends Error {}
|
|
19
|
-
|
|
20
|
-
const EXT: Record<AttachmentFormat, string> = { png: "png", jpeg: "jpg", xlsx: "xlsx" };
|
|
21
|
-
export const ATTACHMENT_TYPES: Record<AttachmentFormat, string> = {
|
|
22
|
-
png: "image/png",
|
|
23
|
-
jpeg: "image/jpeg",
|
|
24
|
-
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* ZIP の一覧(中央ディレクトリ)だけを読む。展開はしない(中身の読み取りは xlsx の展開で、別に上限をかけて行う)。
|
|
29
|
-
* 読めなければ undefined
|
|
30
|
-
*/
|
|
31
|
-
export function zipEntries(buf: Buffer): { name: string; uncompressed: number }[] | undefined {
|
|
32
|
-
const min = Math.max(0, buf.length - 65_557);
|
|
33
|
-
let eocd = -1;
|
|
34
|
-
for (let i = buf.length - 22; i >= min; i--) {
|
|
35
|
-
if (buf.readUInt32LE(i) === 0x06054b50) {
|
|
36
|
-
eocd = i;
|
|
37
|
-
break;
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
if (eocd < 0) return undefined;
|
|
41
|
-
const count = buf.readUInt16LE(eocd + 10);
|
|
42
|
-
let at = buf.readUInt32LE(eocd + 16);
|
|
43
|
-
const entries: { name: string; uncompressed: number }[] = [];
|
|
44
|
-
for (let i = 0; i < count; i++) {
|
|
45
|
-
if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) return undefined;
|
|
46
|
-
const nameLen = buf.readUInt16LE(at + 28);
|
|
47
|
-
const extra = buf.readUInt16LE(at + 30);
|
|
48
|
-
const comment = buf.readUInt16LE(at + 32);
|
|
49
|
-
entries.push({ name: buf.toString("utf8", at + 46, at + 46 + nameLen), uncompressed: buf.readUInt32LE(at + 24) });
|
|
50
|
-
at += 46 + nameLen + extra + comment;
|
|
51
|
-
}
|
|
52
|
-
return entries;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** 中身から形式を決めて確かめる。拡張子とも合わせる。だめなら AttachmentError */
|
|
56
|
-
export function inspectAttachment(data: Buffer, name: string): { format: AttachmentFormat; width?: number; height?: number } {
|
|
57
|
-
const ext = name.toLowerCase().split(".").pop() ?? "";
|
|
58
|
-
const want: AttachmentFormat | undefined = ext === "png" ? "png" : ext === "jpg" || ext === "jpeg" ? "jpeg" : ext === "xlsx" ? "xlsx" : undefined;
|
|
59
|
-
if (!want) throw new AttachmentError(`添付できるのは PNG / JPEG / xlsx です(${name})。xls や xlsm は xlsx で保存し直すか、画像にしてください`);
|
|
60
|
-
if (want === "xlsx") {
|
|
61
|
-
if (data.length > ATTACHMENT_LIMITS.xlsxBytes) throw new AttachmentError(`xlsx が大きすぎます(上限 ${ATTACHMENT_LIMITS.xlsxBytes} バイト)`);
|
|
62
|
-
if (data.readUInt32LE(0) !== 0x04034b50) throw new AttachmentError(`${name}: xlsx(ZIP)として読めません`);
|
|
63
|
-
const entries = zipEntries(data);
|
|
64
|
-
if (!entries) throw new AttachmentError(`${name}: xlsx(ZIP)の一覧が読めません`);
|
|
65
|
-
if (entries.length > ATTACHMENT_LIMITS.zipEntries) throw new AttachmentError(`${name}: 中のファイルが多すぎます(${entries.length})`);
|
|
66
|
-
const total = entries.reduce((n, e) => n + e.uncompressed, 0);
|
|
67
|
-
if (total > ATTACHMENT_LIMITS.zipUncompressed) throw new AttachmentError(`${name}: 展開すると大きすぎます(${total} バイト)`);
|
|
68
|
-
if (entries.some((e) => e.name.startsWith("/") || e.name.includes("\\") || e.name.split("/").includes(".."))) throw new AttachmentError(`${name}: 中に外を指すパスがあります`);
|
|
69
|
-
const names = new Set(entries.map((e) => e.name));
|
|
70
|
-
if (!names.has("[Content_Types].xml") || !names.has("xl/workbook.xml")) throw new AttachmentError(`${name}: xlsx のブックではありません`);
|
|
71
|
-
if ([...names].some((n) => /vbaProject\.bin$/i.test(n))) throw new AttachmentError(`${name}: マクロを含むブックは扱いません(マクロを外した xlsx にしてください)`);
|
|
72
|
-
return { format: "xlsx" };
|
|
73
|
-
}
|
|
74
|
-
if (data.length > ATTACHMENT_LIMITS.imageBytes) throw new AttachmentError(`画像が大きすぎます(上限 ${ATTACHMENT_LIMITS.imageBytes} バイト)`);
|
|
75
|
-
const info = imageInfo(data);
|
|
76
|
-
if (!info) throw new AttachmentError(`${name}: PNG / JPEG として読めません`);
|
|
77
|
-
if (info.format !== want) throw new AttachmentError(`${name}: 拡張子と中身の形式が合いません(中身は ${info.format})`);
|
|
78
|
-
if (info.width > UI_LIMITS.width || info.height > UI_LIMITS.height || info.width * info.height > UI_LIMITS.pixels) {
|
|
79
|
-
throw new AttachmentError(`${name}: 画像の大きさが上限を超えています(${info.width}x${info.height})`);
|
|
80
|
-
}
|
|
81
|
-
return info;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** ダウンロードの名前(制御文字・パスの区切りを外す) */
|
|
85
|
-
export function safeFileName(name: string, format: AttachmentFormat): string {
|
|
86
|
-
// oxlint-disable-next-line no-control-regex -- 制御文字を外すのが目的
|
|
87
|
-
const base = name.replace(/[\u0000-\u001f\u007f/\\:*?"<>|]/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
|
|
88
|
-
const ext = `.${EXT[format]}`;
|
|
89
|
-
const withExt = /\.(png|jpe?g|xlsx)$/i.test(base) ? base : `${base || "attachment"}${ext}`;
|
|
90
|
-
return withExt || `attachment${ext}`;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* requests/<要望ID>/attachments/<ID>/
|
|
95
|
-
* meta.json 元の名前・説明・出典・形式・大きさ・sha256・追加した人と日時
|
|
96
|
-
* file.<拡張子> 原本(内部の名前)
|
|
97
|
-
*
|
|
98
|
-
* 1件1フォルダなので、複数人が同時に足しても衝突しない。書きかけ(.tmp-)と消しかけ(.del-)は一覧に出さない。
|
|
99
|
-
*/
|
|
100
|
-
export class AttachmentStore {
|
|
101
|
-
constructor(readonly requestsDir: string) {}
|
|
102
|
-
|
|
103
|
-
dir(requestId: string) {
|
|
104
|
-
return join(this.requestsDir, requestId, "attachments");
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
private fileOf(requestId: string, a: Pick<Attachment, "id" | "format">) {
|
|
108
|
-
return join(this.dir(requestId), a.id, `file.${EXT[a.format]}`);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
async add(requestId: string, input: { data: Buffer; name: string; description?: string; source?: string }, actor?: string): Promise<Attachment> {
|
|
112
|
-
const name = input.name.trim().split(/[\\/]/).pop() ?? "";
|
|
113
|
-
if (!name) throw new AttachmentError("ファイル名がありません");
|
|
114
|
-
const info = inspectAttachment(input.data, name);
|
|
115
|
-
const { items } = await this.list(requestId);
|
|
116
|
-
if (items.length >= ATTACHMENT_LIMITS.count) throw new AttachmentError(`添付は1つの要望に ${ATTACHMENT_LIMITS.count} 件までです`);
|
|
117
|
-
const total = items.reduce((n, a) => n + a.bytes, 0) + input.data.length;
|
|
118
|
-
if (total > ATTACHMENT_LIMITS.totalBytes) throw new AttachmentError(`添付の合計が上限(${ATTACHMENT_LIMITS.totalBytes} バイト)を超えます`);
|
|
119
|
-
const createdAt = nowIso();
|
|
120
|
-
const id = `A-${createdAt.replace(/[-:]/g, "").replace("T", "-").slice(0, 15)}-${randomBytes(2).toString("hex")}`;
|
|
121
|
-
const text = (v?: string) => (v?.trim() ? v.trim() : undefined);
|
|
122
|
-
const a: Attachment = {
|
|
123
|
-
id,
|
|
124
|
-
requestId,
|
|
125
|
-
name,
|
|
126
|
-
format: info.format,
|
|
127
|
-
bytes: input.data.length,
|
|
128
|
-
sha256: createHash("sha256").update(input.data).digest("hex"),
|
|
129
|
-
...(text(input.description) ? { description: text(input.description) } : {}),
|
|
130
|
-
...(text(input.source) ? { source: text(input.source) } : {}),
|
|
131
|
-
...(info.width ? { width: info.width, height: info.height } : {}),
|
|
132
|
-
createdAt,
|
|
133
|
-
...(actor ? { createdBy: actor } : {}),
|
|
134
|
-
};
|
|
135
|
-
// 書きかけのフォルダに全部書いてから名前を変える(途中で止まっても一覧に半端なものが出ない)
|
|
136
|
-
const tmp = join(this.dir(requestId), `.tmp-${id}`);
|
|
137
|
-
await mkdir(tmp, { recursive: true });
|
|
138
|
-
try {
|
|
139
|
-
await writeFile(join(tmp, `file.${EXT[a.format]}`), input.data);
|
|
140
|
-
await writeFile(join(tmp, "meta.json"), JSON.stringify(withoutRequest(a), null, 2) + "\n");
|
|
141
|
-
await rename(tmp, join(this.dir(requestId), id));
|
|
142
|
-
} catch (e) {
|
|
143
|
-
await rm(tmp, { recursive: true, force: true });
|
|
144
|
-
throw e;
|
|
145
|
-
}
|
|
146
|
-
return a;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** 古い順。読めないものは invalid に理由(黙って捨てない) */
|
|
150
|
-
async list(requestId: string): Promise<{ items: Attachment[]; invalid: { id: string; error: string }[] }> {
|
|
151
|
-
const names = await readdir(this.dir(requestId)).catch(() => [] as string[]);
|
|
152
|
-
const items: Attachment[] = [];
|
|
153
|
-
const invalid: { id: string; error: string }[] = [];
|
|
154
|
-
for (const id of names.filter((n) => !n.startsWith("."))) {
|
|
155
|
-
try {
|
|
156
|
-
items.push(await this.read(requestId, id));
|
|
157
|
-
} catch (e) {
|
|
158
|
-
invalid.push({ id, error: (e as Error).message });
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
items.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
162
|
-
return { items, invalid };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
private async read(requestId: string, id: string): Promise<Attachment> {
|
|
166
|
-
if (!ATTACHMENT_ID.test(id)) throw new AttachmentError("名前が A-YYYYMMDD-HHMMSS-xxxx ではありません");
|
|
167
|
-
const dir = join(this.dir(requestId), id);
|
|
168
|
-
const st = await lstat(dir);
|
|
169
|
-
if (!st.isDirectory()) throw new AttachmentError("フォルダではありません");
|
|
170
|
-
const meta = JSON.parse(await readFile(join(dir, "meta.json"), "utf8"));
|
|
171
|
-
if (meta.id !== id || !(meta.format in EXT) || typeof meta.name !== "string") throw new AttachmentError("meta.json が読めません");
|
|
172
|
-
return { ...meta, requestId };
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
async get(requestId: string, id: string): Promise<Attachment | undefined> {
|
|
176
|
-
if (!ATTACHMENT_ID.test(id)) return undefined;
|
|
177
|
-
return this.read(requestId, id).catch(() => undefined);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/** 原本を読む。保存したときの形式・大きさ・sha256 と合うかを確かめる(差し替えやシンボリックリンクは断る) */
|
|
181
|
-
async content(requestId: string, id: string): Promise<{ meta: Attachment; data: Buffer }> {
|
|
182
|
-
const meta = await this.get(requestId, id);
|
|
183
|
-
if (!meta) throw new AttachmentError(`添付 ${id} がありません`);
|
|
184
|
-
const file = this.fileOf(requestId, meta);
|
|
185
|
-
const st = await lstat(file).catch(() => undefined);
|
|
186
|
-
if (!st?.isFile()) throw new AttachmentError(`添付 ${id} の原本がありません`);
|
|
187
|
-
const data = await readFile(file);
|
|
188
|
-
if (data.length !== meta.bytes || createHash("sha256").update(data).digest("hex") !== meta.sha256) {
|
|
189
|
-
throw new AttachmentError(`添付 ${id} の原本が保存したときと変わっています`);
|
|
190
|
-
}
|
|
191
|
-
return { meta, data };
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
async remove(requestId: string, id: string): Promise<void> {
|
|
195
|
-
if (!(await this.get(requestId, id))) throw new AttachmentError(`添付 ${id} がありません`);
|
|
196
|
-
// 先に名前を変えて一覧から外してから消す(消しかけを開始時のコピーが読まない)
|
|
197
|
-
const del = join(this.dir(requestId), `.del-${id}-${randomBytes(2).toString("hex")}`);
|
|
198
|
-
await rename(join(this.dir(requestId), id), del);
|
|
199
|
-
await rm(del, { recursive: true, force: true });
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/**
|
|
203
|
-
* Preflight を始めるときに、今の添付を run の中へコピーして固定する。画像は <runDir>/ui/current/、xlsx は
|
|
204
|
-
* <runDir>/attachments/ に置き、一覧を <runDir>/attachments.json に書く。コピーの途中で消された・変わったものがあれば
|
|
205
|
-
* AttachmentError(その Preflight は始めない。原本は残る)
|
|
206
|
-
*/
|
|
207
|
-
async snapshot(requestId: string, runDir: string): Promise<FixedAttachment[]> {
|
|
208
|
-
const { items } = await this.list(requestId);
|
|
209
|
-
const fixed: FixedAttachment[] = [];
|
|
210
|
-
for (const a of items) {
|
|
211
|
-
let data: Buffer;
|
|
212
|
-
try {
|
|
213
|
-
({ data } = await this.content(requestId, a.id));
|
|
214
|
-
} catch (e) {
|
|
215
|
-
throw new AttachmentError(`添付を固定できません(始める間に添付が変わりました。もう一度始めてください): ${(e as Error).message}`);
|
|
216
|
-
}
|
|
217
|
-
const path = a.format === "xlsx" ? `attachments/${a.id}.xlsx` : `ui/current/${a.id}.${EXT[a.format]}`;
|
|
218
|
-
await mkdir(join(runDir, path, ".."), { recursive: true });
|
|
219
|
-
await writeFile(join(runDir, path), data);
|
|
220
|
-
const { requestId: _, ...rest } = a;
|
|
221
|
-
fixed.push({ ...rest, path });
|
|
222
|
-
}
|
|
223
|
-
if (fixed.length) await writeFileAtomic(join(runDir, "attachments.json"), JSON.stringify(fixed, null, 2) + "\n");
|
|
224
|
-
return fixed;
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
const withoutRequest = ({ requestId: _, ...a }: Attachment) => a;
|
|
@@ -1,282 +0,0 @@
|
|
|
1
|
-
import { access, mkdir, readFile, readdir, rename } from "node:fs/promises";
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.ts";
|
|
4
|
-
import { createExclusive, nowIso, writeFileAtomic } from "./fsutil.ts";
|
|
5
|
-
|
|
6
|
-
export interface Entity {
|
|
7
|
-
id: string;
|
|
8
|
-
rev: number;
|
|
9
|
-
createdAt: string;
|
|
10
|
-
updatedAt: string;
|
|
11
|
-
updatedBy?: string;
|
|
12
|
-
body: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export class ConflictError extends Error {
|
|
16
|
-
constructor(
|
|
17
|
-
public id: string,
|
|
18
|
-
public expected: number,
|
|
19
|
-
public actual: number,
|
|
20
|
-
) {
|
|
21
|
-
super(`${id}: rev conflict (expected ${expected}, actual ${actual})`);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export class NotFoundError extends Error {
|
|
26
|
-
constructor(public id: string) {
|
|
27
|
-
super(`${id} not found`);
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** エンティティをどこに置き、どう採番するか */
|
|
32
|
-
export interface Layout {
|
|
33
|
-
/** エンティティのファイル */
|
|
34
|
-
path(id: string): string;
|
|
35
|
-
/** ディスク上にある ID */
|
|
36
|
-
scan(): Promise<string[]>;
|
|
37
|
-
/** 採番で使わない ID(アーカイブ済みなど。読み込みの対象ではない) */
|
|
38
|
-
reserved?(): Promise<string[]>;
|
|
39
|
-
/** 新しい ID。attempt は衝突してやり直した回数 */
|
|
40
|
-
nextId(existing: string[], attempt: number): string;
|
|
41
|
-
/** アーカイブ: 移す元と先 */
|
|
42
|
-
archive(id: string): { from: string; to: string };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface CollectionOptions<T extends Entity> {
|
|
46
|
-
layout: Layout;
|
|
47
|
-
normalize: (data: Record<string, unknown>, body: string, id: string) => T;
|
|
48
|
-
/** frontmatter に書くキー順 */
|
|
49
|
-
keyOrder: (keyof T)[];
|
|
50
|
-
/** ファイルに書かないキー(場所から決まるもの) */
|
|
51
|
-
derived?: (keyof T)[];
|
|
52
|
-
/** 書く直前の加工(ステータスを変えた日時の記録など)。prev は作成時 undefined */
|
|
53
|
-
beforeWrite?: (prev: T | undefined, next: T) => T;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** 全件の読み込みの準備(prepareLoad)。commit で読んだ結果を公開し、abort で捨てる */
|
|
57
|
-
export interface PreparedLoad {
|
|
58
|
-
/** 読めた ID(読めなかったものは含まない) */
|
|
59
|
-
ids: string[];
|
|
60
|
-
commit(): void;
|
|
61
|
-
abort(): void;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
type ReadResult<T> = { item: T } | { error: string } | { missing: true };
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* 1エンティティ = 1 Markdown ファイル(YAML frontmatter + 本文)のコレクション。
|
|
68
|
-
* メモリ上にキャッシュし、ファイル変更(人手・AI・Codex・git pull)は reload() で取り込む。
|
|
69
|
-
*
|
|
70
|
-
* 全件の読み込み(load / prepareLoad)は、読み終えてから入れ替える(読んでいる途中の空や半分の状態を見せない)。
|
|
71
|
-
* 読み込みの間に作成・更新・アーカイブ・1件の読み直しがあった ID は、読んだ結果ではなくその時点の状態を残す
|
|
72
|
-
* (読み込みが先に読んだ古い内容で、後の書き込みを戻さない)。
|
|
73
|
-
*/
|
|
74
|
-
export class MarkdownCollection<T extends Entity> {
|
|
75
|
-
private items = new Map<string, T>();
|
|
76
|
-
/** 読めないファイル。壊れたファイルで全体が落ちないようにする */
|
|
77
|
-
readonly errors = new Map<string, string>();
|
|
78
|
-
private layout: Layout;
|
|
79
|
-
/** 進行中の全件の読み込みごとの「その間に変わった ID」 */
|
|
80
|
-
private loads = new Set<Set<string>>();
|
|
81
|
-
|
|
82
|
-
constructor(private opts: CollectionOptions<T>) {
|
|
83
|
-
this.layout = opts.layout;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
async load(): Promise<void> {
|
|
87
|
-
(await this.prepareLoad()).commit();
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** ディスクから全件を読む。公開は commit でまとめて(同期で)行う */
|
|
91
|
-
async prepareLoad(): Promise<PreparedLoad> {
|
|
92
|
-
const touched = new Set<string>();
|
|
93
|
-
this.loads.add(touched);
|
|
94
|
-
const items = new Map<string, T>();
|
|
95
|
-
const errors = new Map<string, string>();
|
|
96
|
-
try {
|
|
97
|
-
for (const id of await this.layout.scan()) {
|
|
98
|
-
const r = await this.read(id);
|
|
99
|
-
if ("item" in r) items.set(id, r.item);
|
|
100
|
-
else if ("error" in r) errors.set(id, r.error);
|
|
101
|
-
}
|
|
102
|
-
} catch (e) {
|
|
103
|
-
this.loads.delete(touched);
|
|
104
|
-
throw e;
|
|
105
|
-
}
|
|
106
|
-
return {
|
|
107
|
-
ids: [...items.keys()],
|
|
108
|
-
commit: () => {
|
|
109
|
-
if (!this.loads.delete(touched)) return;
|
|
110
|
-
for (const id of touched) {
|
|
111
|
-
const live = this.items.get(id);
|
|
112
|
-
if (live) items.set(id, live);
|
|
113
|
-
else items.delete(id);
|
|
114
|
-
const err = this.errors.get(id);
|
|
115
|
-
if (err !== undefined) errors.set(id, err);
|
|
116
|
-
else errors.delete(id);
|
|
117
|
-
}
|
|
118
|
-
this.items = items;
|
|
119
|
-
this.errors.clear();
|
|
120
|
-
for (const [id, e] of errors) this.errors.set(id, e);
|
|
121
|
-
},
|
|
122
|
-
abort: () => void this.loads.delete(touched),
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* 1件をディスクから読むだけ(読み込んだ内容・索引・変更通知には触れない)。監視に頼らずに今のファイルを確かめるため。
|
|
128
|
-
* 無ければ { missing }、読めなければ { error }
|
|
129
|
-
*/
|
|
130
|
-
peek(id: string): Promise<ReadResult<T>> {
|
|
131
|
-
return this.read(id);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
private async read(id: string): Promise<ReadResult<T>> {
|
|
135
|
-
try {
|
|
136
|
-
const { data, body } = parseFrontmatter(await readFile(this.layout.path(id), "utf8"));
|
|
137
|
-
return { item: this.opts.normalize(data, body, id) };
|
|
138
|
-
} catch (e) {
|
|
139
|
-
return (e as NodeJS.ErrnoException).code === "ENOENT" ? { missing: true } : { error: String(e) };
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
private touch(id: string) {
|
|
144
|
-
for (const t of this.loads) t.add(id);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
private put(id: string, item: T) {
|
|
148
|
-
this.items.set(id, item);
|
|
149
|
-
this.touch(id);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** 1件を読み直す。消えていれば除く */
|
|
153
|
-
async reload(id: string): Promise<void> {
|
|
154
|
-
const r = await this.read(id);
|
|
155
|
-
if ("item" in r) {
|
|
156
|
-
this.put(id, r.item);
|
|
157
|
-
this.errors.delete(id);
|
|
158
|
-
} else {
|
|
159
|
-
this.items.delete(id);
|
|
160
|
-
if ("error" in r) this.errors.set(id, r.error);
|
|
161
|
-
else this.errors.delete(id);
|
|
162
|
-
this.touch(id);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
list(): T[] {
|
|
167
|
-
return [...this.items.values()].sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true }));
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
get(id: string): T | undefined {
|
|
171
|
-
return this.items.get(id);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
require(id: string): T {
|
|
175
|
-
const v = this.items.get(id);
|
|
176
|
-
if (!v) throw new NotFoundError(id);
|
|
177
|
-
return v;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
path(id: string) {
|
|
181
|
-
return this.layout.path(id);
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
private serialize(item: T): string {
|
|
185
|
-
const { body, ...rest } = item;
|
|
186
|
-
const skip = new Set<string>(["body", ...((this.opts.derived ?? []) as string[])]);
|
|
187
|
-
const ordered: Record<string, unknown> = {};
|
|
188
|
-
for (const k of this.opts.keyOrder) if (!skip.has(k as string)) ordered[k as string] = (rest as Record<string, unknown>)[k as string];
|
|
189
|
-
for (const [k, v] of Object.entries(rest)) if (!(k in ordered) && !skip.has(k)) ordered[k] = v;
|
|
190
|
-
return stringifyFrontmatter(ordered, body);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/** 作る。省いた項目は normalize の既定値になる */
|
|
194
|
-
async create(input: Partial<Omit<T, "id" | "rev" | "createdAt" | "updatedAt">>, actor?: string): Promise<T> {
|
|
195
|
-
// アーカイブ済みの ID も使わない(アーカイブしたタスクへの関係が新しいタスクを指さないように)
|
|
196
|
-
const existing = [...new Set([...this.items.keys(), ...(await this.layout.scan()), ...((await this.layout.reserved?.()) ?? [])])];
|
|
197
|
-
// 別のプロセス(CLI・AI)と同時に作っても、排他作成で衝突を検出して次の ID にする
|
|
198
|
-
for (let attempt = 0; ; attempt++) {
|
|
199
|
-
const id = this.layout.nextId(existing, attempt);
|
|
200
|
-
const now = nowIso();
|
|
201
|
-
const item = this.opts.normalize({}, "", id);
|
|
202
|
-
Object.assign(item, input, { id, rev: 1, createdAt: now, updatedAt: now, updatedBy: actor });
|
|
203
|
-
const final = this.opts.beforeWrite?.(undefined, item) ?? item;
|
|
204
|
-
Object.assign(item, final);
|
|
205
|
-
if (await createExclusive(this.layout.path(id), this.serialize(item))) {
|
|
206
|
-
this.put(id, item);
|
|
207
|
-
return item;
|
|
208
|
-
}
|
|
209
|
-
existing.push(id);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* 部分更新。expectedRev を渡すと楽観ロック(AI が古い状態を元に上書きするのを防ぐ)。
|
|
215
|
-
*/
|
|
216
|
-
async update(id: string, patch: Partial<T>, opts: { expectedRev?: number; actor?: string } = {}): Promise<T> {
|
|
217
|
-
// 外部での編集を取りこぼさないよう、更新の直前にディスクから読み直す
|
|
218
|
-
await this.reload(id);
|
|
219
|
-
const cur = this.require(id);
|
|
220
|
-
if (opts.expectedRev !== undefined && opts.expectedRev !== cur.rev) {
|
|
221
|
-
throw new ConflictError(id, opts.expectedRev, cur.rev);
|
|
222
|
-
}
|
|
223
|
-
const merged = {
|
|
224
|
-
...cur,
|
|
225
|
-
...patch,
|
|
226
|
-
id,
|
|
227
|
-
rev: cur.rev + 1,
|
|
228
|
-
createdAt: cur.createdAt,
|
|
229
|
-
updatedAt: nowIso(),
|
|
230
|
-
updatedBy: opts.actor ?? cur.updatedBy,
|
|
231
|
-
} as T;
|
|
232
|
-
const next = this.opts.beforeWrite?.(cur, merged) ?? merged;
|
|
233
|
-
await writeFileAtomic(this.layout.path(id), this.serialize(next));
|
|
234
|
-
this.put(id, next);
|
|
235
|
-
return next;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/** 物理削除はせず .archive/ へ移す */
|
|
239
|
-
async archive(id: string): Promise<void> {
|
|
240
|
-
this.require(id);
|
|
241
|
-
const { from, to } = this.layout.archive(id);
|
|
242
|
-
// 既にアーカイブに同じ ID があれば上書きしない(rename は黙って置き換えるので先に確かめる)
|
|
243
|
-
if (await access(to).then(() => true, () => false)) throw new Error(`${id} は既にアーカイブにあります(${to})。上書きしません`);
|
|
244
|
-
await mkdir(dirname(to), { recursive: true });
|
|
245
|
-
await rename(from, to);
|
|
246
|
-
this.items.delete(id);
|
|
247
|
-
this.touch(id);
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/** ディレクトリの中の "<ID>.md"(タスク)。ID は要望の中の連番 */
|
|
252
|
-
export function fileLayout(dir: string, idPattern: RegExp, format: (n: number) => string): Layout {
|
|
253
|
-
/** ディレクトリの中の有効な名前の ID(中身は読まないので、壊れたファイルでも ID は予約される) */
|
|
254
|
-
const ids = async (d: string) =>
|
|
255
|
-
(await readdir(d).catch(() => [] as string[]))
|
|
256
|
-
.filter((f) => f.endsWith(".md"))
|
|
257
|
-
.map((f) => f.slice(0, -3))
|
|
258
|
-
.filter((id) => idPattern.test(id));
|
|
259
|
-
return {
|
|
260
|
-
path: (id) => join(dir, `${id}.md`),
|
|
261
|
-
scan: () => ids(dir),
|
|
262
|
-
reserved: () => ids(join(dir, ".archive")),
|
|
263
|
-
nextId: (existing, attempt) => {
|
|
264
|
-
const nums = existing.map((id) => Number(/\d+/.exec(id)?.[0] ?? 0));
|
|
265
|
-
return format((nums.length ? Math.max(...nums) : 0) + 1 + attempt);
|
|
266
|
-
},
|
|
267
|
-
archive: (id) => ({ from: join(dir, `${id}.md`), to: join(dir, ".archive", `${id}.md`) }),
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/** "<ID>/<file>"(要望)。フォルダごと1件で、ID は新しく作る */
|
|
272
|
-
export function folderLayout(dir: string, file: string, idPattern: RegExp, newId: () => string): Layout {
|
|
273
|
-
return {
|
|
274
|
-
path: (id) => join(dir, id, file),
|
|
275
|
-
scan: async () =>
|
|
276
|
-
(await readdir(dir, { withFileTypes: true }).catch(() => []))
|
|
277
|
-
.filter((d) => d.isDirectory() && idPattern.test(d.name))
|
|
278
|
-
.map((d) => d.name),
|
|
279
|
-
nextId: () => newId(),
|
|
280
|
-
archive: (id) => ({ from: join(dir, id), to: join(dir, ".archive", id) }),
|
|
281
|
-
};
|
|
282
|
-
}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import YAML from "yaml";
|
|
2
|
-
|
|
3
|
-
const FENCE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
4
|
-
|
|
5
|
-
/** `---\nyaml\n---\nbody` 形式を分解する。frontmatter が無ければ空オブジェクト。 */
|
|
6
|
-
export function parseFrontmatter(text: string): { data: Record<string, unknown>; body: string } {
|
|
7
|
-
const m = FENCE.exec(text);
|
|
8
|
-
if (!m) return { data: {}, body: text };
|
|
9
|
-
const data = (YAML.parse(m[1]) ?? {}) as Record<string, unknown>;
|
|
10
|
-
// stringify は frontmatter と本文の間に空行を1つ入れるので、それを取り除く
|
|
11
|
-
return { data, body: text.slice(m[0].length).replace(/^\r?\n/, "") };
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function stringifyFrontmatter(data: Record<string, unknown>, body: string): string {
|
|
15
|
-
// undefined / 空配列は書かない(差分を小さく、人が読みやすく保つ)
|
|
16
|
-
const clean = Object.fromEntries(
|
|
17
|
-
Object.entries(data).filter(([, v]) => v !== undefined && !(Array.isArray(v) && v.length === 0)),
|
|
18
|
-
);
|
|
19
|
-
const yaml = YAML.stringify(clean, { lineWidth: 0 }).trimEnd();
|
|
20
|
-
const text = body.trim();
|
|
21
|
-
return `---\n${yaml}\n---\n${text ? `\n${text}\n` : ""}`;
|
|
22
|
-
}
|
package/src/core/store/fsutil.ts
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import { mkdir, rename, writeFile, open, stat, unlink } from "node:fs/promises";
|
|
2
|
-
import { dirname } from "node:path";
|
|
3
|
-
import { randomBytes, randomInt } from "node:crypto";
|
|
4
|
-
|
|
5
|
-
/** tmp に書いてから rename する。外部エディタ/AI が途中状態を読まないように。 */
|
|
6
|
-
export async function writeFileAtomic(path: string, content: string): Promise<void> {
|
|
7
|
-
await mkdir(dirname(path), { recursive: true });
|
|
8
|
-
const tmp = `${path}.${randomBytes(4).toString("hex")}.tmp`;
|
|
9
|
-
await writeFile(tmp, content, "utf8");
|
|
10
|
-
await rename(tmp, path);
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* ロックのファイル(O_EXCL で作る)で、同じマシンの別のプロセス(CLI・serve)と処理を1つずつにする。
|
|
15
|
-
* 取れなければ少し待つ。古いロック(staleMs より前)は落ちたプロセスのものとして取り直す。
|
|
16
|
-
*/
|
|
17
|
-
export async function withFileLock<T>(
|
|
18
|
-
lock: string,
|
|
19
|
-
fn: () => Promise<T>,
|
|
20
|
-
opts: { timeoutMs?: number; staleMs?: number; busyMessage?: string; mode?: number } = {},
|
|
21
|
-
): Promise<T> {
|
|
22
|
-
const { timeoutMs = 30_000, staleMs = 60_000, busyMessage = `${lock} を待ちきれませんでした(別のプロセスが使っています)` } = opts;
|
|
23
|
-
await mkdir(dirname(lock), { recursive: true, mode: 0o700 });
|
|
24
|
-
const until = Date.now() + timeoutMs;
|
|
25
|
-
for (;;) {
|
|
26
|
-
try {
|
|
27
|
-
const fh = await open(lock, "wx", opts.mode ?? 0o600);
|
|
28
|
-
await fh.writeFile(String(process.pid));
|
|
29
|
-
await fh.close();
|
|
30
|
-
break;
|
|
31
|
-
} catch (e) {
|
|
32
|
-
if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
|
|
33
|
-
const st = await stat(lock).catch(() => undefined);
|
|
34
|
-
if (st && Date.now() - st.mtimeMs > staleMs) {
|
|
35
|
-
await unlink(lock).catch(() => {});
|
|
36
|
-
continue;
|
|
37
|
-
}
|
|
38
|
-
if (Date.now() > until) throw new Error(busyMessage);
|
|
39
|
-
await new Promise((r) => setTimeout(r, 20 + Math.random() * 80));
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
try {
|
|
43
|
-
return await fn();
|
|
44
|
-
} finally {
|
|
45
|
-
await unlink(lock).catch(() => {});
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** 既に存在する場合は false を返す(ID 採番の競合検出用) */
|
|
50
|
-
export async function createExclusive(path: string, content: string): Promise<boolean> {
|
|
51
|
-
await mkdir(dirname(path), { recursive: true });
|
|
52
|
-
try {
|
|
53
|
-
const fh = await open(path, "wx");
|
|
54
|
-
await fh.writeFile(content, "utf8");
|
|
55
|
-
await fh.close();
|
|
56
|
-
return true;
|
|
57
|
-
} catch (e) {
|
|
58
|
-
if ((e as NodeJS.ErrnoException).code === "EEXIST") return false;
|
|
59
|
-
throw e;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export const nowIso = () => new Date().toISOString();
|
|
64
|
-
|
|
65
|
-
export function slugify(s: string): string {
|
|
66
|
-
return (
|
|
67
|
-
s
|
|
68
|
-
.toLowerCase()
|
|
69
|
-
.normalize("NFKC")
|
|
70
|
-
.replace(/[^a-z0-9]+/g, "-")
|
|
71
|
-
.replace(/^-+|-+$/g, "")
|
|
72
|
-
.slice(0, 40)
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const BASE32 = "0123456789abcdefghjkmnpqrstvwxyz"; // Crockford(i l o u を除く)
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* 要望の ID(= フォルダ名)。作成日 + 乱数5文字(例: 261009-k7m3x)。
|
|
80
|
-
* 時刻順に並び、人が読み書きでき、複数人が同時に作っても実用上衝突しない(1日あたり約3,300万通り)。
|
|
81
|
-
* タイトルは後から変わるので含めない。
|
|
82
|
-
*/
|
|
83
|
-
export function newRequestId(now = new Date()): string {
|
|
84
|
-
// 作った人の日付(ローカル時刻)で付ける
|
|
85
|
-
const p2 = (n: number) => String(n).padStart(2, "0");
|
|
86
|
-
const d = `${p2(now.getFullYear() % 100)}${p2(now.getMonth() + 1)}${p2(now.getDate())}`;
|
|
87
|
-
let rand = "";
|
|
88
|
-
for (let i = 0; i < 5; i++) rand += BASE32[randomInt(32)];
|
|
89
|
-
return `${d}-${rand}`;
|
|
90
|
-
}
|