@pathmx/embed 0.6.4

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/LICENSE.md ADDED
@@ -0,0 +1,172 @@
1
+ # PathMX Proprietary Beta License
2
+
3
+ Version 0.1 — July 21, 2026
4
+
5
+ Copyright © 2026 DUO Interactive, LLC.
6
+ All rights reserved.
7
+
8
+ This license governs the first-party PathMX software distributed in the npm
9
+ package `@pathmx/core`, including its command-line interface, bundled
10
+ library surfaces, runtime and Player components, and accompanying
11
+ documentation (the “Software”). DUO Interactive, LLC is the “Licensor.” This
12
+ license does not cover the private PathMX source-code repository or separately
13
+ identified third-party materials.
14
+
15
+ “Project” means Paths, Sources, responses, data, and other content authored or
16
+ processed with the Software.
17
+
18
+ “Application” means software or a service created by you in which the Software
19
+ supports product-specific functionality but is not itself offered as a
20
+ general-purpose PathMX product.
21
+
22
+ “Redistributable Components” means runtime, Player, or library portions of the
23
+ Software incorporated into a Project, Application, or generated output through
24
+ ordinary use of the Software or ordinary compilation and bundling tools.
25
+
26
+ “Authorized Users” means your employees and individual contractors who use the
27
+ Software on your behalf, and your hosting, continuous-integration, and other
28
+ service providers that possess or run necessary copies solely to provide
29
+ services to you.
30
+
31
+ ## 1. Agreement
32
+
33
+ By installing, accessing, or using the Software, you agree to this license. If
34
+ you use the Software on behalf of an organization, you represent that you have
35
+ authority to accept this license for that organization. If you do not agree,
36
+ do not install or use the Software.
37
+
38
+ ## 2. License grant
39
+
40
+ Subject to this license, the Licensor grants you a non-exclusive, worldwide,
41
+ royalty-free, non-transferable, and non-sublicensable license, perpetual for
42
+ the version of the Software to which it applies unless terminated under
43
+ Section 10, to:
44
+
45
+ - install, execute, and use the Software for personal, educational,
46
+ internal-business, or commercial purposes;
47
+ - use the Software to author, integrate, build, test, serve, play, host, and
48
+ operate Projects and Applications;
49
+ - import, compile, bundle, configure, and integrate the Software through its
50
+ documented library and command-line interfaces;
51
+ - create and distribute independent Projects, Applications, plugins, and
52
+ integrations that use those interfaces without modifying the Software
53
+ itself; and
54
+ - make copies reasonably necessary for local development, testing, continuous
55
+ integration, backup, and hosted production environments.
56
+
57
+ Your Authorized Users may exercise those rights solely on your behalf. You are
58
+ responsible for their compliance with this license.
59
+
60
+ You may reproduce and distribute Redistributable Components only as
61
+ incorporated into your Project, Application, or generated output, and only when
62
+ you preserve applicable license and proprietary notices. You may host and
63
+ commercially provide access to that Project, Application, or output. You may
64
+ not distribute Redistributable Components as a standalone package or as a
65
+ general-purpose substitute for the Software.
66
+
67
+ Each lawful recipient of a Redistributable Component may execute and use that
68
+ component, display its output, and make technically necessary transitory copies
69
+ solely as incorporated into the Project, Application, or output in which they
70
+ received it. This limited recipient permission does not include a right to
71
+ extract, modify, or redistribute the component separately.
72
+
73
+ ## 3. Restrictions
74
+
75
+ Except where applicable law does not allow the restriction, you may not:
76
+
77
+ - modify, adapt, translate, or create derivative works of the Software, except
78
+ for the compilation, bundling, configuration, and integration expressly
79
+ permitted in Section 2;
80
+ - redistribute, sublicense, sell, lease, or otherwise provide the Software to
81
+ another person as a standalone package, product, or service except to an
82
+ Authorized User or as a Redistributable Component under Section 2;
83
+ - resell, rebrand, or provide the Software as a hosted or managed service that
84
+ gives third parties general-purpose access to substantial PathMX authoring,
85
+ building, serving, Player-administration, or library functionality for their
86
+ own unrelated projects;
87
+ - reverse engineer, decompile, disassemble, or otherwise attempt to derive the
88
+ source code of the Software; or
89
+ - remove or alter copyright, license, trademark, or other proprietary notices.
90
+
91
+ For clarity, the managed-service restriction does not prohibit a hosted
92
+ Project or Application in which PathMX supports the licensee's own
93
+ product-specific experience and is not itself the general-purpose product
94
+ offered to customers.
95
+
96
+ ## 4. Your content
97
+
98
+ As between you and the Licensor, you retain ownership of the Paths, Sources,
99
+ responses, data, independent application code, and other content that you
100
+ author or provide while using the Software. You are responsible for that
101
+ content and for having the rights needed to use it.
102
+
103
+ Generated output may contain Redistributable Components or third-party
104
+ materials. Your ownership of your content does not change the ownership or
105
+ license terms of those components and materials.
106
+
107
+ ## 5. Ownership and trademarks
108
+
109
+ The Software is licensed, not sold. The Licensor and its suppliers retain all
110
+ rights in the Software not expressly granted by this license. This license
111
+ does not grant permission to use the PathMX name, logos, or other marks except
112
+ as reasonably necessary to identify the Software accurately.
113
+
114
+ ## 6. Beta status and changes
115
+
116
+ The Software is a proprietary beta release. Its APIs, behavior, file formats,
117
+ and features may change or be removed without notice. The Licensor has no
118
+ obligation to provide support, maintenance, updates, continued availability,
119
+ or backward compatibility. A later version may be offered under different
120
+ license terms, including an open-source license. Different terms for a later
121
+ version do not change the license previously granted for an earlier version.
122
+
123
+ ## 7. Third-party materials
124
+
125
+ The Software and Redistributable Components may include or depend on
126
+ third-party materials governed by their own license terms. Those terms control
127
+ for the applicable third-party materials. You must preserve third-party notices
128
+ when the applicable third-party terms require it.
129
+
130
+ ## 8. Disclaimer of warranties
131
+
132
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED “AS IS” AND
133
+ “AS AVAILABLE,” WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EXPRESS,
134
+ IMPLIED, OR STATUTORY, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
135
+ PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THAT THE SOFTWARE WILL BE
136
+ SECURE, ERROR-FREE, OR UNINTERRUPTED.
137
+
138
+ ## 9. Limitation of liability
139
+
140
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE LICENSOR AND ITS CONTRIBUTORS,
141
+ SUPPLIERS, AND AFFILIATES WILL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
142
+ SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOSS OF DATA,
143
+ PROFITS, REVENUE, GOODWILL, OR BUSINESS OPPORTUNITY, ARISING FROM OR RELATED TO
144
+ THE SOFTWARE OR THIS LICENSE, EVEN IF ADVISED OF THE POSSIBILITY OF THOSE
145
+ DAMAGES.
146
+
147
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, THEIR TOTAL LIABILITY FOR ALL CLAIMS
148
+ ARISING FROM OR RELATED TO THE SOFTWARE OR THIS LICENSE WILL NOT EXCEED THE
149
+ GREATER OF THE AMOUNT YOU PAID FOR THE SOFTWARE DURING THE TWELVE MONTHS BEFORE
150
+ THE EVENT GIVING RISE TO THE CLAIM OR US$100.
151
+
152
+ ## 10. Termination
153
+
154
+ This license terminates if you materially breach it and do not cure the breach
155
+ within thirty days after receiving written notice from the Licensor. On
156
+ termination, you and your Authorized Users must stop using and delete your
157
+ copies of the Software. Sections 4, 5, 8, 9, 10, and 11 survive termination.
158
+ Termination does not withdraw the limited permission already granted by
159
+ Section 2 to lawful recipients of Redistributable Components distributed
160
+ before termination.
161
+
162
+ ## 11. General
163
+
164
+ If a provision of this license is unenforceable, it will be modified only to
165
+ the minimum extent necessary to make it enforceable, and the remaining
166
+ provisions will continue in effect. Failure to enforce a provision is not a
167
+ waiver. You may not assign or transfer this license without the Licensor's
168
+ written consent. The Licensor may assign this license together with ownership
169
+ of the Software to a successor owner. This license binds and benefits the
170
+ permitted successors and assigns of you and the Licensor. This license is the
171
+ entire agreement concerning the Software unless you and the Licensor have
172
+ signed a separate agreement that expressly replaces it.
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # @pathmx/embed
2
+
3
+ Embed an X post, YouTube video, or rich preview of another public web page.
4
+
5
+ ```sh
6
+ bun run pmx plugins add embed
7
+ ```
8
+
9
+ Add a titled link to a Source:
10
+
11
+ ```md
12
+ [@embed A post](https://x.com/example/status/123)
13
+
14
+ [@embed A video](https://www.youtube.com/watch?v=M7lc1UVf-VE)
15
+
16
+ [@embed An article](https://example.com/article)
17
+ ```
18
+
19
+ See the [Embed reference](https://docs.pathmx.dev/docs/authoring/embed.reference).
package/browser/x.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { mountPathMXBehavior } from "@pathmx/core/controls/browser"
2
+
3
+ declare global {
4
+ interface Window {
5
+ twttr?: { widgets?: { load(root?: HTMLElement): Promise<unknown> } }
6
+ }
7
+ }
8
+
9
+ let script: Promise<void> | undefined
10
+
11
+ function loadWidgets() {
12
+ if (window.twttr?.widgets) return Promise.resolve()
13
+ if (script) return script
14
+ script = new Promise((resolve, reject) => {
15
+ const existing = document.querySelector<HTMLScriptElement>(
16
+ 'script[src="https://platform.twitter.com/widgets.js"]',
17
+ )
18
+ const element = existing ?? document.createElement("script")
19
+ element.addEventListener("load", () => resolve(), { once: true })
20
+ element.addEventListener(
21
+ "error",
22
+ () => reject(new Error("X widgets failed to load.")),
23
+ {
24
+ once: true,
25
+ },
26
+ )
27
+ if (!existing) {
28
+ element.async = true
29
+ element.src = "https://platform.twitter.com/widgets.js"
30
+ document.head.append(element)
31
+ }
32
+ })
33
+ return script
34
+ }
35
+
36
+ mountPathMXBehavior("[data-pmx-embed-x]", (root) => ({
37
+ update() {
38
+ void loadWidgets()
39
+ .then(() => window.twttr?.widgets?.load(root))
40
+ .catch(() => {
41
+ // The authored link remains usable when X is blocked or unavailable.
42
+ })
43
+ },
44
+ }))
package/index.ts ADDED
@@ -0,0 +1,162 @@
1
+ import { parseDirectiveLabel, type Plugin } from "@pathmx/core"
2
+ import { decodeHTML } from "entities"
3
+ import { embedSource, type EmbedSource } from "./source.ts"
4
+ import {
5
+ resolveWebLinkMetadata,
6
+ type EmbedFetch,
7
+ type EmbedLookup,
8
+ type WebLinkMetadata,
9
+ } from "./metadata.ts"
10
+ import { embedPresentation } from "./presentation.ts"
11
+ import styles from "./theme.css" with { type: "text" }
12
+
13
+ export type EmbedPluginOptions = Readonly<{
14
+ fetch?: EmbedFetch
15
+ lookup?: EmbedLookup
16
+ }>
17
+
18
+ type AuthoredEmbed = Readonly<{
19
+ href: string
20
+ text: string
21
+ source?: EmbedSource
22
+ metadata?: WebLinkMetadata
23
+ }>
24
+
25
+ /** Enhance deliberate @embed links, preserving their authored destination as fallback. */
26
+ export function EmbedPlugin(options: EmbedPluginOptions = {}): Plugin {
27
+ const fetcher = options.fetch ?? globalThis.fetch
28
+ const lookup: EmbedLookup =
29
+ options.lookup ??
30
+ (async (hostname) => {
31
+ if (typeof Bun === "undefined")
32
+ throw new Error("Web metadata lookup needs a server environment.")
33
+ return (await Bun.dns.lookup(hostname, { family: 0 })).map(
34
+ (result) => result.address,
35
+ )
36
+ })
37
+ const metadata = new Map<string, Promise<WebLinkMetadata | undefined>>()
38
+
39
+ return {
40
+ id: "embed",
41
+ lint(report, app) {
42
+ for (const source of app.sources.all()) {
43
+ for (const link of source.links) {
44
+ if (link.directive?.name !== "embed") continue
45
+ try {
46
+ if (link.directiveIssue) throw new Error(link.directiveIssue)
47
+ if (link.kind === "image")
48
+ throw new Error(
49
+ "Use [@embed Title](url), without the image ! prefix.",
50
+ )
51
+ if (link.directive.qualifiers.length)
52
+ throw new Error("@embed does not define qualifiers.")
53
+ if (Object.keys(link.directive.params).length)
54
+ throw new Error("@embed does not define named parameters.")
55
+ embedSource(link.href)
56
+ } catch (error) {
57
+ report(source, (error as Error).message, { code: "embed.source" })
58
+ }
59
+ }
60
+ }
61
+ },
62
+ async postcompile(content, ctx, app) {
63
+ const links: AuthoredEmbed[] = []
64
+ let current: { href: string; text: string } | undefined
65
+ app.rewriteHtml(content, [
66
+ [
67
+ "a[href]",
68
+ {
69
+ element(element) {
70
+ current = {
71
+ href: decodeHTML(element.getAttribute("href") ?? ""),
72
+ text: "",
73
+ }
74
+ links.push(current)
75
+ element.onEndTag(() => {
76
+ current = undefined
77
+ })
78
+ },
79
+ text(chunk) {
80
+ if (current) current.text += chunk.text
81
+ },
82
+ },
83
+ ],
84
+ ])
85
+
86
+ const resolved = await Promise.all(
87
+ links.map(async (link): Promise<AuthoredEmbed> => {
88
+ const parsed = parseDirectiveLabel(decodeHTML(link.text).trim())
89
+ if (parsed.directive?.name !== "embed") return link
90
+ try {
91
+ if (parsed.issue) throw new Error(parsed.issue)
92
+ if (parsed.directive.qualifiers.length)
93
+ throw new Error("@embed does not define qualifiers.")
94
+ if (Object.keys(parsed.directive.params).length)
95
+ throw new Error("@embed does not define named parameters.")
96
+ const source = embedSource(link.href)
97
+ if (source.provider !== "web") return { ...link, source }
98
+ let pending = metadata.get(source.href)
99
+ if (!pending) {
100
+ pending = resolveWebLinkMetadata(
101
+ source.href,
102
+ fetcher,
103
+ lookup,
104
+ app.rewriteHtml,
105
+ ).catch((error) => {
106
+ app.log.warn("embed", {
107
+ source: ctx.source.id,
108
+ url: source.href,
109
+ error: error instanceof Error ? error.message : String(error),
110
+ })
111
+ return undefined
112
+ })
113
+ metadata.set(source.href, pending)
114
+ }
115
+ return { ...link, source, metadata: await pending }
116
+ } catch (error) {
117
+ app.invalid(ctx.source, (error as Error).message, {
118
+ code: "embed.source",
119
+ block: ctx.block?.id,
120
+ })
121
+ return link
122
+ }
123
+ }),
124
+ )
125
+
126
+ let index = 0
127
+ return app.rewriteHtml(content, [
128
+ [
129
+ "a[href]",
130
+ {
131
+ element(element) {
132
+ const link = resolved[index++]!
133
+ if (!link.source) return
134
+ const parsed = parseDirectiveLabel(decodeHTML(link.text).trim())
135
+ const label =
136
+ parsed.label || link.metadata?.title || link.source.href
137
+ element.before(
138
+ String(embedPresentation(link.source, label, link.metadata)),
139
+ {
140
+ html: true,
141
+ },
142
+ )
143
+ element.remove()
144
+ },
145
+ },
146
+ ],
147
+ ])
148
+ },
149
+ async page(content, ctx) {
150
+ if (!content.includes('class="pmx-embed')) return content
151
+ ctx.addAsset({ type: "stylesheet", name: "embed.css", text: styles })
152
+ if (content.includes("data-pmx-embed-x"))
153
+ await ctx.addBrowserBundle(
154
+ new URL("./browser/x.ts", import.meta.url),
155
+ "embed-x",
156
+ )
157
+ return content
158
+ },
159
+ }
160
+ }
161
+
162
+ export default EmbedPlugin
package/metadata.ts ADDED
@@ -0,0 +1,231 @@
1
+ import { decodeHTML } from "entities"
2
+ import type { AppContext } from "@pathmx/core"
3
+
4
+ type HtmlStringRewrite = AppContext["rewriteHtml"]
5
+
6
+ export type WebLinkMetadata = Readonly<{
7
+ url: string
8
+ title?: string
9
+ description?: string
10
+ image?: string
11
+ publisher?: string
12
+ }>
13
+
14
+ export type EmbedFetch = (
15
+ input: string | URL | Request,
16
+ init?: RequestInit,
17
+ ) => Promise<Response>
18
+ export type EmbedLookup = (hostname: string) => Promise<readonly string[]>
19
+
20
+ const MAX_REDIRECTS = 3
21
+ const MAX_HTML_BYTES = 512 * 1024
22
+ const TIMEOUT_MS = 5_000
23
+
24
+ function privateAddress(address: string) {
25
+ const value = address.toLowerCase().split("%", 1)[0]!
26
+ const ipv4 = value.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
27
+ if (ipv4) {
28
+ const [, a, b] = ipv4.map(Number)
29
+ return (
30
+ a === 0 ||
31
+ a === 10 ||
32
+ a === 127 ||
33
+ (a === 100 && b! >= 64 && b! <= 127) ||
34
+ (a === 169 && b === 254) ||
35
+ (a === 172 && b! >= 16 && b! <= 31) ||
36
+ (a === 192 && b === 168) ||
37
+ (a === 198 && (b === 18 || b === 19)) ||
38
+ a! >= 224
39
+ )
40
+ }
41
+ if (value.includes(":"))
42
+ return (
43
+ value === "::" ||
44
+ value === "::1" ||
45
+ /^f[cd]/.test(value) ||
46
+ /^fe[89ab]/.test(value) ||
47
+ value.startsWith("ff") ||
48
+ value.startsWith("2001:db8:") ||
49
+ value.startsWith("::ffff:127.") ||
50
+ value.startsWith("::ffff:10.") ||
51
+ value.startsWith("::ffff:192.168.")
52
+ )
53
+ return true
54
+ }
55
+
56
+ async function assertPublicHost(url: URL, lookup: EmbedLookup) {
57
+ let timer: ReturnType<typeof setTimeout> | undefined
58
+ const timeout = new Promise<never>((_, reject) => {
59
+ timer = setTimeout(
60
+ () => reject(new Error("Host lookup timed out.")),
61
+ TIMEOUT_MS,
62
+ )
63
+ })
64
+ const addresses = await Promise.race([lookup(url.hostname), timeout]).finally(
65
+ () => clearTimeout(timer),
66
+ )
67
+ if (!addresses.length || addresses.some(privateAddress))
68
+ throw new Error(
69
+ "The page host does not resolve exclusively to public addresses.",
70
+ )
71
+ }
72
+
73
+ function allowedUrl(value: string, base?: string) {
74
+ try {
75
+ const url = new URL(value, base)
76
+ if (
77
+ !/^https?:$/.test(url.protocol) ||
78
+ url.username ||
79
+ url.password ||
80
+ url.port ||
81
+ url.hostname === "localhost" ||
82
+ url.hostname.endsWith(".localhost") ||
83
+ /^(?:127\.|0\.|10\.|169\.254\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.)/.test(
84
+ url.hostname,
85
+ ) ||
86
+ url.hostname.startsWith("[")
87
+ )
88
+ return
89
+ return url
90
+ } catch {
91
+ return
92
+ }
93
+ }
94
+
95
+ async function limitedText(response: Response) {
96
+ if (!response.body) return ""
97
+
98
+ const reader = response.body.getReader()
99
+ const decoder = new TextDecoder()
100
+ let bytes = 0
101
+ let text = ""
102
+ while (true) {
103
+ const { done, value } = await reader.read()
104
+ if (done) break
105
+ bytes += value.byteLength
106
+ if (bytes > MAX_HTML_BYTES) {
107
+ await reader.cancel()
108
+ break
109
+ }
110
+ text += decoder.decode(value, { stream: true })
111
+ if (/<\/head\s*>/i.test(text)) {
112
+ await reader.cancel()
113
+ break
114
+ }
115
+ }
116
+ return text + decoder.decode()
117
+ }
118
+
119
+ async function fetchPage(
120
+ href: string,
121
+ fetcher: EmbedFetch,
122
+ lookup: EmbedLookup,
123
+ ) {
124
+ const initial = allowedUrl(href)
125
+ if (!initial) throw new Error("The page URL is not public.")
126
+ let url: URL = initial
127
+
128
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
129
+ await assertPublicHost(url, lookup)
130
+ const response = await fetcher(url, {
131
+ redirect: "manual",
132
+ signal: AbortSignal.timeout(TIMEOUT_MS),
133
+ headers: {
134
+ accept: "text/html,application/xhtml+xml;q=0.9",
135
+ "user-agent": "PathMX Embed/0.1",
136
+ },
137
+ })
138
+ if (response.status >= 300 && response.status < 400) {
139
+ const location = response.headers.get("location")
140
+ const next: URL | undefined = location
141
+ ? allowedUrl(location, url.href)
142
+ : undefined
143
+ if (!next) throw new Error("The page redirected to a non-public URL.")
144
+ url = next
145
+ continue
146
+ }
147
+ if (!response.ok)
148
+ throw new Error(`The page returned HTTP ${response.status}.`)
149
+ const type = response.headers.get("content-type")?.toLowerCase() ?? ""
150
+ if (
151
+ type &&
152
+ !type.includes("text/html") &&
153
+ !type.includes("application/xhtml+xml")
154
+ )
155
+ throw new Error("The page is not HTML.")
156
+ return { html: await limitedText(response), url: url.href }
157
+ }
158
+ throw new Error("The page redirected too many times.")
159
+ }
160
+
161
+ function clean(value: string | undefined) {
162
+ const normalized = value && decodeHTML(value).replace(/\s+/g, " ").trim()
163
+ return normalized || undefined
164
+ }
165
+
166
+ function imageUrl(value: string | undefined, base: string) {
167
+ const url = value ? allowedUrl(decodeHTML(value), base) : undefined
168
+ return url?.href
169
+ }
170
+
171
+ export function readWebLinkMetadata(
172
+ source: string,
173
+ url: string,
174
+ rewriteHtml: HtmlStringRewrite,
175
+ ): WebLinkMetadata {
176
+ const values = new Map<string, string>()
177
+ let title = ""
178
+ rewriteHtml(source, [
179
+ [
180
+ "meta[content]",
181
+ {
182
+ element(element) {
183
+ const key = (
184
+ element.getAttribute("property") ?? element.getAttribute("name")
185
+ )?.toLowerCase()
186
+ const value = element.getAttribute("content")
187
+ if (key && value && !values.has(key)) values.set(key, value)
188
+ },
189
+ },
190
+ ],
191
+ [
192
+ "title",
193
+ {
194
+ text(chunk) {
195
+ title += chunk.text
196
+ },
197
+ },
198
+ ],
199
+ ])
200
+
201
+ return {
202
+ url,
203
+ title: clean(
204
+ values.get("og:title") ?? values.get("twitter:title") ?? title,
205
+ ),
206
+ description: clean(
207
+ values.get("og:description") ??
208
+ values.get("twitter:description") ??
209
+ values.get("description"),
210
+ ),
211
+ image: imageUrl(
212
+ values.get("og:image:secure_url") ??
213
+ values.get("og:image") ??
214
+ values.get("twitter:image"),
215
+ url,
216
+ ),
217
+ publisher: clean(
218
+ values.get("og:site_name") ?? values.get("application-name"),
219
+ ),
220
+ }
221
+ }
222
+
223
+ export async function resolveWebLinkMetadata(
224
+ href: string,
225
+ fetcher: EmbedFetch,
226
+ lookup: EmbedLookup,
227
+ rewriteHtml: HtmlStringRewrite,
228
+ ) {
229
+ const page = await fetchPage(href, fetcher, lookup)
230
+ return readWebLinkMetadata(page.html, page.url, rewriteHtml)
231
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@pathmx/embed",
3
+ "description": "X posts, YouTube videos, and rich web link cards for PathMX.",
4
+ "version": "0.6.4",
5
+ "license": "SEE LICENSE IN LICENSE.md",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/pathmx/pathmx-beta.git",
9
+ "directory": "pathmx/embed"
10
+ },
11
+ "homepage": "https://github.com/pathmx/pathmx-beta#readme",
12
+ "bugs": "https://github.com/pathmx/pathmx-beta/issues",
13
+ "publishConfig": {
14
+ "access": "public",
15
+ "registry": "https://registry.npmjs.org/",
16
+ "tag": "beta"
17
+ },
18
+ "type": "module",
19
+ "exports": "./index.ts",
20
+ "pathmx": {
21
+ "plugin": "."
22
+ },
23
+ "engines": {
24
+ "bun": ">=1.4.0"
25
+ },
26
+ "peerDependencies": {
27
+ "@pathmx/core": "^0.6.0"
28
+ },
29
+ "dependencies": {
30
+ "entities": "^8.0.0"
31
+ }
32
+ }
@@ -0,0 +1,65 @@
1
+ import { html } from "@pathmx/core"
2
+ import type { EmbedSource } from "./source.ts"
3
+ import type { WebLinkMetadata } from "./metadata.ts"
4
+
5
+ export function embedPresentation(
6
+ source: EmbedSource,
7
+ label: string,
8
+ metadata?: WebLinkMetadata,
9
+ ) {
10
+ if (source.provider === "youtube")
11
+ return html`<span class="pmx-embed pmx-embed-youtube" data-pmx-embed>
12
+ <span class="pmx-embed-youtube-frame">
13
+ <iframe
14
+ src="https://www.youtube-nocookie.com/embed/${source.id}"
15
+ title="${label}"
16
+ loading="lazy"
17
+ referrerpolicy="strict-origin-when-cross-origin"
18
+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture; fullscreen"
19
+ allowfullscreen
20
+ ></iframe>
21
+ </span>
22
+ <a
23
+ class="pmx-embed-source"
24
+ href="${source.href}"
25
+ aria-label="${label} — open on YouTube"
26
+ >Open on YouTube</a
27
+ >
28
+ </span>`
29
+
30
+ if (source.provider === "x")
31
+ return html`<div
32
+ class="pmx-embed pmx-embed-x"
33
+ data-pmx-embed
34
+ data-pmx-embed-x
35
+ >
36
+ <blockquote class="twitter-tweet">
37
+ <a href="${source.href}">${label}</a>
38
+ </blockquote>
39
+ <a
40
+ class="pmx-embed-x-fallback"
41
+ href="${source.href}"
42
+ aria-label="${label} — open on X"
43
+ >Open on X</a
44
+ >
45
+ </div>`
46
+
47
+ const title = metadata?.title || label || source.href
48
+ const publisher =
49
+ metadata?.publisher ||
50
+ new URL(metadata?.url ?? source.href).hostname.replace(/^www\./, "")
51
+ return html`<a
52
+ class="pmx-embed pmx-embed-card"
53
+ href="${metadata?.url ?? source.href}"
54
+ aria-label="${title} — visit source"
55
+ data-pmx-embed
56
+ data-pmx-link="card"
57
+ >
58
+ <span class="pmx-embed-card-body">
59
+ <strong class="pmx-embed-card-title">${title}</strong>
60
+ ${metadata?.description ? html`<span class="pmx-embed-card-description">${metadata.description}</span>` : ""}
61
+ <span class="pmx-embed-card-publisher">${publisher}</span>
62
+ </span>
63
+ ${metadata?.image ? html`<img class="pmx-embed-card-image" src="${metadata.image}" alt="" loading="lazy" decoding="async" referrerpolicy="no-referrer" />` : ""}
64
+ </a>`
65
+ }
package/source.ts ADDED
@@ -0,0 +1,91 @@
1
+ export type EmbedSource = Readonly<
2
+ | { provider: "x"; id: string; href: string }
3
+ | { provider: "youtube"; id: string; href: string }
4
+ | { provider: "web"; href: string }
5
+ >
6
+
7
+ const X_HOSTS = new Set([
8
+ "x.com",
9
+ "www.x.com",
10
+ "twitter.com",
11
+ "www.twitter.com",
12
+ ])
13
+ const YOUTUBE_HOSTS = new Set([
14
+ "youtube.com",
15
+ "www.youtube.com",
16
+ "m.youtube.com",
17
+ "music.youtube.com",
18
+ "youtube-nocookie.com",
19
+ "www.youtube-nocookie.com",
20
+ "youtu.be",
21
+ "www.youtu.be",
22
+ ])
23
+
24
+ function publicUrl(href: string) {
25
+ let url: URL
26
+ try {
27
+ url = new URL(href)
28
+ } catch {
29
+ throw new Error("@embed needs a complete HTTP or HTTPS URL.")
30
+ }
31
+ if (
32
+ !/^https?:$/.test(url.protocol) ||
33
+ url.username ||
34
+ url.password ||
35
+ url.port
36
+ )
37
+ throw new Error(
38
+ "@embed needs a public HTTP or HTTPS URL without credentials or a custom port.",
39
+ )
40
+ return url
41
+ }
42
+
43
+ /** Normalize the deliberately small set of rich providers; all other URLs are web cards. */
44
+ export function embedSource(href: string): EmbedSource {
45
+ const url = publicUrl(href)
46
+ const host = url.hostname.toLowerCase()
47
+ const parts = url.pathname.split("/").filter(Boolean)
48
+
49
+ if (X_HOSTS.has(host)) {
50
+ const username =
51
+ parts.length === 3 &&
52
+ parts[1] === "status" &&
53
+ /^[a-z\d_]{1,15}$/i.test(parts[0] ?? "")
54
+ ? parts[0]
55
+ : undefined
56
+ const status = username ? parts[2] : undefined
57
+ if (!status || !/^\d+$/.test(status))
58
+ throw new Error(
59
+ "@embed supports an individual X post, not a profile, feed, or other X URL.",
60
+ )
61
+ return {
62
+ provider: "x",
63
+ id: status,
64
+ href: `https://x.com/${username}/status/${status}`,
65
+ }
66
+ }
67
+
68
+ if (YOUTUBE_HOSTS.has(host)) {
69
+ const id = host.endsWith("youtu.be")
70
+ ? parts.length === 1
71
+ ? parts[0]
72
+ : undefined
73
+ : parts[0] === "watch" && parts.length === 1
74
+ ? (url.searchParams.get("v") ?? undefined)
75
+ : ["embed", "shorts", "live", "v"].includes(parts[0] ?? "") &&
76
+ parts.length === 2
77
+ ? parts[1]
78
+ : undefined
79
+ if (!id || !/^[\w-]{11}$/.test(id))
80
+ throw new Error(
81
+ "@embed supports an individual YouTube video, not a channel, playlist, or other YouTube URL.",
82
+ )
83
+ return {
84
+ provider: "youtube",
85
+ id,
86
+ href: `https://www.youtube.com/watch?v=${id}`,
87
+ }
88
+ }
89
+
90
+ return { provider: "web", href: url.href }
91
+ }
package/theme.css ADDED
@@ -0,0 +1,172 @@
1
+ .pmx-embed {
2
+ box-sizing: border-box;
3
+ width: 100%;
4
+ margin-block: 1.25rem;
5
+ }
6
+
7
+ .pmx-embed-youtube {
8
+ display: block;
9
+ }
10
+
11
+ .pmx-embed-youtube-frame {
12
+ position: relative;
13
+ display: block;
14
+ overflow: hidden;
15
+ aspect-ratio: 16 / 9;
16
+ border-radius: var(--pmx-radius-xl, 0.75rem);
17
+ background: #09090b;
18
+ }
19
+
20
+ .pmx-embed-youtube-frame iframe {
21
+ position: absolute;
22
+ inset: 0;
23
+ display: block;
24
+ width: 100%;
25
+ height: 100%;
26
+ border: 0;
27
+ }
28
+
29
+ .pmx-embed-source,
30
+ .pmx-embed-x-fallback {
31
+ display: inline-flex;
32
+ min-height: 2.75rem;
33
+ align-items: center;
34
+ justify-content: center;
35
+ padding-inline: 0.65rem;
36
+ color: var(--pmx-color-muted, #667);
37
+ font-size: 0.8em;
38
+ }
39
+
40
+ .pmx-embed-source {
41
+ margin-top: 0.25rem;
42
+ }
43
+
44
+ .pmx-embed-x {
45
+ display: grid;
46
+ min-height: 8rem;
47
+ place-items: center;
48
+ }
49
+
50
+ .pmx-embed-x > .twitter-tweet {
51
+ width: min(100%, 550px);
52
+ margin: 0;
53
+ padding: 1.25rem;
54
+ border-radius: var(--pmx-radius-xl, 0.75rem);
55
+ background: var(--pmx-color-surface, Canvas);
56
+ color: var(--pmx-color-fg, CanvasText);
57
+ font: inherit;
58
+ text-align: center;
59
+ }
60
+
61
+ .pmx-embed-x-fallback {
62
+ justify-self: center;
63
+ }
64
+
65
+ .pmx-embed-source:focus-visible,
66
+ .pmx-embed-x-fallback:focus-visible {
67
+ border-radius: var(--pmx-radius-sm, 0.25rem);
68
+ outline: 2px solid var(--pmx-color-focus, currentColor);
69
+ outline-offset: 2px;
70
+ }
71
+
72
+ .pmx-prose a.pmx-embed-card,
73
+ a.pmx-embed-card {
74
+ display: flex;
75
+ min-width: 0;
76
+ align-items: stretch;
77
+ overflow: hidden;
78
+ color: var(--pmx-color-fg, CanvasText);
79
+ background: var(--pmx-color-bg, Canvas);
80
+ border-radius: var(--pmx-radius-xl, 0.75rem);
81
+ box-shadow:
82
+ 0 0 0 1px var(--pmx-color-border, #8885),
83
+ var(--pmx-shadow-xs, 0 1px 2px #0001);
84
+ text-decoration: none;
85
+ transition:
86
+ box-shadow 140ms ease,
87
+ transform 140ms ease;
88
+ }
89
+
90
+ a.pmx-embed-card:hover {
91
+ box-shadow:
92
+ 0 0 0 1px var(--pmx-color-accent, currentColor),
93
+ var(--pmx-shadow-sm, 0 2px 5px #0002);
94
+ transform: translateY(-1px);
95
+ }
96
+
97
+ a.pmx-embed-card:focus-visible {
98
+ outline: 2px solid var(--pmx-color-focus, currentColor);
99
+ outline-offset: 3px;
100
+ }
101
+
102
+ .pmx-embed-card-body {
103
+ display: flex;
104
+ flex: 1;
105
+ min-width: 0;
106
+ flex-direction: column;
107
+ justify-content: center;
108
+ gap: 0.45rem;
109
+ padding: 1.15rem;
110
+ }
111
+
112
+ .pmx-embed-card-title {
113
+ overflow-wrap: anywhere;
114
+ font-family: var(--pmx-font-heading, inherit);
115
+ font-size: 1.05em;
116
+ font-weight: 650;
117
+ line-height: 1.35;
118
+ }
119
+
120
+ .pmx-embed-card-description {
121
+ display: -webkit-box;
122
+ overflow: hidden;
123
+ color: var(--pmx-color-muted, #667);
124
+ font-size: 0.9em;
125
+ line-height: 1.5;
126
+ -webkit-box-orient: vertical;
127
+ -webkit-line-clamp: 3;
128
+ }
129
+
130
+ .pmx-embed-card-publisher {
131
+ overflow: hidden;
132
+ color: var(--pmx-color-muted, #667);
133
+ font-size: 0.8em;
134
+ line-height: 1.4;
135
+ text-overflow: ellipsis;
136
+ white-space: nowrap;
137
+ }
138
+
139
+ .pmx-prose .pmx-embed-card-image,
140
+ .pmx-embed-card-image {
141
+ width: clamp(7rem, 30%, 13rem);
142
+ min-height: 8rem;
143
+ flex: none;
144
+ margin: 0;
145
+ object-fit: cover;
146
+ outline: 1px solid color-mix(in oklch, currentColor 10%, transparent);
147
+ outline-offset: -1px;
148
+ }
149
+
150
+ @media (max-width: 32rem) {
151
+ .pmx-prose a.pmx-embed-card,
152
+ a.pmx-embed-card {
153
+ flex-direction: column-reverse;
154
+ }
155
+
156
+ .pmx-prose .pmx-embed-card-image,
157
+ .pmx-embed-card-image {
158
+ width: 100%;
159
+ min-height: 0;
160
+ aspect-ratio: 16 / 9;
161
+ }
162
+ }
163
+
164
+ @media (prefers-reduced-motion: reduce) {
165
+ a.pmx-embed-card {
166
+ transition: none;
167
+ }
168
+
169
+ a.pmx-embed-card:hover {
170
+ transform: none;
171
+ }
172
+ }