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