@conloca/content-api 0.1.16 → 0.2.1

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