astro-lilypond 0.13.0 → 0.15.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.
Files changed (52) hide show
  1. package/README.md +3 -7
  2. package/dist/binary/autoInstall.d.ts +13 -0
  3. package/dist/binary/autoInstall.js +6 -0
  4. package/dist/binary/cacheDir.d.ts +1 -0
  5. package/dist/binary/cacheDir.js +15 -0
  6. package/dist/binary/downloadLilypond.d.ts +15 -0
  7. package/dist/binary/downloadLilypond.js +129 -0
  8. package/dist/binary/index.d.ts +5 -0
  9. package/dist/binary/index.js +5 -0
  10. package/dist/binary/platformTarget.d.ts +14 -0
  11. package/dist/binary/platformTarget.js +35 -0
  12. package/dist/binary/resolveLilypondBinary.d.ts +9 -0
  13. package/dist/binary/resolveLilypondBinary.js +41 -0
  14. package/dist/index.d.ts +59 -7
  15. package/dist/index.js +89 -39
  16. package/dist/loader.d.ts +50 -30
  17. package/dist/loader.js +34 -48
  18. package/dist/plugins/rehype.js +2 -0
  19. package/dist/plugins/remark.js +2 -0
  20. package/dist/plugins/satteri.js +2 -0
  21. package/dist/plugins/types.d.ts +1 -0
  22. package/dist/readOutputFile.js +4 -7
  23. package/dist/render.d.ts +4 -7
  24. package/dist/render.js +1 -1
  25. package/dist/renderState.d.ts +29 -0
  26. package/dist/renderState.js +46 -0
  27. package/dist/utils/altTextFor.d.ts +1 -3
  28. package/dist/utils/altTextFor.js +1 -3
  29. package/dist/utils/altTextForBlock.d.ts +0 -1
  30. package/dist/utils/altTextForBlock.js +0 -1
  31. package/dist/utils/emitLilypondAsset.d.ts +1 -17
  32. package/dist/utils/emitLilypondAsset.fake.d.ts +0 -4
  33. package/dist/utils/emitLilypondAsset.fake.js +0 -4
  34. package/dist/utils/emitLilypondAsset.js +5 -16
  35. package/dist/utils/emitLilypondPdfAsset.d.ts +8 -0
  36. package/dist/utils/emitLilypondPdfAsset.fake.d.ts +5 -0
  37. package/dist/utils/emitLilypondPdfAsset.fake.js +6 -0
  38. package/dist/utils/emitLilypondPdfAsset.js +12 -0
  39. package/dist/utils/index.d.ts +3 -3
  40. package/dist/utils/index.js +2 -2
  41. package/dist/utils/lilypondMetadata.d.ts +10 -0
  42. package/dist/utils/lilypondMetadata.js +19 -0
  43. package/dist/utils/lyTypeDeclarationsFor.d.ts +2 -6
  44. package/dist/utils/lyTypeDeclarationsFor.js +3 -8
  45. package/dist/utils/renderedHtml.d.ts +9 -1
  46. package/dist/utils/renderedHtml.js +15 -12
  47. package/package.json +3 -5
  48. package/components/LilyPond.astro +0 -52
  49. package/dist/utils/lyImportQuery.d.ts +0 -22
  50. package/dist/utils/lyImportQuery.js +0 -26
  51. package/dist/utils/splitHeaderFields.d.ts +0 -23
  52. package/dist/utils/splitHeaderFields.js +0 -32
package/README.md CHANGED
@@ -13,17 +13,13 @@ Read the docs: https://lilypond.ky.fyi
13
13
 
14
14
  ## Quick Start
15
15
 
16
- ### 1. Install LilyPond
17
-
18
- Install the LilyPond binary directly from [lilypond.org](https://lilypond.org/download.html) or with `brew install lilypond` (Mac) or `apt install lilypond` (Linux).
19
-
20
- ### 2. Install `astro-lilypond`
16
+ ### 1. Install `astro-lilypond`
21
17
 
22
18
  ```sh
23
19
  pnpm add astro-lilypond
24
20
  ```
25
21
 
26
- ### 3. Add the integration to your Astro config
22
+ ### 2. Add the integration to your Astro config
27
23
 
28
24
  ```js
29
25
  // astro.config.mjs
@@ -35,7 +31,7 @@ export default defineConfig({
35
31
  });
36
32
  ```
37
33
 
38
- ### 4. Write your music
34
+ ### 3. Write your music
39
35
 
40
36
  Write LilyPond code within fenced code blocks with the `lilypond`, `ly`, or `ily` language tag.
41
37
 
@@ -0,0 +1,13 @@
1
+ import type { LilypondVersion } from "../types/lilypondVersion.js";
2
+ export interface AutoInstallOptions {
3
+ /**
4
+ * LilyPond version to download when none is found on `PATH`. Independent
5
+ * of `defaults.version`, which scores are compiled against.
6
+ * @default "2.26.0"
7
+ */
8
+ version?: LilypondVersion;
9
+ }
10
+ export declare function resolveAutoInstallOption(autoInstall: boolean | AutoInstallOptions | undefined): {
11
+ version?: LilypondVersion;
12
+ autoInstall: boolean;
13
+ };
@@ -0,0 +1,6 @@
1
+ export function resolveAutoInstallOption(autoInstall) {
2
+ return {
3
+ version: typeof autoInstall === "object" ? autoInstall.version : undefined,
4
+ autoInstall: autoInstall !== false,
5
+ };
6
+ }
@@ -0,0 +1 @@
1
+ export declare function lilypondCacheDir(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
@@ -0,0 +1,15 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ export function lilypondCacheDir(env = process.env, platform = process.platform) {
4
+ if (env.ASTRO_LILYPOND_CACHE_DIR)
5
+ return env.ASTRO_LILYPOND_CACHE_DIR;
6
+ if (platform === "darwin") {
7
+ return join(homedir(), "Library", "Caches", "astro-lilypond");
8
+ }
9
+ if (platform === "win32") {
10
+ const base = env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local");
11
+ return join(base, "astro-lilypond", "Cache");
12
+ }
13
+ const base = env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
14
+ return join(base, "astro-lilypond");
15
+ }
@@ -0,0 +1,15 @@
1
+ import type { LilypondVersion } from "../types/lilypondVersion.js";
2
+ export interface DownloadLilypondOptions {
3
+ version: LilypondVersion;
4
+ cacheDir?: string;
5
+ fetchImpl?: typeof fetch;
6
+ log?: (message: string) => void;
7
+ }
8
+ /**
9
+ * Downloads, verifies, and extracts a prebuilt LilyPond release into the
10
+ * cache dir, then returns the path to its `bin/lilypond[.exe]`. Returns
11
+ * `undefined` when LilyPond publishes no prebuilt for the current
12
+ * platform/arch. A previously-completed install for the same version is
13
+ * reused as-is.
14
+ */
15
+ export declare function downloadLilypond({ version, cacheDir, fetchImpl, log, }: DownloadLilypondOptions): Promise<string | undefined>;
@@ -0,0 +1,129 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { access, mkdir, mkdtemp, readdir, rename, rm, writeFile, } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { lilypondCacheDir } from "./cacheDir.js";
7
+ import { resolvePlatformTarget } from "./platformTarget.js";
8
+ const execFileAsync = promisify(execFile);
9
+ function downloadUrlFor(version, platform, arch, archiveExt) {
10
+ const filename = `lilypond-${version}-${platform}-${arch}.${archiveExt}`;
11
+ return `https://gitlab.com/api/v4/projects/lilypond%2Flilypond/packages/generic/lilypond/${version}/${filename}`;
12
+ }
13
+ async function pathExists(path) {
14
+ try {
15
+ await access(path);
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ /**
23
+ * `.zip` archives (Windows/mingw) use PowerShell's `Expand-Archive` rather
24
+ * than `tar`, since `tar -xf`'s zip support depends on a libarchive/bsdtar
25
+ * build resolving first on `PATH`, which isn't guaranteed on Windows.
26
+ */
27
+ async function extractArchive(archivePath, extractDir, archiveExt) {
28
+ if (archiveExt === "zip") {
29
+ await execFileAsync("powershell.exe", [
30
+ "-NoProfile",
31
+ "-NonInteractive",
32
+ "-Command",
33
+ "Expand-Archive -LiteralPath $env:ASTRO_LILYPOND_ARCHIVE -DestinationPath $env:ASTRO_LILYPOND_EXTRACT_DIR -Force",
34
+ ], {
35
+ env: {
36
+ ...process.env,
37
+ ASTRO_LILYPOND_ARCHIVE: archivePath,
38
+ ASTRO_LILYPOND_EXTRACT_DIR: extractDir,
39
+ },
40
+ });
41
+ return;
42
+ }
43
+ await execFileAsync("tar", ["-xf", archivePath, "-C", extractDir]);
44
+ }
45
+ /**
46
+ * Downloads, verifies, and extracts a prebuilt LilyPond release into the
47
+ * cache dir, then returns the path to its `bin/lilypond[.exe]`. Returns
48
+ * `undefined` when LilyPond publishes no prebuilt for the current
49
+ * platform/arch. A previously-completed install for the same version is
50
+ * reused as-is.
51
+ */
52
+ export async function downloadLilypond({ version, cacheDir = lilypondCacheDir(), fetchImpl = fetch, log = () => { }, }) {
53
+ const target = resolvePlatformTarget();
54
+ if (!target)
55
+ return undefined;
56
+ const { platform, arch, archiveExt, binaryName } = target;
57
+ const installDir = join(cacheDir, `lilypond-${version}-${platform}-${arch}`);
58
+ const markerPath = join(installDir, ".complete");
59
+ const binaryPath = join(installDir, "bin", binaryName);
60
+ if (await pathExists(markerPath))
61
+ return binaryPath;
62
+ const url = downloadUrlFor(version, platform, arch, archiveExt);
63
+ log(`astro-lilypond: downloading LilyPond ${version} (${platform}-${arch})…`);
64
+ const response = await fetchImpl(url);
65
+ if (!response.ok || !response.body) {
66
+ throw new Error(`failed to download LilyPond ${version} from ${url} (HTTP ${response.status})`);
67
+ }
68
+ const expectedSha256 = response.headers.get("x-checksum-sha256");
69
+ await mkdir(cacheDir, { recursive: true });
70
+ const workDir = await mkdtemp(join(cacheDir, ".tmp-"));
71
+ try {
72
+ const archivePath = join(workDir, `archive.${archiveExt}`);
73
+ const hash = createHash("sha256");
74
+ const chunks = [];
75
+ for await (const chunk of response.body) {
76
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
77
+ hash.update(buf);
78
+ chunks.push(buf);
79
+ }
80
+ const data = Buffer.concat(chunks);
81
+ if (expectedSha256) {
82
+ const actualSha256 = hash.digest("hex");
83
+ if (actualSha256 !== expectedSha256) {
84
+ throw new Error(`checksum mismatch downloading LilyPond ${version} from ${url}\n` +
85
+ ` expected ${expectedSha256}\n got ${actualSha256}`);
86
+ }
87
+ }
88
+ else {
89
+ log("astro-lilypond: download response had no checksum header — skipping integrity verification");
90
+ }
91
+ await writeFile(archivePath, data);
92
+ const extractDir = join(workDir, "extract");
93
+ await mkdir(extractDir, { recursive: true });
94
+ await extractArchive(archivePath, extractDir, archiveExt);
95
+ // The archive contains a single top-level `lilypond-<version>/` dir.
96
+ const [extractedRoot] = await readdir(extractDir);
97
+ if (!extractedRoot) {
98
+ throw new Error(`downloaded archive for LilyPond ${version} was empty`);
99
+ }
100
+ const extractedPath = join(extractDir, extractedRoot);
101
+ // Writing the marker inside the extracted tree makes the rename below
102
+ // move the binary and its "installed" marker into place atomically
103
+ // together, so a process killed mid-install can't leave a good install
104
+ // looking uninstalled.
105
+ await writeFile(join(extractedPath, ".complete"), "");
106
+ const reuseConcurrentInstall = async () => {
107
+ if (!(await pathExists(markerPath)))
108
+ return false;
109
+ log(`astro-lilypond: LilyPond ${version} was installed concurrently by another process; reusing it`);
110
+ return true;
111
+ };
112
+ if (await reuseConcurrentInstall())
113
+ return binaryPath;
114
+ try {
115
+ await rm(installDir, { recursive: true, force: true });
116
+ await rename(extractedPath, installDir);
117
+ }
118
+ catch (err) {
119
+ if (await reuseConcurrentInstall())
120
+ return binaryPath;
121
+ throw err;
122
+ }
123
+ log(`astro-lilypond: installed LilyPond ${version} to ${installDir}`);
124
+ return binaryPath;
125
+ }
126
+ finally {
127
+ await rm(workDir, { recursive: true, force: true });
128
+ }
129
+ }
@@ -0,0 +1,5 @@
1
+ export { type AutoInstallOptions, resolveAutoInstallOption, } from "./autoInstall.js";
2
+ export { lilypondCacheDir } from "./cacheDir.js";
3
+ export { downloadLilypond } from "./downloadLilypond.js";
4
+ export { resolvePlatformTarget } from "./platformTarget.js";
5
+ export { DEFAULT_LILYPOND_VERSION, resolveLilypondBinary, } from "./resolveLilypondBinary.js";
@@ -0,0 +1,5 @@
1
+ export { resolveAutoInstallOption, } from "./autoInstall.js";
2
+ export { lilypondCacheDir } from "./cacheDir.js";
3
+ export { downloadLilypond } from "./downloadLilypond.js";
4
+ export { resolvePlatformTarget } from "./platformTarget.js";
5
+ export { DEFAULT_LILYPOND_VERSION, resolveLilypondBinary, } from "./resolveLilypondBinary.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A platform/arch combination LilyPond publishes a prebuilt archive for,
3
+ * per https://gitlab.com/lilypond/lilypond/-/releases.
4
+ */
5
+ export interface PlatformTarget {
6
+ /** LilyPond's own platform token, as used in its release filenames. */
7
+ platform: "linux" | "darwin" | "mingw";
8
+ /** LilyPond's own arch token, as used in its release filenames. */
9
+ arch: "x86_64" | "arm64";
10
+ archiveExt: "tar.gz" | "zip";
11
+ /** Name of the `lilypond` executable inside the archive's `bin/` dir. */
12
+ binaryName: "lilypond" | "lilypond.exe";
13
+ }
14
+ export declare function resolvePlatformTarget(platform?: NodeJS.Platform, arch?: string): PlatformTarget | undefined;
@@ -0,0 +1,35 @@
1
+ export function resolvePlatformTarget(platform = process.platform, arch = process.arch) {
2
+ if (platform === "linux" && arch === "x64") {
3
+ return {
4
+ platform: "linux",
5
+ arch: "x86_64",
6
+ archiveExt: "tar.gz",
7
+ binaryName: "lilypond",
8
+ };
9
+ }
10
+ if (platform === "darwin" && arch === "arm64") {
11
+ return {
12
+ platform: "darwin",
13
+ arch: "arm64",
14
+ archiveExt: "tar.gz",
15
+ binaryName: "lilypond",
16
+ };
17
+ }
18
+ if (platform === "darwin" && arch === "x64") {
19
+ return {
20
+ platform: "darwin",
21
+ arch: "x86_64",
22
+ archiveExt: "tar.gz",
23
+ binaryName: "lilypond",
24
+ };
25
+ }
26
+ if (platform === "win32" && arch === "x64") {
27
+ return {
28
+ platform: "mingw",
29
+ arch: "x86_64",
30
+ archiveExt: "zip",
31
+ binaryName: "lilypond.exe",
32
+ };
33
+ }
34
+ return undefined;
35
+ }
@@ -0,0 +1,9 @@
1
+ import type { LilypondVersion } from "../types/lilypondVersion.js";
2
+ export declare const DEFAULT_LILYPOND_VERSION: LilypondVersion;
3
+ export interface ResolveLilypondBinaryOptions {
4
+ version?: LilypondVersion;
5
+ autoInstall: boolean;
6
+ log?: (message: string) => void;
7
+ warn?: (message: string) => void;
8
+ }
9
+ export declare function resolveLilypondBinary({ version, autoInstall, log, warn, }: ResolveLilypondBinaryOptions): Promise<string>;
@@ -0,0 +1,41 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { downloadLilypond } from "./downloadLilypond.js";
4
+ import { resolvePlatformTarget } from "./platformTarget.js";
5
+ const execFileAsync = promisify(execFile);
6
+ export const DEFAULT_LILYPOND_VERSION = "2.26.0";
7
+ const IS_ON_PATH_TIMEOUT_MS = 10_000;
8
+ async function isOnPath() {
9
+ try {
10
+ await execFileAsync("lilypond", ["--version"], {
11
+ signal: AbortSignal.timeout(IS_ON_PATH_TIMEOUT_MS),
12
+ });
13
+ return true;
14
+ }
15
+ catch (err) {
16
+ const code = err?.code;
17
+ return code !== "ENOENT";
18
+ }
19
+ }
20
+ export async function resolveLilypondBinary({ version = DEFAULT_LILYPOND_VERSION, autoInstall, log = () => { }, warn = () => { }, }) {
21
+ if (await isOnPath())
22
+ return "lilypond";
23
+ if (!autoInstall) {
24
+ warn("astro-lilypond: `lilypond` binary not found on PATH — LilyPond blocks will render as errors. " +
25
+ "Install LilyPond and ensure it is on PATH, or enable the `autoInstall` option (on by default).");
26
+ return "lilypond";
27
+ }
28
+ if (!resolvePlatformTarget()) {
29
+ warn(`astro-lilypond: \`lilypond\` binary not found on PATH, and no prebuilt LilyPond ${version} ` +
30
+ `is available for ${process.platform}/${process.arch}. Install LilyPond manually and ensure it is on PATH.`);
31
+ return "lilypond";
32
+ }
33
+ try {
34
+ const binaryPath = await downloadLilypond({ version, log });
35
+ return binaryPath ?? "lilypond";
36
+ }
37
+ catch (err) {
38
+ throw new Error(`astro-lilypond: automatic LilyPond install failed — ${err instanceof Error ? err.message : String(err)}. ` +
39
+ "Install LilyPond manually and ensure it is on PATH, or set `autoInstall: false` to require a PATH install without attempting a download.", { cause: err });
40
+ }
41
+ }
package/dist/index.d.ts CHANGED
@@ -1,33 +1,85 @@
1
1
  import type { AstroIntegration } from "astro";
2
+ import { type AstroComponentFactory } from "astro/runtime/server/index.js";
3
+ import type { AutoInstallOptions } from "./binary/index.js";
2
4
  import { type PluginOptions } from "./plugins/index.js";
3
5
  import { type LilypondDefaults } from "./render.js";
6
+ import { type LilypondMetadata } from "./utils/index.js";
4
7
  export declare const LY_EXTENSIONS: readonly [".ly", ".lilypond", ".ily"];
5
- export type { LilypondDefaults, PluginOptions as LilypondPluginOptions };
8
+ export type { AstroComponentFactory, AutoInstallOptions, LilypondDefaults, LilypondMetadata, PluginOptions as LilypondPluginOptions, };
6
9
  export interface LilypondPage {
7
10
  src: string;
8
11
  width?: number;
9
12
  height?: number;
10
13
  }
11
- export interface LilypondContent {
14
+ /**
15
+ * The result of a `.ly`/`.ily`/`.lilypond` import
16
+ * or `lilypondLoader()` collection entry.
17
+ */
18
+ export interface LilypondScore {
19
+ source: string;
20
+ alt: string;
21
+ sourceName: string | undefined;
22
+ includePaths: string[];
23
+ assetTitle: string;
24
+ meta: LilypondMetadata;
25
+ }
26
+ export interface RenderOptions {
27
+ /**
28
+ * Output format for `Score`.
29
+ * @default "svg"
30
+ */
31
+ format?: "svg" | "png";
32
+ /**
33
+ * Crop `Score` to a single tightly-fit image instead of full pages.
34
+ * @default resolved from the integration's `defaults.crop`
35
+ */
36
+ crop?: boolean;
37
+ /**
38
+ * Render a downloadable PDF of the same score, returned as `pdf`.
39
+ * @default false
40
+ */
41
+ pdf?: boolean;
42
+ }
43
+ export interface LilypondImageResult {
12
44
  pages: LilypondPage[];
13
45
  alt?: string;
14
46
  }
47
+ export interface LilypondPdfResult {
48
+ src: string;
49
+ }
50
+ export interface RenderResult {
51
+ Score: AstroComponentFactory;
52
+ pageCount: number;
53
+ pdf?: LilypondPdfResult;
54
+ meta: LilypondMetadata;
55
+ raw: string;
56
+ }
57
+ /**
58
+ * Renders a `LilypondScore` (from a `.ly`/`.ily`/`.lilypond` import,
59
+ * or a `lilypondLoader()` entry) to a renderable `<Score />` component.
60
+ */
61
+ export declare function render(score: LilypondScore, options?: RenderOptions): Promise<RenderResult>;
62
+ export declare function renderAll(scores: LilypondScore[], options?: RenderOptions): Promise<RenderResult[]>;
15
63
  export interface LilypondOptions extends PluginOptions {
16
64
  /**
17
- * Output format.
65
+ * Output format used by Markdown fences and `lilypondLoader()` entries.
18
66
  * @default "svg"
19
67
  */
20
68
  format?: "svg" | "png";
21
69
  /**
22
- * Defaults passed to each score.
23
- * Defaults can still be overridden by individual `.ly` files.
70
+ * Defaults passed to each score; can be overridden at render time.
24
71
  */
25
72
  defaults?: LilypondDefaults;
26
73
  /**
27
- * Milliseconds to wait for a single `lilypond` invocation before
28
- * aborting it.
74
+ * Ms to wait for a single `lilypond` invocation before aborting.
29
75
  * @default 60000
30
76
  */
31
77
  timeout?: number;
78
+ /**
79
+ * When no `lilypond` binary is found on `PATH`, download a matching
80
+ * prebuilt release into a local cache and use that instead.
81
+ * @default true
82
+ */
83
+ autoInstall?: boolean | AutoInstallOptions;
32
84
  }
33
85
  export default function lilypond(options?: LilypondOptions): AstroIntegration;
package/dist/index.js CHANGED
@@ -1,52 +1,101 @@
1
- import { execFile } from "node:child_process";
2
- import { promisify } from "node:util";
1
+ import { createComponent, renderTemplate, unescapeHTML, } from "astro/runtime/server/index.js";
3
2
  import emitAssetIntegration from "astro-emit-asset";
4
3
  import { rehypePlugin, remarkPlugin, satteriPlugin, } from "./plugins/index.js";
5
- import { defaultOptions, render, resolveCrop, } from "./render.js";
6
- import { altTextFor, emitLilypondAsset, includePathsFor, lyTypeDeclarationsFor, parseLyHeader, parseLyImportQuery, prependVersion, RECOGNIZED_QUERY_PARAMS, resolveDefaults, sourceNameFor, titleFor, } from "./utils/index.js";
7
- const execFileAsync = promisify(execFile);
4
+ import { render as renderScore, resolveCrop, } from "./render.js";
5
+ import { getRenderState, resolveAndSetRenderState } from "./renderState.js";
6
+ import { altTextFor, emitLilypondAsset, emitLilypondPdfAsset, includePathsFor, lyTypeDeclarationsFor, parseLyHeaderFields, prependVersion, renderedHtml, resolveDefaults, sourceNameFor, titleFor, toLilypondMetadata, } from "./utils/index.js";
8
7
  export const LY_EXTENSIONS = [".ly", ".lilypond", ".ily"];
9
- function lyFilePlugin(options) {
10
- return {
11
- name: "vite-plugin-astro-lilypond-ly",
12
- enforce: "pre",
13
- async transform(source, id) {
14
- const query = parseLyImportQuery(id);
15
- if (!query)
16
- return;
17
- const { pathname, cropOverride } = query;
18
- if (!LY_EXTENSIONS.some((ext) => pathname.endsWith(ext)))
19
- return;
20
- const { version, resolution, crop: cropSetting, cropScale, } = resolveDefaults(options.defaults);
21
- const crop = cropOverride ?? resolveCrop(cropSetting, "component");
22
- const src = version ? prependVersion(source, version) : source;
23
- const format = options.format ?? defaultOptions.format;
24
- const includePaths = includePathsFor(pathname);
25
- const sourceName = sourceNameFor(pathname);
26
- const title = titleFor(sourceName);
27
- const alt = altTextFor(parseLyHeader(source));
8
+ function createScoreComponent(content) {
9
+ return createComponent((_result, props) => {
10
+ const alt = props.alt ?? content.alt ?? "";
11
+ const html = renderedHtml(content.pages, alt, {
12
+ class: props.class,
13
+ style: props.style,
14
+ pageLimit: props.pageLimit,
15
+ });
16
+ return renderTemplate `${unescapeHTML(html)}`;
17
+ });
18
+ }
19
+ /**
20
+ * Renders a `LilypondScore` (from a `.ly`/`.ily`/`.lilypond` import,
21
+ * or a `lilypondLoader()` entry) to a renderable `<Score />` component.
22
+ */
23
+ export async function render(score, options = {}) {
24
+ const state = getRenderState();
25
+ const { resolution, crop: cropSetting, cropScale, } = resolveDefaults(state.defaults);
26
+ const format = options.format ?? "svg";
27
+ const crop = options.crop ?? resolveCrop(cropSetting, "component");
28
+ const [{ Score, pageCount }, pdf] = await Promise.all([
29
+ (async () => {
28
30
  const pages = await emitLilypondAsset({
29
- title,
31
+ title: score.assetTitle,
30
32
  format,
31
- source: src,
33
+ source: score.source,
32
34
  resolution,
33
35
  crop,
34
36
  sizeScale: crop ? cropScale : 1,
35
- render: () => render(src, {
37
+ binaryPath: state.binaryPath,
38
+ render: () => renderScore(score.source, {
36
39
  format,
37
40
  crop,
38
- defaults: options.defaults,
39
- timeout: options.timeout,
40
- includePaths,
41
- sourceName,
41
+ defaults: state.defaults,
42
+ timeout: state.timeout,
43
+ binaryPath: state.binaryPath,
44
+ includePaths: score.includePaths,
45
+ sourceName: score.sourceName,
42
46
  }),
43
47
  });
44
- const content = {
45
- pages,
48
+ return {
49
+ Score: createScoreComponent({ pages, alt: score.alt }),
50
+ pageCount: pages.length,
51
+ };
52
+ })(),
53
+ options.pdf
54
+ ? emitLilypondPdfAsset({
55
+ title: score.assetTitle,
56
+ source: score.source,
57
+ binaryPath: state.binaryPath,
58
+ render: () => renderScore(score.source, {
59
+ format: "pdf",
60
+ crop: false,
61
+ defaults: state.defaults,
62
+ timeout: state.timeout,
63
+ binaryPath: state.binaryPath,
64
+ includePaths: score.includePaths,
65
+ sourceName: score.sourceName,
66
+ }),
67
+ })
68
+ : Promise.resolve(undefined),
69
+ ]);
70
+ return { Score, pageCount, pdf, meta: score.meta, raw: score.source };
71
+ }
72
+ export async function renderAll(scores, options = {}) {
73
+ return Promise.all(scores.map((score) => render(score, options)));
74
+ }
75
+ function lyFilePlugin(options) {
76
+ return {
77
+ name: "vite-plugin-astro-lilypond-ly",
78
+ enforce: "pre",
79
+ async transform(source, id) {
80
+ if (!LY_EXTENSIONS.some((ext) => id.endsWith(ext)))
81
+ return;
82
+ const { version } = resolveDefaults(options.defaults);
83
+ const src = version ? prependVersion(source, version) : source;
84
+ const includePaths = includePathsFor(id);
85
+ const sourceName = sourceNameFor(id);
86
+ const assetTitle = titleFor(sourceName);
87
+ const meta = toLilypondMetadata(parseLyHeaderFields(source));
88
+ const alt = altTextFor(meta);
89
+ const score = {
90
+ source: src,
46
91
  alt,
92
+ sourceName,
93
+ includePaths,
94
+ assetTitle,
95
+ meta,
47
96
  };
48
97
  return {
49
- code: `export default ${JSON.stringify(content)}`,
98
+ code: `export default ${JSON.stringify(score)}`,
50
99
  };
51
100
  },
52
101
  };
@@ -56,10 +105,11 @@ export default function lilypond(options = {}) {
56
105
  name: "astro-lilypond",
57
106
  hooks: {
58
107
  "astro:config:setup": async ({ config, updateConfig, logger }) => {
59
- await execFileAsync("lilypond", ["--version"]).catch((err) => {
60
- if (err.code === "ENOENT") {
61
- logger?.warn("astro-lilypond: `lilypond` binary not found — LilyPond blocks will render as errors. Install LilyPond and ensure it is on PATH.");
62
- }
108
+ options.binaryPath = await resolveAndSetRenderState({
109
+ autoInstall: options.autoInstall,
110
+ defaults: options.defaults,
111
+ timeout: options.timeout,
112
+ logger,
63
113
  });
64
114
  updateConfig({
65
115
  integrations: [emitAssetIntegration()],
@@ -120,7 +170,7 @@ export default function lilypond(options = {}) {
120
170
  "astro:config:done": ({ injectTypes }) => {
121
171
  injectTypes({
122
172
  filename: "ly-types.d.ts",
123
- content: lyTypeDeclarationsFor(LY_EXTENSIONS, RECOGNIZED_QUERY_PARAMS),
173
+ content: lyTypeDeclarationsFor(LY_EXTENSIONS),
124
174
  });
125
175
  },
126
176
  },