vvvfs 0.2.3 → 0.2.4

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/Media.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * @file Media.ts
3
- * @description 定义自定义 HTML 元素 <fs-audio> 与 <fs-video>,可直接播放存储在 vvvfs 中的音频 / 视频文件。
4
- * 同时导出 <fs-img> / <fs-audio> / <fs-video> 共用的抽象基类 FsMedia。
3
+ * @description 定义 <fs-img> / <fs-audio> / <fs-video> 共用的媒体元素基类 FsMedia,
4
+ * 以及 <fs-audio> 与 <fs-video>;可直接显示 / 播放存储在 vvvfs 中的媒体文件。
5
+ * src 为 http(s) 地址时,会先下载到 /home/.cache/cloud/<hostname>/<pathname> 再展示。
5
6
  * @author IFTC
6
7
  * @example
8
+ * <fs-img src="/home/user/Pictures/logo.png" alt="Logo" width="120"></fs-img>
7
9
  * <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
8
- * <fs-video src="/home/user/Videos/demo.mp4" width="320"></fs-video>
10
+ * <fs-video src="https://example.com/video/demo.mp4" width="320"></fs-video>
9
11
  */
10
12
  import type { VVVFS, VVVFSOptions } from "./index";
11
13
 
@@ -32,6 +34,41 @@ const OBSERVED_ATTRIBUTES = [
32
34
  */
33
35
  const DEFAULT_DB_NAME = "vvvfs";
34
36
 
37
+ /**
38
+ * 云端文件缓存根目录
39
+ */
40
+ const CLOUD_CACHE_ROOT = "/home/.cache/cloud";
41
+
42
+ /**
43
+ * 判断是否为云端地址(http / https / 协议相对 URL)
44
+ * @param src 路径字符串
45
+ */
46
+ function isRemoteUrl(src: string): boolean {
47
+ return /^(https?:\/\/|\/\/)/i.test(src.trim());
48
+ }
49
+
50
+ /**
51
+ * 计算云端文件在 vvvfs 中的缓存路径
52
+ * @description /home/.cache/cloud/<hostname>/<pathname>
53
+ * @param src 云端地址
54
+ */
55
+ function cloudCachePath(src: string): string {
56
+ const base =
57
+ typeof globalThis.location?.href === "string"
58
+ ? globalThis.location.href
59
+ : "http://localhost/";
60
+ const url = new URL(src, base);
61
+ let pathname = url.pathname;
62
+ try {
63
+ pathname = decodeURIComponent(pathname);
64
+ } catch {
65
+ // 保留原始路径(百分号编码非法时)
66
+ }
67
+ // 去掉首尾多余的斜杠,避免拼接出重复分隔符
68
+ pathname = pathname.replace(/^\/+|\/+$/g, "");
69
+ return `${CLOUD_CACHE_ROOT}/${url.hostname}/${pathname}`;
70
+ }
71
+
35
72
  /**
36
73
  * 会改变文件内容的操作类型(其余操作不会触发刷新)
37
74
  */
@@ -180,8 +217,8 @@ export interface FsMediaErrorDetail {
180
217
 
181
218
  /**
182
219
  * 媒体元素基类
183
- * @description <fs-img> / <fs-audio> / <fs-video> 共用,封装文件读取、ObjectURL、
184
- * watch 自动刷新、Shadow DOM 渲染与 load / error 事件。
220
+ * @description <fs-img> / <fs-audio> / <fs-video> 共用,封装文件读取、云端下载与缓存、
221
+ * ObjectURL、watch 自动刷新、Shadow DOM 渲染与 load / error 事件。
185
222
  */
186
223
  export abstract class FsMedia extends HTMLElement {
187
224
  /**
@@ -372,11 +409,19 @@ export abstract class FsMedia extends HTMLElement {
372
409
  * 以避开 vvvfs watch 在操作提交前触发导致的旧内容问题。
373
410
  */
374
411
  scheduleWatchRefresh(): void {
375
- if (this.#watchTimer !== null || !this.isConnected || !this.watch) return;
412
+ // 自身下载 / 读取触发的 watch 不递归刷新
413
+ if (
414
+ this.#skipWatch ||
415
+ this.#watchTimer !== null ||
416
+ !this.isConnected ||
417
+ !this.watch
418
+ ) {
419
+ return;
420
+ }
376
421
  let attempts = 0;
377
422
  const tick = async () => {
378
423
  this.#watchTimer = null;
379
- if (!this.isConnected || !this.watch) return;
424
+ if (this.#skipWatch || !this.isConnected || !this.watch) return;
380
425
  const changed = await this.#refreshForWatch();
381
426
  attempts++;
382
427
  if (!changed && attempts < WATCH_MAX_ATTEMPTS) {
@@ -386,6 +431,15 @@ export abstract class FsMedia extends HTMLElement {
386
431
  this.#watchTimer = window.setTimeout(tick, WATCH_RETRY_DELAY);
387
432
  }
388
433
 
434
+ /**
435
+ * 当前生效的 vvvfs 路径
436
+ * @description 云端地址会被解析为本地缓存路径;其余情况与 src 一致
437
+ */
438
+ #targetPath(): string {
439
+ const src = this.src;
440
+ return isRemoteUrl(src) ? cloudCachePath(src) : src;
441
+ }
442
+
389
443
  /**
390
444
  * 执行加载
391
445
  */
@@ -405,10 +459,21 @@ export abstract class FsMedia extends HTMLElement {
405
459
  if (!fs) return false;
406
460
  this.#syncWatch(fs);
407
461
 
462
+ const remote = isRemoteUrl(src);
463
+ const targetPath = remote ? cloudCachePath(src) : src;
464
+
408
465
  let file: File | null = null;
466
+ let displayed = false;
409
467
  this.#skipWatch = true;
410
468
  try {
411
- file = await fs.read(src);
469
+ if (remote) {
470
+ // 云端文件:缓存优先展示,再通过 HEAD 校验远端大小,必要时重新下载
471
+ const result = await this.#loadRemote(fs, targetPath, token);
472
+ file = result.file;
473
+ displayed = result.displayed;
474
+ } else {
475
+ file = await fs.read(src);
476
+ }
412
477
  } catch (error) {
413
478
  if (token === this.#token && this.isConnected) {
414
479
  this.#fail(error instanceof Error ? error.message : String(error));
@@ -421,11 +486,48 @@ export abstract class FsMedia extends HTMLElement {
421
486
  if (token !== this.#token || !this.isConnected) return false;
422
487
 
423
488
  if (!file) {
424
- this.#fail(`文件不存在: ${src}`);
489
+ this.#fail(`文件不存在: ${targetPath}`);
425
490
  return false;
426
491
  }
427
492
 
428
- return this.#display(file);
493
+ return displayed ? true : this.#display(file, remote);
494
+ }
495
+
496
+ /**
497
+ * 加载远端文件
498
+ * @description 缓存优先:已有缓存时先展示缓存,再发送 HEAD 校验远端文件大小;
499
+ * 大小不一致、缺少 Content-Type 或缓存不可显示时重新下载
500
+ * @param fs VVVFS 实例
501
+ * @param targetPath 缓存路径
502
+ * @param token 加载令牌
503
+ * @returns 最终文件,以及是否已经展示过缓存
504
+ */
505
+ async #loadRemote(
506
+ fs: VVVFS,
507
+ targetPath: string,
508
+ token: number,
509
+ ): Promise<{ file: File | null; displayed: boolean }> {
510
+ const cached = (await fs.exists(targetPath)) ? await fs.read(targetPath) : null;
511
+ if (cached) {
512
+ // 缓存优先展示
513
+ if (token === this.#token && this.isConnected && this.#display(cached, true)) {
514
+ // HEAD 校验远端文件大小与类型
515
+ const info = await fs.head(this.src);
516
+ if (
517
+ info.contentType != null &&
518
+ info.contentLength != null &&
519
+ info.contentLength === cached.size
520
+ ) {
521
+ // 缓存有效,无需重新下载
522
+ return { file: cached, displayed: true };
523
+ }
524
+ }
525
+ }
526
+ if (!(await fs.downloadFile(this.src, targetPath))) {
527
+ throw new Error(`下载失败: ${this.src}`);
528
+ }
529
+ const file = await fs.read(targetPath);
530
+ return { file, displayed: false };
429
531
  }
430
532
 
431
533
  /**
@@ -433,15 +535,15 @@ export abstract class FsMedia extends HTMLElement {
433
535
  * @returns 内容是否发生变化(或无需比较)
434
536
  */
435
537
  async #refreshForWatch(): Promise<boolean> {
436
- const src = this.src;
437
- if (!src) return true;
538
+ const targetPath = this.#targetPath();
539
+ if (!targetPath) return true;
438
540
  const fs = this.#fs ?? this.#resolveFS();
439
541
  if (!fs) return true;
440
542
 
441
543
  let file: File | null = null;
442
544
  this.#skipWatch = true;
443
545
  try {
444
- file = await fs.read(src);
546
+ file = await fs.read(targetPath);
445
547
  } catch {
446
548
  return true;
447
549
  } finally {
@@ -452,11 +554,11 @@ export abstract class FsMedia extends HTMLElement {
452
554
  if (this.#isSameFile(file, this.#currentFile)) return false;
453
555
 
454
556
  if (!file) {
455
- this.#fail(`文件不存在: ${src}`);
557
+ this.#fail(`文件不存在: ${targetPath}`);
456
558
  return true;
457
559
  }
458
560
  // 无论是否为对应类型的媒体,内容已变化,处理完毕即停止重试
459
- this.#display(file);
561
+ this.#display(file, isRemoteUrl(this.src));
460
562
  return true;
461
563
  }
462
564
 
@@ -507,11 +609,16 @@ export abstract class FsMedia extends HTMLElement {
507
609
  /**
508
610
  * 展示文件
509
611
  * @param file 媒体文件
612
+ * @param allowUnknownType 是否允许未知类型(application/octet-stream,交由浏览器按内容嗅探)
510
613
  * @returns 是否成功展示
511
614
  */
512
- #display(file: File): boolean {
513
- if (file.type && !file.type.startsWith(this.acceptPrefix)) {
514
- this.#fail(`文件不是${this.mediaLabel}: ${this.src}(${file.type})`);
615
+ #display(file: File, allowUnknownType = false): boolean {
616
+ const typeMatched = !file.type || file.type.startsWith(this.acceptPrefix);
617
+ // 云端文件的 MIME 由缓存路径扩展名推断,扩展名缺失时为 application/octet-stream
618
+ const unknownAllowed =
619
+ allowUnknownType && file.type === "application/octet-stream";
620
+ if (!typeMatched && !unknownAllowed) {
621
+ this.#fail(`文件不是${this.mediaLabel}: ${this.#targetPath()}(${file.type})`);
515
622
  return false;
516
623
  }
517
624
  const media = this.#ensureMedia();
@@ -534,7 +641,7 @@ export abstract class FsMedia extends HTMLElement {
534
641
  this.#setState("error");
535
642
  this.dispatchEvent(
536
643
  new CustomEvent<FsMediaErrorDetail>("error", {
537
- detail: { path: this.src, message },
644
+ detail: { path: this.#targetPath(), message },
538
645
  }),
539
646
  );
540
647
  }
@@ -570,7 +677,7 @@ export abstract class FsMedia extends HTMLElement {
570
677
  this.#setState("loaded");
571
678
  this.dispatchEvent(
572
679
  new CustomEvent<FsMediaLoadDetail>("load", {
573
- detail: { path: this.src, file: this.#currentFile },
680
+ detail: { path: this.#targetPath(), file: this.#currentFile },
574
681
  }),
575
682
  );
576
683
  });
@@ -580,7 +687,7 @@ export abstract class FsMedia extends HTMLElement {
580
687
  this.#setState("error");
581
688
  this.dispatchEvent(
582
689
  new CustomEvent<FsMediaErrorDetail>("error", {
583
- detail: { path: this.src, message: "媒体加载失败" },
690
+ detail: { path: this.#targetPath(), message: "媒体加载失败" },
584
691
  }),
585
692
  );
586
693
  });
@@ -614,7 +721,7 @@ export abstract class FsMedia extends HTMLElement {
614
721
  */
615
722
  #syncWatch(fs?: VVVFS | null): void {
616
723
  const dbname = this.dbname;
617
- const path = this.src;
724
+ const path = this.#targetPath();
618
725
  const watching = this.watch && path.length > 0;
619
726
 
620
727
  // 目标未变化时无需处理
package/README.md CHANGED
@@ -110,6 +110,8 @@ const vvvfs = new VVVFS("vvvfs", {
110
110
  <fs-img src="/home/user/Pictures/logo.png" alt="Logo" width="120"></fs-img>
111
111
  <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
112
112
  <fs-video src="/home/user/Videos/demo.mp4" width="320"></fs-video>
113
+ <!-- src 也支持 http(s) 云端地址,会先下载到本地缓存再显示 -->
114
+ <fs-img src="https://example.com/Pictures/logo.png"></fs-img>
113
115
  ```
114
116
 
115
117
  ```javascript
@@ -119,9 +121,22 @@ img.src = "/home/user/Pictures/logo.png";
119
121
  document.body.appendChild(img);
120
122
  ```
121
123
 
124
+ `src` 除了 vvvfs 内的路径,也支持 `http(s)` 云端地址。文件会缓存到 `/home/.cache/cloud/<hostname>/<pathname>`,再从缓存显示 / 播放:
125
+
126
+ ```html
127
+ <fs-img src="https://example.com/Pictures/logo.png"></fs-img>
128
+ <fs-video src="https://example.com/Videos/demo.mp4" width="320"></fs-video>
129
+ ```
130
+
131
+ - **缓存优先**:已有缓存时先直接展示缓存,再发送 HEAD 校验远端文件大小;大小不一致、HEAD 未返回 Content-Type 或缓存不可显示时,自动重新下载并刷新
132
+ - **多线程下载**:默认使用 4 线程按 Range 分片并行下载(`vvvfs.downloadFile(url, path, { threads })` 可调整,1-8);文件过小、服务器不支持 Range 或分片失败时自动回退单线程
133
+ - `vvvfs.head(url)` 可单独获取远端文件的 `Content-Length` / `Content-Type`,用于自定义校验
134
+ - 下载使用 `fetch`,目标服务器需允许跨域(CORS)
135
+ - 云端文件同样支持 `watch`,监听的是本地缓存路径
136
+
122
137
  三者共有的属性:
123
138
 
124
- - `src` / `path`:文件在 vvvfs 中的路径(`src` 优先)
139
+ - `src` / `path`:媒体路径(`src` 优先),支持 vvvfs 内的路径与 `http(s)` 云端地址
125
140
  - `dbname`:数据库名,默认 `vvvfs`;未指定且存在全局 `vvvfs` 实例时直接使用该实例
126
141
  - `watch`:`true` 时启用文件监听,`false` 时停止监听;启用后文件内容发生变化会自动刷新(缺省或空值视为 `true`,兼容 `<fs-img watch>` 的写法)
127
142
 
@@ -131,7 +146,7 @@ document.body.appendChild(img);
131
146
  - `<fs-audio>`:`autoplay` / `loop` / `muted` / `preload` 透传到内部 `<audio>` 元素;`controls` 默认开启,移除该属性即可关闭
132
147
  - `<fs-video>`:`autoplay` / `loop` / `muted` / `preload` / `width` / `height` 透传到内部 `<video>` 元素;`controls` 默认开启,移除该属性即可关闭
133
148
 
134
- 事件:`load`(加载完成)、`error`(加载失败),`detail` 中包含 `path` 与 `file`(或 `message`)。元素上还会写入 `data-state` 属性(`loading` / `loaded` / `error`),便于 CSS 定制。
149
+ 事件:`load`(加载完成)、`error`(加载失败),`detail` 中包含 `path` 与 `file`(或 `message`);`path` 为媒体文件在 vvvfs 中的实际路径,云端文件即本地缓存路径。元素上还会写入 `data-state` 属性(`loading` / `loaded` / `error`),便于 CSS 定制。
135
150
 
136
151
  此外提供 `data` 属性(JS 属性),返回当前媒体文件的 Blob 对象(未加载或加载失败时为 `null`),可用于上传、二次处理等场景。
137
152
 
@@ -139,6 +154,12 @@ document.body.appendChild(img);
139
154
 
140
155
  ## 更新日志
141
156
 
157
+ ### 0.2.4
158
+ - `<fs-img>` / `<fs-audio>` / `<fs-video>` 的 `src` 支持 `http(s)` 云端地址:文件缓存到 `/home/.cache/cloud/<hostname>/<pathname>` 后显示 / 播放
159
+ - 云端文件改为**缓存优先**:先展示已有缓存,再发送 HEAD 校验远端文件大小;大小不一致、HEAD 未返回 Content-Type 或缓存不可显示时自动重新下载并刷新
160
+ - `downloadFile` 支持多线程下载(默认 4 线程,`threads` 可配置 1-8,按 Range 分片并行);文件过小、服务器不支持 Range 或分片失败时自动回退单线程
161
+ - 新增 `vvvfs.head(url)` 方法,返回远端文件的 `Content-Length` / `Content-Type` / `acceptRanges`
162
+
142
163
  ### 0.2.3
143
164
 
144
165
  - 新增 `<fs-audio>` 自定义元素,可直接播放 vvvfs 中的音频文件
@@ -361,6 +382,8 @@ Once the library is loaded, these three elements are registered automatically an
361
382
  <fs-img src="/home/user/Pictures/logo.png" alt="Logo" width="120"></fs-img>
362
383
  <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
363
384
  <fs-video src="/home/user/Videos/demo.mp4" width="320"></fs-video>
385
+ <!-- src also accepts http(s) URLs; the file is downloaded to the local cache first -->
386
+ <fs-img src="https://example.com/Pictures/logo.png"></fs-img>
364
387
  ```
365
388
 
366
389
  ```javascript
@@ -370,9 +393,22 @@ img.src = "/home/user/Pictures/logo.png";
370
393
  document.body.appendChild(img);
371
394
  ```
372
395
 
396
+ Besides paths inside vvvfs, `src` also accepts `http(s)` URLs. The file is cached into `/home/.cache/cloud/<hostname>/<pathname>` and then displayed / played from the cache:
397
+
398
+ ```html
399
+ <fs-img src="https://example.com/Pictures/logo.png"></fs-img>
400
+ <fs-video src="https://example.com/Videos/demo.mp4" width="320"></fs-video>
401
+ ```
402
+
403
+ - **Cache first**: when a cache entry exists it is displayed immediately, then a HEAD request validates the remote file size; if the size differs, the HEAD response has no Content-Type, or the cache cannot be displayed, the file is downloaded again and the element refreshes
404
+ - **Multi-threaded download**: downloads run in 4 parallel Range-based chunks by default (configurable via `vvvfs.downloadFile(url, path, { threads })`, 1-8); it falls back to a single thread when the file is too small, the server ignores Range, or a chunk fails
405
+ - `vvvfs.head(url)` returns the remote `Content-Length` / `Content-Type` on its own for custom validation
406
+ - Downloads use `fetch`, so the target server must allow cross-origin requests (CORS)
407
+ - Cloud files support `watch` as well; the local cache path is what gets watched
408
+
373
409
  Attributes shared by all three:
374
410
 
375
- - `src` / `path`: path of the file inside vvvfs (`src` takes precedence)
411
+ - `src` / `path`: media path (`src` takes precedence), either inside vvvfs or an `http(s)` URL
376
412
  - `dbname`: database name, defaults to `vvvfs`; when omitted and a global `vvvfs` instance exists, that instance is used directly
377
413
  - `watch`: `true` enables file watching and `false` disables it; when enabled, the media is refreshed automatically after the file content changes (a missing or empty value is treated as `true`, for compatibility with `<fs-img watch>`)
378
414
 
@@ -382,7 +418,7 @@ Element-specific attributes:
382
418
  - `<fs-audio>`: `autoplay` / `loop` / `muted` / `preload` are passed through to the inner `<audio>` element; `controls` is enabled by default and can be turned off by removing the attribute
383
419
  - `<fs-video>`: `autoplay` / `loop` / `muted` / `preload` / `width` / `height` are passed through to the inner `<video>` element; `controls` is enabled by default and can be turned off by removing the attribute
384
420
 
385
- Events: `load` (media loaded) and `error` (loading failed); `detail` contains `path` plus `file` (or `message`). A `data-state` attribute (`loading` / `loaded` / `error`) is also written to the element for CSS customization.
421
+ Events: `load` (media loaded) and `error` (loading failed); `detail` contains `path` plus `file` (or `message`), where `path` is the actual vvvfs path of the media file (the local cache path for cloud files). A `data-state` attribute (`loading` / `loaded` / `error`) is also written to the element for CSS customization.
386
422
 
387
423
  A `data` property (JS property) is also available, returning the Blob object of the current media file (`null` before loading or after a failure), which is useful for uploading or further processing.
388
424
 
@@ -390,6 +426,12 @@ Rendering happens inside a Shadow DOM: the media element is exposed as `part="im
390
426
 
391
427
  ## Changelog
392
428
 
429
+ ### 0.2.4
430
+ - The `src` attribute of `<fs-img>` / `<fs-audio>` / `<fs-video>` now accepts `http(s)` URLs: the file is cached into `/home/.cache/cloud/<hostname>/<pathname>` and then displayed / played
431
+ - Cloud files are now **cache-first**: the existing cache is shown immediately, then a HEAD request validates the remote file size; a size mismatch, a missing Content-Type, or an undisplayable cache triggers a fresh download and refresh
432
+ - `downloadFile` supports multi-threaded downloads (4 threads by default, configurable via `threads`, 1-8, using parallel Range chunks); it falls back to a single thread when the file is too small, the server ignores Range, or a chunk fails
433
+ - Added `vvvfs.head(url)`, returning the remote `Content-Length` / `Content-Type` / `acceptRanges`
434
+
393
435
  ### 0.2.3
394
436
 
395
437
  - Added the `<fs-audio>` custom element to play audio files stored in vvvfs directly