@dirwell/share-image 0.0.1-alpha.1 → 0.0.2
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/README.md +49 -1
- package/dist/index.d.mts +7 -2
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{share-image-D2N_4dRw.mjs → share-image-DPfRwKbZ.mjs} +93 -15
- package/dist/share-image-DPfRwKbZ.mjs.map +1 -0
- package/dist/share-image-api-BIAcrVlH.mjs +10 -0
- package/dist/share-image-api-BIAcrVlH.mjs.map +1 -0
- package/dist/share-image-api-BVDAWsM-.mjs +2 -0
- package/package.json +7 -3
- package/dist/share-image-D2N_4dRw.mjs.map +0 -1
- package/dist/share-image-api-BZH7001a.mjs +0 -2
- package/dist/share-image-api-DcmMcWT0.mjs +0 -10
- package/dist/share-image-api-DcmMcWT0.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -1,7 +1,38 @@
|
|
|
1
1
|
# @dirwell/share-image
|
|
2
2
|
|
|
3
|
+
Requires Node.js 22.12 or later. [Read the guide](https://vp-tw.github.io/dirwell/metadata/).
|
|
4
|
+
|
|
3
5
|
Optional build-time metadata and 1200 × 630 PNG images. Install this package only when share metadata or image rendering is needed. Core, Plain and the rich themes do not depend on it.
|
|
4
6
|
|
|
7
|
+
## Save a share image
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @dirwell/share-image@0.0.2
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Save this as `image.mjs`, then run `node image.mjs`:
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { writeFile } from "node:fs/promises";
|
|
17
|
+
import { createShareImage } from "@dirwell/share-image";
|
|
18
|
+
const image = await createShareImage({
|
|
19
|
+
theme: "plain",
|
|
20
|
+
title: "Sample downloads",
|
|
21
|
+
description: "Release files and reports",
|
|
22
|
+
});
|
|
23
|
+
await writeFile("share.png", new Uint8Array(await image.arrayBuffer()));
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The result is a local 1200 × 630 PNG. No explorer build or browser runtime is required.
|
|
27
|
+
|
|
28
|
+
## Add metadata to an explorer
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
npm install @dirwell/core@0.0.2 @dirwell/theme-plain@0.0.2 @dirwell/share-image@0.0.2
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Create `files/note.txt`, save the following as `build.mjs` and run `node build.mjs`. Serve the complete `public/downloads` folder over HTTP; its pages reference the generated metadata/image assets.
|
|
35
|
+
|
|
5
36
|
```js
|
|
6
37
|
import { generateExplorer } from "@dirwell/core";
|
|
7
38
|
import { createPlainTheme } from "@dirwell/theme-plain";
|
|
@@ -18,6 +49,23 @@ await generateExplorer({
|
|
|
18
49
|
});
|
|
19
50
|
```
|
|
20
51
|
|
|
21
|
-
Omit `imageTheme` for text-only metadata. `image: false` disables any preset; a local File/path/file URL or async callback supplies a custom image. `createShareImage({ theme, title, description })` returns a PNG File. Rendering is lazy, uses bundled Adobe fonts
|
|
52
|
+
Omit `imageTheme` for text-only metadata. `image: false` disables any preset; a local File/path/file URL or async callback supplies a custom image. `createShareImage({ theme, title, description })` returns a PNG File. Rendering is lazy, uses bundled Adobe fonts by default or the supplied local fonts described below, and retains at most 32 rendered PNGs per process. No network/system-font lookup occurs. The selected fonts must cover every displayed character; unsupported text fails instead of silently emitting missing glyphs. Supply a licensed local font for other scripts, or use a separate renderer when the required shaping is outside your qualified workload. Per-build image loading is deduplicated; image output paths are validated and conflicting bytes are rejected.
|
|
22
53
|
|
|
23
54
|
This is a static-build provider. No server image route or runtime image service is implied.
|
|
55
|
+
|
|
56
|
+
The 0.0.x API may evolve. Pin your qualified version and upgrade the official family together. See [support and verification](https://vp-tw.github.io/dirwell/support/) for host, browser and device boundaries.
|
|
57
|
+
|
|
58
|
+
## Custom local fonts (0.0.2)
|
|
59
|
+
|
|
60
|
+
Supply a licensed single-face TTF or OTF file with coverage for every displayed character. Paths resolve from the process cwd; local file URLs also work. A body font supplies both roles unless a headline font is specified. Font files are read for each call, limited to 32 MiB each, and their byte digests invalidate the 32-image cache. No font is downloaded and no system font is consulted.
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
const image = await createShareImage({
|
|
64
|
+
theme: "ledger",
|
|
65
|
+
title: "資料下載",
|
|
66
|
+
description: "Release files",
|
|
67
|
+
fonts: { body: new URL("./fonts/MyLicensedFont.ttf", import.meta.url) },
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Custom text is shaped and outlined from the supplied bytes. Missing glyphs fail with the role and Unicode code point; no silent fallback is used. Collections, WOFF/WOFF2 and remote URLs are unsupported. Use a complete font for your text; the repository's renamed OFL test subset is deliberately limited. To use the image in metadata, pass the resulting `File` through `createMetadataProvider({ image, ... })`, or call the renderer from an async image callback. Complex-script/emoji rendering beyond the qualified Latin/CJK workload requires your own qualification.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { ContentCounts, DirectoryData, MetadataOptions, MetadataProviderFactory, PageMetadata, ThemeMetadataDefaults } from "@dirwell/core";
|
|
2
2
|
//#region src/share-image.d.ts
|
|
3
|
+
interface ShareImageFonts {
|
|
4
|
+
readonly body?: string | URL;
|
|
5
|
+
readonly headline?: string | URL;
|
|
6
|
+
}
|
|
3
7
|
interface ShareImageOptions {
|
|
8
|
+
readonly fonts?: ShareImageFonts;
|
|
4
9
|
readonly theme?: "ledger" | "plain" | "crosswave";
|
|
5
10
|
readonly title: string;
|
|
6
11
|
readonly description: string;
|
|
@@ -9,7 +14,7 @@ interface ShareImageOptions {
|
|
|
9
14
|
}
|
|
10
15
|
//#endregion
|
|
11
16
|
//#region src/share-image-api.d.ts
|
|
12
|
-
/** Render a PNG at build time using the selected
|
|
17
|
+
/** Render a PNG at build time using the selected preset and bundled or supplied local fonts. */
|
|
13
18
|
export declare function createShareImage(options: ShareImageOptions): Promise<File>;
|
|
14
19
|
//#endregion
|
|
15
20
|
//#region src/metadata.d.ts
|
|
@@ -26,5 +31,5 @@ export declare function createMetadataResolver(options: MetadataOptions, default
|
|
|
26
31
|
/** Opt-in build metadata. PNG presets are generated only when defaults.imageTheme is supplied. */
|
|
27
32
|
export declare function createMetadataProvider(options: MetadataOptions, defaults: ThemeMetadataDefaults, sourceDirectory?: string): MetadataProviderFactory;
|
|
28
33
|
//#endregion
|
|
29
|
-
export type { ShareImageOptions };
|
|
34
|
+
export type { ShareImageFonts, ShareImageOptions };
|
|
30
35
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createShareImage } from "./share-image-api-
|
|
1
|
+
import { t as createShareImage } from "./share-image-api-BIAcrVlH.mjs";
|
|
2
2
|
import { escapeHtml } from "@dirwell/core";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
@@ -106,7 +106,7 @@ function createMetadataResolver(options, defaults, counts, sourceDirectory) {
|
|
|
106
106
|
if (configured === void 0) {
|
|
107
107
|
const preset = defaults.imageTheme;
|
|
108
108
|
if (preset === void 0) return null;
|
|
109
|
-
defaultImage ??= import("./share-image-api-
|
|
109
|
+
defaultImage ??= import("./share-image-api-BVDAWsM-.mjs").then(({ createShareImage }) => createShareImage({
|
|
110
110
|
theme: preset,
|
|
111
111
|
repositoryName: site.repositoryName,
|
|
112
112
|
title: presetTitle,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/metadata.ts","../src/index.ts"],"sourcesContent":["import { escapeHtml } from \"@dirwell/core\";\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DirectoryData } from \"@dirwell/core\";\n\nimport type {\n ContentCounts,\n MetadataContext,\n ImageSource,\n MetadataImage,\n ResolvedMetadataContext,\n MetadataOptions,\n ThemeMetadataDefaults,\n PageMetadata,\n} from \"@dirwell/core\";\nexport type {\n ContentCounts,\n MetadataContext,\n MetadataValue,\n ImageSource,\n MetadataImage,\n ResolvedMetadataContext,\n MetadataImageValue,\n MetadataOptions,\n ThemeMetadataDefaults,\n PageMetadata,\n} from \"@dirwell/core\";\nexport function countEntries(directory: DirectoryData): ContentCounts {\n return countKinds(directory.entries.map((entry) => entry.kind));\n}\nexport function countKinds(kinds: Iterable<string>): ContentCounts {\n let folderCount = 0,\n fileCount = 0,\n linkCount = 0;\n for (const kind of kinds) {\n if (kind === \"directory\") folderCount++;\n else if (kind === \"file\") fileCount++;\n else if (kind === \"symlink\") linkCount++;\n }\n return { folderCount, fileCount, linkCount };\n}\nexport function describeContent(counts: ContentCounts): string {\n const parts: string[] = [];\n for (const [count, noun] of [\n [counts.folderCount, \"folder\"],\n [counts.fileCount, \"file\"],\n [counts.linkCount, \"link\"],\n ] as const) {\n if (count > 0) parts.push(`${count} ${noun}${count === 1 ? \"\" : \"s\"}`);\n }\n return parts.join(\" · \") || \"Empty folder\";\n}\nexport function repositoryName(repositoryUrl: string): string {\n try {\n return new URL(repositoryUrl).pathname.replace(/^\\/+|\\/+$/g, \"\").replace(/\\.git$/, \"\");\n } catch {\n return repositoryUrl;\n }\n}\n\nfunction stringValue(value: unknown, label: string): string {\n if (typeof value !== \"string\") throw new TypeError(`${label} must resolve to a string`);\n return value;\n}\nfunction safeOutputPath(value: string): string {\n if (\n !value ||\n value.includes(\"\\\\\") ||\n value.includes(\"\\0\") ||\n value.startsWith(\"/\") ||\n /^[a-z]:/i.test(value) ||\n value.split(\"/\").some((part) => !part || part === \".\" || part === \"..\")\n )\n throw new Error(`Unsafe metadata image outputPath: ${value}`);\n if (value.startsWith(\"__dirwell/\") && !value.startsWith(\"__dirwell/metadata/\"))\n throw new Error(\"Metadata image cannot overwrite reserved Dirwell assets\");\n return value;\n}\nfunction deployedRoot(value: string | undefined): URL | undefined {\n if (value === undefined) return undefined;\n const url = new URL(value);\n if (\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.search ||\n url.hash ||\n url.username ||\n url.password\n )\n throw new Error(\n \"metadata.siteUrl must be an HTTP(S) explorer root without credentials, query, or fragment\",\n );\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n return url;\n}\nexport function createMetadataResolver(\n options: MetadataOptions,\n defaults: ThemeMetadataDefaults,\n counts: ContentCounts,\n sourceDirectory: string,\n) {\n const site = Object.freeze({\n ...counts,\n name: stringValue(options.siteName ?? defaults.siteName, \"metadata.siteName\"),\n repositoryName: stringValue(\n options.repositoryName ?? defaults.repositoryName,\n \"metadata.repositoryName\",\n ),\n });\n const siteUrl = deployedRoot(options.siteUrl);\n const presetTitle = typeof options.title === \"string\" ? options.title : site.name;\n const presetDescription =\n typeof options.description === \"string\"\n ? options.description\n : `Archive totals: ${describeContent(site)}`;\n const assets = new Map<string, Uint8Array>();\n let defaultImage: Promise<File> | undefined;\n // One source snapshot per build: fixed images should not reread or rehash per page.\n const fileSources = new WeakMap<\n File,\n Promise<{ bytes: Uint8Array; extension: string; digest: string }>\n >();\n const pathSources = new Map<\n string,\n Promise<{ bytes: Uint8Array; extension: string; digest: string }>\n >();\n const loaded = async (bytes: Uint8Array, filename: string) => {\n const extension = path.extname(filename).toLowerCase();\n if (![\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"].includes(extension))\n throw new Error(\"Metadata images must be PNG, JPEG, WebP, or GIF files\");\n return { bytes, extension, digest: createHash(\"sha256\").update(bytes).digest(\"hex\") };\n };\n function loadImage(source: ImageSource) {\n if (source instanceof File) {\n let image = fileSources.get(source);\n if (image === undefined) {\n image = source.arrayBuffer().then((buffer) => loaded(new Uint8Array(buffer), source.name));\n fileSources.set(source, image);\n }\n return image;\n }\n if (typeof source !== \"string\" && !(source instanceof URL))\n throw new TypeError(\"metadata.image.source must be a File, local path, or file URL\");\n if (source instanceof URL && source.protocol !== \"file:\")\n throw new Error(\"metadata.image source URLs must use file:\");\n const input =\n source instanceof URL ? fileURLToPath(source) : path.resolve(sourceDirectory, source);\n let image = pathSources.get(input);\n if (image === undefined) {\n image = readFile(input).then((bytes) => loaded(bytes, path.basename(input)));\n pathSources.set(input, image);\n }\n return image;\n }\n\n async function imageFor(\n context: ResolvedMetadataContext,\n ): Promise<{ outputPath: string; alt: string } | null> {\n const configured = options.image === undefined ? defaults.image : options.image;\n const isPreset = configured === undefined && defaults.imageTheme !== undefined;\n let image = typeof configured === \"function\" ? await configured(context) : configured;\n if (image === false) return null;\n if (configured === undefined) {\n const preset = defaults.imageTheme;\n if (preset === undefined) return null;\n defaultImage ??= import(\"./share-image-api.ts\").then(({ createShareImage }) =>\n createShareImage({\n theme: preset,\n repositoryName: site.repositoryName,\n title: presetTitle,\n description: presetDescription,\n }),\n );\n image = await defaultImage;\n }\n if (image === undefined)\n throw new TypeError(\"metadata.image callback must return an image or false\");\n const config: MetadataImage =\n image instanceof File || typeof image === \"string\" || image instanceof URL\n ? { source: image }\n : image;\n if (!config || typeof config !== \"object\")\n throw new TypeError(\n \"metadata.image must resolve to a File, local path, file URL, or source object\",\n );\n const { bytes, extension, digest } = await loadImage(config.source);\n const outputPath = safeOutputPath(\n config.outputPath ?? `__dirwell/metadata/${digest}${extension}`,\n );\n const existing = assets.get(outputPath);\n if (existing !== undefined && existing !== bytes && !Buffer.from(existing).equals(bytes))\n throw new Error(`Conflicting metadata image outputPath: ${outputPath}`);\n assets.set(outputPath, bytes);\n return {\n outputPath,\n alt: stringValue(\n config.alt ?? (isPreset ? `${presetTitle}. ${presetDescription}` : context.title),\n \"metadata.image.alt\",\n ),\n };\n }\n return {\n assets,\n async resolve(\n directory: DirectoryData,\n hrefForOutput: (outputPath: string) => string,\n pagePath: string,\n ): Promise<PageMetadata> {\n const relativePath = directory.current.relativePath;\n const context: MetadataContext = Object.freeze({\n site,\n directory: Object.freeze({\n ...countEntries(directory),\n relativePath,\n name: directory.current.name,\n }),\n });\n const title = stringValue(\n typeof options.title === \"function\"\n ? await options.title(context)\n : (options.title ?? (relativePath ? `${relativePath} · ${site.name}` : site.name)),\n \"metadata.title\",\n );\n const description = stringValue(\n typeof options.description === \"function\"\n ? await options.description(context)\n : (options.description ??\n (relativePath\n ? `Browse ${relativePath} in ${site.name}. This folder: ${describeContent(context.directory)}.`\n : `Browse files in ${site.name}. Archive totals: ${describeContent(site)}.`)),\n \"metadata.description\",\n );\n const image = await imageFor(Object.freeze({ ...context, title, description }));\n const meta = (key: string, value: string, property = false) =>\n `<meta data-dirwell-metadata ${property ? \"property\" : \"name\"}=\"${key}\" content=\"${escapeHtml(value)}\">`;\n let head = `<title>${escapeHtml(title)}</title>${meta(\"description\", description)}${meta(\"og:title\", title, true)}${meta(\"og:description\", description, true)}${meta(\"og:type\", \"website\", true)}`;\n if (siteUrl) {\n const canonical = new URL(pagePath.split(\"/\").map(encodeURIComponent).join(\"/\"), siteUrl)\n .href;\n head += `${meta(\"og:url\", canonical, true)}<link data-dirwell-metadata rel=\"canonical\" href=\"${escapeHtml(canonical)}\">`;\n }\n if (image) {\n const href = siteUrl\n ? new URL(image.outputPath.split(\"/\").map(encodeURIComponent).join(\"/\"), siteUrl).href\n : hrefForOutput(image.outputPath);\n head +=\n meta(\"og:image\", href, true) +\n meta(\"og:image:alt\", image.alt, true) +\n meta(\"twitter:card\", \"summary_large_image\") +\n meta(\"twitter:title\", title) +\n meta(\"twitter:description\", description) +\n meta(\"twitter:image\", href) +\n meta(\"twitter:image:alt\", image.alt);\n }\n return { title, description, head };\n },\n };\n}\n","import type {\n MetadataOptions,\n ThemeMetadataDefaults,\n MetadataProviderFactory,\n} from \"@dirwell/core\";\nimport { countKinds, createMetadataResolver } from \"./metadata.ts\";\nexport { createShareImage } from \"./share-image-api.ts\";\nexport type { ShareImageOptions } from \"./share-image-api.ts\";\nexport {\n countEntries,\n countKinds,\n describeContent,\n repositoryName,\n createMetadataResolver,\n} from \"./metadata.ts\";\n/** Opt-in build metadata. PNG presets are generated only when defaults.imageTheme is supplied. */\nexport function createMetadataProvider(\n options: MetadataOptions,\n defaults: ThemeMetadataDefaults,\n sourceDirectory = process.cwd(),\n): MetadataProviderFactory {\n return ({ sourceKinds }) =>\n createMetadataResolver(options, defaults, countKinds(sourceKinds.values()), sourceDirectory);\n}\n"],"mappings":";;;;;;;AA6BA,SAAgB,aAAa,WAAyC;CACpE,OAAO,WAAW,UAAU,QAAQ,KAAK,UAAU,MAAM,IAAI,CAAC;AAChE;AACA,SAAgB,WAAW,OAAwC;CACjE,IAAI,cAAc,GAChB,YAAY,GACZ,YAAY;CACd,KAAK,MAAM,QAAQ,OACjB,IAAI,SAAS,aAAa;MACrB,IAAI,SAAS,QAAQ;MACrB,IAAI,SAAS,WAAW;CAE/B,OAAO;EAAE;EAAa;EAAW;CAAU;AAC7C;AACA,SAAgB,gBAAgB,QAA+B;CAC7D,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,OAAO,SAAS;EAC1B,CAAC,OAAO,aAAa,QAAQ;EAC7B,CAAC,OAAO,WAAW,MAAM;EACzB,CAAC,OAAO,WAAW,MAAM;CAC3B,GACE,IAAI,QAAQ,GAAG,MAAM,KAAK,GAAG,MAAM,GAAG,OAAO,UAAU,IAAI,KAAK,KAAK;CAEvE,OAAO,MAAM,KAAK,KAAK,KAAK;AAC9B;AACA,SAAgB,eAAe,eAA+B;CAC5D,IAAI;EACF,OAAO,IAAI,IAAI,aAAa,CAAC,CAAC,SAAS,QAAQ,cAAc,EAAE,CAAC,CAAC,QAAQ,UAAU,EAAE;CACvF,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,YAAY,OAAgB,OAAuB;CAC1D,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,UAAU,GAAG,MAAM,0BAA0B;CACtF,OAAO;AACT;AACA,SAAS,eAAe,OAAuB;CAC7C,IACE,CAAC,SACD,MAAM,SAAS,IAAI,KACnB,MAAM,SAAS,IAAI,KACnB,MAAM,W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,QAAQ,EAAE,kBACR,uBAAuB,SAAS,UAAU,WAAW,YAAY,OAAO,CAAC,GAAG,eAAe;AAC/F"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/metadata.ts","../src/index.ts"],"sourcesContent":["import { escapeHtml } from \"@dirwell/core\";\nimport { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DirectoryData } from \"@dirwell/core\";\n\nimport type {\n ContentCounts,\n MetadataContext,\n ImageSource,\n MetadataImage,\n ResolvedMetadataContext,\n MetadataOptions,\n ThemeMetadataDefaults,\n PageMetadata,\n} from \"@dirwell/core\";\nexport type {\n ContentCounts,\n MetadataContext,\n MetadataValue,\n ImageSource,\n MetadataImage,\n ResolvedMetadataContext,\n MetadataImageValue,\n MetadataOptions,\n ThemeMetadataDefaults,\n PageMetadata,\n} from \"@dirwell/core\";\nexport function countEntries(directory: DirectoryData): ContentCounts {\n return countKinds(directory.entries.map((entry) => entry.kind));\n}\nexport function countKinds(kinds: Iterable<string>): ContentCounts {\n let folderCount = 0,\n fileCount = 0,\n linkCount = 0;\n for (const kind of kinds) {\n if (kind === \"directory\") folderCount++;\n else if (kind === \"file\") fileCount++;\n else if (kind === \"symlink\") linkCount++;\n }\n return { folderCount, fileCount, linkCount };\n}\nexport function describeContent(counts: ContentCounts): string {\n const parts: string[] = [];\n for (const [count, noun] of [\n [counts.folderCount, \"folder\"],\n [counts.fileCount, \"file\"],\n [counts.linkCount, \"link\"],\n ] as const) {\n if (count > 0) parts.push(`${count} ${noun}${count === 1 ? \"\" : \"s\"}`);\n }\n return parts.join(\" · \") || \"Empty folder\";\n}\nexport function repositoryName(repositoryUrl: string): string {\n try {\n return new URL(repositoryUrl).pathname.replace(/^\\/+|\\/+$/g, \"\").replace(/\\.git$/, \"\");\n } catch {\n return repositoryUrl;\n }\n}\n\nfunction stringValue(value: unknown, label: string): string {\n if (typeof value !== \"string\") throw new TypeError(`${label} must resolve to a string`);\n return value;\n}\nfunction safeOutputPath(value: string): string {\n if (\n !value ||\n value.includes(\"\\\\\") ||\n value.includes(\"\\0\") ||\n value.startsWith(\"/\") ||\n /^[a-z]:/i.test(value) ||\n value.split(\"/\").some((part) => !part || part === \".\" || part === \"..\")\n )\n throw new Error(`Unsafe metadata image outputPath: ${value}`);\n if (value.startsWith(\"__dirwell/\") && !value.startsWith(\"__dirwell/metadata/\"))\n throw new Error(\"Metadata image cannot overwrite reserved Dirwell assets\");\n return value;\n}\nfunction deployedRoot(value: string | undefined): URL | undefined {\n if (value === undefined) return undefined;\n const url = new URL(value);\n if (\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.search ||\n url.hash ||\n url.username ||\n url.password\n )\n throw new Error(\n \"metadata.siteUrl must be an HTTP(S) explorer root without credentials, query, or fragment\",\n );\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n return url;\n}\nexport function createMetadataResolver(\n options: MetadataOptions,\n defaults: ThemeMetadataDefaults,\n counts: ContentCounts,\n sourceDirectory: string,\n) {\n const site = Object.freeze({\n ...counts,\n name: stringValue(options.siteName ?? defaults.siteName, \"metadata.siteName\"),\n repositoryName: stringValue(\n options.repositoryName ?? defaults.repositoryName,\n \"metadata.repositoryName\",\n ),\n });\n const siteUrl = deployedRoot(options.siteUrl);\n const presetTitle = typeof options.title === \"string\" ? options.title : site.name;\n const presetDescription =\n typeof options.description === \"string\"\n ? options.description\n : `Archive totals: ${describeContent(site)}`;\n const assets = new Map<string, Uint8Array>();\n let defaultImage: Promise<File> | undefined;\n // One source snapshot per build: fixed images should not reread or rehash per page.\n const fileSources = new WeakMap<\n File,\n Promise<{ bytes: Uint8Array; extension: string; digest: string }>\n >();\n const pathSources = new Map<\n string,\n Promise<{ bytes: Uint8Array; extension: string; digest: string }>\n >();\n const loaded = async (bytes: Uint8Array, filename: string) => {\n const extension = path.extname(filename).toLowerCase();\n if (![\".png\", \".jpg\", \".jpeg\", \".webp\", \".gif\"].includes(extension))\n throw new Error(\"Metadata images must be PNG, JPEG, WebP, or GIF files\");\n return { bytes, extension, digest: createHash(\"sha256\").update(bytes).digest(\"hex\") };\n };\n function loadImage(source: ImageSource) {\n if (source instanceof File) {\n let image = fileSources.get(source);\n if (image === undefined) {\n image = source.arrayBuffer().then((buffer) => loaded(new Uint8Array(buffer), source.name));\n fileSources.set(source, image);\n }\n return image;\n }\n if (typeof source !== \"string\" && !(source instanceof URL))\n throw new TypeError(\"metadata.image.source must be a File, local path, or file URL\");\n if (source instanceof URL && source.protocol !== \"file:\")\n throw new Error(\"metadata.image source URLs must use file:\");\n const input =\n source instanceof URL ? fileURLToPath(source) : path.resolve(sourceDirectory, source);\n let image = pathSources.get(input);\n if (image === undefined) {\n image = readFile(input).then((bytes) => loaded(bytes, path.basename(input)));\n pathSources.set(input, image);\n }\n return image;\n }\n\n async function imageFor(\n context: ResolvedMetadataContext,\n ): Promise<{ outputPath: string; alt: string } | null> {\n const configured = options.image === undefined ? defaults.image : options.image;\n const isPreset = configured === undefined && defaults.imageTheme !== undefined;\n let image = typeof configured === \"function\" ? await configured(context) : configured;\n if (image === false) return null;\n if (configured === undefined) {\n const preset = defaults.imageTheme;\n if (preset === undefined) return null;\n defaultImage ??= import(\"./share-image-api.ts\").then(({ createShareImage }) =>\n createShareImage({\n theme: preset,\n repositoryName: site.repositoryName,\n title: presetTitle,\n description: presetDescription,\n }),\n );\n image = await defaultImage;\n }\n if (image === undefined)\n throw new TypeError(\"metadata.image callback must return an image or false\");\n const config: MetadataImage =\n image instanceof File || typeof image === \"string\" || image instanceof URL\n ? { source: image }\n : image;\n if (!config || typeof config !== \"object\")\n throw new TypeError(\n \"metadata.image must resolve to a File, local path, file URL, or source object\",\n );\n const { bytes, extension, digest } = await loadImage(config.source);\n const outputPath = safeOutputPath(\n config.outputPath ?? `__dirwell/metadata/${digest}${extension}`,\n );\n const existing = assets.get(outputPath);\n if (existing !== undefined && existing !== bytes && !Buffer.from(existing).equals(bytes))\n throw new Error(`Conflicting metadata image outputPath: ${outputPath}`);\n assets.set(outputPath, bytes);\n return {\n outputPath,\n alt: stringValue(\n config.alt ?? (isPreset ? `${presetTitle}. ${presetDescription}` : context.title),\n \"metadata.image.alt\",\n ),\n };\n }\n return {\n assets,\n async resolve(\n directory: DirectoryData,\n hrefForOutput: (outputPath: string) => string,\n pagePath: string,\n ): Promise<PageMetadata> {\n const relativePath = directory.current.relativePath;\n const context: MetadataContext = Object.freeze({\n site,\n directory: Object.freeze({\n ...countEntries(directory),\n relativePath,\n name: directory.current.name,\n }),\n });\n const title = stringValue(\n typeof options.title === \"function\"\n ? await options.title(context)\n : (options.title ?? (relativePath ? `${relativePath} · ${site.name}` : site.name)),\n \"metadata.title\",\n );\n const description = stringValue(\n typeof options.description === \"function\"\n ? await options.description(context)\n : (options.description ??\n (relativePath\n ? `Browse ${relativePath} in ${site.name}. This folder: ${describeContent(context.directory)}.`\n : `Browse files in ${site.name}. Archive totals: ${describeContent(site)}.`)),\n \"metadata.description\",\n );\n const image = await imageFor(Object.freeze({ ...context, title, description }));\n const meta = (key: string, value: string, property = false) =>\n `<meta data-dirwell-metadata ${property ? \"property\" : \"name\"}=\"${key}\" content=\"${escapeHtml(value)}\">`;\n let head = `<title>${escapeHtml(title)}</title>${meta(\"description\", description)}${meta(\"og:title\", title, true)}${meta(\"og:description\", description, true)}${meta(\"og:type\", \"website\", true)}`;\n if (siteUrl) {\n const canonical = new URL(pagePath.split(\"/\").map(encodeURIComponent).join(\"/\"), siteUrl)\n .href;\n head += `${meta(\"og:url\", canonical, true)}<link data-dirwell-metadata rel=\"canonical\" href=\"${escapeHtml(canonical)}\">`;\n }\n if (image) {\n const href = siteUrl\n ? new URL(image.outputPath.split(\"/\").map(encodeURIComponent).join(\"/\"), siteUrl).href\n : hrefForOutput(image.outputPath);\n head +=\n meta(\"og:image\", href, true) +\n meta(\"og:image:alt\", image.alt, true) +\n meta(\"twitter:card\", \"summary_large_image\") +\n meta(\"twitter:title\", title) +\n meta(\"twitter:description\", description) +\n meta(\"twitter:image\", href) +\n meta(\"twitter:image:alt\", image.alt);\n }\n return { title, description, head };\n },\n };\n}\n","import type {\n MetadataOptions,\n ThemeMetadataDefaults,\n MetadataProviderFactory,\n} from \"@dirwell/core\";\nimport { countKinds, createMetadataResolver } from \"./metadata.ts\";\nexport { createShareImage } from \"./share-image-api.ts\";\nexport type { ShareImageOptions, ShareImageFonts } from \"./share-image-api.ts\";\nexport {\n countEntries,\n countKinds,\n describeContent,\n repositoryName,\n createMetadataResolver,\n} from \"./metadata.ts\";\n/** Opt-in build metadata. PNG presets are generated only when defaults.imageTheme is supplied. */\nexport function createMetadataProvider(\n options: MetadataOptions,\n defaults: ThemeMetadataDefaults,\n sourceDirectory = process.cwd(),\n): MetadataProviderFactory {\n return ({ sourceKinds }) =>\n createMetadataResolver(options, defaults, countKinds(sourceKinds.values()), sourceDirectory);\n}\n"],"mappings":";;;;;;;AA6BA,SAAgB,aAAa,WAAyC;CACpE,OAAO,WAAW,UAAU,QAAQ,KAAK,UAAU,MAAM,IAAI,CAAC;AAChE;AACA,SAAgB,WAAW,OAAwC;CACjE,IAAI,cAAc,GAChB,YAAY,GACZ,YAAY;CACd,KAAK,MAAM,QAAQ,OACjB,IAAI,SAAS,aAAa;MACrB,IAAI,SAAS,QAAQ;MACrB,IAAI,SAAS,WAAW;CAE/B,OAAO;EAAE;EAAa;EAAW;CAAU;AAC7C;AACA,SAAgB,gBAAgB,QAA+B;CAC7D,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,CAAC,OAAO,SAAS;EAC1B,CAAC,OAAO,aAAa,QAAQ;EAC7B,CAAC,OAAO,WAAW,MAAM;EACzB,CAAC,OAAO,WAAW,MAAM;CAC3B,GACE,IAAI,QAAQ,GAAG,MAAM,KAAK,GAAG,MAAM,GAAG,OAAO,UAAU,IAAI,KAAK,KAAK;CAEvE,OAAO,MAAM,KAAK,KAAK,KAAK;AAC9B;AACA,SAAgB,eAAe,eA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,CAAC,OAChF,cAAc,MAAM,UAAU;IAClC,QACE,KAAK,YAAY,MAAM,IAAI,IAC3B,KAAK,gBAAgB,MAAM,KAAK,IAAI,IACpC,KAAK,gBAAgB,qBAAqB,IAC1C,KAAK,iBAAiB,KAAK,IAC3B,KAAK,uBAAuB,WAAW,IACvC,KAAK,iBAAiB,IAAI,IAC1B,KAAK,qBAAqB,MAAM,GAAG;GACvC;GACA,OAAO;IAAE;IAAO;IAAa;GAAK;EACpC;CACF;AACF;;;;AClPA,SAAgB,uBACd,SACA,UACA,kBAAkB,QAAQ,IAAI,GACL;CACzB,QAAQ,EAAE,kBACR,uBAAuB,SAAS,UAAU,WAAW,YAAY,OAAO,CAAC,GAAG,eAAe;AAC/F"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { escapeHtml } from "@dirwell/core";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
-
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { open, readFile } from "node:fs/promises";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { create } from "fontkit";
|
|
6
6
|
import { Resvg } from "@resvg/resvg-js";
|
|
@@ -46,18 +46,62 @@ const themes = {
|
|
|
46
46
|
}
|
|
47
47
|
};
|
|
48
48
|
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
|
|
49
|
+
async function loadFace(source, role) {
|
|
50
|
+
if (typeof source !== "string" && !(source instanceof URL) || typeof source === "string" && (!source || /^[a-z][a-z0-9+.-]*:\/\//i.test(source)) || source instanceof URL && (source.protocol !== "file:" || source.hostname && source.hostname !== "localhost")) throw new TypeError(`fonts.${role} must be a local path or file URL`);
|
|
51
|
+
const handle = await open(source, "r").catch((cause) => {
|
|
52
|
+
throw new TypeError(`Cannot read fonts.${role}`, { cause });
|
|
53
|
+
});
|
|
54
|
+
let bytes;
|
|
55
|
+
try {
|
|
56
|
+
const stats = await handle.stat();
|
|
57
|
+
if (!stats.isFile()) throw new TypeError(`fonts.${role} must refer to a regular font file`);
|
|
58
|
+
const size = stats.size;
|
|
59
|
+
if (size < 12) throw new TypeError(`fonts.${role} must contain a valid TTF or OTF header`);
|
|
60
|
+
if (size > 33554432) throw new TypeError(`fonts.${role} must be at most 32 MiB`);
|
|
61
|
+
const bounded = Buffer.alloc(size + 1);
|
|
62
|
+
let received = 0;
|
|
63
|
+
while (received < bounded.length) {
|
|
64
|
+
const result = await handle.read(bounded, received, bounded.length - received, null);
|
|
65
|
+
if (!result.bytesRead) break;
|
|
66
|
+
received += result.bytesRead;
|
|
67
|
+
}
|
|
68
|
+
if (received !== size) throw new TypeError(`fonts.${role} changed while being read`);
|
|
69
|
+
bytes = bounded.subarray(0, received);
|
|
70
|
+
} finally {
|
|
71
|
+
await handle.close();
|
|
72
|
+
}
|
|
73
|
+
if (bytes.readUInt32BE(0) !== 65536 && bytes.toString("ascii", 0, 4) !== "OTTO") throw new TypeError(`fonts.${role} must be a single TTF or OTF font`);
|
|
74
|
+
let font;
|
|
75
|
+
try {
|
|
76
|
+
font = create(bytes);
|
|
77
|
+
if (typeof font.layout !== "function" || !Number.isFinite(font.unitsPerEm) || font.unitsPerEm <= 0) throw new TypeError("Invalid font metrics");
|
|
78
|
+
} catch (cause) {
|
|
79
|
+
throw new TypeError(`Invalid fonts.${role}`, { cause });
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
face: {
|
|
83
|
+
font,
|
|
84
|
+
custom: true,
|
|
85
|
+
role
|
|
86
|
+
},
|
|
87
|
+
bytes
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function requireGlyphs(value, face) {
|
|
91
|
+
for (const character of value) {
|
|
92
|
+
const codePoint = character.codePointAt(0);
|
|
93
|
+
if (!face.font.hasGlyphForCodePoint(codePoint)) throw new Error(`${face.custom ? `Share-image ${face.role}` : "Bundled share-image"} font lacks U+${codePoint.toString(16).toUpperCase()}; supply a font with glyph coverage or metadata.image: false`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
49
96
|
function width(text, face, size) {
|
|
50
|
-
const font =
|
|
97
|
+
const font = face.font;
|
|
51
98
|
return font.layout(text).positions.reduce((sum, position) => sum + position.xAdvance, 0) * size / font.unitsPerEm;
|
|
52
99
|
}
|
|
53
100
|
function fit(value, face, sizes, limit, maxLines = 2) {
|
|
54
101
|
if (typeof value !== "string") throw new TypeError("Share image text must be a string");
|
|
55
102
|
const text = Array.from(segmenter.segment(value.slice(0, 16384).normalize("NFC").replace(/\s+/g, " ").trim()), (part) => part.segment);
|
|
56
103
|
const bounded = text.slice(0, 2048);
|
|
57
|
-
|
|
58
|
-
const codePoint = character.codePointAt(0);
|
|
59
|
-
if (!fonts[face].hasGlyphForCodePoint(codePoint)) throw new Error(`Bundled share-image font lacks U+${codePoint.toString(16).toUpperCase()}; use a custom image renderer or metadata.image: false`);
|
|
60
|
-
}
|
|
104
|
+
requireGlyphs(bounded.join(""), face);
|
|
61
105
|
for (const size of sizes) {
|
|
62
106
|
let position = 0;
|
|
63
107
|
const lines = [];
|
|
@@ -74,6 +118,7 @@ function fit(value, face, sizes, limit, maxLines = 2) {
|
|
|
74
118
|
let graphemes = Array.from(segmenter.segment(line), (part) => part.segment);
|
|
75
119
|
while (graphemes.length && width(graphemes.join("") + "…", face, size) > limit) graphemes.pop();
|
|
76
120
|
line = graphemes.join("") + "…";
|
|
121
|
+
requireGlyphs(line, face);
|
|
77
122
|
}
|
|
78
123
|
lines.push(line);
|
|
79
124
|
position = end;
|
|
@@ -88,18 +133,51 @@ function fit(value, face, sizes, limit, maxLines = 2) {
|
|
|
88
133
|
lines: []
|
|
89
134
|
};
|
|
90
135
|
}
|
|
91
|
-
function text(value, x, y, gap, fill, family, weight = 400, anchor = "start") {
|
|
136
|
+
function text(value, x, y, gap, fill, family, weight = 400, anchor = "start", face) {
|
|
137
|
+
if (face?.custom) return value.lines.map((line, index) => {
|
|
138
|
+
requireGlyphs(line, face);
|
|
139
|
+
const run = face.font.layout(line), scale = value.size / face.font.unitsPerEm;
|
|
140
|
+
const total = run.positions.reduce((sum, position) => sum + position.xAdvance, 0);
|
|
141
|
+
let advance = 0;
|
|
142
|
+
return run.glyphs.map((glyph, position) => {
|
|
143
|
+
const offset = run.positions[position];
|
|
144
|
+
const data = glyph.path.toSVG();
|
|
145
|
+
const translatedX = x + (advance + offset.xOffset - (anchor === "end" ? total : 0)) * scale;
|
|
146
|
+
advance += offset.xAdvance;
|
|
147
|
+
return data ? `<path d="${data}" transform="translate(${translatedX} ${y + index * gap - offset.yOffset * scale}) scale(${scale} ${-scale})" fill="${fill}"/>` : "";
|
|
148
|
+
}).join("");
|
|
149
|
+
}).join("");
|
|
92
150
|
return value.lines.map((line, index) => `<text x="${x}" y="${y + index * gap}" font-family="${family}" font-weight="${weight}" font-size="${value.size}" fill="${fill}" text-anchor="${anchor}">${escapeHtml(line)}</text>`).join("");
|
|
93
151
|
}
|
|
94
152
|
const wave = `<defs><linearGradient id="bg" x2=".2" y2="1"><stop stop-color="#2b4f85"/><stop offset="1" stop-color="#091a3a"/></linearGradient><linearGradient id="ribbon"><stop stop-color="#80afff" stop-opacity=".02"/><stop offset=".5" stop-color="#b7d6ff" stop-opacity=".24"/><stop offset="1" stop-color="#e6f2ff" stop-opacity=".03"/></linearGradient></defs><rect width="1200" height="630" fill="url(#bg)"/><path d="M-80 470C170 270 330 560 630 435S980 290 1280 470" stroke="url(#ribbon)" stroke-width="32" fill="none"/><path d="M-80 495C170 590 370 315 690 465S1020 580 1280 390" stroke="url(#ribbon)" stroke-width="14" fill="none"/>`;
|
|
95
153
|
const cache = /* @__PURE__ */ new Map();
|
|
96
|
-
/** Build-time PNG generation with bundled fonts; no network or system-font search. */
|
|
97
|
-
function renderShareImage(options) {
|
|
154
|
+
/** Build-time PNG generation with bundled or supplied local fonts; no network or system-font search. */
|
|
155
|
+
async function renderShareImage(options) {
|
|
98
156
|
const theme = options.theme ?? "ledger";
|
|
99
157
|
const t = themes[theme];
|
|
100
158
|
if (!t) throw new TypeError("Unknown share image theme");
|
|
101
|
-
|
|
102
|
-
const
|
|
159
|
+
if (options.fonts !== void 0 && (typeof options.fonts !== "object" || options.fonts === null || Array.isArray(options.fonts) || Object.keys(options.fonts).some((key) => !["body", "headline"].includes(key)))) throw new TypeError("fonts must contain only body/headline local font paths");
|
|
160
|
+
const body = options.fonts?.body === void 0 ? null : await loadFace(options.fonts.body, "body");
|
|
161
|
+
const customHeadline = options.fonts?.headline === void 0 ? body : await loadFace(options.fonts.headline, "headline");
|
|
162
|
+
const regular = body?.face ?? {
|
|
163
|
+
font: fonts[theme === "plain" ? 2 : 0],
|
|
164
|
+
custom: false,
|
|
165
|
+
role: "body"
|
|
166
|
+
};
|
|
167
|
+
const headlineFace = customHeadline ? {
|
|
168
|
+
...customHeadline.face,
|
|
169
|
+
role: "headline"
|
|
170
|
+
} : {
|
|
171
|
+
font: fonts[t.face],
|
|
172
|
+
custom: false,
|
|
173
|
+
role: "headline"
|
|
174
|
+
};
|
|
175
|
+
const digest = createHash("sha256").update(JSON.stringify([
|
|
176
|
+
fontDigest,
|
|
177
|
+
body ? createHash("sha256").update(body.bytes).digest("hex") : null,
|
|
178
|
+
customHeadline ? createHash("sha256").update(customHeadline.bytes).digest("hex") : null
|
|
179
|
+
])).digest("hex");
|
|
180
|
+
const headline = fit(options.title, headlineFace, [
|
|
103
181
|
96,
|
|
104
182
|
88,
|
|
105
183
|
80,
|
|
@@ -118,11 +196,11 @@ function renderShareImage(options) {
|
|
|
118
196
|
26
|
|
119
197
|
], 1064, 1);
|
|
120
198
|
const directory = fit(options.directoryPath ? `/${options.directoryPath}/` : "", regular, [24], 1064, 1);
|
|
121
|
-
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630"><rect width="1200" height="630" fill="${t.bg}"/>${theme === "crosswave" ? wave : ""}${text(header, 68, 86, 0, t.fg, t.family)}${text({
|
|
199
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630"><rect width="1200" height="630" fill="${t.bg}"/>${theme === "crosswave" ? wave : ""}${text(header, 68, 86, 0, t.fg, t.family, 400, "start", regular)}${text({
|
|
122
200
|
size: 30,
|
|
123
201
|
lines: [t.name]
|
|
124
|
-
}, 1130, 86, 0, t.fg, t.family, 400, "end")}${theme === "crosswave" ? "" : `<path d="M64 126H1136" stroke="${t.rule}"/>`}${text(headline, 68, 276, 112, t.fg, t.family, t.weight)}${text(description, 68, 480, 0, t.muted, t.family)}${text(directory, 68, 572, 0, t.muted, t.family)}</svg>`;
|
|
125
|
-
const key = createHash("sha256").update(
|
|
202
|
+
}, 1130, 86, 0, t.fg, t.family, 400, "end", regular)}${theme === "crosswave" ? "" : `<path d="M64 126H1136" stroke="${t.rule}"/>`}${text(headline, 68, 276, 112, t.fg, t.family, t.weight, "start", headlineFace)}${text(description, 68, 480, 0, t.muted, t.family, 400, "start", regular)}${text(directory, 68, 572, 0, t.muted, t.family, 400, "start", regular)}</svg>`;
|
|
203
|
+
const key = createHash("sha256").update(digest).update(svg).digest("hex");
|
|
126
204
|
const previous = cache.get(key);
|
|
127
205
|
if (previous) return previous;
|
|
128
206
|
const png = new Resvg(svg, { font: {
|
|
@@ -137,4 +215,4 @@ function renderShareImage(options) {
|
|
|
137
215
|
//#endregion
|
|
138
216
|
export { renderShareImage };
|
|
139
217
|
|
|
140
|
-
//# sourceMappingURL=share-image-
|
|
218
|
+
//# sourceMappingURL=share-image-DPfRwKbZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"share-image-DPfRwKbZ.mjs","names":[],"sources":["../src/share-image.ts"],"sourcesContent":["import { escapeHtml } from \"@dirwell/core\";\nimport { readFile, open } from \"node:fs/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { createHash } from \"node:crypto\";\nimport { create, type Font } from \"fontkit\";\nimport { Resvg } from \"@resvg/resvg-js\";\n\nexport interface ShareImageFonts {\n readonly body?: string | URL;\n readonly headline?: string | URL;\n}\nexport interface ShareImageOptions {\n readonly fonts?: ShareImageFonts;\n readonly theme?: \"ledger\" | \"plain\" | \"crosswave\";\n readonly title: string;\n readonly description: string;\n readonly repositoryName?: string;\n readonly directoryPath?: string;\n}\nconst fontNames = [\n \"SourceSans3-Regular.otf\",\n \"SourceSans3-Light.otf\",\n \"SourceSerif4-Regular.otf\",\n] as const;\nconst buffers = await Promise.all(\n fontNames.map((name) => readFile(new URL(`./fonts/${name}`, import.meta.url))),\n);\nconst fonts = buffers.map((bytes) => create(bytes) as Font);\nconst fontDigest = createHash(\"sha256\").update(Buffer.concat(buffers)).digest(\"hex\");\nconst themes = {\n ledger: {\n name: \"Ledger\",\n face: 0,\n family: \"Source Sans 3\",\n bg: \"#f3f0e8\",\n fg: \"#171815\",\n muted: \"#64655f\",\n rule: \"#c9c5ba\",\n weight: 400,\n },\n plain: {\n name: \"Plain\",\n face: 2,\n family: \"Source Serif 4\",\n bg: \"#ffffff\",\n fg: \"#171815\",\n muted: \"#454545\",\n rule: \"#171815\",\n weight: 400,\n },\n crosswave: {\n name: \"Crosswave\",\n face: 1,\n family: \"Source Sans 3\",\n bg: \"#091a3a\",\n fg: \"#f7fbff\",\n muted: \"#edf4fc\",\n rule: \"#edf4fc\",\n weight: 300,\n },\n} as const;\nconst segmenter = new Intl.Segmenter(\"en\", { granularity: \"grapheme\" });\n\ninterface ImageFace {\n readonly font: Font;\n readonly custom: boolean;\n readonly role: \"body\" | \"headline\";\n}\nasync function loadFace(source: string | URL, role: ImageFace[\"role\"]) {\n if (\n (typeof source !== \"string\" && !(source instanceof URL)) ||\n (typeof source === \"string\" && (!source || /^[a-z][a-z0-9+.-]*:\\/\\//i.test(source))) ||\n (source instanceof URL &&\n (source.protocol !== \"file:\" || (source.hostname && source.hostname !== \"localhost\")))\n )\n throw new TypeError(`fonts.${role} must be a local path or file URL`);\n const handle = await open(source, \"r\").catch((cause: unknown) => {\n throw new TypeError(`Cannot read fonts.${role}`, { cause });\n });\n let bytes: Buffer;\n try {\n const stats = await handle.stat();\n if (!stats.isFile()) throw new TypeError(`fonts.${role} must refer to a regular font file`);\n const size = stats.size;\n if (size < 12) throw new TypeError(`fonts.${role} must contain a valid TTF or OTF header`);\n if (size > 32 * 1024 * 1024) throw new TypeError(`fonts.${role} must be at most 32 MiB`);\n const bounded = Buffer.alloc(size + 1);\n let received = 0;\n while (received < bounded.length) {\n const result = await handle.read(bounded, received, bounded.length - received, null);\n if (!result.bytesRead) break;\n received += result.bytesRead;\n }\n if (received !== size) throw new TypeError(`fonts.${role} changed while being read`);\n bytes = bounded.subarray(0, received);\n } finally {\n await handle.close();\n }\n if (bytes.readUInt32BE(0) !== 0x00010000 && bytes.toString(\"ascii\", 0, 4) !== \"OTTO\")\n throw new TypeError(`fonts.${role} must be a single TTF or OTF font`);\n let font: Font;\n try {\n font = create(bytes) as Font;\n if (\n typeof font.layout !== \"function\" ||\n !Number.isFinite(font.unitsPerEm) ||\n font.unitsPerEm <= 0\n )\n throw new TypeError(\"Invalid font metrics\");\n } catch (cause) {\n throw new TypeError(`Invalid fonts.${role}`, { cause });\n }\n return { face: { font, custom: true, role } satisfies ImageFace, bytes };\n}\nfunction requireGlyphs(value: string, face: ImageFace) {\n for (const character of value) {\n const codePoint = character.codePointAt(0)!;\n if (!face.font.hasGlyphForCodePoint(codePoint))\n throw new Error(\n `${face.custom ? `Share-image ${face.role}` : \"Bundled share-image\"} font lacks U+${codePoint.toString(16).toUpperCase()}; supply a font with glyph coverage or metadata.image: false`,\n );\n }\n}\nfunction width(text: string, face: ImageFace, size: number): number {\n const font = face.font;\n return (\n (font.layout(text).positions.reduce((sum, position) => sum + position.xAdvance, 0) * size) /\n font.unitsPerEm\n );\n}\nfunction fit(\n value: string,\n face: ImageFace,\n sizes: readonly number[],\n limit: number,\n maxLines = 2,\n): { size: number; lines: string[] } {\n if (typeof value !== \"string\") throw new TypeError(\"Share image text must be a string\");\n const text = Array.from(\n segmenter.segment(value.slice(0, 16384).normalize(\"NFC\").replace(/\\s+/g, \" \").trim()),\n (part) => part.segment,\n );\n const bounded = text.slice(0, 2048);\n requireGlyphs(bounded.join(\"\"), face);\n for (const size of sizes) {\n let position = 0;\n const lines: string[] = [];\n while (position < bounded.length && lines.length < maxLines) {\n let low = 0,\n high = bounded.length - position;\n while (low < high) {\n const count = Math.ceil((low + high) / 2);\n if (width(bounded.slice(position, position + count).join(\"\"), face, size) <= limit)\n low = count;\n else high = count - 1;\n }\n const end = position + Math.max(1, low);\n let line = bounded.slice(position, end).join(\"\").trim();\n if (lines.length === maxLines - 1 && (end < text.length || value.length > 16384)) {\n let graphemes = Array.from(segmenter.segment(line), (part) => part.segment);\n while (graphemes.length && width(graphemes.join(\"\") + \"…\", face, size) > limit)\n graphemes.pop();\n line = graphemes.join(\"\") + \"…\";\n requireGlyphs(line, face);\n }\n lines.push(line);\n position = end;\n }\n if (position >= text.length || size === sizes.at(-1)) return { size, lines };\n }\n return { size: 56, lines: [] };\n}\nfunction text(\n value: { size: number; lines: string[] },\n x: number,\n y: number,\n gap: number,\n fill: string,\n family: string,\n weight = 400,\n anchor = \"start\",\n face?: ImageFace,\n): string {\n if (face?.custom)\n return value.lines\n .map((line, index) => {\n requireGlyphs(line, face);\n const run = face.font.layout(line),\n scale = value.size / face.font.unitsPerEm;\n const total = run.positions.reduce((sum, position) => sum + position.xAdvance, 0);\n let advance = 0;\n const paths = run.glyphs\n .map((glyph, position) => {\n const offset = run.positions[position]!;\n const data = glyph.path.toSVG();\n const translatedX =\n x + (advance + offset.xOffset - (anchor === \"end\" ? total : 0)) * scale;\n advance += offset.xAdvance;\n return data\n ? `<path d=\"${data}\" transform=\"translate(${translatedX} ${y + index * gap - offset.yOffset * scale}) scale(${scale} ${-scale})\" fill=\"${fill}\"/>`\n : \"\";\n })\n .join(\"\");\n return paths;\n })\n .join(\"\");\n return value.lines\n .map(\n (line, index) =>\n `<text x=\"${x}\" y=\"${y + index * gap}\" font-family=\"${family}\" font-weight=\"${weight}\" font-size=\"${value.size}\" fill=\"${fill}\" text-anchor=\"${anchor}\">${escapeHtml(line)}</text>`,\n )\n .join(\"\");\n}\nconst wave = `<defs><linearGradient id=\"bg\" x2=\".2\" y2=\"1\"><stop stop-color=\"#2b4f85\"/><stop offset=\"1\" stop-color=\"#091a3a\"/></linearGradient><linearGradient id=\"ribbon\"><stop stop-color=\"#80afff\" stop-opacity=\".02\"/><stop offset=\".5\" stop-color=\"#b7d6ff\" stop-opacity=\".24\"/><stop offset=\"1\" stop-color=\"#e6f2ff\" stop-opacity=\".03\"/></linearGradient></defs><rect width=\"1200\" height=\"630\" fill=\"url(#bg)\"/><path d=\"M-80 470C170 270 330 560 630 435S980 290 1280 470\" stroke=\"url(#ribbon)\" stroke-width=\"32\" fill=\"none\"/><path d=\"M-80 495C170 590 370 315 690 465S1020 580 1280 390\" stroke=\"url(#ribbon)\" stroke-width=\"14\" fill=\"none\"/>`;\nconst cache = new Map<string, File>();\n/** Build-time PNG generation with bundled or supplied local fonts; no network or system-font search. */\nexport async function renderShareImage(options: ShareImageOptions): Promise<File> {\n const theme = options.theme ?? \"ledger\";\n const t = themes[theme];\n if (!t) throw new TypeError(\"Unknown share image theme\");\n if (\n options.fonts !== undefined &&\n (typeof options.fonts !== \"object\" ||\n options.fonts === null ||\n Array.isArray(options.fonts) ||\n Object.keys(options.fonts).some((key) => ![\"body\", \"headline\"].includes(key)))\n )\n throw new TypeError(\"fonts must contain only body/headline local font paths\");\n const body =\n options.fonts?.body === undefined ? null : await loadFace(options.fonts.body, \"body\");\n const customHeadline =\n options.fonts?.headline === undefined\n ? body\n : await loadFace(options.fonts.headline, \"headline\");\n const regular: ImageFace = body?.face ?? {\n font: fonts[theme === \"plain\" ? 2 : 0]!,\n custom: false,\n role: \"body\",\n };\n const headlineFace: ImageFace = customHeadline\n ? { ...customHeadline.face, role: \"headline\" }\n : { font: fonts[t.face]!, custom: false, role: \"headline\" };\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify([\n fontDigest,\n body ? createHash(\"sha256\").update(body.bytes).digest(\"hex\") : null,\n customHeadline ? createHash(\"sha256\").update(customHeadline.bytes).digest(\"hex\") : null,\n ]),\n )\n .digest(\"hex\");\n const headline = fit(options.title, headlineFace, [96, 88, 80, 72, 64, 56], 1064);\n const header = fit(options.repositoryName ?? \"\", regular, [30, 28, 26], 800, 1);\n const description = fit(options.description, regular, [34, 30, 26], 1064, 1);\n const directory = fit(\n options.directoryPath ? `/${options.directoryPath}/` : \"\",\n regular,\n [24],\n 1064,\n 1,\n );\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"630\" viewBox=\"0 0 1200 630\"><rect width=\"1200\" height=\"630\" fill=\"${t.bg}\"/>${theme === \"crosswave\" ? wave : \"\"}${text(header, 68, 86, 0, t.fg, t.family, 400, \"start\", regular)}${text({ size: 30, lines: [t.name] }, 1130, 86, 0, t.fg, t.family, 400, \"end\", regular)}${theme === \"crosswave\" ? \"\" : `<path d=\"M64 126H1136\" stroke=\"${t.rule}\"/>`}${text(headline, 68, 276, 112, t.fg, t.family, t.weight, \"start\", headlineFace)}${text(description, 68, 480, 0, t.muted, t.family, 400, \"start\", regular)}${text(directory, 68, 572, 0, t.muted, t.family, 400, \"start\", regular)}</svg>`;\n const key = createHash(\"sha256\").update(digest).update(svg).digest(\"hex\");\n const previous = cache.get(key);\n if (previous) return previous;\n const png = new Resvg(svg, {\n font: {\n fontFiles: fontNames.map((name) =>\n fileURLToPath(new URL(`./fonts/${name}`, import.meta.url)),\n ),\n loadSystemFonts: false,\n },\n })\n .render()\n .asPng();\n const file = new File([new Uint8Array(png)], `${theme}.png`, { type: \"image/png\" });\n if (cache.size >= 32) cache.delete(cache.keys().next().value!);\n cache.set(key, file);\n return file;\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,YAAY;CAChB;CACA;CACA;AACF;AACA,MAAM,UAAU,MAAM,QAAQ,IAC5B,UAAU,KAAK,SAAS,SAAS,IAAI,IAAI,WAAW,QAAQ,YAAY,GAAG,CAAC,CAAC,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AAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;CAC7D,MAAM,IAAI,KAAK,IAAI;CACnB,OAAO;AACT"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/share-image-api.ts
|
|
2
|
+
/** Render a PNG at build time using the selected preset and bundled or supplied local fonts. */
|
|
3
|
+
async function createShareImage(options) {
|
|
4
|
+
const { renderShareImage } = await import("./share-image-DPfRwKbZ.mjs");
|
|
5
|
+
return renderShareImage(options);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
export { createShareImage as t };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=share-image-api-BIAcrVlH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"share-image-api-BIAcrVlH.mjs","names":[],"sources":["../src/share-image-api.ts"],"sourcesContent":["import type { ShareImageOptions } from \"./share-image.ts\";\nexport type { ShareImageOptions, ShareImageFonts } from \"./share-image.ts\";\n/** Render a PNG at build time using the selected preset and bundled or supplied local fonts. */\nexport async function createShareImage(options: ShareImageOptions): Promise<File> {\n const { renderShareImage } = await import(\"./share-image.ts\");\n return renderShareImage(options);\n}\n"],"mappings":";;AAGA,eAAsB,iBAAiB,SAA2C;CAChF,MAAM,EAAE,qBAAqB,MAAM,OAAO;CAC1C,OAAO,iBAAiB,OAAO;AACjC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dirwell/share-image",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.2",
|
|
4
4
|
"description": "Optional build-time metadata and PNG share-image rendering.",
|
|
5
|
+
"homepage": "https://vp-tw.github.io/dirwell/metadata/",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/vp-tw/dirwell/issues"
|
|
8
|
+
},
|
|
5
9
|
"license": "MIT",
|
|
6
10
|
"repository": {
|
|
7
11
|
"type": "git",
|
|
@@ -24,10 +28,10 @@
|
|
|
24
28
|
"publishConfig": {
|
|
25
29
|
"access": "public",
|
|
26
30
|
"provenance": true,
|
|
27
|
-
"tag": "
|
|
31
|
+
"tag": "latest"
|
|
28
32
|
},
|
|
29
33
|
"dependencies": {
|
|
30
|
-
"@dirwell/core": "0.0.
|
|
34
|
+
"@dirwell/core": "0.0.2",
|
|
31
35
|
"@resvg/resvg-js": "2.6.2",
|
|
32
36
|
"fontkit": "2.0.4"
|
|
33
37
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"share-image-D2N_4dRw.mjs","names":[],"sources":["../src/share-image.ts"],"sourcesContent":["import { escapeHtml } from \"@dirwell/core\";\nimport { readFile } from \"node:fs/promises\";\nimport { fileURLToPath } from \"node:url\";\nimport { createHash } from \"node:crypto\";\nimport { create, type Font } from \"fontkit\";\nimport { Resvg } from \"@resvg/resvg-js\";\n\nexport interface ShareImageOptions {\n readonly theme?: \"ledger\" | \"plain\" | \"crosswave\";\n readonly title: string;\n readonly description: string;\n readonly repositoryName?: string;\n readonly directoryPath?: string;\n}\nconst fontNames = [\n \"SourceSans3-Regular.otf\",\n \"SourceSans3-Light.otf\",\n \"SourceSerif4-Regular.otf\",\n] as const;\nconst buffers = await Promise.all(\n fontNames.map((name) => readFile(new URL(`./fonts/${name}`, import.meta.url))),\n);\nconst fonts = buffers.map((bytes) => create(bytes) as Font);\nconst fontDigest = createHash(\"sha256\").update(Buffer.concat(buffers)).digest(\"hex\");\nconst themes = {\n ledger: {\n name: \"Ledger\",\n face: 0,\n family: \"Source Sans 3\",\n bg: \"#f3f0e8\",\n fg: \"#171815\",\n muted: \"#64655f\",\n rule: \"#c9c5ba\",\n weight: 400,\n },\n plain: {\n name: \"Plain\",\n face: 2,\n family: \"Source Serif 4\",\n bg: \"#ffffff\",\n fg: \"#171815\",\n muted: \"#454545\",\n rule: \"#171815\",\n weight: 400,\n },\n crosswave: {\n name: \"Crosswave\",\n face: 1,\n family: \"Source Sans 3\",\n bg: \"#091a3a\",\n fg: \"#f7fbff\",\n muted: \"#edf4fc\",\n rule: \"#edf4fc\",\n weight: 300,\n },\n} as const;\nconst segmenter = new Intl.Segmenter(\"en\", { granularity: \"grapheme\" });\n\nfunction width(text: string, face: number, size: number): number {\n const font = fonts[face]!;\n return (\n (font.layout(text).positions.reduce((sum, position) => sum + position.xAdvance, 0) * size) /\n font.unitsPerEm\n );\n}\nfunction fit(\n value: string,\n face: number,\n sizes: readonly number[],\n limit: number,\n maxLines = 2,\n): { size: number; lines: string[] } {\n if (typeof value !== \"string\") throw new TypeError(\"Share image text must be a string\");\n const text = Array.from(\n segmenter.segment(value.slice(0, 16384).normalize(\"NFC\").replace(/\\s+/g, \" \").trim()),\n (part) => part.segment,\n );\n const bounded = text.slice(0, 2048);\n for (const character of bounded.join(\"\")) {\n const codePoint = character.codePointAt(0)!;\n if (!fonts[face]!.hasGlyphForCodePoint(codePoint))\n throw new Error(\n `Bundled share-image font lacks U+${codePoint.toString(16).toUpperCase()}; use a custom image renderer or metadata.image: false`,\n );\n }\n for (const size of sizes) {\n let position = 0;\n const lines: string[] = [];\n while (position < bounded.length && lines.length < maxLines) {\n let low = 0,\n high = bounded.length - position;\n while (low < high) {\n const count = Math.ceil((low + high) / 2);\n if (width(bounded.slice(position, position + count).join(\"\"), face, size) <= limit)\n low = count;\n else high = count - 1;\n }\n const end = position + Math.max(1, low);\n let line = bounded.slice(position, end).join(\"\").trim();\n if (lines.length === maxLines - 1 && (end < text.length || value.length > 16384)) {\n let graphemes = Array.from(segmenter.segment(line), (part) => part.segment);\n while (graphemes.length && width(graphemes.join(\"\") + \"…\", face, size) > limit)\n graphemes.pop();\n line = graphemes.join(\"\") + \"…\";\n }\n lines.push(line);\n position = end;\n }\n if (position >= text.length || size === sizes.at(-1)) return { size, lines };\n }\n return { size: 56, lines: [] };\n}\nfunction text(\n value: { size: number; lines: string[] },\n x: number,\n y: number,\n gap: number,\n fill: string,\n family: string,\n weight = 400,\n anchor = \"start\",\n): string {\n return value.lines\n .map(\n (line, index) =>\n `<text x=\"${x}\" y=\"${y + index * gap}\" font-family=\"${family}\" font-weight=\"${weight}\" font-size=\"${value.size}\" fill=\"${fill}\" text-anchor=\"${anchor}\">${escapeHtml(line)}</text>`,\n )\n .join(\"\");\n}\nconst wave = `<defs><linearGradient id=\"bg\" x2=\".2\" y2=\"1\"><stop stop-color=\"#2b4f85\"/><stop offset=\"1\" stop-color=\"#091a3a\"/></linearGradient><linearGradient id=\"ribbon\"><stop stop-color=\"#80afff\" stop-opacity=\".02\"/><stop offset=\".5\" stop-color=\"#b7d6ff\" stop-opacity=\".24\"/><stop offset=\"1\" stop-color=\"#e6f2ff\" stop-opacity=\".03\"/></linearGradient></defs><rect width=\"1200\" height=\"630\" fill=\"url(#bg)\"/><path d=\"M-80 470C170 270 330 560 630 435S980 290 1280 470\" stroke=\"url(#ribbon)\" stroke-width=\"32\" fill=\"none\"/><path d=\"M-80 495C170 590 370 315 690 465S1020 580 1280 390\" stroke=\"url(#ribbon)\" stroke-width=\"14\" fill=\"none\"/>`;\nconst cache = new Map<string, File>();\n/** Build-time PNG generation with bundled fonts; no network or system-font search. */\nexport function renderShareImage(options: ShareImageOptions): File {\n const theme = options.theme ?? \"ledger\";\n const t = themes[theme];\n if (!t) throw new TypeError(\"Unknown share image theme\");\n const regular = theme === \"plain\" ? 2 : 0;\n const headline = fit(options.title, t.face, [96, 88, 80, 72, 64, 56], 1064);\n const header = fit(options.repositoryName ?? \"\", regular, [30, 28, 26], 800, 1);\n const description = fit(options.description, regular, [34, 30, 26], 1064, 1);\n const directory = fit(\n options.directoryPath ? `/${options.directoryPath}/` : \"\",\n regular,\n [24],\n 1064,\n 1,\n );\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"630\" viewBox=\"0 0 1200 630\"><rect width=\"1200\" height=\"630\" fill=\"${t.bg}\"/>${theme === \"crosswave\" ? wave : \"\"}${text(header, 68, 86, 0, t.fg, t.family)}${text({ size: 30, lines: [t.name] }, 1130, 86, 0, t.fg, t.family, 400, \"end\")}${theme === \"crosswave\" ? \"\" : `<path d=\"M64 126H1136\" stroke=\"${t.rule}\"/>`}${text(headline, 68, 276, 112, t.fg, t.family, t.weight)}${text(description, 68, 480, 0, t.muted, t.family)}${text(directory, 68, 572, 0, t.muted, t.family)}</svg>`;\n const key = createHash(\"sha256\").update(fontDigest).update(svg).digest(\"hex\");\n const previous = cache.get(key);\n if (previous) return previous;\n const png = new Resvg(svg, {\n font: {\n fontFiles: fontNames.map((name) =>\n fileURLToPath(new URL(`./fonts/${name}`, import.meta.url)),\n ),\n loadSystemFonts: false,\n },\n })\n .render()\n .asPng();\n const file = new File([new Uint8Array(png)], `${theme}.png`, { type: \"image/png\" });\n if (cache.size >= 32) cache.delete(cache.keys().next().value!);\n cache.set(key, file);\n return file;\n}\n"],"mappings":";;;;;;;AAcA,MAAM,YAAY;CAChB;CACA;CACA;AACF;AACA,MAAM,UAAU,MAAM,QAAQ,IAC5B,UAAU,KAAK,SAAS,SAAS,IAAI,IAAI,WAAW,QAAQ,YAAY,GAAG,CAAC,CAAC,CAC/E;AACA,MAAM,QAAQ,QAAQ,KAAK,UAAU,OAAO,KAAK,CAAS;AAC1D,MAAM,aAAa,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,OAAO,OAAO,CAAC,CAAC,CAAC,OAAO,KAAK;AACnF,MAAM,SAAS;CACb,QAAQ;EACN,MAAM;EACN,MAAM;EACN,QAAQ;EACR,IAAI;EACJ,IAAI;EACJ,OAAO;EACP,MAAM;EACN,QAAQ;CACV;CACA,OAAO;EACL,MAAM;EACN,MAAM;EACN,QAAQ;EACR,IAAI;EACJ,IAAI;EACJ,OAAO;EACP,MAAM;EACN,QAAQ;CACV;CACA,WAAW;EACT,MAAM;EACN,MAAM;EACN,QAAQ;EACR,IAAI;EACJ,IAAI;EACJ,OAAO;EACP,MAAM;EACN,QAAQ;CACV;AACF;AACA,MAAM,YAAY,IAAI,KAAK,UAAU,MAAM,E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B,OAAO;AACT"}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
//#region src/share-image-api.ts
|
|
2
|
-
/** Render a PNG at build time using the selected built-in theme and bundled fonts. */
|
|
3
|
-
async function createShareImage(options) {
|
|
4
|
-
const { renderShareImage } = await import("./share-image-D2N_4dRw.mjs");
|
|
5
|
-
return renderShareImage(options);
|
|
6
|
-
}
|
|
7
|
-
//#endregion
|
|
8
|
-
export { createShareImage as t };
|
|
9
|
-
|
|
10
|
-
//# sourceMappingURL=share-image-api-DcmMcWT0.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"share-image-api-DcmMcWT0.mjs","names":[],"sources":["../src/share-image-api.ts"],"sourcesContent":["import type { ShareImageOptions } from \"./share-image.ts\";\nexport type { ShareImageOptions } from \"./share-image.ts\";\n/** Render a PNG at build time using the selected built-in theme and bundled fonts. */\nexport async function createShareImage(options: ShareImageOptions): Promise<File> {\n const { renderShareImage } = await import(\"./share-image.ts\");\n return renderShareImage(options);\n}\n"],"mappings":";;AAGA,eAAsB,iBAAiB,SAA2C;CAChF,MAAM,EAAE,qBAAqB,MAAM,OAAO;CAC1C,OAAO,iBAAiB,OAAO;AACjC"}
|