{"version":3,"file":"lit-html.js","sources":["../../src/lit-html.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n// Use window for browser builds because IE11 doesn't have globalThis.\nconst global = NODE_MODE ? globalThis : window;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: HTMLElement | DocumentFragment;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n // Issue a warning, if we haven't already.\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (!global.litIssuedWarnings!.has(warning)) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? global.ShadyDOM!.wrap\n : (node: Node) => node;\n\nconst trustedTypes = (global as unknown as Partial).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${String(Math.random()).slice(9)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with