@pyreon/head 0.11.5 → 0.11.7
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 +6 -8
- package/lib/index.js.map +1 -1
- package/lib/provider.js.map +1 -1
- package/lib/ssr.js.map +1 -1
- package/lib/types/index.d.ts +4 -4
- package/lib/types/provider.d.ts +1 -1
- package/lib/types/use-head.d.ts +3 -3
- package/lib/use-head.js.map +1 -1
- package/package.json +18 -18
- package/src/context.ts +5 -5
- package/src/dom.ts +7 -7
- package/src/index.ts +5 -5
- package/src/provider.ts +5 -5
- package/src/ssr.ts +15 -15
- package/src/tests/head.test.ts +447 -445
- package/src/tests/setup.ts +1 -1
- package/src/use-head.ts +19 -19
package/README.md
CHANGED
|
@@ -11,18 +11,16 @@ bun add @pyreon/head
|
|
|
11
11
|
## Quick Start
|
|
12
12
|
|
|
13
13
|
```tsx
|
|
14
|
-
import { HeadProvider, useHead } from
|
|
14
|
+
import { HeadProvider, useHead } from '@pyreon/head'
|
|
15
15
|
|
|
16
16
|
const App = () => {
|
|
17
17
|
useHead({
|
|
18
|
-
title:
|
|
18
|
+
title: 'My App',
|
|
19
19
|
meta: [
|
|
20
|
-
{ name:
|
|
21
|
-
{ property:
|
|
22
|
-
],
|
|
23
|
-
link: [
|
|
24
|
-
{ rel: "canonical", href: "https://example.com" },
|
|
20
|
+
{ name: 'description', content: 'A Pyreon application' },
|
|
21
|
+
{ property: 'og:title', content: 'My App' },
|
|
25
22
|
],
|
|
23
|
+
link: [{ rel: 'canonical', href: 'https://example.com' }],
|
|
26
24
|
})
|
|
27
25
|
|
|
28
26
|
return <div>Hello</div>
|
|
@@ -41,7 +39,7 @@ const Root = () => (
|
|
|
41
39
|
Use `renderWithHead` to capture head tags during server-side rendering:
|
|
42
40
|
|
|
43
41
|
```tsx
|
|
44
|
-
import { renderWithHead } from
|
|
42
|
+
import { renderWithHead } from '@pyreon/head'
|
|
45
43
|
|
|
46
44
|
const { html, head } = renderWithHead(<App />)
|
|
47
45
|
// `head` contains the serialized <title>, <meta>, <link>, etc.
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/provider.ts","../src/dom.ts","../src/use-head.ts"],"sourcesContent":["import { createContext } from \"@pyreon/core\"\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: \"title\" | \"meta\" | \"link\" | \"script\" | \"style\" | \"base\" | \"noscript\"\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n \"http-equiv\"?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: \"high\" | \"low\" | \"auto\"\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\"\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { ComponentFn, Props, VNodeChild } from \"@pyreon/core\"\nimport { provide } from \"@pyreon/core\"\nimport type { HeadContextValue } from \"./context\"\nimport { createHeadContext, HeadContext } from \"./context\"\n\nexport interface HeadProviderProps extends Props {\n context?: HeadContextValue | undefined\n children?: VNodeChild\n}\n\n/**\n * Provides a HeadContextValue to all descendant components.\n * Wrap your app root with this to enable useHead() throughout the tree.\n *\n * If no `context` prop is passed, a new HeadContext is created automatically.\n *\n * @example\n * // Auto-create context:\n * <HeadProvider><App /></HeadProvider>\n *\n * // Explicit context (e.g. for SSR):\n * const headCtx = createHeadContext()\n * mount(h(HeadProvider, { context: headCtx }, h(App, null)), root)\n */\nexport const HeadProvider: ComponentFn<HeadProviderProps> = (props) => {\n const ctx = props.context ?? createHeadContext()\n provide(HeadContext, ctx)\n\n const ch = props.children\n return typeof ch === \"function\" ? (ch as () => VNodeChild)() : ch\n}\n","import type { HeadContextValue } from \"./context\"\n\nconst ATTR = \"data-pyreon-head\"\n\n/** Tracks managed elements by key — avoids querySelectorAll on every sync */\nconst managedElements = new Map<string, Element>()\n\n/**\n * Sync the resolved head tags to the real DOM <head>.\n * Uses incremental diffing: matches existing elements by key, patches attributes\n * in-place, adds new elements, and removes stale ones.\n * Also syncs htmlAttrs, bodyAttrs, and applies titleTemplate.\n * No-op on the server (typeof document === \"undefined\").\n */\nfunction patchExistingTag(\n found: Element,\n tag: { props: Record<string, unknown>; children: string },\n kept: Set<string>,\n): void {\n kept.add(found.getAttribute(ATTR) as string)\n patchAttrs(found, tag.props as Record<string, string>)\n const content = String(tag.children)\n if (found.textContent !== content) found.textContent = content\n}\n\nfunction createNewTag(tag: {\n tag: string\n props: Record<string, unknown>\n children: string\n key: unknown\n}): void {\n const el = document.createElement(tag.tag)\n const key = tag.key as string\n el.setAttribute(ATTR, key)\n for (const [k, v] of Object.entries(tag.props as Record<string, string>)) {\n el.setAttribute(k, v)\n }\n if (tag.children) el.textContent = tag.children\n document.head.appendChild(el)\n managedElements.set(key, el)\n}\n\nexport function syncDom(ctx: HeadContextValue): void {\n if (typeof document === \"undefined\") return\n\n const tags = ctx.resolve()\n const titleTemplate = ctx.resolveTitleTemplate()\n\n // Seed from DOM on first sync, or re-seed if DOM was reset (e.g. between tests)\n let needsSeed = managedElements.size === 0\n if (!needsSeed) {\n // Check if a tracked element is still in the DOM\n const sample = managedElements.values().next().value\n if (sample && !sample.isConnected) {\n managedElements.clear()\n needsSeed = true\n }\n }\n if (needsSeed) {\n const existing = document.head.querySelectorAll(`[${ATTR}]`)\n for (const el of existing) {\n managedElements.set(el.getAttribute(ATTR) as string, el)\n }\n }\n\n const kept = new Set<string>()\n\n for (const tag of tags) {\n if (tag.tag === \"title\") {\n document.title = applyTitleTemplate(String(tag.children), titleTemplate)\n continue\n }\n\n const key = tag.key as string\n const found = managedElements.get(key)\n\n if (found && found.tagName.toLowerCase() === tag.tag) {\n patchExistingTag(found, tag as { props: Record<string, unknown>; children: string }, kept)\n } else {\n if (found) {\n found.remove()\n managedElements.delete(key)\n }\n createNewTag(\n tag as { tag: string; props: Record<string, unknown>; children: string; key: unknown },\n )\n kept.add(key)\n }\n }\n\n // Remove stale elements\n for (const [key, el] of managedElements) {\n if (!kept.has(key)) {\n el.remove()\n managedElements.delete(key)\n }\n }\n\n syncElementAttrs(document.documentElement, ctx.resolveHtmlAttrs())\n syncElementAttrs(document.body, ctx.resolveBodyAttrs())\n}\n\n/** Patch an element's attributes to match the desired props. */\nfunction patchAttrs(el: Element, props: Record<string, string>): void {\n for (let i = el.attributes.length - 1; i >= 0; i--) {\n const attr = el.attributes[i]\n if (!attr || attr.name === ATTR) continue\n if (!(attr.name in props)) el.removeAttribute(attr.name)\n }\n for (const [k, v] of Object.entries(props)) {\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n}\n\nfunction applyTitleTemplate(\n title: string,\n template: string | ((t: string) => string) | undefined,\n): string {\n if (!template) return title\n if (typeof template === \"function\") return template(title)\n return template.replace(/%s/g, title)\n}\n\n/** Sync pyreon-managed attributes on <html> or <body>. */\nfunction syncElementAttrs(el: Element, attrs: Record<string, string>): void {\n // Remove previously managed attrs that are no longer present\n const managed = el.getAttribute(`${ATTR}-attrs`)\n if (managed) {\n for (const name of managed.split(\",\")) {\n if (name && !(name in attrs)) el.removeAttribute(name)\n }\n }\n const keys: string[] = []\n for (const [k, v] of Object.entries(attrs)) {\n keys.push(k)\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n if (keys.length > 0) {\n el.setAttribute(`${ATTR}-attrs`, keys.join(\",\"))\n } else if (managed) {\n el.removeAttribute(`${ATTR}-attrs`)\n }\n}\n","import { onMount, onUnmount, useContext } from \"@pyreon/core\"\nimport { effect } from \"@pyreon/reactivity\"\nimport type { HeadEntry, HeadTag, UseHeadInput } from \"./context\"\nimport { HeadContext } from \"./context\"\nimport { syncDom } from \"./dom\"\n\n/** Cast a strict tag interface to the internal props format, stripping undefined values */\nfunction toProps(obj: Record<string, string | undefined>): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) result[k] = v\n }\n return result\n}\n\nfunction buildEntry(o: UseHeadInput): HeadEntry {\n const tags: HeadTag[] = []\n if (o.title != null) tags.push({ tag: \"title\", key: \"title\", children: o.title })\n o.meta?.forEach((m, i) => {\n tags.push({\n tag: \"meta\",\n key: m.name ?? m.property ?? `meta-${i}`,\n props: toProps(m as Record<string, string | undefined>),\n })\n })\n o.link?.forEach((l, i) => {\n tags.push({\n tag: \"link\",\n key: l.href ? `link-${l.rel || \"\"}-${l.href}` : l.rel ? `link-${l.rel}` : `link-${i}`,\n props: toProps(l as Record<string, string | undefined>),\n })\n })\n o.script?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: \"script\",\n key: s.src ?? `script-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n ...(children != null ? { children } : {}),\n })\n })\n o.style?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: \"style\",\n key: `style-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n children,\n })\n })\n o.noscript?.forEach((ns, i) => {\n tags.push({ tag: \"noscript\", key: `noscript-${i}`, children: ns.children })\n })\n if (o.jsonLd) {\n tags.push({\n tag: \"script\",\n key: \"jsonld\",\n props: { type: \"application/ld+json\" },\n children: JSON.stringify(o.jsonLd),\n })\n }\n if (o.base)\n tags.push({\n tag: \"base\",\n key: \"base\",\n props: toProps(o.base as Record<string, string | undefined>),\n })\n return {\n tags,\n titleTemplate: o.titleTemplate,\n htmlAttrs: o.htmlAttrs,\n bodyAttrs: o.bodyAttrs,\n }\n}\n\n/**\n * Register head tags (title, meta, link, script, style, noscript, base, jsonLd)\n * for the current component.\n *\n * Accepts a static object or a reactive getter:\n * useHead({ title: \"My Page\", meta: [{ name: \"description\", content: \"...\" }] })\n * useHead(() => ({ title: `${count()} items` })) // updates when signal changes\n *\n * Tags are deduplicated by key — innermost component wins.\n * Requires a <HeadProvider> (CSR) or renderWithHead() (SSR) ancestor.\n */\nexport function useHead(input: UseHeadInput | (() => UseHeadInput)): void {\n const ctx = useContext(HeadContext)\n if (!ctx) return // no HeadProvider — silently no-op\n\n const id = Symbol()\n\n if (typeof input === \"function\") {\n if (typeof document !== \"undefined\") {\n // CSR: reactive — re-register whenever signals change\n effect(() => {\n ctx.add(id, buildEntry(input()))\n syncDom(ctx)\n })\n } else {\n // SSR: evaluate once synchronously (no effects on server)\n ctx.add(id, buildEntry(input()))\n }\n }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Y,OAAO,EAAE,UAAU,GAAG,EAAE;GACzC,CAAC;GACF;AACF,GAAE,OAAO,SAAS,GAAG,MAAM;EACzB,MAAM,EAAE,UAAU,GAAG,SAAS;AAC9B,OAAK,KAAK;GACR,KAAK;GACL,KAAK,SAAS;GACd,OAAO,QAAQ,KAA2C;GAC1D;GACD,CAAC;GACF;AACF,GAAE,UAAU,SAAS,IAAI,MAAM;AAC7B,OAAK,KAAK;GAAE,KAAK;GAAY,KAAK,YAAY;GAAK,UAAU,GAAG;GAAU,CAAC;GAC3E;AACF,KAAI,EAAE,OACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,EAAE,MAAM,uBAAuB;EACtC,UAAU,KAAK,UAAU,EAAE,OAAO;EACnC,CAAC;AAEJ,KAAI,EAAE,KACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,QAAQ,EAAE,KAA2C;EAC7D,CAAC;AACJ,QAAO;EACL;EACA,eAAe,EAAE;EACjB,WAAW,EAAE;EACb,WAAW,EAAE;EACd;;;;;;;;;;;;;AAcH,SAAgB,QAAQ,OAAkD;CACxE,MAAM,MAAM,WAAW,YAAY;AACnC,KAAI,CAAC,IAAK;CAEV,MAAM,KAAK,QAAQ;AAEnB,KAAI,OAAO,UAAU,WACnB,KAAI,OAAO,aAAa,YAEtB,cAAa;AACX,MAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;AAChC,UAAQ,IAAI;GACZ;KAGF,KAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;MAE7B;AACL,MAAI,IAAI,IAAI,WAAW,MAAM,CAAC;AAC9B,gBAAc;AACZ,WAAQ,IAAI;IACZ;;AAGJ,iBAAgB;AACd,MAAI,OAAO,GAAG;AACd,UAAQ,IAAI;GACZ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/context.ts","../src/provider.ts","../src/dom.ts","../src/use-head.ts"],"sourcesContent":["import { createContext } from '@pyreon/core'\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript'\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n 'http-equiv'?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: 'high' | 'low' | 'auto'\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: '_blank' | '_self' | '_parent' | '_top'\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { ComponentFn, Props, VNodeChild } from '@pyreon/core'\nimport { provide } from '@pyreon/core'\nimport type { HeadContextValue } from './context'\nimport { createHeadContext, HeadContext } from './context'\n\nexport interface HeadProviderProps extends Props {\n context?: HeadContextValue | undefined\n children?: VNodeChild\n}\n\n/**\n * Provides a HeadContextValue to all descendant components.\n * Wrap your app root with this to enable useHead() throughout the tree.\n *\n * If no `context` prop is passed, a new HeadContext is created automatically.\n *\n * @example\n * // Auto-create context:\n * <HeadProvider><App /></HeadProvider>\n *\n * // Explicit context (e.g. for SSR):\n * const headCtx = createHeadContext()\n * mount(h(HeadProvider, { context: headCtx }, h(App, null)), root)\n */\nexport const HeadProvider: ComponentFn<HeadProviderProps> = (props) => {\n const ctx = props.context ?? createHeadContext()\n provide(HeadContext, ctx)\n\n const ch = props.children\n return typeof ch === 'function' ? (ch as () => VNodeChild)() : ch\n}\n","import type { HeadContextValue } from './context'\n\nconst ATTR = 'data-pyreon-head'\n\n/** Tracks managed elements by key — avoids querySelectorAll on every sync */\nconst managedElements = new Map<string, Element>()\n\n/**\n * Sync the resolved head tags to the real DOM <head>.\n * Uses incremental diffing: matches existing elements by key, patches attributes\n * in-place, adds new elements, and removes stale ones.\n * Also syncs htmlAttrs, bodyAttrs, and applies titleTemplate.\n * No-op on the server (typeof document === \"undefined\").\n */\nfunction patchExistingTag(\n found: Element,\n tag: { props: Record<string, unknown>; children: string },\n kept: Set<string>,\n): void {\n kept.add(found.getAttribute(ATTR) as string)\n patchAttrs(found, tag.props as Record<string, string>)\n const content = String(tag.children)\n if (found.textContent !== content) found.textContent = content\n}\n\nfunction createNewTag(tag: {\n tag: string\n props: Record<string, unknown>\n children: string\n key: unknown\n}): void {\n const el = document.createElement(tag.tag)\n const key = tag.key as string\n el.setAttribute(ATTR, key)\n for (const [k, v] of Object.entries(tag.props as Record<string, string>)) {\n el.setAttribute(k, v)\n }\n if (tag.children) el.textContent = tag.children\n document.head.appendChild(el)\n managedElements.set(key, el)\n}\n\nexport function syncDom(ctx: HeadContextValue): void {\n if (typeof document === 'undefined') return\n\n const tags = ctx.resolve()\n const titleTemplate = ctx.resolveTitleTemplate()\n\n // Seed from DOM on first sync, or re-seed if DOM was reset (e.g. between tests)\n let needsSeed = managedElements.size === 0\n if (!needsSeed) {\n // Check if a tracked element is still in the DOM\n const sample = managedElements.values().next().value\n if (sample && !sample.isConnected) {\n managedElements.clear()\n needsSeed = true\n }\n }\n if (needsSeed) {\n const existing = document.head.querySelectorAll(`[${ATTR}]`)\n for (const el of existing) {\n managedElements.set(el.getAttribute(ATTR) as string, el)\n }\n }\n\n const kept = new Set<string>()\n\n for (const tag of tags) {\n if (tag.tag === 'title') {\n document.title = applyTitleTemplate(String(tag.children), titleTemplate)\n continue\n }\n\n const key = tag.key as string\n const found = managedElements.get(key)\n\n if (found && found.tagName.toLowerCase() === tag.tag) {\n patchExistingTag(found, tag as { props: Record<string, unknown>; children: string }, kept)\n } else {\n if (found) {\n found.remove()\n managedElements.delete(key)\n }\n createNewTag(\n tag as { tag: string; props: Record<string, unknown>; children: string; key: unknown },\n )\n kept.add(key)\n }\n }\n\n // Remove stale elements\n for (const [key, el] of managedElements) {\n if (!kept.has(key)) {\n el.remove()\n managedElements.delete(key)\n }\n }\n\n syncElementAttrs(document.documentElement, ctx.resolveHtmlAttrs())\n syncElementAttrs(document.body, ctx.resolveBodyAttrs())\n}\n\n/** Patch an element's attributes to match the desired props. */\nfunction patchAttrs(el: Element, props: Record<string, string>): void {\n for (let i = el.attributes.length - 1; i >= 0; i--) {\n const attr = el.attributes[i]\n if (!attr || attr.name === ATTR) continue\n if (!(attr.name in props)) el.removeAttribute(attr.name)\n }\n for (const [k, v] of Object.entries(props)) {\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n}\n\nfunction applyTitleTemplate(\n title: string,\n template: string | ((t: string) => string) | undefined,\n): string {\n if (!template) return title\n if (typeof template === 'function') return template(title)\n return template.replace(/%s/g, title)\n}\n\n/** Sync pyreon-managed attributes on <html> or <body>. */\nfunction syncElementAttrs(el: Element, attrs: Record<string, string>): void {\n // Remove previously managed attrs that are no longer present\n const managed = el.getAttribute(`${ATTR}-attrs`)\n if (managed) {\n for (const name of managed.split(',')) {\n if (name && !(name in attrs)) el.removeAttribute(name)\n }\n }\n const keys: string[] = []\n for (const [k, v] of Object.entries(attrs)) {\n keys.push(k)\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n if (keys.length > 0) {\n el.setAttribute(`${ATTR}-attrs`, keys.join(','))\n } else if (managed) {\n el.removeAttribute(`${ATTR}-attrs`)\n }\n}\n","import { onMount, onUnmount, useContext } from '@pyreon/core'\nimport { effect } from '@pyreon/reactivity'\nimport type { HeadEntry, HeadTag, UseHeadInput } from './context'\nimport { HeadContext } from './context'\nimport { syncDom } from './dom'\n\n/** Cast a strict tag interface to the internal props format, stripping undefined values */\nfunction toProps(obj: Record<string, string | undefined>): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) result[k] = v\n }\n return result\n}\n\nfunction buildEntry(o: UseHeadInput): HeadEntry {\n const tags: HeadTag[] = []\n if (o.title != null) tags.push({ tag: 'title', key: 'title', children: o.title })\n o.meta?.forEach((m, i) => {\n tags.push({\n tag: 'meta',\n key: m.name ?? m.property ?? `meta-${i}`,\n props: toProps(m as Record<string, string | undefined>),\n })\n })\n o.link?.forEach((l, i) => {\n tags.push({\n tag: 'link',\n key: l.href ? `link-${l.rel || ''}-${l.href}` : l.rel ? `link-${l.rel}` : `link-${i}`,\n props: toProps(l as Record<string, string | undefined>),\n })\n })\n o.script?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: 'script',\n key: s.src ?? `script-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n ...(children != null ? { children } : {}),\n })\n })\n o.style?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: 'style',\n key: `style-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n children,\n })\n })\n o.noscript?.forEach((ns, i) => {\n tags.push({ tag: 'noscript', key: `noscript-${i}`, children: ns.children })\n })\n if (o.jsonLd) {\n tags.push({\n tag: 'script',\n key: 'jsonld',\n props: { type: 'application/ld+json' },\n children: JSON.stringify(o.jsonLd),\n })\n }\n if (o.base)\n tags.push({\n tag: 'base',\n key: 'base',\n props: toProps(o.base as Record<string, string | undefined>),\n })\n return {\n tags,\n titleTemplate: o.titleTemplate,\n htmlAttrs: o.htmlAttrs,\n bodyAttrs: o.bodyAttrs,\n }\n}\n\n/**\n * Register head tags (title, meta, link, script, style, noscript, base, jsonLd)\n * for the current component.\n *\n * Accepts a static object or a reactive getter:\n * useHead({ title: \"My Page\", meta: [{ name: \"description\", content: \"...\" }] })\n * useHead(() => ({ title: `${count()} items` })) // updates when signal changes\n *\n * Tags are deduplicated by key — innermost component wins.\n * Requires a <HeadProvider> (CSR) or renderWithHead() (SSR) ancestor.\n */\nexport function useHead(input: UseHeadInput | (() => UseHeadInput)): void {\n const ctx = useContext(HeadContext)\n if (!ctx) return // no HeadProvider — silently no-op\n\n const id = Symbol()\n\n if (typeof input === 'function') {\n if (typeof document !== 'undefined') {\n // CSR: reactive — re-register whenever signals change\n effect(() => {\n ctx.add(id, buildEntry(input()))\n syncDom(ctx)\n })\n } else {\n // SSR: evaluate once synchronously (no effects on server)\n ctx.add(id, buildEntry(input()))\n }\n } else {\n ctx.add(id, buildEntry(input))\n onMount(() => {\n syncDom(ctx)\n })\n }\n\n onUnmount(() => {\n ctx.remove(id)\n syncDom(ctx)\n })\n}\n"],"mappings":";;;;AAqKA,SAAgB,oBAAsC;CACpD,MAAM,sBAAM,IAAI,KAAwB;CAGxC,IAAI,QAAQ;CACZ,IAAI,aAAwB,EAAE;CAC9B,IAAI;CACJ,IAAI,kBAA0C,EAAE;CAChD,IAAI,kBAA0C,EAAE;CAEhD,SAAS,UAAgB;AACvB,M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G;GAAU,CAAC;GAC3E;AACF,KAAI,EAAE,OACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,EAAE,MAAM,uBAAuB;EACtC,UAAU,KAAK,UAAU,EAAE,OAAO;EACnC,CAAC;AAEJ,KAAI,EAAE,KACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,QAAQ,EAAE,KAA2C;EAC7D,CAAC;AACJ,QAAO;EACL;EACA,eAAe,EAAE;EACjB,WAAW,EAAE;EACb,WAAW,EAAE;EACd;;;;;;;;;;;;;AAcH,SAAgB,QAAQ,OAAkD;CACxE,MAAM,MAAM,WAAW,YAAY;AACnC,KAAI,CAAC,IAAK;CAEV,MAAM,KAAK,QAAQ;AAEnB,KAAI,OAAO,UAAU,WACnB,KAAI,OAAO,aAAa,YAEtB,cAAa;AACX,MAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;AAChC,UAAQ,IAAI;GACZ;KAGF,KAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;MAE7B;AACL,MAAI,IAAI,IAAI,WAAW,MAAM,CAAC;AAC9B,gBAAc;AACZ,WAAQ,IAAI;IACZ;;AAGJ,iBAAgB;AACd,MAAI,OAAO,GAAG;AACd,UAAQ,IAAI;GACZ"}
|
package/lib/provider.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","names":[],"sources":["../src/context.ts","../src/provider.ts"],"sourcesContent":["import { createContext } from
|
|
1
|
+
{"version":3,"file":"provider.js","names":[],"sources":["../src/context.ts","../src/provider.ts"],"sourcesContent":["import { createContext } from '@pyreon/core'\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript'\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n 'http-equiv'?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: 'high' | 'low' | 'auto'\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: '_blank' | '_self' | '_parent' | '_top'\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { ComponentFn, Props, VNodeChild } from '@pyreon/core'\nimport { provide } from '@pyreon/core'\nimport type { HeadContextValue } from './context'\nimport { createHeadContext, HeadContext } from './context'\n\nexport interface HeadProviderProps extends Props {\n context?: HeadContextValue | undefined\n children?: VNodeChild\n}\n\n/**\n * Provides a HeadContextValue to all descendant components.\n * Wrap your app root with this to enable useHead() throughout the tree.\n *\n * If no `context` prop is passed, a new HeadContext is created automatically.\n *\n * @example\n * // Auto-create context:\n * <HeadProvider><App /></HeadProvider>\n *\n * // Explicit context (e.g. for SSR):\n * const headCtx = createHeadContext()\n * mount(h(HeadProvider, { context: headCtx }, h(App, null)), root)\n */\nexport const HeadProvider: ComponentFn<HeadProviderProps> = (props) => {\n const ctx = props.context ?? createHeadContext()\n provide(HeadContext, ctx)\n\n const ch = props.children\n return typeof ch === 'function' ? (ch as () => VNodeChild)() : ch\n}\n"],"mappings":";;;AAqKA,SAAgB,oBAAsC;CACpD,MAAM,sBAAM,IAAI,KAAwB;CAGxC,IAAI,QAAQ;CACZ,IAAI,aAAwB,EAAE;CAC9B,IAAI;CACJ,IAAI,kBAA0C,EAAE;CAChD,IAAI,kBAA0C,EAAE;CAEhD,SAAS,UAAgB;AACvB,MAAI,CAAC,MAAO;AACZ,UAAQ;EAER,MAAM,wBAAQ,IAAI,KAAsB;EACxC,MAAM,UAAqB,EAAE;EAC7B,IAAI;EACJ,MAAM,YAAoC,EAAE;EAC5C,MAAM,YAAoC,EAAE;AAE5C,OAAK,MAAM,SAAS,IAAI,QAAQ,EAAE;AAChC,QAAK,MAAM,OAAO,MAAM,KACtB,KAAI,IAAI,IAAK,OAAM,IAAI,IAAI,KAAK,IAAI;OAC/B,SAAQ,KAAK,IAAI;AAExB,OAAI,MAAM,kBAAkB,OAAW,iBAAgB,MAAM;AAC7D,OAAI,MAAM,UAAW,QAAO,OAAO,WAAW,MAAM,UAAU;AAC9D,OAAI,MAAM,UAAW,QAAO,OAAO,WAAW,MAAM,UAAU;;AAGhE,eAAa,CAAC,GAAG,MAAM,QAAQ,EAAE,GAAG,QAAQ;AAC5C,wBAAsB;AACtB,oBAAkB;AAClB,oBAAkB;;AAGpB,QAAO;EACL,IAAI,IAAI,OAAO;AACb,OAAI,IAAI,IAAI,MAAM;AAClB,WAAQ;;EAEV,OAAO,IAAI;AACT,OAAI,OAAO,GAAG;AACd,WAAQ;;EAEV,UAAU;AACR,YAAS;AACT,UAAO;;EAET,uBAAuB;AACrB,YAAS;AACT,UAAO;;EAET,mBAAmB;AACjB,YAAS;AACT,UAAO;;EAET,mBAAmB;AACjB,YAAS;AACT,UAAO;;EAEV;;AAGH,MAAa,cAAc,cAAuC,KAAK;;;;;;;;;;;;;;;;;;AC7MvE,MAAa,gBAAgD,UAAU;AAErE,SAAQ,aADI,MAAM,WAAW,mBAAmB,CACvB;CAEzB,MAAM,KAAK,MAAM;AACjB,QAAO,OAAO,OAAO,aAAc,IAAyB,GAAG"}
|
package/lib/ssr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.js","names":[],"sources":["../src/context.ts","../src/ssr.ts"],"sourcesContent":["import { createContext } from \"@pyreon/core\"\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: \"title\" | \"meta\" | \"link\" | \"script\" | \"style\" | \"base\" | \"noscript\"\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n \"http-equiv\"?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: \"high\" | \"low\" | \"auto\"\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\"\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { ComponentFn, VNode } from \"@pyreon/core\"\nimport { h, pushContext } from \"@pyreon/core\"\nimport { renderToString } from \"@pyreon/runtime-server\"\nimport type { HeadTag } from \"./context\"\nimport { createHeadContext, HeadContext } from \"./context\"\n\nconst VOID_TAGS = new Set([\"meta\", \"link\", \"base\"])\n\n/**\n * Render a Pyreon app to an HTML fragment + a serialized <head> string.\n *\n * The returned `head` string can be injected directly into your HTML template:\n *\n * @example\n * const { html, head } = await renderWithHead(h(App, null))\n * const page = `<!DOCTYPE html>\n * <html>\n * <head>\n * <meta charset=\"UTF-8\" />\n * ${head}\n * </head>\n * <body><div id=\"app\">${html}</div></body>\n * </html>`\n */\nexport interface RenderWithHeadResult {\n html: string\n head: string\n /** Attributes to set on the <html> element */\n htmlAttrs: Record<string, string>\n /** Attributes to set on the <body> element */\n bodyAttrs: Record<string, string>\n}\n\nexport async function renderWithHead(app: VNode): Promise<RenderWithHeadResult> {\n const ctx = createHeadContext()\n\n // HeadInjector runs inside renderToString's ALS scope, so pushContext reaches\n // the per-request context stack rather than the module-level fallback stack.\n function HeadInjector(): VNode {\n pushContext(new Map([[HeadContext.id, ctx]]))\n return app\n }\n\n const html = await renderToString(h(HeadInjector as ComponentFn, null))\n const titleTemplate = ctx.resolveTitleTemplate()\n const head = ctx\n .resolve()\n .map((tag) => serializeTag(tag, titleTemplate))\n .join(\"\\n \")\n return {\n html,\n head,\n htmlAttrs: ctx.resolveHtmlAttrs(),\n bodyAttrs: ctx.resolveBodyAttrs(),\n }\n}\n\nfunction serializeTag(tag: HeadTag, titleTemplate?: string | ((title: string) => string)): string {\n if (tag.tag === \"title\") {\n const raw = tag.children || \"\"\n const title = titleTemplate\n ? typeof titleTemplate === \"function\"\n ? titleTemplate(raw)\n : titleTemplate.replace(/%s/g, raw)\n : raw\n return `<title>${esc(title)}</title>`\n }\n const props = tag.props as Record<string, string> | undefined\n const attrs = props\n ? Object.entries(props)\n .map(([k, v]) => `${k}=\"${esc(v)}\"`)\n .join(\" \")\n : \"\"\n const open = attrs ? `<${tag.tag} ${attrs}` : `<${tag.tag}`\n if (VOID_TAGS.has(tag.tag)) return `${open} />`\n const content = tag.children || \"\"\n // Escape sequences that could break out of script/style/noscript blocks:\n // 1. Closing tags like </script> — use Unicode escape in the slash\n // 2. HTML comment openers <!-- that could confuse parsers\n const body = content.replace(/<\\/(script|style|noscript)/gi, \"<\\\\/$1\").replace(/<!--/g, \"<\\\\!--\")\n return `${open}>${body}</${tag.tag}>`\n}\n\nconst ESC_RE = /[&<>\"]/g\nconst ESC_MAP: Record<string, string> = { \"&\": \"&\", \"<\": \"<\", \">\": \">\", '\"': \""\" }\n\nfunction esc(s: string): string {\n return ESC_RE.test(s) ? s.replace(ESC_RE, (ch) => ESC_MAP[ch] as string) : s\n}\n"],"mappings":";;;;AAqKA,SAAgB,oBAAsC;CACpD,MAAM,sBAAM,IAAI,KAAwB;CAGxC,IAAI,Q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;AAC7C,SAAO;;CAGT,MAAM,OAAO,MAAM,eAAe,EAAE,cAA6B,KAAK,CAAC;CACvE,MAAM,gBAAgB,IAAI,sBAAsB;AAKhD,QAAO;EACL;EACA,MANW,IACV,SAAS,CACT,KAAK,QAAQ,aAAa,KAAK,cAAc,CAAC,CAC9C,KAAK,OAAO;EAIb,WAAW,IAAI,kBAAkB;EACjC,WAAW,IAAI,kBAAkB;EAClC;;AAGH,SAAS,aAAa,KAAc,eAA8D;AAChG,KAAI,IAAI,QAAQ,SAAS;EACvB,MAAM,MAAM,IAAI,YAAY;AAM5B,SAAO,UAAU,IALH,gBACV,OAAO,kBAAkB,aACvB,cAAc,IAAI,GAClB,cAAc,QAAQ,OAAO,IAAI,GACnC,IACuB,CAAC;;CAE9B,MAAM,QAAQ,IAAI;CAClB,MAAM,QAAQ,QACV,OAAO,QAAQ,MAAM,CAClB,KAAK,CAAC,GAAG,OAAO,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,GAAG,CACnC,KAAK,IAAI,GACZ;CACJ,MAAM,OAAO,QAAQ,IAAI,IAAI,IAAI,GAAG,UAAU,IAAI,IAAI;AACtD,KAAI,UAAU,IAAI,IAAI,IAAI,CAAE,QAAO,GAAG,KAAK;AAM3C,QAAO,GAAG,KAAK,IALC,IAAI,YAAY,IAIX,QAAQ,gCAAgC,SAAS,CAAC,QAAQ,SAAS,SAAS,CAC1E,IAAI,IAAI,IAAI;;AAGrC,MAAM,SAAS;AACf,MAAM,UAAkC;CAAE,KAAK;CAAS,KAAK;CAAQ,KAAK;CAAQ,MAAK;CAAU;AAEjG,SAAS,IAAI,GAAmB;AAC9B,QAAO,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,SAAS,OAAO,QAAQ,IAAc,GAAG"}
|
|
1
|
+
{"version":3,"file":"ssr.js","names":[],"sources":["../src/context.ts","../src/ssr.ts"],"sourcesContent":["import { createContext } from '@pyreon/core'\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript'\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n 'http-equiv'?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: 'high' | 'low' | 'auto'\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: '_blank' | '_self' | '_parent' | '_top'\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { ComponentFn, VNode } from '@pyreon/core'\nimport { h, pushContext } from '@pyreon/core'\nimport { renderToString } from '@pyreon/runtime-server'\nimport type { HeadTag } from './context'\nimport { createHeadContext, HeadContext } from './context'\n\nconst VOID_TAGS = new Set(['meta', 'link', 'base'])\n\n/**\n * Render a Pyreon app to an HTML fragment + a serialized <head> string.\n *\n * The returned `head` string can be injected directly into your HTML template:\n *\n * @example\n * const { html, head } = await renderWithHead(h(App, null))\n * const page = `<!DOCTYPE html>\n * <html>\n * <head>\n * <meta charset=\"UTF-8\" />\n * ${head}\n * </head>\n * <body><div id=\"app\">${html}</div></body>\n * </html>`\n */\nexport interface RenderWithHeadResult {\n html: string\n head: string\n /** Attributes to set on the <html> element */\n htmlAttrs: Record<string, string>\n /** Attributes to set on the <body> element */\n bodyAttrs: Record<string, string>\n}\n\nexport async function renderWithHead(app: VNode): Promise<RenderWithHeadResult> {\n const ctx = createHeadContext()\n\n // HeadInjector runs inside renderToString's ALS scope, so pushContext reaches\n // the per-request context stack rather than the module-level fallback stack.\n function HeadInjector(): VNode {\n pushContext(new Map([[HeadContext.id, ctx]]))\n return app\n }\n\n const html = await renderToString(h(HeadInjector as ComponentFn, null))\n const titleTemplate = ctx.resolveTitleTemplate()\n const head = ctx\n .resolve()\n .map((tag) => serializeTag(tag, titleTemplate))\n .join('\\n ')\n return {\n html,\n head,\n htmlAttrs: ctx.resolveHtmlAttrs(),\n bodyAttrs: ctx.resolveBodyAttrs(),\n }\n}\n\nfunction serializeTag(tag: HeadTag, titleTemplate?: string | ((title: string) => string)): string {\n if (tag.tag === 'title') {\n const raw = tag.children || ''\n const title = titleTemplate\n ? typeof titleTemplate === 'function'\n ? titleTemplate(raw)\n : titleTemplate.replace(/%s/g, raw)\n : raw\n return `<title>${esc(title)}</title>`\n }\n const props = tag.props as Record<string, string> | undefined\n const attrs = props\n ? Object.entries(props)\n .map(([k, v]) => `${k}=\"${esc(v)}\"`)\n .join(' ')\n : ''\n const open = attrs ? `<${tag.tag} ${attrs}` : `<${tag.tag}`\n if (VOID_TAGS.has(tag.tag)) return `${open} />`\n const content = tag.children || ''\n // Escape sequences that could break out of script/style/noscript blocks:\n // 1. Closing tags like </script> — use Unicode escape in the slash\n // 2. HTML comment openers <!-- that could confuse parsers\n const body = content.replace(/<\\/(script|style|noscript)/gi, '<\\\\/$1').replace(/<!--/g, '<\\\\!--')\n return `${open}>${body}</${tag.tag}>`\n}\n\nconst ESC_RE = /[&<>\"]/g\nconst ESC_MAP: Record<string, string> = { '&': '&', '<': '<', '>': '>', '\"': '"' }\n\nfunction esc(s: string): string {\n return ESC_RE.test(s) ? s.replace(ESC_RE, (ch) => ESC_MAP[ch] as string) : s\n}\n"],"mappings":";;;;AAqKA,SAAgB,oBAAsC;CACpD,MAAM,sBAAM,IAAI,KAAwB;CAGxC,IAAI,QAAQ;CACZ,IAAI,aAAwB,EAAE;CAC9B,IAAI;CACJ,IAAI,kBAA0C,EAAE;CAChD,IAAI,kBAA0C,EAAE;CAEhD,SAAS,UAAgB;AACvB,MAAI,CAAC,MAAO;AACZ,UAAQ;EAER,MAAM,wBAAQ,IAAI,KAAsB;EACxC,MAAM,UAAqB,EAAE;EAC7B,IAAI;EACJ,MAAM,YAAoC,EAAE;EAC5C,MAAM,YAAoC,EAAE;AAE5C,OAAK,MAAM,SAAS,IAAI,QAAQ,EAAE;AAChC,QAAK,MAAM,OAAO,MAAM,KACtB,KAAI,IAAI,IAAK,OAAM,IAAI,IAAI,KAAK,IAAI;OAC/B,SAAQ,KAAK,IAAI;AAExB,OAAI,MAAM,kBAAkB,OAAW,iBAAgB,MAAM;AAC7D,OAAI,MAAM,UAAW,QAAO,OAAO,WAAW,MAAM,UAAU;AAC9D,OAAI,MAAM,UAAW,QAAO,OAAO,WAAW,MAAM,UAAU;;AAGhE,eAAa,CAAC,GAAG,MAAM,QAAQ,EAAE,GAAG,QAAQ;AAC5C,wBAAsB;AACtB,oBAAkB;AAClB,oBA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AU,IAAI,IAAI;AACtD,KAAI,UAAU,IAAI,IAAI,IAAI,CAAE,QAAO,GAAG,KAAK;AAM3C,QAAO,GAAG,KAAK,IALC,IAAI,YAAY,IAIX,QAAQ,gCAAgC,SAAS,CAAC,QAAQ,SAAS,SAAS,CAC1E,IAAI,IAAI,IAAI;;AAGrC,MAAM,SAAS;AACf,MAAM,UAAkC;CAAE,KAAK;CAAS,KAAK;CAAQ,KAAK;CAAQ,MAAK;CAAU;AAEjG,SAAS,IAAI,GAAmB;AAC9B,QAAO,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,SAAS,OAAO,QAAQ,IAAc,GAAG"}
|
package/lib/types/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { ComponentFn, Props, VNodeChild } from "@pyreon/core";
|
|
|
4
4
|
//#region src/context.d.ts
|
|
5
5
|
interface HeadTag {
|
|
6
6
|
/** HTML tag name */
|
|
7
|
-
tag:
|
|
7
|
+
tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript';
|
|
8
8
|
/**
|
|
9
9
|
* Deduplication key. Tags with the same key replace each other;
|
|
10
10
|
* innermost component (last added) wins.
|
|
@@ -23,7 +23,7 @@ interface MetaTag {
|
|
|
23
23
|
/** Open Graph / social property (e.g. "og:title", "twitter:card") */
|
|
24
24
|
property?: string;
|
|
25
25
|
/** HTTP equivalent header (e.g. "refresh", "content-type") */
|
|
26
|
-
|
|
26
|
+
'http-equiv'?: string;
|
|
27
27
|
/** Value associated with name, property, or http-equiv */
|
|
28
28
|
content?: string;
|
|
29
29
|
/** Document character encoding (e.g. "utf-8") */
|
|
@@ -56,7 +56,7 @@ interface LinkTag {
|
|
|
56
56
|
/** Title for the link (used for alternate stylesheets) */
|
|
57
57
|
title?: string;
|
|
58
58
|
/** Fetch priority hint */
|
|
59
|
-
fetchpriority?:
|
|
59
|
+
fetchpriority?: 'high' | 'low' | 'auto';
|
|
60
60
|
/** Referrer policy */
|
|
61
61
|
referrerpolicy?: string;
|
|
62
62
|
/** Image source set for preloading responsive images */
|
|
@@ -109,7 +109,7 @@ interface BaseTag {
|
|
|
109
109
|
/** Base URL for relative URLs in the document */
|
|
110
110
|
href?: string;
|
|
111
111
|
/** Default target for links and forms */
|
|
112
|
-
target?:
|
|
112
|
+
target?: '_blank' | '_self' | '_parent' | '_top';
|
|
113
113
|
}
|
|
114
114
|
interface UseHeadInput {
|
|
115
115
|
title?: string;
|
package/lib/types/provider.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ComponentFn, Props, VNodeChild } from "@pyreon/core";
|
|
|
3
3
|
//#region src/context.d.ts
|
|
4
4
|
interface HeadTag {
|
|
5
5
|
/** HTML tag name */
|
|
6
|
-
tag:
|
|
6
|
+
tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript';
|
|
7
7
|
/**
|
|
8
8
|
* Deduplication key. Tags with the same key replace each other;
|
|
9
9
|
* innermost component (last added) wins.
|
package/lib/types/use-head.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ interface MetaTag {
|
|
|
6
6
|
/** Open Graph / social property (e.g. "og:title", "twitter:card") */
|
|
7
7
|
property?: string;
|
|
8
8
|
/** HTTP equivalent header (e.g. "refresh", "content-type") */
|
|
9
|
-
|
|
9
|
+
'http-equiv'?: string;
|
|
10
10
|
/** Value associated with name, property, or http-equiv */
|
|
11
11
|
content?: string;
|
|
12
12
|
/** Document character encoding (e.g. "utf-8") */
|
|
@@ -39,7 +39,7 @@ interface LinkTag {
|
|
|
39
39
|
/** Title for the link (used for alternate stylesheets) */
|
|
40
40
|
title?: string;
|
|
41
41
|
/** Fetch priority hint */
|
|
42
|
-
fetchpriority?:
|
|
42
|
+
fetchpriority?: 'high' | 'low' | 'auto';
|
|
43
43
|
/** Referrer policy */
|
|
44
44
|
referrerpolicy?: string;
|
|
45
45
|
/** Image source set for preloading responsive images */
|
|
@@ -92,7 +92,7 @@ interface BaseTag {
|
|
|
92
92
|
/** Base URL for relative URLs in the document */
|
|
93
93
|
href?: string;
|
|
94
94
|
/** Default target for links and forms */
|
|
95
|
-
target?:
|
|
95
|
+
target?: '_blank' | '_self' | '_parent' | '_top';
|
|
96
96
|
}
|
|
97
97
|
interface UseHeadInput {
|
|
98
98
|
title?: string;
|
package/lib/use-head.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-head.js","names":[],"sources":["../src/context.ts","../src/dom.ts","../src/use-head.ts"],"sourcesContent":["import { createContext } from \"@pyreon/core\"\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: \"title\" | \"meta\" | \"link\" | \"script\" | \"style\" | \"base\" | \"noscript\"\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n \"http-equiv\"?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: \"high\" | \"low\" | \"auto\"\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\"\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { HeadContextValue } from \"./context\"\n\nconst ATTR = \"data-pyreon-head\"\n\n/** Tracks managed elements by key — avoids querySelectorAll on every sync */\nconst managedElements = new Map<string, Element>()\n\n/**\n * Sync the resolved head tags to the real DOM <head>.\n * Uses incremental diffing: matches existing elements by key, patches attributes\n * in-place, adds new elements, and removes stale ones.\n * Also syncs htmlAttrs, bodyAttrs, and applies titleTemplate.\n * No-op on the server (typeof document === \"undefined\").\n */\nfunction patchExistingTag(\n found: Element,\n tag: { props: Record<string, unknown>; children: string },\n kept: Set<string>,\n): void {\n kept.add(found.getAttribute(ATTR) as string)\n patchAttrs(found, tag.props as Record<string, string>)\n const content = String(tag.children)\n if (found.textContent !== content) found.textContent = content\n}\n\nfunction createNewTag(tag: {\n tag: string\n props: Record<string, unknown>\n children: string\n key: unknown\n}): void {\n const el = document.createElement(tag.tag)\n const key = tag.key as string\n el.setAttribute(ATTR, key)\n for (const [k, v] of Object.entries(tag.props as Record<string, string>)) {\n el.setAttribute(k, v)\n }\n if (tag.children) el.textContent = tag.children\n document.head.appendChild(el)\n managedElements.set(key, el)\n}\n\nexport function syncDom(ctx: HeadContextValue): void {\n if (typeof document === \"undefined\") return\n\n const tags = ctx.resolve()\n const titleTemplate = ctx.resolveTitleTemplate()\n\n // Seed from DOM on first sync, or re-seed if DOM was reset (e.g. between tests)\n let needsSeed = managedElements.size === 0\n if (!needsSeed) {\n // Check if a tracked element is still in the DOM\n const sample = managedElements.values().next().value\n if (sample && !sample.isConnected) {\n managedElements.clear()\n needsSeed = true\n }\n }\n if (needsSeed) {\n const existing = document.head.querySelectorAll(`[${ATTR}]`)\n for (const el of existing) {\n managedElements.set(el.getAttribute(ATTR) as string, el)\n }\n }\n\n const kept = new Set<string>()\n\n for (const tag of tags) {\n if (tag.tag === \"title\") {\n document.title = applyTitleTemplate(String(tag.children), titleTemplate)\n continue\n }\n\n const key = tag.key as string\n const found = managedElements.get(key)\n\n if (found && found.tagName.toLowerCase() === tag.tag) {\n patchExistingTag(found, tag as { props: Record<string, unknown>; children: string }, kept)\n } else {\n if (found) {\n found.remove()\n managedElements.delete(key)\n }\n createNewTag(\n tag as { tag: string; props: Record<string, unknown>; children: string; key: unknown },\n )\n kept.add(key)\n }\n }\n\n // Remove stale elements\n for (const [key, el] of managedElements) {\n if (!kept.has(key)) {\n el.remove()\n managedElements.delete(key)\n }\n }\n\n syncElementAttrs(document.documentElement, ctx.resolveHtmlAttrs())\n syncElementAttrs(document.body, ctx.resolveBodyAttrs())\n}\n\n/** Patch an element's attributes to match the desired props. */\nfunction patchAttrs(el: Element, props: Record<string, string>): void {\n for (let i = el.attributes.length - 1; i >= 0; i--) {\n const attr = el.attributes[i]\n if (!attr || attr.name === ATTR) continue\n if (!(attr.name in props)) el.removeAttribute(attr.name)\n }\n for (const [k, v] of Object.entries(props)) {\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n}\n\nfunction applyTitleTemplate(\n title: string,\n template: string | ((t: string) => string) | undefined,\n): string {\n if (!template) return title\n if (typeof template === \"function\") return template(title)\n return template.replace(/%s/g, title)\n}\n\n/** Sync pyreon-managed attributes on <html> or <body>. */\nfunction syncElementAttrs(el: Element, attrs: Record<string, string>): void {\n // Remove previously managed attrs that are no longer present\n const managed = el.getAttribute(`${ATTR}-attrs`)\n if (managed) {\n for (const name of managed.split(\",\")) {\n if (name && !(name in attrs)) el.removeAttribute(name)\n }\n }\n const keys: string[] = []\n for (const [k, v] of Object.entries(attrs)) {\n keys.push(k)\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n if (keys.length > 0) {\n el.setAttribute(`${ATTR}-attrs`, keys.join(\",\"))\n } else if (managed) {\n el.removeAttribute(`${ATTR}-attrs`)\n }\n}\n","import { onMount, onUnmount, useContext } from \"@pyreon/core\"\nimport { effect } from \"@pyreon/reactivity\"\nimport type { HeadEntry, HeadTag, UseHeadInput } from \"./context\"\nimport { HeadContext } from \"./context\"\nimport { syncDom } from \"./dom\"\n\n/** Cast a strict tag interface to the internal props format, stripping undefined values */\nfunction toProps(obj: Record<string, string | undefined>): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) result[k] = v\n }\n return result\n}\n\nfunction buildEntry(o: UseHeadInput): HeadEntry {\n const tags: HeadTag[] = []\n if (o.title != null) tags.push({ tag: \"title\", key: \"title\", children: o.title })\n o.meta?.forEach((m, i) => {\n tags.push({\n tag: \"meta\",\n key: m.name ?? m.property ?? `meta-${i}`,\n props: toProps(m as Record<string, string | undefined>),\n })\n })\n o.link?.forEach((l, i) => {\n tags.push({\n tag: \"link\",\n key: l.href ? `link-${l.rel || \"\"}-${l.href}` : l.rel ? `link-${l.rel}` : `link-${i}`,\n props: toProps(l as Record<string, string | undefined>),\n })\n })\n o.script?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: \"script\",\n key: s.src ?? `script-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n ...(children != null ? { children } : {}),\n })\n })\n o.style?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: \"style\",\n key: `style-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n children,\n })\n })\n o.noscript?.forEach((ns, i) => {\n tags.push({ tag: \"noscript\", key: `noscript-${i}`, children: ns.children })\n })\n if (o.jsonLd) {\n tags.push({\n tag: \"script\",\n key: \"jsonld\",\n props: { type: \"application/ld+json\" },\n children: JSON.stringify(o.jsonLd),\n })\n }\n if (o.base)\n tags.push({\n tag: \"base\",\n key: \"base\",\n props: toProps(o.base as Record<string, string | undefined>),\n })\n return {\n tags,\n titleTemplate: o.titleTemplate,\n htmlAttrs: o.htmlAttrs,\n bodyAttrs: o.bodyAttrs,\n }\n}\n\n/**\n * Register head tags (title, meta, link, script, style, noscript, base, jsonLd)\n * for the current component.\n *\n * Accepts a static object or a reactive getter:\n * useHead({ title: \"My Page\", meta: [{ name: \"description\", content: \"...\" }] })\n * useHead(() => ({ title: `${count()} items` })) // updates when signal changes\n *\n * Tags are deduplicated by key — innermost component wins.\n * Requires a <HeadProvider> (CSR) or renderWithHead() (SSR) ancestor.\n */\nexport function useHead(input: UseHeadInput | (() => UseHeadInput)): void {\n const ctx = useContext(HeadContext)\n if (!ctx) return // no HeadProvider — silently no-op\n\n const id = Symbol()\n\n if (typeof input === \"function\") {\n if (typeof document !== \"undefined\") {\n // CSR: reactive — re-register whenever signals change\n effect(() => {\n ctx.add(id, buildEntry(input()))\n syncDom(ctx)\n })\n } else {\n // SSR: evaluate once synchronously (no effects on server)\n ctx.add(id, buildEntry(input()))\n }\n } else {\n ctx.add(id, buildEntry(input))\n onMount(() => {\n syncDom(ctx)\n })\n }\n\n onUnmount(() => {\n ctx.remove(id)\n syncDom(ctx)\n })\n}\n"],"mappings":";;;;AAqOA,MAAa,cAAc,cAAuC,KAAK;;;;ACnOvE,MAAM,OAAO;;AAGb,MAAM,kCAAkB,IAAI,KAAsB;;;;;;;;AASlD,SAAS,iBACP,OACA,KACA,MACM;AACN,MAAK,IAAI,MAAM,aAAa,KAAK,CAAW;AAC5C,YAAW,OAAO,IAAI,MAAgC;CACtD,MAAM,UAAU,OAAO,IAAI,SAAS;AACpC,KAAI,MAAM,gBAAgB,QAAS,OAAM,cAAc;;AAGzD,SAAS,aAAa,KAKb;CACP,MAAM,KAAK,SAAS,cAAc,IAAI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AAE,OAAO;EACnC,CAAC;AAEJ,KAAI,EAAE,KACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,QAAQ,EAAE,KAA2C;EAC7D,CAAC;AACJ,QAAO;EACL;EACA,eAAe,EAAE;EACjB,WAAW,EAAE;EACb,WAAW,EAAE;EACd;;;;;;;;;;;;;AAcH,SAAgB,QAAQ,OAAkD;CACxE,MAAM,MAAM,WAAW,YAAY;AACnC,KAAI,CAAC,IAAK;CAEV,MAAM,KAAK,QAAQ;AAEnB,KAAI,OAAO,UAAU,WACnB,KAAI,OAAO,aAAa,YAEtB,cAAa;AACX,MAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;AAChC,UAAQ,IAAI;GACZ;KAGF,KAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;MAE7B;AACL,MAAI,IAAI,IAAI,WAAW,MAAM,CAAC;AAC9B,gBAAc;AACZ,WAAQ,IAAI;IACZ;;AAGJ,iBAAgB;AACd,MAAI,OAAO,GAAG;AACd,UAAQ,IAAI;GACZ"}
|
|
1
|
+
{"version":3,"file":"use-head.js","names":[],"sources":["../src/context.ts","../src/dom.ts","../src/use-head.ts"],"sourcesContent":["import { createContext } from '@pyreon/core'\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface HeadTag {\n /** HTML tag name */\n tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript'\n /**\n * Deduplication key. Tags with the same key replace each other;\n * innermost component (last added) wins.\n * Example: all components setting the page title use key \"title\".\n */\n key?: string\n /** HTML attributes for the tag */\n props?: Record<string, string>\n /** Text content — for <title>, <script>, <style>, <noscript> */\n children?: string\n}\n\n// ─── Strict tag types ────────────────────────────────────────────────────────\n\n/** Standard `<meta>` tag attributes. Catches typos like `{ naem: \"description\" }`. */\nexport interface MetaTag {\n /** Standard meta name (e.g. \"description\", \"viewport\", \"robots\") */\n name?: string\n /** Open Graph / social property (e.g. \"og:title\", \"twitter:card\") */\n property?: string\n /** HTTP equivalent header (e.g. \"refresh\", \"content-type\") */\n 'http-equiv'?: string\n /** Value associated with name, property, or http-equiv */\n content?: string\n /** Document character encoding (e.g. \"utf-8\") */\n charset?: string\n /** Schema.org itemprop */\n itemprop?: string\n /** Media condition for applicability (e.g. \"(prefers-color-scheme: dark)\") */\n media?: string\n}\n\n/** Standard `<link>` tag attributes. */\nexport interface LinkTag {\n /** Relationship to the current document (e.g. \"stylesheet\", \"icon\", \"canonical\") */\n rel?: string\n /** URL of the linked resource */\n href?: string\n /** Resource type hint for preloading (e.g. \"style\", \"script\", \"font\") */\n as?: string\n /** MIME type (e.g. \"text/css\", \"image/png\") */\n type?: string\n /** Media query for conditional loading */\n media?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Icon sizes (e.g. \"32x32\", \"any\") */\n sizes?: string\n /** Language of the linked resource */\n hreflang?: string\n /** Title for the link (used for alternate stylesheets) */\n title?: string\n /** Fetch priority hint */\n fetchpriority?: 'high' | 'low' | 'auto'\n /** Referrer policy */\n referrerpolicy?: string\n /** Image source set for preloading responsive images */\n imagesrcset?: string\n /** Image sizes for preloading responsive images */\n imagesizes?: string\n /** Disable the resource (for stylesheets) */\n disabled?: string\n /** Color for mask-icon */\n color?: string\n}\n\n/** Standard `<script>` tag attributes. */\nexport interface ScriptTag {\n /** External script URL */\n src?: string\n /** Script MIME type or module type (e.g. \"module\", \"importmap\") */\n type?: string\n /** Load asynchronously */\n async?: string\n /** Defer execution until document is parsed */\n defer?: string\n /** CORS mode */\n crossorigin?: string\n /** Subresource integrity hash */\n integrity?: string\n /** Exclude from module-supporting browsers */\n nomodule?: string\n /** Referrer policy */\n referrerpolicy?: string\n /** Fetch priority hint */\n fetchpriority?: string\n /** Inline script content */\n children?: string\n}\n\n/** Standard `<style>` tag attributes. */\nexport interface StyleTag {\n /** Inline CSS content (required) */\n children: string\n /** Media query for conditional styles */\n media?: string\n /** Nonce for CSP */\n nonce?: string\n /** Title for alternate stylesheets */\n title?: string\n /** Render-blocking behavior */\n blocking?: string\n}\n\n/** Standard `<base>` tag attributes. */\nexport interface BaseTag {\n /** Base URL for relative URLs in the document */\n href?: string\n /** Default target for links and forms */\n target?: '_blank' | '_self' | '_parent' | '_top'\n}\n\nexport interface UseHeadInput {\n title?: string\n /**\n * Title template — use `%s` as a placeholder for the page title.\n * Applied to the resolved title after deduplication.\n * @example useHead({ titleTemplate: \"%s | My App\" })\n */\n titleTemplate?: string | ((title: string) => string)\n meta?: MetaTag[]\n link?: LinkTag[]\n script?: ScriptTag[]\n style?: StyleTag[]\n noscript?: { children: string }[]\n /** Convenience: emits a <script type=\"application/ld+json\"> tag with JSON.stringify'd content */\n jsonLd?: Record<string, unknown> | Record<string, unknown>[]\n base?: BaseTag\n /** Attributes to set on the <html> element (e.g. { lang: \"en\", dir: \"ltr\" }) */\n htmlAttrs?: Record<string, string>\n /** Attributes to set on the <body> element (e.g. { class: \"dark\" }) */\n bodyAttrs?: Record<string, string>\n}\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface HeadEntry {\n tags: HeadTag[]\n titleTemplate?: string | ((title: string) => string) | undefined\n htmlAttrs?: Record<string, string> | undefined\n bodyAttrs?: Record<string, string> | undefined\n}\n\nexport interface HeadContextValue {\n add(id: symbol, entry: HeadEntry): void\n remove(id: symbol): void\n /** Returns deduplicated tags — last-added entry wins per key */\n resolve(): HeadTag[]\n /** Returns the merged titleTemplate (last-added wins) */\n resolveTitleTemplate(): (string | ((title: string) => string)) | undefined\n /** Returns merged htmlAttrs (later entries override earlier) */\n resolveHtmlAttrs(): Record<string, string>\n /** Returns merged bodyAttrs (later entries override earlier) */\n resolveBodyAttrs(): Record<string, string>\n}\n\nexport function createHeadContext(): HeadContextValue {\n const map = new Map<symbol, HeadEntry>()\n\n // ── Cached resolve ───────────────────────────────────────────────────────\n let dirty = true\n let cachedTags: HeadTag[] = []\n let cachedTitleTemplate: (string | ((title: string) => string)) | undefined\n let cachedHtmlAttrs: Record<string, string> = {}\n let cachedBodyAttrs: Record<string, string> = {}\n\n function rebuild(): void {\n if (!dirty) return\n dirty = false\n\n const keyed = new Map<string, HeadTag>()\n const unkeyed: HeadTag[] = []\n let titleTemplate: (string | ((title: string) => string)) | undefined\n const htmlAttrs: Record<string, string> = {}\n const bodyAttrs: Record<string, string> = {}\n\n for (const entry of map.values()) {\n for (const tag of entry.tags) {\n if (tag.key) keyed.set(tag.key, tag)\n else unkeyed.push(tag)\n }\n if (entry.titleTemplate !== undefined) titleTemplate = entry.titleTemplate\n if (entry.htmlAttrs) Object.assign(htmlAttrs, entry.htmlAttrs)\n if (entry.bodyAttrs) Object.assign(bodyAttrs, entry.bodyAttrs)\n }\n\n cachedTags = [...keyed.values(), ...unkeyed]\n cachedTitleTemplate = titleTemplate\n cachedHtmlAttrs = htmlAttrs\n cachedBodyAttrs = bodyAttrs\n }\n\n return {\n add(id, entry) {\n map.set(id, entry)\n dirty = true\n },\n remove(id) {\n map.delete(id)\n dirty = true\n },\n resolve() {\n rebuild()\n return cachedTags\n },\n resolveTitleTemplate() {\n rebuild()\n return cachedTitleTemplate\n },\n resolveHtmlAttrs() {\n rebuild()\n return cachedHtmlAttrs\n },\n resolveBodyAttrs() {\n rebuild()\n return cachedBodyAttrs\n },\n }\n}\n\nexport const HeadContext = createContext<HeadContextValue | null>(null)\n","import type { HeadContextValue } from './context'\n\nconst ATTR = 'data-pyreon-head'\n\n/** Tracks managed elements by key — avoids querySelectorAll on every sync */\nconst managedElements = new Map<string, Element>()\n\n/**\n * Sync the resolved head tags to the real DOM <head>.\n * Uses incremental diffing: matches existing elements by key, patches attributes\n * in-place, adds new elements, and removes stale ones.\n * Also syncs htmlAttrs, bodyAttrs, and applies titleTemplate.\n * No-op on the server (typeof document === \"undefined\").\n */\nfunction patchExistingTag(\n found: Element,\n tag: { props: Record<string, unknown>; children: string },\n kept: Set<string>,\n): void {\n kept.add(found.getAttribute(ATTR) as string)\n patchAttrs(found, tag.props as Record<string, string>)\n const content = String(tag.children)\n if (found.textContent !== content) found.textContent = content\n}\n\nfunction createNewTag(tag: {\n tag: string\n props: Record<string, unknown>\n children: string\n key: unknown\n}): void {\n const el = document.createElement(tag.tag)\n const key = tag.key as string\n el.setAttribute(ATTR, key)\n for (const [k, v] of Object.entries(tag.props as Record<string, string>)) {\n el.setAttribute(k, v)\n }\n if (tag.children) el.textContent = tag.children\n document.head.appendChild(el)\n managedElements.set(key, el)\n}\n\nexport function syncDom(ctx: HeadContextValue): void {\n if (typeof document === 'undefined') return\n\n const tags = ctx.resolve()\n const titleTemplate = ctx.resolveTitleTemplate()\n\n // Seed from DOM on first sync, or re-seed if DOM was reset (e.g. between tests)\n let needsSeed = managedElements.size === 0\n if (!needsSeed) {\n // Check if a tracked element is still in the DOM\n const sample = managedElements.values().next().value\n if (sample && !sample.isConnected) {\n managedElements.clear()\n needsSeed = true\n }\n }\n if (needsSeed) {\n const existing = document.head.querySelectorAll(`[${ATTR}]`)\n for (const el of existing) {\n managedElements.set(el.getAttribute(ATTR) as string, el)\n }\n }\n\n const kept = new Set<string>()\n\n for (const tag of tags) {\n if (tag.tag === 'title') {\n document.title = applyTitleTemplate(String(tag.children), titleTemplate)\n continue\n }\n\n const key = tag.key as string\n const found = managedElements.get(key)\n\n if (found && found.tagName.toLowerCase() === tag.tag) {\n patchExistingTag(found, tag as { props: Record<string, unknown>; children: string }, kept)\n } else {\n if (found) {\n found.remove()\n managedElements.delete(key)\n }\n createNewTag(\n tag as { tag: string; props: Record<string, unknown>; children: string; key: unknown },\n )\n kept.add(key)\n }\n }\n\n // Remove stale elements\n for (const [key, el] of managedElements) {\n if (!kept.has(key)) {\n el.remove()\n managedElements.delete(key)\n }\n }\n\n syncElementAttrs(document.documentElement, ctx.resolveHtmlAttrs())\n syncElementAttrs(document.body, ctx.resolveBodyAttrs())\n}\n\n/** Patch an element's attributes to match the desired props. */\nfunction patchAttrs(el: Element, props: Record<string, string>): void {\n for (let i = el.attributes.length - 1; i >= 0; i--) {\n const attr = el.attributes[i]\n if (!attr || attr.name === ATTR) continue\n if (!(attr.name in props)) el.removeAttribute(attr.name)\n }\n for (const [k, v] of Object.entries(props)) {\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n}\n\nfunction applyTitleTemplate(\n title: string,\n template: string | ((t: string) => string) | undefined,\n): string {\n if (!template) return title\n if (typeof template === 'function') return template(title)\n return template.replace(/%s/g, title)\n}\n\n/** Sync pyreon-managed attributes on <html> or <body>. */\nfunction syncElementAttrs(el: Element, attrs: Record<string, string>): void {\n // Remove previously managed attrs that are no longer present\n const managed = el.getAttribute(`${ATTR}-attrs`)\n if (managed) {\n for (const name of managed.split(',')) {\n if (name && !(name in attrs)) el.removeAttribute(name)\n }\n }\n const keys: string[] = []\n for (const [k, v] of Object.entries(attrs)) {\n keys.push(k)\n if (el.getAttribute(k) !== v) el.setAttribute(k, v)\n }\n if (keys.length > 0) {\n el.setAttribute(`${ATTR}-attrs`, keys.join(','))\n } else if (managed) {\n el.removeAttribute(`${ATTR}-attrs`)\n }\n}\n","import { onMount, onUnmount, useContext } from '@pyreon/core'\nimport { effect } from '@pyreon/reactivity'\nimport type { HeadEntry, HeadTag, UseHeadInput } from './context'\nimport { HeadContext } from './context'\nimport { syncDom } from './dom'\n\n/** Cast a strict tag interface to the internal props format, stripping undefined values */\nfunction toProps(obj: Record<string, string | undefined>): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined) result[k] = v\n }\n return result\n}\n\nfunction buildEntry(o: UseHeadInput): HeadEntry {\n const tags: HeadTag[] = []\n if (o.title != null) tags.push({ tag: 'title', key: 'title', children: o.title })\n o.meta?.forEach((m, i) => {\n tags.push({\n tag: 'meta',\n key: m.name ?? m.property ?? `meta-${i}`,\n props: toProps(m as Record<string, string | undefined>),\n })\n })\n o.link?.forEach((l, i) => {\n tags.push({\n tag: 'link',\n key: l.href ? `link-${l.rel || ''}-${l.href}` : l.rel ? `link-${l.rel}` : `link-${i}`,\n props: toProps(l as Record<string, string | undefined>),\n })\n })\n o.script?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: 'script',\n key: s.src ?? `script-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n ...(children != null ? { children } : {}),\n })\n })\n o.style?.forEach((s, i) => {\n const { children, ...rest } = s\n tags.push({\n tag: 'style',\n key: `style-${i}`,\n props: toProps(rest as Record<string, string | undefined>),\n children,\n })\n })\n o.noscript?.forEach((ns, i) => {\n tags.push({ tag: 'noscript', key: `noscript-${i}`, children: ns.children })\n })\n if (o.jsonLd) {\n tags.push({\n tag: 'script',\n key: 'jsonld',\n props: { type: 'application/ld+json' },\n children: JSON.stringify(o.jsonLd),\n })\n }\n if (o.base)\n tags.push({\n tag: 'base',\n key: 'base',\n props: toProps(o.base as Record<string, string | undefined>),\n })\n return {\n tags,\n titleTemplate: o.titleTemplate,\n htmlAttrs: o.htmlAttrs,\n bodyAttrs: o.bodyAttrs,\n }\n}\n\n/**\n * Register head tags (title, meta, link, script, style, noscript, base, jsonLd)\n * for the current component.\n *\n * Accepts a static object or a reactive getter:\n * useHead({ title: \"My Page\", meta: [{ name: \"description\", content: \"...\" }] })\n * useHead(() => ({ title: `${count()} items` })) // updates when signal changes\n *\n * Tags are deduplicated by key — innermost component wins.\n * Requires a <HeadProvider> (CSR) or renderWithHead() (SSR) ancestor.\n */\nexport function useHead(input: UseHeadInput | (() => UseHeadInput)): void {\n const ctx = useContext(HeadContext)\n if (!ctx) return // no HeadProvider — silently no-op\n\n const id = Symbol()\n\n if (typeof input === 'function') {\n if (typeof document !== 'undefined') {\n // CSR: reactive — re-register whenever signals change\n effect(() => {\n ctx.add(id, buildEntry(input()))\n syncDom(ctx)\n })\n } else {\n // SSR: evaluate once synchronously (no effects on server)\n ctx.add(id, buildEntry(input()))\n }\n } else {\n ctx.add(id, buildEntry(input))\n onMount(() => {\n syncDom(ctx)\n })\n }\n\n onUnmount(() => {\n ctx.remove(id)\n sy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,GAAG,MAAM;EACzB,MAAM,EAAE,UAAU,GAAG,SAAS;AAC9B,OAAK,KAAK;GACR,KAAK;GACL,KAAK,SAAS;GACd,OAAO,QAAQ,KAA2C;GAC1D;GACD,CAAC;GACF;AACF,GAAE,UAAU,SAAS,IAAI,MAAM;AAC7B,OAAK,KAAK;GAAE,KAAK;GAAY,KAAK,YAAY;GAAK,UAAU,GAAG;GAAU,CAAC;GAC3E;AACF,KAAI,EAAE,OACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,EAAE,MAAM,uBAAuB;EACtC,UAAU,KAAK,UAAU,EAAE,OAAO;EACnC,CAAC;AAEJ,KAAI,EAAE,KACJ,MAAK,KAAK;EACR,KAAK;EACL,KAAK;EACL,OAAO,QAAQ,EAAE,KAA2C;EAC7D,CAAC;AACJ,QAAO;EACL;EACA,eAAe,EAAE;EACjB,WAAW,EAAE;EACb,WAAW,EAAE;EACd;;;;;;;;;;;;;AAcH,SAAgB,QAAQ,OAAkD;CACxE,MAAM,MAAM,WAAW,YAAY;AACnC,KAAI,CAAC,IAAK;CAEV,MAAM,KAAK,QAAQ;AAEnB,KAAI,OAAO,UAAU,WACnB,KAAI,OAAO,aAAa,YAEtB,cAAa;AACX,MAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;AAChC,UAAQ,IAAI;GACZ;KAGF,KAAI,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;MAE7B;AACL,MAAI,IAAI,IAAI,WAAW,MAAM,CAAC;AAC9B,gBAAc;AACZ,WAAQ,IAAI;IACZ;;AAGJ,iBAAgB;AACd,MAAI,OAAO,GAAG;AACd,UAAQ,IAAI;GACZ"}
|
package/package.json
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pyreon/head",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.7",
|
|
4
4
|
"description": "Head tag management for Pyreon — works in SSR and CSR",
|
|
5
|
+
"homepage": "https://github.com/pyreon/pyreon/tree/main/packages/head#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/pyreon/pyreon/issues"
|
|
8
|
+
},
|
|
5
9
|
"license": "MIT",
|
|
6
10
|
"repository": {
|
|
7
11
|
"type": "git",
|
|
8
12
|
"url": "https://github.com/pyreon/pyreon.git",
|
|
9
13
|
"directory": "packages/core/head"
|
|
10
14
|
},
|
|
11
|
-
"homepage": "https://github.com/pyreon/pyreon/tree/main/packages/head#readme",
|
|
12
|
-
"bugs": {
|
|
13
|
-
"url": "https://github.com/pyreon/pyreon/issues"
|
|
14
|
-
},
|
|
15
15
|
"files": [
|
|
16
16
|
"lib",
|
|
17
17
|
"src",
|
|
18
18
|
"README.md",
|
|
19
19
|
"LICENSE"
|
|
20
20
|
],
|
|
21
|
-
"sideEffects": false,
|
|
22
21
|
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
23
|
"main": "./lib/index.js",
|
|
24
24
|
"module": "./lib/index.js",
|
|
25
25
|
"types": "./lib/types/index.d.ts",
|
|
@@ -45,32 +45,32 @@
|
|
|
45
45
|
"types": "./lib/types/ssr.d.ts"
|
|
46
46
|
}
|
|
47
47
|
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
48
51
|
"scripts": {
|
|
49
52
|
"build": "vl_rolldown_build",
|
|
50
53
|
"dev": "vl_rolldown_build-watch",
|
|
51
54
|
"test": "vitest run",
|
|
52
55
|
"typecheck": "tsc --noEmit",
|
|
53
|
-
"lint": "
|
|
56
|
+
"lint": "oxlint .",
|
|
54
57
|
"prepublishOnly": "bun run build"
|
|
55
58
|
},
|
|
56
59
|
"dependencies": {
|
|
57
|
-
"@pyreon/core": "^0.11.
|
|
58
|
-
"@pyreon/reactivity": "^0.11.
|
|
60
|
+
"@pyreon/core": "^0.11.7",
|
|
61
|
+
"@pyreon/reactivity": "^0.11.7"
|
|
62
|
+
},
|
|
63
|
+
"devDependencies": {
|
|
64
|
+
"@happy-dom/global-registrator": "^20.8.3",
|
|
65
|
+
"@pyreon/runtime-dom": "^0.11.7",
|
|
66
|
+
"@pyreon/runtime-server": "^0.11.7"
|
|
59
67
|
},
|
|
60
68
|
"peerDependencies": {
|
|
61
|
-
"@pyreon/runtime-server": "^0.11.
|
|
69
|
+
"@pyreon/runtime-server": "^0.11.7"
|
|
62
70
|
},
|
|
63
71
|
"peerDependenciesMeta": {
|
|
64
72
|
"@pyreon/runtime-server": {
|
|
65
73
|
"optional": true
|
|
66
74
|
}
|
|
67
|
-
},
|
|
68
|
-
"devDependencies": {
|
|
69
|
-
"@happy-dom/global-registrator": "^20.8.3",
|
|
70
|
-
"@pyreon/runtime-dom": "^0.11.5",
|
|
71
|
-
"@pyreon/runtime-server": "^0.11.5"
|
|
72
|
-
},
|
|
73
|
-
"publishConfig": {
|
|
74
|
-
"access": "public"
|
|
75
75
|
}
|
|
76
76
|
}
|
package/src/context.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { createContext } from
|
|
1
|
+
import { createContext } from '@pyreon/core'
|
|
2
2
|
|
|
3
3
|
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
4
4
|
|
|
5
5
|
export interface HeadTag {
|
|
6
6
|
/** HTML tag name */
|
|
7
|
-
tag:
|
|
7
|
+
tag: 'title' | 'meta' | 'link' | 'script' | 'style' | 'base' | 'noscript'
|
|
8
8
|
/**
|
|
9
9
|
* Deduplication key. Tags with the same key replace each other;
|
|
10
10
|
* innermost component (last added) wins.
|
|
@@ -26,7 +26,7 @@ export interface MetaTag {
|
|
|
26
26
|
/** Open Graph / social property (e.g. "og:title", "twitter:card") */
|
|
27
27
|
property?: string
|
|
28
28
|
/** HTTP equivalent header (e.g. "refresh", "content-type") */
|
|
29
|
-
|
|
29
|
+
'http-equiv'?: string
|
|
30
30
|
/** Value associated with name, property, or http-equiv */
|
|
31
31
|
content?: string
|
|
32
32
|
/** Document character encoding (e.g. "utf-8") */
|
|
@@ -60,7 +60,7 @@ export interface LinkTag {
|
|
|
60
60
|
/** Title for the link (used for alternate stylesheets) */
|
|
61
61
|
title?: string
|
|
62
62
|
/** Fetch priority hint */
|
|
63
|
-
fetchpriority?:
|
|
63
|
+
fetchpriority?: 'high' | 'low' | 'auto'
|
|
64
64
|
/** Referrer policy */
|
|
65
65
|
referrerpolicy?: string
|
|
66
66
|
/** Image source set for preloading responsive images */
|
|
@@ -116,7 +116,7 @@ export interface BaseTag {
|
|
|
116
116
|
/** Base URL for relative URLs in the document */
|
|
117
117
|
href?: string
|
|
118
118
|
/** Default target for links and forms */
|
|
119
|
-
target?:
|
|
119
|
+
target?: '_blank' | '_self' | '_parent' | '_top'
|
|
120
120
|
}
|
|
121
121
|
|
|
122
122
|
export interface UseHeadInput {
|