UNPKG

esbuild-plugin-lit

Version:

Import CSS, SVG, HTML, XLIFF files as tagged-template literals. Optionally minify with esbuild minifier.

70 lines 2.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.XLFLoader = void 0; const asset_loader_js_1 = require("./asset-loader.js"); class XLFLoader extends asset_loader_js_1.AssetLoader { extension = /\.xlf$/; minify = true; constructor(build, options = {}, specifier = "lit", minifier) { super(build, options, specifier, minifier); if (options.extension) this.extension = options.extension; if (options.transform) this.transform = options.transform; } load(input, filename) { const output = this.transform(input, filename); if (!this.minifier) return Promise.resolve(output); // TODO: throw? const nodes = this.minifier(output, { filter: (node) => node.tagName === "trans-unit", keepWhitespace: true, }); const messages = []; for (const unit of nodes) { const { id } = unit.attributes; if (!id) continue; //TODO: throw? const target = unit.children.find((node) => node.tagName === "target"); if (!target) continue; //not translated const parts = target.children; if (!parts.length) continue; //empty translation const strings = []; let hasExpression = false; for (const part of parts) { if (typeof part === "string") { strings.push(part); } else if (part.tagName === "x") { hasExpression = true; const partId = part.attributes["id"]; const text = part.attributes["equiv-text"]; strings.push(this.decodePart(text, partId)); } } messages.push(this.formatMessage(id, strings, hasExpression)); } return Promise.resolve(`import { html } from '${this.specifier}'; export const templates = {${messages.join(",")}};`); } decodePart(encoded, id) { return encoded .replace(/\$\{.*?\}/g, `\${${id}}`) .replace(/&amp;|&lt;|&gt;|&#39;|&quot;/g, (tag) => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&#39;": "'", "&quot;": '"', }[tag] || tag)); } formatMessage(id, strings, hasExpression) { return hasExpression ? `"${id}": html\`${strings.join("")}\`` : `"${id}": \`${strings.join("")}\``; } } exports.XLFLoader = XLFLoader; //# sourceMappingURL=xlf-loader.js.map