@maizzle/framework 6.0.0-rc.21 → 6.0.0-rc.22
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/dist/components/Body.vue +1 -1
- package/dist/components/CodeBlock.vue +1 -1
- package/dist/components/CodeInline.vue +72 -2
- package/dist/components/Column.vue +2 -1
- package/dist/components/Container.vue +1 -11
- package/dist/components/Img.vue +199 -4
- package/dist/components/Preheader.vue +33 -5
- package/dist/components/Section.vue +9 -14
- package/dist/components/Text.vue +1 -1
- package/dist/composables/defineConfig.d.ts +3 -4
- package/dist/composables/defineConfig.d.ts.map +1 -1
- package/dist/composables/defineConfig.js +3 -4
- package/dist/composables/defineConfig.js.map +1 -1
- package/dist/composables/renderContext.d.ts +0 -1
- package/dist/composables/renderContext.d.ts.map +1 -1
- package/dist/composables/renderContext.js.map +1 -1
- package/dist/composables/usePreheader.d.ts +6 -5
- package/dist/composables/usePreheader.d.ts.map +1 -1
- package/dist/composables/usePreheader.js +3 -3
- package/dist/composables/usePreheader.js.map +1 -1
- package/dist/composables/useTransformers.d.ts +1 -1
- package/dist/composables/useTransformers.js +1 -1
- package/dist/composables/useTransformers.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/render/createRenderer.js +2 -2
- package/dist/render/createRenderer.js.map +1 -1
- package/dist/transformers/addAttributes.d.ts +18 -8
- package/dist/transformers/addAttributes.d.ts.map +1 -1
- package/dist/transformers/addAttributes.js +22 -8
- package/dist/transformers/addAttributes.js.map +1 -1
- package/dist/transformers/columnWidth.d.ts.map +1 -1
- package/dist/transformers/columnWidth.js +136 -150
- package/dist/transformers/columnWidth.js.map +1 -1
- package/dist/transformers/entities.d.ts.map +1 -1
- package/dist/transformers/entities.js +1 -0
- package/dist/transformers/entities.js.map +1 -1
- package/dist/transformers/index.d.ts.map +1 -1
- package/dist/transformers/index.js +7 -5
- package/dist/transformers/index.js.map +1 -1
- package/dist/transformers/inlineCss.js +2 -7
- package/dist/transformers/inlineCss.js.map +1 -1
- package/dist/transformers/minifyCodeInline.d.ts +29 -0
- package/dist/transformers/minifyCodeInline.d.ts.map +1 -0
- package/dist/transformers/minifyCodeInline.js +36 -0
- package/dist/transformers/minifyCodeInline.js.map +1 -0
- package/dist/transformers/msoPlaceholders.d.ts +10 -5
- package/dist/transformers/msoPlaceholders.d.ts.map +1 -1
- package/dist/transformers/msoPlaceholders.js +38 -7
- package/dist/transformers/msoPlaceholders.js.map +1 -1
- package/dist/transformers/safeSelectors.d.ts +37 -0
- package/dist/transformers/safeSelectors.d.ts.map +1 -0
- package/dist/transformers/{safeClassNames.js → safeSelectors.js} +24 -5
- package/dist/transformers/safeSelectors.js.map +1 -0
- package/dist/transformers/shorthandCss.js +38 -7
- package/dist/transformers/shorthandCss.js.map +1 -1
- package/dist/types/config.d.ts +2 -2
- package/dist/types/config.d.ts.map +1 -1
- package/dist/utils/ast/serializer.d.ts.map +1 -1
- package/dist/utils/ast/serializer.js +27 -17
- package/dist/utils/ast/serializer.js.map +1 -1
- package/dist/utils/cssBox.d.ts +42 -0
- package/dist/utils/cssBox.d.ts.map +1 -0
- package/dist/utils/cssBox.js +156 -0
- package/dist/utils/cssBox.js.map +1 -0
- package/package.json +1 -1
- package/dist/transformers/safeClassNames.d.ts +0 -22
- package/dist/transformers/safeClassNames.d.ts.map +0 -1
- package/dist/transformers/safeClassNames.js.map +0 -1
|
@@ -13,7 +13,7 @@ import { getCurrentInstance, inject, provide } from "vue";
|
|
|
13
13
|
* - `useTransformers({ prettify: true, minify: true })` *enables*
|
|
14
14
|
* transformers that would otherwise no-op (boolean-driven ones:
|
|
15
15
|
* inlineCss, purgeCss, prettify, minify, shorthandCss, sixHex,
|
|
16
|
-
*
|
|
16
|
+
* safeSelectors, entities). Same effect as setting their config
|
|
17
17
|
* slice directly, scoped to one template.
|
|
18
18
|
*
|
|
19
19
|
* Data-driven transformers (filters, baseURL, urlQuery, addAttributes,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useTransformers.js","names":[],"sources":["../../src/composables/useTransformers.ts"],"sourcesContent":["import { getCurrentInstance, inject, provide } from 'vue'\nimport { MaizzleConfigKey } from './useConfig.ts'\nimport { RenderContextKey } from './renderContext.ts'\nimport type { MaizzleConfig, TransformerToggles } from '../types/index.ts'\n\n/**\n * Toggle the transformer pipeline for the current template.\n *\n * - `useTransformers(false)` skips the entire pipeline (CSS inlining,\n * purging, shorthand, etc).\n * - `useTransformers(true)` (or no argument) keeps everything on.\n * - `useTransformers({ inlineCss: false, minify: false })` runs the\n * pipeline but skips the listed transformers.\n * - `useTransformers({ prettify: true, minify: true })` *enables*\n * transformers that would otherwise no-op (boolean-driven ones:\n * inlineCss, purgeCss, prettify, minify, shorthandCss, sixHex,\n *
|
|
1
|
+
{"version":3,"file":"useTransformers.js","names":[],"sources":["../../src/composables/useTransformers.ts"],"sourcesContent":["import { getCurrentInstance, inject, provide } from 'vue'\nimport { MaizzleConfigKey } from './useConfig.ts'\nimport { RenderContextKey } from './renderContext.ts'\nimport type { MaizzleConfig, TransformerToggles } from '../types/index.ts'\n\n/**\n * Toggle the transformer pipeline for the current template.\n *\n * - `useTransformers(false)` skips the entire pipeline (CSS inlining,\n * purging, shorthand, etc).\n * - `useTransformers(true)` (or no argument) keeps everything on.\n * - `useTransformers({ inlineCss: false, minify: false })` runs the\n * pipeline but skips the listed transformers.\n * - `useTransformers({ prettify: true, minify: true })` *enables*\n * transformers that would otherwise no-op (boolean-driven ones:\n * inlineCss, purgeCss, prettify, minify, shorthandCss, sixHex,\n * safeSelectors, entities). Same effect as setting their config\n * slice directly, scoped to one template.\n *\n * Data-driven transformers (filters, baseURL, urlQuery, addAttributes,\n * removeAttributes, replaceStrings, attributeToStyle) need actual\n * values in config — a bare `true` toggle for them is a no-op.\n *\n * Mirrors the `useTransformers` config flag, scoped to a single template\n * — no need to edit `maizzle.config.ts`.\n *\n * Usage in SFC <script setup>:\n * ```ts\n * useTransformers(false)\n * useTransformers({ inlineCss: false, minify: false })\n * useTransformers({ prettify: true })\n * ```\n */\nexport function useTransformers(value: boolean | TransformerToggles = true): void {\n if (!getCurrentInstance()) return\n\n const ctx = inject(RenderContextKey)\n if (!ctx) return\n\n const globalConfig = inject(MaizzleConfigKey, {} as MaizzleConfig)\n const merged: MaizzleConfig = {\n ...(ctx.sfcConfig ?? globalConfig),\n useTransformers: value,\n }\n\n ctx.sfcConfig = merged\n provide(MaizzleConfigKey, merged)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,gBAAgB,QAAsC,MAAY;CAChF,IAAI,CAAC,oBAAoB,EAAE;CAE3B,MAAM,MAAM,OAAO,iBAAiB;CACpC,IAAI,CAAC,KAAK;CAEV,MAAM,eAAe,OAAO,kBAAkB,EAAE,CAAkB;CAClE,MAAM,SAAwB;EAC5B,GAAI,IAAI,aAAa;EACrB,iBAAiB;EAClB;CAED,IAAI,YAAY;CAChB,QAAQ,kBAAkB,OAAO"}
|
package/dist/index.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ import { inlineLink } from "./transformers/inlineLink.js";
|
|
|
23
23
|
import { urlQuery } from "./transformers/urlQuery.js";
|
|
24
24
|
import { BaseUrlOptions, base } from "./transformers/base.js";
|
|
25
25
|
import { entities } from "./transformers/entities.js";
|
|
26
|
-
import {
|
|
26
|
+
import { safeSelectors } from "./transformers/safeSelectors.js";
|
|
27
27
|
import { attributeToStyle } from "./transformers/attributeToStyle.js";
|
|
28
28
|
import { InlineCssOptions, inlineCss } from "./transformers/inlineCss.js";
|
|
29
29
|
import { ShorthandCssOptions, shorthandCss } from "./transformers/shorthandCss.js";
|
|
@@ -36,4 +36,4 @@ import { replaceStrings } from "./transformers/replaceStrings.js";
|
|
|
36
36
|
import { FormatOptions, format } from "./transformers/format.js";
|
|
37
37
|
import { MinifyOptions, minify } from "./transformers/minify.js";
|
|
38
38
|
import { useHead } from "@unhead/vue";
|
|
39
|
-
export { type AttributesConfig, type BaseUrlOptions, type ComponentSource, type CreateRendererOptions, type CssConfig, type EntitiesConfig, type FilterFunction, type FiltersConfig, type FormatOptions, type HtmlConfig, type InlineCssOptions, type MaizzleConfig, type MinifyOptions, type NormalizedComponentSource, type PlaintextConfig, type PrepareOptions, type PurgeCssOptions, type RemoveAttributeOption, type RemoveAttributeRule, type RenderResult, type RenderedTemplate, type Renderer, type ShorthandCssOptions, type UrlConfig, type UrlQuery, type UrlQueryOptions, addAttributes, attributeToStyle, base, build, createPlaintext, createRenderer, defineConfig, entities, filters, format, inlineCss, inlineLink, maizzle, minify, normalizeComponentSources, prepare, purgeCss, removeAttributes, render, replaceStrings, resolveConfig,
|
|
39
|
+
export { type AttributesConfig, type BaseUrlOptions, type ComponentSource, type CreateRendererOptions, type CssConfig, type EntitiesConfig, type FilterFunction, type FiltersConfig, type FormatOptions, type HtmlConfig, type InlineCssOptions, type MaizzleConfig, type MinifyOptions, type NormalizedComponentSource, type PlaintextConfig, type PrepareOptions, type PurgeCssOptions, type RemoveAttributeOption, type RemoveAttributeRule, type RenderResult, type RenderedTemplate, type Renderer, type ShorthandCssOptions, type UrlConfig, type UrlQuery, type UrlQueryOptions, addAttributes, attributeToStyle, base, build, createPlaintext, createRenderer, defineConfig, entities, filters, format, inlineCss, inlineLink, maizzle, minify, normalizeComponentSources, prepare, purgeCss, removeAttributes, render, replaceStrings, resolveConfig, safeSelectors, serve, shorthandCss, sixHex, urlQuery, useBaseUrl, useConfig, useCurrentTemplate, useDoctype, useEvent, useFont, useHead, useOutlookFallback, usePlaintext, useTransformers, useUrlQuery };
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { useConfig } from "./composables/useConfig.js";
|
|
|
2
2
|
import { defineConfig } from "./composables/defineConfig.js";
|
|
3
3
|
import { resolveConfig } from "./config/index.js";
|
|
4
4
|
import { inlineLink } from "./transformers/inlineLink.js";
|
|
5
|
-
import {
|
|
5
|
+
import { safeSelectors } from "./transformers/safeSelectors.js";
|
|
6
6
|
import { attributeToStyle } from "./transformers/attributeToStyle.js";
|
|
7
7
|
import { inlineCss } from "./transformers/inlineCss.js";
|
|
8
8
|
import { removeAttributes } from "./transformers/removeAttributes.js";
|
|
@@ -35,4 +35,4 @@ import { useTransformers } from "./composables/useTransformers.js";
|
|
|
35
35
|
import { useBaseUrl } from "./composables/useBaseUrl.js";
|
|
36
36
|
import { useUrlQuery } from "./composables/useUrlQuery.js";
|
|
37
37
|
import { useHead } from "@unhead/vue";
|
|
38
|
-
export { addAttributes, attributeToStyle, base, build, createPlaintext, createRenderer, defineConfig, entities, filters, format, inlineCss, inlineLink, maizzle, minify, normalizeComponentSources, prepare, purgeCss, removeAttributes, render, replaceStrings, resolveConfig,
|
|
38
|
+
export { addAttributes, attributeToStyle, base, build, createPlaintext, createRenderer, defineConfig, entities, filters, format, inlineCss, inlineLink, maizzle, minify, normalizeComponentSources, prepare, purgeCss, removeAttributes, render, replaceStrings, resolveConfig, safeSelectors, serve, shorthandCss, sixHex, urlQuery, useBaseUrl, useConfig, useCurrentTemplate, useDoctype, useEvent, useFont, useHead, useOutlookFallback, usePlaintext, useTransformers, useUrlQuery };
|
|
@@ -287,8 +287,8 @@ async function createRenderer(options = {}) {
|
|
|
287
287
|
html = serializeDom(dom);
|
|
288
288
|
}
|
|
289
289
|
if (renderContext.preheader) {
|
|
290
|
-
const { text, fillerCount
|
|
291
|
-
const previewHtml = `<div style="display:none">${text}${"
|
|
290
|
+
const { text, fillerCount } = renderContext.preheader;
|
|
291
|
+
const previewHtml = `<div style="display:none">${text}${" ͏ ".repeat(fillerCount)}\u00A0</div>`;
|
|
292
292
|
html = html.replace(/<body([^>]*)>/, `<body$1>${previewHtml}`);
|
|
293
293
|
}
|
|
294
294
|
html = html.replaceAll("<!--[-->", "").replaceAll("<!--]-->", "").replaceAll("<!--teleport start anchor-->", "").replaceAll("<!--teleport anchor-->", "").replaceAll("<!--teleport start-->", "").replaceAll("<!--teleport end-->", "");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRenderer.js","names":["relPath","merge"],"sources":["../../src/render/createRenderer.ts"],"sourcesContent":["import { dirname, relative as relPath, resolve } from 'node:path'\nimport { mkdirSync, writeFileSync, existsSync, rmSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { isLaravel } from '../utils/detect.ts'\nimport { rowSourceLocation } from './plugins/rowSourceLocation.ts'\nimport { rawExtract } from './plugins/rawExtract.ts'\nimport { codeBlockExtract } from './plugins/codeBlockExtract.ts'\nimport { markdownExtract } from './plugins/markdownExtract.ts'\nimport { createServer, mergeConfig, type InlineConfig, type Plugin } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport Markdown from 'unplugin-vue-markdown/vite'\nimport AutoImport from 'unplugin-auto-import/vite'\nimport Components from 'unplugin-vue-components/vite'\nimport { unheadVueComposablesImports } from '@unhead/vue'\nimport { defu as merge } from 'defu'\nimport { glob, globSync } from 'tinyglobby'\nimport { createSSRApp } from 'vue'\nimport { renderToString } from 'vue/server-renderer'\nimport { createHead } from '@unhead/vue/server'\nimport { MaizzleConfigKey } from '../composables/useConfig.ts'\nimport { RenderContextKey } from '../composables/renderContext.ts'\nimport { componentNameFromPath, type NormalizedComponentSource } from '../utils/componentSources.ts'\nimport type { Component, InjectionKey } from 'vue'\nimport type { MaizzleConfig, MarkdownConfig } from '../types/index.ts'\nimport type { MarkdownExit } from 'markdown-exit'\nimport type { RenderContext } from '../composables/renderContext.ts'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nconst vuePkgDir = dirname(fileURLToPath(import.meta.resolve('vue/package.json')))\nconst vueServerRendererPkgDir = dirname(fileURLToPath(import.meta.resolve('@vue/server-renderer/package.json')))\nconst unheadVuePkgDir = resolve(dirname(fileURLToPath(import.meta.resolve('@unhead/vue'))), '..')\nconst vueRouterPkgDir = dirname(fileURLToPath(import.meta.resolve('vue-router/package.json')))\n\nexport interface RenderedTemplate {\n html: string\n doctype?: string\n templateConfig: MaizzleConfig\n sfcEventHandlers: RenderContext['sfcEventHandlers']\n plaintext?: RenderContext['plaintext']\n tailwindBlocks?: RenderContext['tailwindBlocks']\n}\n\nexport interface Renderer {\n render(input: string | Component, config: MaizzleConfig): Promise<RenderedTemplate>\n invalidate(filePath: string): Promise<void>\n invalidateAll(): Promise<void>\n close(): Promise<void>\n}\n\nexport interface CreateRendererOptions {\n /** Generate .d.ts files for auto-imports and components (default: false) */\n dts?: boolean\n /** Options passed to unplugin-vue-markdown */\n markdown?: MarkdownConfig\n /** Root directory for resolving user component dirs and .d.ts output */\n root?: string\n /**\n * Additional component sources to register for auto-import. Already\n * normalized — pass through `normalizeComponentSources()` first.\n */\n componentDirs?: NormalizedComponentSource[]\n /** User Vite config options to merge into the internal SSR server */\n vite?: InlineConfig\n}\n\n/**\n * Lightweight Vite SSR loader for rendering Vue SFC email templates.\n *\n * Uses only Vue + unplugin for component/auto-import resolution.\n * Tailwind CSS compilation is handled by the transformer pipeline.\n */\nexport async function createRenderer(\n options: CreateRendererOptions = {},\n): Promise<Renderer> {\n const { dts = false, markdown: markdownOptionsRaw, root = process.cwd(), componentDirs = [], vite: userViteConfig } = options\n const { shikiTheme = 'github-light', ...markdownOptions } = markdownOptionsRaw ?? {}\n\n // Sources without an explicit prefix get registered via unplugin's `dirs`\n // (folder name auto-namespaces). Sources with an explicit `prefix` are\n // registered through a custom resolver below so we can fully control naming.\n const dirSources = componentDirs.filter(s => s.prefix === undefined)\n const prefixedSources = componentDirs.filter(s => s.prefix !== undefined)\n\n // Absolute component dirs — used to skip auto-wrapping `.md` files that are\n // imported as reusable components (vs. entry-point email templates).\n const componentDirsAbs = [resolve(root, 'components'), ...componentDirs.map(s => s.path)]\n\n const dtsDir = isLaravel()\n ? resolve(process.cwd(), 'resources/js/types/maizzle')\n : resolve(root, '.maizzle')\n\n // Built-in framework components live at this path. When a user provides a\n // top-level file with the same (PascalCased) basename, drop the built-in\n // from unplugin's scan so the user's component is the only candidate. This\n // avoids the \"naming conflicts\" warning and the alphabetical-glob ordering\n // pitfall that decides who wins when both are present in `dirs`.\n const frameworkComponentsDir = resolve(__dirname, '../components')\n\n function topLevelBasenamesLower(dir: string): Set<string> {\n if (!existsSync(dir)) return new Set()\n const files = globSync(['*.vue', '*.md'], { cwd: dir, absolute: false })\n return new Set(files.map(f => f.replace(/\\.(vue|md)$/, '').toLowerCase()))\n }\n\n const frameworkFiles = globSync(['*.vue', '*.md'], { cwd: frameworkComponentsDir, absolute: false })\n const frameworkByLower = new Map(\n frameworkFiles.map(f => [f.replace(/\\.(vue|md)$/, '').toLowerCase(), f]),\n )\n\n const shadowedNames = new Set<string>()\n for (const dir of [resolve(root, 'components'), ...dirSources.map(s => s.path)]) {\n for (const lower of topLevelBasenamesLower(dir)) {\n if (frameworkByLower.has(lower)) shadowedNames.add(lower)\n }\n }\n\n const frameworkExcludes = [...shadowedNames]\n .map(lower => `${frameworkComponentsDir}/${frameworkByLower.get(lower)}`)\n\n // Pre-scanned name → absolute-path map for prefixed sources. Rebuilt on\n // file add/unlink via the watcher hook plugin further down. Powers the\n // runtime resolver and the d.ts file we write for IDE autocompletion.\n const prefixedNameMap = new Map<string, string>()\n\n async function scanPrefixedSources(): Promise<void> {\n prefixedNameMap.clear()\n const seen = new Map<string, string>()\n for (const source of prefixedSources) {\n const files = await glob(['**/*.vue', '**/*.md'], { cwd: source.path, absolute: true })\n for (const file of files) {\n const name = componentNameFromPath({\n filePath: file,\n dirRoot: source.path,\n prefix: source.prefix,\n pathPrefix: source.pathPrefix,\n })\n const existing = seen.get(name)\n if (existing && existing !== file) {\n throw new Error(\n `[maizzle] Component name collision: \"${name}\" resolved from both \"${existing}\" and \"${file}\". `\n + 'Rename one of the files or split them into separate sources with distinct prefixes.',\n )\n }\n seen.set(name, file)\n prefixedNameMap.set(name, file)\n }\n }\n }\n\n await scanPrefixedSources()\n\n const prefixedResolver = (name: string) => prefixedNameMap.get(name)\n\n // unplugin-vue-components' own d.ts only covers components found via `dirs`;\n // its `types` option emits named-import entries which break for SFC `default`\n // exports. Write a sibling d.ts for prefixed sources so editors get correct\n // autocompletion via TypeScript interface merging on `vue.GlobalComponents`.\n const prefixedDtsPath = resolve(dtsDir, 'prefixed-components.d.ts')\n\n function writePrefixedDts(): void {\n if (!dts) return\n if (prefixedNameMap.size === 0) {\n if (existsSync(prefixedDtsPath)) rmSync(prefixedDtsPath)\n return\n }\n const dtsBase = dirname(prefixedDtsPath)\n mkdirSync(dtsBase, { recursive: true })\n const lines = Array.from(prefixedNameMap.entries())\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, file]) => {\n const relativePath = relPath(dtsBase, file).replace(/\\\\/g, '/')\n const importPath = relativePath.startsWith('.') ? relativePath : `./${relativePath}`\n return ` ${name}: typeof import('${importPath}')['default']`\n })\n .join('\\n')\n writeFileSync(\n prefixedDtsPath,\n `/* eslint-disable */\\n// @ts-nocheck\\n// biome-ignore lint: disable\\n// oxlint-disable\\n// Generated by Maizzle for prefixed component sources\\n\\nexport {}\\n\\n/* prettier-ignore */\\ndeclare module 'vue' {\\n export interface GlobalComponents {\\n${lines}\\n }\\n}\\n`,\n )\n }\n\n writePrefixedDts()\n\n /**\n * Watches prefixed source dirs and rebuilds {@link prefixedNameMap} when\n * files are added/removed. Vite's watcher already covers `dirSources`\n * via unplugin-vue-components' own filesystem hooks.\n */\n const prefixedSourceWatcher: Plugin | null = prefixedSources.length > 0\n ? {\n name: 'maizzle:prefixed-component-watcher',\n configureServer(server) {\n for (const source of prefixedSources) {\n server.watcher.add(source.path)\n }\n const refresh = async (file: string) => {\n if (!prefixedSources.some(s => file.startsWith(`${s.path}/`))) return\n if (!/\\.(vue|md)$/.test(file)) return\n await scanPrefixedSources()\n writePrefixedDts()\n }\n server.watcher.on('add', refresh)\n server.watcher.on('unlink', refresh)\n },\n }\n : null\n\n const VIRTUAL_SFC_ID = 'virtual:maizzle-sfc.vue'\n let virtualSfcSource = ''\n\n // Never load the host project's vite.config.ts here. Doing so pulls every\n // host plugin (Nitro, TanStack Start, the Maizzle plugin itself, …) into\n // this isolated SSR pipeline, where they override env factories, re-trigger\n // configureServer hooks, and break Vite's hot channel wiring. Users that\n // need extra Vite plugins for SSR pass them explicitly via the `vite` option.\n const maizzleConfig: InlineConfig = {\n configFile: false,\n plugins: [\n rawExtract(),\n codeBlockExtract(),\n markdownExtract(),\n rowSourceLocation(),\n {\n name: 'maizzle:virtual-sfc',\n resolveId(id) {\n if (id === VIRTUAL_SFC_ID) return id\n },\n load(id) {\n if (id === VIRTUAL_SFC_ID) return virtualSfcSource\n },\n },\n vue({\n include: [/\\.vue$/, /\\.md$/],\n template: {\n transformAssetUrls: false,\n },\n }),\n Markdown(merge(markdownOptions ?? {}, {\n headEnabled: true,\n wrapperDiv: false,\n wrapperClasses: 'prose',\n wrapperComponent: (id: string, raw: string) => {\n const fm = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/)?.[1]\n const layout = fm?.match(/^[ \\t]*layout[ \\t]*:[ \\t]*['\"]?([A-Za-z][\\w-]*|false|none)['\"]?[ \\t]*$/m)?.[1]\n if (layout === 'false' || layout === 'none') return null\n if (layout) return layout\n // No `layout:` set — default to the built-in `MarkdownLayout` for\n // entry-template `.md` files. Skip for `.md` files inside component\n // dirs, which are reusable fragments imported into other templates.\n const inComponentDir = componentDirsAbs.some(d => id === d || id.startsWith(`${d}/`))\n return inComponentDir ? null : 'MarkdownLayout'\n },\n markdownOptions: {\n async highlight(code: string, lang: string) {\n const { codeToHtml } = await import('shiki')\n return codeToHtml(code, { lang, theme: shikiTheme })\n },\n },\n markdownSetup(md: MarkdownExit) {\n const wrapPre = (html: string) =>\n `<table class=\"w-full\"><tr><td class=\"max-w-0 mso-padding-alt-4\">${html}</td></tr></table>\\n`\n\n const defaultFence = md.renderer.rules.fence!\n md.renderer.rules.fence = (...args) => {\n const result = defaultFence(...args)\n if (typeof result === 'string') return wrapPre(result)\n return result.then(wrapPre)\n }\n\n const defaultCodeBlock = md.renderer.rules.code_block!\n md.renderer.rules.code_block = (...args) => wrapPre(defaultCodeBlock(...args) as string)\n },\n })),\n AutoImport({\n dirs: [\n resolve(__dirname, '../composables'),\n resolve(__dirname, '../filters'),\n ],\n imports: ['vue', unheadVueComposablesImports],\n dts: dts ? resolve(dtsDir, 'auto-imports.d.ts') : false,\n }),\n Components({\n extensions: ['vue', 'md'],\n include: [/\\.vue$/, /\\.vue\\?vue/, /\\.md$/],\n dirs: [\n frameworkComponentsDir,\n resolve(root, 'components'),\n ...dirSources.map(s => s.path),\n ],\n // Drop built-in component files whose name the user has shadowed.\n // This makes the user's version the only match — no \"naming\n // conflicts\" warning, no glob-ordering games.\n globsExclude: frameworkExcludes,\n directoryAsNamespace: true,\n collapseSamePrefixes: true,\n resolvers: prefixedSources.length > 0 ? [prefixedResolver] : undefined,\n dts: dts ? resolve(dtsDir, 'components.d.ts') : false,\n }),\n ...(prefixedSourceWatcher ? [prefixedSourceWatcher] : []),\n ],\n resolve: {\n alias: {\n 'vue/server-renderer': resolve(vueServerRendererPkgDir, 'dist/server-renderer.esm-bundler.js'),\n 'vue': resolve(vuePkgDir, 'dist/vue.runtime.esm-bundler.js'),\n 'vue-router': vueRouterPkgDir,\n '@unhead/vue/server': resolve(unheadVuePkgDir, 'dist/server.mjs'),\n '@unhead/vue': resolve(unheadVuePkgDir, 'dist/index.mjs'),\n },\n },\n server: {\n middlewareMode: true,\n hmr: false,\n // Watcher is required so unplugin-vue-components and unplugin-auto-import\n // detect added/removed component files and rewrite their .d.ts on the fly.\n // (We only render via SSR — HMR is off, but chokidar still drives the plugins.)\n fs: {\n allow: [process.cwd(), root, ...componentDirs.map(s => s.path), vuePkgDir, vueServerRendererPkgDir, unheadVuePkgDir, vueRouterPkgDir],\n },\n },\n appType: 'custom',\n logLevel: 'silent',\n optimizeDeps: {\n noDiscovery: true,\n },\n }\n\n // Merge user's vite config (from config.vite) under Maizzle's config.\n // mergeConfig(a, b) → b overrides a for scalars, arrays are concatenated.\n // This ensures Maizzle's critical settings (middlewareMode, appType, etc.) always win,\n // while user plugins and other options are included.\n const finalConfig = userViteConfig\n ? mergeConfig(userViteConfig, maizzleConfig)\n : maizzleConfig\n\n const server = await createServer(finalConfig)\n\n return {\n async render(input: string | Component, config: MaizzleConfig): Promise<RenderedTemplate> {\n let component: Component\n let configKey: InjectionKey<MaizzleConfig>\n let contextKey: InjectionKey<RenderContext>\n\n if (typeof input === 'string') {\n // String input goes through Vite — must use ssrLoadModule for injection keys\n // so they share the same module instance as the SFC\n const configModule = await server.ssrLoadModule(resolve(__dirname, '../composables/useConfig'))\n const contextModule = await server.ssrLoadModule(resolve(__dirname, '../composables/renderContext'))\n configKey = configModule.MaizzleConfigKey\n contextKey = contextModule.RenderContextKey\n\n if (input.includes('<template') || input.includes('<script')) {\n virtualSfcSource = input\n const mod = server.moduleGraph.getModuleById(VIRTUAL_SFC_ID)\n if (mod) server.moduleGraph.invalidateModule(mod)\n component = (await server.ssrLoadModule(VIRTUAL_SFC_ID)).default\n } else {\n component = (await server.ssrLoadModule(input)).default\n }\n } else {\n // Pre-compiled component — use directly imported keys\n component = input\n configKey = MaizzleConfigKey\n contextKey = RenderContextKey\n }\n\n const renderContext: RenderContext = {\n doctype: undefined,\n sfcConfig: undefined,\n sfcEventHandlers: [],\n }\n\n const head = createHead({ disableDefaults: true })\n const app = createSSRApp(component)\n app.use(head)\n\n // Register user Vue plugins, directives, and global properties\n if (config.vue) {\n const plugins = typeof config.vue.plugins === 'function'\n ? config.vue.plugins()\n : config.vue.plugins ?? []\n for (const plugin of plugins) {\n app.use(plugin)\n }\n for (const [name, directive] of Object.entries(config.vue.directives ?? {})) {\n app.directive(name, directive)\n }\n Object.assign(app.config.globalProperties, config.vue.globalProperties)\n }\n\n app.provide(configKey, config)\n app.provide(contextKey, renderContext)\n\n const ssrContext: Record<string, any> = {}\n let html: string = await renderToString(app, ssrContext)\n\n const { headTags, bodyTags, bodyTagsOpen, htmlAttrs, bodyAttrs } = head.render()\n\n // Inject head entries into the rendered HTML\n if (htmlAttrs) {\n html = html.replace(/<html([^>]*)>/, `<html$1 ${htmlAttrs}>`)\n }\n if (headTags) {\n html = html.replace('</head>', `${headTags}\\n</head>`)\n }\n if (bodyAttrs) {\n html = html.replace(/<body([^>]*)>/, `<body$1 ${bodyAttrs}>`)\n }\n if (bodyTagsOpen) {\n html = html.replace(/<body([^>]*)>/, `<body$1>\\n${bodyTagsOpen}`)\n }\n if (bodyTags) {\n html = html.replace('</body>', `${bodyTags}\\n</body>`)\n }\n\n // Inject SSR teleport content into their target elements\n const hasTeleports = ssrContext.teleports && Object.keys(ssrContext.teleports).length > 0\n const hasFonts = (renderContext.fonts?.length ?? 0) > 0\n\n if (hasTeleports || hasFonts) {\n const { parse: parseDom, serialize: serializeDom, walk } = await import('../utils/ast/index.ts')\n let dom = parseDom(html)\n\n if (hasTeleports) {\n for (const [rawTarget, content] of Object.entries(ssrContext.teleports) as [string, string][]) {\n if (!content) continue\n\n const prepend = rawTarget.endsWith(':start')\n const target = prepend ? rawTarget.slice(0, -6) : rawTarget\n const targetChildren = parseDom(content)\n\n walk(dom, (node) => {\n const el = node as import('domhandler').Element\n\n if (!el.name) return\n\n const matched\n = target === el.name\n || (target.startsWith('#') && el.attribs?.id === target.slice(1))\n || (target.startsWith('.') && el.attribs?.class?.split(/\\s+/).includes(target.slice(1)))\n\n if (matched) {\n for (const child of targetChildren) {\n child.parent = el as any\n }\n\n el.children = prepend\n ? [...targetChildren, ...(el.children || [])] as any\n : [...(el.children || []), ...targetChildren] as any\n }\n })\n }\n }\n\n if (hasFonts) {\n const { injectFonts } = await import('./injectFonts.ts')\n injectFonts(dom, renderContext.fonts!, parseDom, walk)\n }\n\n html = serializeDom(dom)\n }\n\n // Inject preheader text from usePreheader() composable\n if (renderContext.preheader) {\n const { text, fillerCount, shyCount } = renderContext.preheader\n const filler = '\\u2007\\u034F '.repeat(fillerCount)\n const shys = '\\u00AD '.repeat(shyCount)\n const previewHtml = `<div style=\"display:none\">${text}${filler}${shys}\\u00A0</div>`\n html = html.replace(/<body([^>]*)>/, `<body$1>${previewHtml}`)\n }\n\n // Strip Vue SSR fragment markers + teleport anchor comments. These are\n // rendering hygiene, not transformer concerns — must run regardless of\n // `useTransformers` state. Fragment markers contain `-->`, which would\n // prematurely terminate MSO conditional comments downstream.\n html = html\n .replaceAll('<!--[-->', '')\n .replaceAll('<!--]-->', '')\n .replaceAll('<!--teleport start anchor-->', '')\n .replaceAll('<!--teleport anchor-->', '')\n .replaceAll('<!--teleport start-->', '')\n .replaceAll('<!--teleport end-->', '')\n\n return {\n html,\n doctype: renderContext.doctype,\n // Layer sfcConfig over config — sfcConfig is a partial override\n // emitted by composables (defineConfig, useTransformers, etc.).\n // A naive replacement (`sfcConfig ?? config`) drops defaults from\n // the resolved config when the SFC only sets a single key, since\n // the composables' inject() of globalConfig can return `{}` in\n // dev when ssrLoadModule and the SFC's auto-imported module\n // resolve to different module instances (different Symbols).\n templateConfig: renderContext.sfcConfig ? merge(renderContext.sfcConfig, config) : config,\n sfcEventHandlers: renderContext.sfcEventHandlers,\n plaintext: renderContext.plaintext,\n tailwindBlocks: renderContext.tailwindBlocks,\n }\n },\n\n async invalidate(filePath: string): Promise<void> {\n const mod = await server.moduleGraph.getModuleByUrl(filePath)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n },\n\n async invalidateAll(): Promise<void> {\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n server.moduleGraph.invalidateModule(mod)\n }\n },\n\n async close(): Promise<void> {\n await server.close()\n // unplugin-auto-import schedules a 500ms-throttled, fire-and-forget\n // d.ts write on its first scan. server.close() doesn't drain that\n // pending write, so callers tearing down the working dir right after\n // close (tests, ephemeral build pipelines) can race the mkdir against\n // a missing parent directory. Wait one throttle window past close so\n // that lingering write resolves while the dir still exists.\n if (dts) {\n await new Promise(resolve => setTimeout(resolve, 600))\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,YAAY,QAAQ,cAA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ACvC,WAAW,uBAAuB,GAAG;GAExC,OAAO;IACL;IACA,SAAS,cAAc;IAQvB,gBAAgB,cAAc,YAAYA,OAAM,cAAc,WAAW,OAAO,GAAG;IACnF,kBAAkB,cAAc;IAChC,WAAW,cAAc;IACzB,gBAAgB,cAAc;IAC/B;;EAGH,MAAM,WAAW,UAAiC;GAChD,MAAM,MAAM,MAAM,OAAO,YAAY,eAAe,SAAS;GAC7D,IAAI,KACF,OAAO,YAAY,iBAAiB,IAAI;;EAI5C,MAAM,gBAA+B;GACnC,KAAK,MAAM,OAAO,OAAO,YAAY,cAAc,QAAQ,EACzD,OAAO,YAAY,iBAAiB,IAAI;;EAI5C,MAAM,QAAuB;GAC3B,MAAM,OAAO,OAAO;GAOpB,IAAI,KACF,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,IAAI,CAAC;;EAG3D"}
|
|
1
|
+
{"version":3,"file":"createRenderer.js","names":["relPath","merge"],"sources":["../../src/render/createRenderer.ts"],"sourcesContent":["import { dirname, relative as relPath, resolve } from 'node:path'\nimport { mkdirSync, writeFileSync, existsSync, rmSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { isLaravel } from '../utils/detect.ts'\nimport { rowSourceLocation } from './plugins/rowSourceLocation.ts'\nimport { rawExtract } from './plugins/rawExtract.ts'\nimport { codeBlockExtract } from './plugins/codeBlockExtract.ts'\nimport { markdownExtract } from './plugins/markdownExtract.ts'\nimport { createServer, mergeConfig, type InlineConfig, type Plugin } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport Markdown from 'unplugin-vue-markdown/vite'\nimport AutoImport from 'unplugin-auto-import/vite'\nimport Components from 'unplugin-vue-components/vite'\nimport { unheadVueComposablesImports } from '@unhead/vue'\nimport { defu as merge } from 'defu'\nimport { glob, globSync } from 'tinyglobby'\nimport { createSSRApp } from 'vue'\nimport { renderToString } from 'vue/server-renderer'\nimport { createHead } from '@unhead/vue/server'\nimport { MaizzleConfigKey } from '../composables/useConfig.ts'\nimport { RenderContextKey } from '../composables/renderContext.ts'\nimport { componentNameFromPath, type NormalizedComponentSource } from '../utils/componentSources.ts'\nimport type { Component, InjectionKey } from 'vue'\nimport type { MaizzleConfig, MarkdownConfig } from '../types/index.ts'\nimport type { MarkdownExit } from 'markdown-exit'\nimport type { RenderContext } from '../composables/renderContext.ts'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nconst vuePkgDir = dirname(fileURLToPath(import.meta.resolve('vue/package.json')))\nconst vueServerRendererPkgDir = dirname(fileURLToPath(import.meta.resolve('@vue/server-renderer/package.json')))\nconst unheadVuePkgDir = resolve(dirname(fileURLToPath(import.meta.resolve('@unhead/vue'))), '..')\nconst vueRouterPkgDir = dirname(fileURLToPath(import.meta.resolve('vue-router/package.json')))\n\nexport interface RenderedTemplate {\n html: string\n doctype?: string\n templateConfig: MaizzleConfig\n sfcEventHandlers: RenderContext['sfcEventHandlers']\n plaintext?: RenderContext['plaintext']\n tailwindBlocks?: RenderContext['tailwindBlocks']\n}\n\nexport interface Renderer {\n render(input: string | Component, config: MaizzleConfig): Promise<RenderedTemplate>\n invalidate(filePath: string): Promise<void>\n invalidateAll(): Promise<void>\n close(): Promise<void>\n}\n\nexport interface CreateRendererOptions {\n /** Generate .d.ts files for auto-imports and components (default: false) */\n dts?: boolean\n /** Options passed to unplugin-vue-markdown */\n markdown?: MarkdownConfig\n /** Root directory for resolving user component dirs and .d.ts output */\n root?: string\n /**\n * Additional component sources to register for auto-import. Already\n * normalized — pass through `normalizeComponentSources()` first.\n */\n componentDirs?: NormalizedComponentSource[]\n /** User Vite config options to merge into the internal SSR server */\n vite?: InlineConfig\n}\n\n/**\n * Lightweight Vite SSR loader for rendering Vue SFC email templates.\n *\n * Uses only Vue + unplugin for component/auto-import resolution.\n * Tailwind CSS compilation is handled by the transformer pipeline.\n */\nexport async function createRenderer(\n options: CreateRendererOptions = {},\n): Promise<Renderer> {\n const { dts = false, markdown: markdownOptionsRaw, root = process.cwd(), componentDirs = [], vite: userViteConfig } = options\n const { shikiTheme = 'github-light', ...markdownOptions } = markdownOptionsRaw ?? {}\n\n // Sources without an explicit prefix get registered via unplugin's `dirs`\n // (folder name auto-namespaces). Sources with an explicit `prefix` are\n // registered through a custom resolver below so we can fully control naming.\n const dirSources = componentDirs.filter(s => s.prefix === undefined)\n const prefixedSources = componentDirs.filter(s => s.prefix !== undefined)\n\n // Absolute component dirs — used to skip auto-wrapping `.md` files that are\n // imported as reusable components (vs. entry-point email templates).\n const componentDirsAbs = [resolve(root, 'components'), ...componentDirs.map(s => s.path)]\n\n const dtsDir = isLaravel()\n ? resolve(process.cwd(), 'resources/js/types/maizzle')\n : resolve(root, '.maizzle')\n\n // Built-in framework components live at this path. When a user provides a\n // top-level file with the same (PascalCased) basename, drop the built-in\n // from unplugin's scan so the user's component is the only candidate. This\n // avoids the \"naming conflicts\" warning and the alphabetical-glob ordering\n // pitfall that decides who wins when both are present in `dirs`.\n const frameworkComponentsDir = resolve(__dirname, '../components')\n\n function topLevelBasenamesLower(dir: string): Set<string> {\n if (!existsSync(dir)) return new Set()\n const files = globSync(['*.vue', '*.md'], { cwd: dir, absolute: false })\n return new Set(files.map(f => f.replace(/\\.(vue|md)$/, '').toLowerCase()))\n }\n\n const frameworkFiles = globSync(['*.vue', '*.md'], { cwd: frameworkComponentsDir, absolute: false })\n const frameworkByLower = new Map(\n frameworkFiles.map(f => [f.replace(/\\.(vue|md)$/, '').toLowerCase(), f]),\n )\n\n const shadowedNames = new Set<string>()\n for (const dir of [resolve(root, 'components'), ...dirSources.map(s => s.path)]) {\n for (const lower of topLevelBasenamesLower(dir)) {\n if (frameworkByLower.has(lower)) shadowedNames.add(lower)\n }\n }\n\n const frameworkExcludes = [...shadowedNames]\n .map(lower => `${frameworkComponentsDir}/${frameworkByLower.get(lower)}`)\n\n // Pre-scanned name → absolute-path map for prefixed sources. Rebuilt on\n // file add/unlink via the watcher hook plugin further down. Powers the\n // runtime resolver and the d.ts file we write for IDE autocompletion.\n const prefixedNameMap = new Map<string, string>()\n\n async function scanPrefixedSources(): Promise<void> {\n prefixedNameMap.clear()\n const seen = new Map<string, string>()\n for (const source of prefixedSources) {\n const files = await glob(['**/*.vue', '**/*.md'], { cwd: source.path, absolute: true })\n for (const file of files) {\n const name = componentNameFromPath({\n filePath: file,\n dirRoot: source.path,\n prefix: source.prefix,\n pathPrefix: source.pathPrefix,\n })\n const existing = seen.get(name)\n if (existing && existing !== file) {\n throw new Error(\n `[maizzle] Component name collision: \"${name}\" resolved from both \"${existing}\" and \"${file}\". `\n + 'Rename one of the files or split them into separate sources with distinct prefixes.',\n )\n }\n seen.set(name, file)\n prefixedNameMap.set(name, file)\n }\n }\n }\n\n await scanPrefixedSources()\n\n const prefixedResolver = (name: string) => prefixedNameMap.get(name)\n\n // unplugin-vue-components' own d.ts only covers components found via `dirs`;\n // its `types` option emits named-import entries which break for SFC `default`\n // exports. Write a sibling d.ts for prefixed sources so editors get correct\n // autocompletion via TypeScript interface merging on `vue.GlobalComponents`.\n const prefixedDtsPath = resolve(dtsDir, 'prefixed-components.d.ts')\n\n function writePrefixedDts(): void {\n if (!dts) return\n if (prefixedNameMap.size === 0) {\n if (existsSync(prefixedDtsPath)) rmSync(prefixedDtsPath)\n return\n }\n const dtsBase = dirname(prefixedDtsPath)\n mkdirSync(dtsBase, { recursive: true })\n const lines = Array.from(prefixedNameMap.entries())\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, file]) => {\n const relativePath = relPath(dtsBase, file).replace(/\\\\/g, '/')\n const importPath = relativePath.startsWith('.') ? relativePath : `./${relativePath}`\n return ` ${name}: typeof import('${importPath}')['default']`\n })\n .join('\\n')\n writeFileSync(\n prefixedDtsPath,\n `/* eslint-disable */\\n// @ts-nocheck\\n// biome-ignore lint: disable\\n// oxlint-disable\\n// Generated by Maizzle for prefixed component sources\\n\\nexport {}\\n\\n/* prettier-ignore */\\ndeclare module 'vue' {\\n export interface GlobalComponents {\\n${lines}\\n }\\n}\\n`,\n )\n }\n\n writePrefixedDts()\n\n /**\n * Watches prefixed source dirs and rebuilds {@link prefixedNameMap} when\n * files are added/removed. Vite's watcher already covers `dirSources`\n * via unplugin-vue-components' own filesystem hooks.\n */\n const prefixedSourceWatcher: Plugin | null = prefixedSources.length > 0\n ? {\n name: 'maizzle:prefixed-component-watcher',\n configureServer(server) {\n for (const source of prefixedSources) {\n server.watcher.add(source.path)\n }\n const refresh = async (file: string) => {\n if (!prefixedSources.some(s => file.startsWith(`${s.path}/`))) return\n if (!/\\.(vue|md)$/.test(file)) return\n await scanPrefixedSources()\n writePrefixedDts()\n }\n server.watcher.on('add', refresh)\n server.watcher.on('unlink', refresh)\n },\n }\n : null\n\n const VIRTUAL_SFC_ID = 'virtual:maizzle-sfc.vue'\n let virtualSfcSource = ''\n\n // Never load the host project's vite.config.ts here. Doing so pulls every\n // host plugin (Nitro, TanStack Start, the Maizzle plugin itself, …) into\n // this isolated SSR pipeline, where they override env factories, re-trigger\n // configureServer hooks, and break Vite's hot channel wiring. Users that\n // need extra Vite plugins for SSR pass them explicitly via the `vite` option.\n const maizzleConfig: InlineConfig = {\n configFile: false,\n plugins: [\n rawExtract(),\n codeBlockExtract(),\n markdownExtract(),\n rowSourceLocation(),\n {\n name: 'maizzle:virtual-sfc',\n resolveId(id) {\n if (id === VIRTUAL_SFC_ID) return id\n },\n load(id) {\n if (id === VIRTUAL_SFC_ID) return virtualSfcSource\n },\n },\n vue({\n include: [/\\.vue$/, /\\.md$/],\n template: {\n transformAssetUrls: false,\n },\n }),\n Markdown(merge(markdownOptions ?? {}, {\n headEnabled: true,\n wrapperDiv: false,\n wrapperClasses: 'prose',\n wrapperComponent: (id: string, raw: string) => {\n const fm = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/)?.[1]\n const layout = fm?.match(/^[ \\t]*layout[ \\t]*:[ \\t]*['\"]?([A-Za-z][\\w-]*|false|none)['\"]?[ \\t]*$/m)?.[1]\n if (layout === 'false' || layout === 'none') return null\n if (layout) return layout\n // No `layout:` set — default to the built-in `MarkdownLayout` for\n // entry-template `.md` files. Skip for `.md` files inside component\n // dirs, which are reusable fragments imported into other templates.\n const inComponentDir = componentDirsAbs.some(d => id === d || id.startsWith(`${d}/`))\n return inComponentDir ? null : 'MarkdownLayout'\n },\n markdownOptions: {\n async highlight(code: string, lang: string) {\n const { codeToHtml } = await import('shiki')\n return codeToHtml(code, { lang, theme: shikiTheme })\n },\n },\n markdownSetup(md: MarkdownExit) {\n const wrapPre = (html: string) =>\n `<table class=\"w-full\"><tr><td class=\"max-w-0 mso-padding-alt-4\">${html}</td></tr></table>\\n`\n\n const defaultFence = md.renderer.rules.fence!\n md.renderer.rules.fence = (...args) => {\n const result = defaultFence(...args)\n if (typeof result === 'string') return wrapPre(result)\n return result.then(wrapPre)\n }\n\n const defaultCodeBlock = md.renderer.rules.code_block!\n md.renderer.rules.code_block = (...args) => wrapPre(defaultCodeBlock(...args) as string)\n },\n })),\n AutoImport({\n dirs: [\n resolve(__dirname, '../composables'),\n resolve(__dirname, '../filters'),\n ],\n imports: ['vue', unheadVueComposablesImports],\n dts: dts ? resolve(dtsDir, 'auto-imports.d.ts') : false,\n }),\n Components({\n extensions: ['vue', 'md'],\n include: [/\\.vue$/, /\\.vue\\?vue/, /\\.md$/],\n dirs: [\n frameworkComponentsDir,\n resolve(root, 'components'),\n ...dirSources.map(s => s.path),\n ],\n // Drop built-in component files whose name the user has shadowed.\n // This makes the user's version the only match — no \"naming\n // conflicts\" warning, no glob-ordering games.\n globsExclude: frameworkExcludes,\n directoryAsNamespace: true,\n collapseSamePrefixes: true,\n resolvers: prefixedSources.length > 0 ? [prefixedResolver] : undefined,\n dts: dts ? resolve(dtsDir, 'components.d.ts') : false,\n }),\n ...(prefixedSourceWatcher ? [prefixedSourceWatcher] : []),\n ],\n resolve: {\n alias: {\n 'vue/server-renderer': resolve(vueServerRendererPkgDir, 'dist/server-renderer.esm-bundler.js'),\n 'vue': resolve(vuePkgDir, 'dist/vue.runtime.esm-bundler.js'),\n 'vue-router': vueRouterPkgDir,\n '@unhead/vue/server': resolve(unheadVuePkgDir, 'dist/server.mjs'),\n '@unhead/vue': resolve(unheadVuePkgDir, 'dist/index.mjs'),\n },\n },\n server: {\n middlewareMode: true,\n hmr: false,\n // Watcher is required so unplugin-vue-components and unplugin-auto-import\n // detect added/removed component files and rewrite their .d.ts on the fly.\n // (We only render via SSR — HMR is off, but chokidar still drives the plugins.)\n fs: {\n allow: [process.cwd(), root, ...componentDirs.map(s => s.path), vuePkgDir, vueServerRendererPkgDir, unheadVuePkgDir, vueRouterPkgDir],\n },\n },\n appType: 'custom',\n logLevel: 'silent',\n optimizeDeps: {\n noDiscovery: true,\n },\n }\n\n // Merge user's vite config (from config.vite) under Maizzle's config.\n // mergeConfig(a, b) → b overrides a for scalars, arrays are concatenated.\n // This ensures Maizzle's critical settings (middlewareMode, appType, etc.) always win,\n // while user plugins and other options are included.\n const finalConfig = userViteConfig\n ? mergeConfig(userViteConfig, maizzleConfig)\n : maizzleConfig\n\n const server = await createServer(finalConfig)\n\n return {\n async render(input: string | Component, config: MaizzleConfig): Promise<RenderedTemplate> {\n let component: Component\n let configKey: InjectionKey<MaizzleConfig>\n let contextKey: InjectionKey<RenderContext>\n\n if (typeof input === 'string') {\n // String input goes through Vite — must use ssrLoadModule for injection keys\n // so they share the same module instance as the SFC\n const configModule = await server.ssrLoadModule(resolve(__dirname, '../composables/useConfig'))\n const contextModule = await server.ssrLoadModule(resolve(__dirname, '../composables/renderContext'))\n configKey = configModule.MaizzleConfigKey\n contextKey = contextModule.RenderContextKey\n\n if (input.includes('<template') || input.includes('<script')) {\n virtualSfcSource = input\n const mod = server.moduleGraph.getModuleById(VIRTUAL_SFC_ID)\n if (mod) server.moduleGraph.invalidateModule(mod)\n component = (await server.ssrLoadModule(VIRTUAL_SFC_ID)).default\n } else {\n component = (await server.ssrLoadModule(input)).default\n }\n } else {\n // Pre-compiled component — use directly imported keys\n component = input\n configKey = MaizzleConfigKey\n contextKey = RenderContextKey\n }\n\n const renderContext: RenderContext = {\n doctype: undefined,\n sfcConfig: undefined,\n sfcEventHandlers: [],\n }\n\n const head = createHead({ disableDefaults: true })\n const app = createSSRApp(component)\n app.use(head)\n\n // Register user Vue plugins, directives, and global properties\n if (config.vue) {\n const plugins = typeof config.vue.plugins === 'function'\n ? config.vue.plugins()\n : config.vue.plugins ?? []\n for (const plugin of plugins) {\n app.use(plugin)\n }\n for (const [name, directive] of Object.entries(config.vue.directives ?? {})) {\n app.directive(name, directive)\n }\n Object.assign(app.config.globalProperties, config.vue.globalProperties)\n }\n\n app.provide(configKey, config)\n app.provide(contextKey, renderContext)\n\n const ssrContext: Record<string, any> = {}\n let html: string = await renderToString(app, ssrContext)\n\n const { headTags, bodyTags, bodyTagsOpen, htmlAttrs, bodyAttrs } = head.render()\n\n // Inject head entries into the rendered HTML\n if (htmlAttrs) {\n html = html.replace(/<html([^>]*)>/, `<html$1 ${htmlAttrs}>`)\n }\n if (headTags) {\n html = html.replace('</head>', `${headTags}\\n</head>`)\n }\n if (bodyAttrs) {\n html = html.replace(/<body([^>]*)>/, `<body$1 ${bodyAttrs}>`)\n }\n if (bodyTagsOpen) {\n html = html.replace(/<body([^>]*)>/, `<body$1>\\n${bodyTagsOpen}`)\n }\n if (bodyTags) {\n html = html.replace('</body>', `${bodyTags}\\n</body>`)\n }\n\n // Inject SSR teleport content into their target elements\n const hasTeleports = ssrContext.teleports && Object.keys(ssrContext.teleports).length > 0\n const hasFonts = (renderContext.fonts?.length ?? 0) > 0\n\n if (hasTeleports || hasFonts) {\n const { parse: parseDom, serialize: serializeDom, walk } = await import('../utils/ast/index.ts')\n let dom = parseDom(html)\n\n if (hasTeleports) {\n for (const [rawTarget, content] of Object.entries(ssrContext.teleports) as [string, string][]) {\n if (!content) continue\n\n const prepend = rawTarget.endsWith(':start')\n const target = prepend ? rawTarget.slice(0, -6) : rawTarget\n const targetChildren = parseDom(content)\n\n walk(dom, (node) => {\n const el = node as import('domhandler').Element\n\n if (!el.name) return\n\n const matched\n = target === el.name\n || (target.startsWith('#') && el.attribs?.id === target.slice(1))\n || (target.startsWith('.') && el.attribs?.class?.split(/\\s+/).includes(target.slice(1)))\n\n if (matched) {\n for (const child of targetChildren) {\n child.parent = el as any\n }\n\n el.children = prepend\n ? [...targetChildren, ...(el.children || [])] as any\n : [...(el.children || []), ...targetChildren] as any\n }\n })\n }\n }\n\n if (hasFonts) {\n const { injectFonts } = await import('./injectFonts.ts')\n injectFonts(dom, renderContext.fonts!, parseDom, walk)\n }\n\n html = serializeDom(dom)\n }\n\n // Inject preheader text from usePreheader() composable\n if (renderContext.preheader) {\n const { text, fillerCount } = renderContext.preheader\n const filler = '\\u2007\\uFEFF\\u034F '.repeat(fillerCount)\n const previewHtml = `<div style=\"display:none\">${text}${filler}\\u00A0</div>`\n html = html.replace(/<body([^>]*)>/, `<body$1>${previewHtml}`)\n }\n\n // Strip Vue SSR fragment markers + teleport anchor comments. These are\n // rendering hygiene, not transformer concerns — must run regardless of\n // `useTransformers` state. Fragment markers contain `-->`, which would\n // prematurely terminate MSO conditional comments downstream.\n html = html\n .replaceAll('<!--[-->', '')\n .replaceAll('<!--]-->', '')\n .replaceAll('<!--teleport start anchor-->', '')\n .replaceAll('<!--teleport anchor-->', '')\n .replaceAll('<!--teleport start-->', '')\n .replaceAll('<!--teleport end-->', '')\n\n return {\n html,\n doctype: renderContext.doctype,\n // Layer sfcConfig over config — sfcConfig is a partial override\n // emitted by composables (defineConfig, useTransformers, etc.).\n // A naive replacement (`sfcConfig ?? config`) drops defaults from\n // the resolved config when the SFC only sets a single key, since\n // the composables' inject() of globalConfig can return `{}` in\n // dev when ssrLoadModule and the SFC's auto-imported module\n // resolve to different module instances (different Symbols).\n templateConfig: renderContext.sfcConfig ? merge(renderContext.sfcConfig, config) : config,\n sfcEventHandlers: renderContext.sfcEventHandlers,\n plaintext: renderContext.plaintext,\n tailwindBlocks: renderContext.tailwindBlocks,\n }\n },\n\n async invalidate(filePath: string): Promise<void> {\n const mod = await server.moduleGraph.getModuleByUrl(filePath)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n }\n },\n\n async invalidateAll(): Promise<void> {\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n server.moduleGraph.invalidateModule(mod)\n }\n },\n\n async close(): Promise<void> {\n await server.close()\n // unplugin-auto-import schedules a 500ms-throttled, fire-and-forget\n // d.ts write on its first scan. server.close() doesn't drain that\n // pending write, so callers tearing down the working dir right after\n // close (tests, ephemeral build pipelines) can race the mkdir against\n // a missing parent directory. Wait one throttle window past close so\n // that lingering write resolves while the dir still exists.\n if (dts) {\n await new Promise(resolve => setTimeout(resolve, 600))\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,YAAY,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC;AAEzD,MAAM,YAAY,QAAQ,cAAc,OAAO,KAAK,QAAQ,mBAAmB,CAAC,CAAC;AACjF,MAAM,0BAA0B,QAAQ,cAAc,OAAO,KAAK,QAAQ,oCAAoC,CAAC,CAAC;AAChH,MAAM,kBAAkB,QAAQ,QAAQ,cAAc,OAAO,KAAK,QAAQ,cAAc,CAAC,CAAC,EAAE,KAAK;AACjG,MAAM,kBAAkB,QAAQ,cAAc,OAAO,KAAK,QAAQ,0BAA0B,CAAC,CAAC;;;;;;;AAwC9F,eAAsB,eACpB,UAAiC,EAAE,EAChB;CACnB,MAAM,EAAE,MAAM,OAAO,UAAU,oBAAoB,OAAO,QAAQ,KAAK,EAAE,gBAAgB,EAAE,EAAE,MAAM,mBAAmB;CACtH,MAAM,EAAE,aAAa,gBAAgB,GAAG,oBAAoB,sBAAsB,EAAE;CAKpF,MAAM,aAAa,cAAc,QAAO,MAAK,EAAE,WAAW,KAAA,EAAU;CACpE,MAAM,kBAAkB,cAAc,QAAO,MAAK,EAAE,WAAW,KAAA,EAAU;CAIzE,MAAM,mBAAmB,CAAC,QAAQ,MAAM,aAAa,EAAE,GAAG,cAAc,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AG,eAAe;;OAEjD;;IAIN,IAAI,UAAU;KACZ,MAAM,EAAE,gBAAgB,MAAM,OAAO;KACrC,YAAY,KAAK,cAAc,OAAQ,UAAU,KAAK;;IAGxD,OAAO,aAAa,IAAI;;GAI1B,IAAI,cAAc,WAAW;IAC3B,MAAM,EAAE,MAAM,gBAAgB,cAAc;IAE5C,MAAM,cAAc,6BAA6B,OADlC,OAAsB,OAAO,YACkB,CAAC;IAC/D,OAAO,KAAK,QAAQ,iBAAiB,WAAW,cAAc;;GAOhE,OAAO,KACJ,WAAW,YAAY,GAAG,CAC1B,WAAW,YAAY,GAAG,CAC1B,WAAW,gCAAgC,GAAG,CAC9C,WAAW,0BAA0B,GAAG,CACxC,WAAW,yBAAyB,GAAG,CACvC,WAAW,uBAAuB,GAAG;GAExC,OAAO;IACL;IACA,SAAS,cAAc;IAQvB,gBAAgB,cAAc,YAAYA,OAAM,cAAc,WAAW,OAAO,GAAG;IACnF,kBAAkB,cAAc;IAChC,WAAW,cAAc;IACzB,gBAAgB,cAAc;IAC/B;;EAGH,MAAM,WAAW,UAAiC;GAChD,MAAM,MAAM,MAAM,OAAO,YAAY,eAAe,SAAS;GAC7D,IAAI,KACF,OAAO,YAAY,iBAAiB,IAAI;;EAI5C,MAAM,gBAA+B;GACnC,KAAK,MAAM,OAAO,OAAO,YAAY,cAAc,QAAQ,EACzD,OAAO,YAAY,iBAAiB,IAAI;;EAI5C,MAAM,QAAuB;GAC3B,MAAM,OAAO,OAAO;GAOpB,IAAI,KACF,MAAM,IAAI,SAAQ,YAAW,WAAW,SAAS,IAAI,CAAC;;EAG3D"}
|
|
@@ -14,19 +14,29 @@ import { ChildNode } from "domhandler";
|
|
|
14
14
|
* Supports tag, class, id, and attribute selectors.
|
|
15
15
|
* Multiple selectors can be specified by comma-separating them.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* @param html HTML string to transform.
|
|
18
|
+
* @param config Attributes config (see {@link AttributesConfig}).
|
|
19
|
+
* @returns The transformed HTML string.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* import { addAttributes } from '@maizzle/framework'
|
|
23
|
+
*
|
|
24
|
+
* const out = addAttributes('<div></div>', {
|
|
20
25
|
* add: {
|
|
21
26
|
* div: { role: 'article' },
|
|
22
27
|
* '.test': { editable: true },
|
|
23
28
|
* '#header': { 'data-id': 'main' },
|
|
24
29
|
* 'div, p': { class: 'content' },
|
|
25
|
-
* }
|
|
26
|
-
* }
|
|
27
|
-
|
|
30
|
+
* },
|
|
31
|
+
* })
|
|
32
|
+
*/
|
|
33
|
+
declare function addAttributes(html: string, config?: AttributesConfig): string;
|
|
34
|
+
/**
|
|
35
|
+
* DOM-form of {@link addAttributes} used by the internal transformer pipeline.
|
|
36
|
+
* Takes a parsed DOM, returns a parsed DOM — avoids redundant
|
|
37
|
+
* serialize/parse round-trips when chained with other transformers.
|
|
28
38
|
*/
|
|
29
|
-
declare function
|
|
39
|
+
declare function addAttributesDom(dom: ChildNode[], config?: AttributesConfig): ChildNode[];
|
|
30
40
|
//#endregion
|
|
31
|
-
export { addAttributes };
|
|
41
|
+
export { addAttributes, addAttributesDom };
|
|
32
42
|
//# sourceMappingURL=addAttributes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"addAttributes.d.ts","names":[],"sources":["../../src/transformers/addAttributes.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"addAttributes.d.ts","names":[],"sources":["../../src/transformers/addAttributes.ts"],"mappings":";;;;;;AA+CA;;;;;;;;;AASA;;;;;;;;;;;;;;;;;iBATgB,aAAA,CAAc,IAAA,UAAc,MAAA,GAAQ,gBAAA;;;;;;iBASpC,gBAAA,CAAiB,GAAA,EAAK,SAAA,IAAa,MAAA,GAAQ,gBAAA,GAAwB,SAAA"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { parse } from "../utils/ast/parser.js";
|
|
1
2
|
import { walk } from "../utils/ast/walker.js";
|
|
3
|
+
import { serialize } from "../utils/ast/serializer.js";
|
|
2
4
|
import "../utils/ast/index.js";
|
|
3
5
|
import { defu as defu$1 } from "defu";
|
|
4
6
|
//#region src/transformers/addAttributes.ts
|
|
@@ -25,19 +27,31 @@ const DEFAULT_ATTRIBUTES = {
|
|
|
25
27
|
* Supports tag, class, id, and attribute selectors.
|
|
26
28
|
* Multiple selectors can be specified by comma-separating them.
|
|
27
29
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
30
|
+
* @param html HTML string to transform.
|
|
31
|
+
* @param config Attributes config (see {@link AttributesConfig}).
|
|
32
|
+
* @returns The transformed HTML string.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* import { addAttributes } from '@maizzle/framework'
|
|
36
|
+
*
|
|
37
|
+
* const out = addAttributes('<div></div>', {
|
|
31
38
|
* add: {
|
|
32
39
|
* div: { role: 'article' },
|
|
33
40
|
* '.test': { editable: true },
|
|
34
41
|
* '#header': { 'data-id': 'main' },
|
|
35
42
|
* 'div, p': { class: 'content' },
|
|
36
|
-
* }
|
|
37
|
-
* }
|
|
38
|
-
|
|
43
|
+
* },
|
|
44
|
+
* })
|
|
45
|
+
*/
|
|
46
|
+
function addAttributes(html, config = {}) {
|
|
47
|
+
return serialize(addAttributesDom(parse(html), config));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* DOM-form of {@link addAttributes} used by the internal transformer pipeline.
|
|
51
|
+
* Takes a parsed DOM, returns a parsed DOM — avoids redundant
|
|
52
|
+
* serialize/parse round-trips when chained with other transformers.
|
|
39
53
|
*/
|
|
40
|
-
function
|
|
54
|
+
function addAttributesDom(dom, config = {}) {
|
|
41
55
|
const addConfig = config.add;
|
|
42
56
|
if (addConfig === false) return dom;
|
|
43
57
|
const attributesToAdd = defu$1(typeof addConfig === "object" ? addConfig : {}, DEFAULT_ATTRIBUTES);
|
|
@@ -99,6 +113,6 @@ function elementMatches(el, selector) {
|
|
|
99
113
|
return el.name === selector;
|
|
100
114
|
}
|
|
101
115
|
//#endregion
|
|
102
|
-
export { addAttributes };
|
|
116
|
+
export { addAttributes, addAttributesDom };
|
|
103
117
|
|
|
104
118
|
//# sourceMappingURL=addAttributes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"addAttributes.js","names":["merge"],"sources":["../../src/transformers/addAttributes.ts"],"sourcesContent":["import { defu as merge } from 'defu'\nimport type { ChildNode, Element } from 'domhandler'\nimport { walk } from '../utils/ast/index.ts'\nimport type { AttributesConfig } from '../types/config.ts'\n\n/**\n * Default attributes to add to elements.\n */\nconst DEFAULT_ATTRIBUTES: Record<string, Record<string, string | boolean | number>> = {\n table: {\n cellpadding: 0,\n cellspacing: 0,\n role: 'none',\n },\n img: {\n alt: '',\n },\n}\n\n/**\n * Add attributes transformer.\n *\n * Automatically adds attributes to HTML elements based on CSS selectors.\n *\n * Default attributes (can be disabled by setting `attributes.add` to false):\n * - table: cellpadding=\"0\", cellspacing=\"0\", role=\"none\"\n * - img: alt=\"\"\n *\n * Supports tag, class, id, and attribute selectors.\n * Multiple selectors can be specified by comma-separating them.\n *\n *
|
|
1
|
+
{"version":3,"file":"addAttributes.js","names":["merge"],"sources":["../../src/transformers/addAttributes.ts"],"sourcesContent":["import { defu as merge } from 'defu'\nimport type { ChildNode, Element } from 'domhandler'\nimport { parse, serialize, walk } from '../utils/ast/index.ts'\nimport type { AttributesConfig } from '../types/config.ts'\n\n/**\n * Default attributes to add to elements.\n */\nconst DEFAULT_ATTRIBUTES: Record<string, Record<string, string | boolean | number>> = {\n table: {\n cellpadding: 0,\n cellspacing: 0,\n role: 'none',\n },\n img: {\n alt: '',\n },\n}\n\n/**\n * Add attributes transformer.\n *\n * Automatically adds attributes to HTML elements based on CSS selectors.\n *\n * Default attributes (can be disabled by setting `attributes.add` to false):\n * - table: cellpadding=\"0\", cellspacing=\"0\", role=\"none\"\n * - img: alt=\"\"\n *\n * Supports tag, class, id, and attribute selectors.\n * Multiple selectors can be specified by comma-separating them.\n *\n * @param html HTML string to transform.\n * @param config Attributes config (see {@link AttributesConfig}).\n * @returns The transformed HTML string.\n *\n * @example\n * import { addAttributes } from '@maizzle/framework'\n *\n * const out = addAttributes('<div></div>', {\n * add: {\n * div: { role: 'article' },\n * '.test': { editable: true },\n * '#header': { 'data-id': 'main' },\n * 'div, p': { class: 'content' },\n * },\n * })\n */\nexport function addAttributes(html: string, config: AttributesConfig = {}): string {\n return serialize(addAttributesDom(parse(html), config))\n}\n\n/**\n * DOM-form of {@link addAttributes} used by the internal transformer pipeline.\n * Takes a parsed DOM, returns a parsed DOM — avoids redundant\n * serialize/parse round-trips when chained with other transformers.\n */\nexport function addAttributesDom(dom: ChildNode[], config: AttributesConfig = {}): ChildNode[] {\n const addConfig = config.add\n\n // Disabled when explicitly set to false\n if (addConfig === false) {\n return dom\n }\n\n // Deep merge user attributes on top of defaults using defu\n const userAttributes = typeof addConfig === 'object' ? addConfig : {}\n const attributesToAdd = merge(userAttributes, DEFAULT_ATTRIBUTES) as Record<string, false | Record<string, false | string | boolean | number>>\n\n if (Object.keys(attributesToAdd).length === 0) {\n return dom\n }\n\n // Process each selector pattern\n for (const [selectorPattern, attributes] of Object.entries(attributesToAdd)) {\n // User opted out of this selector entirely (e.g. `table: false`)\n if (attributes === false) continue\n // Split by comma for multiple selectors\n const selectors = selectorPattern.split(',').map(s => s.trim())\n\n walk(dom, (node) => {\n const el = node as Element\n if (!el.name) return\n\n // Check if element matches any selector in the pattern\n const matches = selectors.some(selector => elementMatches(el, selector))\n\n if (matches) {\n // Initialize attribs if needed\n if (!el.attribs) {\n el.attribs = {}\n }\n\n for (const [attrName, attrValue] of Object.entries(attributes)) {\n // User opted out of this specific attribute (e.g. `role: false`)\n if (attrValue === false) continue\n // Special handling for class - merge instead of replace\n if (attrName === 'class' && el.attribs.class) {\n const existingClasses = el.attribs.class.split(/\\s+/).filter(Boolean)\n const newClasses = String(attrValue).split(/\\s+/).filter(Boolean)\n const mergedClasses = [...new Set([...existingClasses, ...newClasses])]\n if (mergedClasses.join(' ') !== el.attribs.class) {\n el.attribs.class = mergedClasses.join(' ')\n }\n } else {\n // Only add attribute if not already present\n if (!(attrName in el.attribs)) {\n el.attribs[attrName] = String(attrValue)\n }\n }\n }\n }\n })\n }\n\n return dom\n}\n\n/**\n * Check if an element matches a CSS selector.\n * Supports: tag, .class, #id, [attribute], [attribute=value]\n */\nfunction elementMatches(el: Element, selector: string): boolean {\n // Remove whitespace\n selector = selector.trim()\n\n // Check for attribute selector [attr] or [attr=value]\n const attrMatch = selector.match(/^\\[([^\\]=]+)(?:=([^\\]]*))?\\]$/)\n if (attrMatch) {\n const [, attrName, attrValue] = attrMatch\n if (attrValue === undefined) {\n // Just checking if attribute exists\n return attrName in (el.attribs || {})\n } else {\n // Check if attribute has specific value\n return el.attribs?.[attrName] === attrValue\n }\n }\n\n // Check for class selector .class\n if (selector.startsWith('.')) {\n const className = selector.slice(1)\n const classes = el.attribs?.class?.split(/\\s+/) || []\n return classes.includes(className)\n }\n\n // Check for id selector #id\n if (selector.startsWith('#')) {\n const id = selector.slice(1)\n return el.attribs?.id === id\n }\n\n // Check for tag selector (possibly with attribute)\n // Split tag from attribute if present, e.g., \"div[role=alert]\"\n const tagAttrMatch = selector.match(/^([a-z][a-z0-9]*)\\[([^\\]]+)\\]$/i)\n if (tagAttrMatch) {\n const [, tagName, attrPart] = tagAttrMatch\n if (el.name !== tagName) return false\n\n // Parse attribute part: could be \"attr\" or \"attr=value\"\n const attrEqMatch = attrPart.match(/^([^=]+)(?:=(.*))?$/)\n if (attrEqMatch) {\n const [, attrName, attrValue] = attrEqMatch\n if (attrValue === undefined) {\n return attrName in (el.attribs || {})\n } else {\n return el.attribs?.[attrName] === attrValue\n }\n }\n return false\n }\n\n // Simple tag selector\n return el.name === selector\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,qBAAgF;CACpF,OAAO;EACL,aAAa;EACb,aAAa;E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5C,IAAI,EAAE,YAAY,GAAG,UACnB,GAAG,QAAQ,YAAY,OAAO,UAAU;;;IAKhD;;CAGJ,OAAO;;;;;;AAOT,SAAS,eAAe,IAAa,UAA2B;CAE9D,WAAW,SAAS,MAAM;CAG1B,MAAM,YAAY,SAAS,MAAM,gCAAgC;CACjE,IAAI,WAAW;EACb,MAAM,GAAG,UAAU,aAAa;EAChC,IAAI,cAAc,KAAA,GAEhB,OAAO,aAAa,GAAG,WAAW,EAAE;OAGpC,OAAO,GAAG,UAAU,cAAc;;CAKtC,IAAI,SAAS,WAAW,IAAI,EAAE;EAC5B,MAAM,YAAY,SAAS,MAAM,EAAE;EAEnC,QADgB,GAAG,SAAS,OAAO,MAAM,MAAM,IAAI,EAAE,EACtC,SAAS,UAAU;;CAIpC,IAAI,SAAS,WAAW,IAAI,EAAE;EAC5B,MAAM,KAAK,SAAS,MAAM,EAAE;EAC5B,OAAO,GAAG,SAAS,OAAO;;CAK5B,MAAM,eAAe,SAAS,MAAM,kCAAkC;CACtE,IAAI,cAAc;EAChB,MAAM,GAAG,SAAS,YAAY;EAC9B,IAAI,GAAG,SAAS,SAAS,OAAO;EAGhC,MAAM,cAAc,SAAS,MAAM,sBAAsB;EACzD,IAAI,aAAa;GACf,MAAM,GAAG,UAAU,aAAa;GAChC,IAAI,cAAc,KAAA,GAChB,OAAO,aAAa,GAAG,WAAW,EAAE;QAEpC,OAAO,GAAG,UAAU,cAAc;;EAGtC,OAAO;;CAIT,OAAO,GAAG,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"columnWidth.d.ts","names":[],"sources":["../../src/transformers/columnWidth.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"columnWidth.d.ts","names":[],"sources":["../../src/transformers/columnWidth.ts"],"mappings":";;;;;AAyKA;;;;;;;;;;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,GAAA,EAAK,SAAA,KAAc,SAAA"}
|