@s-hirano-ist/s-scripts 4.1.0 → 4.3.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/README.md +8 -0
- package/dist/{chunk-7XX57D7G.js → chunk-3INTMHPH.js} +1 -1
- package/dist/chunk-4CXH2QIX.js +445 -0
- package/dist/chunk-67LIMNXH.js +36 -0
- package/dist/{chunk-OCEV2QX3.js → chunk-BYEEIQ7O.js} +1 -1
- package/dist/{chunk-2PZXXOYG.js → chunk-GBQOCN2C.js} +24 -25
- package/dist/chunk-MJYGMGH5.js +382 -0
- package/dist/chunk-MVYAZJB2.js +160 -0
- package/dist/{chunk-DIG75T3J.js → chunk-RLAYINCA.js} +10 -13
- package/dist/{chunk-MNBEFEFR.js → chunk-RO5QUZFR.js} +1 -1
- package/dist/chunk-SFKQ2RAP.js +87 -0
- package/dist/{chunk-FVK44UTM.js → chunk-ZMQUO6OA.js} +1 -1
- package/dist/cleanup-minio-images.js +62 -91
- package/dist/enrich-books.js +6 -4
- package/dist/fetch-articles.js +6 -24
- package/dist/fetch-books.js +12 -35
- package/dist/fetch-images.js +12 -35
- package/dist/fetch-notes.js +6 -24
- package/dist/find-duplicate-json-articles.js +11 -13
- package/dist/fix-book-frontmatter.js +6 -4
- package/dist/fix-image-formats.js +7 -5
- package/dist/ingest-articles.js +7 -5
- package/dist/ingest-books.js +10 -8
- package/dist/ingest-images.js +7 -5
- package/dist/ingest-notes.js +10 -8
- package/dist/rag/delete-collection.js +5 -30
- package/dist/rag/ingest.js +5 -379
- package/dist/rag/search.js +5 -84
- package/dist/reset-articles.js +8 -23
- package/dist/reset-books.js +8 -23
- package/dist/reset-images.js +8 -23
- package/dist/reset-notes.js +8 -23
- package/dist/revert-articles.js +8 -23
- package/dist/revert-books.js +8 -23
- package/dist/revert-images.js +8 -23
- package/dist/revert-notes.js +8 -23
- package/dist/s-content-format.js +9 -11
- package/dist/update-json-articles.js +19 -41
- package/dist/update-raw-articles.js +14 -37
- package/dist/validate-json-articles.js +8 -5
- package/package.json +13 -11
- package/dist/chunk-7PVU2Z32.js +0 -71
- package/dist/chunk-F4J6JBR4.js +0 -115
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { createRequire as __cliCreateRequire } from "node:module"; const require = __cliCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
RAG_CONFIG,
|
|
4
|
+
deletePointsByChunkIds,
|
|
5
|
+
ensureCollection,
|
|
6
|
+
getCollectionStats,
|
|
7
|
+
getExistingHashes,
|
|
8
|
+
listAllChunkIds,
|
|
9
|
+
upsertPoints
|
|
10
|
+
} from "./chunk-J4VLH4VA.js";
|
|
11
|
+
import {
|
|
12
|
+
parseMarkdownFrontmatter
|
|
13
|
+
} from "./chunk-HDYQV2Y2.js";
|
|
14
|
+
import {
|
|
15
|
+
globPaths
|
|
16
|
+
} from "./chunk-AJMTRCPJ.js";
|
|
17
|
+
import {
|
|
18
|
+
reportCliError
|
|
19
|
+
} from "./chunk-4CXH2QIX.js";
|
|
20
|
+
import "./chunk-JZOR5GA2.js";
|
|
21
|
+
|
|
22
|
+
// ../search/dist/chunker.js
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
24
|
+
function generateHash(content) {
|
|
25
|
+
return createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
26
|
+
}
|
|
27
|
+
function generateChunkId(docId, index) {
|
|
28
|
+
return `${docId}#${index}`;
|
|
29
|
+
}
|
|
30
|
+
function parseJsonArticle(filePath, content) {
|
|
31
|
+
const json = JSON.parse(content);
|
|
32
|
+
const docId = `file:${filePath}`;
|
|
33
|
+
const chunks = [];
|
|
34
|
+
for (let i = 0; i < json.body.length; i++) {
|
|
35
|
+
const item = json.body[i];
|
|
36
|
+
const textParts = [];
|
|
37
|
+
if (item.title)
|
|
38
|
+
textParts.push(item.title);
|
|
39
|
+
if (item.ogTitle && item.ogTitle !== item.title)
|
|
40
|
+
textParts.push(item.ogTitle);
|
|
41
|
+
if (item.ogDescription)
|
|
42
|
+
textParts.push(item.ogDescription);
|
|
43
|
+
if (item.quote)
|
|
44
|
+
textParts.push(item.quote);
|
|
45
|
+
const text = textParts.join("\n");
|
|
46
|
+
if (!text.trim())
|
|
47
|
+
continue;
|
|
48
|
+
const chunkId = generateChunkId(docId, i);
|
|
49
|
+
chunks.push({
|
|
50
|
+
type: "bookmark_json",
|
|
51
|
+
content_type: "articles",
|
|
52
|
+
top_heading: json.heading,
|
|
53
|
+
doc_id: docId,
|
|
54
|
+
chunk_id: chunkId,
|
|
55
|
+
title: item.title || item.ogTitle || "Untitled",
|
|
56
|
+
url: item.url,
|
|
57
|
+
heading_path: [json.heading],
|
|
58
|
+
text,
|
|
59
|
+
content_hash: generateHash(text)
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return chunks;
|
|
63
|
+
}
|
|
64
|
+
function parseFrontmatter(content) {
|
|
65
|
+
const parsed = parseMarkdownFrontmatter(content);
|
|
66
|
+
const frontmatter = {
|
|
67
|
+
heading: typeof parsed.data.heading === "string" ? parsed.data.heading : "unknown"
|
|
68
|
+
};
|
|
69
|
+
if (typeof parsed.data.description === "string") {
|
|
70
|
+
frontmatter.description = parsed.data.description;
|
|
71
|
+
}
|
|
72
|
+
if (typeof parsed.data.draft === "boolean") {
|
|
73
|
+
frontmatter.draft = parsed.data.draft;
|
|
74
|
+
}
|
|
75
|
+
return { frontmatter, body: parsed.content };
|
|
76
|
+
}
|
|
77
|
+
function pushPreambleSection(state) {
|
|
78
|
+
if (state.preambleContent.trim()) {
|
|
79
|
+
state.sections.push({
|
|
80
|
+
headingPath: [],
|
|
81
|
+
title: "",
|
|
82
|
+
content: state.preambleContent,
|
|
83
|
+
level: 0
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function handleHeadingLine(state, headingMatch) {
|
|
88
|
+
if (!state.preambleDone) {
|
|
89
|
+
state.preambleDone = true;
|
|
90
|
+
pushPreambleSection(state);
|
|
91
|
+
}
|
|
92
|
+
if (state.currentSection?.content.trim()) {
|
|
93
|
+
state.sections.push(state.currentSection);
|
|
94
|
+
}
|
|
95
|
+
const level = headingMatch[1].length;
|
|
96
|
+
const title = headingMatch[2];
|
|
97
|
+
const headingStack = state.headingStack;
|
|
98
|
+
let top = headingStack.at(-1);
|
|
99
|
+
while (top && top.level >= level) {
|
|
100
|
+
headingStack.pop();
|
|
101
|
+
top = headingStack.at(-1);
|
|
102
|
+
}
|
|
103
|
+
headingStack.push({ level, title });
|
|
104
|
+
state.currentSection = {
|
|
105
|
+
headingPath: headingStack.map((h) => h.title),
|
|
106
|
+
title,
|
|
107
|
+
content: "",
|
|
108
|
+
level
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function splitMarkdownByHeadings(content) {
|
|
112
|
+
const state = {
|
|
113
|
+
sections: [],
|
|
114
|
+
currentSection: null,
|
|
115
|
+
headingStack: [],
|
|
116
|
+
// Preamble buffer (content before first H2/H3)
|
|
117
|
+
preambleContent: "",
|
|
118
|
+
preambleDone: false
|
|
119
|
+
};
|
|
120
|
+
for (const line of content.split("\n")) {
|
|
121
|
+
if (/^#\s+\S/u.test(line)) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const headingMatch = /^(#{2,3})\s+(\S.*)$/u.exec(line);
|
|
125
|
+
if (headingMatch) {
|
|
126
|
+
handleHeadingLine(state, headingMatch);
|
|
127
|
+
} else if (!state.preambleDone) {
|
|
128
|
+
state.preambleContent += `${line}
|
|
129
|
+
`;
|
|
130
|
+
} else if (state.currentSection) {
|
|
131
|
+
state.currentSection.content += `${line}
|
|
132
|
+
`;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (!state.preambleDone) {
|
|
136
|
+
pushPreambleSection(state);
|
|
137
|
+
}
|
|
138
|
+
if (state.currentSection?.content.trim()) {
|
|
139
|
+
state.sections.push(state.currentSection);
|
|
140
|
+
}
|
|
141
|
+
return state.sections;
|
|
142
|
+
}
|
|
143
|
+
function splitByParagraphs(text, maxLength) {
|
|
144
|
+
if (text.length <= maxLength) {
|
|
145
|
+
return [text];
|
|
146
|
+
}
|
|
147
|
+
const paragraphs = text.split(/\n{2,}/u);
|
|
148
|
+
const chunks = [];
|
|
149
|
+
let currentChunk = "";
|
|
150
|
+
for (const para of paragraphs) {
|
|
151
|
+
if (currentChunk.length + para.length > maxLength && currentChunk) {
|
|
152
|
+
chunks.push(currentChunk.trim());
|
|
153
|
+
currentChunk = para;
|
|
154
|
+
} else {
|
|
155
|
+
currentChunk += (currentChunk ? "\n\n" : "") + para;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (currentChunk.trim()) {
|
|
159
|
+
chunks.push(currentChunk.trim());
|
|
160
|
+
}
|
|
161
|
+
return chunks;
|
|
162
|
+
}
|
|
163
|
+
function parseMarkdownWithDocId(docId, content, contentType = "notes") {
|
|
164
|
+
const { frontmatter, body } = parseFrontmatter(content);
|
|
165
|
+
const chunks = [];
|
|
166
|
+
if (frontmatter.draft) {
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
const sections = splitMarkdownByHeadings(body);
|
|
170
|
+
let chunkIndex = 0;
|
|
171
|
+
for (const section of sections) {
|
|
172
|
+
const textChunks = splitByParagraphs(section.content, RAG_CONFIG.chunking.maxChunkLength);
|
|
173
|
+
for (const text of textChunks) {
|
|
174
|
+
if (!text.trim())
|
|
175
|
+
continue;
|
|
176
|
+
const isPreamble = section.level === 0 && section.title === "";
|
|
177
|
+
const sectionTitle = isPreamble ? frontmatter.description ?? frontmatter.heading : section.title;
|
|
178
|
+
const fullHeadingPath = isPreamble ? [frontmatter.heading] : [frontmatter.heading, ...section.headingPath];
|
|
179
|
+
const chunkId = generateChunkId(docId, chunkIndex);
|
|
180
|
+
chunks.push({
|
|
181
|
+
type: "markdown_note",
|
|
182
|
+
content_type: contentType,
|
|
183
|
+
top_heading: frontmatter.heading,
|
|
184
|
+
doc_id: docId,
|
|
185
|
+
chunk_id: chunkId,
|
|
186
|
+
title: sectionTitle,
|
|
187
|
+
heading_path: fullHeadingPath,
|
|
188
|
+
text,
|
|
189
|
+
content_hash: generateHash(text)
|
|
190
|
+
});
|
|
191
|
+
chunkIndex++;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return chunks;
|
|
195
|
+
}
|
|
196
|
+
function parseMarkdown(filePath, content, contentType = "notes") {
|
|
197
|
+
return parseMarkdownWithDocId(`file:${filePath}`, content, contentType);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ../search/dist/ingest.js
|
|
201
|
+
import { setTimeout } from "node:timers/promises";
|
|
202
|
+
var BATCH_SIZE = 20;
|
|
203
|
+
var MAX_RETRIES = 3;
|
|
204
|
+
var RETRY_DELAY_MS = 2e3;
|
|
205
|
+
async function withRetry(fn, retries = MAX_RETRIES) {
|
|
206
|
+
for (let i = 0; i < retries; i++) {
|
|
207
|
+
try {
|
|
208
|
+
return await fn();
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (i === retries - 1)
|
|
211
|
+
throw error;
|
|
212
|
+
console.log(` Retry ${i + 1}/${retries} after error...`);
|
|
213
|
+
await setTimeout(RETRY_DELAY_MS);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
throw new Error("Unreachable");
|
|
217
|
+
}
|
|
218
|
+
async function ingestChunks(chunks, options) {
|
|
219
|
+
console.log(`Total chunks: ${chunks.length}
|
|
220
|
+
`);
|
|
221
|
+
let changedChunks;
|
|
222
|
+
let skippedChunks;
|
|
223
|
+
if (options.force) {
|
|
224
|
+
changedChunks = chunks;
|
|
225
|
+
skippedChunks = 0;
|
|
226
|
+
} else {
|
|
227
|
+
console.log("Checking for changes...");
|
|
228
|
+
const chunkIds = chunks.map((c) => c.chunk_id);
|
|
229
|
+
const existingHashes = await getExistingHashes(chunkIds);
|
|
230
|
+
changedChunks = chunks.filter((chunk) => {
|
|
231
|
+
const existingHash = existingHashes.get(chunk.chunk_id);
|
|
232
|
+
return existingHash !== chunk.content_hash;
|
|
233
|
+
});
|
|
234
|
+
skippedChunks = chunks.length - changedChunks.length;
|
|
235
|
+
}
|
|
236
|
+
console.log(`Changed chunks: ${changedChunks.length}`);
|
|
237
|
+
console.log(`Skipped (unchanged): ${skippedChunks}
|
|
238
|
+
`);
|
|
239
|
+
if (changedChunks.length === 0) {
|
|
240
|
+
console.log("No changes detected. Done!");
|
|
241
|
+
return {
|
|
242
|
+
totalChunks: chunks.length,
|
|
243
|
+
changedChunks: 0,
|
|
244
|
+
skippedChunks
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
console.log("Upserting to Qdrant...");
|
|
248
|
+
let processed = 0;
|
|
249
|
+
for (let i = 0; i < changedChunks.length; i += BATCH_SIZE) {
|
|
250
|
+
const batch = changedChunks.slice(i, i + BATCH_SIZE);
|
|
251
|
+
const points = batch.map((chunk) => ({
|
|
252
|
+
id: chunk.chunk_id,
|
|
253
|
+
text: chunk.text,
|
|
254
|
+
payload: chunk
|
|
255
|
+
}));
|
|
256
|
+
await withRetry(() => upsertPoints(points));
|
|
257
|
+
processed += batch.length;
|
|
258
|
+
console.log(` Progress: ${processed}/${changedChunks.length}`);
|
|
259
|
+
await setTimeout(100);
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
totalChunks: chunks.length,
|
|
263
|
+
changedChunks: changedChunks.length,
|
|
264
|
+
skippedChunks
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
async function pruneOrphans(currentChunkIds) {
|
|
268
|
+
const existingIds = await listAllChunkIds();
|
|
269
|
+
const currentSet = new Set(currentChunkIds);
|
|
270
|
+
const orphanIds = existingIds.filter((id) => !currentSet.has(id));
|
|
271
|
+
console.log(`Existing Qdrant chunks: ${existingIds.length}`);
|
|
272
|
+
console.log(`Orphan chunks to delete: ${orphanIds.length}`);
|
|
273
|
+
if (orphanIds.length === 0) {
|
|
274
|
+
return { deletedCount: 0 };
|
|
275
|
+
}
|
|
276
|
+
let deleted = 0;
|
|
277
|
+
for (let i = 0; i < orphanIds.length; i += BATCH_SIZE) {
|
|
278
|
+
const batch = orphanIds.slice(i, i + BATCH_SIZE);
|
|
279
|
+
await withRetry(() => deletePointsByChunkIds(batch));
|
|
280
|
+
deleted += batch.length;
|
|
281
|
+
console.log(` Prune progress: ${deleted}/${orphanIds.length}`);
|
|
282
|
+
await setTimeout(100);
|
|
283
|
+
}
|
|
284
|
+
return { deletedCount: deleted };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// src/rag/ingest-command.ts
|
|
288
|
+
import { readFileSync } from "node:fs";
|
|
289
|
+
|
|
290
|
+
// src/rag/ingest-config.ts
|
|
291
|
+
var INGEST_CONFIG = {
|
|
292
|
+
paths: {
|
|
293
|
+
notes: "markdown/note/**/*.md",
|
|
294
|
+
books: "markdown/book/**/*.md",
|
|
295
|
+
articles: "json/article/**/*.json"
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
// src/rag/ingest-command.ts
|
|
300
|
+
async function listFiles() {
|
|
301
|
+
const files = [];
|
|
302
|
+
const articleFiles = await globPaths(INGEST_CONFIG.paths.articles);
|
|
303
|
+
for (const path of articleFiles) {
|
|
304
|
+
files.push({ path, type: "json", contentType: "articles" });
|
|
305
|
+
}
|
|
306
|
+
const noteFiles = await globPaths(INGEST_CONFIG.paths.notes);
|
|
307
|
+
for (const path of noteFiles) {
|
|
308
|
+
files.push({ path, type: "markdown", contentType: "notes" });
|
|
309
|
+
}
|
|
310
|
+
const bookFiles = await globPaths(INGEST_CONFIG.paths.books);
|
|
311
|
+
for (const path of bookFiles) {
|
|
312
|
+
files.push({ path, type: "markdown", contentType: "books" });
|
|
313
|
+
}
|
|
314
|
+
return files;
|
|
315
|
+
}
|
|
316
|
+
function parseFile(file) {
|
|
317
|
+
const content = readFileSync(file.path, "utf-8");
|
|
318
|
+
if (file.type === "json") {
|
|
319
|
+
return parseJsonArticle(file.path, content);
|
|
320
|
+
}
|
|
321
|
+
return parseMarkdown(file.path, content, file.contentType);
|
|
322
|
+
}
|
|
323
|
+
async function ingest(flags) {
|
|
324
|
+
console.log("Starting ingest...\n");
|
|
325
|
+
if (flags.dryRun) {
|
|
326
|
+
console.log("Dry-run mode: no writes to Qdrant\n");
|
|
327
|
+
} else {
|
|
328
|
+
await ensureCollection();
|
|
329
|
+
const initialStats = await getCollectionStats();
|
|
330
|
+
console.log(`Initial points count: ${initialStats.pointsCount}
|
|
331
|
+
`);
|
|
332
|
+
}
|
|
333
|
+
if (flags.force) {
|
|
334
|
+
console.log("Force mode enabled: skipping change detection\n");
|
|
335
|
+
}
|
|
336
|
+
const files = await listFiles();
|
|
337
|
+
const articleCount = files.filter((f) => f.contentType === "articles").length;
|
|
338
|
+
const noteCount = files.filter((f) => f.contentType === "notes").length;
|
|
339
|
+
const bookCount = files.filter((f) => f.contentType === "books").length;
|
|
340
|
+
console.log(`Found ${files.length} files to process`);
|
|
341
|
+
console.log(` - Articles: ${articleCount}`);
|
|
342
|
+
console.log(` - Notes: ${noteCount}`);
|
|
343
|
+
console.log(` - Books: ${bookCount}
|
|
344
|
+
`);
|
|
345
|
+
console.log("Parsing files...");
|
|
346
|
+
const allChunks = [];
|
|
347
|
+
for (const file of files) {
|
|
348
|
+
try {
|
|
349
|
+
const chunks = parseFile(file);
|
|
350
|
+
allChunks.push(...chunks);
|
|
351
|
+
} catch (error) {
|
|
352
|
+
reportCliError(error, "rag-ingest");
|
|
353
|
+
console.error(`Error parsing ${file.path}:`, error);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
console.log(`Total chunks parsed: ${allChunks.length}`);
|
|
357
|
+
if (flags.dryRun) {
|
|
358
|
+
console.log("Dry-run complete. Skipping upsert and prune.");
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const result = await ingestChunks(allChunks, { force: flags.force });
|
|
362
|
+
const pruneResult = await pruneOrphans(allChunks.map((c) => c.chunk_id));
|
|
363
|
+
const finalStats = await getCollectionStats();
|
|
364
|
+
console.log(`
|
|
365
|
+
Final points count: ${finalStats.pointsCount}`);
|
|
366
|
+
console.log(
|
|
367
|
+
`Ingest completed! (${result.changedChunks} changed, ${result.skippedChunks} skipped, ${pruneResult.deletedCount} pruned)`
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
async function main() {
|
|
371
|
+
if (!process.env.QDRANT_URL) {
|
|
372
|
+
throw new Error("QDRANT_URL environment variable is required.");
|
|
373
|
+
}
|
|
374
|
+
const flags = {
|
|
375
|
+
force: process.argv.includes("--force"),
|
|
376
|
+
dryRun: process.argv.includes("--dry-run")
|
|
377
|
+
};
|
|
378
|
+
await ingest(flags);
|
|
379
|
+
}
|
|
380
|
+
export {
|
|
381
|
+
main
|
|
382
|
+
};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { createRequire as __cliCreateRequire } from "node:module"; const require = __cliCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// ../storage/dist/src/client.js
|
|
4
|
+
import { S3Client, CreateBucketCommand, DeleteBucketCommand, PutObjectCommand, GetObjectCommand, HeadObjectCommand, DeleteObjectCommand, paginateListObjectsV2 } from "@aws-sdk/client-s3";
|
|
5
|
+
import { createWriteStream } from "node:fs";
|
|
6
|
+
import { Readable } from "node:stream";
|
|
7
|
+
import { pipeline } from "node:stream/promises";
|
|
8
|
+
function loadStorageConfig(env = process.env) {
|
|
9
|
+
const required = (key) => {
|
|
10
|
+
const value = env[key];
|
|
11
|
+
if (!value)
|
|
12
|
+
throw new Error(`${key} is required`);
|
|
13
|
+
return value;
|
|
14
|
+
};
|
|
15
|
+
const endpoint = required("S3_ENDPOINT");
|
|
16
|
+
const url = new URL(endpoint);
|
|
17
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/")
|
|
18
|
+
throw new Error("S3_ENDPOINT must be an HTTP(S) origin");
|
|
19
|
+
const pathStyle = env.S3_FORCE_PATH_STYLE ?? "false";
|
|
20
|
+
if (pathStyle !== "true" && pathStyle !== "false")
|
|
21
|
+
throw new Error("S3_FORCE_PATH_STYLE must be true or false");
|
|
22
|
+
return {
|
|
23
|
+
endpoint,
|
|
24
|
+
region: required("S3_REGION"),
|
|
25
|
+
accessKeyId: required("S3_ACCESS_KEY_ID"),
|
|
26
|
+
secretAccessKey: required("S3_SECRET_ACCESS_KEY"),
|
|
27
|
+
forcePathStyle: pathStyle === "true"
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function isObjectNotFound(error) {
|
|
31
|
+
if (typeof error !== "object" || error === null)
|
|
32
|
+
return false;
|
|
33
|
+
const value = error;
|
|
34
|
+
return value.$metadata?.httpStatusCode === 404 && (value.name === "NotFound" || value.name === "NoSuchKey");
|
|
35
|
+
}
|
|
36
|
+
function createObjectStorageClient(config = loadStorageConfig()) {
|
|
37
|
+
const client = new S3Client({
|
|
38
|
+
endpoint: config.endpoint,
|
|
39
|
+
region: config.region,
|
|
40
|
+
credentials: {
|
|
41
|
+
accessKeyId: config.accessKeyId,
|
|
42
|
+
secretAccessKey: config.secretAccessKey
|
|
43
|
+
},
|
|
44
|
+
forcePathStyle: config.forcePathStyle
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
async createBucket(bucket) {
|
|
48
|
+
await client.send(new CreateBucketCommand({ Bucket: bucket }));
|
|
49
|
+
},
|
|
50
|
+
async deleteBucket(bucket) {
|
|
51
|
+
await client.send(new DeleteBucketCommand({ Bucket: bucket }));
|
|
52
|
+
},
|
|
53
|
+
async putObject(bucket, key, body) {
|
|
54
|
+
const result = await client.send(new PutObjectCommand({ Bucket: bucket, Key: key, Body: body }));
|
|
55
|
+
return { etag: result.ETag, versionId: result.VersionId };
|
|
56
|
+
},
|
|
57
|
+
async getObject(bucket, key) {
|
|
58
|
+
const result = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
|
|
59
|
+
if (!(result.Body instanceof Readable))
|
|
60
|
+
throw new TypeError("Object storage returned no Node readable body");
|
|
61
|
+
return result.Body;
|
|
62
|
+
},
|
|
63
|
+
async downloadObject(bucket, key, destination) {
|
|
64
|
+
const result = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
|
|
65
|
+
if (!(result.Body instanceof Readable))
|
|
66
|
+
throw new TypeError("Object storage returned no Node readable body");
|
|
67
|
+
await pipeline(result.Body, createWriteStream(destination));
|
|
68
|
+
},
|
|
69
|
+
async statObject(bucket, key) {
|
|
70
|
+
const result = await client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
|
|
71
|
+
return {
|
|
72
|
+
size: result.ContentLength,
|
|
73
|
+
etag: result.ETag,
|
|
74
|
+
lastModified: result.LastModified,
|
|
75
|
+
metaData: result.Metadata ?? {}
|
|
76
|
+
};
|
|
77
|
+
},
|
|
78
|
+
async removeObject(bucket, key) {
|
|
79
|
+
await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
|
|
80
|
+
},
|
|
81
|
+
async listObjects(bucket, prefix) {
|
|
82
|
+
const keys = [];
|
|
83
|
+
for await (const page of paginateListObjectsV2({ client }, { Bucket: bucket, Prefix: prefix })) {
|
|
84
|
+
for (const object of page.Contents ?? [])
|
|
85
|
+
if (object.Key)
|
|
86
|
+
keys.push(object.Key);
|
|
87
|
+
}
|
|
88
|
+
return keys;
|
|
89
|
+
},
|
|
90
|
+
destroy() {
|
|
91
|
+
client.destroy();
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ../storage/dist/index.js
|
|
97
|
+
import { S3ServiceException } from "@aws-sdk/client-s3";
|
|
98
|
+
|
|
99
|
+
// ../storage/dist/src/errors.js
|
|
100
|
+
var StorageOperationError = class extends Error {
|
|
101
|
+
context;
|
|
102
|
+
constructor(context, cause) {
|
|
103
|
+
super(`Storage ${context.operation} failed for ${context.objectKey}`, {
|
|
104
|
+
cause
|
|
105
|
+
});
|
|
106
|
+
this.name = "StorageOperationError";
|
|
107
|
+
this.context = context;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// ../storage/dist/src/storage-service.js
|
|
112
|
+
function createStorageService(client, bucketName, pathConfig) {
|
|
113
|
+
function buildObjectKey(path, isThumbnail) {
|
|
114
|
+
return `${isThumbnail ? pathConfig.thumbnailPrefix : pathConfig.originalPrefix}/${path}`;
|
|
115
|
+
}
|
|
116
|
+
function wrapStorageError(operation, objectKey, isThumbnail, error) {
|
|
117
|
+
throw new StorageOperationError({ operation, objectKey, bucketName, isThumbnail }, error);
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
async uploadImage(path, bytes, isThumbnail) {
|
|
121
|
+
const objKey = buildObjectKey(path, isThumbnail);
|
|
122
|
+
try {
|
|
123
|
+
await client.putObject(bucketName, objKey, Buffer.from(bytes));
|
|
124
|
+
} catch (error) {
|
|
125
|
+
wrapStorageError("uploadImage", objKey, isThumbnail, error);
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
async getImage(path, isThumbnail) {
|
|
129
|
+
const objKey = buildObjectKey(path, isThumbnail);
|
|
130
|
+
try {
|
|
131
|
+
return await client.getObject(bucketName, objKey);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return wrapStorageError("getImage", objKey, isThumbnail, error);
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
async getImageOrThrow(path, isThumbnail) {
|
|
137
|
+
const objKey = buildObjectKey(path, isThumbnail);
|
|
138
|
+
try {
|
|
139
|
+
await client.statObject(bucketName, objKey);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
wrapStorageError("getImageOrThrow", objKey, isThumbnail, error);
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
async deleteImage(path, isThumbnail) {
|
|
145
|
+
const objKey = buildObjectKey(path, isThumbnail);
|
|
146
|
+
try {
|
|
147
|
+
await client.removeObject(bucketName, objKey);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
wrapStorageError("deleteImage", objKey, isThumbnail, error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export {
|
|
156
|
+
isObjectNotFound,
|
|
157
|
+
createObjectStorageClient,
|
|
158
|
+
StorageOperationError,
|
|
159
|
+
createStorageService
|
|
160
|
+
};
|