@ox-content/vite-plugin 2.16.0 → 2.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/migrate-vitepress.mjs +27 -0
- package/dist/index.cjs +371 -367
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -4
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +29 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +371 -367
- package/dist/index.mjs.map +1 -1
- package/dist/mermaid.cjs +19 -48
- package/dist/mermaid.cjs.map +1 -1
- package/dist/mermaid.mjs +2 -109
- package/dist/mermaid2.mjs +92 -2
- package/dist/mermaid2.mjs.map +1 -0
- package/dist/napi.cjs +45 -0
- package/dist/napi.cjs.map +1 -0
- package/dist/napi.mjs +34 -0
- package/dist/napi.mjs.map +1 -0
- package/dist/ogp.cjs +1 -1
- package/dist/ogp.cjs.map +1 -1
- package/dist/ogp2.mjs +1 -1
- package/dist/ogp2.mjs.map +1 -1
- package/dist/tabs.cjs +14 -154
- package/dist/tabs.cjs.map +1 -1
- package/dist/tabs2.mjs +14 -152
- package/dist/tabs2.mjs.map +1 -1
- package/dist/vitepress-cli.cjs +1 -1
- package/dist/vitepress-cli.mjs +1 -1
- package/dist/vitepress.cjs +2 -26
- package/dist/vitepress.cjs.map +1 -1
- package/dist/vitepress.mjs +2 -26
- package/dist/vitepress.mjs.map +1 -1
- package/dist/youtube.cjs +10 -89
- package/dist/youtube.cjs.map +1 -1
- package/dist/youtube2.mjs +10 -87
- package/dist/youtube2.mjs.map +1 -1
- package/package.json +5 -4
- package/dist/mermaid.mjs.map +0 -1
package/dist/mermaid.cjs
CHANGED
|
@@ -1,38 +1,8 @@
|
|
|
1
1
|
const require_chunk = require("./chunk.cjs");
|
|
2
|
+
const require_napi = require("./napi.cjs");
|
|
2
3
|
let node_module = require("node:module");
|
|
3
4
|
let node_fs = require("node:fs");
|
|
4
5
|
let node_path = require("node:path");
|
|
5
|
-
let node_url = require("node:url");
|
|
6
|
-
//#region src/napi.ts
|
|
7
|
-
const requireNapi = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
8
|
-
function getDefaultExport(value) {
|
|
9
|
-
if (!value || typeof value !== "object" || !("default" in value)) return;
|
|
10
|
-
const defaultExport = value.default;
|
|
11
|
-
return defaultExport && typeof defaultExport === "object" ? defaultExport : void 0;
|
|
12
|
-
}
|
|
13
|
-
function normalizeNapiModule(mod) {
|
|
14
|
-
const defaultExport = getDefaultExport(mod);
|
|
15
|
-
return defaultExport ? {
|
|
16
|
-
...defaultExport,
|
|
17
|
-
...mod
|
|
18
|
-
} : mod;
|
|
19
|
-
}
|
|
20
|
-
async function importNapiModule() {
|
|
21
|
-
return normalizeNapiModule(await import("@ox-content/napi"));
|
|
22
|
-
}
|
|
23
|
-
let syncNapiModule;
|
|
24
|
-
function importNapiModuleSync() {
|
|
25
|
-
if (syncNapiModule) return syncNapiModule;
|
|
26
|
-
if (syncNapiModule === null) throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
27
|
-
try {
|
|
28
|
-
syncNapiModule = normalizeNapiModule(requireNapi("@ox-content/napi"));
|
|
29
|
-
return syncNapiModule;
|
|
30
|
-
} catch {
|
|
31
|
-
syncNapiModule = null;
|
|
32
|
-
throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
//#endregion
|
|
36
6
|
//#region src/plugins/mermaid.ts
|
|
37
7
|
/**
|
|
38
8
|
* Mermaid Plugin - Native Rust renderer via NAPI
|
|
@@ -52,7 +22,7 @@ async function loadNapi() {
|
|
|
52
22
|
if (napiLoadAttempted) return napiBindings;
|
|
53
23
|
napiLoadAttempted = true;
|
|
54
24
|
try {
|
|
55
|
-
const binding = await importNapiModule();
|
|
25
|
+
const binding = await require_napi.importNapiModule();
|
|
56
26
|
if (typeof binding.transformMermaid !== "function") {
|
|
57
27
|
napiBindings = null;
|
|
58
28
|
return null;
|
|
@@ -65,11 +35,11 @@ async function loadNapi() {
|
|
|
65
35
|
}
|
|
66
36
|
}
|
|
67
37
|
let cachedMmdcPath;
|
|
38
|
+
let missingMmdcWarned = false;
|
|
68
39
|
function resolveMmdcPath() {
|
|
69
40
|
if (cachedMmdcPath !== void 0) return cachedMmdcPath;
|
|
70
|
-
try {
|
|
71
|
-
const
|
|
72
|
-
const cliPath = (0, node_url.fileURLToPath)(new URL("./cli.js", entry));
|
|
41
|
+
for (const resolver of createMmdcResolvers()) try {
|
|
42
|
+
const cliPath = (0, node_path.join)((0, node_path.dirname)(resolver.resolve("@mermaid-js/mermaid-cli")), "cli.js");
|
|
73
43
|
if ((0, node_fs.existsSync)(cliPath)) {
|
|
74
44
|
cachedMmdcPath = cliPath;
|
|
75
45
|
return cachedMmdcPath;
|
|
@@ -83,6 +53,14 @@ function resolveMmdcPath() {
|
|
|
83
53
|
cachedMmdcPath = null;
|
|
84
54
|
return null;
|
|
85
55
|
}
|
|
56
|
+
function createMmdcResolvers() {
|
|
57
|
+
const consumerRequire = (0, node_module.createRequire)((0, node_path.join)(process.cwd(), "noop.js"));
|
|
58
|
+
const resolvers = [consumerRequire];
|
|
59
|
+
try {
|
|
60
|
+
resolvers.push((0, node_module.createRequire)(consumerRequire.resolve("@ox-content/vite-plugin")));
|
|
61
|
+
} catch {}
|
|
62
|
+
return resolvers;
|
|
63
|
+
}
|
|
86
64
|
/**
|
|
87
65
|
* Transforms mermaid code blocks in HTML to rendered SVG diagrams.
|
|
88
66
|
* Uses the native Rust NAPI transformMermaid function.
|
|
@@ -92,7 +70,7 @@ async function transformMermaidStatic(html, _options) {
|
|
|
92
70
|
if (!napi) return html;
|
|
93
71
|
const mmdcPath = resolveMmdcPath();
|
|
94
72
|
if (!mmdcPath) {
|
|
95
|
-
|
|
73
|
+
warnMissingMmdcOnce();
|
|
96
74
|
return html;
|
|
97
75
|
}
|
|
98
76
|
try {
|
|
@@ -104,23 +82,16 @@ async function transformMermaidStatic(html, _options) {
|
|
|
104
82
|
return html;
|
|
105
83
|
}
|
|
106
84
|
}
|
|
85
|
+
function warnMissingMmdcOnce() {
|
|
86
|
+
if (missingMmdcWarned) return;
|
|
87
|
+
missingMmdcWarned = true;
|
|
88
|
+
console.warn("[ox-content] mmdc not found; skipping Mermaid rendering.");
|
|
89
|
+
}
|
|
107
90
|
/**
|
|
108
91
|
* @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.
|
|
109
92
|
*/
|
|
110
93
|
const mermaidClientScript = "";
|
|
111
94
|
//#endregion
|
|
112
|
-
Object.defineProperty(exports, "importNapiModule", {
|
|
113
|
-
enumerable: true,
|
|
114
|
-
get: function() {
|
|
115
|
-
return importNapiModule;
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
Object.defineProperty(exports, "importNapiModuleSync", {
|
|
119
|
-
enumerable: true,
|
|
120
|
-
get: function() {
|
|
121
|
-
return importNapiModuleSync;
|
|
122
|
-
}
|
|
123
|
-
});
|
|
124
95
|
Object.defineProperty(exports, "mermaidClientScript", {
|
|
125
96
|
enumerable: true,
|
|
126
97
|
get: function() {
|
package/dist/mermaid.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mermaid.cjs","names":[],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"mermaid.cjs","names":["importNapiModule"],"sources":["../src/plugins/mermaid.ts"],"sourcesContent":["/**\n * Mermaid Plugin - Native Rust renderer via NAPI\n *\n * Renders mermaid code blocks to SVG using the native Rust renderer\n * via NAPI. Delegates to the NAPI `transformMermaid` function which\n * extracts mermaid code blocks from HTML and renders them using mmdc.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { importNapiModule } from \"../napi\";\n\nexport interface MermaidOptions {\n /** Mermaid theme. Default: \"neutral\" */\n theme?: \"default\" | \"dark\" | \"forest\" | \"neutral\" | \"base\";\n}\n\n/** Cached NAPI bindings */\nlet napiBindings: {\n transformMermaid: (html: string, mmdcPath: string) => { html: string; errors: string[] };\n} | null = null;\n\nlet napiLoadAttempted = false;\n\nasync function loadNapi() {\n if (napiLoadAttempted) return napiBindings;\n napiLoadAttempted = true;\n try {\n const binding = (await importNapiModule()) as unknown as NonNullable<typeof napiBindings>;\n if (typeof binding.transformMermaid !== \"function\") {\n napiBindings = null;\n return null;\n }\n napiBindings = binding;\n return binding;\n } catch {\n napiBindings = null;\n return null;\n }\n}\n\nlet cachedMmdcPath: string | null | undefined;\nlet missingMmdcWarned = false;\n\nfunction resolveMmdcPath(): string | null {\n if (cachedMmdcPath !== undefined) return cachedMmdcPath;\n\n for (const resolver of createMmdcResolvers()) {\n try {\n const entry = resolver.resolve(\"@mermaid-js/mermaid-cli\");\n const cliPath = join(dirname(entry), \"cli.js\");\n if (existsSync(cliPath)) {\n cachedMmdcPath = cliPath;\n return cachedMmdcPath;\n }\n } catch {\n // Try the next resolver.\n }\n }\n\n // Fallback: node_modules/.bin/mmdc relative to cwd\n const binPath = join(process.cwd(), \"node_modules\", \".bin\", \"mmdc\");\n if (existsSync(binPath)) {\n cachedMmdcPath = binPath;\n return cachedMmdcPath;\n }\n\n cachedMmdcPath = null;\n return null;\n}\n\nfunction createMmdcResolvers(): NodeJS.Require[] {\n // Resolve from the consumer first, then from this package. The second lookup\n // matters under pnpm strict linking: docs apps can depend on the plugin\n // without directly depending on mermaid-cli.\n const consumerRequire = createRequire(join(process.cwd(), \"noop.js\"));\n const resolvers = [consumerRequire];\n\n try {\n resolvers.push(createRequire(consumerRequire.resolve(\"@ox-content/vite-plugin\")));\n } catch {\n // If the package is used from source without its package name resolvable,\n // the consumer resolver and bin fallback still cover direct installs.\n }\n\n return resolvers;\n}\n\n/**\n * Transforms mermaid code blocks in HTML to rendered SVG diagrams.\n * Uses the native Rust NAPI transformMermaid function.\n */\nexport async function transformMermaidStatic(\n html: string,\n _options?: MermaidOptions,\n): Promise<string> {\n const napi = await loadNapi();\n if (!napi) {\n return html;\n }\n\n const mmdcPath = resolveMmdcPath();\n if (!mmdcPath) {\n warnMissingMmdcOnce();\n return html;\n }\n\n try {\n const result = napi.transformMermaid(html, mmdcPath);\n for (const error of result.errors) {\n console.warn(\"[ox-content] Mermaid render error:\", error);\n }\n return result.html;\n } catch (err) {\n console.warn(\"[ox-content] Mermaid transform error:\", err);\n return html;\n }\n}\n\nfunction warnMissingMmdcOnce(): void {\n if (missingMmdcWarned) {\n return;\n }\n\n missingMmdcWarned = true;\n console.warn(\"[ox-content] mmdc not found; skipping Mermaid rendering.\");\n}\n\n/**\n * @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.\n */\nexport const mermaidClientScript = \"\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,IAAI,eAEO;AAEX,IAAI,oBAAoB;AAExB,eAAe,WAAW;CACxB,IAAI,mBAAmB,OAAO;CAC9B,oBAAoB;CACpB,IAAI;EACF,MAAM,UAAW,MAAMA,aAAAA,kBAAkB;EACzC,IAAI,OAAO,QAAQ,qBAAqB,YAAY;GAClD,eAAe;GACf,OAAO;;EAET,eAAe;EACf,OAAO;SACD;EACN,eAAe;EACf,OAAO;;;AAIX,IAAI;AACJ,IAAI,oBAAoB;AAExB,SAAS,kBAAiC;CACxC,IAAI,mBAAmB,KAAA,GAAW,OAAO;CAEzC,KAAK,MAAM,YAAY,qBAAqB,EAC1C,IAAI;EAEF,MAAM,WAAA,GAAA,UAAA,OAAA,GAAA,UAAA,SADQ,SAAS,QAAQ,0BACG,CAAC,EAAE,SAAS;EAC9C,KAAA,GAAA,QAAA,YAAe,QAAQ,EAAE;GACvB,iBAAiB;GACjB,OAAO;;SAEH;CAMV,MAAM,WAAA,GAAA,UAAA,MAAe,QAAQ,KAAK,EAAE,gBAAgB,QAAQ,OAAO;CACnE,KAAA,GAAA,QAAA,YAAe,QAAQ,EAAE;EACvB,iBAAiB;EACjB,OAAO;;CAGT,iBAAiB;CACjB,OAAO;;AAGT,SAAS,sBAAwC;CAI/C,MAAM,mBAAA,GAAA,YAAA,gBAAA,GAAA,UAAA,MAAqC,QAAQ,KAAK,EAAE,UAAU,CAAC;CACrE,MAAM,YAAY,CAAC,gBAAgB;CAEnC,IAAI;EACF,UAAU,MAAA,GAAA,YAAA,eAAmB,gBAAgB,QAAQ,0BAA0B,CAAC,CAAC;SAC3E;CAKR,OAAO;;;;;;AAOT,eAAsB,uBACpB,MACA,UACiB;CACjB,MAAM,OAAO,MAAM,UAAU;CAC7B,IAAI,CAAC,MACH,OAAO;CAGT,MAAM,WAAW,iBAAiB;CAClC,IAAI,CAAC,UAAU;EACb,qBAAqB;EACrB,OAAO;;CAGT,IAAI;EACF,MAAM,SAAS,KAAK,iBAAiB,MAAM,SAAS;EACpD,KAAK,MAAM,SAAS,OAAO,QACzB,QAAQ,KAAK,sCAAsC,MAAM;EAE3D,OAAO,OAAO;UACP,KAAK;EACZ,QAAQ,KAAK,yCAAyC,IAAI;EAC1D,OAAO;;;AAIX,SAAS,sBAA4B;CACnC,IAAI,mBACF;CAGF,oBAAoB;CACpB,QAAQ,KAAK,2DAA2D;;;;;AAM1E,MAAa,sBAAsB"}
|
package/dist/mermaid.mjs
CHANGED
|
@@ -1,109 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
5
|
-
//#region src/napi.ts
|
|
6
|
-
const requireNapi = createRequire(import.meta.url);
|
|
7
|
-
function getDefaultExport(value) {
|
|
8
|
-
if (!value || typeof value !== "object" || !("default" in value)) return;
|
|
9
|
-
const defaultExport = value.default;
|
|
10
|
-
return defaultExport && typeof defaultExport === "object" ? defaultExport : void 0;
|
|
11
|
-
}
|
|
12
|
-
function normalizeNapiModule(mod) {
|
|
13
|
-
const defaultExport = getDefaultExport(mod);
|
|
14
|
-
return defaultExport ? {
|
|
15
|
-
...defaultExport,
|
|
16
|
-
...mod
|
|
17
|
-
} : mod;
|
|
18
|
-
}
|
|
19
|
-
async function importNapiModule() {
|
|
20
|
-
return normalizeNapiModule(await import("@ox-content/napi"));
|
|
21
|
-
}
|
|
22
|
-
let syncNapiModule;
|
|
23
|
-
function importNapiModuleSync() {
|
|
24
|
-
if (syncNapiModule) return syncNapiModule;
|
|
25
|
-
if (syncNapiModule === null) throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
26
|
-
try {
|
|
27
|
-
syncNapiModule = normalizeNapiModule(requireNapi("@ox-content/napi"));
|
|
28
|
-
return syncNapiModule;
|
|
29
|
-
} catch {
|
|
30
|
-
syncNapiModule = null;
|
|
31
|
-
throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
//#endregion
|
|
35
|
-
//#region src/plugins/mermaid.ts
|
|
36
|
-
/**
|
|
37
|
-
* Mermaid Plugin - Native Rust renderer via NAPI
|
|
38
|
-
*
|
|
39
|
-
* Renders mermaid code blocks to SVG using the native Rust renderer
|
|
40
|
-
* via NAPI. Delegates to the NAPI `transformMermaid` function which
|
|
41
|
-
* extracts mermaid code blocks from HTML and renders them using mmdc.
|
|
42
|
-
*/
|
|
43
|
-
/** Cached NAPI bindings */
|
|
44
|
-
let napiBindings = null;
|
|
45
|
-
let napiLoadAttempted = false;
|
|
46
|
-
async function loadNapi() {
|
|
47
|
-
if (napiLoadAttempted) return napiBindings;
|
|
48
|
-
napiLoadAttempted = true;
|
|
49
|
-
try {
|
|
50
|
-
const binding = await importNapiModule();
|
|
51
|
-
if (typeof binding.transformMermaid !== "function") {
|
|
52
|
-
napiBindings = null;
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
napiBindings = binding;
|
|
56
|
-
return binding;
|
|
57
|
-
} catch {
|
|
58
|
-
napiBindings = null;
|
|
59
|
-
return null;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
let cachedMmdcPath;
|
|
63
|
-
function resolveMmdcPath() {
|
|
64
|
-
if (cachedMmdcPath !== void 0) return cachedMmdcPath;
|
|
65
|
-
try {
|
|
66
|
-
const entry = import.meta.resolve("@mermaid-js/mermaid-cli");
|
|
67
|
-
const cliPath = fileURLToPath(new URL("./cli.js", entry));
|
|
68
|
-
if (existsSync(cliPath)) {
|
|
69
|
-
cachedMmdcPath = cliPath;
|
|
70
|
-
return cachedMmdcPath;
|
|
71
|
-
}
|
|
72
|
-
} catch {}
|
|
73
|
-
const binPath = join(process.cwd(), "node_modules", ".bin", "mmdc");
|
|
74
|
-
if (existsSync(binPath)) {
|
|
75
|
-
cachedMmdcPath = binPath;
|
|
76
|
-
return cachedMmdcPath;
|
|
77
|
-
}
|
|
78
|
-
cachedMmdcPath = null;
|
|
79
|
-
return null;
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Transforms mermaid code blocks in HTML to rendered SVG diagrams.
|
|
83
|
-
* Uses the native Rust NAPI transformMermaid function.
|
|
84
|
-
*/
|
|
85
|
-
async function transformMermaidStatic(html, _options) {
|
|
86
|
-
const napi = await loadNapi();
|
|
87
|
-
if (!napi) return html;
|
|
88
|
-
const mmdcPath = resolveMmdcPath();
|
|
89
|
-
if (!mmdcPath) {
|
|
90
|
-
console.warn("[ox-content] mmdc not found, skipping mermaid rendering");
|
|
91
|
-
return html;
|
|
92
|
-
}
|
|
93
|
-
try {
|
|
94
|
-
const result = napi.transformMermaid(html, mmdcPath);
|
|
95
|
-
for (const error of result.errors) console.warn("[ox-content] Mermaid render error:", error);
|
|
96
|
-
return result.html;
|
|
97
|
-
} catch (err) {
|
|
98
|
-
console.warn("[ox-content] Mermaid transform error:", err);
|
|
99
|
-
return html;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
/**
|
|
103
|
-
* @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.
|
|
104
|
-
*/
|
|
105
|
-
const mermaidClientScript = "";
|
|
106
|
-
//#endregion
|
|
107
|
-
export { importNapiModuleSync as i, transformMermaidStatic as n, importNapiModule as r, mermaidClientScript as t };
|
|
108
|
-
|
|
109
|
-
//# sourceMappingURL=mermaid.mjs.map
|
|
1
|
+
import { n as transformMermaidStatic } from "./mermaid2.mjs";
|
|
2
|
+
export { transformMermaidStatic };
|
package/dist/mermaid2.mjs
CHANGED
|
@@ -1,2 +1,92 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { t as importNapiModule } from "./napi.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
//#region src/plugins/mermaid.ts
|
|
6
|
+
/**
|
|
7
|
+
* Mermaid Plugin - Native Rust renderer via NAPI
|
|
8
|
+
*
|
|
9
|
+
* Renders mermaid code blocks to SVG using the native Rust renderer
|
|
10
|
+
* via NAPI. Delegates to the NAPI `transformMermaid` function which
|
|
11
|
+
* extracts mermaid code blocks from HTML and renders them using mmdc.
|
|
12
|
+
*/
|
|
13
|
+
/** Cached NAPI bindings */
|
|
14
|
+
let napiBindings = null;
|
|
15
|
+
let napiLoadAttempted = false;
|
|
16
|
+
async function loadNapi() {
|
|
17
|
+
if (napiLoadAttempted) return napiBindings;
|
|
18
|
+
napiLoadAttempted = true;
|
|
19
|
+
try {
|
|
20
|
+
const binding = await importNapiModule();
|
|
21
|
+
if (typeof binding.transformMermaid !== "function") {
|
|
22
|
+
napiBindings = null;
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
napiBindings = binding;
|
|
26
|
+
return binding;
|
|
27
|
+
} catch {
|
|
28
|
+
napiBindings = null;
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
let cachedMmdcPath;
|
|
33
|
+
let missingMmdcWarned = false;
|
|
34
|
+
function resolveMmdcPath() {
|
|
35
|
+
if (cachedMmdcPath !== void 0) return cachedMmdcPath;
|
|
36
|
+
for (const resolver of createMmdcResolvers()) try {
|
|
37
|
+
const cliPath = join(dirname(resolver.resolve("@mermaid-js/mermaid-cli")), "cli.js");
|
|
38
|
+
if (existsSync(cliPath)) {
|
|
39
|
+
cachedMmdcPath = cliPath;
|
|
40
|
+
return cachedMmdcPath;
|
|
41
|
+
}
|
|
42
|
+
} catch {}
|
|
43
|
+
const binPath = join(process.cwd(), "node_modules", ".bin", "mmdc");
|
|
44
|
+
if (existsSync(binPath)) {
|
|
45
|
+
cachedMmdcPath = binPath;
|
|
46
|
+
return cachedMmdcPath;
|
|
47
|
+
}
|
|
48
|
+
cachedMmdcPath = null;
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
function createMmdcResolvers() {
|
|
52
|
+
const consumerRequire = createRequire(join(process.cwd(), "noop.js"));
|
|
53
|
+
const resolvers = [consumerRequire];
|
|
54
|
+
try {
|
|
55
|
+
resolvers.push(createRequire(consumerRequire.resolve("@ox-content/vite-plugin")));
|
|
56
|
+
} catch {}
|
|
57
|
+
return resolvers;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Transforms mermaid code blocks in HTML to rendered SVG diagrams.
|
|
61
|
+
* Uses the native Rust NAPI transformMermaid function.
|
|
62
|
+
*/
|
|
63
|
+
async function transformMermaidStatic(html, _options) {
|
|
64
|
+
const napi = await loadNapi();
|
|
65
|
+
if (!napi) return html;
|
|
66
|
+
const mmdcPath = resolveMmdcPath();
|
|
67
|
+
if (!mmdcPath) {
|
|
68
|
+
warnMissingMmdcOnce();
|
|
69
|
+
return html;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const result = napi.transformMermaid(html, mmdcPath);
|
|
73
|
+
for (const error of result.errors) console.warn("[ox-content] Mermaid render error:", error);
|
|
74
|
+
return result.html;
|
|
75
|
+
} catch (err) {
|
|
76
|
+
console.warn("[ox-content] Mermaid transform error:", err);
|
|
77
|
+
return html;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function warnMissingMmdcOnce() {
|
|
81
|
+
if (missingMmdcWarned) return;
|
|
82
|
+
missingMmdcWarned = true;
|
|
83
|
+
console.warn("[ox-content] mmdc not found; skipping Mermaid rendering.");
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.
|
|
87
|
+
*/
|
|
88
|
+
const mermaidClientScript = "";
|
|
89
|
+
//#endregion
|
|
90
|
+
export { transformMermaidStatic as n, mermaidClientScript as t };
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=mermaid2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mermaid2.mjs","names":[],"sources":["../src/plugins/mermaid.ts"],"sourcesContent":["/**\n * Mermaid Plugin - Native Rust renderer via NAPI\n *\n * Renders mermaid code blocks to SVG using the native Rust renderer\n * via NAPI. Delegates to the NAPI `transformMermaid` function which\n * extracts mermaid code blocks from HTML and renders them using mmdc.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { importNapiModule } from \"../napi\";\n\nexport interface MermaidOptions {\n /** Mermaid theme. Default: \"neutral\" */\n theme?: \"default\" | \"dark\" | \"forest\" | \"neutral\" | \"base\";\n}\n\n/** Cached NAPI bindings */\nlet napiBindings: {\n transformMermaid: (html: string, mmdcPath: string) => { html: string; errors: string[] };\n} | null = null;\n\nlet napiLoadAttempted = false;\n\nasync function loadNapi() {\n if (napiLoadAttempted) return napiBindings;\n napiLoadAttempted = true;\n try {\n const binding = (await importNapiModule()) as unknown as NonNullable<typeof napiBindings>;\n if (typeof binding.transformMermaid !== \"function\") {\n napiBindings = null;\n return null;\n }\n napiBindings = binding;\n return binding;\n } catch {\n napiBindings = null;\n return null;\n }\n}\n\nlet cachedMmdcPath: string | null | undefined;\nlet missingMmdcWarned = false;\n\nfunction resolveMmdcPath(): string | null {\n if (cachedMmdcPath !== undefined) return cachedMmdcPath;\n\n for (const resolver of createMmdcResolvers()) {\n try {\n const entry = resolver.resolve(\"@mermaid-js/mermaid-cli\");\n const cliPath = join(dirname(entry), \"cli.js\");\n if (existsSync(cliPath)) {\n cachedMmdcPath = cliPath;\n return cachedMmdcPath;\n }\n } catch {\n // Try the next resolver.\n }\n }\n\n // Fallback: node_modules/.bin/mmdc relative to cwd\n const binPath = join(process.cwd(), \"node_modules\", \".bin\", \"mmdc\");\n if (existsSync(binPath)) {\n cachedMmdcPath = binPath;\n return cachedMmdcPath;\n }\n\n cachedMmdcPath = null;\n return null;\n}\n\nfunction createMmdcResolvers(): NodeJS.Require[] {\n // Resolve from the consumer first, then from this package. The second lookup\n // matters under pnpm strict linking: docs apps can depend on the plugin\n // without directly depending on mermaid-cli.\n const consumerRequire = createRequire(join(process.cwd(), \"noop.js\"));\n const resolvers = [consumerRequire];\n\n try {\n resolvers.push(createRequire(consumerRequire.resolve(\"@ox-content/vite-plugin\")));\n } catch {\n // If the package is used from source without its package name resolvable,\n // the consumer resolver and bin fallback still cover direct installs.\n }\n\n return resolvers;\n}\n\n/**\n * Transforms mermaid code blocks in HTML to rendered SVG diagrams.\n * Uses the native Rust NAPI transformMermaid function.\n */\nexport async function transformMermaidStatic(\n html: string,\n _options?: MermaidOptions,\n): Promise<string> {\n const napi = await loadNapi();\n if (!napi) {\n return html;\n }\n\n const mmdcPath = resolveMmdcPath();\n if (!mmdcPath) {\n warnMissingMmdcOnce();\n return html;\n }\n\n try {\n const result = napi.transformMermaid(html, mmdcPath);\n for (const error of result.errors) {\n console.warn(\"[ox-content] Mermaid render error:\", error);\n }\n return result.html;\n } catch (err) {\n console.warn(\"[ox-content] Mermaid transform error:\", err);\n return html;\n }\n}\n\nfunction warnMissingMmdcOnce(): void {\n if (missingMmdcWarned) {\n return;\n }\n\n missingMmdcWarned = true;\n console.warn(\"[ox-content] mmdc not found; skipping Mermaid rendering.\");\n}\n\n/**\n * @deprecated No longer used. Mermaid rendering is now done at build time via NAPI.\n */\nexport const mermaidClientScript = \"\";\n"],"mapp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ACZ,QAAQ,KAAK,yCAAyC,IAAI;EAC1D,OAAO;;;AAIX,SAAS,sBAA4B;CACnC,IAAI,mBACF;CAGF,oBAAoB;CACpB,QAAQ,KAAK,2DAA2D;;;;;AAM1E,MAAa,sBAAsB"}
|
package/dist/napi.cjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
require("./chunk.cjs");
|
|
2
|
+
//#region src/napi.ts
|
|
3
|
+
const requireNapi = (0, require("node:module").createRequire)(require("url").pathToFileURL(__filename).href);
|
|
4
|
+
function getDefaultExport(value) {
|
|
5
|
+
if (!value || typeof value !== "object" || !("default" in value)) return;
|
|
6
|
+
const defaultExport = value.default;
|
|
7
|
+
return defaultExport && typeof defaultExport === "object" ? defaultExport : void 0;
|
|
8
|
+
}
|
|
9
|
+
function normalizeNapiModule(mod) {
|
|
10
|
+
const defaultExport = getDefaultExport(mod);
|
|
11
|
+
return defaultExport ? {
|
|
12
|
+
...defaultExport,
|
|
13
|
+
...mod
|
|
14
|
+
} : mod;
|
|
15
|
+
}
|
|
16
|
+
async function importNapiModule() {
|
|
17
|
+
return normalizeNapiModule(await import("@ox-content/napi"));
|
|
18
|
+
}
|
|
19
|
+
let syncNapiModule;
|
|
20
|
+
function importNapiModuleSync() {
|
|
21
|
+
if (syncNapiModule) return syncNapiModule;
|
|
22
|
+
if (syncNapiModule === null) throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
23
|
+
try {
|
|
24
|
+
syncNapiModule = normalizeNapiModule(requireNapi("@ox-content/napi"));
|
|
25
|
+
return syncNapiModule;
|
|
26
|
+
} catch {
|
|
27
|
+
syncNapiModule = null;
|
|
28
|
+
throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
Object.defineProperty(exports, "importNapiModule", {
|
|
33
|
+
enumerable: true,
|
|
34
|
+
get: function() {
|
|
35
|
+
return importNapiModule;
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
Object.defineProperty(exports, "importNapiModuleSync", {
|
|
39
|
+
enumerable: true,
|
|
40
|
+
get: function() {
|
|
41
|
+
return importNapiModuleSync;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=napi.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"napi.cjs","names":[],"sources":["../src/napi.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\ntype NapiModule = typeof import(\"@ox-content/napi\");\nconst requireNapi = createRequire(import.meta.url);\n\nfunction getDefaultExport(value: unknown): object | undefined {\n if (!value || typeof value !== \"object\" || !(\"default\" in value)) {\n return undefined;\n }\n\n const defaultExport = value.default;\n return defaultExport && typeof defaultExport === \"object\" ? defaultExport : undefined;\n}\n\nfunction normalizeNapiModule(mod: NapiModule): NapiModule {\n const defaultExport = getDefaultExport(mod);\n return defaultExport\n ? ({\n ...defaultExport,\n ...mod,\n } as NapiModule)\n : mod;\n}\n\nexport async function importNapiModule(): Promise<NapiModule> {\n return normalizeNapiModule((await import(\"@ox-content/napi\")) as NapiModule);\n}\n\nlet syncNapiModule: NapiModule | null | undefined;\n\nexport function importNapiModuleSync(): NapiModule {\n if (syncNapiModule) {\n return syncNapiModule;\n }\n\n if (syncNapiModule === null) {\n throw new Error(\n \"[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.\",\n );\n }\n\n try {\n const mod = requireNapi(\"@ox-content/napi\") as NapiModule;\n syncNapiModule = normalizeNapiModule(mod);\n return syncNapiModule;\n } catch {\n syncNapiModule = null;\n throw new Error(\n \"[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.\",\n );\n }\n}\n"],"mappings":";;AAGA,MAAM,eAAA,yBAAA,CAAA,eAAA,QAAA,MAAA,CAAA,cAAA,WAAA,CAAA,KAA4C;AAElD,SAAS,iBAAiB,OAAoC;CAC5D,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,EAAE,aAAa,QACxD;CAGF,MAAM,gBAAgB,MAAM;CAC5B,OAAO,iBAAiB,OAAO,kBAAkB,WAAW,gBAAgB,KAAA;;AAG9E,SAAS,oBAAoB,KAA6B;CACxD,MAAM,gBAAgB,iBAAiB,IAAI;CAC3C,OAAO,gBACF;EACC,GAAG;EACH,GAAG;EACJ,GACD;;AAGN,eAAsB,mBAAwC;CAC5D,OAAO,oBAAqB,MAAM,OAAO,oBAAmC;;AAG9E,IAAI;AAEJ,SAAgB,uBAAmC;CACjD,IAAI,gBACF,OAAO;CAGT,IAAI,mBAAmB,MACrB,MAAM,IAAI,MACR,qFACD;CAGH,IAAI;EAEF,iBAAiB,oBADL,YAAY,mBACgB,CAAC;EACzC,OAAO;SACD;EACN,iBAAiB;EACjB,MAAM,IAAI,MACR,qFACD"}
|
package/dist/napi.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
//#region src/napi.ts
|
|
3
|
+
const requireNapi = createRequire(import.meta.url);
|
|
4
|
+
function getDefaultExport(value) {
|
|
5
|
+
if (!value || typeof value !== "object" || !("default" in value)) return;
|
|
6
|
+
const defaultExport = value.default;
|
|
7
|
+
return defaultExport && typeof defaultExport === "object" ? defaultExport : void 0;
|
|
8
|
+
}
|
|
9
|
+
function normalizeNapiModule(mod) {
|
|
10
|
+
const defaultExport = getDefaultExport(mod);
|
|
11
|
+
return defaultExport ? {
|
|
12
|
+
...defaultExport,
|
|
13
|
+
...mod
|
|
14
|
+
} : mod;
|
|
15
|
+
}
|
|
16
|
+
async function importNapiModule() {
|
|
17
|
+
return normalizeNapiModule(await import("@ox-content/napi"));
|
|
18
|
+
}
|
|
19
|
+
let syncNapiModule;
|
|
20
|
+
function importNapiModuleSync() {
|
|
21
|
+
if (syncNapiModule) return syncNapiModule;
|
|
22
|
+
if (syncNapiModule === null) throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
23
|
+
try {
|
|
24
|
+
syncNapiModule = normalizeNapiModule(requireNapi("@ox-content/napi"));
|
|
25
|
+
return syncNapiModule;
|
|
26
|
+
} catch {
|
|
27
|
+
syncNapiModule = null;
|
|
28
|
+
throw new Error("[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { importNapiModuleSync as n, importNapiModule as t };
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=napi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"napi.mjs","names":[],"sources":["../src/napi.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\ntype NapiModule = typeof import(\"@ox-content/napi\");\nconst requireNapi = createRequire(import.meta.url);\n\nfunction getDefaultExport(value: unknown): object | undefined {\n if (!value || typeof value !== \"object\" || !(\"default\" in value)) {\n return undefined;\n }\n\n const defaultExport = value.default;\n return defaultExport && typeof defaultExport === \"object\" ? defaultExport : undefined;\n}\n\nfunction normalizeNapiModule(mod: NapiModule): NapiModule {\n const defaultExport = getDefaultExport(mod);\n return defaultExport\n ? ({\n ...defaultExport,\n ...mod,\n } as NapiModule)\n : mod;\n}\n\nexport async function importNapiModule(): Promise<NapiModule> {\n return normalizeNapiModule((await import(\"@ox-content/napi\")) as NapiModule);\n}\n\nlet syncNapiModule: NapiModule | null | undefined;\n\nexport function importNapiModuleSync(): NapiModule {\n if (syncNapiModule) {\n return syncNapiModule;\n }\n\n if (syncNapiModule === null) {\n throw new Error(\n \"[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.\",\n );\n }\n\n try {\n const mod = requireNapi(\"@ox-content/napi\") as NapiModule;\n syncNapiModule = normalizeNapiModule(mod);\n return syncNapiModule;\n } catch {\n syncNapiModule = null;\n throw new Error(\n \"[ox-content] @ox-content/napi is required. Please ensure the NAPI module is built.\",\n );\n }\n}\n"],"mappings":";;AAGA,MAAM,cAAc,cAAc,OAAO,KAAK,IAAI;AAElD,SAAS,iBAAiB,OAAoC;CAC5D,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,EAAE,aAAa,QACxD;CAGF,MAAM,gBAAgB,MAAM;CAC5B,OAAO,iBAAiB,OAAO,kBAAkB,WAAW,gBAAgB,KAAA;;AAG9E,SAAS,oBAAoB,KAA6B;CACxD,MAAM,gBAAgB,iBAAiB,IAAI;CAC3C,OAAO,gBACF;EACC,GAAG;EACH,GAAG;EACJ,GACD;;AAGN,eAAsB,mBAAwC;CAC5D,OAAO,oBAAqB,MAAM,OAAO,oBAAmC;;AAG9E,IAAI;AAEJ,SAAgB,uBAAmC;CACjD,IAAI,gBACF,OAAO;CAGT,IAAI,mBAAmB,MACrB,MAAM,IAAI,MACR,qFACD;CAGH,IAAI;EAEF,iBAAiB,oBADL,YAAY,mBACgB,CAAC;EACzC,OAAO;SACD;EACN,iBAAiB;EACjB,MAAM,IAAI,MACR,qFACD"}
|
package/dist/ogp.cjs
CHANGED
|
@@ -22,7 +22,7 @@ const defaultOptions = {
|
|
|
22
22
|
timeout: 1e4,
|
|
23
23
|
cache: true,
|
|
24
24
|
cacheTTL: 36e5,
|
|
25
|
-
userAgent: "ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei/ox-content)"
|
|
25
|
+
userAgent: "ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)"
|
|
26
26
|
};
|
|
27
27
|
const ogpCache = /* @__PURE__ */ new Map();
|
|
28
28
|
function isPrivateIPv4(hostname) {
|
package/dist/ogp.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ogp.cjs","names":["rehypeParse","rehypeStringify"],"sources":["../src/plugins/ogp.ts"],"sourcesContent":["/**\n * OGP Card Plugin - Link card embedding\n *\n * Transforms <OgCard> components into static link preview cards\n * by fetching OGP metadata at build time.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParse from \"rehype-parse\";\nimport rehypeStringify from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\n\nexport interface OgpData {\n url: string;\n title: string;\n description?: string;\n image?: string;\n siteName?: string;\n favicon?: string;\n}\n\nexport interface OgpOptions {\n /** Request timeout in milliseconds. Default: 10000 */\n timeout?: number;\n /** Cache fetched data. Default: true */\n cache?: boolean;\n /** Cache TTL in milliseconds. Default: 3600000 (1 hour) */\n cacheTTL?: number;\n /** User agent for requests */\n userAgent?: string;\n}\n\nconst defaultOptions: Required<OgpOptions> = {\n timeout: 10000,\n cache: true,\n cacheTTL: 3600000,\n userAgent: \"ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei/ox-content)\",\n};\n\n// Simple in-memory cache\nconst ogpCache = new Map<string, { data: OgpData; timestamp: number }>();\n\nfunction isPrivateIPv4(hostname: string): boolean {\n const parts = hostname.split(\".\").map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n const [a, b] = parts;\n return (\n a === 10 ||\n a === 127 ||\n a === 0 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 169 && b === 254)\n );\n}\n\nexport function isSafeOgpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n const host = url.hostname.toLowerCase();\n const ipv6 = host.replace(/^\\[|\\]$/g, \"\");\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return false;\n if (\n ipv6.includes(\":\") &&\n (ipv6 === \"::1\" || ipv6.startsWith(\"fc\") || ipv6.startsWith(\"fd\") || ipv6.startsWith(\"fe80\"))\n )\n return false;\n return !isPrivateIPv4(host);\n } catch {\n return false;\n }\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Extract domain from URL.\n */\nfunction extractDomain(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.hostname;\n } catch {\n return url;\n }\n}\n\n/**\n * Get favicon URL for a domain.\n */\nfunction getFaviconUrl(url: string): string {\n try {\n const urlObj = new URL(url);\n // Use Google's favicon service as fallback\n return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Parse OGP metadata from HTML.\n */\nfunction parseOgpFromHtml(html: string, url: string): OgpData {\n const result: OgpData = {\n url,\n title: \"\",\n };\n\n // Extract title\n const titleMatch = html.match(/<title[^>]*>([^<]+)<\\/title>/i);\n const ogTitleMatch =\n html.match(/<meta[^>]*property=[\"']og:title[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:title[\"']/i);\n\n result.title = ogTitleMatch?.[1] || titleMatch?.[1] || extractDomain(url);\n\n // Extract description\n const descMatch =\n html.match(/<meta[^>]*property=[\"']og:description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:description[\"']/i) ||\n html.match(/<meta[^>]*name=[\"']description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*name=[\"']description[\"']/i);\n\n if (descMatch) {\n result.description = descMatch[1];\n }\n\n // Extract image\n const imageMatch =\n html.match(/<meta[^>]*property=[\"']og:image[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:image[\"']/i);\n\n if (imageMatch) {\n let imageUrl = imageMatch[1];\n // Handle relative URLs\n if (imageUrl.startsWith(\"/\")) {\n try {\n const urlObj = new URL(url);\n imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;\n } catch {\n // Keep as is\n }\n }\n result.image = imageUrl;\n }\n\n // Extract site name\n const siteNameMatch =\n html.match(/<meta[^>]*property=[\"']og:site_name[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:site_name[\"']/i);\n\n if (siteNameMatch) {\n result.siteName = siteNameMatch[1];\n }\n\n // Get favicon\n result.favicon = getFaviconUrl(url);\n\n return result;\n}\n\n/**\n * Fetch OGP data for a URL.\n */\nexport async function fetchOgpData(\n url: string,\n options: Required<OgpOptions>,\n): Promise<OgpData | null> {\n if (!isSafeOgpUrl(url)) {\n return null;\n }\n\n // Check cache\n if (options.cache) {\n const cached = ogpCache.get(url);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n const response = await fetch(url, {\n headers: {\n \"User-Agent\": options.userAgent,\n Accept: \"text/html,application/xhtml+xml\",\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`Failed to fetch OGP for ${url}: ${response.status}`);\n return null;\n }\n\n const html = await response.text();\n const data = parseOgpFromHtml(html, url);\n\n // Cache the result\n if (options.cache) {\n ogpCache.set(url, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n console.warn(`Timeout fetching OGP for ${url}`);\n } else {\n console.warn(`Error fetching OGP for ${url}:`, error);\n }\n return null;\n }\n}\n\n/**\n * Create OGP card element.\n */\nfunction createOgpCard(data: OgpData): Element {\n const children: Element[\"children\"] = [];\n\n // Content section\n const contentChildren: Element[\"children\"] = [];\n\n // Title\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-title\"] },\n children: [{ type: \"text\", value: data.title }],\n });\n\n // Description\n if (data.description) {\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-description\"] },\n children: [{ type: \"text\", value: data.description }],\n });\n }\n\n // Meta (favicon + domain)\n const metaChildren: Element[\"children\"] = [];\n\n if (data.favicon) {\n metaChildren.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-favicon\"],\n src: data.favicon,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n metaChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-ogp-domain\"] },\n children: [{ type: \"text\", value: data.siteName || extractDomain(data.url) }],\n });\n\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-meta\"] },\n children: metaChildren,\n });\n\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-content\"] },\n children: contentChildren,\n });\n\n // Image\n if (data.image) {\n children.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-image\"],\n src: data.image,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-card\"],\n href: isSafeOgpUrl(data.url) ? data.url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children,\n };\n}\n\n/**\n * Create fallback element when OGP data is unavailable.\n */\nfunction createFallbackCard(url: string): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-simple\"],\n href: isSafeOgpUrl(url) ? url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n \"stroke-width\": \"2\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3\",\n },\n children: [],\n },\n ],\n },\n { type: \"text\", value: extractDomain(url) },\n ],\n };\n}\n\n/**\n * Collect all OGP URLs from HTML for pre-fetching.\n */\nexport async function collectOgpUrls(html: string): Promise<string[]> {\n const urls: string[] = [];\n const urlPattern = /<ogcard[^>]*\\s+url=[\"']([^\"']+)[\"']/gi;\n\n let match;\n while ((match = urlPattern.exec(html)) !== null) {\n if (isSafeOgpUrl(match[1])) {\n urls.push(match[1]);\n }\n }\n\n return urls;\n}\n\n/**\n * Pre-fetch all OGP data.\n */\nexport async function prefetchOgpData(\n urls: string[],\n options?: OgpOptions,\n): Promise<Map<string, OgpData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, OgpData | null>();\n\n await Promise.all(\n urls.map(async (url) => {\n const data = await fetchOgpData(url, mergedOptions);\n results.set(url, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Rehype plugin to transform OgCard components.\n */\nfunction rehypeOgp(ogpDataMap: Map<string, OgpData | null>) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <OgCard> component\n if (child.tagName.toLowerCase() === \"ogcard\") {\n const url = getAttribute(child, \"url\");\n\n if (url) {\n const ogpData = ogpDataMap.get(url);\n const cardElement = ogpData ? createOgpCard(ogpData) : createFallbackCard(url);\n node.children[i] = cardElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform OgCard components in HTML.\n */\nexport async function transformOgp(\n html: string,\n ogpDataMap?: Map<string, OgpData | null>,\n options?: OgpOptions,\n): Promise<string> {\n // If no pre-fetched data, collect and fetch\n let dataMap = ogpDataMap;\n if (!dataMap) {\n const urls = await collectOgpUrls(html);\n dataMap = await prefetchOgpData(urls, options);\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeOgp, dataMap)\n .use(rehypeStringify)\n .process(html);\n\n return String(result);\n}\n"],"mappings":";;;;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sC;CACtC,MAAM,gBAAgB;EAAE,GAAG;EAAgB,GAAG;EAAS;CACvD,MAAM,0BAAU,IAAI,KAA6B;CAEjD,MAAM,QAAQ,IACZ,KAAK,IAAI,OAAO,QAAQ;EACtB,MAAM,OAAO,MAAM,aAAa,KAAK,cAAc;EACnD,QAAQ,IAAI,KAAK,KAAK;GACtB,CACH;CAED,OAAO;;;;;AAMT,SAAS,UAAU,YAAyC;CAC1D,QAAQ,SAAe;EACrB,MAAM,SAAS,SAAyB;GACtC,IAAI,cAAc,MAChB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,KAAK;IAC7C,MAAM,QAAQ,KAAK,SAAS;IAE5B,IAAI,MAAM,SAAS,WAEjB,IAAI,MAAM,QAAQ,aAAa,KAAK,UAAU;KAC5C,MAAM,MAAM,aAAa,OAAO,MAAM;KAEtC,IAAI,KAAK;MACP,MAAM,UAAU,WAAW,IAAI,IAAI;MACnC,MAAM,cAAc,UAAU,cAAc,QAAQ,GAAG,mBAAmB,IAAI;MAC9E,KAAK,SAAS,KAAK;;WAGrB,MAAM,MAAM;;;EAOtB,MAAM,KAAK;;;;;;AAOf,eAAsB,aACpB,MACA,YACA,SACiB;CAEjB,IAAI,UAAU;CACd,IAAI,CAAC,SAEH,UAAU,MAAM,gBAAgB,MADb,eAAe,KAAK,EACD,QAAQ;CAGhD,MAAM,SAAS,OAAA,GAAA,QAAA,UAAe,CAC3B,IAAIA,aAAAA,SAAa,EAAE,UAAU,MAAM,CAAC,CACpC,IAAI,WAAW,QAAQ,CACvB,IAAIC,iBAAAA,QAAgB,CACpB,QAAQ,KAAK;CAEhB,OAAO,OAAO,OAAO"}
|
|
1
|
+
{"version":3,"file":"ogp.cjs","names":["rehypeParse","rehypeStringify"],"sources":["../src/plugins/ogp.ts"],"sourcesContent":["/**\n * OGP Card Plugin - Link card embedding\n *\n * Transforms <OgCard> components into static link preview cards\n * by fetching OGP metadata at build time.\n */\n\nimport { unified } from \"unified\";\nimport rehypeParse from \"rehype-parse\";\nimport rehypeStringify from \"rehype-stringify\";\nimport type { Root, Element } from \"hast\";\n\nexport interface OgpData {\n url: string;\n title: string;\n description?: string;\n image?: string;\n siteName?: string;\n favicon?: string;\n}\n\nexport interface OgpOptions {\n /** Request timeout in milliseconds. Default: 10000 */\n timeout?: number;\n /** Cache fetched data. Default: true */\n cache?: boolean;\n /** Cache TTL in milliseconds. Default: 3600000 (1 hour) */\n cacheTTL?: number;\n /** User agent for requests */\n userAgent?: string;\n}\n\nconst defaultOptions: Required<OgpOptions> = {\n timeout: 10000,\n cache: true,\n cacheTTL: 3600000,\n userAgent: \"ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)\",\n};\n\n// Simple in-memory cache\nconst ogpCache = new Map<string, { data: OgpData; timestamp: number }>();\n\nfunction isPrivateIPv4(hostname: string): boolean {\n const parts = hostname.split(\".\").map(Number);\n if (\n parts.length !== 4 ||\n parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n ) {\n return false;\n }\n const [a, b] = parts;\n return (\n a === 10 ||\n a === 127 ||\n a === 0 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 169 && b === 254)\n );\n}\n\nexport function isSafeOgpUrl(value: string): boolean {\n try {\n const url = new URL(value);\n const host = url.hostname.toLowerCase();\n const ipv6 = host.replace(/^\\[|\\]$/g, \"\");\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n if (host === \"localhost\" || host.endsWith(\".localhost\")) return false;\n if (\n ipv6.includes(\":\") &&\n (ipv6 === \"::1\" || ipv6.startsWith(\"fc\") || ipv6.startsWith(\"fd\") || ipv6.startsWith(\"fe80\"))\n )\n return false;\n return !isPrivateIPv4(host);\n } catch {\n return false;\n }\n}\n\n/**\n * Get element attribute value.\n */\nfunction getAttribute(el: Element, name: string): string | undefined {\n const value = el.properties?.[name];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) return value.join(\" \");\n return undefined;\n}\n\n/**\n * Extract domain from URL.\n */\nfunction extractDomain(url: string): string {\n try {\n const urlObj = new URL(url);\n return urlObj.hostname;\n } catch {\n return url;\n }\n}\n\n/**\n * Get favicon URL for a domain.\n */\nfunction getFaviconUrl(url: string): string {\n try {\n const urlObj = new URL(url);\n // Use Google's favicon service as fallback\n return `https://www.google.com/s2/favicons?domain=${urlObj.hostname}&sz=32`;\n } catch {\n return \"\";\n }\n}\n\n/**\n * Parse OGP metadata from HTML.\n */\nfunction parseOgpFromHtml(html: string, url: string): OgpData {\n const result: OgpData = {\n url,\n title: \"\",\n };\n\n // Extract title\n const titleMatch = html.match(/<title[^>]*>([^<]+)<\\/title>/i);\n const ogTitleMatch =\n html.match(/<meta[^>]*property=[\"']og:title[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:title[\"']/i);\n\n result.title = ogTitleMatch?.[1] || titleMatch?.[1] || extractDomain(url);\n\n // Extract description\n const descMatch =\n html.match(/<meta[^>]*property=[\"']og:description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:description[\"']/i) ||\n html.match(/<meta[^>]*name=[\"']description[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*name=[\"']description[\"']/i);\n\n if (descMatch) {\n result.description = descMatch[1];\n }\n\n // Extract image\n const imageMatch =\n html.match(/<meta[^>]*property=[\"']og:image[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:image[\"']/i);\n\n if (imageMatch) {\n let imageUrl = imageMatch[1];\n // Handle relative URLs\n if (imageUrl.startsWith(\"/\")) {\n try {\n const urlObj = new URL(url);\n imageUrl = `${urlObj.protocol}//${urlObj.host}${imageUrl}`;\n } catch {\n // Keep as is\n }\n }\n result.image = imageUrl;\n }\n\n // Extract site name\n const siteNameMatch =\n html.match(/<meta[^>]*property=[\"']og:site_name[\"'][^>]*content=[\"']([^\"']+)[\"']/i) ||\n html.match(/<meta[^>]*content=[\"']([^\"']+)[\"'][^>]*property=[\"']og:site_name[\"']/i);\n\n if (siteNameMatch) {\n result.siteName = siteNameMatch[1];\n }\n\n // Get favicon\n result.favicon = getFaviconUrl(url);\n\n return result;\n}\n\n/**\n * Fetch OGP data for a URL.\n */\nexport async function fetchOgpData(\n url: string,\n options: Required<OgpOptions>,\n): Promise<OgpData | null> {\n if (!isSafeOgpUrl(url)) {\n return null;\n }\n\n // Check cache\n if (options.cache) {\n const cached = ogpCache.get(url);\n if (cached && Date.now() - cached.timestamp < options.cacheTTL) {\n return cached.data;\n }\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n\n const response = await fetch(url, {\n headers: {\n \"User-Agent\": options.userAgent,\n Accept: \"text/html,application/xhtml+xml\",\n },\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n console.warn(`Failed to fetch OGP for ${url}: ${response.status}`);\n return null;\n }\n\n const html = await response.text();\n const data = parseOgpFromHtml(html, url);\n\n // Cache the result\n if (options.cache) {\n ogpCache.set(url, { data, timestamp: Date.now() });\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n console.warn(`Timeout fetching OGP for ${url}`);\n } else {\n console.warn(`Error fetching OGP for ${url}:`, error);\n }\n return null;\n }\n}\n\n/**\n * Create OGP card element.\n */\nfunction createOgpCard(data: OgpData): Element {\n const children: Element[\"children\"] = [];\n\n // Content section\n const contentChildren: Element[\"children\"] = [];\n\n // Title\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-title\"] },\n children: [{ type: \"text\", value: data.title }],\n });\n\n // Description\n if (data.description) {\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-description\"] },\n children: [{ type: \"text\", value: data.description }],\n });\n }\n\n // Meta (favicon + domain)\n const metaChildren: Element[\"children\"] = [];\n\n if (data.favicon) {\n metaChildren.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-favicon\"],\n src: data.favicon,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n metaChildren.push({\n type: \"element\",\n tagName: \"span\",\n properties: { className: [\"ox-ogp-domain\"] },\n children: [{ type: \"text\", value: data.siteName || extractDomain(data.url) }],\n });\n\n contentChildren.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-meta\"] },\n children: metaChildren,\n });\n\n children.push({\n type: \"element\",\n tagName: \"div\",\n properties: { className: [\"ox-ogp-content\"] },\n children: contentChildren,\n });\n\n // Image\n if (data.image) {\n children.push({\n type: \"element\",\n tagName: \"img\",\n properties: {\n className: [\"ox-ogp-image\"],\n src: data.image,\n alt: \"\",\n loading: \"lazy\",\n },\n children: [],\n });\n }\n\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-card\"],\n href: isSafeOgpUrl(data.url) ? data.url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children,\n };\n}\n\n/**\n * Create fallback element when OGP data is unavailable.\n */\nfunction createFallbackCard(url: string): Element {\n return {\n type: \"element\",\n tagName: \"a\",\n properties: {\n className: [\"ox-ogp-simple\"],\n href: isSafeOgpUrl(url) ? url : \"#\",\n target: \"_blank\",\n rel: \"noopener noreferrer\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"svg\",\n properties: {\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n stroke: \"currentColor\",\n \"stroke-width\": \"2\",\n },\n children: [\n {\n type: \"element\",\n tagName: \"path\",\n properties: {\n d: \"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14L21 3\",\n },\n children: [],\n },\n ],\n },\n { type: \"text\", value: extractDomain(url) },\n ],\n };\n}\n\n/**\n * Collect all OGP URLs from HTML for pre-fetching.\n */\nexport async function collectOgpUrls(html: string): Promise<string[]> {\n const urls: string[] = [];\n const urlPattern = /<ogcard[^>]*\\s+url=[\"']([^\"']+)[\"']/gi;\n\n let match;\n while ((match = urlPattern.exec(html)) !== null) {\n if (isSafeOgpUrl(match[1])) {\n urls.push(match[1]);\n }\n }\n\n return urls;\n}\n\n/**\n * Pre-fetch all OGP data.\n */\nexport async function prefetchOgpData(\n urls: string[],\n options?: OgpOptions,\n): Promise<Map<string, OgpData | null>> {\n const mergedOptions = { ...defaultOptions, ...options };\n const results = new Map<string, OgpData | null>();\n\n await Promise.all(\n urls.map(async (url) => {\n const data = await fetchOgpData(url, mergedOptions);\n results.set(url, data);\n }),\n );\n\n return results;\n}\n\n/**\n * Rehype plugin to transform OgCard components.\n */\nfunction rehypeOgp(ogpDataMap: Map<string, OgpData | null>) {\n return (tree: Root) => {\n const visit = (node: Root | Element) => {\n if (\"children\" in node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n\n if (child.type === \"element\") {\n // Check for <OgCard> component\n if (child.tagName.toLowerCase() === \"ogcard\") {\n const url = getAttribute(child, \"url\");\n\n if (url) {\n const ogpData = ogpDataMap.get(url);\n const cardElement = ogpData ? createOgpCard(ogpData) : createFallbackCard(url);\n node.children[i] = cardElement;\n }\n } else {\n visit(child);\n }\n }\n }\n }\n };\n\n visit(tree);\n };\n}\n\n/**\n * Transform OgCard components in HTML.\n */\nexport async function transformOgp(\n html: string,\n ogpDataMap?: Map<string, OgpData | null>,\n options?: OgpOptions,\n): Promise<string> {\n // If no pre-fetched data, collect and fetch\n let dataMap = ogpDataMap;\n if (!dataMap) {\n const urls = await collectOgpUrls(html);\n dataMap = await prefetchOgpData(urls, options);\n }\n\n const result = await unified()\n .use(rehypeParse, { fragment: true })\n .use(rehypeOgp, dataMap)\n .use(rehypeSt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ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei/ox-content)"
|
|
15
|
+
userAgent: "ox-content-ogp-bot/1.0 (compatible; +https://github.com/ubugeeei-prod/ox-content)"
|
|
16
16
|
};
|
|
17
17
|
const ogpCache = /* @__PURE__ */ new Map();
|
|
18
18
|
function isPrivateIPv4(hostname) {
|