@conloca/content-api 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +164 -0
  10. package/dist/asset-operations.d.ts.map +1 -0
  11. package/dist/asset-operations.js +784 -0
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +72 -0
  14. package/dist/asset-types.d.ts.map +1 -0
  15. package/dist/asset-types.js +13 -0
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +10 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +49 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +63 -0
  22. package/dist/base-content-index.d.ts.map +1 -0
  23. package/dist/base-content-index.js +200 -0
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.d.ts +31 -0
  26. package/dist/cf-access.d.ts.map +1 -0
  27. package/dist/cf-access.js +67 -0
  28. package/dist/cf-access.js.map +1 -0
  29. package/dist/component-registry.d.ts +50 -0
  30. package/dist/component-registry.d.ts.map +1 -0
  31. package/dist/component-registry.js +121 -0
  32. package/dist/component-registry.js.map +1 -0
  33. package/dist/component-registry.types.d.ts +11 -0
  34. package/dist/component-registry.types.d.ts.map +1 -0
  35. package/dist/component-registry.types.js +2 -0
  36. package/dist/component-registry.types.js.map +1 -0
  37. package/dist/component-vocabulary.d.ts +33 -0
  38. package/dist/component-vocabulary.d.ts.map +1 -0
  39. package/dist/component-vocabulary.js +105 -0
  40. package/dist/component-vocabulary.js.map +1 -0
  41. package/dist/content-api.interface.d.ts +64 -0
  42. package/dist/content-api.interface.d.ts.map +1 -0
  43. package/dist/content-api.interface.js +2 -0
  44. package/dist/content-api.interface.js.map +1 -0
  45. package/dist/content-filters.d.ts +31 -0
  46. package/dist/content-filters.d.ts.map +1 -0
  47. package/dist/content-filters.js +247 -0
  48. package/dist/content-filters.js.map +1 -0
  49. package/dist/content-index.d.ts +184 -0
  50. package/dist/content-index.d.ts.map +1 -0
  51. package/dist/content-index.js +546 -0
  52. package/dist/content-index.js.map +1 -0
  53. package/dist/content-operations.d.ts +157 -0
  54. package/dist/content-operations.d.ts.map +1 -0
  55. package/dist/content-operations.js +359 -0
  56. package/dist/content-operations.js.map +1 -0
  57. package/dist/content-path.d.ts +59 -0
  58. package/dist/content-path.d.ts.map +1 -0
  59. package/dist/content-path.js +88 -0
  60. package/dist/content-path.js.map +1 -0
  61. package/dist/content-reader.d.ts +10 -0
  62. package/dist/content-reader.d.ts.map +1 -0
  63. package/dist/content-reader.js +14 -0
  64. package/dist/content-reader.js.map +1 -0
  65. package/dist/content-utils.d.ts +175 -0
  66. package/dist/content-utils.d.ts.map +1 -0
  67. package/dist/content-utils.js +421 -0
  68. package/dist/content-utils.js.map +1 -0
  69. package/dist/content-watcher.d.ts +43 -0
  70. package/dist/content-watcher.d.ts.map +1 -0
  71. package/dist/content-watcher.js +86 -0
  72. package/dist/content-watcher.js.map +1 -0
  73. package/dist/data-index.d.ts +8 -0
  74. package/dist/data-index.d.ts.map +1 -0
  75. package/dist/data-index.js +8 -0
  76. package/dist/data-index.js.map +1 -0
  77. package/dist/data.d.ts +35 -0
  78. package/dist/data.d.ts.map +1 -0
  79. package/dist/data.js +104 -0
  80. package/dist/data.js.map +1 -0
  81. package/dist/editor-data-bindings.d.ts +10 -0
  82. package/dist/editor-data-bindings.d.ts.map +1 -0
  83. package/dist/editor-data-bindings.js +67 -0
  84. package/dist/editor-data-bindings.js.map +1 -0
  85. package/dist/etag-utils.d.ts +77 -0
  86. package/dist/etag-utils.d.ts.map +1 -0
  87. package/dist/etag-utils.js +161 -0
  88. package/dist/etag-utils.js.map +1 -0
  89. package/dist/filesystem-content-api.d.ts +162 -0
  90. package/dist/filesystem-content-api.d.ts.map +1 -0
  91. package/dist/filesystem-content-api.js +2307 -0
  92. package/dist/filesystem-content-api.js.map +1 -0
  93. package/dist/filesystem-reader-backend.d.ts +46 -0
  94. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  95. package/dist/filesystem-reader-backend.js +119 -0
  96. package/dist/filesystem-reader-backend.js.map +1 -0
  97. package/dist/fragment-index.d.ts +8 -0
  98. package/dist/fragment-index.d.ts.map +1 -0
  99. package/dist/fragment-index.js +8 -0
  100. package/dist/fragment-index.js.map +1 -0
  101. package/dist/fragments.d.ts +16 -0
  102. package/dist/fragments.d.ts.map +1 -0
  103. package/dist/fragments.js +104 -0
  104. package/dist/fragments.js.map +1 -0
  105. package/dist/git-operations.d.ts +49 -0
  106. package/dist/git-operations.d.ts.map +1 -0
  107. package/dist/git-operations.js +256 -0
  108. package/dist/git-operations.js.map +1 -0
  109. package/dist/header-parser.d.ts +37 -0
  110. package/dist/header-parser.d.ts.map +1 -0
  111. package/dist/header-parser.js +233 -0
  112. package/dist/header-parser.js.map +1 -0
  113. package/dist/in-memory-content-api.d.ts +35 -0
  114. package/dist/in-memory-content-api.d.ts.map +1 -0
  115. package/dist/in-memory-content-api.js +609 -0
  116. package/dist/in-memory-content-api.js.map +1 -0
  117. package/dist/index.d.ts +26 -0
  118. package/dist/index.d.ts.map +1 -0
  119. package/dist/index.js +28 -0
  120. package/dist/index.js.map +1 -0
  121. package/dist/indexing.d.ts +5 -0
  122. package/dist/indexing.d.ts.map +1 -0
  123. package/dist/indexing.js +8 -0
  124. package/dist/indexing.js.map +1 -0
  125. package/dist/json-whitespace-view.d.ts +32 -0
  126. package/dist/json-whitespace-view.d.ts.map +1 -0
  127. package/dist/json-whitespace-view.js +153 -0
  128. package/dist/json-whitespace-view.js.map +1 -0
  129. package/dist/middleware.d.ts +20 -0
  130. package/dist/middleware.d.ts.map +1 -0
  131. package/dist/middleware.js +1082 -0
  132. package/dist/middleware.js.map +1 -0
  133. package/dist/node.d.ts +32 -0
  134. package/dist/node.d.ts.map +1 -0
  135. package/dist/node.js +27 -0
  136. package/dist/node.js.map +1 -0
  137. package/dist/page-references.d.ts +21 -0
  138. package/dist/page-references.d.ts.map +1 -0
  139. package/dist/page-references.js +50 -0
  140. package/dist/page-references.js.map +1 -0
  141. package/dist/read-date.d.ts +3 -0
  142. package/dist/read-date.d.ts.map +1 -0
  143. package/dist/read-date.js +9 -0
  144. package/dist/read-date.js.map +1 -0
  145. package/dist/reader-backend.d.ts +54 -0
  146. package/dist/reader-backend.d.ts.map +1 -0
  147. package/dist/reader-backend.js +2 -0
  148. package/dist/reader-backend.js.map +1 -0
  149. package/dist/reader.d.ts +15 -0
  150. package/dist/reader.d.ts.map +1 -0
  151. package/dist/reader.js +14 -0
  152. package/dist/reader.js.map +1 -0
  153. package/dist/schemas/index.d.ts +102 -0
  154. package/dist/schemas/index.d.ts.map +1 -0
  155. package/dist/schemas/index.js +88 -0
  156. package/dist/schemas/index.js.map +1 -0
  157. package/dist/site-index.d.ts +60 -0
  158. package/dist/site-index.d.ts.map +1 -0
  159. package/dist/site-index.js +291 -0
  160. package/dist/site-index.js.map +1 -0
  161. package/dist/site.d.ts +23 -0
  162. package/dist/site.d.ts.map +1 -0
  163. package/dist/site.js +180 -0
  164. package/dist/site.js.map +1 -0
  165. package/dist/types.d.ts +641 -0
  166. package/dist/types.d.ts.map +1 -0
  167. package/dist/types.js +45 -0
  168. package/dist/types.js.map +1 -0
  169. package/dist/url-safe-base64.d.ts +12 -0
  170. package/dist/url-safe-base64.d.ts.map +1 -0
  171. package/dist/url-safe-base64.js +41 -0
  172. package/dist/url-safe-base64.js.map +1 -0
  173. package/dist/url-validation.d.ts +28 -0
  174. package/dist/url-validation.d.ts.map +1 -0
  175. package/dist/url-validation.js +123 -0
  176. package/dist/url-validation.js.map +1 -0
  177. package/dist/utils/atomic-write.d.ts +6 -0
  178. package/dist/utils/atomic-write.d.ts.map +1 -0
  179. package/dist/utils/atomic-write.js +21 -0
  180. package/dist/utils/atomic-write.js.map +1 -0
  181. package/dist/utils.d.ts +46 -0
  182. package/dist/utils.d.ts.map +1 -0
  183. package/dist/utils.js +71 -0
  184. package/dist/utils.js.map +1 -0
  185. package/dist/vite-plugin.d.ts +12 -0
  186. package/dist/vite-plugin.d.ts.map +1 -0
  187. package/dist/vite-plugin.js +30 -0
  188. package/dist/vite-plugin.js.map +1 -0
  189. package/dist/vxjson-serialize.d.ts +13 -0
  190. package/dist/vxjson-serialize.d.ts.map +1 -0
  191. package/dist/vxjson-serialize.js +53 -0
  192. package/dist/vxjson-serialize.js.map +1 -0
  193. package/dist/vxjson.d.ts +113 -0
  194. package/dist/vxjson.d.ts.map +1 -0
  195. package/dist/vxjson.js +381 -0
  196. package/dist/vxjson.js.map +1 -0
  197. package/dist/xxhash.d.ts +10 -0
  198. package/dist/xxhash.d.ts.map +1 -0
  199. package/dist/xxhash.js +35 -0
  200. package/dist/xxhash.js.map +1 -0
  201. package/package.json +132 -34
  202. package/src/asset-constraints.ts +33 -0
  203. package/src/asset-metadata-store.ts +401 -0
  204. package/src/asset-operations.ts +914 -0
  205. package/src/asset-types.ts +74 -0
  206. package/src/asset-usage.ts +47 -0
  207. package/src/base-content-index.ts +227 -0
  208. package/src/cf-access.ts +85 -0
  209. package/src/component-registry.ts +145 -0
  210. package/src/component-registry.types.ts +12 -0
  211. package/src/component-vocabulary.ts +87 -0
  212. package/src/content-api.interface.ts +94 -0
  213. package/src/content-filters.ts +278 -0
  214. package/src/content-index.ts +642 -0
  215. package/src/content-operations.ts +497 -0
  216. package/src/content-path.ts +113 -0
  217. package/src/content-reader.ts +18 -0
  218. package/src/content-utils.ts +474 -0
  219. package/src/content-watcher.ts +122 -0
  220. package/src/data-index.ts +7 -0
  221. package/src/data.ts +134 -0
  222. package/src/editor-data-bindings.ts +66 -0
  223. package/src/etag-utils.ts +204 -0
  224. package/src/filesystem-content-api.ts +2685 -0
  225. package/src/filesystem-reader-backend.ts +135 -0
  226. package/src/fragment-index.ts +7 -0
  227. package/src/fragments.ts +113 -0
  228. package/src/git-operations.ts +340 -0
  229. package/src/header-parser.ts +272 -0
  230. package/src/in-memory-content-api.ts +760 -0
  231. package/src/index.ts +45 -0
  232. package/src/indexing.ts +8 -0
  233. package/src/json-whitespace-view.ts +155 -0
  234. package/src/middleware.ts +1341 -0
  235. package/src/node.ts +40 -0
  236. package/src/page-references.ts +76 -0
  237. package/src/read-date.ts +7 -0
  238. package/src/reader-backend.ts +54 -0
  239. package/src/reader.ts +15 -0
  240. package/src/schemas/index.ts +113 -0
  241. package/src/site-index.ts +330 -0
  242. package/src/site.ts +198 -0
  243. package/src/types.ts +759 -0
  244. package/src/url-safe-base64.ts +38 -0
  245. package/src/url-validation.ts +121 -0
  246. package/src/utils/atomic-write.ts +20 -0
  247. package/src/utils.ts +84 -0
  248. package/src/vite-plugin.ts +45 -0
  249. package/src/vxjson-serialize.ts +66 -0
  250. package/src/vxjson.ts +442 -0
  251. package/src/xxhash.ts +43 -0
  252. package/dist/component-registry.types-CBGONnYn.d.mts +0 -71
  253. package/dist/component-registry.types-CBGONnYn.d.mts.map +0 -1
  254. package/dist/content-operations-Dv67amz3.d.mts +0 -852
  255. package/dist/content-operations-Dv67amz3.d.mts.map +0 -1
  256. package/dist/data-Db1Iv9T0.mjs +0 -60
  257. package/dist/data-Db1Iv9T0.mjs.map +0 -1
  258. package/dist/filesystem-content-api-C1TM0GLo.d.mts +0 -119
  259. package/dist/filesystem-content-api-C1TM0GLo.d.mts.map +0 -1
  260. package/dist/filesystem-content-api-kxKY5IUw.mjs +0 -2678
  261. package/dist/filesystem-content-api-kxKY5IUw.mjs.map +0 -1
  262. package/dist/index.d.mts +0 -79
  263. package/dist/index.d.mts.map +0 -1
  264. package/dist/index.mjs +0 -47
  265. package/dist/index.mjs.map +0 -1
  266. package/dist/node.d.mts +0 -378
  267. package/dist/node.d.mts.map +0 -1
  268. package/dist/node.mjs +0 -2618
  269. package/dist/node.mjs.map +0 -1
  270. package/dist/reader.d.mts +0 -18
  271. package/dist/reader.d.mts.map +0 -1
  272. package/dist/reader.mjs +0 -22
  273. package/dist/reader.mjs.map +0 -1
  274. package/dist/schemas/index.d.mts +0 -90
  275. package/dist/schemas/index.d.mts.map +0 -1
  276. package/dist/schemas/index.mjs +0 -70
  277. package/dist/schemas/index.mjs.map +0 -1
  278. package/dist/site-vNtJ5jCh.mjs +0 -538
  279. package/dist/site-vNtJ5jCh.mjs.map +0 -1
  280. package/dist/types-DWt912tu.mjs +0 -33
  281. package/dist/types-DWt912tu.mjs.map +0 -1
@@ -0,0 +1,914 @@
1
+ import type { Dirent, Stats } from 'node:fs';
2
+ import { lstat, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
3
+ import { extname, join, parse, resolve, sep } from 'node:path';
4
+ import { imageSizeFromFile } from 'image-size/fromFile';
5
+ import { DEFAULT_ACCEPTED_FORMATS, DEFAULT_MAX_FILE_SIZE, IMAGE_EXTENSION_MIME } from './asset-constraints.js';
6
+ import * as assetMetadata from './asset-metadata-store.js';
7
+ import type {
8
+ AssetEntry,
9
+ AssetMetadata,
10
+ AssetMetadataPatch,
11
+ AssetUsage,
12
+ FolderListing,
13
+ FolderTreeNode,
14
+ } from './asset-types.js';
15
+ import { setupGitLfsAttributes } from './git-operations.js';
16
+ import type { JsonValue } from './types.js';
17
+ import { validateFetchUrl } from './url-validation.js';
18
+
19
+ export interface AssetConfig {
20
+ assetsPath: string;
21
+ maxFileSize?: number;
22
+ acceptedFormats?: string[];
23
+ /** The content root: it holds each asset's metadata record, and is scanned for the pages that use an asset */
24
+ contentRoot: string;
25
+ }
26
+
27
+ /** Recognized web image extensions for filesystem scanning — the accepted upload formats */
28
+ const RECOGNIZED_IMAGE_EXTENSIONS = new Set(DEFAULT_ACCEPTED_FORMATS);
29
+
30
+ /** System files to skip during filesystem scanning */
31
+ const SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini', '.asset-manifest.json']);
32
+
33
+ /** Max redirect hops a URL import may follow (each re-validated before it is requested) */
34
+ const MAX_IMPORT_REDIRECTS = 5;
35
+
36
+ /** Recursively enumerate vxjson files without serial directory waits. */
37
+ async function vxjsonFiles(dir: string): Promise<string[]> {
38
+ let entries: Dirent[];
39
+ try {
40
+ entries = await readdir(dir, { withFileTypes: true });
41
+ } catch {
42
+ return [];
43
+ }
44
+ const nested = await Promise.all(
45
+ entries.map(async (entry): Promise<string[]> => {
46
+ const fullPath = join(dir, entry.name);
47
+ if (entry.isDirectory() && !entry.name.startsWith('.')) return vxjsonFiles(fullPath);
48
+ return entry.isFile() && entry.name.endsWith('.vxjson') ? [fullPath] : [];
49
+ }),
50
+ );
51
+ return nested.flat();
52
+ }
53
+
54
+ /** Check if filename has a recognized web image extension */
55
+ function isRecognizedImageExtension(filename: string): boolean {
56
+ const ext = extname(filename).slice(1).toLowerCase();
57
+ return RECOGNIZED_IMAGE_EXTENSIONS.has(ext);
58
+ }
59
+
60
+ /** Check if file is a system/hidden file that should be skipped */
61
+ function isSystemFile(filename: string): boolean {
62
+ return filename.startsWith('.') || SYSTEM_FILES.has(filename.toLowerCase());
63
+ }
64
+
65
+ /**
66
+ * Check that a name is one file in its folder, not a path that could step out of it. The names come
67
+ * straight from a request body, so anything that is not a string is refused too.
68
+ */
69
+ function isBareFilename(filename: unknown): boolean {
70
+ return (
71
+ typeof filename === 'string' && filename !== '' && filename !== '.' && filename !== '..' && !/[/\\]/.test(filename)
72
+ );
73
+ }
74
+
75
+ export class AssetOperations {
76
+ private config: Required<AssetConfig>;
77
+ private dirEnsured = false;
78
+ private lfsSetup = false;
79
+
80
+ constructor(config: AssetConfig) {
81
+ this.config = {
82
+ assetsPath: config.assetsPath,
83
+ maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
84
+ // Copy: the shared default is frozen, but AssetConfig stays a plain string[]
85
+ acceptedFormats: config.acceptedFormats ?? [...DEFAULT_ACCEPTED_FORMATS],
86
+ contentRoot: config.contentRoot,
87
+ };
88
+ }
89
+
90
+ /** A bare filename always means the assets root; subfolder assets are addressed with their folder. */
91
+ private async ensureDir(subpath?: string): Promise<void> {
92
+ const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;
93
+ if (!subpath && this.dirEnsured) return;
94
+ await mkdir(targetPath, { recursive: true });
95
+ if (!subpath) this.dirEnsured = true;
96
+ }
97
+
98
+ /**
99
+ * Validate that a subpath is safe (no path traversal attacks)
100
+ * Returns the resolved full path if valid, throws if invalid
101
+ */
102
+ private validateSubpath(subpath: string): string {
103
+ // Normalize the path: remove leading/trailing slashes, resolve .. and .
104
+ const normalizedSubpath = subpath.replace(/^\/+|\/+$/g, '') || '.';
105
+ // Resolve both paths to absolute to ensure consistent comparison
106
+ const assetsAbsolute = resolve(this.config.assetsPath);
107
+ const fullPath = resolve(assetsAbsolute, normalizedSubpath);
108
+
109
+ // Security check: ensure resolved path is assetsPath or inside it. The separator matters:
110
+ // a bare prefix check lets `../assets-evil` through as if it were inside `assets`.
111
+ if (fullPath !== assetsAbsolute && !fullPath.startsWith(`${assetsAbsolute}${sep}`)) {
112
+ throw new Error('Path traversal detected');
113
+ }
114
+
115
+ return fullPath;
116
+ }
117
+
118
+ /**
119
+ * Resolve a unique filename by appending -1, -2, etc. if collision exists
120
+ * @param originalName Original filename
121
+ * @param folder Optional folder path (relative to assets root)
122
+ */
123
+ private async resolveFilename(originalName: string, folder?: string): Promise<string> {
124
+ const { name, ext } = parse(originalName);
125
+ // Normalize compatibility forms and accents before restricting the stored filename.
126
+ const cleaned = name
127
+ .normalize('NFKD')
128
+ .toLowerCase()
129
+ .replace(/\s+/g, '-')
130
+ .replace(/[^a-z0-9-]/g, '')
131
+ .slice(0, 200);
132
+ const sanitized = /[a-z0-9]/.test(cleaned) ? cleaned : 'file';
133
+ const safeExt = ext.toLowerCase();
134
+
135
+ // Determine base directory (assetsPath or assetsPath/folder)
136
+ const baseDir =
137
+ folder && folder !== '/'
138
+ ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, ''))
139
+ : this.config.assetsPath;
140
+
141
+ let candidate = `${sanitized}${safeExt}`;
142
+ let counter = 0;
143
+
144
+ // eslint-disable-next-line no-constant-condition
145
+ while (true) {
146
+ try {
147
+ // lstat also reserves the name of a broken symlink.
148
+ await lstat(join(baseDir, candidate));
149
+ counter++;
150
+ candidate = `${sanitized}-${counter}${safeExt}`;
151
+ } catch {
152
+ break;
153
+ }
154
+ }
155
+
156
+ return candidate;
157
+ }
158
+
159
+ private validateFormat(filename: string): boolean {
160
+ const ext = extname(filename).slice(1).toLowerCase();
161
+ return this.config.acceptedFormats.includes(ext);
162
+ }
163
+
164
+ private validateSize(size: number): boolean {
165
+ return size <= this.config.maxFileSize;
166
+ }
167
+
168
+ /**
169
+ * Measure an image by reading its header. Never cached: the image is the only
170
+ * honest source, and writing the numbers back turned every listing into a write.
171
+ */
172
+ private async getDimensions(filePath: string): Promise<{ width?: number; height?: number }> {
173
+ try {
174
+ const result = await imageSizeFromFile(filePath);
175
+ return { width: result.width, height: result.height };
176
+ } catch {
177
+ // SVGs without intrinsic size and unsupported formats have no dimensions
178
+ return { width: undefined, height: undefined };
179
+ }
180
+ }
181
+
182
+ /**
183
+ * One AssetEntry: the file as it is on disk, plus whatever a person has
184
+ * written about it. Shared by every read, so they cannot drift.
185
+ */
186
+ private async assetEntry(
187
+ filename: string,
188
+ folder: string,
189
+ stats: Stats,
190
+ metadata: AssetMetadata | undefined,
191
+ ): Promise<AssetEntry> {
192
+ const { width, height } = await this.getDimensions(this.getAssetPath(filename, folder));
193
+ const ext = extname(filename).slice(1).toLowerCase();
194
+
195
+ return {
196
+ filename,
197
+ originalName: metadata?.originalName || filename,
198
+ mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
199
+ size: stats.size,
200
+ width,
201
+ height,
202
+ alt: metadata?.alt,
203
+ uploadedAt: metadata?.uploadedAt || stats.birthtime.toISOString(),
204
+ uploadedBy: metadata?.uploadedBy,
205
+ folder,
206
+ tags: metadata?.tags,
207
+ };
208
+ }
209
+
210
+ /** Build an AssetEntry from a directory entry and the records already read for its folder */
211
+ private async buildAssetEntry(
212
+ dirent: Dirent,
213
+ folder: string,
214
+ records: Map<string, AssetMetadata>,
215
+ ): Promise<AssetEntry> {
216
+ const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
217
+ const stats: Stats = await stat(this.getAssetPath(dirent.name, folder));
218
+ return this.assetEntry(dirent.name, folder, stats, records.get(relativePath));
219
+ }
220
+
221
+ async upload(
222
+ file: File,
223
+ metadata?: { alt?: string; uploadedBy?: string; folder?: string },
224
+ ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {
225
+ if (!this.validateFormat(file.name)) {
226
+ const allowed = this.config.acceptedFormats.join(', ');
227
+ return { success: false, error: `Invalid format. Accepted: ${allowed}` };
228
+ }
229
+
230
+ if (!this.validateSize(file.size)) {
231
+ const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
232
+ return { success: false, error: `File too large. Maximum: ${maxMB}MB` };
233
+ }
234
+
235
+ // Normalize folder path
236
+ const folder = metadata?.folder && metadata.folder !== '/' ? `/${metadata.folder.replace(/^\/+|\/+$/g, '')}` : '/';
237
+
238
+ // Validate folder path (prevent path traversal)
239
+ if (folder !== '/') {
240
+ try {
241
+ this.validateSubpath(folder);
242
+ } catch {
243
+ return { success: false, error: 'Invalid folder path' };
244
+ }
245
+ }
246
+
247
+ try {
248
+ await assetMetadata.migrateLegacyManifest(this.config);
249
+ } catch (err) {
250
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
251
+ }
252
+
253
+ await this.ensureDir();
254
+
255
+ // Ensure target folder exists
256
+ if (folder !== '/') {
257
+ await this.ensureDir(folder.replace(/^\//, ''));
258
+ }
259
+
260
+ if (!this.lfsSetup) {
261
+ await setupGitLfsAttributes(this.config.assetsPath);
262
+ this.lfsSetup = true;
263
+ }
264
+
265
+ const data = new Uint8Array(await file.arrayBuffer());
266
+ let filename: string;
267
+ let filePath: string;
268
+ for (;;) {
269
+ filename = await this.resolveFilename(file.name, folder);
270
+ filePath = this.getAssetPath(filename, folder);
271
+ try {
272
+ // oxlint-disable-next-line no-await-in-loop -- each exclusive create depends on the filename collision found by the preceding attempt.
273
+ await writeFile(filePath, data, { flag: 'wx' });
274
+ break;
275
+ } catch (error) {
276
+ if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;
277
+ }
278
+ }
279
+
280
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
281
+
282
+ const uploadedAt = new Date().toISOString();
283
+ const uploaded: AssetMetadata = {
284
+ alt: metadata?.alt,
285
+ uploadedAt,
286
+ uploadedBy: metadata?.uploadedBy,
287
+ originalName: file.name,
288
+ };
289
+
290
+ // Replace, never merge: a new file landing on a freed filename must not
291
+ // inherit the alt text of the picture that used to be there.
292
+ await assetMetadata.write(this.config, relativePath, uploaded);
293
+
294
+ // Measure the file that was just written, so URL imports and API clients
295
+ // that send no dimensions still get the real ones back
296
+ const { width, height } = await this.getDimensions(filePath);
297
+
298
+ const ext = extname(filename).slice(1).toLowerCase();
299
+ const entry: AssetEntry = {
300
+ filename,
301
+ originalName: file.name,
302
+ mimeType: IMAGE_EXTENSION_MIME[ext] || `image/${ext}`,
303
+ size: file.size,
304
+ width,
305
+ height,
306
+ alt: metadata?.alt,
307
+ uploadedAt,
308
+ uploadedBy: metadata?.uploadedBy,
309
+ folder,
310
+ };
311
+
312
+ return { success: true, asset: entry };
313
+ }
314
+
315
+ /**
316
+ * List all assets recursively from filesystem
317
+ */
318
+ async list(): Promise<AssetEntry[]> {
319
+ const assets: AssetEntry[] = [];
320
+
321
+ // Recursive scanning helper
322
+ const scanFolder = async (folderPath: string, folder: string): Promise<void> => {
323
+ let entries: Dirent[];
324
+ try {
325
+ entries = await readdir(folderPath, { withFileTypes: true });
326
+ } catch {
327
+ return;
328
+ }
329
+
330
+ // Skip hidden files, system files, and symlinks
331
+ const visible = entries.filter((entry) => !isSystemFile(entry.name) && !entry.isSymbolicLink());
332
+ const imageFiles = visible.filter((entry) => entry.isFile() && isRecognizedImageExtension(entry.name));
333
+
334
+ if (imageFiles.length > 0) {
335
+ // Records are gathered per folder: one folder's records say nothing
336
+ // about another's, so a single read of the root would blank every
337
+ // subfolder image's alt text.
338
+ const records = await assetMetadata.readFolder(this.config, folder);
339
+ const folderAssets = await Promise.all(imageFiles.map((entry) => this.buildAssetEntry(entry, folder, records)));
340
+ for (const asset of folderAssets) assets.push(asset);
341
+ }
342
+
343
+ for (const entry of visible) {
344
+ if (entry.isDirectory()) {
345
+ const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;
346
+ // oxlint-disable-next-line no-await-in-loop -- preserve deterministic depth-first asset ordering across folders.
347
+ await scanFolder(join(folderPath, entry.name), subFolder);
348
+ }
349
+ }
350
+ };
351
+
352
+ await scanFolder(this.config.assetsPath, '/');
353
+ return assets;
354
+ }
355
+
356
+ /**
357
+ * Get asset by filename and optional folder
358
+ */
359
+ async getAsset(filename: string, folder = '/'): Promise<AssetEntry | undefined> {
360
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
361
+ let stats: Stats;
362
+ try {
363
+ stats = await stat(this.getAssetPath(filename, folder));
364
+ } catch {
365
+ return undefined;
366
+ }
367
+ if (!stats.isFile()) return undefined;
368
+ const metadata = await assetMetadata.read(this.config, relativePath);
369
+ return this.assetEntry(filename, folder, stats, metadata);
370
+ }
371
+
372
+ /**
373
+ * Delete asset file and manifest entry
374
+ */
375
+ async delete(filename: string, folder = '/'): Promise<{ success: true } | { success: false; error: string }> {
376
+ // Resolve the path BEFORE the catch that forgives a missing file: a path
377
+ // that climbs out of the media library names nothing we may delete.
378
+ let assetPath: string;
379
+ try {
380
+ assetPath = this.getAssetPath(filename, folder);
381
+ } catch {
382
+ return { success: false, error: 'Asset not found' };
383
+ }
384
+
385
+ try {
386
+ await assetMetadata.migrateLegacyManifest(this.config);
387
+ } catch (err) {
388
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
389
+ }
390
+
391
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
392
+
393
+ // Delete file from disk (ignore if already gone)
394
+ try {
395
+ await unlink(assetPath);
396
+ } catch {
397
+ // File may already be gone, continue with metadata cleanup
398
+ }
399
+
400
+ await assetMetadata.remove(this.config, relativePath);
401
+ return { success: true };
402
+ }
403
+
404
+ /**
405
+ * Import an image from a URL (server-side fetch, no CORS issues)
406
+ * Validates the URL and every redirect hop against SSRF, enforces 30s timeout,
407
+ * and checks response size.
408
+ */
409
+ async importFromUrl(
410
+ url: string,
411
+ metadata?: { alt?: string; uploadedBy?: string; folder?: string },
412
+ ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {
413
+ // Validate URL: block private IPs and non-http(s) schemes
414
+ try {
415
+ validateFetchUrl(url);
416
+ } catch (err) {
417
+ return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
418
+ }
419
+
420
+ // Fetch with 30-second timeout, following redirects MANUALLY so every hop's
421
+ // target runs through the SSRF guard BEFORE it is requested — otherwise a
422
+ // public URL can redirect into a loopback or link-local (cloud metadata)
423
+ // address that the initial check would have rejected.
424
+ const controller = new AbortController();
425
+ const timeout = setTimeout(() => controller.abort(), 30_000);
426
+ let response: Response | undefined;
427
+ let current = url;
428
+ try {
429
+ for (let hop = 0; hop <= MAX_IMPORT_REDIRECTS; hop += 1) {
430
+ const hopResponse = await fetch(current, { signal: controller.signal, redirect: 'manual' });
431
+ if (hopResponse.status < 300 || hopResponse.status >= 400) {
432
+ response = hopResponse;
433
+ break;
434
+ }
435
+ const location = hopResponse.headers.get('location');
436
+ if (location === null) {
437
+ return { success: false, error: 'Redirect missing Location header' };
438
+ }
439
+ try {
440
+ // A relative Location is legal and common; resolve it against the URL
441
+ // that produced it, then validate the absolute result.
442
+ current = validateFetchUrl(new URL(location, current).toString()).toString();
443
+ } catch (err) {
444
+ return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
445
+ }
446
+ }
447
+ } catch {
448
+ return { success: false, error: 'Failed to fetch URL' };
449
+ } finally {
450
+ clearTimeout(timeout);
451
+ }
452
+
453
+ // Budget exhausted without a final response — fail closed rather than
454
+ // treating the last redirect as content
455
+ if (!response) {
456
+ return { success: false, error: 'Too many redirects' };
457
+ }
458
+
459
+ if (!response.ok) {
460
+ return { success: false, error: `Fetch failed with status ${response.status}` };
461
+ }
462
+
463
+ // Early size check from Content-Length header
464
+ const contentLength = response.headers.get('content-length');
465
+ if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) {
466
+ const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
467
+ return { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
468
+ }
469
+
470
+ const contentType = response.headers.get('content-type') || '';
471
+ const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
472
+ let urlFilename = lastSegment;
473
+ try {
474
+ const decoded = decodeURIComponent(lastSegment);
475
+ if (!/\p{Cc}/u.test(decoded)) urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
476
+ } catch {
477
+ // A malformed escape keeps the filename as written in the address.
478
+ }
479
+
480
+ // Read response body and verify actual size
481
+ const arrayBuffer = await response.arrayBuffer();
482
+ if (arrayBuffer.byteLength > this.config.maxFileSize) {
483
+ const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
484
+ return { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
485
+ }
486
+
487
+ const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
488
+
489
+ return this.upload(file, metadata);
490
+ }
491
+
492
+ /**
493
+ * List assets and subfolders within a folder (filesystem-first)
494
+ * @param subpath Folder path relative to assets root (default '/')
495
+ */
496
+ async listFolder(subpath = '/'): Promise<FolderListing> {
497
+ // Normalize subpath
498
+ const normalizedSubpath = subpath === '/' ? '/' : `/${subpath.replace(/^\/+|\/+$/g, '')}`;
499
+
500
+ // Validate path (prevent path traversal)
501
+ let fullPath: string;
502
+ if (normalizedSubpath === '/') {
503
+ fullPath = this.config.assetsPath;
504
+ } else {
505
+ fullPath = this.validateSubpath(normalizedSubpath);
506
+ }
507
+
508
+ // Read directory entries
509
+ let entries: Dirent[];
510
+ try {
511
+ entries = await readdir(fullPath, { withFileTypes: true });
512
+ } catch {
513
+ // Directory doesn't exist yet - return empty
514
+ return { assets: [], folders: [] };
515
+ }
516
+
517
+ // Get subfolders (exclude hidden, symlinks)
518
+ const folders = entries
519
+ .filter((e) => e.isDirectory() && !isSystemFile(e.name) && !e.isSymbolicLink())
520
+ .map((e) => ({
521
+ name: e.name,
522
+ path: normalizedSubpath === '/' ? `/${e.name}` : `${normalizedSubpath}/${e.name}`,
523
+ }));
524
+
525
+ // Get image files (exclude hidden, system files, symlinks, non-images)
526
+ const imageFiles = entries.filter(
527
+ (e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name),
528
+ );
529
+
530
+ const records = await assetMetadata.readFolder(this.config, normalizedSubpath);
531
+
532
+ // Build asset entries from filesystem
533
+ const assets = await Promise.all(
534
+ imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, records)),
535
+ );
536
+
537
+ return { assets, folders };
538
+ }
539
+
540
+ /**
541
+ * Create a folder on disk
542
+ * @param subpath Folder path relative to assets root
543
+ */
544
+ async createFolder(subpath: string): Promise<{ success: true } | { success: false; error: string }> {
545
+ if (!subpath || /^\/+$/.test(subpath)) {
546
+ return { success: false, error: 'Cannot create root folder' };
547
+ }
548
+
549
+ // Validate path (prevent path traversal)
550
+ let fullPath: string;
551
+ try {
552
+ fullPath = this.validateSubpath(subpath);
553
+ } catch {
554
+ return { success: false, error: 'Invalid folder path' };
555
+ }
556
+
557
+ const folderSegments = subpath.split('/').filter(Boolean);
558
+ if (folderSegments.some(isSystemFile)) {
559
+ return { success: false, error: "Folder names can't start with a dot or be a system file name like Thumbs.db" };
560
+ }
561
+ if (/[#?%\\]/.test(subpath)) {
562
+ return { success: false, error: "Folder names can't contain #, ?, % or \\" };
563
+ }
564
+ if (/[\t\n\r]/.test(subpath)) {
565
+ return { success: false, error: "Folder names can't contain tabs or line breaks" };
566
+ }
567
+
568
+ try {
569
+ await mkdir(fullPath, { recursive: true });
570
+ return { success: true };
571
+ } catch (err) {
572
+ return {
573
+ success: false,
574
+ error: `Failed to create folder: ${err instanceof Error ? err.message : 'Unknown error'}`,
575
+ };
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Update asset metadata (alt text, tags). The merge happens inside the
581
+ * record's lock and the saved value is what comes back — the old re-read
582
+ * afterwards is how a success could report alt text another save had
583
+ * already written over.
584
+ * @param filename Asset filename
585
+ * @param updates Metadata updates (alt, tags)
586
+ * @param folder Optional folder path (default '/')
587
+ */
588
+ async updateMetadata(
589
+ filename: string,
590
+ updates: AssetMetadataPatch,
591
+ folder = '/',
592
+ ): Promise<
593
+ { success: true; asset: AssetEntry } | { success: false; reason: 'not-found' | 'write-failed'; error: string }
594
+ > {
595
+ const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
596
+
597
+ let stats: Stats;
598
+ try {
599
+ stats = await stat(this.getAssetPath(filename, folder));
600
+ } catch {
601
+ return { success: false, reason: 'not-found', error: 'Asset not found' };
602
+ }
603
+
604
+ let metadata: AssetMetadata;
605
+ try {
606
+ await assetMetadata.migrateLegacyManifest(this.config);
607
+ metadata = await assetMetadata.update(this.config, relativePath, updates);
608
+ } catch (err) {
609
+ return {
610
+ success: false,
611
+ reason: 'write-failed',
612
+ error: err instanceof Error ? err.message : 'Failed to save asset metadata',
613
+ };
614
+ }
615
+
616
+ return { success: true, asset: await this.assetEntry(filename, folder, stats, metadata) };
617
+ }
618
+
619
+ /**
620
+ * Get usage information for an asset (which pages reference it)
621
+ * @param filename Asset filename
622
+ */
623
+ async getUsage(filename: string): Promise<AssetUsage[]> {
624
+ const usages: AssetUsage[] = [];
625
+
626
+ // Search patterns for the asset
627
+ const searchPatterns = [filename, `/assets/uploads/${filename}`, `assets/uploads/${filename}`];
628
+
629
+ const files = await vxjsonFiles(this.config.contentRoot);
630
+ // Promise.all preserves `files` order while avoiding serial disk reads.
631
+ const documents = await Promise.all(
632
+ files.map(async (filePath) => {
633
+ try {
634
+ return { filePath, content: await readFile(filePath, 'utf-8') };
635
+ } catch {
636
+ return null;
637
+ }
638
+ }),
639
+ );
640
+
641
+ for (const document of documents) {
642
+ if (document === null) continue;
643
+ const { filePath, content } = document;
644
+ if (!searchPatterns.some((pattern) => content.includes(pattern))) continue;
645
+
646
+ const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\]/, '');
647
+ const pageName = relativePath.replace(/\.vxjson$/, '');
648
+ let field = 'content';
649
+ try {
650
+ const json: JsonValue = JSON.parse(content);
651
+ field = this.findFieldWithAsset(json, searchPatterns) || 'content';
652
+ } catch {
653
+ // An unreadable JSON document can still be reported by its text match.
654
+ }
655
+ usages.push({ page: pageName, field });
656
+ }
657
+
658
+ return usages;
659
+ }
660
+
661
+ /**
662
+ * Get the file path for an asset
663
+ * @param filename Asset filename
664
+ * @param folder Optional folder path (defaults to asset's stored folder)
665
+ */
666
+ getAssetPath(filename: string, folder?: string): string {
667
+ const subpath = folder && folder !== '/' ? folder.replace(/^\/+|\/+$/g, '') : '';
668
+ const combined = subpath ? `${subpath}/${filename}` : filename;
669
+ return this.validateSubpath(combined);
670
+ }
671
+
672
+ /**
673
+ * Read asset file contents for serving (filesystem-first)
674
+ * @param filename Asset filename
675
+ * @param folder Optional folder path (default '/')
676
+ */
677
+ async readAssetFile(
678
+ filename: string,
679
+ folder = '/',
680
+ ): Promise<{ success: true; buffer: Buffer; mimeType: string } | { success: false; error: string }> {
681
+ // Serve images only: the metadata records live under the same tree and are
682
+ // nobody's business, and neither is any other file that lands in there.
683
+ if (!isRecognizedImageExtension(filename)) {
684
+ return { success: false, error: 'Asset not found' };
685
+ }
686
+
687
+ // Build path from folder + filename
688
+ const filePath = this.getAssetPath(filename, folder);
689
+
690
+ // Derive mimeType from extension (don't require a metadata record)
691
+ const ext = extname(filename).slice(1).toLowerCase();
692
+ const mimeType = IMAGE_EXTENSION_MIME[ext] || `image/${ext}`;
693
+
694
+ try {
695
+ const buffer = await readFile(filePath);
696
+ return { success: true, buffer, mimeType };
697
+ } catch {
698
+ return { success: false, error: 'Asset not found' };
699
+ }
700
+ }
701
+
702
+ /**
703
+ * Helper to find which field contains an asset reference
704
+ */
705
+ private findFieldWithAsset(obj: JsonValue, patterns: string[], path = ''): string | null {
706
+ if (typeof obj === 'string') {
707
+ if (patterns.some((p) => obj.includes(p))) {
708
+ return path || 'root';
709
+ }
710
+ return null;
711
+ }
712
+
713
+ if (Array.isArray(obj)) {
714
+ for (let i = 0; i < obj.length; i++) {
715
+ const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);
716
+ if (result) return result;
717
+ }
718
+ return null;
719
+ }
720
+
721
+ if (obj && typeof obj === 'object') {
722
+ for (const [key, value] of Object.entries(obj)) {
723
+ const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);
724
+ if (result) return result;
725
+ }
726
+ }
727
+
728
+ return null;
729
+ }
730
+
731
+ /**
732
+ * Move assets from one folder to another
733
+ * @param filenames List of filenames to move
734
+ * @param sourceFolder Source folder path (relative to assets root)
735
+ * @param targetFolder Target folder path (relative to assets root)
736
+ */
737
+ async moveAssets(
738
+ filenames: string[],
739
+ sourceFolder: string,
740
+ targetFolder: string,
741
+ ): Promise<{ success: true; moved: number } | { success: false; error: string }> {
742
+ // Normalize folder paths
743
+ const normalizedSource = sourceFolder === '/' ? '/' : `/${sourceFolder.replace(/^\/+|\/+$/g, '')}`;
744
+ const normalizedTarget = targetFolder === '/' ? '/' : `/${targetFolder.replace(/^\/+|\/+$/g, '')}`;
745
+
746
+ // Validate both folders exist (for non-root folders)
747
+ let sourcePath: string;
748
+ let targetPath: string;
749
+
750
+ try {
751
+ sourcePath = normalizedSource === '/' ? this.config.assetsPath : this.validateSubpath(normalizedSource);
752
+ targetPath = normalizedTarget === '/' ? this.config.assetsPath : this.validateSubpath(normalizedTarget);
753
+ } catch {
754
+ return { success: false, error: 'Invalid folder path' };
755
+ }
756
+
757
+ // Each name is joined onto both folders, so one with a separator or `..` would reach outside them
758
+ if (!filenames.every(isBareFilename)) {
759
+ return { success: false, error: 'Invalid filename' };
760
+ }
761
+ // The listing hides system files, and moving the folder's own manifest would drop every asset's metadata
762
+ if (filenames.some(isSystemFile)) {
763
+ return { success: false, error: 'Invalid filename' };
764
+ }
765
+
766
+ // Verify source folder exists
767
+ try {
768
+ const sourceStat = await stat(sourcePath);
769
+ if (!sourceStat.isDirectory()) {
770
+ return { success: false, error: 'Source folder does not exist' };
771
+ }
772
+ } catch {
773
+ return { success: false, error: 'Source folder does not exist' };
774
+ }
775
+
776
+ // Verify target folder exists
777
+ try {
778
+ const targetStat = await stat(targetPath);
779
+ if (!targetStat.isDirectory()) {
780
+ return { success: false, error: 'Target folder does not exist' };
781
+ }
782
+ } catch {
783
+ return { success: false, error: 'Target folder does not exist' };
784
+ }
785
+
786
+ if (normalizedSource === normalizedTarget) return { success: true, moved: 0 };
787
+
788
+ const found = await Promise.all(filenames.map((filename) => lstat(join(sourcePath, filename)).catch(() => null)));
789
+ const notFiles = filenames.filter((_, index) => found[index]?.isFile() === false);
790
+ if (notFiles.length > 0) return { success: false, error: `Not a file: ${notFiles.join(', ')}` };
791
+
792
+ const taken = new Set((await readdir(targetPath)).map((name) => name.toLowerCase()));
793
+ const conflicts = filenames.filter((filename) => taken.has(filename.toLowerCase()));
794
+ if (conflicts.length > 0) {
795
+ return { success: false, error: `Already in the target folder: ${conflicts.join(', ')}` };
796
+ }
797
+
798
+ try {
799
+ await assetMetadata.migrateLegacyManifest(this.config);
800
+ } catch (err) {
801
+ return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
802
+ }
803
+
804
+ // Move each file with its own record, so one failure cannot take the rest
805
+ // of the folder's metadata with it
806
+ let moved = 0;
807
+ for (const filename of filenames) {
808
+ const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;
809
+ const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;
810
+
811
+ // Both folders are checked above, but the names come straight off the
812
+ // request and a name is free to carry `../` of its own
813
+ let from: string;
814
+ let to: string;
815
+ try {
816
+ from = this.getAssetPath(filename, normalizedSource);
817
+ to = this.getAssetPath(filename, normalizedTarget);
818
+ } catch {
819
+ console.error(`[AssetOperations] Refusing to move ${filename}: it points outside the media library`);
820
+ continue;
821
+ }
822
+
823
+ try {
824
+ // oxlint-disable-next-line no-await-in-loop -- each move is committed before its metadata follows; partial failure stays attributable to one filename.
825
+ await rename(from, to);
826
+ } catch (err) {
827
+ console.error(`[AssetOperations] Failed to move ${filename}:`, err);
828
+ continue;
829
+ }
830
+
831
+ // oxlint-disable-next-line no-await-in-loop -- metadata must follow the file that just moved before the next file starts.
832
+ await assetMetadata.move(this.config, oldRelativePath, newRelativePath);
833
+ moved += 1;
834
+ }
835
+
836
+ return { success: true, moved };
837
+ }
838
+
839
+ /**
840
+ * Get the complete folder tree with asset counts
841
+ * @returns Array of folder tree nodes representing the folder hierarchy
842
+ */
843
+ async getFolderTree(): Promise<FolderTreeNode[]> {
844
+ const buildTree = async (folderPath: string, folder: string): Promise<FolderTreeNode[]> => {
845
+ let entries: Dirent[];
846
+ try {
847
+ entries = await readdir(folderPath, { withFileTypes: true });
848
+ } catch {
849
+ return [];
850
+ }
851
+
852
+ const result: FolderTreeNode[] = [];
853
+
854
+ for (const entry of entries) {
855
+ // Skip hidden files/folders and symlinks
856
+ if (isSystemFile(entry.name) || entry.isSymbolicLink()) {
857
+ continue;
858
+ }
859
+
860
+ if (entry.isDirectory()) {
861
+ const entryPath = join(folderPath, entry.name);
862
+ const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;
863
+
864
+ // Count image files in this folder (non-recursive count for this folder only)
865
+ let assetCount = 0;
866
+ try {
867
+ const subEntries = await readdir(entryPath, { withFileTypes: true });
868
+ assetCount = subEntries.filter(
869
+ (e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name),
870
+ ).length;
871
+ } catch {
872
+ // If we can't read the folder, count is 0
873
+ }
874
+
875
+ // Recursively get children
876
+ const children = await buildTree(entryPath, subFolder);
877
+
878
+ result.push({
879
+ name: entry.name,
880
+ path: subFolder,
881
+ assetCount,
882
+ children,
883
+ });
884
+ }
885
+ }
886
+
887
+ return result;
888
+ };
889
+
890
+ // Count assets in root folder
891
+ let rootAssetCount = 0;
892
+ try {
893
+ const rootEntries = await readdir(this.config.assetsPath, { withFileTypes: true });
894
+ rootAssetCount = rootEntries.filter(
895
+ (e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name),
896
+ ).length;
897
+ } catch {
898
+ // If we can't read root, count is 0
899
+ }
900
+
901
+ // Build tree starting from assets root
902
+ const children = await buildTree(this.config.assetsPath, '/');
903
+
904
+ // Return root as first element with its children
905
+ return [
906
+ {
907
+ name: 'Root',
908
+ path: '/',
909
+ assetCount: rootAssetCount,
910
+ children,
911
+ },
912
+ ];
913
+ }
914
+ }