Repository navigation
Expand file tree
/
Copy pathdocusaurus.config.mts
More file actions
891 lines (839 loc) · 31 KB
/
Copy pathdocusaurus.config.mts
File metadata and controls
891 lines (839 loc) · 31 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
import { themes as prismThemes } from "prism-react-renderer";
import type { Config } from "@docusaurus/types";
import type * as Preset from "@docusaurus/preset-classic";
import type {
NormalizedSidebarItem,
SidebarItemsGeneratorDoc,
} from "@docusaurus/plugin-content-docs/src/sidebars/types.js";
import remarkGithubAdmonitionsToDirectives from "remark-github-admonitions-to-directives";
import remarkVersionPlaceholders from "./src/remark/version-placeholders";
import * as path from "path";
import * as fs from "fs";
import { createRequire } from "module";
import { fileURLToPath } from "url";
import { AlphaTabWebPackPlugin } from "@coderline/alphatab-webpack";
import type { Compiler, Module, RuleSetRule } from "webpack";
const siteDir = path.dirname(fileURLToPath(import.meta.url));
// The docs and the site styles import these generator outputs; without them the
// build fails with unrelated-looking "Module not found" or sass errors.
const generatedFiles = [
"docs/reference/_apiTable.mdx",
"docs/reference/_settingsTable.mdx",
"docs/alphatex/_score-metadata.mdx",
"src/css/highlight.scss",
];
const missingGeneratedFiles = generatedFiles.filter(
(f) => !fs.existsSync(path.join(siteDir, f))
);
if (missingGeneratedFiles.length > 0) {
throw new Error(
`Generated reference docs are missing (${missingGeneratedFiles.join(", ")}). ` +
"Run `npm run generate-alphatabdoc` in website/ first; `npm run build` and `npm start` do this automatically."
);
}
// alphaTab's package exports don't expose ./package.json, so it is located
// relative to the resolved entry (dist/alphaTab.js).
const alphaTabVersionFull: string = JSON.parse(
fs.readFileSync(
path.resolve(
createRequire(import.meta.url).resolve("@coderline/alphatab"),
"../../package.json"
),
"utf8"
)
).version;
// Fetch the GitHub star count from shields.io at build time. Stored in
// customFields as the initial value; the client-side GitHubStarsLink component
// refreshes it on page load (shields.io's 30 min HTTP cache prevents per-visitor
// chatter). shields.io's JSON endpoint is documented at
// https://github.com/badges/shields/blob/master/doc/json-format.md
async function fetchInitialGithubStars(
slug: string,
fallback: string,
): Promise<string> {
try {
const ctrl = new AbortController();
const timeout = setTimeout(() => ctrl.abort(), 5000);
const res = await fetch(
`https://img.shields.io/github/stars/${slug}.json`,
{ signal: ctrl.signal },
);
clearTimeout(timeout);
if (!res.ok) { return fallback; }
const data = (await res.json()) as { message?: string; value?: string };
return data.message ?? data.value ?? fallback;
} catch {
return fallback;
}
}
const githubRepo = "CoderLine/alphaTab";
// Discover the latest release-notes page so the landing banner's "Release
// notes" link always points to the newest release without manual edits.
function findLatestReleaseNotesPath(): string {
const dir = path.join(siteDir, "docs", "releases");
const files = fs.readdirSync(dir);
// Filenames look like `release1_8.mdx`. Sort by the numeric suffix and pick
// the highest. Strip the extension for the docs URL.
const ranked = files
.map((f) => {
const m = f.match(/^release(\d+)_(\d+)\.(mdx?|md)$/);
if (!m) { return null; }
const major = parseInt(m[1], 10);
const minor = parseInt(m[2], 10);
const base = f.replace(/\.(mdx?|md)$/, "");
return { major, minor, base };
})
.filter((x): x is { major: number; minor: number; base: string } => x !== null)
.sort((a, b) => b.major - a.major || b.minor - a.minor);
const latest = ranked[0]?.base ?? "release1_0";
return `/docs/releases/${latest}`;
}
const latestReleaseNotesPath = findLatestReleaseNotesPath();
const isPreRelease = alphaTabVersionFull.indexOf("-") >= 0;
let alphaTabVersion: string;
let algoliaAppId = '26AE6KNYRK';
let algoliaApiKey = '3db9646111702a74fe1f2249ddafa870';
let algoliaIndexName: string;
if (isPreRelease) {
alphaTabVersion = alphaTabVersionFull.substring(
0,
alphaTabVersionFull.indexOf("-")
);
algoliaIndexName = 'next_alphaTab';
} else {
alphaTabVersion = alphaTabVersionFull;
algoliaIndexName = 'alphaTab';
}
// alphaSkia version the Kotlin alphaTab-core depends on, shown in the JVM install snippets.
const alphaSkiaVersion = /^alphaskia\s*=\s*"([^"]+)"/m.exec(
fs.readFileSync(
path.resolve(siteDir, "../packages/kotlin/src/gradle/libs.versions.toml"),
"utf8"
)
)![1];
function getSortValue(
prop: string,
docs: Map<string, SidebarItemsGeneratorDoc>,
item: NormalizedSidebarItem
): string | number | undefined {
if (prop in item) {
return item[prop];
}
switch (item.type) {
case "doc":
const doc = docs.get(item.id);
if (doc) {
if (prop in doc) {
return doc[prop];
}
if (prop in doc.frontMatter) {
switch (typeof doc.frontMatter[prop]) {
case "number":
case "string":
return doc.frontMatter[prop];
case "undefined":
break;
default:
return String(doc.frontMatter[prop]);
}
}
}
break;
case "category":
if (prop === "title") {
return item.label;
}
break;
}
if (item.customProps && prop in item.customProps) {
switch (typeof item.customProps[prop]) {
case "number":
case "string":
return item.customProps[prop];
default:
return String(item.customProps[prop]);
}
}
// console.warn(`Could not get sort prop '${prop}' on sidebar item`, item);
return undefined;
}
// Docusaurus loads .mts configs via jiti, which does not support top-level
// await. Wrap the config in an async default-export function so we can await
// the shields.io fetch at build time.
const lazyCompilationOptions = { imports: true, entries: false };
// Docusaurus' dev server is webpack-dev-server, which does not wire up Rspack's lazy
// compilation; the middleware must be created on the compiler before its first build.
let rspackLazyCompilationMiddleware: ((req: unknown, res: unknown, next: () => void) => void) | undefined;
type RspackCompiler = {
rspack: { lazyCompilationMiddleware(compiler: unknown): typeof rspackLazyCompilationMiddleware };
};
class RspackLazyCompilationMiddlewarePlugin {
apply(compiler: Compiler) {
const rspackCompiler = compiler as unknown as RspackCompiler;
rspackLazyCompilationMiddleware = rspackCompiler.rspack.lazyCompilationMiddleware(rspackCompiler);
}
}
function lazyCompilationConfig(isRspack: boolean) {
if (!isRspack) {
return { experiments: { lazyCompilation: lazyCompilationOptions } };
}
return {
lazyCompilation: lazyCompilationOptions,
devServer: {
setupMiddlewares(middlewares: unknown[]) {
if (rspackLazyCompilationMiddleware) {
middlewares.unshift({ name: "rspack-lazy-compilation", middleware: rspackLazyCompilationMiddleware });
}
return middlewares;
},
},
};
}
async function createConfig(): Promise<Config> {
const githubStarsInitial = await fetchInitialGithubStars(githubRepo, "1.7k");
return {
title: "alphaTab",
tagline: "Build modern music notation apps for web, desktop and mobile",
url: "https://alphatab.net",
baseUrl: "/",
favicon: "img/favicon.ico",
organizationName: "CoderLine",
projectName: "alphaTab",
onBrokenLinks: "throw",
onBrokenAnchors: "throw",
future: {
v4: {
removeLegacyPostBuildHeadAttribute: true,
},
faster: {
rspackBundler: true,
rspackPersistentCache: true,
mdxCrossCompilerCache: true,
ssgWorkerThreads: true,
swcJsLoader: true,
swcJsMinimizer: true,
},
},
customFields: {
isPreRelease: isPreRelease,
alphaTabVersion: alphaTabVersion,
alphaTabVersionFull: alphaTabVersionFull,
githubRepo: githubRepo,
githubStarsInitial: githubStarsInitial,
latestReleaseNotesPath: latestReleaseNotesPath,
},
markdown: {
hooks: {
onBrokenMarkdownLinks: "warn",
}
},
clientModules: ["./src/clientModules/revealActiveSidebarLink.ts"],
presets: [
[
"classic",
{
blog: false,
docs: {
sidebarPath: "./sidebars.ts",
editUrl: ({ versionDocsDirPath, docPath }) =>
/^reference\/(api|settings|types)\//.test(docPath)
? undefined
: `https://github.com/CoderLine/alphaTab/edit/develop/website/${versionDocsDirPath}/${docPath}`,
beforeDefaultRemarkPlugins: [remarkGithubAdmonitionsToDirectives],
remarkPlugins: [[remarkVersionPlaceholders, { alphaTabVersion, alphaSkiaVersion }]],
async sidebarItemsGenerator({
defaultSidebarItemsGenerator,
...args
}) {
const sidebarItems = await defaultSidebarItemsGenerator(args);
// Tag feature-catalog stubs (external-link cards) with a CSS class
// that hides them from the sidebar UI, while keeping them in the
// sidebar tree so the auto-generated card grid can still read them.
// Docusaurus' built-in `unlisted: true` only takes effect in
// production builds and would also remove them from the tree.
const docsById = new Map<string, SidebarItemsGeneratorDoc>(
args.docs.map((d) => [d.id, d])
);
const isStub = (id: string) => {
const doc = docsById.get(id);
const fm = (doc as any)?.frontMatter ?? {};
return !!fm.sidebar_custom_props?.feature_external_link;
};
const tagStubs = (items: any[]): any[] =>
items.map((item) => {
if (item.type === "doc" && isStub(item.id)) {
return {
...item,
className: [item.className, "sidebar-hidden"]
.filter(Boolean)
.join(" "),
};
}
if (item.type === "category") {
return { ...item, items: tagStubs(item.items ?? []) };
}
return item;
});
// Group feature-catalog pages under their chapter — matching the
// card grid on the group index. Chapter order and labels come from
// `_chapters.ts` next to each group directory.
const featuresRoot = path.join(siteDir, "docs", "features");
const chaptersCache = new Map<
string,
{ id: string; label: string }[]
>();
const parseChapters = (groupName: string) => {
if (chaptersCache.has(groupName)) {
return chaptersCache.get(groupName)!;
}
const filePath = path.join(
featuresRoot,
groupName,
"_chapters.ts"
);
const chapters: { id: string; label: string }[] = [];
if (fs.existsSync(filePath)) {
const text = fs.readFileSync(filePath, "utf-8");
const regex = /\{\s*id:\s*['"]([^'"]+)['"][\s\S]*?label:\s*['"]([^'"]+)['"]/g;
for (const m of text.matchAll(regex)) {
chapters.push({ id: m[1], label: m[2] });
}
}
chaptersCache.set(groupName, chapters);
return chapters;
};
const featureChapter = (id: string): string | undefined => {
const doc = docsById.get(id);
return (doc as any)?.frontMatter?.sidebar_custom_props
?.feature_chapter;
};
const featureOrder = (id: string): number => {
const doc = docsById.get(id);
const raw = (doc as any)?.frontMatter?.sidebar_custom_props
?.feature_order;
return typeof raw === "number" ? raw : 999;
};
const groupByChapter = (item: any): any => {
if (item.type !== "category" || !Array.isArray(item.items)) {
return item;
}
// Detect a feature-group category by looking for a child doc id
// that starts with `features/<group>/`.
const docChild = item.items.find(
(c: any) => c.type === "doc" && typeof c.id === "string"
);
const match =
docChild &&
/^features\/([^/]+)\//.exec((docChild as any).id);
if (!match) { return item; }
const groupName = match[1];
const chapters = parseChapters(groupName);
if (chapters.length === 0) { return item; }
const indexId = `features/${groupName}/index`;
const indexItem = item.items.find(
(c: any) => c.type === "doc" && c.id === indexId
);
const buckets = new Map<string, any[]>();
for (const c of chapters) {
buckets.set(c.id, []);
}
const rest: any[] = [];
for (const child of item.items) {
if (child === indexItem) { continue; }
if (child.type !== "doc") {
rest.push(child);
continue;
}
const ch = featureChapter((child as any).id);
if (ch && buckets.has(ch)) {
buckets.get(ch)!.push(child);
} else {
rest.push(child);
}
}
for (const [, arr] of buckets) {
arr.sort(
(a: any, b: any) =>
featureOrder(a.id) - featureOrder(b.id)
);
}
const newItems: any[] = [];
if (indexItem) { newItems.push(indexItem); }
for (const chapter of chapters) {
const arr = buckets.get(chapter.id) || [];
if (arr.length === 0) { continue; }
newItems.push({
type: "category",
label: chapter.label,
collapsed: false,
collapsible: true,
items: arr,
});
}
newItems.push(...rest);
return { ...item, items: newItems };
};
const processed = tagStubs(sidebarItems).map(groupByChapter);
sidebarItems.length = 0;
sidebarItems.push(...processed);
if (Array.isArray(args.item.customProps?.["sort"])) {
let props = args.item.customProps?.["sort"] as
| [string, string]
| [string, string][];
if (!Array.isArray(props[0])) {
props = [props as [string, string]];
}
const docsLookup = new Map<string, SidebarItemsGeneratorDoc>(
args.docs.map((d) => [d.id, d])
);
// Reverse items in categories
sidebarItems.sort((a, b) => {
for (const prop of props) {
const ascending = prop[1] !== "desc";
let av = getSortValue(prop[0], docsLookup, a);
let bv = getSortValue(prop[0], docsLookup, b);
if (typeof av !== typeof bv) {
av = av === undefined ? av : String(av);
bv = bv === undefined ? bv : String(bv);
}
let result = 0;
if (av === undefined && bv === undefined) {
// continue
} else if (av === undefined) {
return -1;
} else if (bv === undefined) {
return 1;
} else if (typeof av === "string") {
if (ascending) {
result = av.localeCompare(bv as string);
} else {
result = (bv as string).localeCompare(av);
}
} else {
if (ascending) {
result = av - (bv as number);
} else {
result = (bv as number) - av;
}
}
if (result !== 0) {
return result;
}
}
return 0;
});
}
return sidebarItems;
},
},
theme: {
customCss: "./src/css/custom.scss",
},
sitemap: {
async createSitemapItems({defaultCreateSitemapItems, ...params}) {
const defaultItems = await defaultCreateSitemapItems(params);
// rank reference type docs lower than manual docs
for(const item of defaultItems) {
if(item.url.includes('reference/types')) {
item.priority = 0.1;
}
}
return defaultItems;
},
}
} satisfies Preset.Options,
],
],
themeConfig: {
docs: {
sidebar: {
hideable: true,
},
},
navbar: {
title: "alphaTab",
logo: {
alt: "alphaTab Logo",
src: "img/alphaTab.png",
},
items: [
{
type: "doc",
docId: "introduction",
position: "left",
label: "Docs",
},
{
type: "doc",
docId: "tutorials",
position: "left",
label: "Tutorial",
},
{
type: "doc",
docId: "features/index",
position: "left",
label: "Features",
},
{
type: "doc",
docId: "alphatex/introduction",
position: "left",
label: "alphaTex",
className: "navbar-link-secondary",
},
{
to: "/playground",
position: "left",
label: "Playground",
},
{
to: "/showcase",
position: "left",
label: "Showcase",
className: "navbar-link-secondary",
},
// Right
{
type: "search",
position: "right"
},
{
type: "dropdown",
position: "right",
label: isPreRelease ? `${alphaTabVersion} 🚧` : alphaTabVersion,
items: [
{
href: "https://next.alphatab.net",
label: "Next Version 🚧",
},
{
href: "https://alphatab.net",
label: "Stable Version",
},
],
},
// Site-wide playback source + SoundFont preferences (src/theme/NavbarItem/PlaybackSettingsNavbarItem.tsx).
{
type: "custom-playbackSettings",
position: "right",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
// Custom navbar item type — see src/theme/NavbarItem/ComponentTypes.ts.
// Renders the GitHub icon + live star count from shields.io, falling
// back to the build-time fetched value in `customFields.githubStarsInitial`.
{
type: "custom-githubStarsLink",
position: "right",
href: `https://github.com/${githubRepo}`,
className: "header-github-link",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
],
},
footer: {
style: "light",
links: [
{
title: "Docs",
items: [
{ label: "Getting started", to: "/docs/introduction" },
{ label: "Web", to: "/docs/getting-started/installation-web" },
{ label: ".NET", to: "/docs/getting-started/installation-net" },
{ label: "Kotlin", to: "/docs/getting-started/installation-kotlin" },
{ label: "API reference", to: "/docs/reference/api" },
],
},
{
title: "Learn",
items: [
{ label: "Tutorial", to: "/docs/tutorials" },
{ label: "alphaTex", to: "/docs/alphatex/introduction" },
{ label: "Features", to: "/docs/features/" },
{ label: "Playground", to: "/playground" },
],
},
{
title: "Project",
items: [
{ label: "GitHub", href: "https://github.com/CoderLine/alphaTab" },
{ label: "Release notes", to: latestReleaseNotesPath },
{ label: "Contributing", to: "/docs/contributing" },
],
},
{
title: "Community",
items: [
{ label: "Showcase", to: "/showcase" },
{
label: "Show and tell",
href: "https://github.com/CoderLine/alphaTab/discussions/categories/show-and-tell",
},
{
label: "Discussions",
href: "https://github.com/CoderLine/alphaTab/discussions",
},
{
label: "Issues",
href: "https://github.com/CoderLine/alphaTab/issues",
},
{
label: "Stack Overflow",
href: "https://stackoverflow.com/questions/tagged/alphatab",
},
],
},
],
copyright: `© 2010—${new Date().getFullYear()} alphaTab contributors · MPL-2.0`,
},
prism: {
theme: prismThemes.github,
darkTheme: prismThemes.dracula,
additionalLanguages: ["csharp", "diff", "kotlin", "groovy"],
},
colorMode: {
defaultMode: 'light'
},
algolia: {
appId: algoliaAppId,
apiKey: algoliaApiKey,
indexName: algoliaIndexName
},
} satisfies Preset.ThemeConfig,
plugins: [
"docusaurus-plugin-sass",
[
"@docusaurus/plugin-client-redirects",
{
// Legacy /docs/showcase/* pages were folded into the feature catalog
// under /docs/features/render/. Keep external links alive by mapping
// each old slug to the closest new page. See docs/features/render/
// for the destinations.
redirects: [
// Version-independent link to the newest release notes; the alphaTab README links here.
{ from: "/docs/releases", to: latestReleaseNotesPath },
{ from: ["/docs/playground/playground", "/docs/playground"], to: "/playground" },
{ from: "/docs/showcase/introduction", to: "/docs/features/" },
{
from: ["/docs/migration/breaking-changes-095-096", "/docs/migration/breaking-changes-097-098"],
to: latestReleaseNotesPath,
},
{ from: "/docs/migration/data-attributes", to: "/docs/getting-started/configuration-web" },
{ from: "/docs/migration/dom-events", to: "/docs/getting-started/configuration-web" },
{ from: "/docs/migration/jquery", to: "/docs/getting-started/installation-web" },
{ from: "/docs/getting-started/installation-android", to: "/docs/getting-started/installation-kotlin" },
{
from: "/docs/showcase/general",
to: "/docs/features/render/coverage-repeats",
},
{
from: "/docs/showcase/layouts",
to: "/docs/features/render/page-layout",
},
{
from: "/docs/showcase/music-notation",
to: "/docs/features/render/standard-notation",
},
{
from: "/docs/showcase/guitar-tabs",
to: "/docs/features/render/guitar-tablature",
},
{
from: "/docs/showcase/special-tracks",
to: "/docs/features/render/coverage-special-tracks",
},
{
from: "/docs/showcase/special-notes",
to: "/docs/features/render/coverage-special-notes",
},
{
from: "/docs/showcase/effects",
to: "/docs/features/render/coverage-effects-articulations",
},
{
from: "/docs/features/extend/custom-smufl-font",
to: "/docs/features/render/custom-smufl-fonts",
},
{
from: "/docs/features/extend/custom-fonts-on-skia",
to: "/docs/features/render/custom-fonts-on-skia",
},
],
},
],
(context) => ({
name: "docusaurus-customization",
injectHtmlTags() {
return {};
},
configureWebpack(config, isServer, options) {
const matchRule = (r: RuleSetRule) => {
if (typeof r === "object") {
if (r.test instanceof RegExp) {
return !!r.test.exec("custom.sass");
} else if (typeof r.test === "undefined") {
return true;
} else {
// unsupported
return false;
}
} else {
return false;
}
};
let sassRule = config.module!.rules!.find(matchRule);
if (typeof sassRule !== "object") {
throw new Error("Could not find SASS rule");
}
if (sassRule!.oneOf) {
sassRule = sassRule!.oneOf.find(matchRule);
}
if (typeof sassRule !== "object") {
throw new Error("Could not find inner SASS rule");
}
if (!Array.isArray(sassRule!.use)) {
throw new Error("Need SASS rule with use[]");
}
const sassLoaderIndex = sassRule!.use.findIndex(
(l) => typeof l === "object" && l!.loader?.includes("sass-loader")
);
if (sassLoaderIndex === -1) {
throw new Error("Could not find sass-loader in rule");
}
// ensure source-map before resolve-url-loader
const sassLoader = sassRule!.use[sassLoaderIndex] as RuleSetRule;
sassLoader.options = {
...((sassLoader.options as object | undefined) ?? {}),
sourceMap: true, // force sourcemaps
};
// insert resolve-url-loader before SASS loader to fix relative URLs
sassRule!.use.splice(sassLoaderIndex, 0, {
loader: "resolve-url-loader",
});
const alias: Record<string, string | false> = isServer
? {
// The alphaTex editor is loaded on demand in the browser only.
"monaco-editor": false,
"@coderline/alphatab-monaco": false,
"@coderline/alphatab-language-server/server/browser": false,
"vscode-languageserver-protocol/browser": false,
"vscode-languageserver/browser": false,
}
: {
// Monaco's root entry registers ~80 bundled languages; the site only needs alphaTex.
"monaco-editor$": path.resolve(
context.siteDir,
"src/monaco-slim.ts"
),
};
const bundler = options.currentBundler;
const isRspack = bundler.name === "rspack";
// Webpack keeps each module in several serialized forms, which makes the
// uncompressed packs several hundred MB per compilation.
const webpackCache =
typeof config.cache === "object" && config.cache.type === "filesystem"
? {
type: "filesystem" as const,
compression: "gzip" as const,
...(config.mode === "development"
? { maxMemoryGenerations: 1 }
: {}),
}
: undefined;
// Same maps as Docusaurus' `eval-cheap-module-source-map`, but only for the site's own
// code: maps for prebuilt code (Monaco, alphaTab's dist) embed its source a second
// time and roughly double the size of those chunks.
const isDevClient = !isServer && config.mode === "development";
const sourceMaps = isDevClient
? new bundler.instance.EvalSourceMapDevToolPlugin({
module: true,
columns: false,
moduleFilenameTemplate: config.output?.devtoolModuleFilenameTemplate,
exclude: [/[\\/]node_modules[\\/]/, /[\\/]packages[\\/][^\\/]+[\\/]dist[\\/]/],
})
: undefined;
return {
// Every page (including ~540 generated reference pages) and the alphaTex editor's
// Monaco are `import()`ed, so in dev they compile when the browser first requests
// them instead of all at startup.
...(isDevClient ? lazyCompilationConfig(isRspack) : {}),
...(sourceMaps ? { devtool: false } : {}),
...(webpackCache ? { cache: webpackCache } : {}),
optimization: {
splitChunks: {
cacheGroups: {
// Docusaurus turns splitChunks off for the server bundle; only the group below
// is wanted there, not webpack's defaults.
...(isServer ? { default: false, defaultVendors: false } : {}),
// Linked workspace packages resolve outside node_modules, so webpack's vendor
// group misses them and every page chunk would embed its own copy of alphaTab.
linkedPackages: {
test: (module: Module) => {
const resource = module.nameForCondition();
return (
!!resource &&
!resource.startsWith(siteDir + path.sep) &&
!/[\\/]node_modules[\\/]/.test(resource)
);
},
idHint: "vendors",
priority: -10,
reuseExistingChunk: true,
},
},
},
},
module: {
rules: [
...(isDevClient
? [
{
test: /[\\/]\.docusaurus[\\/]registry\.js$/,
loader: path.resolve(
context.siteDir,
"scripts/registry-without-weak-ids-loader.cjs"
),
},
]
: []),
{
// Monaco's fallback for hosts without MonacoEnvironment.getWorker: webpack would copy
// the unbundled module, whose relative imports do not exist, into the build root.
// The editor always passes its own bundled worker, so the URL only has to be valid.
test: /[\\/]monaco-editor[\\/]esm[\\/]vs[\\/]editor[\\/]common[\\/]services[\\/]editorWebWorkerMain\.js$/,
dependency: "url",
type: "asset/inline",
},
],
},
plugins: [
...(sourceMaps ? [sourceMaps] : []),
...(isDevClient && isRspack ? [new RspackLazyCompilationMiddlewarePlugin()] : []),
// Copy the Font and SoundFont Files to the output
new AlphaTabWebPackPlugin({
assetOutputDir: config.output!.path,
}),
],
resolve: {
alias,
fallback: {
fs: false,
buffer: false,
path: false,
os: false,
util: false,
assert: false,
stream: false,
crypto: false,
constants: false,
child_process: false,
module: false,
},
},
};
},
}),
],
};
}
export default createConfig;