@molecule/api-media-streaming-hls 1.0.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 ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-media-streaming-hls` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-media-streaming-hls is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,48 @@
1
+ /**
2
+ * HLS media streaming provider for molecule.dev.
3
+ *
4
+ * Provides HLS (HTTP Live Streaming) support via ffmpeg for media segmentation
5
+ * and transcoding, with pure-TypeScript M3U8 playlist generation. Requires
6
+ * ffmpeg to be installed on the host system.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { setProvider, createStream } from '@molecule/api-media-streaming'
11
+ * import { provider } from '@molecule/api-media-streaming-hls'
12
+ *
13
+ * setProvider(provider)
14
+ *
15
+ * const manifest = await createStream('/path/to/video.mp4', {
16
+ * segmentDuration: 6,
17
+ * protocol: 'hls',
18
+ * })
19
+ * console.log(manifest.manifestUri) // '/hls-…/index.m3u8'
20
+ * ```
21
+ *
22
+ * @remarks
23
+ * - **Requires the `ffmpeg` binary on the host** (resolved via PATH, or set
24
+ * `createProvider({ ffmpegPath })`). A missing binary fails at first
25
+ * `createStream()`/`transcode()` call with `spawn ffmpeg ENOENT` — verify
26
+ * with `ffmpeg -version` before shipping.
27
+ * - **The default output directory is `os.tmpdir()`** — volatile and served by
28
+ * nothing. Pass `createProvider({ outputBasePath })` pointing at a directory
29
+ * your server exposes (see the core remarks), or serve bytes through
30
+ * `getSegment()` / `generateManifest()` endpoints.
31
+ * - `createStream()` also caches every segment `Buffer` in an in-process map
32
+ * (never evicted) so `getSegment()` is fast; memory grows by the full video
33
+ * size per stream. `getSegment()` disk fallback looks ONLY under
34
+ * `outputBasePath/<streamId>/` — a per-call `createStream(..., { outputPath })`
35
+ * override writes segments where the fallback cannot find them after a
36
+ * restart, and `transcode()` ignores `outputPath` entirely (always writes
37
+ * under `outputBasePath`).
38
+ * - `ffprobePath` in `HlsConfig` is currently RESERVED — no ffprobe call exists
39
+ * yet; segment durations come from the requested `segmentDuration`.
40
+ *
41
+ * @module
42
+ */
43
+ export * from './browser-guard.js';
44
+ export * from './m3u8.js';
45
+ export * from './provider.js';
46
+ export * from './types.js';
47
+ export * from './validate.js';
48
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * HLS media streaming provider for molecule.dev.
3
+ *
4
+ * Provides HLS (HTTP Live Streaming) support via ffmpeg for media segmentation
5
+ * and transcoding, with pure-TypeScript M3U8 playlist generation. Requires
6
+ * ffmpeg to be installed on the host system.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { setProvider, createStream } from '@molecule/api-media-streaming'
11
+ * import { provider } from '@molecule/api-media-streaming-hls'
12
+ *
13
+ * setProvider(provider)
14
+ *
15
+ * const manifest = await createStream('/path/to/video.mp4', {
16
+ * segmentDuration: 6,
17
+ * protocol: 'hls',
18
+ * })
19
+ * console.log(manifest.manifestUri) // '/hls-…/index.m3u8'
20
+ * ```
21
+ *
22
+ * @remarks
23
+ * - **Requires the `ffmpeg` binary on the host** (resolved via PATH, or set
24
+ * `createProvider({ ffmpegPath })`). A missing binary fails at first
25
+ * `createStream()`/`transcode()` call with `spawn ffmpeg ENOENT` — verify
26
+ * with `ffmpeg -version` before shipping.
27
+ * - **The default output directory is `os.tmpdir()`** — volatile and served by
28
+ * nothing. Pass `createProvider({ outputBasePath })` pointing at a directory
29
+ * your server exposes (see the core remarks), or serve bytes through
30
+ * `getSegment()` / `generateManifest()` endpoints.
31
+ * - `createStream()` also caches every segment `Buffer` in an in-process map
32
+ * (never evicted) so `getSegment()` is fast; memory grows by the full video
33
+ * size per stream. `getSegment()` disk fallback looks ONLY under
34
+ * `outputBasePath/<streamId>/` — a per-call `createStream(..., { outputPath })`
35
+ * override writes segments where the fallback cannot find them after a
36
+ * restart, and `transcode()` ignores `outputPath` entirely (always writes
37
+ * under `outputBasePath`).
38
+ * - `ffprobePath` in `HlsConfig` is currently RESERVED — no ffprobe call exists
39
+ * yet; segment durations come from the requested `segmentDuration`.
40
+ *
41
+ * @module
42
+ */
43
+ export * from './browser-guard.js';
44
+ export * from './m3u8.js';
45
+ export * from './provider.js';
46
+ export * from './types.js';
47
+ export * from './validate.js';
package/dist/m3u8.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Pure-TypeScript M3U8 (HLS playlist) generation utilities.
3
+ *
4
+ * Generates Media Playlists, Master Playlists (adaptive bitrate), and
5
+ * parses segment metadata — all without external dependencies.
6
+ *
7
+ * @module
8
+ */
9
+ import type { StreamSegment, TranscodeVariant } from '@molecule/api-media-streaming';
10
+ /**
11
+ * Options for generating an M3U8 media playlist.
12
+ */
13
+ export interface M3u8PlaylistOptions {
14
+ /** HLS playlist version. Defaults to `3`. */
15
+ version?: number;
16
+ /** Target segment duration in seconds. Defaults to the maximum segment duration. */
17
+ targetDuration?: number;
18
+ /** Whether this is a VOD (complete) or live (in-progress) playlist. Defaults to `'vod'`. */
19
+ playlistType?: 'vod' | 'event';
20
+ /** Media sequence number for the first segment. Defaults to `0`. */
21
+ mediaSequence?: number;
22
+ }
23
+ /**
24
+ * Generates an M3U8 media playlist from a list of stream segments.
25
+ *
26
+ * @param segments - Ordered list of stream segments.
27
+ * @param options - Playlist generation options.
28
+ * @returns The M3U8 playlist content as a string.
29
+ */
30
+ export declare const generateMediaPlaylist: (segments: StreamSegment[], options?: M3u8PlaylistOptions) => string;
31
+ /**
32
+ * Generates an M3U8 master playlist for adaptive bitrate streaming.
33
+ *
34
+ * @param variants - The transcoded variant streams.
35
+ * @returns The master M3U8 playlist content as a string.
36
+ */
37
+ export declare const generateMasterPlaylist: (variants: TranscodeVariant[]) => string;
38
+ //# sourceMappingURL=m3u8.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"m3u8.d.ts","sourceRoot":"","sources":["../src/m3u8.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAA;AAEpF;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAA;IAEhB,oFAAoF;IACpF,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB,4FAA4F;IAC5F,YAAY,CAAC,EAAE,KAAK,GAAG,OAAO,CAAA;IAE9B,oEAAoE;IACpE,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,GAChC,UAAU,aAAa,EAAE,EACzB,UAAS,mBAAwB,KAChC,MAwBF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GAAI,UAAU,gBAAgB,EAAE,KAAG,MAarE,CAAA"}
package/dist/m3u8.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Pure-TypeScript M3U8 (HLS playlist) generation utilities.
3
+ *
4
+ * Generates Media Playlists, Master Playlists (adaptive bitrate), and
5
+ * parses segment metadata — all without external dependencies.
6
+ *
7
+ * @module
8
+ */
9
+ /**
10
+ * Generates an M3U8 media playlist from a list of stream segments.
11
+ *
12
+ * @param segments - Ordered list of stream segments.
13
+ * @param options - Playlist generation options.
14
+ * @returns The M3U8 playlist content as a string.
15
+ */
16
+ export const generateMediaPlaylist = (segments, options = {}) => {
17
+ const version = options.version ?? 3;
18
+ const targetDuration = options.targetDuration ?? Math.ceil(Math.max(...segments.map((s) => s.duration), 0));
19
+ const mediaSequence = options.mediaSequence ?? 0;
20
+ const playlistType = options.playlistType ?? 'vod';
21
+ const lines = [
22
+ '#EXTM3U',
23
+ `#EXT-X-VERSION:${version}`,
24
+ `#EXT-X-TARGETDURATION:${targetDuration}`,
25
+ `#EXT-X-MEDIA-SEQUENCE:${mediaSequence}`,
26
+ `#EXT-X-PLAYLIST-TYPE:${playlistType.toUpperCase()}`,
27
+ ];
28
+ for (const segment of segments) {
29
+ lines.push(`#EXTINF:${segment.duration.toFixed(6)},`);
30
+ lines.push(segment.uri);
31
+ }
32
+ lines.push('#EXT-X-ENDLIST');
33
+ lines.push('');
34
+ return lines.join('\n');
35
+ };
36
+ /**
37
+ * Generates an M3U8 master playlist for adaptive bitrate streaming.
38
+ *
39
+ * @param variants - The transcoded variant streams.
40
+ * @returns The master M3U8 playlist content as a string.
41
+ */
42
+ export const generateMasterPlaylist = (variants) => {
43
+ const lines = ['#EXTM3U'];
44
+ for (const variant of variants) {
45
+ lines.push(`#EXT-X-STREAM-INF:BANDWIDTH=${variant.bitrate},RESOLUTION=${variant.width}x${variant.height},NAME="${variant.profile}"`);
46
+ lines.push(variant.uri);
47
+ }
48
+ lines.push('');
49
+ return lines.join('\n');
50
+ };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * HLS implementation of StreamingProvider.
3
+ *
4
+ * Uses ffmpeg (via `child_process`) for media segmentation and transcoding,
5
+ * and pure-TypeScript M3U8 generation for playlist creation. Requires ffmpeg
6
+ * to be installed on the host system.
7
+ *
8
+ * @module
9
+ */
10
+ import type { StreamingProvider } from '@molecule/api-media-streaming';
11
+ import type { HlsConfig } from './types.js';
12
+ /**
13
+ * Creates an HLS streaming provider.
14
+ *
15
+ * @param config - Optional provider configuration.
16
+ * @returns A `StreamingProvider` backed by HLS / ffmpeg.
17
+ */
18
+ export declare const createProvider: (config?: HlsConfig) => StreamingProvider;
19
+ /**
20
+ * The provider implementation with default configuration.
21
+ */
22
+ export declare const provider: StreamingProvider;
23
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAQH,OAAO,KAAK,EACV,iBAAiB,EAOlB,MAAM,+BAA+B,CAAA;AAGtC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAwD3C;;;;;GAKG;AACH,eAAO,MAAM,cAAc,GAAI,SAAQ,SAAc,KAAG,iBA8JvD,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,iBAAoC,CAAA"}
@@ -0,0 +1,202 @@
1
+ /**
2
+ * HLS implementation of StreamingProvider.
3
+ *
4
+ * Uses ffmpeg (via `child_process`) for media segmentation and transcoding,
5
+ * and pure-TypeScript M3U8 generation for playlist creation. Requires ffmpeg
6
+ * to be installed on the host system.
7
+ *
8
+ * @module
9
+ */
10
+ import { execFile } from 'node:child_process';
11
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { promisify } from 'node:util';
15
+ import { generateMasterPlaylist, generateMediaPlaylist } from './m3u8.js';
16
+ import { assertSafePathComponent, assertSegmentIndex, resolveWithinBase } from './validate.js';
17
+ const execFileAsync = promisify(execFile);
18
+ let streamCounter = 0;
19
+ /**
20
+ * Generates a unique stream identifier.
21
+ *
22
+ * @returns A unique stream ID string.
23
+ */
24
+ const generateStreamId = () => {
25
+ streamCounter += 1;
26
+ return `hls-${Date.now()}-${streamCounter}`;
27
+ };
28
+ /**
29
+ * Writes a Buffer input to a temporary file for ffmpeg processing.
30
+ *
31
+ * @param input - The media data.
32
+ * @param dir - The directory to write to.
33
+ * @returns The path to the written file.
34
+ */
35
+ const prepareInput = async (input, dir) => {
36
+ if (typeof input === 'string') {
37
+ return input;
38
+ }
39
+ const inputPath = join(dir, 'input.tmp');
40
+ await writeFile(inputPath, input);
41
+ return inputPath;
42
+ };
43
+ /**
44
+ * Parses segment files from an output directory and builds segment metadata.
45
+ *
46
+ * @param dir - The directory containing `.ts` segment files.
47
+ * @param baseUri - Base URI prefix for segment URIs.
48
+ * @param segmentDuration - Expected segment duration in seconds.
49
+ * @returns An array of stream segments.
50
+ */
51
+ const parseSegments = async (dir, baseUri, segmentDuration) => {
52
+ const files = await readdir(dir);
53
+ const tsFiles = files.filter((f) => f.endsWith('.ts')).sort();
54
+ return tsFiles.map((file, index) => ({
55
+ index,
56
+ duration: segmentDuration,
57
+ uri: `${baseUri}/${file}`,
58
+ }));
59
+ };
60
+ /**
61
+ * Creates an HLS streaming provider.
62
+ *
63
+ * @param config - Optional provider configuration.
64
+ * @returns A `StreamingProvider` backed by HLS / ffmpeg.
65
+ */
66
+ export const createProvider = (config = {}) => {
67
+ const ffmpegPath = config.ffmpegPath ?? 'ffmpeg';
68
+ const outputBasePath = config.outputBasePath ?? tmpdir();
69
+ const defaultSegmentDuration = config.segmentDuration ?? 6;
70
+ const hlsVersion = config.hlsVersion ?? 3;
71
+ /** In-memory segment store keyed by `streamId:segmentIndex`. */
72
+ const segmentStore = new Map();
73
+ return {
74
+ async createStream(input, options) {
75
+ const streamId = generateStreamId();
76
+ const segmentDuration = options?.segmentDuration ?? defaultSegmentDuration;
77
+ const outputDir = join(options?.outputPath ?? outputBasePath, streamId);
78
+ await mkdir(outputDir, { recursive: true });
79
+ const inputPath = await prepareInput(input, outputDir);
80
+ await execFileAsync(ffmpegPath, [
81
+ // Restrict ffmpeg to safe protocols so a string input can't abuse dangerous
82
+ // ones (concat/gopher/ftp/subfile/unix) for LFI/SSRF escalation. [P5BONDS DiD]
83
+ '-protocol_whitelist',
84
+ 'file,crypto,data,http,https,tcp,tls',
85
+ '-i',
86
+ inputPath,
87
+ '-codec',
88
+ 'copy',
89
+ '-start_number',
90
+ '0',
91
+ '-hls_time',
92
+ String(segmentDuration),
93
+ '-hls_list_size',
94
+ '0',
95
+ '-hls_segment_filename',
96
+ join(outputDir, 'seg-%03d.ts'),
97
+ '-f',
98
+ 'hls',
99
+ join(outputDir, 'index.m3u8'),
100
+ ]);
101
+ const segments = await parseSegments(outputDir, `/${streamId}`, segmentDuration);
102
+ // Store segments for later retrieval via getSegment
103
+ for (const segment of segments) {
104
+ const fileName = segment.uri.split('/').pop();
105
+ const data = await readFile(join(outputDir, fileName));
106
+ segmentStore.set(`${streamId}:${segment.index}`, data);
107
+ }
108
+ const duration = segments.reduce((sum, s) => sum + s.duration, 0);
109
+ return {
110
+ id: streamId,
111
+ protocol: 'hls',
112
+ manifestUri: `/${streamId}/index.m3u8`,
113
+ duration,
114
+ segments,
115
+ };
116
+ },
117
+ async transcode(input, profiles) {
118
+ const streamId = generateStreamId();
119
+ const outputDir = join(outputBasePath, streamId);
120
+ await mkdir(outputDir, { recursive: true });
121
+ const inputPath = await prepareInput(input, outputDir);
122
+ const variants = [];
123
+ for (const profile of profiles) {
124
+ // Reject untrusted profile names that could escape the output dir or
125
+ // inject ffmpeg args; the validated name is safe for fs paths + URIs.
126
+ assertSafePathComponent(profile.name, 'profile name');
127
+ const profileDir = resolveWithinBase(outputDir, profile.name);
128
+ await mkdir(profileDir, { recursive: true });
129
+ const codec = profile.codec ?? 'h264';
130
+ const args = [
131
+ // Restrict ffmpeg to safe protocols (no concat/gopher/ftp/subfile). [P5BONDS DiD]
132
+ '-protocol_whitelist',
133
+ 'file,crypto,data,http,https,tcp,tls',
134
+ '-i',
135
+ inputPath,
136
+ '-c:v',
137
+ codec === 'h264' ? 'libx264' : codec,
138
+ '-b:v',
139
+ String(profile.videoBitrate),
140
+ '-c:a',
141
+ 'aac',
142
+ '-b:a',
143
+ String(profile.audioBitrate),
144
+ '-vf',
145
+ `scale=${profile.width}:${profile.height}`,
146
+ '-start_number',
147
+ '0',
148
+ '-hls_time',
149
+ String(defaultSegmentDuration),
150
+ '-hls_list_size',
151
+ '0',
152
+ '-hls_segment_filename',
153
+ join(profileDir, 'seg-%03d.ts'),
154
+ '-f',
155
+ 'hls',
156
+ join(profileDir, 'index.m3u8'),
157
+ ];
158
+ await execFileAsync(ffmpegPath, args);
159
+ variants.push({
160
+ profile: profile.name,
161
+ uri: `/${streamId}/${profile.name}/index.m3u8`,
162
+ width: profile.width,
163
+ height: profile.height,
164
+ bitrate: profile.videoBitrate,
165
+ });
166
+ }
167
+ const masterPlaylist = generateMasterPlaylist(variants);
168
+ const masterPath = join(outputDir, 'master.m3u8');
169
+ await writeFile(masterPath, masterPlaylist, 'utf-8');
170
+ return {
171
+ id: streamId,
172
+ masterManifestUri: `/${streamId}/master.m3u8`,
173
+ variants,
174
+ };
175
+ },
176
+ generateManifest(segments, options) {
177
+ return generateMediaPlaylist(segments, {
178
+ version: hlsVersion,
179
+ targetDuration: options?.segmentDuration ?? defaultSegmentDuration,
180
+ });
181
+ },
182
+ async getSegment(streamId, segmentIndex) {
183
+ // Validate caller-supplied lookup values before any fs access — an
184
+ // unvalidated streamId ('../…') would escape the output base on the
185
+ // disk-fallback path below.
186
+ assertSafePathComponent(streamId, 'stream id');
187
+ assertSegmentIndex(segmentIndex);
188
+ const key = `${streamId}:${segmentIndex}`;
189
+ const data = segmentStore.get(key);
190
+ if (!data) {
191
+ // Fall back to reading from disk
192
+ const segmentPath = resolveWithinBase(outputBasePath, streamId, `seg-${String(segmentIndex).padStart(3, '0')}.ts`);
193
+ return readFile(segmentPath);
194
+ }
195
+ return data;
196
+ },
197
+ };
198
+ };
199
+ /**
200
+ * The provider implementation with default configuration.
201
+ */
202
+ export const provider = createProvider();
@@ -0,0 +1,25 @@
1
+ /**
2
+ * HLS media streaming provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ /**
7
+ * Configuration options for the HLS streaming provider.
8
+ */
9
+ export interface HlsConfig {
10
+ /** Path to the ffmpeg binary. Defaults to `'ffmpeg'` (resolved via PATH). */
11
+ ffmpegPath?: string;
12
+ /**
13
+ * Path to the ffprobe binary. RESERVED for future use — the current
14
+ * provider never invokes ffprobe (segment durations are taken from
15
+ * `segmentDuration`, not probed). Setting this has no effect today.
16
+ */
17
+ ffprobePath?: string;
18
+ /** Base directory where stream output files are written. Defaults to `os.tmpdir()`. */
19
+ outputBasePath?: string;
20
+ /** Default segment duration in seconds. Defaults to `6`. */
21
+ segmentDuration?: number;
22
+ /** HLS playlist version. Defaults to `3`. */
23
+ hlsVersion?: number;
24
+ }
25
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,6EAA6E;IAC7E,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB,uFAAuF;IACvF,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB,4DAA4D;IAC5D,eAAe,CAAC,EAAE,MAAM,CAAA;IAExB,6CAA6C;IAC7C,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * HLS media streaming provider configuration.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Path-component validation helpers for the HLS provider.
3
+ *
4
+ * Caller-supplied values (stream ids, transcode profile names, segment
5
+ * indexes) are interpolated into filesystem paths and ffmpeg argument lists.
6
+ * If an application forwards untrusted input, an unvalidated component such as
7
+ * `../../etc` or one containing a shell metacharacter could escape the output
8
+ * directory or alter the ffmpeg invocation. These helpers fail closed: every
9
+ * such component must be a single, allow-listed path segment, and the final
10
+ * resolved path must stay inside its intended base directory.
11
+ *
12
+ * @module
13
+ */
14
+ /**
15
+ * Asserts that a caller-supplied value is a safe single path component.
16
+ *
17
+ * Rejects empty strings, the relative segments `.` and `..`, anything
18
+ * containing a path separator or NUL byte, and anything outside the
19
+ * `[A-Za-z0-9._-]` allow-list (which also rejects shell metacharacters).
20
+ *
21
+ * @param value - The caller-supplied component (e.g. a stream id or profile name).
22
+ * @param label - Human-readable name of the field, used in the error message.
23
+ * @returns The validated component, unchanged.
24
+ * @throws {Error} If the value is not a safe single path component.
25
+ */
26
+ export declare const assertSafePathComponent: (value: string, label: string) => string;
27
+ /**
28
+ * Asserts that a caller-supplied segment index is a non-negative integer.
29
+ *
30
+ * @param index - The caller-supplied segment index.
31
+ * @returns The validated index, unchanged.
32
+ * @throws {Error} If the value is not a non-negative integer.
33
+ */
34
+ export declare const assertSegmentIndex: (index: number) => number;
35
+ /**
36
+ * Resolves `parts` against `base` and asserts the result stays within `base`.
37
+ *
38
+ * Defense-in-depth on top of {@link assertSafePathComponent}: even if a
39
+ * component slipped through, the resolved absolute path is rejected unless it
40
+ * is `base` itself or a descendant of it.
41
+ *
42
+ * @param base - The intended base directory.
43
+ * @param parts - Path segments to append.
44
+ * @returns The resolved absolute path, guaranteed to be inside `base`.
45
+ * @throws {Error} If the resolved path escapes `base`.
46
+ */
47
+ export declare const resolveWithinBase: (base: string, ...parts: string[]) => string;
48
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../src/validate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAYH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,uBAAuB,GAAI,OAAO,MAAM,EAAE,OAAO,MAAM,KAAG,MActE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,GAAI,OAAO,MAAM,KAAG,MAOlD,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,EAAE,GAAG,OAAO,MAAM,EAAE,KAAG,MAOpE,CAAA"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Path-component validation helpers for the HLS provider.
3
+ *
4
+ * Caller-supplied values (stream ids, transcode profile names, segment
5
+ * indexes) are interpolated into filesystem paths and ffmpeg argument lists.
6
+ * If an application forwards untrusted input, an unvalidated component such as
7
+ * `../../etc` or one containing a shell metacharacter could escape the output
8
+ * directory or alter the ffmpeg invocation. These helpers fail closed: every
9
+ * such component must be a single, allow-listed path segment, and the final
10
+ * resolved path must stay inside its intended base directory.
11
+ *
12
+ * @module
13
+ */
14
+ import { resolve, sep } from 'node:path';
15
+ /**
16
+ * Allow-list for a single path component: ASCII alphanumerics plus `.`, `_`,
17
+ * and `-`. This excludes path separators (`/`, `\`), NUL, whitespace, and
18
+ * every shell/ffmpeg metacharacter, so a validated component is safe to use
19
+ * both as a filesystem segment and as an ffmpeg argument fragment.
20
+ */
21
+ const SAFE_COMPONENT = /^[A-Za-z0-9._-]+$/;
22
+ /**
23
+ * Asserts that a caller-supplied value is a safe single path component.
24
+ *
25
+ * Rejects empty strings, the relative segments `.` and `..`, anything
26
+ * containing a path separator or NUL byte, and anything outside the
27
+ * `[A-Za-z0-9._-]` allow-list (which also rejects shell metacharacters).
28
+ *
29
+ * @param value - The caller-supplied component (e.g. a stream id or profile name).
30
+ * @param label - Human-readable name of the field, used in the error message.
31
+ * @returns The validated component, unchanged.
32
+ * @throws {Error} If the value is not a safe single path component.
33
+ */
34
+ export const assertSafePathComponent = (value, label) => {
35
+ if (typeof value !== 'string' ||
36
+ value.length === 0 ||
37
+ value === '.' ||
38
+ value === '..' ||
39
+ value.includes('\0') ||
40
+ !SAFE_COMPONENT.test(value)) {
41
+ throw new Error(`Invalid ${label}: must be a non-empty path component matching [A-Za-z0-9._-] (got ${JSON.stringify(value)})`);
42
+ }
43
+ return value;
44
+ };
45
+ /**
46
+ * Asserts that a caller-supplied segment index is a non-negative integer.
47
+ *
48
+ * @param index - The caller-supplied segment index.
49
+ * @returns The validated index, unchanged.
50
+ * @throws {Error} If the value is not a non-negative integer.
51
+ */
52
+ export const assertSegmentIndex = (index) => {
53
+ if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) {
54
+ throw new Error(`Invalid segment index: must be a non-negative integer (got ${JSON.stringify(index)})`);
55
+ }
56
+ return index;
57
+ };
58
+ /**
59
+ * Resolves `parts` against `base` and asserts the result stays within `base`.
60
+ *
61
+ * Defense-in-depth on top of {@link assertSafePathComponent}: even if a
62
+ * component slipped through, the resolved absolute path is rejected unless it
63
+ * is `base` itself or a descendant of it.
64
+ *
65
+ * @param base - The intended base directory.
66
+ * @param parts - Path segments to append.
67
+ * @returns The resolved absolute path, guaranteed to be inside `base`.
68
+ * @throws {Error} If the resolved path escapes `base`.
69
+ */
70
+ export const resolveWithinBase = (base, ...parts) => {
71
+ const resolvedBase = resolve(base);
72
+ const resolved = resolve(resolvedBase, ...parts);
73
+ if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + sep)) {
74
+ throw new Error(`Resolved path escapes the output directory: ${JSON.stringify(resolved)}`);
75
+ }
76
+ return resolved;
77
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@molecule/api-media-streaming-hls",
3
+ "version": "1.0.0",
4
+ "description": "HLS media streaming provider for molecule.dev — ffmpeg-based segmentation, transcoding, and M3U8 playlist generation",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "media",
25
+ "streaming",
26
+ "hls",
27
+ "m3u8",
28
+ "ffmpeg",
29
+ "transcode"
30
+ ],
31
+ "license": "Apache-2.0",
32
+ "peerDependencies": {
33
+ "@molecule/api-media-streaming": "^1.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@molecule/api-media-streaming": "1.0.0",
37
+ "@types/node": "26.1.2",
38
+ "typescript": "6.0.3",
39
+ "vitest": "4.1.10"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/molecule-dev/molecule.git",
44
+ "directory": "packages/api/bonds/media-streaming/hls"
45
+ },
46
+ "homepage": "https://github.com/molecule-dev/molecule/tree/main/packages/api/bonds/media-streaming/hls",
47
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }