@karsten_zhou/vite-plugin-hls 0.1.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.
- package/LICENSE +21 -0
- package/README.md +124 -0
- package/dist/index.cjs +474 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +55 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +437 -0
- package/dist/index.js.map +1 -0
- package/package.json +98 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vite-plugin-hls contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# vite-plugin-hls
|
|
2
|
+
|
|
3
|
+
Transcode video files to **HLS** (HTTP Live Streaming) at Vite build time using
|
|
4
|
+
[FFmpeg](https://ffmpeg.org/).
|
|
5
|
+
|
|
6
|
+
Import a video like any other module and receive a string with the URL of the
|
|
7
|
+
generated HLS playlist. The plugin segments the file (and, in adaptive mode,
|
|
8
|
+
encodes multiple renditions) during `vite build`, emits the `.m3u8` playlists
|
|
9
|
+
and `.m4s`/`.ts` segments into your output directory, and returns the URL you
|
|
10
|
+
can feed to an HLS player such as `hls.js`.
|
|
11
|
+
|
|
12
|
+
- **Single mode** — remuxes/segments the source into HLS without re-encoding.
|
|
13
|
+
- **Adaptive mode** — encodes multiple resolution/bitrate renditions and writes
|
|
14
|
+
a master playlist.
|
|
15
|
+
- **Persistent cache** — the (expensive) encoding is keyed by source content
|
|
16
|
+
and options, so repeated and client/SSR builds reuse the same output.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install -D @karsten_zhou/vite-plugin-hls
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
[`vite`](https://vitejs.dev) is a **peer dependency**; install it if it is not
|
|
25
|
+
already present in your project. FFmpeg is bundled automatically via
|
|
26
|
+
`ffmpeg-static` (falling back to a system `ffmpeg` on `PATH` if unavailable).
|
|
27
|
+
|
|
28
|
+
## Requirements
|
|
29
|
+
|
|
30
|
+
- Node.js `>=24.3`
|
|
31
|
+
- Vite `^8` (peer)
|
|
32
|
+
- The build runs `ffmpeg`; `ffmpeg-static` downloads a platform binary on
|
|
33
|
+
install.
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
Add the plugin to your Vite config:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
// vite.config.ts
|
|
41
|
+
import { defineConfig } from "vite";
|
|
42
|
+
import { hlsVideos } from "@karsten_zhou/vite-plugin-hls";
|
|
43
|
+
|
|
44
|
+
export default defineConfig({
|
|
45
|
+
plugins: [
|
|
46
|
+
hlsVideos({
|
|
47
|
+
mode: "adaptive",
|
|
48
|
+
variants: [
|
|
49
|
+
{ height: 1080, bitrate: "3M" },
|
|
50
|
+
{ height: 720, bitrate: "1.5M" },
|
|
51
|
+
],
|
|
52
|
+
}),
|
|
53
|
+
],
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Then import any supported video file in your app:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// src/App.ts
|
|
61
|
+
import videoUrl from "./assets/video.mp4";
|
|
62
|
+
import Hls from "hls.js";
|
|
63
|
+
|
|
64
|
+
// videoUrl -> "/assets/hls/my-video-<hash>/master.m3u8"
|
|
65
|
+
const video = document.createElement("video");
|
|
66
|
+
if (Hls.isSupported()) {
|
|
67
|
+
const hls = new Hls();
|
|
68
|
+
hls.loadSource(videoUrl);
|
|
69
|
+
hls.attachMedia(video);
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The plugin also exports `hlsVideos` as the default export, so
|
|
74
|
+
`import hlsVideos from "@karsten_zhou/vite-plugin-hls"` works as well.
|
|
75
|
+
|
|
76
|
+
## Options
|
|
77
|
+
|
|
78
|
+
| Option | Type | Default | Description |
|
|
79
|
+
| ----------------- | ------------------------ | --------------- | ----------------------------------------------------------------- |
|
|
80
|
+
| `mode` | `"single" \| "adaptive"` | `"single"` | `"single"` remuxes the source; `"adaptive"` encodes renditions. |
|
|
81
|
+
| `variants` | `HlsVariant[]` | — | Required in `adaptive` mode: `{ height, bitrate }` per rendition. |
|
|
82
|
+
| `ffmpegPath` | `string` | `ffmpeg-static` | Explicit ffmpeg executable. |
|
|
83
|
+
| `segmentDuration` | `number` | `4` | HLS segment duration in seconds. |
|
|
84
|
+
| `segmentType` | `"fmp4" \| "mpegts"` | `"fmp4"` | HLS segment container format. |
|
|
85
|
+
| `outputDir` | `string` | `"assets/hls"` | Directory (inside the Vite output) where HLS assets are written. |
|
|
86
|
+
| `preset` | `string` | `"medium"` | FFmpeg `-preset` used in adaptive mode. |
|
|
87
|
+
| `crf` | `number` | `23` | H.264 CRF used in adaptive mode. |
|
|
88
|
+
|
|
89
|
+
### Types
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import type {
|
|
93
|
+
HlsPluginOptions,
|
|
94
|
+
HlsVariant,
|
|
95
|
+
} from "@karsten_zhou/vite-plugin-hls";
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Supported video extensions
|
|
99
|
+
|
|
100
|
+
`.mp4`, `.mov`, `.m4v`, `.webm`, `.mkv`, `.avi`
|
|
101
|
+
|
|
102
|
+
## How it works
|
|
103
|
+
|
|
104
|
+
1. `resolveId` intercepts imports of video files and maps them to a virtual module.
|
|
105
|
+
2. `load` transcodes the source with FFmpeg into an HLS output folder inside
|
|
106
|
+
Vite's cache directory (only once per build — results are memoized).
|
|
107
|
+
3. The output is emitted as static assets into `outputDir`, and the module's
|
|
108
|
+
default export is set to the resolved public URL of the playlist
|
|
109
|
+
(`import.meta.env.BASE_URL` + path), so it works under any `base`.
|
|
110
|
+
|
|
111
|
+
### SSR note
|
|
112
|
+
|
|
113
|
+
During an SSR build the files are **not** emitted (Vite would otherwise resolve
|
|
114
|
+
the asset to a `file://` URL). Instead the public URL is returned directly, and
|
|
115
|
+
the actual files are emitted by the client build.
|
|
116
|
+
|
|
117
|
+
## Development
|
|
118
|
+
|
|
119
|
+
See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, commands, and the release
|
|
120
|
+
process.
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
[MIT](./LICENSE)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
default: () => index_default,
|
|
34
|
+
hlsVideos: () => hlsVideos
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(index_exports);
|
|
37
|
+
|
|
38
|
+
// src/options.ts
|
|
39
|
+
var import_ffmpeg_static = __toESM(require("ffmpeg-static"), 1);
|
|
40
|
+
function resolveOptions(input = {}) {
|
|
41
|
+
const common = {
|
|
42
|
+
ffmpegPath: input.ffmpegPath ?? import_ffmpeg_static.default ?? "ffmpeg",
|
|
43
|
+
segmentDuration: input.segmentDuration ?? 4,
|
|
44
|
+
segmentType: input.segmentType ?? "fmp4",
|
|
45
|
+
outputDir: input.outputDir ?? "assets/hls",
|
|
46
|
+
preset: input.preset ?? "medium",
|
|
47
|
+
crf: input.crf ?? 23
|
|
48
|
+
};
|
|
49
|
+
if (input.mode === "adaptive") {
|
|
50
|
+
if (!input.variants || input.variants.length === 0) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
"[vite-plugin-hls] Adaptive mode requires at least one variant."
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
...common,
|
|
57
|
+
mode: "adaptive",
|
|
58
|
+
variants: input.variants
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
...common,
|
|
63
|
+
mode: "single"
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/resolve.ts
|
|
68
|
+
var import_node_path = require("path");
|
|
69
|
+
var VIDEO_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
70
|
+
".mp4",
|
|
71
|
+
".mov",
|
|
72
|
+
".m4v",
|
|
73
|
+
".webm",
|
|
74
|
+
".mkv",
|
|
75
|
+
".avi"
|
|
76
|
+
]);
|
|
77
|
+
var VIRTUAL_PREFIX = "\0vite-plugin-hls:";
|
|
78
|
+
function isVideoSource(source) {
|
|
79
|
+
const pathname = source.split("?")[0] ?? source;
|
|
80
|
+
return VIDEO_EXTENSIONS.has((0, import_node_path.extname)(pathname).toLowerCase());
|
|
81
|
+
}
|
|
82
|
+
function virtualIdForSource(source) {
|
|
83
|
+
return `${VIRTUAL_PREFIX}${encodeURIComponent(source)}`;
|
|
84
|
+
}
|
|
85
|
+
function sourceFromVirtualId(id) {
|
|
86
|
+
return decodeURIComponent(id.slice(VIRTUAL_PREFIX.length));
|
|
87
|
+
}
|
|
88
|
+
async function resolveVideoSource(source, importer, context) {
|
|
89
|
+
if (!isVideoSource(source)) {
|
|
90
|
+
return void 0;
|
|
91
|
+
}
|
|
92
|
+
const resolved = await context.resolve(source, importer, {
|
|
93
|
+
skipSelf: true
|
|
94
|
+
});
|
|
95
|
+
if (!resolved || resolved.external) {
|
|
96
|
+
return void 0;
|
|
97
|
+
}
|
|
98
|
+
return resolved.id.split("?", 1)[0];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/hls.ts
|
|
102
|
+
var import_node_path6 = require("path");
|
|
103
|
+
var import_promises4 = require("fs/promises");
|
|
104
|
+
|
|
105
|
+
// src/encoder.ts
|
|
106
|
+
var import_promises = require("fs/promises");
|
|
107
|
+
var import_node_path2 = require("path");
|
|
108
|
+
var import_node_os = require("os");
|
|
109
|
+
var import_node_child_process = require("child_process");
|
|
110
|
+
|
|
111
|
+
// src/bitrate.ts
|
|
112
|
+
function bitrateToNumber(bitrate) {
|
|
113
|
+
const match = /^([\d.]+)\s*([kKmMgG]?)$/.exec(bitrate.trim());
|
|
114
|
+
if (!match) {
|
|
115
|
+
throw new Error(`[vite-plugin-hls] Invalid bitrate: ${bitrate}`);
|
|
116
|
+
}
|
|
117
|
+
const amount = Number(match[1]);
|
|
118
|
+
const suffix = (match[2] ?? "").toLowerCase();
|
|
119
|
+
const multiplier = suffix === "g" ? 1e9 : suffix === "m" ? 1e6 : suffix === "k" ? 1e3 : 1;
|
|
120
|
+
return Math.round(amount * multiplier);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/encoder.ts
|
|
124
|
+
function runFfmpeg(executable, args) {
|
|
125
|
+
return new Promise((resolvePromise, reject) => {
|
|
126
|
+
const child = (0, import_node_child_process.spawn)(executable, args, {
|
|
127
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
128
|
+
});
|
|
129
|
+
let stderr = "";
|
|
130
|
+
child.stderr.on("data", (data) => {
|
|
131
|
+
stderr += data.toString();
|
|
132
|
+
});
|
|
133
|
+
child.on("error", (error) => {
|
|
134
|
+
if ("code" in error && error.code === "ENOENT") {
|
|
135
|
+
reject(
|
|
136
|
+
new Error(
|
|
137
|
+
[
|
|
138
|
+
"[vite-plugin-hls] ffmpeg was not found.",
|
|
139
|
+
`Executable: ${executable}`,
|
|
140
|
+
"Set ffmpegPath or install ffmpeg."
|
|
141
|
+
].join("\n")
|
|
142
|
+
)
|
|
143
|
+
);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
reject(error);
|
|
147
|
+
});
|
|
148
|
+
child.on("close", (code) => {
|
|
149
|
+
if (code === 0) {
|
|
150
|
+
resolvePromise();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
reject(
|
|
154
|
+
new Error(
|
|
155
|
+
[
|
|
156
|
+
`[vite-plugin-hls] ffmpeg failed with exit code ${code ?? "unknown"}.`,
|
|
157
|
+
stderr.trim()
|
|
158
|
+
].filter(Boolean).join("\n")
|
|
159
|
+
)
|
|
160
|
+
);
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
async function encodeVariant(source, outputDirectory, options, variant = {}) {
|
|
165
|
+
const extension = options.segmentType === "fmp4" ? "m4s" : "ts";
|
|
166
|
+
const playlist = (0, import_node_path2.join)(outputDirectory, "index.m3u8");
|
|
167
|
+
const args = [
|
|
168
|
+
"-y",
|
|
169
|
+
"-i",
|
|
170
|
+
source,
|
|
171
|
+
"-map",
|
|
172
|
+
"0:v:0",
|
|
173
|
+
"-map",
|
|
174
|
+
"0:a:0?"
|
|
175
|
+
];
|
|
176
|
+
if (options.mode === "single") {
|
|
177
|
+
args.push(
|
|
178
|
+
"-c:v",
|
|
179
|
+
"copy",
|
|
180
|
+
"-c:a",
|
|
181
|
+
"copy"
|
|
182
|
+
);
|
|
183
|
+
} else {
|
|
184
|
+
args.push(
|
|
185
|
+
"-c:v",
|
|
186
|
+
"libx264",
|
|
187
|
+
"-preset",
|
|
188
|
+
options.preset,
|
|
189
|
+
"-crf",
|
|
190
|
+
String(options.crf),
|
|
191
|
+
"-pix_fmt",
|
|
192
|
+
"yuv420p",
|
|
193
|
+
"-c:a",
|
|
194
|
+
"aac",
|
|
195
|
+
"-b:a",
|
|
196
|
+
"128k"
|
|
197
|
+
);
|
|
198
|
+
if (variant.height !== void 0) {
|
|
199
|
+
args.push(
|
|
200
|
+
"-vf",
|
|
201
|
+
`scale=-2:${variant.height}:force_original_aspect_ratio=decrease`
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
if (variant.bitrate !== void 0) {
|
|
205
|
+
const bitrate = bitrateToNumber(variant.bitrate);
|
|
206
|
+
args.push(
|
|
207
|
+
"-b:v",
|
|
208
|
+
variant.bitrate,
|
|
209
|
+
"-maxrate",
|
|
210
|
+
variant.bitrate,
|
|
211
|
+
"-bufsize",
|
|
212
|
+
String(Math.round(bitrate * 1.5))
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
args.push(
|
|
217
|
+
"-f",
|
|
218
|
+
"hls",
|
|
219
|
+
"-hls_time",
|
|
220
|
+
String(options.segmentDuration),
|
|
221
|
+
"-hls_playlist_type",
|
|
222
|
+
"vod",
|
|
223
|
+
"-hls_segment_filename",
|
|
224
|
+
(0, import_node_path2.join)(outputDirectory, `segment-%05d.${extension}`)
|
|
225
|
+
);
|
|
226
|
+
if (options.segmentType === "fmp4") {
|
|
227
|
+
args.push(
|
|
228
|
+
"-hls_segment_type",
|
|
229
|
+
"fmp4",
|
|
230
|
+
"-hls_fmp4_init_filename",
|
|
231
|
+
"init.mp4"
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
args.push(playlist);
|
|
235
|
+
await runFfmpeg(options.ffmpegPath, args);
|
|
236
|
+
}
|
|
237
|
+
async function createEncodeDirectory() {
|
|
238
|
+
return (0, import_promises.mkdtemp)((0, import_node_path2.join)((0, import_node_os.tmpdir)(), "vite-plugin-hls-"));
|
|
239
|
+
}
|
|
240
|
+
async function removeEncodeDirectory(directory) {
|
|
241
|
+
await (0, import_promises.rm)(directory, {
|
|
242
|
+
recursive: true,
|
|
243
|
+
force: true
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// src/cache.ts
|
|
248
|
+
var import_node_crypto = require("crypto");
|
|
249
|
+
var import_promises3 = require("fs/promises");
|
|
250
|
+
var import_node_path4 = require("path");
|
|
251
|
+
|
|
252
|
+
// src/fs.ts
|
|
253
|
+
var import_promises2 = require("fs/promises");
|
|
254
|
+
var import_node_path3 = require("path");
|
|
255
|
+
async function collectFiles(directory) {
|
|
256
|
+
const result = /* @__PURE__ */ new Map();
|
|
257
|
+
async function visit(current) {
|
|
258
|
+
for (const entry of await (0, import_promises2.readdir)(current, { withFileTypes: true })) {
|
|
259
|
+
const filename = (0, import_node_path3.join)(current, entry.name);
|
|
260
|
+
if (entry.isDirectory()) {
|
|
261
|
+
await visit(filename);
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
result.set(
|
|
265
|
+
(0, import_node_path3.relative)(directory, filename).replaceAll("\\", "/"),
|
|
266
|
+
await (0, import_promises2.readFile)(filename)
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
await visit(directory);
|
|
271
|
+
return result;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// src/cache.ts
|
|
275
|
+
async function getCacheKey(source, options) {
|
|
276
|
+
const sourceData = await (0, import_promises3.readFile)(source);
|
|
277
|
+
return (0, import_node_crypto.createHash)("sha256").update(sourceData).update(JSON.stringify(options)).digest("hex");
|
|
278
|
+
}
|
|
279
|
+
async function readCache(cacheRoot, key) {
|
|
280
|
+
const directory = (0, import_node_path4.join)(cacheRoot, "hls", key);
|
|
281
|
+
try {
|
|
282
|
+
await (0, import_promises3.stat)(directory);
|
|
283
|
+
} catch {
|
|
284
|
+
return void 0;
|
|
285
|
+
}
|
|
286
|
+
const metadata = JSON.parse(
|
|
287
|
+
await (0, import_promises3.readFile)((0, import_node_path4.join)(directory, "manifest.json"), "utf8")
|
|
288
|
+
);
|
|
289
|
+
const files = await collectFiles(directory);
|
|
290
|
+
files.delete("manifest.json");
|
|
291
|
+
return {
|
|
292
|
+
directoryName: metadata.directoryName,
|
|
293
|
+
manifest: metadata.manifest,
|
|
294
|
+
files
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
async function writeCache(cacheRoot, key, result) {
|
|
298
|
+
const temporaryDirectory = (0, import_node_path4.join)(cacheRoot, "hls", `${key}.tmp`);
|
|
299
|
+
const finalDirectory = (0, import_node_path4.join)(cacheRoot, "hls", key);
|
|
300
|
+
await (0, import_promises3.rm)(temporaryDirectory, {
|
|
301
|
+
recursive: true,
|
|
302
|
+
force: true
|
|
303
|
+
});
|
|
304
|
+
await (0, import_promises3.mkdir)(temporaryDirectory, {
|
|
305
|
+
recursive: true
|
|
306
|
+
});
|
|
307
|
+
for (const [filename, data] of result.files) {
|
|
308
|
+
const destination = (0, import_node_path4.join)(temporaryDirectory, filename);
|
|
309
|
+
await (0, import_promises3.mkdir)((0, import_node_path4.resolve)(destination, ".."), {
|
|
310
|
+
recursive: true
|
|
311
|
+
});
|
|
312
|
+
await (0, import_promises3.writeFile)(destination, data);
|
|
313
|
+
}
|
|
314
|
+
await (0, import_promises3.writeFile)(
|
|
315
|
+
(0, import_node_path4.join)(temporaryDirectory, "manifest.json"),
|
|
316
|
+
JSON.stringify({
|
|
317
|
+
directoryName: result.directoryName,
|
|
318
|
+
manifest: result.manifest
|
|
319
|
+
}),
|
|
320
|
+
"utf8"
|
|
321
|
+
);
|
|
322
|
+
await (0, import_promises3.rm)(finalDirectory, {
|
|
323
|
+
recursive: true,
|
|
324
|
+
force: true
|
|
325
|
+
});
|
|
326
|
+
await (0, import_promises3.rename)(temporaryDirectory, finalDirectory);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// src/playlist.ts
|
|
330
|
+
var import_node_path5 = require("path");
|
|
331
|
+
function slugify(filename) {
|
|
332
|
+
return filename.replace((0, import_node_path5.extname)(filename), "").replace(/[^a-zA-Z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase() || "video";
|
|
333
|
+
}
|
|
334
|
+
function createMasterPlaylist(variants) {
|
|
335
|
+
const lines = ["#EXTM3U", "#EXT-X-VERSION:7"];
|
|
336
|
+
for (const variant of variants) {
|
|
337
|
+
const bandwidth = Math.round(bitrateToNumber(variant.bitrate) * 1.15);
|
|
338
|
+
lines.push(
|
|
339
|
+
`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth}`,
|
|
340
|
+
`${variant.height}p/index.m3u8`
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
return `${lines.join("\n")}
|
|
344
|
+
`;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// src/hls.ts
|
|
348
|
+
async function generateHls(source, cacheRoot, options) {
|
|
349
|
+
const key = await getCacheKey(source, options);
|
|
350
|
+
const cached = await readCache(cacheRoot, key);
|
|
351
|
+
if (cached) {
|
|
352
|
+
console.log(`[vite-plugin-hls] cache hit ${source}`);
|
|
353
|
+
return cached;
|
|
354
|
+
}
|
|
355
|
+
console.log(`[vite-plugin-hls] encoding ${source}`);
|
|
356
|
+
const temporaryDirectory = await createEncodeDirectory();
|
|
357
|
+
try {
|
|
358
|
+
const videoName = slugify((0, import_node_path6.basename)(source, (0, import_node_path6.extname)(source)));
|
|
359
|
+
const directoryName = `${videoName}-${key.slice(0, 12)}`;
|
|
360
|
+
let manifest;
|
|
361
|
+
if (options.mode === "single") {
|
|
362
|
+
await encodeVariant(source, temporaryDirectory, options);
|
|
363
|
+
manifest = "index.m3u8";
|
|
364
|
+
} else {
|
|
365
|
+
for (const variant of options.variants) {
|
|
366
|
+
await encodeVariant(
|
|
367
|
+
source,
|
|
368
|
+
(0, import_node_path6.join)(temporaryDirectory, `${variant.height}p`),
|
|
369
|
+
options,
|
|
370
|
+
{
|
|
371
|
+
height: variant.height,
|
|
372
|
+
bitrate: variant.bitrate
|
|
373
|
+
}
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
const master = createMasterPlaylist(options.variants);
|
|
377
|
+
await (0, import_promises4.writeFile)((0, import_node_path6.join)(temporaryDirectory, "master.m3u8"), master, "utf8");
|
|
378
|
+
manifest = "master.m3u8";
|
|
379
|
+
}
|
|
380
|
+
const result = {
|
|
381
|
+
directoryName,
|
|
382
|
+
manifest,
|
|
383
|
+
files: await collectFiles(temporaryDirectory)
|
|
384
|
+
};
|
|
385
|
+
await writeCache(cacheRoot, key, result);
|
|
386
|
+
console.log(`[vite-plugin-hls] generated ${directoryName}/${manifest}`);
|
|
387
|
+
return result;
|
|
388
|
+
} finally {
|
|
389
|
+
await removeEncodeDirectory(temporaryDirectory);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/assets.ts
|
|
394
|
+
function emitHls(context, result, options) {
|
|
395
|
+
const prefix = `${options.outputDir}/${result.directoryName}`;
|
|
396
|
+
const manifestSource = result.files.get(result.manifest);
|
|
397
|
+
if (!manifestSource) {
|
|
398
|
+
throw new Error(`[vite-plugin-hls] Missing manifest ${result.manifest}`);
|
|
399
|
+
}
|
|
400
|
+
context.emitFile({
|
|
401
|
+
type: "asset",
|
|
402
|
+
fileName: `${prefix}/${result.manifest}`,
|
|
403
|
+
source: manifestSource
|
|
404
|
+
});
|
|
405
|
+
for (const [filename, data] of result.files) {
|
|
406
|
+
if (filename === result.manifest) {
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
context.emitFile({
|
|
410
|
+
type: "asset",
|
|
411
|
+
fileName: `${prefix}/${filename}`,
|
|
412
|
+
source: data
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
function publicManifestExpression(result, options) {
|
|
417
|
+
const path = `${options.outputDir}/${result.directoryName}/${result.manifest}`;
|
|
418
|
+
return `import.meta.env.BASE_URL + ${JSON.stringify(path)}`;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// src/plugin.ts
|
|
422
|
+
var VIRTUAL_PREFIX2 = "\0vite-plugin-hls:";
|
|
423
|
+
function hlsVideos(input) {
|
|
424
|
+
const options = resolveOptions(input);
|
|
425
|
+
let config;
|
|
426
|
+
const resolvedSources = /* @__PURE__ */ new Map();
|
|
427
|
+
const generated = /* @__PURE__ */ new Map();
|
|
428
|
+
return {
|
|
429
|
+
name: "vite-plugin-hls",
|
|
430
|
+
apply: "build",
|
|
431
|
+
enforce: "pre",
|
|
432
|
+
configResolved(resolved) {
|
|
433
|
+
config = resolved;
|
|
434
|
+
},
|
|
435
|
+
async resolveId(source, importer) {
|
|
436
|
+
if (!importer || !isVideoSource(source)) {
|
|
437
|
+
return void 0;
|
|
438
|
+
}
|
|
439
|
+
const resolved = await resolveVideoSource(source, importer, this);
|
|
440
|
+
if (!resolved) {
|
|
441
|
+
return void 0;
|
|
442
|
+
}
|
|
443
|
+
const id = virtualIdForSource(resolved);
|
|
444
|
+
resolvedSources.set(id, resolved);
|
|
445
|
+
return id;
|
|
446
|
+
},
|
|
447
|
+
async load(id, loadOptions) {
|
|
448
|
+
if (!id.startsWith(VIRTUAL_PREFIX2)) {
|
|
449
|
+
return void 0;
|
|
450
|
+
}
|
|
451
|
+
const source = resolvedSources.get(id) ?? sourceFromVirtualId(id);
|
|
452
|
+
let result = generated.get(source);
|
|
453
|
+
if (!result) {
|
|
454
|
+
result = await generateHls(source, config.cacheDir, options);
|
|
455
|
+
generated.set(source, result);
|
|
456
|
+
}
|
|
457
|
+
if (!loadOptions?.ssr) {
|
|
458
|
+
emitHls(this, result, options);
|
|
459
|
+
}
|
|
460
|
+
const manifest = publicManifestExpression(result, options);
|
|
461
|
+
return `
|
|
462
|
+
export default ${manifest};
|
|
463
|
+
`;
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// src/index.ts
|
|
469
|
+
var index_default = hlsVideos;
|
|
470
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
471
|
+
0 && (module.exports = {
|
|
472
|
+
hlsVideos
|
|
473
|
+
});
|
|
474
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/options.ts","../src/resolve.ts","../src/hls.ts","../src/encoder.ts","../src/bitrate.ts","../src/cache.ts","../src/fs.ts","../src/playlist.ts","../src/assets.ts","../src/plugin.ts"],"sourcesContent":["import { hlsVideos } from \"./plugin\";\n\nexport { hlsVideos };\nexport default hlsVideos;\n\nexport type { HlsPluginOptions, HlsVariant } from \"./types\";\n","import ffmpegStatic from \"ffmpeg-static\";\n\nimport type { HlsPluginOptions, ResolvedHlsOptions } from \"./types\";\n\nexport function resolveOptions(\n input: HlsPluginOptions = {},\n): ResolvedHlsOptions {\n const common = {\n ffmpegPath: input.ffmpegPath ?? ffmpegStatic ?? \"ffmpeg\",\n\n segmentDuration: input.segmentDuration ?? 4,\n\n segmentType: input.segmentType ?? \"fmp4\",\n\n outputDir: input.outputDir ?? \"assets/hls\",\n\n preset: input.preset ?? \"medium\",\n\n crf: input.crf ?? 23,\n };\n\n if (input.mode === \"adaptive\") {\n if (!input.variants || input.variants.length === 0) {\n throw new Error(\n \"[vite-plugin-hls] Adaptive mode requires at least one variant.\",\n );\n }\n\n return {\n ...common,\n mode: \"adaptive\",\n variants: input.variants,\n };\n }\n\n return {\n ...common,\n mode: \"single\",\n };\n}\n","import { extname } from \"node:path\";\n\nimport type { PluginContext } from \"rolldown\";\n\nconst VIDEO_EXTENSIONS = new Set([\n \".mp4\",\n \".mov\",\n \".m4v\",\n \".webm\",\n \".mkv\",\n \".avi\",\n]);\n\nconst VIRTUAL_PREFIX = \"\\0vite-plugin-hls:\";\n\nexport function isVideoSource(source: string): boolean {\n const pathname = source.split(\"?\")[0] ?? source;\n\n return VIDEO_EXTENSIONS.has(extname(pathname).toLowerCase());\n}\n\nexport function virtualIdForSource(source: string): string {\n return `${VIRTUAL_PREFIX}${encodeURIComponent(source)}`;\n}\n\nexport function sourceFromVirtualId(id: string): string {\n return decodeURIComponent(id.slice(VIRTUAL_PREFIX.length));\n}\n\nexport async function resolveVideoSource(\n source: string,\n importer: string,\n context: PluginContext,\n): Promise<string | undefined> {\n if (!isVideoSource(source)) {\n return undefined;\n }\n\n const resolved = await context.resolve(source, importer, {\n skipSelf: true,\n });\n\n if (!resolved || resolved.external) {\n return undefined;\n }\n\n /*\n * Queries such as ?url are irrelevant here.\n * FFmpeg needs the physical file.\n */\n return resolved.id.split(\"?\", 1)[0];\n}\n","import { basename, extname, join } from \"node:path\";\nimport { writeFile } from \"node:fs/promises\";\n\nimport {\n encodeVariant,\n createEncodeDirectory,\n removeEncodeDirectory,\n} from \"./encoder\";\nimport { readCache, getCacheKey, writeCache } from \"./cache\";\nimport { collectFiles } from \"./fs\";\nimport { slugify, createMasterPlaylist } from \"./playlist\";\nimport type { CachedHls, ResolvedHlsOptions } from \"./types\";\n\nexport async function generateHls(\n source: string,\n cacheRoot: string,\n options: ResolvedHlsOptions,\n): Promise<CachedHls> {\n const key = await getCacheKey(source, options);\n\n const cached = await readCache(cacheRoot, key);\n\n if (cached) {\n console.log(`[vite-plugin-hls] cache hit ${source}`);\n\n return cached;\n }\n\n console.log(`[vite-plugin-hls] encoding ${source}`);\n\n const temporaryDirectory = await createEncodeDirectory();\n\n try {\n const videoName = slugify(basename(source, extname(source)));\n\n const directoryName = `${videoName}-${key.slice(0, 12)}`;\n\n let manifest: string;\n\n if (options.mode === \"single\") {\n await encodeVariant(source, temporaryDirectory, options);\n\n manifest = \"index.m3u8\";\n } else {\n for (const variant of options.variants) {\n await encodeVariant(\n source,\n join(temporaryDirectory, `${variant.height}p`),\n options,\n {\n height: variant.height,\n bitrate: variant.bitrate,\n },\n );\n }\n\n const master = createMasterPlaylist(options.variants);\n\n await writeFile(join(temporaryDirectory, \"master.m3u8\"), master, \"utf8\");\n\n manifest = \"master.m3u8\";\n }\n\n const result: CachedHls = {\n directoryName,\n manifest,\n files: await collectFiles(temporaryDirectory),\n };\n\n await writeCache(cacheRoot, key, result);\n\n console.log(`[vite-plugin-hls] generated ${directoryName}/${manifest}`);\n\n return result;\n } finally {\n await removeEncodeDirectory(temporaryDirectory);\n }\n}\n","import { mkdtemp, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\nimport { spawn } from \"node:child_process\";\n\nimport { bitrateToNumber } from \"./bitrate\";\nimport type { ResolvedHlsOptions } from \"./types\";\n\ninterface EncodeVariantOptions {\n height?: number;\n bitrate?: string;\n}\n\nfunction runFfmpeg(executable: string, args: string[]): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n const child = spawn(executable, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stderr = \"\";\n\n child.stderr.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on(\"error\", (error) => {\n if (\"code\" in error && error.code === \"ENOENT\") {\n reject(\n new Error(\n [\n \"[vite-plugin-hls] ffmpeg was not found.\",\n `Executable: ${executable}`,\n \"Set ffmpegPath or install ffmpeg.\",\n ].join(\"\\n\"),\n ),\n );\n return;\n }\n\n reject(error);\n });\n\n child.on(\"close\", (code) => {\n if (code === 0) {\n resolvePromise();\n return;\n }\n\n reject(\n new Error(\n [\n `[vite-plugin-hls] ffmpeg failed with exit code ${code ?? \"unknown\"}.`,\n stderr.trim(),\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n ),\n );\n });\n });\n}\n\nexport async function encodeVariant(\n source: string,\n outputDirectory: string,\n options: ResolvedHlsOptions,\n variant: EncodeVariantOptions = {},\n): Promise<void> {\n const extension = options.segmentType === \"fmp4\" ? \"m4s\" : \"ts\";\n\n const playlist = join(outputDirectory, \"index.m3u8\");\n\n const args: string[] = [\n \"-y\",\n \"-i\",\n source,\n\n \"-map\",\n \"0:v:0\",\n \"-map\",\n \"0:a:0?\",\n ];\n\n /*\n * SINGLE MODE:\n *\n * Do not encode the streams again.\n * FFmpeg only remuxes/segments them into HLS.\n */\n if (options.mode === \"single\") {\n args.push(\n \"-c:v\",\n \"copy\",\n\n \"-c:a\",\n \"copy\",\n );\n } else {\n /*\n * ADAPTIVE MODE:\n *\n * Each rendition needs to be encoded because\n * resolution and bitrate are changed.\n */\n args.push(\n \"-c:v\",\n \"libx264\",\n\n \"-preset\",\n options.preset,\n\n \"-crf\",\n String(options.crf),\n\n \"-pix_fmt\",\n \"yuv420p\",\n\n \"-c:a\",\n \"aac\",\n\n \"-b:a\",\n \"128k\",\n );\n\n if (variant.height !== undefined) {\n args.push(\n \"-vf\",\n `scale=-2:${variant.height}:force_original_aspect_ratio=decrease`,\n );\n }\n\n if (variant.bitrate !== undefined) {\n const bitrate = bitrateToNumber(variant.bitrate);\n\n args.push(\n \"-b:v\",\n variant.bitrate,\n\n \"-maxrate\",\n variant.bitrate,\n\n \"-bufsize\",\n String(Math.round(bitrate * 1.5)),\n );\n }\n }\n\n args.push(\n \"-f\",\n \"hls\",\n\n \"-hls_time\",\n String(options.segmentDuration),\n\n \"-hls_playlist_type\",\n \"vod\",\n\n \"-hls_segment_filename\",\n join(outputDirectory, `segment-%05d.${extension}`),\n );\n\n if (options.segmentType === \"fmp4\") {\n args.push(\n \"-hls_segment_type\",\n \"fmp4\",\n\n \"-hls_fmp4_init_filename\",\n \"init.mp4\",\n );\n }\n\n args.push(playlist);\n\n await runFfmpeg(options.ffmpegPath, args);\n}\n\nexport async function createEncodeDirectory(): Promise<string> {\n return mkdtemp(join(tmpdir(), \"vite-plugin-hls-\"));\n}\n\nexport async function removeEncodeDirectory(directory: string): Promise<void> {\n await rm(directory, {\n recursive: true,\n force: true,\n });\n}\n","/**\n * Converts a human-readable bitrate such as \"1200k\", \"2.5M\" or \"1G\"\n * into the equivalent number of bits per second.\n */\nexport function bitrateToNumber(bitrate: string): number {\n const match = /^([\\d.]+)\\s*([kKmMgG]?)$/.exec(bitrate.trim());\n\n if (!match) {\n throw new Error(`[vite-plugin-hls] Invalid bitrate: ${bitrate}`);\n }\n\n const amount = Number(match[1]);\n\n const suffix = (match[2] ?? \"\").toLowerCase();\n\n const multiplier =\n suffix === \"g\"\n ? 1_000_000_000\n : suffix === \"m\"\n ? 1_000_000\n : suffix === \"k\"\n ? 1_000\n : 1;\n\n return Math.round(amount * multiplier);\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\n\nimport { collectFiles } from \"./fs\";\nimport type { CachedHls, ResolvedHlsOptions } from \"./types\";\n\ninterface CacheManifest {\n directoryName: string;\n manifest: string;\n}\n\nexport async function getCacheKey(\n source: string,\n options: ResolvedHlsOptions,\n): Promise<string> {\n const sourceData = await readFile(source);\n\n return createHash(\"sha256\")\n .update(sourceData)\n .update(JSON.stringify(options))\n .digest(\"hex\");\n}\n\nexport async function readCache(\n cacheRoot: string,\n key: string,\n): Promise<CachedHls | undefined> {\n const directory = join(cacheRoot, \"hls\", key);\n\n try {\n await stat(directory);\n } catch {\n return undefined;\n }\n\n const metadata = JSON.parse(\n await readFile(join(directory, \"manifest.json\"), \"utf8\"),\n ) as CacheManifest;\n\n const files = await collectFiles(directory);\n\n // manifest.json is internal bookkeeping, never an emitted asset.\n files.delete(\"manifest.json\");\n\n return {\n directoryName: metadata.directoryName,\n\n manifest: metadata.manifest,\n\n files,\n };\n}\n\nexport async function writeCache(\n cacheRoot: string,\n key: string,\n result: CachedHls,\n): Promise<void> {\n const temporaryDirectory = join(cacheRoot, \"hls\", `${key}.tmp`);\n\n const finalDirectory = join(cacheRoot, \"hls\", key);\n\n await rm(temporaryDirectory, {\n recursive: true,\n force: true,\n });\n\n await mkdir(temporaryDirectory, {\n recursive: true,\n });\n\n for (const [filename, data] of result.files) {\n const destination = join(temporaryDirectory, filename);\n\n await mkdir(resolve(destination, \"..\"), {\n recursive: true,\n });\n\n await writeFile(destination, data);\n }\n\n await writeFile(\n join(temporaryDirectory, \"manifest.json\"),\n JSON.stringify({\n directoryName: result.directoryName,\n manifest: result.manifest,\n } satisfies CacheManifest),\n \"utf8\",\n );\n\n await rm(finalDirectory, {\n recursive: true,\n force: true,\n });\n\n await rename(temporaryDirectory, finalDirectory);\n}\n","import { readFile, readdir } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\n/**\n * Recursively collects every file under `directory` into a map of\n * directory-relative POSIX paths to their buffer contents.\n */\nexport async function collectFiles(\n directory: string,\n): Promise<Map<string, Buffer>> {\n const result = new Map<string, Buffer>();\n\n async function visit(current: string): Promise<void> {\n for (const entry of await readdir(current, { withFileTypes: true })) {\n const filename = join(current, entry.name);\n\n if (entry.isDirectory()) {\n await visit(filename);\n continue;\n }\n\n result.set(\n relative(directory, filename).replaceAll(\"\\\\\", \"/\"),\n await readFile(filename),\n );\n }\n }\n\n await visit(directory);\n\n return result;\n}\n","import { extname } from \"node:path\";\n\nimport { bitrateToNumber } from \"./bitrate\";\nimport type { HlsVariant } from \"./types\";\n\n/** Turns a filename into a filesystem-safe slug used for the output folder. */\nexport function slugify(filename: string): string {\n return (\n filename\n .replace(extname(filename), \"\")\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .toLowerCase() || \"video\"\n );\n}\n\n/** Builds the adaptive master playlist pointing at each rendition. */\nexport function createMasterPlaylist(variants: readonly HlsVariant[]): string {\n const lines = [\"#EXTM3U\", \"#EXT-X-VERSION:7\"];\n\n for (const variant of variants) {\n // BANDWIDTH is an estimate derived from the configured bitrate.\n const bandwidth = Math.round(bitrateToNumber(variant.bitrate) * 1.15);\n\n lines.push(\n `#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth}`,\n `${variant.height}p/index.m3u8`,\n );\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n","import type { PluginContext } from \"rolldown\";\n\nimport type { CachedHls, ResolvedHlsOptions } from \"./types\";\n\nexport function emitHls(\n context: PluginContext,\n result: CachedHls,\n options: ResolvedHlsOptions,\n): void {\n const prefix = `${options.outputDir}/${result.directoryName}`;\n\n const manifestSource = result.files.get(result.manifest);\n\n if (!manifestSource) {\n throw new Error(`[vite-plugin-hls] Missing manifest ${result.manifest}`);\n }\n\n context.emitFile({\n type: \"asset\",\n fileName: `${prefix}/${result.manifest}`,\n source: manifestSource,\n });\n\n for (const [filename, data] of result.files) {\n if (filename === result.manifest) {\n continue;\n }\n\n context.emitFile({\n type: \"asset\",\n fileName: `${prefix}/${filename}`,\n source: data,\n });\n }\n}\n\nexport function publicManifestExpression(\n result: CachedHls,\n options: ResolvedHlsOptions,\n): string {\n const path = `${options.outputDir}/${result.directoryName}/${result.manifest}`;\n\n /*\n * BASE_URL is replaced by Vite in both the client\n * and SSR builds.\n *\n * Examples:\n *\n * \"/\" -> /assets/hls/...\n * \"/notes/\" -> /notes/assets/hls/...\n * \"./\" -> ./assets/hls/...\n */\n return `import.meta.env.BASE_URL + ${JSON.stringify(path)}`;\n}\n","import type { Plugin, ResolvedConfig } from \"vite\";\n\nimport { resolveOptions } from \"./options\";\nimport {\n isVideoSource,\n resolveVideoSource,\n sourceFromVirtualId,\n virtualIdForSource,\n} from \"./resolve\";\nimport { generateHls } from \"./hls\";\nimport { emitHls, publicManifestExpression } from \"./assets\";\nimport type { HlsPluginOptions } from \"./types\";\n\nconst VIRTUAL_PREFIX = \"\\0vite-plugin-hls:\";\n\nexport function hlsVideos(input?: HlsPluginOptions): Plugin {\n const options = resolveOptions(input);\n\n let config: ResolvedConfig;\n\n const resolvedSources = new Map<string, string>();\n\n /*\n * This only caches inside the current Vite build.\n *\n * The persistent cache in cache.ts handles the\n * client/server build boundary.\n */\n const generated = new Map<string, Awaited<ReturnType<typeof generateHls>>>();\n\n return {\n name: \"vite-plugin-hls\",\n\n apply: \"build\",\n\n enforce: \"pre\",\n\n configResolved(resolved) {\n config = resolved;\n },\n\n async resolveId(source, importer) {\n if (!importer || !isVideoSource(source)) {\n return undefined;\n }\n\n const resolved = await resolveVideoSource(source, importer, this);\n\n if (!resolved) {\n return undefined;\n }\n\n const id = virtualIdForSource(resolved);\n\n resolvedSources.set(id, resolved);\n\n return id;\n },\n\n async load(id, loadOptions) {\n if (!id.startsWith(VIRTUAL_PREFIX)) {\n return undefined;\n }\n\n const source = resolvedSources.get(id) ?? sourceFromVirtualId(id);\n\n let result = generated.get(source);\n\n if (!result) {\n result = await generateHls(source, config.cacheDir, options);\n\n generated.set(source, result);\n }\n\n /*\n * Important:\n *\n * The SSR build must NOT use Vite's emitted-file\n * URL because that resolves to a file:// URL.\n *\n * We only emit the actual files during the client\n * build. SSR receives the public URL directly.\n */\n if (!loadOptions?.ssr) {\n emitHls(this, result, options);\n }\n\n const manifest = publicManifestExpression(result, options);\n\n return `\n export default ${manifest};\n `;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,2BAAyB;AAIlB,SAAS,eACd,QAA0B,CAAC,GACP;AACpB,QAAM,SAAS;AAAA,IACb,YAAY,MAAM,cAAc,qBAAAA,WAAgB;AAAA,IAEhD,iBAAiB,MAAM,mBAAmB;AAAA,IAE1C,aAAa,MAAM,eAAe;AAAA,IAElC,WAAW,MAAM,aAAa;AAAA,IAE9B,QAAQ,MAAM,UAAU;AAAA,IAExB,KAAK,MAAM,OAAO;AAAA,EACpB;AAEA,MAAI,MAAM,SAAS,YAAY;AAC7B,QAAI,CAAC,MAAM,YAAY,MAAM,SAAS,WAAW,GAAG;AAClD,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,MAAM;AAAA,MACN,UAAU,MAAM;AAAA,IAClB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM;AAAA,EACR;AACF;;;ACvCA,uBAAwB;AAIxB,IAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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BAAQ,MAAM,QAAQ,OAAO;AAAA,MAC/B;AAEA,YAAM,WAAW,yBAAyB,QAAQ,OAAO;AAEzD,aAAO;AAAA,yBACY,QAAQ;AAAA;AAAA,IAE7B;AAAA,EACF;AACF;;;AV3FA,IAAO,gBAAQ;","names":["ffmpegStatic","import_node_path","import_promises","import_node_path","import_promises","import_node_path","import_promises","import_node_path","import_node_path","VIRTUAL_PREFIX"]}
|