@c-time/frelio-data-json-generator 1.0.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/dist/index.js ADDED
@@ -0,0 +1,1385 @@
1
+ import { findAffectedOutputs } from '@c-time/frelio-dependency-map';
2
+ import { readFile } from 'fs/promises';
3
+ import { existsSync } from 'fs';
4
+ import { glob } from 'glob';
5
+ import { exec } from 'child_process';
6
+ import { promisify } from 'util';
7
+
8
+ // src/scope/change-detector.ts
9
+ function isContentPath(path) {
10
+ return /^contents\/(published|private)\//.test(path);
11
+ }
12
+ function isPartsPath(path) {
13
+ return /^templates\/(partials\/|_)/.test(path);
14
+ }
15
+ function isTemplatePath(path) {
16
+ return path.startsWith("templates/") && !isPartsPath(path);
17
+ }
18
+ function isContentTypePath(path) {
19
+ return /^content_types\/[^/]+\.json$/.test(path);
20
+ }
21
+ function classifyChangedFiles(gitDiff) {
22
+ const result = {
23
+ contents: { added: [], modified: [], deleted: [] },
24
+ templates: { added: [], modified: [], deleted: [] },
25
+ contentTypes: { added: [], modified: [], deleted: [] },
26
+ parts: { added: [], modified: [], deleted: [] }
27
+ };
28
+ const classify = (path, target) => {
29
+ if (isContentPath(path)) {
30
+ result.contents[target].push(path);
31
+ } else if (isPartsPath(path)) {
32
+ result.parts[target].push(path);
33
+ } else if (isTemplatePath(path)) {
34
+ result.templates[target].push(path);
35
+ } else if (isContentTypePath(path)) {
36
+ result.contentTypes[target].push(path);
37
+ }
38
+ };
39
+ for (const path of gitDiff.added) {
40
+ classify(path, "added");
41
+ }
42
+ for (const path of gitDiff.modified) {
43
+ classify(path, "modified");
44
+ }
45
+ for (const path of gitDiff.deleted) {
46
+ classify(path, "deleted");
47
+ }
48
+ return result;
49
+ }
50
+
51
+ // src/utils/path-utils.ts
52
+ var FORBIDDEN_PATTERNS = [
53
+ /\.\./,
54
+ // 親ディレクトリ参照
55
+ /\\/,
56
+ // バックスラッシュ
57
+ /^\/|^\\/,
58
+ // 先頭のスラッシュ
59
+ /\0/
60
+ // NULL文字
61
+ ];
62
+ function validateOutputPath(path) {
63
+ if (!path || path.trim() === "") {
64
+ return {
65
+ code: "INVALID_OUTPUT_PATH",
66
+ outputPath: path,
67
+ message: "\u51FA\u529B\u30D1\u30B9\u304C\u7A7A\u3067\u3059"
68
+ };
69
+ }
70
+ for (const pattern of FORBIDDEN_PATTERNS) {
71
+ if (pattern.test(path)) {
72
+ return {
73
+ code: "INVALID_OUTPUT_PATH",
74
+ outputPath: path,
75
+ message: `\u51FA\u529B\u30D1\u30B9\u306B\u7981\u6B62\u6587\u5B57\u304C\u542B\u307E\u308C\u3066\u3044\u307E\u3059: ${path}`
76
+ };
77
+ }
78
+ }
79
+ if (/\{\$[^}]+\}/.test(path)) {
80
+ return {
81
+ code: "INVALID_TEMPLATE_VAR",
82
+ outputPath: path,
83
+ message: `\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u5909\u6570\u304C\u89E3\u6C7A\u3055\u308C\u3066\u3044\u307E\u305B\u3093: ${path}`
84
+ };
85
+ }
86
+ return null;
87
+ }
88
+ function sanitizePath(path) {
89
+ return path.replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, "").trim();
90
+ }
91
+ function extractContentIdFromPath(path) {
92
+ const match = path.match(/contents\/[^/]+\/[^/]+\/([^/]+)\.json$/);
93
+ return match ? match[1] : null;
94
+ }
95
+
96
+ // src/utils/glob-matcher.ts
97
+ function matchGlob(pattern, path) {
98
+ if (pattern === path) {
99
+ return true;
100
+ }
101
+ const regexPattern = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "\0GLOBSTAR\0").replace(/\*/g, "[^/]*").replace(/\0GLOBSTAR\0/g, ".*");
102
+ try {
103
+ const regex = new RegExp(`^${regexPattern}$`);
104
+ return regex.test(path);
105
+ } catch {
106
+ return pattern === path;
107
+ }
108
+ }
109
+
110
+ // src/scope/parts-expander.ts
111
+ function expandPartsAffectedScope(changedParts, templateIncludes, dependencyMap) {
112
+ if (!templateIncludes) {
113
+ return [];
114
+ }
115
+ const targets = [];
116
+ const seenOutputPaths = /* @__PURE__ */ new Set();
117
+ for (const partsPath of changedParts) {
118
+ const relativePath = partsPath.startsWith("templates/") ? partsPath.slice("templates/".length) : partsPath;
119
+ for (const [partsPattern, affectedTemplates] of Object.entries(templateIncludes)) {
120
+ if (!matchGlob(partsPattern, relativePath)) {
121
+ continue;
122
+ }
123
+ if (affectedTemplates.includes("*")) {
124
+ for (const outputPath of Object.keys(dependencyMap)) {
125
+ if (!seenOutputPaths.has(outputPath)) {
126
+ seenOutputPaths.add(outputPath);
127
+ targets.push({
128
+ outputPath,
129
+ reason: "parts_changed"
130
+ });
131
+ }
132
+ }
133
+ } else {
134
+ for (const templatePath of affectedTemplates) {
135
+ const depPath = `templates/${templatePath}`;
136
+ const affected = findAffectedOutputs(dependencyMap, depPath);
137
+ for (const outputPath of affected) {
138
+ if (!seenOutputPaths.has(outputPath)) {
139
+ seenOutputPaths.add(outputPath);
140
+ targets.push({
141
+ outputPath,
142
+ reason: "parts_changed"
143
+ });
144
+ }
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ return targets;
151
+ }
152
+
153
+ // src/scope/scope-calculator.ts
154
+ function calculateRegenerationScope(changes, dependencyMap, recipe) {
155
+ const targets = [];
156
+ const seenOutputPaths = /* @__PURE__ */ new Set();
157
+ const addTarget = (target) => {
158
+ const key = `${target.outputPath}:${target.contentId ?? ""}`;
159
+ if (!seenOutputPaths.has(key)) {
160
+ seenOutputPaths.add(key);
161
+ targets.push(target);
162
+ }
163
+ };
164
+ for (const contentPath of [...changes.contents.added, ...changes.contents.modified]) {
165
+ const affected = findAffectedOutputs(dependencyMap, contentPath);
166
+ const contentId = extractContentIdFromPath(contentPath) ?? void 0;
167
+ for (const outputPath of affected) {
168
+ addTarget({
169
+ outputPath,
170
+ reason: "content_changed",
171
+ contentId
172
+ });
173
+ }
174
+ }
175
+ for (const templatePath of [...changes.templates.added, ...changes.templates.modified]) {
176
+ const depPath = templatePath.startsWith("templates/") ? templatePath : `templates/${templatePath}`;
177
+ const affected = findAffectedOutputs(dependencyMap, depPath);
178
+ for (const outputPath of affected) {
179
+ addTarget({
180
+ outputPath,
181
+ reason: "template_changed"
182
+ });
183
+ }
184
+ }
185
+ for (const ctPath of [...changes.contentTypes.added, ...changes.contentTypes.modified]) {
186
+ const affected = findAffectedOutputs(dependencyMap, ctPath);
187
+ for (const outputPath of affected) {
188
+ addTarget({
189
+ outputPath,
190
+ reason: "schema_changed"
191
+ });
192
+ }
193
+ }
194
+ const partsTargets = expandPartsAffectedScope(
195
+ [...changes.parts.added, ...changes.parts.modified],
196
+ recipe.templateIncludes,
197
+ dependencyMap
198
+ );
199
+ for (const target of partsTargets) {
200
+ addTarget(target);
201
+ }
202
+ for (const contentPath of changes.contents.deleted) {
203
+ const contentId = extractContentIdFromPath(contentPath) ?? void 0;
204
+ const affected = findAffectedOutputs(dependencyMap, contentPath);
205
+ for (const outputPath of affected) {
206
+ addTarget({
207
+ outputPath,
208
+ reason: "deleted",
209
+ contentId
210
+ });
211
+ }
212
+ }
213
+ return targets;
214
+ }
215
+ function getAllOutputPaths(dependencyMap) {
216
+ return Object.keys(dependencyMap).map((outputPath) => ({
217
+ outputPath,
218
+ reason: "full_rebuild"
219
+ }));
220
+ }
221
+
222
+ // src/content/content-loader.ts
223
+ var BATCH_SIZE = 50;
224
+ function parseContent(path, content) {
225
+ const json = JSON.parse(content);
226
+ const match = path.match(/contents\/[^/]+\/([^/]+)\/([^/]+)\.json$/);
227
+ const contentTypeId = match?.[1] ?? "unknown";
228
+ const contentId = match?.[2] ?? json.slug ?? "unknown";
229
+ return {
230
+ contentId,
231
+ contentTypeId,
232
+ slug: json.slug ?? contentId,
233
+ title: json.title ?? "",
234
+ status: json.status ?? "draft",
235
+ data: json.data ?? {},
236
+ createdAt: json.createdAt ?? "",
237
+ updatedAt: json.updatedAt ?? "",
238
+ publishedAt: json.publishedAt ?? null,
239
+ createdBy: json.createdBy ?? "",
240
+ filePath: path
241
+ };
242
+ }
243
+ async function loadContents(paths, fileSystem, logger) {
244
+ const results = [];
245
+ for (let i = 0; i < paths.length; i += BATCH_SIZE) {
246
+ const batch = paths.slice(i, i + BATCH_SIZE);
247
+ const batchResults = await Promise.all(
248
+ batch.map(async (path) => {
249
+ try {
250
+ const content = await fileSystem.readFile(path);
251
+ return parseContent(path, content);
252
+ } catch (error) {
253
+ logger.error(`Failed to load content: ${path}`, error);
254
+ return null;
255
+ }
256
+ })
257
+ );
258
+ results.push(...batchResults.filter((r) => r !== null));
259
+ }
260
+ return results;
261
+ }
262
+ async function loadContentsByType(contentTypeIds, contentRootPath, fileSystem, logger) {
263
+ const result = /* @__PURE__ */ new Map();
264
+ for (const contentTypeId of contentTypeIds) {
265
+ const pattern = `${contentRootPath}/contents/published/${contentTypeId}/*.json`;
266
+ const paths = await fileSystem.listFiles(pattern);
267
+ const contentPaths = paths.filter((p) => !p.includes("_index"));
268
+ logger.debug(`Loading ${contentPaths.length} contents for ${contentTypeId}`);
269
+ const contents = await loadContents(contentPaths, fileSystem, logger);
270
+ result.set(contentTypeId, contents);
271
+ }
272
+ return result;
273
+ }
274
+
275
+ // src/recipe/output-path-resolver.ts
276
+ function resolveOutputPath(template, content, pageNumber, numberFormatCount) {
277
+ let result = template;
278
+ if (pageNumber !== void 0) {
279
+ const pageStr = numberFormatCount ? pageNumber.toString().padStart(numberFormatCount, "0") : pageNumber.toString();
280
+ result = result.replace(/\{\$page\}/g, pageStr);
281
+ }
282
+ if (content) {
283
+ result = result.replace(/\{\$this\.([^}]+)\}/g, (_, key) => {
284
+ const value = getValueByKey(key, content);
285
+ if (value === void 0 || value === null) {
286
+ return `{$this.${key}}`;
287
+ }
288
+ return String(value);
289
+ });
290
+ }
291
+ return result;
292
+ }
293
+ function getValueByKey(key, content) {
294
+ if (key in content) {
295
+ return content[key];
296
+ }
297
+ if (content.data && key in content.data) {
298
+ return content.data[key];
299
+ }
300
+ const parts = key.split(".");
301
+ let value = content;
302
+ for (const part of parts) {
303
+ if (value === null || value === void 0) {
304
+ return void 0;
305
+ }
306
+ if (typeof value === "object") {
307
+ const obj = value;
308
+ if (part in obj) {
309
+ value = obj[part];
310
+ } else if ("data" in obj && typeof obj.data === "object" && obj.data !== null) {
311
+ const data = obj.data;
312
+ if (part in data) {
313
+ value = data[part];
314
+ } else {
315
+ return void 0;
316
+ }
317
+ } else {
318
+ return void 0;
319
+ }
320
+ } else {
321
+ return void 0;
322
+ }
323
+ }
324
+ return value;
325
+ }
326
+
327
+ // src/content/content-resolver.ts
328
+ async function resolveRelations(content, expand, context) {
329
+ if (!expand || expand.length === 0) {
330
+ return content.data;
331
+ }
332
+ const result = { ...content.data };
333
+ for (const expandConfig of expand) {
334
+ const fieldValue = content.data[expandConfig.field];
335
+ if (fieldValue === void 0 || fieldValue === null) {
336
+ continue;
337
+ }
338
+ if (Array.isArray(fieldValue)) {
339
+ const resolved = await resolveRelationArray(
340
+ fieldValue,
341
+ expandConfig,
342
+ context
343
+ );
344
+ result[expandConfig.field] = resolved;
345
+ } else if (typeof fieldValue === "string") {
346
+ const resolved = await resolveRelationSingle(
347
+ fieldValue,
348
+ expandConfig,
349
+ context
350
+ );
351
+ result[expandConfig.field] = resolved;
352
+ }
353
+ }
354
+ return result;
355
+ }
356
+ async function resolveRelationArray(ids, expandConfig, context) {
357
+ const results = [];
358
+ let targetIds = ids;
359
+ if (expandConfig.offset) {
360
+ targetIds = targetIds.slice(expandConfig.offset);
361
+ }
362
+ if (expandConfig.limit) {
363
+ targetIds = targetIds.slice(0, expandConfig.limit);
364
+ }
365
+ for (const id of targetIds) {
366
+ const resolved = await resolveRelationSingle(id, expandConfig, context);
367
+ if (resolved) {
368
+ results.push(resolved);
369
+ }
370
+ }
371
+ return results;
372
+ }
373
+ async function resolveRelationSingle(id, expandConfig, context) {
374
+ for (const [_, contents] of context.contentsByType) {
375
+ const found = contents.find((c) => c.contentId === id || c.slug === id);
376
+ if (found) {
377
+ let data = { ...found.data };
378
+ if (expandConfig.fields) {
379
+ const filtered = {};
380
+ for (const field of expandConfig.fields) {
381
+ if (field in data) {
382
+ filtered[field] = data[field];
383
+ }
384
+ }
385
+ filtered.contentId = found.contentId;
386
+ filtered.slug = found.slug;
387
+ filtered.title = found.title;
388
+ data = filtered;
389
+ }
390
+ if (expandConfig.expand) {
391
+ data = await resolveRelations(
392
+ { ...found, data },
393
+ expandConfig.expand,
394
+ context
395
+ );
396
+ }
397
+ return data;
398
+ }
399
+ }
400
+ context.errors.push({
401
+ code: "RELATION_NOT_FOUND",
402
+ field: expandConfig.field,
403
+ message: `\u30EA\u30EC\u30FC\u30B7\u30E7\u30F3\u5148\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${id}`
404
+ });
405
+ return null;
406
+ }
407
+
408
+ // src/transform/format-functions.ts
409
+ function formatValue(value, type, options = {}) {
410
+ if (value === void 0 || value === null) {
411
+ if (type === "default" && options.defaultValue !== void 0) {
412
+ return options.defaultValue;
413
+ }
414
+ return value;
415
+ }
416
+ switch (type) {
417
+ case "string":
418
+ return String(value);
419
+ case "date":
420
+ return formatDate(value, options.format);
421
+ case "number":
422
+ return formatNumber(value, options.format);
423
+ case "escape":
424
+ return escapeHtml(String(value));
425
+ case "toc":
426
+ return extractToc(String(value));
427
+ case "truncate":
428
+ return truncateString(String(value), options.length ?? 100, options.suffix ?? "...");
429
+ case "stripHtml":
430
+ return stripHtml(String(value));
431
+ case "slug":
432
+ return slugify(String(value));
433
+ case "lowercase":
434
+ return String(value).toLowerCase();
435
+ case "uppercase":
436
+ return String(value).toUpperCase();
437
+ case "default":
438
+ return value ?? options.defaultValue;
439
+ case "count":
440
+ return Array.isArray(value) ? value.length : 0;
441
+ case "first":
442
+ return Array.isArray(value) ? value[0] : value;
443
+ case "last":
444
+ return Array.isArray(value) ? value[value.length - 1] : value;
445
+ case "join":
446
+ return Array.isArray(value) ? value.join(options.separator ?? ", ") : String(value);
447
+ case "url":
448
+ return encodeURIComponent(String(value));
449
+ case "picture":
450
+ case "img":
451
+ case "srcset":
452
+ case "fileLink":
453
+ return value;
454
+ default:
455
+ return value;
456
+ }
457
+ }
458
+ function formatDate(value, format) {
459
+ const date = value instanceof Date ? value : new Date(String(value));
460
+ if (isNaN(date.getTime())) {
461
+ return String(value);
462
+ }
463
+ if (!format) {
464
+ return date.toISOString();
465
+ }
466
+ return format.replace(/YYYY/g, String(date.getFullYear())).replace(/MM/g, String(date.getMonth() + 1).padStart(2, "0")).replace(/DD/g, String(date.getDate()).padStart(2, "0")).replace(/HH/g, String(date.getHours()).padStart(2, "0")).replace(/mm/g, String(date.getMinutes()).padStart(2, "0")).replace(/ss/g, String(date.getSeconds()).padStart(2, "0"));
467
+ }
468
+ function formatNumber(value, format) {
469
+ const num = typeof value === "number" ? value : parseFloat(String(value));
470
+ if (isNaN(num)) {
471
+ return String(value);
472
+ }
473
+ if (!format) {
474
+ return String(num);
475
+ }
476
+ if (format.includes(",")) {
477
+ return num.toLocaleString();
478
+ }
479
+ return String(num);
480
+ }
481
+ function escapeHtml(str) {
482
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
483
+ }
484
+ function extractToc(html) {
485
+ const toc = [];
486
+ const regex = /<h([1-6])(?:\s+id="([^"]*)")?[^>]*>([^<]*)<\/h[1-6]>/gi;
487
+ let match;
488
+ while ((match = regex.exec(html)) !== null) {
489
+ const level = parseInt(match[1], 10);
490
+ const id = match[2] || slugify(match[3]);
491
+ const text = match[3].trim();
492
+ toc.push({ level, id, text });
493
+ }
494
+ return toc;
495
+ }
496
+ function truncateString(str, length, suffix) {
497
+ if (str.length <= length) {
498
+ return str;
499
+ }
500
+ return str.slice(0, length - suffix.length) + suffix;
501
+ }
502
+ function stripHtml(html) {
503
+ return html.replace(/<[^>]*>/g, "");
504
+ }
505
+ function slugify(str) {
506
+ return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
507
+ }
508
+
509
+ // src/content/content-filter.ts
510
+ function applyFilters(contents, filters) {
511
+ if (!filters || filters.length === 0) {
512
+ return contents;
513
+ }
514
+ return contents.filter((content) => {
515
+ for (const filter of filters) {
516
+ if (!matchesFilter(content, filter)) {
517
+ return false;
518
+ }
519
+ }
520
+ return true;
521
+ });
522
+ }
523
+ function matchesFilter(content, filter) {
524
+ const value = getFieldValue(content, filter.field);
525
+ switch (filter.operator) {
526
+ case "eq":
527
+ return value === filter.value;
528
+ case "neq":
529
+ return value !== filter.value;
530
+ case "gt":
531
+ return typeof value === "number" && typeof filter.value === "number" ? value > filter.value : false;
532
+ case "gte":
533
+ return typeof value === "number" && typeof filter.value === "number" ? value >= filter.value : false;
534
+ case "lt":
535
+ return typeof value === "number" && typeof filter.value === "number" ? value < filter.value : false;
536
+ case "lte":
537
+ return typeof value === "number" && typeof filter.value === "number" ? value <= filter.value : false;
538
+ case "in":
539
+ return Array.isArray(filter.value) && filter.value.includes(value);
540
+ case "nin":
541
+ return Array.isArray(filter.value) && !filter.value.includes(value);
542
+ case "regex":
543
+ return typeof value === "string" && typeof filter.value === "string" ? new RegExp(filter.value).test(value) : false;
544
+ case "isNull":
545
+ return value === null || value === void 0;
546
+ case "isNotNull":
547
+ return value !== null && value !== void 0;
548
+ default:
549
+ return true;
550
+ }
551
+ }
552
+ function getFieldValue(content, field) {
553
+ if (field in content) {
554
+ return content[field];
555
+ }
556
+ if (field in content.data) {
557
+ return content.data[field];
558
+ }
559
+ const parts = field.split(".");
560
+ let value = content;
561
+ for (const part of parts) {
562
+ if (value === null || value === void 0) {
563
+ return void 0;
564
+ }
565
+ value = value[part];
566
+ }
567
+ return value;
568
+ }
569
+ function applySort(contents, sort) {
570
+ if (!sort) {
571
+ return contents;
572
+ }
573
+ const sortArray = Array.isArray(sort) ? sort : [sort];
574
+ return [...contents].sort((a, b) => {
575
+ for (const s of sortArray) {
576
+ const valueA = getFieldValue(a, s.field);
577
+ const valueB = getFieldValue(b, s.field);
578
+ const comparison = compareValues(valueA, valueB);
579
+ if (comparison !== 0) {
580
+ return s.direction === "desc" ? -comparison : comparison;
581
+ }
582
+ }
583
+ return 0;
584
+ });
585
+ }
586
+ function compareValues(a, b) {
587
+ if (a === null || a === void 0) return 1;
588
+ if (b === null || b === void 0) return -1;
589
+ if (typeof a === "number" && typeof b === "number") {
590
+ return a - b;
591
+ }
592
+ if (typeof a === "string" && typeof b === "string") {
593
+ return a.localeCompare(b);
594
+ }
595
+ if (a instanceof Date && b instanceof Date) {
596
+ return a.getTime() - b.getTime();
597
+ }
598
+ if (typeof a === "string" && typeof b === "string") {
599
+ const dateA = Date.parse(a);
600
+ const dateB = Date.parse(b);
601
+ if (!isNaN(dateA) && !isNaN(dateB)) {
602
+ return dateA - dateB;
603
+ }
604
+ }
605
+ return 0;
606
+ }
607
+
608
+ // src/transform/relation-expander.ts
609
+ async function expandRelationList(field, content, context) {
610
+ let contents = context.contentsByType.get(field.contentTypeId) ?? [];
611
+ if (contents.length === 0) {
612
+ context.warnings.push({
613
+ code: "EMPTY_LIST",
614
+ outputPath: content.filePath,
615
+ message: `relationList: ${field.contentTypeId} \u306B\u30B3\u30F3\u30C6\u30F3\u30C4\u304C\u3042\u308A\u307E\u305B\u3093`
616
+ });
617
+ return [];
618
+ }
619
+ contents = applyFilters(contents, field.filters);
620
+ contents = applySort(contents, field.sort);
621
+ if (field.offset) {
622
+ contents = contents.slice(field.offset);
623
+ }
624
+ if (field.limit) {
625
+ contents = contents.slice(0, field.limit);
626
+ }
627
+ const results = [];
628
+ for (const c of contents) {
629
+ let data = { ...c.data };
630
+ if (field.listFields && field.listFields !== null) {
631
+ const filtered = {};
632
+ for (const key of field.listFields) {
633
+ if (key in data) {
634
+ filtered[key] = data[key];
635
+ }
636
+ }
637
+ filtered.contentId = c.contentId;
638
+ filtered.slug = c.slug;
639
+ filtered.title = c.title;
640
+ data = filtered;
641
+ }
642
+ if (field.expand) {
643
+ data = await resolveRelations({ ...c, data }, field.expand, context);
644
+ }
645
+ if (field.customFields) {
646
+ data = await applyCustomFields(data, field.customFields, c, context);
647
+ }
648
+ results.push(data);
649
+ }
650
+ return results;
651
+ }
652
+
653
+ // src/transform/custom-field-transformer.ts
654
+ async function applyCustomFields(data, customFields, content, context) {
655
+ if (!customFields || customFields.length === 0) {
656
+ return data;
657
+ }
658
+ const result = { ...data };
659
+ for (const field of customFields) {
660
+ if (field.type === "relationList") {
661
+ const expanded = await expandRelationList(field, content, context);
662
+ result[field.field] = expanded;
663
+ } else {
664
+ const transformed = applyTransformField(field, content, result);
665
+ result[field.field] = transformed;
666
+ }
667
+ }
668
+ return result;
669
+ }
670
+ function applyTransformField(field, content, currentData) {
671
+ const sourceValue = resolveSourceExpression(field.source, content, currentData);
672
+ return formatValue(sourceValue, field.type, {
673
+ format: field.format,
674
+ length: field.length,
675
+ suffix: field.suffix,
676
+ separator: field.separator,
677
+ defaultValue: field.defaultValue
678
+ });
679
+ }
680
+ function resolveSourceExpression(source, content, currentData) {
681
+ const singleVarMatch = source.match(/^\{\$this\.([^}]+)\}$/);
682
+ if (singleVarMatch) {
683
+ const key = singleVarMatch[1];
684
+ return getValueByKey2(key, content, currentData);
685
+ }
686
+ return source.replace(/\{\$this\.([^}]+)\}/g, (_, key) => {
687
+ const value = getValueByKey2(key, content, currentData);
688
+ return value !== void 0 && value !== null ? String(value) : "";
689
+ });
690
+ }
691
+ function getValueByKey2(key, content, currentData) {
692
+ if (key in content) {
693
+ return content[key];
694
+ }
695
+ if (key in currentData) {
696
+ return currentData[key];
697
+ }
698
+ if (key in content.data) {
699
+ return content.data[key];
700
+ }
701
+ const parts = key.split(".");
702
+ let value = content;
703
+ for (const part of parts) {
704
+ if (value === null || value === void 0) {
705
+ return void 0;
706
+ }
707
+ if (typeof value === "object" && part in value) {
708
+ value = value[part];
709
+ } else if (typeof value === "object" && "data" in value && part in value.data) {
710
+ value = value.data[part];
711
+ } else {
712
+ return void 0;
713
+ }
714
+ }
715
+ return value;
716
+ }
717
+
718
+ // src/recipe/detail-processor.ts
719
+ async function processDetailRecipes(contentTypeId, recipes, targets, context) {
720
+ const outputs = [];
721
+ const contents = context.contentsByType.get(contentTypeId) ?? [];
722
+ for (const recipe of recipes) {
723
+ for (const content of contents) {
724
+ if (!shouldProcessContent(recipe.outputPath, content, targets)) {
725
+ continue;
726
+ }
727
+ try {
728
+ const output = await processDetailContent(recipe, content, context);
729
+ if (output) {
730
+ outputs.push(output);
731
+ }
732
+ } catch (error) {
733
+ context.errors.push({
734
+ code: "CONTENT_NOT_FOUND",
735
+ contentId: content.contentId,
736
+ outputPath: recipe.outputPath,
737
+ message: `DetailPage \u51E6\u7406\u30A8\u30E9\u30FC: ${error instanceof Error ? error.message : String(error)}`
738
+ });
739
+ }
740
+ }
741
+ }
742
+ return outputs;
743
+ }
744
+ async function processDetailContent(recipe, content, context) {
745
+ const outputPath = sanitizePath(resolveOutputPath(recipe.outputPath, content));
746
+ const pathError = validateOutputPath(outputPath);
747
+ if (pathError) {
748
+ context.errors.push({
749
+ ...pathError,
750
+ contentId: content.contentId
751
+ });
752
+ return null;
753
+ }
754
+ let data = { ...content.data };
755
+ data.contentId = content.contentId;
756
+ data.slug = content.slug;
757
+ data.title = content.title;
758
+ data.status = content.status;
759
+ data.createdAt = content.createdAt;
760
+ data.updatedAt = content.updatedAt;
761
+ data.publishedAt = content.publishedAt;
762
+ data.createdBy = content.createdBy;
763
+ if (recipe.expand) {
764
+ data = await resolveRelations({ ...content, data }, recipe.expand, context);
765
+ }
766
+ if (recipe.customFields) {
767
+ data = await applyCustomFields(data, recipe.customFields, content, context);
768
+ }
769
+ const dataJson = {
770
+ type: "update",
771
+ template: recipe.templatePath,
772
+ outputFile: outputPath,
773
+ data
774
+ };
775
+ return {
776
+ path: outputPath,
777
+ content: dataJson
778
+ };
779
+ }
780
+ function shouldProcessContent(outputPathPattern, content, targets) {
781
+ if (targets.some((t) => t.reason === "full_rebuild")) {
782
+ return true;
783
+ }
784
+ const resolvedPath = sanitizePath(resolveOutputPath(outputPathPattern, content));
785
+ for (const target of targets) {
786
+ if (target.outputPath === outputPathPattern) {
787
+ if (target.contentId && target.contentId !== content.contentId) {
788
+ continue;
789
+ }
790
+ return true;
791
+ }
792
+ if (target.outputPath === resolvedPath) {
793
+ return true;
794
+ }
795
+ if (target.contentId === content.contentId) {
796
+ return true;
797
+ }
798
+ }
799
+ return false;
800
+ }
801
+
802
+ // src/recipe/list-processor.ts
803
+ async function processListRecipes(contentTypeId, recipes, targets, context) {
804
+ const outputs = [];
805
+ for (const recipe of recipes) {
806
+ if (!shouldProcessList(recipe.outputPath, targets)) {
807
+ continue;
808
+ }
809
+ try {
810
+ if (recipe.pagination) {
811
+ const paginatedOutputs = await processListWithPagination(
812
+ contentTypeId,
813
+ recipe,
814
+ context
815
+ );
816
+ outputs.push(...paginatedOutputs);
817
+ } else {
818
+ const output = await processListWithoutPagination(
819
+ contentTypeId,
820
+ recipe,
821
+ context
822
+ );
823
+ if (output) {
824
+ outputs.push(output);
825
+ }
826
+ }
827
+ } catch (error) {
828
+ context.errors.push({
829
+ code: "FILTER_ERROR",
830
+ outputPath: recipe.outputPath,
831
+ message: `ListPage \u51E6\u7406\u30A8\u30E9\u30FC: ${error instanceof Error ? error.message : String(error)}`
832
+ });
833
+ }
834
+ }
835
+ return outputs;
836
+ }
837
+ async function processListWithoutPagination(contentTypeId, recipe, context) {
838
+ let contents = context.contentsByType.get(contentTypeId) ?? [];
839
+ contents = applyFilters(contents, recipe.filters);
840
+ contents = applySort(contents, recipe.sort);
841
+ if (recipe.offset) {
842
+ contents = contents.slice(recipe.offset);
843
+ }
844
+ if (recipe.limit) {
845
+ contents = contents.slice(0, recipe.limit);
846
+ }
847
+ const items = await processListItems(contents, recipe, context);
848
+ const outputPath = sanitizePath(recipe.outputPath);
849
+ const pathError = validateOutputPath(outputPath);
850
+ if (pathError) {
851
+ context.errors.push(pathError);
852
+ return null;
853
+ }
854
+ if (items.length === 0) {
855
+ context.warnings.push({
856
+ code: "EMPTY_LIST",
857
+ outputPath,
858
+ message: `\u30EA\u30B9\u30C8\u304C\u7A7A\u3067\u3059: ${contentTypeId}`
859
+ });
860
+ }
861
+ const dataJson = {
862
+ type: "update",
863
+ template: recipe.templatePath,
864
+ outputFile: outputPath,
865
+ data: {
866
+ items,
867
+ totalCount: items.length
868
+ }
869
+ };
870
+ return {
871
+ path: outputPath,
872
+ content: dataJson
873
+ };
874
+ }
875
+ async function processListWithPagination(contentTypeId, recipe, context) {
876
+ let contents = context.contentsByType.get(contentTypeId) ?? [];
877
+ contents = applyFilters(contents, recipe.filters);
878
+ contents = applySort(contents, recipe.sort);
879
+ if (recipe.offset) {
880
+ contents = contents.slice(recipe.offset);
881
+ }
882
+ const { perPage, numberFormatCount, startPath } = recipe.pagination;
883
+ const totalItems = contents.length;
884
+ const totalPages = Math.max(1, Math.ceil(totalItems / perPage));
885
+ const outputs = [];
886
+ for (let page = 1; page <= totalPages; page++) {
887
+ const start = (page - 1) * perPage;
888
+ const pagedContents = contents.slice(start, start + perPage);
889
+ const pagedItems = await processPagedItems(pagedContents, recipe, context);
890
+ let outputPath;
891
+ if (page === 1 && startPath) {
892
+ outputPath = sanitizePath(startPath);
893
+ } else {
894
+ outputPath = sanitizePath(resolveOutputPath(recipe.outputPath, null, page, numberFormatCount));
895
+ }
896
+ const pathError = validateOutputPath(outputPath);
897
+ if (pathError) {
898
+ context.errors.push(pathError);
899
+ continue;
900
+ }
901
+ const dataJson = {
902
+ type: "update",
903
+ template: recipe.templatePath,
904
+ outputFile: outputPath,
905
+ data: {
906
+ currentPageNumber: page,
907
+ totalPagesCount: totalPages,
908
+ totalItemsCount: totalItems,
909
+ pagedItems
910
+ }
911
+ };
912
+ outputs.push({
913
+ path: outputPath,
914
+ content: dataJson
915
+ });
916
+ }
917
+ return outputs;
918
+ }
919
+ async function processListItems(contents, recipe, context) {
920
+ const items = [];
921
+ for (const content of contents) {
922
+ let data = { ...content.data };
923
+ data.contentId = content.contentId;
924
+ data.slug = content.slug;
925
+ data.title = content.title;
926
+ if (recipe.listFields && recipe.listFields !== null) {
927
+ const filtered = {
928
+ contentId: content.contentId,
929
+ slug: content.slug,
930
+ title: content.title
931
+ };
932
+ for (const key of recipe.listFields) {
933
+ if (key in content.data) {
934
+ filtered[key] = content.data[key];
935
+ }
936
+ }
937
+ data = filtered;
938
+ }
939
+ if (recipe.expand) {
940
+ data = await resolveRelations({ ...content, data }, recipe.expand, context);
941
+ }
942
+ if (recipe.customFields) {
943
+ data = await applyCustomFields(data, recipe.customFields, content, context);
944
+ }
945
+ items.push(data);
946
+ }
947
+ return items;
948
+ }
949
+ async function processPagedItems(contents, recipe, context) {
950
+ const items = [];
951
+ for (const content of contents) {
952
+ let data = { ...content.data };
953
+ data.contentId = content.contentId;
954
+ data.slug = content.slug;
955
+ data.title = content.title;
956
+ if (recipe.items?.fields && recipe.items.fields !== null) {
957
+ const filtered = {
958
+ contentId: content.contentId,
959
+ slug: content.slug,
960
+ title: content.title
961
+ };
962
+ for (const key of recipe.items.fields) {
963
+ if (key in content.data) {
964
+ filtered[key] = content.data[key];
965
+ }
966
+ }
967
+ data = filtered;
968
+ }
969
+ if (recipe.items?.expand) {
970
+ data = await resolveRelations({ ...content, data }, recipe.items.expand, context);
971
+ }
972
+ if (recipe.customFields) {
973
+ data = await applyCustomFields(data, recipe.customFields, content, context);
974
+ }
975
+ items.push(data);
976
+ }
977
+ return items;
978
+ }
979
+ function shouldProcessList(outputPathPattern, targets) {
980
+ if (targets.some((t) => t.reason === "full_rebuild")) {
981
+ return true;
982
+ }
983
+ return targets.some((t) => t.outputPath === outputPathPattern);
984
+ }
985
+
986
+ // src/recipe/static-processor.ts
987
+ async function processStaticRecipes(recipes, targets, context) {
988
+ const outputs = [];
989
+ for (const recipe of recipes) {
990
+ if (!shouldProcessStatic(recipe.outputPath, targets)) {
991
+ continue;
992
+ }
993
+ try {
994
+ const output = await processStaticPage(recipe, context);
995
+ if (output) {
996
+ outputs.push(output);
997
+ }
998
+ } catch (error) {
999
+ context.errors.push({
1000
+ code: "CONTENT_NOT_FOUND",
1001
+ outputPath: recipe.outputPath,
1002
+ message: `StaticPage \u51E6\u7406\u30A8\u30E9\u30FC: ${error instanceof Error ? error.message : String(error)}`
1003
+ });
1004
+ }
1005
+ }
1006
+ return outputs;
1007
+ }
1008
+ async function processStaticPage(recipe, context) {
1009
+ const outputPath = sanitizePath(recipe.outputPath);
1010
+ const pathError = validateOutputPath(outputPath);
1011
+ if (pathError) {
1012
+ context.errors.push(pathError);
1013
+ return null;
1014
+ }
1015
+ const dummyContent = {
1016
+ contentId: "static",
1017
+ contentTypeId: "static",
1018
+ slug: "static",
1019
+ title: "",
1020
+ status: "published",
1021
+ data: {},
1022
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1023
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1024
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1025
+ createdBy: "system",
1026
+ filePath: recipe.outputPath
1027
+ };
1028
+ let data = {};
1029
+ if (recipe.customFields) {
1030
+ data = await applyCustomFields(data, recipe.customFields, dummyContent, context);
1031
+ }
1032
+ const dataJson = {
1033
+ type: "update",
1034
+ template: recipe.templatePath,
1035
+ outputFile: outputPath,
1036
+ data
1037
+ };
1038
+ return {
1039
+ path: outputPath,
1040
+ content: dataJson
1041
+ };
1042
+ }
1043
+ function shouldProcessStatic(outputPath, targets) {
1044
+ if (targets.some((t) => t.reason === "full_rebuild")) {
1045
+ return true;
1046
+ }
1047
+ return targets.some((t) => t.outputPath === outputPath);
1048
+ }
1049
+
1050
+ // src/utils/logger.ts
1051
+ function createLogger(level) {
1052
+ const shouldLog = (targetLevel) => {
1053
+ if (level === "quiet") {
1054
+ return targetLevel === "error";
1055
+ }
1056
+ if (level === "info") {
1057
+ return targetLevel !== "debug";
1058
+ }
1059
+ return true;
1060
+ };
1061
+ return {
1062
+ debug(message, ...args) {
1063
+ if (shouldLog("debug")) {
1064
+ console.log(`[DEBUG] ${message}`, ...args);
1065
+ }
1066
+ },
1067
+ info(message, ...args) {
1068
+ if (shouldLog("info")) {
1069
+ console.log(`[INFO] ${message}`, ...args);
1070
+ }
1071
+ },
1072
+ error(message, ...args) {
1073
+ if (shouldLog("error")) {
1074
+ console.error(`[ERROR] ${message}`, ...args);
1075
+ }
1076
+ }
1077
+ };
1078
+ }
1079
+
1080
+ // src/generator.ts
1081
+ async function generateDataJson(input) {
1082
+ const {
1083
+ recipe,
1084
+ dependencyMap,
1085
+ gitDiff,
1086
+ fileSystem,
1087
+ contentRootPath,
1088
+ outputRootPath,
1089
+ options = {}
1090
+ } = input;
1091
+ const {
1092
+ fullRebuild = false,
1093
+ dryRun = false,
1094
+ logLevel = "info"
1095
+ } = options;
1096
+ const logger = createLogger(logLevel);
1097
+ logger.info(`Starting data-json generation (mode: ${fullRebuild ? "full-rebuild" : "incremental"})`);
1098
+ const errors = [];
1099
+ const warnings = [];
1100
+ let targets;
1101
+ if (fullRebuild) {
1102
+ targets = getAllOutputPaths(dependencyMap);
1103
+ logger.info(`Full rebuild: ${targets.length} outputs`);
1104
+ } else {
1105
+ const changes = classifyChangedFiles(gitDiff);
1106
+ targets = calculateRegenerationScope(changes, dependencyMap, recipe);
1107
+ logger.info(`Incremental build: ${targets.length} outputs affected`);
1108
+ if (logLevel === "debug") {
1109
+ logger.debug("Changed files:", gitDiff);
1110
+ logger.debug("Regeneration targets:", targets);
1111
+ }
1112
+ }
1113
+ if (targets.length === 0) {
1114
+ logger.info("No changes detected, nothing to regenerate");
1115
+ return createEmptyResult(dryRun, fullRebuild);
1116
+ }
1117
+ const requiredContentTypes = extractRequiredContentTypes(recipe);
1118
+ logger.debug(`Required content types: ${requiredContentTypes.join(", ")}`);
1119
+ logger.info(`Loading contents for ${requiredContentTypes.length} content types...`);
1120
+ const contentsByType = await loadContentsByType(
1121
+ requiredContentTypes,
1122
+ contentRootPath,
1123
+ fileSystem,
1124
+ logger
1125
+ );
1126
+ const totalContents = Array.from(contentsByType.values()).reduce((sum, arr) => sum + arr.length, 0);
1127
+ logger.info(`Loaded ${totalContents} contents`);
1128
+ const context = {
1129
+ contentsByType,
1130
+ fileSystem,
1131
+ contentRootPath,
1132
+ outputRootPath,
1133
+ errors,
1134
+ warnings,
1135
+ logLevel
1136
+ };
1137
+ const outputs = [];
1138
+ for (const [contentTypeId, contentTypeRecipe] of Object.entries(recipe.contentTypes)) {
1139
+ if (contentTypeRecipe.details && contentTypeRecipe.details.length > 0) {
1140
+ logger.debug(`Processing detail recipes for ${contentTypeId}`);
1141
+ const detailOutputs = await processDetailRecipes(
1142
+ contentTypeId,
1143
+ contentTypeRecipe.details,
1144
+ targets,
1145
+ context
1146
+ );
1147
+ outputs.push(...detailOutputs);
1148
+ }
1149
+ }
1150
+ for (const [contentTypeId, contentTypeRecipe] of Object.entries(recipe.contentTypes)) {
1151
+ if (contentTypeRecipe.lists && contentTypeRecipe.lists.length > 0) {
1152
+ logger.debug(`Processing list recipes for ${contentTypeId}`);
1153
+ const listOutputs = await processListRecipes(
1154
+ contentTypeId,
1155
+ contentTypeRecipe.lists,
1156
+ targets,
1157
+ context
1158
+ );
1159
+ outputs.push(...listOutputs);
1160
+ }
1161
+ }
1162
+ if (recipe.staticPages && recipe.staticPages.length > 0) {
1163
+ logger.debug("Processing static recipes");
1164
+ const staticOutputs = await processStaticRecipes(
1165
+ recipe.staticPages,
1166
+ targets,
1167
+ context
1168
+ );
1169
+ outputs.push(...staticOutputs);
1170
+ }
1171
+ const deleteOutputs = await detectDeletedOutputs(
1172
+ outputs,
1173
+ outputRootPath,
1174
+ fileSystem,
1175
+ targets,
1176
+ fullRebuild,
1177
+ logger
1178
+ );
1179
+ const deduplicatedOutputs = deduplicateOutputs(outputs, errors);
1180
+ const report = createReport({
1181
+ outputs: deduplicatedOutputs,
1182
+ deleteOutputs,
1183
+ errors: [...errors, ...context.errors],
1184
+ warnings: [...warnings, ...context.warnings],
1185
+ fullRebuild,
1186
+ dryRun});
1187
+ logger.info(`Generation completed: ${report.stats.updated} updated, ${report.stats.deleted} deleted, ${report.stats.errors} errors`);
1188
+ return {
1189
+ outputs: [...deduplicatedOutputs, ...deleteOutputs],
1190
+ report
1191
+ };
1192
+ }
1193
+ function extractRequiredContentTypes(recipe) {
1194
+ const contentTypes = /* @__PURE__ */ new Set();
1195
+ for (const contentTypeId of Object.keys(recipe.contentTypes)) {
1196
+ contentTypes.add(contentTypeId);
1197
+ }
1198
+ return Array.from(contentTypes);
1199
+ }
1200
+ async function detectDeletedOutputs(generatedOutputs, outputRootPath, fileSystem, targets, fullRebuild, logger) {
1201
+ const deleteOutputs = [];
1202
+ if (!fullRebuild) {
1203
+ const deleteTargets = targets.filter((t) => t.reason === "deleted");
1204
+ for (const target of deleteTargets) {
1205
+ const generated = generatedOutputs.some((o) => o.path === target.outputPath);
1206
+ if (!generated) {
1207
+ deleteOutputs.push({
1208
+ path: target.outputPath,
1209
+ content: {
1210
+ type: "delete",
1211
+ outputFile: target.outputPath
1212
+ }
1213
+ });
1214
+ logger.debug(`Marked for deletion: ${target.outputPath}`);
1215
+ }
1216
+ }
1217
+ return deleteOutputs;
1218
+ }
1219
+ try {
1220
+ const existingFiles = await fileSystem.listFiles(`${outputRootPath}/**/*.json`);
1221
+ const existingOutputPaths = existingFiles.filter((f) => !f.endsWith("report.json")).map((f) => f.replace(`${outputRootPath}/`, ""));
1222
+ const generatedPaths = new Set(generatedOutputs.map((o) => o.path));
1223
+ for (const existingPath of existingOutputPaths) {
1224
+ if (!generatedPaths.has(existingPath)) {
1225
+ deleteOutputs.push({
1226
+ path: existingPath,
1227
+ content: {
1228
+ type: "delete",
1229
+ outputFile: existingPath
1230
+ }
1231
+ });
1232
+ logger.debug(`Marked for deletion (orphaned): ${existingPath}`);
1233
+ }
1234
+ }
1235
+ } catch {
1236
+ logger.debug("Could not list existing files for deletion detection");
1237
+ }
1238
+ return deleteOutputs;
1239
+ }
1240
+ function deduplicateOutputs(outputs, errors) {
1241
+ const seen = /* @__PURE__ */ new Map();
1242
+ const duplicates = [];
1243
+ for (const output of outputs) {
1244
+ if (seen.has(output.path)) {
1245
+ duplicates.push(output.path);
1246
+ } else {
1247
+ seen.set(output.path, output);
1248
+ }
1249
+ }
1250
+ for (const path of duplicates) {
1251
+ errors.push({
1252
+ code: "DUPLICATE_OUTPUT_PATH",
1253
+ outputPath: path,
1254
+ message: `\u51FA\u529B\u30D1\u30B9\u304C\u91CD\u8907\u3057\u3066\u3044\u307E\u3059: ${path}`
1255
+ });
1256
+ }
1257
+ return Array.from(seen.values());
1258
+ }
1259
+ function createEmptyResult(dryRun, fullRebuild) {
1260
+ return {
1261
+ outputs: [],
1262
+ report: {
1263
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1264
+ mode: fullRebuild ? "full-rebuild" : "incremental",
1265
+ dryRun,
1266
+ stats: {
1267
+ updated: 0,
1268
+ deleted: 0,
1269
+ skipped: 0,
1270
+ errors: 0
1271
+ },
1272
+ outputs: [],
1273
+ errors: [],
1274
+ warnings: []
1275
+ }
1276
+ };
1277
+ }
1278
+ function createReport(params) {
1279
+ const { outputs, deleteOutputs, errors, warnings, fullRebuild, dryRun} = params;
1280
+ const outputEntries = [
1281
+ ...outputs.map((o) => ({ path: o.path, status: "updated" })),
1282
+ ...deleteOutputs.map((o) => ({ path: o.path, status: "deleted" }))
1283
+ ];
1284
+ return {
1285
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1286
+ mode: fullRebuild ? "full-rebuild" : "incremental",
1287
+ dryRun,
1288
+ stats: {
1289
+ updated: outputs.length,
1290
+ deleted: deleteOutputs.length,
1291
+ skipped: 0,
1292
+ // TODO: スキップ数をカウント
1293
+ errors: errors.length
1294
+ },
1295
+ outputs: outputEntries,
1296
+ errors,
1297
+ warnings
1298
+ };
1299
+ }
1300
+ var NodeFileSystem = class {
1301
+ /**
1302
+ * ファイルを読み込む
1303
+ *
1304
+ * @param path ファイルパス
1305
+ * @returns ファイル内容(UTF-8)
1306
+ * @throws ファイルが存在しない場合
1307
+ */
1308
+ async readFile(path) {
1309
+ return readFile(path, "utf-8");
1310
+ }
1311
+ /**
1312
+ * ファイルの存在確認
1313
+ *
1314
+ * @param path ファイルパス
1315
+ * @returns 存在すれば true
1316
+ */
1317
+ async exists(path) {
1318
+ return existsSync(path);
1319
+ }
1320
+ /**
1321
+ * glob パターンにマッチするファイル一覧を取得
1322
+ *
1323
+ * @param pattern glob パターン
1324
+ * @returns マッチしたファイルパスの配列
1325
+ */
1326
+ async listFiles(pattern) {
1327
+ const normalizedPattern = pattern.replace(/\\/g, "/");
1328
+ const files = await glob(normalizedPattern, {
1329
+ nodir: true,
1330
+ windowsPathsNoEscape: true
1331
+ });
1332
+ return files;
1333
+ }
1334
+ };
1335
+ var execAsync = promisify(exec);
1336
+ function parseGitDiff(diffText) {
1337
+ const added = [];
1338
+ const modified = [];
1339
+ const deleted = [];
1340
+ const lines = diffText.trim().split("\n").filter((line) => line.trim());
1341
+ for (const line of lines) {
1342
+ const parts = line.split(" ");
1343
+ if (parts.length < 2) continue;
1344
+ const status = parts[0].trim();
1345
+ const path = parts[parts.length - 1].trim();
1346
+ switch (status[0]) {
1347
+ // R100 のような場合は最初の文字だけ見る
1348
+ case "A":
1349
+ added.push(path);
1350
+ break;
1351
+ case "M":
1352
+ modified.push(path);
1353
+ break;
1354
+ case "D":
1355
+ deleted.push(path);
1356
+ break;
1357
+ case "R":
1358
+ if (parts.length >= 3) {
1359
+ deleted.push(parts[1].trim());
1360
+ }
1361
+ added.push(path);
1362
+ break;
1363
+ case "C":
1364
+ added.push(path);
1365
+ break;
1366
+ }
1367
+ }
1368
+ return { added, modified, deleted };
1369
+ }
1370
+ async function getGitDiff(diffRange) {
1371
+ if (!diffRange) {
1372
+ return { added: [], modified: [], deleted: [] };
1373
+ }
1374
+ try {
1375
+ const { stdout } = await execAsync(`git diff --name-status ${diffRange}`);
1376
+ return parseGitDiff(stdout);
1377
+ } catch (error) {
1378
+ const message = error instanceof Error ? error.message : String(error);
1379
+ throw new Error(`Failed to get git diff: ${message}`);
1380
+ }
1381
+ }
1382
+
1383
+ export { NodeFileSystem, calculateRegenerationScope, classifyChangedFiles, createLogger, expandPartsAffectedScope, generateDataJson, getAllOutputPaths, getGitDiff, parseGitDiff };
1384
+ //# sourceMappingURL=index.js.map
1385
+ //# sourceMappingURL=index.js.map