@conloca/content-api 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asset-metadata-store.d.ts.map +1 -1
- package/dist/asset-operations.d.ts +20 -34
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +219 -166
- package/dist/asset-operations.js.map +1 -1
- package/dist/asset-usage.d.ts +5 -4
- package/dist/asset-usage.d.ts.map +1 -1
- package/dist/asset-usage.js +6 -5
- package/dist/asset-usage.js.map +1 -1
- package/dist/cf-access.d.ts +4 -2
- package/dist/cf-access.d.ts.map +1 -1
- package/dist/cf-access.js +29 -13
- package/dist/cf-access.js.map +1 -1
- package/dist/component-registry.d.ts +0 -3
- package/dist/component-registry.d.ts.map +1 -1
- package/dist/content-file-id.d.ts +9 -0
- package/dist/content-file-id.d.ts.map +1 -0
- package/dist/content-file-id.js +33 -0
- package/dist/content-file-id.js.map +1 -0
- package/dist/content-operations.js +2 -2
- package/dist/content-operations.js.map +1 -1
- package/dist/content-path.d.ts +5 -0
- package/dist/content-path.d.ts.map +1 -1
- package/dist/content-path.js +7 -0
- package/dist/content-path.js.map +1 -1
- package/dist/filesystem-content-api.d.ts +0 -15
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +60 -17
- package/dist/filesystem-content-api.js.map +1 -1
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +162 -34
- package/dist/git-operations.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +21 -31
- package/dist/middleware.js.map +1 -1
- package/dist/schemas/index.d.ts +9 -97
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +8 -83
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/normalize.d.ts +101 -0
- package/dist/schemas/normalize.d.ts.map +1 -0
- package/dist/schemas/normalize.js +168 -0
- package/dist/schemas/normalize.js.map +1 -0
- package/dist/schemas/types.d.ts +135 -0
- package/dist/schemas/types.d.ts.map +1 -0
- package/dist/schemas/types.js +17 -0
- package/dist/schemas/types.js.map +1 -0
- package/dist/schemas/validators.d.ts +46 -0
- package/dist/schemas/validators.d.ts.map +1 -0
- package/dist/schemas/validators.js +938 -0
- package/dist/schemas/validators.js.map +1 -0
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +12 -5
- package/src/asset-operations.ts +260 -187
- package/src/asset-usage.ts +6 -5
- package/src/cf-access.ts +30 -14
- package/src/content-file-id.ts +31 -0
- package/src/content-operations.ts +2 -2
- package/src/content-path.ts +8 -0
- package/src/filesystem-content-api.ts +72 -17
- package/src/git-operations.ts +188 -41
- package/src/index.ts +17 -1
- package/src/middleware.ts +23 -37
- package/src/schemas/index.ts +34 -108
- package/src/schemas/normalize.ts +194 -0
- package/src/schemas/types.ts +154 -0
- package/src/schemas/validators.ts +176 -0
- package/src/types.ts +7 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asset-metadata-store.d.ts","sourceRoot":"","sources":["../src/asset-metadata-store.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACxB,MAAM,kBAAkB,CAAC;AAK1B;;;;;;;;GAQG;AACH,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACrB;AAWD;;;;;;;;;;GAUG;AACH,OAAO,CAAC,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"asset-metadata-store.d.ts","sourceRoot":"","sources":["../src/asset-metadata-store.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACxB,MAAM,kBAAkB,CAAC;AAK1B;;;;;;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,wBAAsB,qBAAqB,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAkE/E"}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import type { AssetEntry, AssetMetadataPatch,
|
|
1
|
+
import type { AssetEntry, AssetMetadataPatch, FolderListing, FolderTreeNode } from './asset-types.js';
|
|
2
2
|
export interface AssetConfig {
|
|
3
3
|
assetsPath: string;
|
|
4
4
|
maxFileSize?: number;
|
|
5
|
+
/** Wall-clock budget for a URL import: every redirect hop plus reading the whole body */
|
|
6
|
+
importTimeoutMs?: number;
|
|
5
7
|
acceptedFormats?: string[];
|
|
6
|
-
/** The content root: it holds each asset's metadata record
|
|
8
|
+
/** The content root: it holds each asset's metadata record */
|
|
7
9
|
contentRoot: string;
|
|
8
10
|
}
|
|
9
11
|
export declare class AssetOperations {
|
|
@@ -11,32 +13,17 @@ export declare class AssetOperations {
|
|
|
11
13
|
private dirEnsured;
|
|
12
14
|
private lfsSetup;
|
|
13
15
|
constructor(config: AssetConfig);
|
|
14
|
-
/** A bare filename always means the assets root; subfolder assets are addressed with their folder. */
|
|
15
16
|
private ensureDir;
|
|
16
17
|
/**
|
|
17
18
|
* Validate that a subpath is safe (no path traversal attacks)
|
|
18
19
|
* Returns the resolved full path if valid, throws if invalid
|
|
19
20
|
*/
|
|
20
21
|
private validateSubpath;
|
|
21
|
-
/**
|
|
22
|
-
* Resolve a unique filename by appending -1, -2, etc. if collision exists
|
|
23
|
-
* @param originalName Original filename
|
|
24
|
-
* @param folder Optional folder path (relative to assets root)
|
|
25
|
-
*/
|
|
26
22
|
private resolveFilename;
|
|
27
23
|
private validateFormat;
|
|
28
24
|
private validateSize;
|
|
29
|
-
/**
|
|
30
|
-
* Measure an image by reading its header. Never cached: the image is the only
|
|
31
|
-
* honest source, and writing the numbers back turned every listing into a write.
|
|
32
|
-
*/
|
|
33
25
|
private getDimensions;
|
|
34
|
-
/**
|
|
35
|
-
* One AssetEntry: the file as it is on disk, plus whatever a person has
|
|
36
|
-
* written about it. Shared by every read, so they cannot drift.
|
|
37
|
-
*/
|
|
38
26
|
private assetEntry;
|
|
39
|
-
/** Build an AssetEntry from a directory entry and the records already read for its folder */
|
|
40
27
|
private buildAssetEntry;
|
|
41
28
|
upload(file: File, metadata?: {
|
|
42
29
|
alt?: string;
|
|
@@ -54,7 +41,8 @@ export declare class AssetOperations {
|
|
|
54
41
|
*/
|
|
55
42
|
list(): Promise<AssetEntry[]>;
|
|
56
43
|
/**
|
|
57
|
-
* Get asset by filename and
|
|
44
|
+
* Get asset by filename and folder; the default '/' is the top of the assets folder, never a
|
|
45
|
+
* same-named file in another folder
|
|
58
46
|
*/
|
|
59
47
|
getAsset(filename: string, folder?: string): Promise<AssetEntry | undefined>;
|
|
60
48
|
/**
|
|
@@ -68,8 +56,8 @@ export declare class AssetOperations {
|
|
|
68
56
|
}>;
|
|
69
57
|
/**
|
|
70
58
|
* Import an image from a URL (server-side fetch, no CORS issues)
|
|
71
|
-
* Validates the URL and every redirect hop against SSRF,
|
|
72
|
-
* and
|
|
59
|
+
* Validates the URL and every redirect hop against SSRF, and bounds the whole
|
|
60
|
+
* transfer — headers and body — by one time budget and the max file size.
|
|
73
61
|
*/
|
|
74
62
|
importFromUrl(url: string, metadata?: {
|
|
75
63
|
alt?: string;
|
|
@@ -114,16 +102,7 @@ export declare class AssetOperations {
|
|
|
114
102
|
reason: 'not-found' | 'write-failed';
|
|
115
103
|
error: string;
|
|
116
104
|
}>;
|
|
117
|
-
/**
|
|
118
|
-
* Get usage information for an asset (which pages reference it)
|
|
119
|
-
* @param filename Asset filename
|
|
120
|
-
*/
|
|
121
|
-
getUsage(filename: string): Promise<AssetUsage[]>;
|
|
122
|
-
/**
|
|
123
|
-
* Get the file path for an asset
|
|
124
|
-
* @param filename Asset filename
|
|
125
|
-
* @param folder Optional folder path (defaults to asset's stored folder)
|
|
126
|
-
*/
|
|
105
|
+
/** The file path of an asset in a folder; no folder, or '/', is the top of the assets folder. */
|
|
127
106
|
getAssetPath(filename: string, folder?: string): string;
|
|
128
107
|
/**
|
|
129
108
|
* Read asset file contents for serving (filesystem-first)
|
|
@@ -138,10 +117,6 @@ export declare class AssetOperations {
|
|
|
138
117
|
success: false;
|
|
139
118
|
error: string;
|
|
140
119
|
}>;
|
|
141
|
-
/**
|
|
142
|
-
* Helper to find which field contains an asset reference
|
|
143
|
-
*/
|
|
144
|
-
private findFieldWithAsset;
|
|
145
120
|
/**
|
|
146
121
|
* Move assets from one folder to another
|
|
147
122
|
* @param filenames List of filenames to move
|
|
@@ -154,6 +129,7 @@ export declare class AssetOperations {
|
|
|
154
129
|
} | {
|
|
155
130
|
success: false;
|
|
156
131
|
error: string;
|
|
132
|
+
moved?: number;
|
|
157
133
|
}>;
|
|
158
134
|
/**
|
|
159
135
|
* Get the complete folder tree with asset counts
|
|
@@ -161,4 +137,14 @@ export declare class AssetOperations {
|
|
|
161
137
|
*/
|
|
162
138
|
getFolderTree(): Promise<FolderTreeNode[]>;
|
|
163
139
|
}
|
|
140
|
+
/**
|
|
141
|
+
* Asset moves and deletes in this process run one at a time: between claiming a destination
|
|
142
|
+
* and dropping its source, a move holds the asset at two paths, and a delete or second move
|
|
143
|
+
* acting on either path then could split bytes from metadata or remove the only copy.
|
|
144
|
+
* Module-wide because the router builds a fresh AssetOperations per request, and kept on
|
|
145
|
+
* globalThis (as the metadata store's locks are) because a dev server can load this module twice.
|
|
146
|
+
*/
|
|
147
|
+
declare global {
|
|
148
|
+
var conlocaAssetMoveQueue: Promise<unknown> | undefined;
|
|
149
|
+
}
|
|
164
150
|
//# sourceMappingURL=asset-operations.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asset-operations.d.ts","sourceRoot":"","sources":["../src/asset-operations.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"asset-operations.d.ts","sourceRoot":"","sources":["../src/asset-operations.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,UAAU,EA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AC;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAoBlG;IAED;;;;;OAKG;IACG,UAAU,CACd,SAAS,EAAE,MAAM,EAAE,EACnB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAkG/F;IAED;;;OAGG;IACG,aAAa,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC,CAsE/C;CACF;AAED;;;;;;GAMG;AACH,OAAO,CAAC,MAAM,CAAC,CAAC;IAEd,IAAI,qBAAqB,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC;CACzD"}
|
package/dist/asset-operations.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import { link, lstat, mkdir, open, readdir, readFile, stat, unlink, writeFile, } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, extname, join, parse, resolve, sep } from 'node:path';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
3
5
|
import { imageSizeFromFile } from 'image-size/fromFile';
|
|
4
6
|
import { DEFAULT_ACCEPTED_FORMATS, DEFAULT_MAX_FILE_SIZE, IMAGE_EXTENSION_MIME } from './asset-constraints.js';
|
|
5
7
|
import * as assetMetadata from './asset-metadata-store.js';
|
|
@@ -11,23 +13,7 @@ const RECOGNIZED_IMAGE_EXTENSIONS = new Set(DEFAULT_ACCEPTED_FORMATS);
|
|
|
11
13
|
const SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini', '.asset-manifest.json']);
|
|
12
14
|
/** Max redirect hops a URL import may follow (each re-validated before it is requested) */
|
|
13
15
|
const MAX_IMPORT_REDIRECTS = 5;
|
|
14
|
-
|
|
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
|
-
}
|
|
16
|
+
const DEFAULT_IMPORT_TIMEOUT_MS = 30_000;
|
|
31
17
|
/** Check if filename has a recognized web image extension */
|
|
32
18
|
function isRecognizedImageExtension(filename) {
|
|
33
19
|
const ext = extname(filename).slice(1).toLowerCase();
|
|
@@ -52,6 +38,7 @@ export class AssetOperations {
|
|
|
52
38
|
this.config = {
|
|
53
39
|
assetsPath: config.assetsPath,
|
|
54
40
|
maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
|
|
41
|
+
importTimeoutMs: config.importTimeoutMs ?? DEFAULT_IMPORT_TIMEOUT_MS,
|
|
55
42
|
// Copy: the shared default is frozen, but AssetConfig stays a plain string[]
|
|
56
43
|
acceptedFormats: config.acceptedFormats ?? [...DEFAULT_ACCEPTED_FORMATS],
|
|
57
44
|
contentRoot: config.contentRoot,
|
|
@@ -285,7 +272,8 @@ export class AssetOperations {
|
|
|
285
272
|
return assets;
|
|
286
273
|
}
|
|
287
274
|
/**
|
|
288
|
-
* Get asset by filename and
|
|
275
|
+
* Get asset by filename and folder; the default '/' is the top of the assets folder, never a
|
|
276
|
+
* same-named file in another folder
|
|
289
277
|
*/
|
|
290
278
|
async getAsset(filename, folder = '/') {
|
|
291
279
|
const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
|
|
@@ -321,20 +309,23 @@ export class AssetOperations {
|
|
|
321
309
|
return { success: false, error: err instanceof Error ? err.message : 'Failed to migrate asset metadata' };
|
|
322
310
|
}
|
|
323
311
|
const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
|
|
324
|
-
//
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
312
|
+
// Queued with moves: a delete landing mid-move could otherwise remove the only copy
|
|
313
|
+
// between the move's destination check and its removal of the source.
|
|
314
|
+
await withMoveQueue(async () => {
|
|
315
|
+
try {
|
|
316
|
+
await unlink(assetPath);
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
// File may already be gone, continue with metadata cleanup
|
|
320
|
+
}
|
|
321
|
+
await assetMetadata.remove(this.config, relativePath);
|
|
322
|
+
});
|
|
332
323
|
return { success: true };
|
|
333
324
|
}
|
|
334
325
|
/**
|
|
335
326
|
* Import an image from a URL (server-side fetch, no CORS issues)
|
|
336
|
-
* Validates the URL and every redirect hop against SSRF,
|
|
337
|
-
* and
|
|
327
|
+
* Validates the URL and every redirect hop against SSRF, and bounds the whole
|
|
328
|
+
* transfer — headers and body — by one time budget and the max file size.
|
|
338
329
|
*/
|
|
339
330
|
async importFromUrl(url, metadata) {
|
|
340
331
|
// Validate URL: block private IPs and non-http(s) schemes
|
|
@@ -344,74 +335,115 @@ export class AssetOperations {
|
|
|
344
335
|
catch (err) {
|
|
345
336
|
return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
|
|
346
337
|
}
|
|
347
|
-
//
|
|
348
|
-
//
|
|
349
|
-
//
|
|
350
|
-
//
|
|
338
|
+
// One wall-clock budget covers every hop AND the body read: a server that
|
|
339
|
+
// sends headers promptly and then trickles bytes must not hold the import
|
|
340
|
+
// open. Redirects are followed MANUALLY so every hop's target runs through
|
|
341
|
+
// the SSRF guard BEFORE it is requested — otherwise a public URL can
|
|
342
|
+
// redirect into a loopback or link-local (cloud metadata) address that the
|
|
343
|
+
// initial check would have rejected.
|
|
351
344
|
const controller = new AbortController();
|
|
352
|
-
const timeout = setTimeout(() => controller.abort(),
|
|
353
|
-
let response;
|
|
354
|
-
let current = url;
|
|
345
|
+
const timeout = setTimeout(() => controller.abort(), this.config.importTimeoutMs);
|
|
355
346
|
try {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
347
|
+
let response;
|
|
348
|
+
let current = url;
|
|
349
|
+
try {
|
|
350
|
+
for (let hop = 0; hop <= MAX_IMPORT_REDIRECTS; hop += 1) {
|
|
351
|
+
const hopResponse = await fetch(current, { signal: controller.signal, redirect: 'manual' });
|
|
352
|
+
if (hopResponse.status < 300 || hopResponse.status >= 400) {
|
|
353
|
+
response = hopResponse;
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
// A redirect body is never read; release its connection now.
|
|
357
|
+
await hopResponse.body?.cancel().catch(() => { });
|
|
358
|
+
const location = hopResponse.headers.get('location');
|
|
359
|
+
if (location === null) {
|
|
360
|
+
return { success: false, error: 'Redirect missing Location header' };
|
|
361
|
+
}
|
|
362
|
+
try {
|
|
363
|
+
// A relative Location is legal and common; resolve it against the URL
|
|
364
|
+
// that produced it, then validate the absolute result.
|
|
365
|
+
current = validateFetchUrl(new URL(location, current).toString()).toString();
|
|
366
|
+
}
|
|
367
|
+
catch (err) {
|
|
368
|
+
return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
|
|
369
|
+
}
|
|
365
370
|
}
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
|
|
374
|
+
}
|
|
375
|
+
// Budget exhausted without a final response — fail closed rather than
|
|
376
|
+
// treating the last redirect as content
|
|
377
|
+
if (!response) {
|
|
378
|
+
return { success: false, error: 'Too many redirects' };
|
|
379
|
+
}
|
|
380
|
+
const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
|
|
381
|
+
const tooLarge = { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
|
|
382
|
+
if (!response.ok) {
|
|
383
|
+
await response.body?.cancel().catch(() => { });
|
|
384
|
+
return { success: false, error: `Fetch failed with status ${response.status}` };
|
|
385
|
+
}
|
|
386
|
+
// Early size check from Content-Length header
|
|
387
|
+
const contentLength = response.headers.get('content-length');
|
|
388
|
+
if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) {
|
|
389
|
+
await response.body?.cancel().catch(() => { });
|
|
390
|
+
return tooLarge;
|
|
391
|
+
}
|
|
392
|
+
const contentType = response.headers.get('content-type') || '';
|
|
393
|
+
const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
|
|
394
|
+
let urlFilename = lastSegment;
|
|
395
|
+
try {
|
|
396
|
+
const decoded = decodeURIComponent(lastSegment);
|
|
397
|
+
if (!/\p{Cc}/u.test(decoded))
|
|
398
|
+
urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
// A malformed escape keeps the filename as written in the address.
|
|
402
|
+
}
|
|
403
|
+
// Stream the body, stopping the moment it passes the limit: Content-Length
|
|
404
|
+
// is optional and may lie, so it cannot be trusted to bound memory.
|
|
405
|
+
const chunks = [];
|
|
406
|
+
let received = 0;
|
|
407
|
+
if (response.body) {
|
|
408
|
+
const reader = response.body.getReader();
|
|
409
|
+
// A body that ignores the abort signal must still stop at the deadline.
|
|
410
|
+
const onAbort = () => void reader.cancel().catch(() => { });
|
|
411
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
366
412
|
try {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
413
|
+
while (true) {
|
|
414
|
+
const { done, value } = await reader.read();
|
|
415
|
+
if (controller.signal.aborted)
|
|
416
|
+
return { success: false, error: 'URL import timed out' };
|
|
417
|
+
if (done)
|
|
418
|
+
break;
|
|
419
|
+
received += value.byteLength;
|
|
420
|
+
if (received > this.config.maxFileSize) {
|
|
421
|
+
await reader.cancel().catch(() => { });
|
|
422
|
+
return tooLarge;
|
|
423
|
+
}
|
|
424
|
+
chunks.push(value);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
catch {
|
|
428
|
+
await reader.cancel().catch(() => { });
|
|
429
|
+
return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
|
|
370
430
|
}
|
|
371
|
-
|
|
372
|
-
|
|
431
|
+
finally {
|
|
432
|
+
controller.signal.removeEventListener('abort', onAbort);
|
|
373
433
|
}
|
|
374
434
|
}
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
435
|
+
const bytes = new Uint8Array(received);
|
|
436
|
+
let offset = 0;
|
|
437
|
+
for (const chunk of chunks) {
|
|
438
|
+
bytes.set(chunk, offset);
|
|
439
|
+
offset += chunk.byteLength;
|
|
440
|
+
}
|
|
441
|
+
const file = new File([bytes], urlFilename, { type: contentType });
|
|
442
|
+
return this.upload(file, metadata);
|
|
378
443
|
}
|
|
379
444
|
finally {
|
|
380
445
|
clearTimeout(timeout);
|
|
381
446
|
}
|
|
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
447
|
}
|
|
416
448
|
/**
|
|
417
449
|
* List assets and subfolders within a folder (filesystem-first)
|
|
@@ -520,49 +552,7 @@ export class AssetOperations {
|
|
|
520
552
|
}
|
|
521
553
|
return { success: true, asset: await this.assetEntry(filename, folder, stats, metadata) };
|
|
522
554
|
}
|
|
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
|
-
*/
|
|
555
|
+
/** The file path of an asset in a folder; no folder, or '/', is the top of the assets folder. */
|
|
566
556
|
getAssetPath(filename, folder) {
|
|
567
557
|
const subpath = folder && folder !== '/' ? folder.replace(/^\/+|\/+$/g, '') : '';
|
|
568
558
|
const combined = subpath ? `${subpath}/${filename}` : filename;
|
|
@@ -592,33 +582,6 @@ export class AssetOperations {
|
|
|
592
582
|
return { success: false, error: 'Asset not found' };
|
|
593
583
|
}
|
|
594
584
|
}
|
|
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
585
|
/**
|
|
623
586
|
* Move assets from one folder to another
|
|
624
587
|
* @param filenames List of filenames to move
|
|
@@ -687,6 +650,7 @@ export class AssetOperations {
|
|
|
687
650
|
// Move each file with its own record, so one failure cannot take the rest
|
|
688
651
|
// of the folder's metadata with it
|
|
689
652
|
let moved = 0;
|
|
653
|
+
const failed = [];
|
|
690
654
|
for (const filename of filenames) {
|
|
691
655
|
const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;
|
|
692
656
|
const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;
|
|
@@ -700,19 +664,21 @@ export class AssetOperations {
|
|
|
700
664
|
}
|
|
701
665
|
catch {
|
|
702
666
|
console.error(`[AssetOperations] Refusing to move ${filename}: it points outside the media library`);
|
|
667
|
+
failed.push(`${filename} (outside the media library)`);
|
|
703
668
|
continue;
|
|
704
669
|
}
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
670
|
+
// oxlint-disable-next-line no-await-in-loop -- each move settles before the next; partial failure stays attributable to one filename.
|
|
671
|
+
const outcome = await moveOneWithoutOverwrite(this.config, from, to, oldRelativePath, newRelativePath);
|
|
672
|
+
if (outcome === 'moved') {
|
|
673
|
+
moved += 1;
|
|
708
674
|
}
|
|
709
|
-
|
|
710
|
-
console.error(`[AssetOperations] Failed to move ${filename}
|
|
711
|
-
|
|
675
|
+
else {
|
|
676
|
+
console.error(`[AssetOperations] Failed to move ${filename}: ${outcome}`);
|
|
677
|
+
failed.push(`${filename} (${outcome})`);
|
|
712
678
|
}
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
moved
|
|
679
|
+
}
|
|
680
|
+
if (failed.length > 0) {
|
|
681
|
+
return { success: false, moved, error: `Could not move: ${failed.join(', ')}` };
|
|
716
682
|
}
|
|
717
683
|
return { success: true, moved };
|
|
718
684
|
}
|
|
@@ -781,4 +747,91 @@ export class AssetOperations {
|
|
|
781
747
|
];
|
|
782
748
|
}
|
|
783
749
|
}
|
|
750
|
+
function withMoveQueue(operation) {
|
|
751
|
+
const result = (globalThis.conlocaAssetMoveQueue ?? Promise.resolve()).then(operation, operation);
|
|
752
|
+
globalThis.conlocaAssetMoveQueue = result.catch(() => undefined);
|
|
753
|
+
return result;
|
|
754
|
+
}
|
|
755
|
+
function isErrnoException(error) {
|
|
756
|
+
return error instanceof Error && 'code' in error;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Move one asset file and its metadata record without ever replacing a file at the destination.
|
|
760
|
+
* The listing check in moveAssets reports ordinary clashes up front; this closes the window in
|
|
761
|
+
* which an upload or another move claims the name afterwards. A hard link (or, where the
|
|
762
|
+
* filesystem has none, an exclusive copy) claims the destination name atomically, and the source
|
|
763
|
+
* stays until the metadata has followed. Any failure undoes what was done, leaving bytes and
|
|
764
|
+
* metadata where they were. Returns 'moved' or the reason the file stayed.
|
|
765
|
+
*/
|
|
766
|
+
function moveOneWithoutOverwrite(roots, from, to, oldRelativePath, newRelativePath) {
|
|
767
|
+
return withMoveQueue(() => moveOneNow(roots, from, to, oldRelativePath, newRelativePath));
|
|
768
|
+
}
|
|
769
|
+
async function moveOneNow(roots, from, to, oldRelativePath, newRelativePath) {
|
|
770
|
+
// Names differing only in letter case are one file on macOS and Windows. Moves run one at a
|
|
771
|
+
// time, so this re-check sees every earlier move, including earlier files of the same batch.
|
|
772
|
+
const wanted = basename(to).toLowerCase();
|
|
773
|
+
if ((await readdir(dirname(to))).some((name) => name.toLowerCase() === wanted)) {
|
|
774
|
+
return 'already in the target folder';
|
|
775
|
+
}
|
|
776
|
+
try {
|
|
777
|
+
await link(from, to);
|
|
778
|
+
}
|
|
779
|
+
catch (err) {
|
|
780
|
+
const code = isErrnoException(err) ? err.code : undefined;
|
|
781
|
+
if (code === 'EEXIST')
|
|
782
|
+
return 'already in the target folder';
|
|
783
|
+
if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV' && code !== 'EMLINK') {
|
|
784
|
+
return err instanceof Error ? err.message : 'move failed';
|
|
785
|
+
}
|
|
786
|
+
// No hard links here: claim the name with an exclusive create first, so a failed copy
|
|
787
|
+
// only ever removes the file this move created, never one another request put there.
|
|
788
|
+
let claimed;
|
|
789
|
+
try {
|
|
790
|
+
claimed = await open(to, 'wx');
|
|
791
|
+
}
|
|
792
|
+
catch (openErr) {
|
|
793
|
+
if (isErrnoException(openErr) && openErr.code === 'EEXIST')
|
|
794
|
+
return 'already in the target folder';
|
|
795
|
+
return openErr instanceof Error ? openErr.message : 'move failed';
|
|
796
|
+
}
|
|
797
|
+
let copyError;
|
|
798
|
+
try {
|
|
799
|
+
// Streamed: an asset placed outside the upload route may be far larger than an upload.
|
|
800
|
+
await pipeline(createReadStream(from), claimed.createWriteStream({ autoClose: false }));
|
|
801
|
+
}
|
|
802
|
+
catch (pipelineErr) {
|
|
803
|
+
copyError = pipelineErr;
|
|
804
|
+
}
|
|
805
|
+
finally {
|
|
806
|
+
await claimed.close().catch(() => undefined);
|
|
807
|
+
}
|
|
808
|
+
if (copyError !== undefined) {
|
|
809
|
+
// Closed first: some platforms refuse to remove a file that is still open.
|
|
810
|
+
await unlink(to).catch(() => undefined);
|
|
811
|
+
return copyError instanceof Error ? copyError.message : 'move failed';
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
try {
|
|
815
|
+
await assetMetadata.move(roots, oldRelativePath, newRelativePath);
|
|
816
|
+
}
|
|
817
|
+
catch (err) {
|
|
818
|
+
await unlink(to).catch(() => undefined);
|
|
819
|
+
return err instanceof Error ? err.message : 'metadata move failed';
|
|
820
|
+
}
|
|
821
|
+
// A delete aimed at the new path may have removed it meanwhile; dropping the source now
|
|
822
|
+
// would lose the only copy, so keep the source and put its metadata back.
|
|
823
|
+
if (!(await lstat(to).then((s) => s.isFile(), () => false))) {
|
|
824
|
+
await assetMetadata.move(roots, newRelativePath, oldRelativePath).catch(() => undefined);
|
|
825
|
+
return 'removed from the target folder during the move';
|
|
826
|
+
}
|
|
827
|
+
try {
|
|
828
|
+
await unlink(from);
|
|
829
|
+
}
|
|
830
|
+
catch (err) {
|
|
831
|
+
await assetMetadata.move(roots, newRelativePath, oldRelativePath).catch(() => undefined);
|
|
832
|
+
await unlink(to).catch(() => undefined);
|
|
833
|
+
return err instanceof Error ? err.message : 'move failed';
|
|
834
|
+
}
|
|
835
|
+
return 'moved';
|
|
836
|
+
}
|
|
784
837
|
//# sourceMappingURL=asset-operations.js.map
|