-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathbuild-ejected-skins.ts
More file actions
1638 lines (1383 loc) · 55.8 KB
/
build-ejected-skins.ts
File metadata and controls
1638 lines (1383 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Build ejected skin snippets for copy-paste usage.
*
* Produces `site/src/content/ejected-skins.json` with:
* - HTML skins: rendered HTML templates with inline SVGs and resolved classes
* - React skins: TSX (with types) and JSX (types stripped) with inline SVGs
* - CSS variants include a `css` field with all @imports resolved
* - Tailwind variants omit the `css` field (users bring their own Tailwind)
*
* Prerequisites: `pnpm build:packages` (at minimum icons, skins, utils).
*/
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, relative as relativePath, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import ts from 'typescript';
import { resolveImports } from '../../build/plugins/resolve-css-imports.ts';
import { normalizeImports } from './normalize-imports.ts';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, '../..');
const PACKAGES_ROOT = resolve(ROOT, 'packages');
const PACKAGE_MANIFEST_CACHE = new Map<string, PackageManifest>();
const PREFIX = '\x1b[35m[ejected-skins]\x1b[0m';
const HTML_CDN_BASE = 'https://cdn.jsdelivr.net/npm/@videojs/html/cdn';
const DEMO_VIDEO_SRC = 'https://stream.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM/highest.mp4';
const DEMO_POSTER_SRC = 'https://image.mux.com/BV3YZtogl89mg9VcNBhhnHm02Y34zI1nlMuMQfAbl3dM/thumbnail.webp';
const log = {
info: (...args: unknown[]) => console.log(PREFIX, ...args),
warn: (...args: unknown[]) => console.warn(PREFIX, '\x1b[33mwarn:\x1b[0m', ...args),
error: (...args: unknown[]) => console.error(PREFIX, '\x1b[31merror:\x1b[0m', ...args),
};
const SKINS_SRC = resolve(ROOT, 'packages/skins/src');
const OUTPUT = resolve(ROOT, 'site/src/content/ejected-skins.json');
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type PackageExportTarget = string | Record<string, string>;
interface PackageManifest {
name: string;
exports?: Record<string, PackageExportTarget>;
}
interface HtmlSkinDef {
id: string;
name: string;
platform: 'html';
style: 'css' | 'tailwind';
template: string;
css?: string;
iconSet: 'default' | 'minimal';
tailwindModule?: string;
}
interface ReactSkinDef {
id: string;
name: string;
platform: 'react';
style: 'css' | 'tailwind';
source: string;
css?: string;
}
type SkinDef = HtmlSkinDef | ReactSkinDef;
type MediaType = 'video' | 'audio';
function getSkinMediaType(skin: SkinDef): MediaType {
return skin.id.includes('audio') ? 'audio' : 'video';
}
interface EjectedSkinEntry {
id: string;
name: string;
platform: 'html' | 'react';
style: 'css' | 'tailwind';
html?: string;
tsx?: string;
jsx?: string;
css?: string;
}
interface PackageSpecifierParts {
packageDir: string;
packageName: string;
subpath: string;
}
// ---------------------------------------------------------------------------
// Package resolution
// ---------------------------------------------------------------------------
function parsePackageSpecifier(specifier: string): PackageSpecifierParts {
const parts = specifier.split('/');
if (parts.length < 2 || parts[0] !== '@videojs') {
throw new Error(`Expected a @videojs package specifier, got "${specifier}"`);
}
const packageName = `${parts[0]}/${parts[1]}`;
const packageDir = resolve(PACKAGES_ROOT, parts[1]);
const subpath = parts.length > 2 ? `./${parts.slice(2).join('/')}` : '.';
return { packageDir, packageName, subpath };
}
function readPackageManifest(packageDir: string): PackageManifest {
const cached = PACKAGE_MANIFEST_CACHE.get(packageDir);
if (cached) {
return cached;
}
const manifestPath = resolve(packageDir, 'package.json');
if (!existsSync(manifestPath)) {
throw new Error(`Missing package manifest: ${manifestPath}`);
}
const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as PackageManifest;
PACKAGE_MANIFEST_CACHE.set(packageDir, manifest);
return manifest;
}
function matchExportPattern(pattern: string, subpath: string): string | null {
if (!pattern.includes('*')) {
return pattern === subpath ? '' : null;
}
const [prefix, suffix] = pattern.split('*');
if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix)) {
return null;
}
return subpath.slice(prefix.length, subpath.length - suffix.length);
}
function selectExportTarget(exportTarget: PackageExportTarget, specifier: string, packageName: string): string {
if (typeof exportTarget === 'string') {
return exportTarget;
}
const preferredConditions = ['default', 'development', 'import', 'module', 'node', 'types'];
for (const condition of preferredConditions) {
const target = exportTarget[condition];
if (target) {
return target;
}
}
throw new Error(`Package "${packageName}" exports "${specifier}" but does not provide a supported target condition`);
}
function resolvePackageExportFile(specifier: string): string {
const { packageDir, packageName, subpath } = parsePackageSpecifier(specifier);
const manifest = readPackageManifest(packageDir);
const exportsField = manifest.exports;
if (!exportsField) {
throw new Error(`Package "${packageName}" does not define exports`);
}
const exactTarget = exportsField[subpath];
if (exactTarget) {
const target = selectExportTarget(exactTarget, specifier, packageName);
const filePath = resolve(packageDir, target.replace(/^\.\//, ''));
if (!existsSync(filePath)) {
throw new Error(`Resolved file does not exist: ${filePath}`);
}
return filePath;
}
for (const [pattern, exportTarget] of Object.entries(exportsField)) {
const wildcardValue = matchExportPattern(pattern, subpath);
if (wildcardValue === null) {
continue;
}
const targetPattern = selectExportTarget(exportTarget, specifier, packageName);
const filePath = resolve(packageDir, targetPattern.replace('*', wildcardValue).replace(/^\.\//, ''));
if (!existsSync(filePath)) {
throw new Error(`Resolved file does not exist: ${filePath}`);
}
return filePath;
}
throw new Error(`Package "${packageName}" does not export "${subpath}"`);
}
/** Resolve a `@videojs/*` package specifier to its built dist file URL. */
function pkgDistUrl(specifier: string): string {
return pathToFileURL(resolvePackageExportFile(specifier)).href;
}
function collectPackageSpecifiers(source: string): string[] {
const specifiers = new Set<string>();
const importRegex = /from\s+['"](@videojs\/[^'"]+)['"]/g;
let match: RegExpExecArray | null;
while ((match = importRegex.exec(source)) !== null) {
specifiers.add(match[1]);
}
return [...specifiers];
}
function validatePackageImports(source: string, sourcePath: string): void {
for (const specifier of collectPackageSpecifiers(source)) {
try {
resolvePackageExportFile(specifier);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Invalid package import "${specifier}" in "${sourcePath}": ${message}`);
}
}
}
function toRepoPath(filePath: string): string {
return relativePath(ROOT, filePath);
}
function createSourceFile(filePath: string, source: string): ts.SourceFile {
return ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
}
function isDirectivePrologueStatement(statement: ts.Statement): boolean {
return ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression);
}
type NamedDeclaration =
| ts.FunctionDeclaration
| ts.ClassDeclaration
| ts.InterfaceDeclaration
| ts.TypeAliasDeclaration
| ts.EnumDeclaration;
function isNamedDeclaration(statement: ts.Statement): statement is NamedDeclaration {
return (
ts.isFunctionDeclaration(statement) ||
ts.isClassDeclaration(statement) ||
ts.isInterfaceDeclaration(statement) ||
ts.isTypeAliasDeclaration(statement) ||
ts.isEnumDeclaration(statement)
);
}
function getStatementName(statement: ts.Statement): string | null {
if (isNamedDeclaration(statement)) {
return statement.name?.text ?? null;
}
if (ts.isVariableStatement(statement)) {
const decl = statement.declarationList.declarations[0];
return decl && ts.isIdentifier(decl.name) ? decl.name.text : null;
}
return null;
}
function isRelativeImport(specifier: string): boolean {
return specifier.startsWith('./') || specifier.startsWith('../');
}
function resolveRelativeModulePath(importerPath: string, specifier: string): string {
const basePath = resolve(dirname(importerPath), specifier);
const candidates = [
basePath,
`${basePath}.ts`,
`${basePath}.tsx`,
`${basePath}.js`,
`${basePath}.jsx`,
resolve(basePath, 'index.ts'),
resolve(basePath, 'index.tsx'),
resolve(basePath, 'index.js'),
resolve(basePath, 'index.jsx'),
];
for (const candidate of candidates) {
if (existsSync(candidate)) {
return candidate;
}
}
throw new Error(`Could not resolve relative import "${specifier}" from "${toRepoPath(importerPath)}"`);
}
function stripExportModifier(text: string): string {
return text.replace(/^export\s+default\s+/, '').replace(/^export\s+/, '');
}
function getImportStatementText(source: string, node: ts.ImportDeclaration): string {
return source.slice(node.getFullStart(), node.getEnd()).trim();
}
function findLocalDeclarationText(sourceFile: ts.SourceFile, localName: string): string | null {
for (const statement of sourceFile.statements) {
if (getStatementName(statement) === localName) {
return statement.getText(sourceFile);
}
}
return null;
}
function getNamedExportText(sourceFile: ts.SourceFile, exportName: string): string | null {
for (const statement of sourceFile.statements) {
const isExported = hasExportModifier(statement);
if (isExported && getStatementName(statement) === exportName) {
return stripExportModifier(statement.getText(sourceFile));
}
if (
ts.isExportDeclaration(statement) &&
!statement.moduleSpecifier &&
statement.exportClause &&
ts.isNamedExports(statement.exportClause)
) {
for (const element of statement.exportClause.elements) {
const exportedName = element.name.text;
const localName = element.propertyName?.text ?? exportedName;
if (exportedName === exportName) {
return findLocalDeclarationText(sourceFile, localName);
}
}
}
}
return null;
}
function getLocalDeclarationTexts(sourceFile: ts.SourceFile): Map<string, string> {
const declarations = new Map<string, string>();
for (const statement of sourceFile.statements) {
if (ts.isExportDeclaration(statement)) continue;
const name = getStatementName(statement);
if (!name) continue;
const text = ts.canHaveModifiers(statement)
? stripExportModifier(statement.getText(sourceFile))
: statement.getText(sourceFile);
declarations.set(name, text);
}
return declarations;
}
function collectDeclarationClosure(
sourceFile: ts.SourceFile,
declarationName: string,
declarations: Map<string, string>,
seen = new Set<string>()
): string[] {
if (seen.has(declarationName)) {
return [];
}
const declarationText = declarations.get(declarationName) ?? getNamedExportText(sourceFile, declarationName);
if (!declarationText) {
throw new Error(`Could not find declaration "${declarationName}" in "${sourceFile.fileName}"`);
}
seen.add(declarationName);
const identifierRegex = /\b[A-Za-z_]\w*\b/g;
const dependencyNames = new Set<string>();
let match: RegExpExecArray | null;
while ((match = identifierRegex.exec(declarationText)) !== null) {
const identifier = match[0];
if (identifier !== declarationName && declarations.has(identifier)) {
dependencyNames.add(identifier);
}
}
const dependencyTexts = [...dependencyNames].flatMap((name) =>
collectDeclarationClosure(sourceFile, name, declarations, seen)
);
return [...dependencyTexts, declarationText];
}
function inlineModuleExport(
sourceFile: ts.SourceFile,
importName: string,
localName: string,
isTypeOnly: boolean
): string {
const declarations = getLocalDeclarationTexts(sourceFile);
const exportTexts = collectDeclarationClosure(sourceFile, importName, declarations);
const exportText = exportTexts.join('\n\n');
if (importName === localName) {
return exportText;
}
const aliasKeyword = isTypeOnly ? 'type' : 'const';
return `${exportText}\n\n${aliasKeyword} ${localName} = ${importName};`;
}
function inlineRelativeImports(source: string, sourcePath: string): string {
const sourceFile = createSourceFile(sourcePath, source);
const declarationsToInline: string[] = [];
const extraImports = new Set<string>();
const declarationsSeen = new Set<string>();
const replacements: Array<{ start: number; end: number; text: string }> = [];
for (const statement of sourceFile.statements) {
if (!ts.isImportDeclaration(statement)) {
continue;
}
const specifier = statement.moduleSpecifier.getText(sourceFile).slice(1, -1);
if (!isRelativeImport(specifier)) {
continue;
}
const importClause = statement.importClause;
if (!importClause?.namedBindings || !ts.isNamedImports(importClause.namedBindings) || importClause.name) {
throw new Error(`Unsupported relative import in "${toRepoPath(sourcePath)}": ${statement.getText(sourceFile)}`);
}
const targetPath = resolveRelativeModulePath(sourcePath, specifier);
const targetSource = readFileSync(targetPath, 'utf-8');
validatePackageImports(targetSource, toRepoPath(targetPath));
const transformedTargetSource = inlineRelativeImports(targetSource, targetPath);
const transformedTargetFile = createSourceFile(targetPath, transformedTargetSource);
for (const targetStatement of transformedTargetFile.statements) {
if (isDirectivePrologueStatement(targetStatement)) {
continue;
}
if (!ts.isImportDeclaration(targetStatement)) {
break;
}
const targetSpecifier = targetStatement.moduleSpecifier.getText(transformedTargetFile).slice(1, -1);
if (isRelativeImport(targetSpecifier)) {
throw new Error(
`Relative import remained after inlining in "${toRepoPath(targetPath)}": ${targetStatement.getText(
transformedTargetFile
)}`
);
}
extraImports.add(getImportStatementText(transformedTargetSource, targetStatement));
}
for (const element of importClause.namedBindings.elements) {
const importName = element.propertyName?.text ?? element.name.text;
const localName = element.name.text;
const declaration = inlineModuleExport(transformedTargetFile, importName, localName, element.isTypeOnly);
if (!declarationsSeen.has(declaration)) {
declarationsSeen.add(declaration);
declarationsToInline.push(declaration);
}
}
replacements.push({
start: statement.getFullStart(),
end: statement.getEnd(),
text: '',
});
}
let transformedSource = source;
for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
transformedSource = `${transformedSource.slice(0, replacement.start)}${replacement.text}${transformedSource.slice(
replacement.end
)}`;
}
if (extraImports.size > 0) {
transformedSource = `${[...extraImports].join('\n')}\n${transformedSource}`;
}
if (declarationsToInline.length > 0) {
const insertPos = findLastImportEnd(transformedSource);
const block = `\n${declarationsToInline.join('\n\n')}\n`;
transformedSource = `${transformedSource.slice(0, insertPos)}${block}${transformedSource.slice(insertPos)}`;
}
transformedSource = normalizeImports(transformedSource);
for (const relativeSpecifier of collectRelativeImportSpecifiers(transformedSource)) {
throw new Error(`Relative import "${relativeSpecifier}" remains in "${toRepoPath(sourcePath)}" after inlining`);
}
return transformedSource;
}
function collectRelativeImportSpecifiers(source: string): string[] {
const specifiers = new Set<string>();
const importRegex = /from\s+['"]((?:\.\/|\.\.\/)[^'"]+)['"]/g;
let match: RegExpExecArray | null;
while ((match = importRegex.exec(source)) !== null) {
specifiers.add(match[1]);
}
return [...specifiers];
}
// ---------------------------------------------------------------------------
// Skin definitions
// ---------------------------------------------------------------------------
const SKINS: SkinDef[] = [
// HTML CSS
{
id: 'default-video',
name: 'Default Video',
platform: 'html',
style: 'css',
template: 'packages/html/src/define/video/skin.ts',
css: 'packages/html/src/define/video/skin.css',
iconSet: 'default',
},
{
id: 'default-audio',
name: 'Default Audio',
platform: 'html',
style: 'css',
template: 'packages/html/src/define/audio/skin.ts',
css: 'packages/html/src/define/audio/skin.css',
iconSet: 'default',
},
{
id: 'minimal-video',
name: 'Minimal Video',
platform: 'html',
style: 'css',
template: 'packages/html/src/define/video/minimal-skin.ts',
css: 'packages/html/src/define/video/minimal-skin.css',
iconSet: 'minimal',
},
{
id: 'minimal-audio',
name: 'Minimal Audio',
platform: 'html',
style: 'css',
template: 'packages/html/src/define/audio/minimal-skin.ts',
css: 'packages/html/src/define/audio/minimal-skin.css',
iconSet: 'minimal',
},
// HTML Tailwind
{
id: 'default-video-tailwind',
name: 'Default Video (Tailwind)',
platform: 'html',
style: 'tailwind',
template: 'packages/html/src/define/video/skin.tailwind.ts',
iconSet: 'default',
tailwindModule: '@videojs/skins/default/tailwind/video.tailwind',
},
{
id: 'default-audio-tailwind',
name: 'Default Audio (Tailwind)',
platform: 'html',
style: 'tailwind',
template: 'packages/html/src/define/audio/skin.tailwind.ts',
iconSet: 'default',
tailwindModule: '@videojs/skins/default/tailwind/audio.tailwind',
},
{
id: 'minimal-video-tailwind',
name: 'Minimal Video (Tailwind)',
platform: 'html',
style: 'tailwind',
template: 'packages/html/src/define/video/minimal-skin.tailwind.ts',
iconSet: 'minimal',
tailwindModule: '@videojs/skins/minimal/tailwind/video.tailwind',
},
{
id: 'minimal-audio-tailwind',
name: 'Minimal Audio (Tailwind)',
platform: 'html',
style: 'tailwind',
template: 'packages/html/src/define/audio/minimal-skin.tailwind.ts',
iconSet: 'minimal',
tailwindModule: '@videojs/skins/minimal/tailwind/audio.tailwind',
},
// React CSS
{
id: 'default-video-react',
name: 'Default Video (React)',
platform: 'react',
style: 'css',
source: 'packages/react/src/presets/video/skin.tsx',
css: 'packages/react/src/presets/video/skin.css',
},
{
id: 'default-audio-react',
name: 'Default Audio (React)',
platform: 'react',
style: 'css',
source: 'packages/react/src/presets/audio/skin.tsx',
css: 'packages/react/src/presets/audio/skin.css',
},
{
id: 'minimal-video-react',
name: 'Minimal Video (React)',
platform: 'react',
style: 'css',
source: 'packages/react/src/presets/video/minimal-skin.tsx',
css: 'packages/react/src/presets/video/minimal-skin.css',
},
{
id: 'minimal-audio-react',
name: 'Minimal Audio (React)',
platform: 'react',
style: 'css',
source: 'packages/react/src/presets/audio/minimal-skin.tsx',
css: 'packages/react/src/presets/audio/minimal-skin.css',
},
// React Tailwind
{
id: 'default-video-react-tailwind',
name: 'Default Video (React + Tailwind)',
platform: 'react',
style: 'tailwind',
source: 'packages/react/src/presets/video/skin.tailwind.tsx',
},
{
id: 'default-audio-react-tailwind',
name: 'Default Audio (React + Tailwind)',
platform: 'react',
style: 'tailwind',
source: 'packages/react/src/presets/audio/skin.tailwind.tsx',
},
{
id: 'minimal-video-react-tailwind',
name: 'Minimal Video (React + Tailwind)',
platform: 'react',
style: 'tailwind',
source: 'packages/react/src/presets/video/minimal-skin.tailwind.tsx',
},
{
id: 'minimal-audio-react-tailwind',
name: 'Minimal Audio (React + Tailwind)',
platform: 'react',
style: 'tailwind',
source: 'packages/react/src/presets/audio/minimal-skin.tailwind.tsx',
},
];
// ---------------------------------------------------------------------------
// CSS resolution
// ---------------------------------------------------------------------------
function resolveCss(cssPath: string): string {
const abs = resolve(ROOT, cssPath);
const raw = readFileSync(abs, 'utf-8');
return resolveImports(raw, dirname(abs), SKINS_SRC);
}
function getHtmlSkinCdnFileName(skin: HtmlSkinDef): string {
const isMinimal = skin.id.includes('minimal');
const prefix = skin.id.includes('video') ? 'video' : 'audio';
return isMinimal ? `${prefix}-minimal-ui` : `${prefix}-ui`;
}
function prependHtmlSkinScripts(html: string, skin: HtmlSkinDef): string {
const cdnFileName = getHtmlSkinCdnFileName(skin);
const scriptTag = `<script type="module" src="${HTML_CDN_BASE}/${cdnFileName}.js"></script>`;
const cssLink = `<link rel="stylesheet" href="./player.css">`;
const playerTag = getSkinMediaType(skin) === 'audio' ? 'audio-player' : 'video-player';
const indented = html
.split('\n')
.map((l) => (l.length > 0 ? ` ${l}` : l))
.join('\n');
return `${scriptTag}\n${cssLink}\n\n<${playerTag}>\n${indented}\n</${playerTag}>`;
}
// ---------------------------------------------------------------------------
// HTML template extraction and evaluation
// ---------------------------------------------------------------------------
/**
* Extract the body of `getTemplateHTML()` from the source file.
* Returns the raw template literal content (without the surrounding backticks).
*/
function extractTemplateLiteral(source: string): string {
// Match: function getTemplateHTML(...) { return /*html*/ `...`; }
// or: function getTemplateHTML(...) { return `...`; }
const match = source.match(
/function\s+getTemplateHTML\s*\([^)]*\)\s*\{[\s\S]*?return\s+(?:\/\*html\*\/\s*)?`([\s\S]*?)`\s*;?\s*\}/
);
if (!match) {
throw new Error('Could not extract getTemplateHTML template literal');
}
return match[1];
}
/**
* Collect all import names that the template uses from the tailwind module.
* Parses lines like: `import { foo, bar } from '@videojs/skins/...'`
* and also picks up re-imports from other modules used in the template.
*/
function parseImportedNames(source: string): Map<string, string> {
const imports = new Map<string, string>();
const importRegex = /import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
let match: RegExpExecArray | null;
while ((match = importRegex.exec(source)) !== null) {
const names = match[1]
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const module = match[2];
for (const name of names) {
// Handle `foo as bar`
const parts = name.split(/\s+as\s+/);
const localName = parts.length > 1 ? parts[1] : parts[0];
imports.set(localName, module);
}
}
return imports;
}
async function loadRenderIcon(
iconSet: 'default' | 'minimal'
): Promise<(name: string, attrs?: Record<string, string>) => string> {
const mod = await import(pkgDistUrl(`@videojs/icons/render/${iconSet}`));
return mod.renderIcon;
}
async function loadCn(): Promise<(...args: unknown[]) => string> {
const mod = await import(pkgDistUrl('@videojs/utils/style'));
return mod.cn;
}
async function loadTailwindTokens(specifier: string): Promise<Record<string, unknown>> {
return await import(pkgDistUrl(specifier));
}
/**
* Evaluate the HTML template by replacing `${...}` expressions with
* their computed values.
*
* Uses `new Function()` to evaluate the template literal in a context
* that provides renderIcon, cn, SEEK_TIME, and all tailwind tokens.
*/
function evaluateTemplate(templateBody: string, context: Record<string, unknown>): string {
const keys = Object.keys(context);
const values = Object.values(context);
// Build a function that returns the evaluated template literal
const fn = new Function(...keys, `return \`${templateBody}\`;`);
const html = fn(...values) as string;
// Clean up whitespace: dedent, trim trailing spaces, and trim outer edges.
const lines = html.split('\n').map((line) => line.trimEnd());
const minIndent = lines
.filter((l) => l.length > 0)
.reduce((min, l) => Math.min(min, l.length - l.trimStart().length), Infinity);
return lines
.map((l) => (l.length > 0 ? l.slice(minIndent) : l))
.join('\n')
.trim();
}
/**
* Replace `<slot name="media">`, `<slot>` (default slot), and
* `<slot name="poster">` with concrete elements so the ejected HTML is
* self-contained.
*/
function replaceSlots(html: string, mediaType: MediaType): string {
const tag = mediaType === 'audio' ? 'audio' : 'video';
const playsInline = mediaType === 'video' ? ' playsinline' : '';
const mediaElement = `<${tag} src="${DEMO_VIDEO_SRC}"${playsInline}></${tag}>`;
// Replace the deprecated comment + slot="media" + default slot block with the
// media element, preserving the original indentation.
html = html.replace(
/^([ \t]*)<!--\s*@deprecated[^\n]*\n\s*<slot name="media"><\/slot>\n\s*<slot><\/slot>/m,
`$1${mediaElement}`
);
// Replace the poster slot with an <img> element.
html = html.replace(/<slot name="poster"><\/slot>/, `<img src="${DEMO_POSTER_SRC}" />`);
return html;
}
/**
* Process an HTML skin: extract the template, evaluate it with the right
* context, and return the rendered HTML string.
*/
async function processHtmlSkin(skin: HtmlSkinDef): Promise<string> {
const absPath = resolve(ROOT, skin.template);
const source = readFileSync(absPath, 'utf-8');
validatePackageImports(source, skin.template);
const templateBody = extractTemplateLiteral(source);
const renderIcon = await loadRenderIcon(skin.iconSet);
const cn = await loadCn();
// Build context object with all the variables the template needs
const context: Record<string, unknown> = {
renderIcon,
cn,
SEEK_TIME: 10,
};
if (skin.style === 'tailwind') {
// Load the primary tailwind module
if (skin.tailwindModule) {
const tokens = await loadTailwindTokens(skin.tailwindModule);
Object.assign(context, tokens);
}
// Check if the source imports from additional tailwind modules
const imports = parseImportedNames(source);
const loadedModules = new Set<string>();
if (skin.tailwindModule) loadedModules.add(skin.tailwindModule);
for (const [name, mod] of imports) {
if (mod.includes('/tailwind/') && !loadedModules.has(mod)) {
loadedModules.add(mod);
const extraTokens = await loadTailwindTokens(mod);
// Only add names that aren't already in context
if (!(name in context) && name in extraTokens) {
context[name] = extraTokens[name];
}
}
}
}
let html = evaluateTemplate(templateBody, context);
html = replaceSlots(html, getSkinMediaType(skin));
return prependHtmlSkinScripts(html, skin);
}
// ---------------------------------------------------------------------------
// React skin processing — inline SVGs, resolve imports, produce TSX + JSX
// ---------------------------------------------------------------------------
/** Convert PascalCase icon component name to kebab-case icon name. */
function componentToIconName(name: string): string {
return name
.replace(/Icon$/, '')
.replace(/([a-z])([A-Z])/g, '$1-$2')
.toLowerCase();
}
/** Convert HTML SVG attribute names to JSX camelCase equivalents. */
function svgToJsx(svg: string): string {
return svg
.replace(/\bstroke-width=/g, 'strokeWidth=')
.replace(/\bstroke-linecap=/g, 'strokeLinecap=')
.replace(/\bstroke-linejoin=/g, 'strokeLinejoin=')
.replace(/\bstroke-dasharray=/g, 'strokeDasharray=')
.replace(/\bstroke-dashoffset=/g, 'strokeDashoffset=')
.replace(/\bstroke-miterlimit=/g, 'strokeMiterlimit=')
.replace(/\bfill-rule=/g, 'fillRule=')
.replace(/\bclip-rule=/g, 'clipRule=')
.replace(/\bfill-opacity=/g, 'fillOpacity=')
.replace(/\bstroke-opacity=/g, 'strokeOpacity=');
}
/** Load the raw icons map from a render dist module. */
async function loadIconsMap(iconSet: 'default' | 'minimal'): Promise<Record<string, string>> {
const mod = await import(pkgDistUrl(`@videojs/icons/render/${iconSet}`));
const renderIcon = mod.renderIcon as (name: string) => string;
const assetsDir = resolve(PACKAGES_ROOT, 'icons/src/assets', iconSet);
const iconNames = readdirSync(assetsDir)
.filter((f) => f.endsWith('.svg'))
.map((f) => f.replace(/\.svg$/, ''));
const map: Record<string, string> = {};
for (const name of iconNames) {
const svg = renderIcon(name);
if (svg) map[name] = svg;
}
return map;
}
/** Serialize a JS value to source code. */
function serializeValue(value: unknown, indent = 0): string {
if (typeof value === 'string') return JSON.stringify(value);
if (typeof value === 'function') {
// Function tokens (like `root`) — resolve with false (no shadow DOM)
return `() => ${JSON.stringify((value as (arg: boolean) => string)(false))}`;
}
if (typeof value === 'object' && value !== null) {
const entries = Object.entries(value as Record<string, unknown>);
const pad = ' '.repeat(indent + 1);
const closePad = ' '.repeat(indent);
const parts = entries.map(([k, v]) => `${pad}${k}: ${serializeValue(v, indent + 1)}`);
return `{\n${parts.join(',\n')},\n${closePad}}`;
}
return String(value);
}
/** Strip TypeScript types from TSX source to produce plain JSX. */
function tsxToJsx(source: string): string {
const result = ts.transpileModule(source, {
compilerOptions: {
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.ESNext,
jsx: ts.JsxEmit.Preserve,
},
});
return result.outputText;
}
// -- React source transforms --
// Each transform removes its import(s) and collects any non-import code
// (const declarations, type defs, inlined components) into `postImport`.
// After all transforms, collected code is inserted after the final import.
/**
* Remove `cn` import and replace all `cn(...)` calls with template literals.
* `cn(a, b)` → `` `${a} ${b}` ``, with string literal args inlined directly.
*/
function inlineCn(source: string): string {
if (!source.match(/import\s+\{[^}]*\bcn\b[^}]*\}\s+from\s+['"]@videojs\/utils\/style['"]/)) {
return source;
}
source = source.replace(/import\s+\{[^}]*\bcn\b[^}]*\}\s+from\s+['"]@videojs\/utils\/style['"];?\n?/g, '');
return replaceCnCalls(source);
}
/** Convert parsed `cn(...)` args into a template literal expression. */
function cnToConcat(args: string[]): string {
const isLiteral = (a: string) => /^['"]/.test(a) && /['"]$/.test(a);
const unwrap = (a: string) => a.slice(1, -1);
// All string literals → merge into a single quoted string
if (args.every(isLiteral)) {
return `'${args.map(unwrap).join(' ')}'`;
}
// Build template literal parts
const parts = args.map((a) => {
if (isLiteral(a)) return unwrap(a);
if (a === 'className') return `\${className ?? ''}`;
return `\${${a}}`;
});
return `\`${parts.join(' ')}\``;
}
/** Replace all `cn(...)` calls with simple string concatenation. */
function replaceCnCalls(source: string): string {
const parts: string[] = [];
let i = 0;
while (i < source.length) {
const cnIndex = source.indexOf('cn(', i);
if (cnIndex === -1) {
parts.push(source.slice(i));
break;
}
// Ensure `cn(` is a standalone call, not part of another identifier
if (cnIndex > 0 && /\w/.test(source[cnIndex - 1])) {
parts.push(source.slice(i, cnIndex + 3));
i = cnIndex + 3;
continue;
}
parts.push(source.slice(i, cnIndex));
// Find the matching closing paren
const argsStart = cnIndex + 3;
let depth = 1;
let j = argsStart;
while (j < source.length && depth > 0) {
if (source[j] === '(') depth++;
else if (source[j] === ')') depth--;
if (depth > 0) j++;
}
const argsStr = source.slice(argsStart, j);
const args = splitTopLevelCommas(argsStr).map((a) => a.trim());
parts.push(cnToConcat(args));
i = j + 1; // skip past closing paren
}
return parts.join('');
}
/** Split a string by commas that are not inside parentheses, brackets, or template literals. */