UNPKG

@lwc/ssr-runtime

Version:

Runtime complement to @lwc/ssr-compiler

1,328 lines (1,302 loc) 76.3 kB
/** * Copyright (c) 2025 Salesforce, Inc. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ /* v8 ignore start */ // Stubs for all the un-implemented exports from @lwc/engine-server function api(..._) { throw new Error('@api cannot be used in SSR context.'); } function createElement(..._) { throw new Error('createElement cannot be used in SSR context.'); } function freezeTemplate(..._) { throw new Error('freezeTemplate cannot be used in SSR context.'); } function getComponentDef(..._) { throw new Error('getComponentDef cannot be used in SSR context.'); } function isComponentConstructor(..._) { throw new Error('isComponentConstructor cannot be used in SSR context.'); } function parseFragment(..._) { throw new Error('parseFragment cannot be used in SSR context.'); } function parseSVGFragment(..._) { throw new Error('parseSVGFragment cannot be used in SSR context.'); } function registerComponent(..._) { throw new Error('registerComponent cannot be used in SSR context.'); } function registerDecorators(..._) { throw new Error('registerDecorators cannot be used in SSR context.'); } function registerTemplate(..._) { throw new Error('registerTemplate cannot be used in SSR context.'); } function sanitizeAttribute(..._) { throw new Error('sanitizeAttribute cannot be used in SSR context.'); } function setFeatureFlag(..._) { throw new Error('setFeatureFlag cannot be used in SSR context.'); } function setFeatureFlagForTest(..._) { throw new Error('setFeatureFlagForTest cannot be used in SSR context.'); } function swapComponent(..._) { throw new Error('swapComponent cannot be used in SSR context.'); } function swapStyle(..._) { throw new Error('swapStyle cannot be used in SSR context.'); } function swapTemplate(..._) { throw new Error('swapTemplate cannot be used in SSR context.'); } function track(..._) { throw new Error('@track cannot be used in SSR context.'); } function unwrap$1(..._) { throw new Error('unwrap cannot be used in SSR context.'); } function wire(..._) { throw new Error('@wire cannot be used in SSR context.'); } function setContextKeys(..._) { throw new Error('@setContextKeys cannot be used in SSR context.'); } function setTrustedContextSet(..._) { throw new Error('setTrustedContextSet cannot be used in SSR context.'); } const renderer = { isSyntheticShadowDefined: false, insert(..._) { throw new Error('renderer.insert cannot be used in SSR context.'); }, remove(..._) { throw new Error('renderer.remove cannot be used in SSR context.'); }, cloneNode(..._) { throw new Error('renderer.cloneNode cannot be used in SSR context.'); }, createFragment(..._) { throw new Error('renderer.createFragment cannot be used in SSR context.'); }, createElement(..._) { throw new Error('renderer.createElement cannot be used in SSR context.'); }, createText(..._) { throw new Error('renderer.createText cannot be used in SSR context.'); }, createComment(..._) { throw new Error('renderer.createComment cannot be used in SSR context.'); }, createCustomElement(..._) { throw new Error('renderer.createCustomElement cannot be used in SSR context.'); }, nextSibling(..._) { throw new Error('renderer.nextSibling cannot be used in SSR context.'); }, previousSibling(..._) { throw new Error('renderer.previousSibling cannot be used in SSR context.'); }, attachShadow(..._) { throw new Error('renderer.attachShadow cannot be used in SSR context.'); }, getProperty(..._) { throw new Error('renderer.getProperty cannot be used in SSR context.'); }, setProperty(..._) { throw new Error('renderer.setProperty cannot be used in SSR context.'); }, setText(..._) { throw new Error('renderer.setText cannot be used in SSR context.'); }, getAttribute(..._) { throw new Error('renderer.getAttribute cannot be used in SSR context.'); }, setAttribute(..._) { throw new Error('renderer.setAttribute cannot be used in SSR context.'); }, removeAttribute(..._) { throw new Error('renderer.removeAttribute cannot be used in SSR context.'); }, addEventListener(..._) { throw new Error('renderer.addEventListener cannot be used in SSR context.'); }, removeEventListener(..._) { throw new Error('renderer.removeEventListener cannot be used in SSR context.'); }, dispatchEvent(..._) { throw new Error('renderer.dispatchEvent cannot be used in SSR context.'); }, getClassList(..._) { throw new Error('renderer.getClassList cannot be used in SSR context.'); }, setCSSStyleProperty(..._) { throw new Error('renderer.setCSSStyleProperty cannot be used in SSR context.'); }, getBoundingClientRect(..._) { throw new Error('renderer.getBoundingClientRect cannot be used in SSR context.'); }, querySelector(..._) { throw new Error('renderer.querySelector cannot be used in SSR context.'); }, querySelectorAll(..._) { throw new Error('renderer.querySelectorAll cannot be used in SSR context.'); }, getElementsByTagName(..._) { throw new Error('renderer.getElementsByTagName cannot be used in SSR context.'); }, getElementsByClassName(..._) { throw new Error('renderer.getElementsByClassName cannot be used in SSR context.'); }, getChildren(..._) { throw new Error('renderer.getChildren cannot be used in SSR context.'); }, getChildNodes(..._) { throw new Error('renderer.getChildNodes cannot be used in SSR context.'); }, getFirstChild(..._) { throw new Error('renderer.getFirstChild cannot be used in SSR context.'); }, getFirstElementChild(..._) { throw new Error('renderer.getFirstElementChild cannot be used in SSR context.'); }, getLastChild(..._) { throw new Error('renderer.getLastChild cannot be used in SSR context.'); }, getLastElementChild(..._) { throw new Error('renderer.getLastElementChild cannot be used in SSR context.'); }, getTagName(..._) { throw new Error('renderer.getTagName cannot be used in SSR context.'); }, getStyle(..._) { throw new Error('renderer.getStyle cannot be used in SSR context.'); }, isConnected(..._) { throw new Error('renderer.isConnected cannot be used in SSR context.'); }, insertStylesheet(..._) { throw new Error('renderer.insertStylesheet cannot be used in SSR context.'); }, assertInstanceOfHTMLElement(..._) { throw new Error('renderer.assertInstanceOfHTMLElement cannot be used in SSR context.'); }, ownerDocument(..._) { throw new Error('renderer.ownerDocument cannot be used in SSR context.'); }, registerContextConsumer(..._) { throw new Error('renderer.registerContextConsumer cannot be used in SSR context.'); }, attachInternals(..._) { throw new Error('renderer.attachInternals cannot be used in SSR context.'); }, defineCustomElement(..._) { throw new Error('renderer.defineCustomElement cannot be used in SSR context.'); }, getParentNode(..._) { throw new Error('renderer.getParentNode cannot be used in SSR context.'); }, startTrackingMutations(..._) { throw new Error('renderer.startTrackingMutations cannot be used in SSR context.'); }, stopTrackingMutations(..._) { throw new Error('renderer.stopTrackingMutations cannot be used in SSR context.'); }, }; /** * The hot API is used to orchestrate hot swapping in client rendered components. * It doesn't do anything on the server side, however, you may import it. * * The whole point of defining this and exporting it is so that you can import it in isomorphic code without * an error being thrown by the import itself. */ // A real stub, not a "not implemented" one! 😯 const hot = undefined; /* v8 ignore stop */ /** * Copyright (c) 2025 Salesforce, Inc. */ /* * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ /** * * @param value * @param msg */ /** * * @param value * @param msg */ function isFalse$1(value, msg) { if (value) { throw new Error(`Assert Violation: ${msg}`); } } /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ const { /** Detached {@linkcode Object.assign}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign MDN Reference}. */ assign, /** Detached {@linkcode Object.create}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create MDN Reference}. */ create, /** Detached {@linkcode Object.defineProperties}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties MDN Reference}. */ defineProperties, /** Detached {@linkcode Object.entries}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries MDN Reference}. */ entries, /** Detached {@linkcode Object.getOwnPropertyNames}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames MDN Reference}. */ getOwnPropertyNames: getOwnPropertyNames$1, /** Detached {@linkcode Object.hasOwnProperty}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty MDN Reference}. */ hasOwnProperty: hasOwnProperty$1, /** Detached {@linkcode Object.keys}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys MDN Reference}. */ keys} = Object; const { /** Detached {@linkcode Array.isArray}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray MDN Reference}. */ isArray: isArray$1} = Array; // For some reason, JSDoc don't get picked up for multiple renamed destructured constants (even // though it works fine for one, e.g. isArray), so comments for these are added to the export // statement, rather than this declaration. const { join: ArrayJoin, map: ArrayMap, forEach, // Weird anomaly! } = Array.prototype; /** Detached {@linkcode String.fromCharCode}; see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode MDN Reference}. */ const { fromCharCode: StringFromCharCode } = String; // No JSDocs here - see comment for Array.prototype const { charCodeAt: StringCharCodeAt, replace: StringReplace, toLowerCase: StringToLowerCase, trim: StringTrim, } = String.prototype; /** * Determines whether the argument is `undefined`. * @param obj Value to test * @returns `true` if the value is `undefined`. */ function isUndefined$1(obj) { return obj === undefined; } /** * Determines whether the argument is `null`. * @param obj Value to test * @returns `true` if the value is `null`. */ function isNull(obj) { return obj === null; } /** * Determines whether the argument is an object or null. * @param obj Value to test * @returns `true` if the value is an object or null. */ function isObject(obj) { return typeof obj === 'object'; } /** * Determines whether the argument is a string. * @param obj Value to test * @returns `true` if the value is a string. */ function isString(obj) { return typeof obj === 'string'; } const OtS = {}.toString; /** * Converts the argument to a string, safely accounting for objects with "null" prototype. * Note that `toString(null)` returns `"[object Null]"` rather than `"null"`. * @param obj Value to convert to a string. * @returns String representation of the value. */ function toString(obj) { if (obj?.toString) { // Arrays might hold objects with "null" prototype So using // Array.prototype.toString directly will cause an error Iterate through // all the items and handle individually. if (isArray$1(obj)) { // This behavior is slightly different from Array#toString: // 1. Array#toString calls `this.join`, rather than Array#join // Ex: arr = []; arr.join = () => 1; arr.toString() === 1; toString(arr) === '' // 2. Array#toString delegates to Object#toString if `this.join` is not a function // Ex: arr = []; arr.join = 'no'; arr.toString() === '[object Array]; toString(arr) = '' // 3. Array#toString converts null/undefined to '' // Ex: arr = [null, undefined]; arr.toString() === ','; toString(arr) === '[object Null],undefined' // 4. Array#toString converts recursive references to arrays to '' // Ex: arr = [1]; arr.push(arr, 2); arr.toString() === '1,,2'; toString(arr) throws // Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString return ArrayJoin.call(ArrayMap.call(obj, toString), ','); } return obj.toString(); } else if (typeof obj === 'object') { // This catches null and returns "[object Null]". Weird, but kept for backwards compatibility. return OtS.call(obj); } else { return String(obj); } } /* * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ /** * According to the following list, there are 48 aria attributes of which two (ariaDropEffect and * ariaGrabbed) are deprecated: * https://www.w3.org/TR/wai-aria-1.1/#x6-6-definitions-of-states-and-properties-all-aria-attributes * * The above list of 46 aria attributes is consistent with the following resources: * https://github.com/w3c/aria/pull/708/files#diff-eacf331f0ffc35d4b482f1d15a887d3bR11060 * https://wicg.github.io/aom/spec/aria-reflection.html * * NOTE: If you update this list, please update test files that implicitly reference this list! * Searching the codebase for `aria-flowto` and `ariaFlowTo` should be good enough to find all usages. */ const AriaPropertyNames = [ 'ariaActiveDescendant', 'ariaAtomic', 'ariaAutoComplete', 'ariaBusy', 'ariaChecked', 'ariaColCount', 'ariaColIndex', 'ariaColIndexText', 'ariaColSpan', 'ariaControls', 'ariaCurrent', 'ariaDescribedBy', 'ariaDescription', 'ariaDetails', 'ariaDisabled', 'ariaErrorMessage', 'ariaExpanded', 'ariaFlowTo', 'ariaHasPopup', 'ariaHidden', 'ariaInvalid', 'ariaKeyShortcuts', 'ariaLabel', 'ariaLabelledBy', 'ariaLevel', 'ariaLive', 'ariaModal', 'ariaMultiLine', 'ariaMultiSelectable', 'ariaOrientation', 'ariaOwns', 'ariaPlaceholder', 'ariaPosInSet', 'ariaPressed', 'ariaReadOnly', 'ariaRelevant', 'ariaRequired', 'ariaRoleDescription', 'ariaRowCount', 'ariaRowIndex', 'ariaRowIndexText', 'ariaRowSpan', 'ariaSelected', 'ariaSetSize', 'ariaSort', 'ariaValueMax', 'ariaValueMin', 'ariaValueNow', 'ariaValueText', 'ariaBrailleLabel', 'ariaBrailleRoleDescription', 'role', ]; const { AriaAttrNameToPropNameMap, AriaPropNameToAttrNameMap } = /*@__PURE__*/ (() => { const AriaAttrNameToPropNameMap = create(null); const AriaPropNameToAttrNameMap = create(null); // Synthetic creation of all AOM property descriptors for Custom Elements forEach.call(AriaPropertyNames, (propName) => { const attrName = StringToLowerCase.call(StringReplace.call(propName, /^aria/, () => 'aria-')); // These type assertions are because the map types are a 1:1 mapping of ariaX to aria-x. // TypeScript knows we have one of ariaX | ariaY and one of aria-x | aria-y, and tries to // prevent us from doing ariaX: aria-y, but we that it's safe. AriaAttrNameToPropNameMap[attrName] = propName; AriaPropNameToAttrNameMap[propName] = attrName; }); return { AriaAttrNameToPropNameMap, AriaPropNameToAttrNameMap }; })(); /** * * @param attrName */ function isAriaAttribute(attrName) { return attrName in AriaAttrNameToPropNameMap; } // These are HTML standard prop/attribute IDL mappings, but are not predictable based on camel/kebab-case conversion const SPECIAL_PROPERTY_ATTRIBUTE_MAPPING = /*@__PURE__@*/ new Map([ ['accessKey', 'accesskey'], ['readOnly', 'readonly'], ['tabIndex', 'tabindex'], ['bgColor', 'bgcolor'], ['colSpan', 'colspan'], ['rowSpan', 'rowspan'], ['contentEditable', 'contenteditable'], ['crossOrigin', 'crossorigin'], ['dateTime', 'datetime'], ['formAction', 'formaction'], ['isMap', 'ismap'], ['maxLength', 'maxlength'], ['minLength', 'minlength'], ['noValidate', 'novalidate'], ['useMap', 'usemap'], ['htmlFor', 'for'], ]); // Global properties that this framework currently reflects. For CSR, the native // descriptors for these properties are added from HTMLElement.prototype to // LightningElement.prototype. For SSR, in order to match CSR behavior, this // list is used to determine which attributes to reflect. const REFLECTIVE_GLOBAL_PROPERTY_SET = /*@__PURE__@*/ new Set([ 'accessKey', 'dir', 'draggable', 'hidden', 'id', 'lang', 'spellcheck', 'tabIndex', 'title', ]); /** * Map associating previously transformed HTML property into HTML attribute. */ const CACHED_PROPERTY_ATTRIBUTE_MAPPING = /*@__PURE__@*/ new Map(); /** * * @param propName */ function htmlPropertyToAttribute(propName) { const ariaAttributeName = AriaPropNameToAttrNameMap[propName]; if (!isUndefined$1(ariaAttributeName)) { return ariaAttributeName; } const specialAttributeName = SPECIAL_PROPERTY_ATTRIBUTE_MAPPING.get(propName); if (!isUndefined$1(specialAttributeName)) { return specialAttributeName; } const cachedAttributeName = CACHED_PROPERTY_ATTRIBUTE_MAPPING.get(propName); if (!isUndefined$1(cachedAttributeName)) { return cachedAttributeName; } let attributeName = ''; for (let i = 0, len = propName.length; i < len; i++) { const code = StringCharCodeAt.call(propName, i); if (code >= 65 && // "A" code <= 90 // "Z" ) { attributeName += '-' + StringFromCharCode(code + 32); } else { attributeName += StringFromCharCode(code); } } CACHED_PROPERTY_ATTRIBUTE_MAPPING.set(propName, attributeName); return attributeName; } /* * Copyright (c) 2020, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ const ESCAPED_CHARS = { '"': '&quot;', "'": '&#x27;', '<': '&lt;', '>': '&gt;', '&': '&amp;', }; /** * * @param str * @param attrMode */ function htmlEscape(str, attrMode = false) { const searchValue = attrMode ? /["&]/g : /["'<>&]/g; return str.replace(searchValue, (char) => ESCAPED_CHARS[char]); } /* * Copyright (c) 2020, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ /** * [ncls] - Normalize class name attribute. * * Transforms the provided class property value from an object/string into a string the diffing algo * can operate on. * * This implementation is borrowed from Vue: * https://github.com/vuejs/core/blob/e790e1bdd7df7be39e14780529db86e4da47a3db/packages/shared/src/normalizeProp.ts#L63-L82 */ function normalizeClass(value) { if (isUndefined$1(value) || isNull(value)) { // Returning undefined here improves initial render cost, because the old vnode's class will be considered // undefined in the `patchClassAttribute` routine, so `oldClass === newClass` will be true so we return early return undefined; } let res = ''; if (isString(value)) { res = value; } else if (isArray$1(value)) { for (let i = 0; i < value.length; i++) { const normalized = normalizeClass(value[i]); if (normalized) { res += normalized + ' '; } } } else if (isObject(value) && !isNull(value)) { // Iterate own enumerable keys of the object const _keys = keys(value); for (let i = 0; i < _keys.length; i += 1) { const key = _keys[i]; if (value[key]) { res += key + ' '; } } } return StringTrim.call(res); } /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ let hooksAreSet = false; /** * EXPERIMENTAL: This function acts like a hook for Lightning Locker Service and other similar * libraries to sanitize HTML content. This hook process the content passed via the template to * lwc:inner-html directive. * It is meant to be overridden via `setHooks`; it throws an error by default. */ exports.sanitizeHtmlContent = () => { // locker-service patches this function during runtime to sanitize HTML content. throw new Error('sanitizeHtmlContent hook must be implemented.'); }; function setHooks(hooks) { isFalse$1(hooksAreSet, 'Hooks are already overridden, only one definition is allowed.'); hooksAreSet = true; exports.sanitizeHtmlContent = hooks.sanitizeHtmlContent; } /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ const DEFAULT_SSR_MODE = 'sync'; /* * Copyright (c) 2025, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ /** * Global HTML "tabindex" attribute is specially massaged into a stringified number * This follows the historical behavior in api.ts: * https://github.com/salesforce/lwc/blob/f34a347/packages/%40lwc/engine-core/src/framework/api.ts#L193-L211 */ function normalizeTabIndex(value) { const shouldNormalize = value > 0 && typeof value !== 'boolean'; return shouldNormalize ? 0 : value; } /** version: 8.20.0 */ /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ const MULTI_SPACE = /\s+/g; function parseClassName(className) { return (className ?? '') .split(MULTI_SPACE) .map((item) => item.trim()) .filter(Boolean); } class ClassList { constructor(el) { this.el = el; } add(...newClassNames) { const set = new Set(parseClassName(this.el.className)); for (const newClassName of newClassNames) { set.add(newClassName); } this.el.className = Array.from(set).join(' '); } contains(className) { return parseClassName(this.el.className).includes(className); } remove(...classNamesToRemove) { const set = new Set(parseClassName(this.el.className)); for (const newClassName of classNamesToRemove) { set.delete(newClassName); } this.el.className = Array.from(set).join(' '); } replace(oldClassName, newClassName) { let classWasReplaced = false; const listOfClasses = parseClassName(this.el.className); listOfClasses.forEach((value, idx) => { if (value === oldClassName) { classWasReplaced = true; listOfClasses[idx] = newClassName; } }); this.el.className = listOfClasses.join(' '); return classWasReplaced; } toggle(classNameToToggle, force) { const set = new Set(parseClassName(this.el.className)); if (!set.has(classNameToToggle) && force !== false) { set.add(classNameToToggle); } else if (set.has(classNameToToggle) && force !== true) { set.delete(classNameToToggle); } this.el.className = Array.from(set).join(' '); return set.has(classNameToToggle); } get value() { return this.el.className; } toString() { return this.el.className; } get length() { return parseClassName(this.el.className).length; } item(index) { return parseClassName(this.el.className ?? '')[index] ?? null; } forEach(callbackFn, thisArg) { parseClassName(this.el.className).forEach((value, index) => callbackFn.call(thisArg, value, index, this)); } // This method is present on DOMTokenList but throws an error in the browser when used // in connection with Element#classList. supports(_token) { throw new TypeError('DOMTokenList has no supported tokens.'); } } /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ var _MutationTracker_enabledSet, _MutationTracker_mutationMap; class MutationTracker { constructor() { _MutationTracker_enabledSet.set(this, new WeakSet()); _MutationTracker_mutationMap.set(this, new WeakMap()); } add(instance, attrName) { if (__classPrivateFieldGet(this, _MutationTracker_enabledSet, "f").has(instance)) { let mutatedAttrs = __classPrivateFieldGet(this, _MutationTracker_mutationMap, "f").get(instance); if (!mutatedAttrs) { mutatedAttrs = new Set(); __classPrivateFieldGet(this, _MutationTracker_mutationMap, "f").set(instance, mutatedAttrs); } mutatedAttrs.add(attrName.toLowerCase()); } } enable(instance) { __classPrivateFieldGet(this, _MutationTracker_enabledSet, "f").add(instance); } disable(instance) { __classPrivateFieldGet(this, _MutationTracker_enabledSet, "f").delete(instance); } renderMutatedAttrs(instance) { const mutatedAttrs = __classPrivateFieldGet(this, _MutationTracker_mutationMap, "f").get(instance); if (mutatedAttrs) { return ` data-lwc-host-mutated="${[...mutatedAttrs].sort().join(' ')}"`; } else { return ''; } } } _MutationTracker_enabledSet = new WeakMap(), _MutationTracker_mutationMap = new WeakMap(); const mutationTracker = new MutationTracker(); /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ /** * Descriptor for IDL attribute reflections that merely reflect the string, e.g. `title`. */ const stringDescriptor = (attrName) => ({ configurable: true, enumerable: true, get() { return this.getAttribute(attrName); }, set(newValue) { const currentValue = this.getAttribute(attrName); const normalizedValue = String(newValue); if (normalizedValue !== currentValue) { this.setAttribute(attrName, normalizedValue); } }, }); /** Descriptor for a boolean that checks for `attr="true"` or `attr="false"`, e.g. `spellcheck` and `draggable`. */ const explicitBooleanDescriptor = (attrName, defaultValue) => ({ configurable: true, enumerable: true, get() { const value = this.getAttribute(attrName); if (value === null) return defaultValue; // spellcheck=false => false, everything else => true // draggable=true => true, everything else => false return value.toLowerCase() === String(defaultValue) ? defaultValue : !defaultValue; }, set(newValue) { const currentValue = this.getAttribute(attrName); const normalizedValue = String(Boolean(newValue)); if (normalizedValue !== currentValue) { this.setAttribute(attrName, normalizedValue); } }, }); /** * Descriptor for a "true" boolean attribute that checks solely for presence, e.g. `hidden`. */ const booleanAttributeDescriptor = (attrName) => ({ configurable: true, enumerable: true, get() { return this.hasAttribute(attrName); }, set(newValue) { const hasAttribute = this.hasAttribute(attrName); if (newValue) { if (!hasAttribute) { this.setAttribute(attrName, ''); } } else { if (hasAttribute) { this.removeAttribute(attrName); } } }, }); /** * Descriptor for ARIA reflections, e.g. `ariaLabel` and `role`. */ const ariaDescriptor = (attrName) => ({ configurable: true, enumerable: true, get() { return this.getAttribute(attrName); }, set(newValue) { const currentValue = this.getAttribute(attrName); if (newValue !== currentValue) { // TODO [#3284]: According to the spec, IDL nullable type values // (null and undefined) should remove the attribute; however, we // only do so in the case of null for historical reasons. if (isNull(newValue)) { this.removeAttribute(attrName); } else { this.setAttribute(attrName, toString(newValue)); } } }, }); const tabIndexDescriptor = () => ({ configurable: true, enumerable: true, get() { const str = this.getAttribute('tabindex'); const num = Number(str); return isFinite(num) ? Math.trunc(num) : -1; }, set(newValue) { const currentValue = this.getAttribute('tabindex'); const num = Number(newValue); const normalizedValue = isFinite(num) ? String(Math.trunc(num)) : '0'; if (normalizedValue !== currentValue) { this.setAttribute('tabindex', toString(newValue)); } }, }); const descriptors = { accessKey: stringDescriptor('accesskey'), dir: stringDescriptor('dir'), draggable: explicitBooleanDescriptor('draggable', true), hidden: booleanAttributeDescriptor('hidden'), id: stringDescriptor('id'), lang: stringDescriptor('lang'), spellcheck: explicitBooleanDescriptor('spellcheck', false), tabIndex: tabIndexDescriptor(), title: stringDescriptor('title'), }; // Add descriptors for ARIA attributes for (const [attrName, propName] of entries(AriaAttrNameToPropNameMap)) { descriptors[propName] = ariaDescriptor(attrName); } /** * Copyright (C) 2017 salesforce.com, inc. */ const { isArray } = Array; const { prototype: ObjectDotPrototype, getPrototypeOf, create: ObjectCreate, defineProperty: ObjectDefineProperty, isExtensible, getOwnPropertyDescriptor, getOwnPropertyNames, getOwnPropertySymbols, preventExtensions, hasOwnProperty, } = Object; const { push: ArrayPush, concat: ArrayConcat } = Array.prototype; function isUndefined(obj) { return obj === undefined; } function isFunction(obj) { return typeof obj === 'function'; } const proxyToValueMap = new WeakMap(); function registerProxy(proxy, value) { proxyToValueMap.set(proxy, value); } const unwrap = (replicaOrAny) => proxyToValueMap.get(replicaOrAny) || replicaOrAny; class BaseProxyHandler { constructor(membrane, value) { this.originalTarget = value; this.membrane = membrane; } // Shared utility methods wrapDescriptor(descriptor) { if (hasOwnProperty.call(descriptor, 'value')) { descriptor.value = this.wrapValue(descriptor.value); } else { const { set: originalSet, get: originalGet } = descriptor; if (!isUndefined(originalGet)) { descriptor.get = this.wrapGetter(originalGet); } if (!isUndefined(originalSet)) { descriptor.set = this.wrapSetter(originalSet); } } return descriptor; } copyDescriptorIntoShadowTarget(shadowTarget, key) { const { originalTarget } = this; // Note: a property might get defined multiple times in the shadowTarget // but it will always be compatible with the previous descriptor // to preserve the object invariants, which makes these lines safe. const originalDescriptor = getOwnPropertyDescriptor(originalTarget, key); // TODO: it should be impossible for the originalDescriptor to ever be undefined, this `if` can be removed /* istanbul ignore else */ if (!isUndefined(originalDescriptor)) { const wrappedDesc = this.wrapDescriptor(originalDescriptor); ObjectDefineProperty(shadowTarget, key, wrappedDesc); } } lockShadowTarget(shadowTarget) { const { originalTarget } = this; const targetKeys = ArrayConcat.call(getOwnPropertyNames(originalTarget), getOwnPropertySymbols(originalTarget)); targetKeys.forEach((key) => { this.copyDescriptorIntoShadowTarget(shadowTarget, key); }); const { membrane: { tagPropertyKey }, } = this; if (!isUndefined(tagPropertyKey) && !hasOwnProperty.call(shadowTarget, tagPropertyKey)) { ObjectDefineProperty(shadowTarget, tagPropertyKey, ObjectCreate(null)); } preventExtensions(shadowTarget); } // Shared Traps // TODO: apply() is never called /* istanbul ignore next */ apply(shadowTarget, thisArg, argArray) { /* No op */ } // TODO: construct() is never called /* istanbul ignore next */ construct(shadowTarget, argArray, newTarget) { /* No op */ } get(shadowTarget, key) { const { originalTarget, membrane: { valueObserved }, } = this; const value = originalTarget[key]; valueObserved(originalTarget, key); return this.wrapValue(value); } has(shadowTarget, key) { const { originalTarget, membrane: { tagPropertyKey, valueObserved }, } = this; valueObserved(originalTarget, key); // since key is never going to be undefined, and tagPropertyKey might be undefined // we can simply compare them as the second part of the condition. return key in originalTarget || key === tagPropertyKey; } ownKeys(shadowTarget) { const { originalTarget, membrane: { tagPropertyKey }, } = this; // if the membrane tag key exists and it is not in the original target, we add it to the keys. const keys = isUndefined(tagPropertyKey) || hasOwnProperty.call(originalTarget, tagPropertyKey) ? [] : [tagPropertyKey]; // small perf optimization using push instead of concat to avoid creating an extra array ArrayPush.apply(keys, getOwnPropertyNames(originalTarget)); ArrayPush.apply(keys, getOwnPropertySymbols(originalTarget)); return keys; } isExtensible(shadowTarget) { const { originalTarget } = this; // optimization to avoid attempting to lock down the shadowTarget multiple times if (!isExtensible(shadowTarget)) { return false; // was already locked down } if (!isExtensible(originalTarget)) { this.lockShadowTarget(shadowTarget); return false; } return true; } getPrototypeOf(shadowTarget) { const { originalTarget } = this; return getPrototypeOf(originalTarget); } getOwnPropertyDescriptor(shadowTarget, key) { const { originalTarget, membrane: { valueObserved, tagPropertyKey }, } = this; // keys looked up via getOwnPropertyDescriptor need to be reactive valueObserved(originalTarget, key); let desc = getOwnPropertyDescriptor(originalTarget, key); if (isUndefined(desc)) { if (key !== tagPropertyKey) { return undefined; } // if the key is the membrane tag key, and is not in the original target, // we produce a synthetic descriptor and install it on the shadow target desc = { value: undefined, writable: false, configurable: false, enumerable: false }; ObjectDefineProperty(shadowTarget, tagPropertyKey, desc); return desc; } if (desc.configurable === false) { // updating the descriptor to non-configurable on the shadow this.copyDescriptorIntoShadowTarget(shadowTarget, key); } // Note: by accessing the descriptor, the key is marked as observed // but access to the value, setter or getter (if available) cannot observe // mutations, just like regular methods, in which case we just do nothing. return this.wrapDescriptor(desc); } } const getterMap$1 = new WeakMap(); const setterMap$1 = new WeakMap(); const reverseGetterMap = new WeakMap(); const reverseSetterMap = new WeakMap(); class ReactiveProxyHandler extends BaseProxyHandler { wrapValue(value) { return this.membrane.getProxy(value); } wrapGetter(originalGet) { const wrappedGetter = getterMap$1.get(originalGet); if (!isUndefined(wrappedGetter)) { return wrappedGetter; } const handler = this; const get = function () { // invoking the original getter with the original target return handler.wrapValue(originalGet.call(unwrap(this))); }; getterMap$1.set(originalGet, get); reverseGetterMap.set(get, originalGet); return get; } wrapSetter(originalSet) { const wrappedSetter = setterMap$1.get(originalSet); if (!isUndefined(wrappedSetter)) { return wrappedSetter; } const set = function (v) { // invoking the original setter with the original target originalSet.call(unwrap(this), unwrap(v)); }; setterMap$1.set(originalSet, set); reverseSetterMap.set(set, originalSet); return set; } unwrapDescriptor(descriptor) { if (hasOwnProperty.call(descriptor, 'value')) { // dealing with a data descriptor descriptor.value = unwrap(descriptor.value); } else { const { set, get } = descriptor; if (!isUndefined(get)) { descriptor.get = this.unwrapGetter(get); } if (!isUndefined(set)) { descriptor.set = this.unwrapSetter(set); } } return descriptor; } unwrapGetter(redGet) { const reverseGetter = reverseGetterMap.get(redGet); if (!isUndefined(reverseGetter)) { return reverseGetter; } const handler = this; const get = function () { // invoking the red getter with the proxy of this return unwrap(redGet.call(handler.wrapValue(this))); }; getterMap$1.set(get, redGet); reverseGetterMap.set(redGet, get); return get; } unwrapSetter(redSet) { const reverseSetter = reverseSetterMap.get(redSet); if (!isUndefined(reverseSetter)) { return reverseSetter; } const handler = this; const set = function (v) { // invoking the red setter with the proxy of this redSet.call(handler.wrapValue(this), handler.wrapValue(v)); }; setterMap$1.set(set, redSet); reverseSetterMap.set(redSet, set); return set; } set(shadowTarget, key, value) { const { originalTarget, membrane: { valueMutated }, } = this; const oldValue = originalTarget[key]; if (oldValue !== value) { originalTarget[key] = value; valueMutated(originalTarget, key); } else if (key === 'length' && isArray(originalTarget)) { // fix for issue #236: push will add the new index, and by the time length // is updated, the internal length is already equal to the new length value // therefore, the oldValue is equal to the value. This is the forking logic // to support this use case. valueMutated(originalTarget, key); } return true; } deleteProperty(shadowTarget, key) { const { originalTarget, membrane: { valueMutated }, } = this; delete originalTarget[key]; valueMutated(originalTarget, key); return true; } setPrototypeOf(shadowTarget, prototype) { } preventExtensions(shadowTarget) { if (isExtensible(shadowTarget)) { const { originalTarget } = this; preventExtensions(originalTarget); // if the originalTarget is a proxy itself, it might reject // the preventExtension call, in which case we should not attempt to lock down // the shadow target. // TODO: It should not actually be possible to reach this `if` statement. // If a proxy rejects extensions, then calling preventExtensions will throw an error: // https://codepen.io/nolanlawson-the-selector/pen/QWMOjbY /* istanbul ignore if */ if (isExtensible(originalTarget)) { return false; } this.lockShadowTarget(shadowTarget); } return true; } defineProperty(shadowTarget, key, descriptor) { const { originalTarget, membrane: { valueMutated, tagPropertyKey }, } = this; if (key === tagPropertyKey && !hasOwnProperty.call(originalTarget, key)) { // To avoid leaking the membrane tag property into the original target, we must // be sure that the original target doesn't have yet. // NOTE: we do not return false here because Object.freeze and equivalent operations // will attempt to set the descriptor to the same value, and expect no to throw. This // is an small compromise for the sake of not having to diff the descriptors. return true; } ObjectDefineProperty(originalTarget, key, this.unwrapDescriptor(descriptor)); // intentionally testing if false since it could be undefined as well if (descriptor.configurable === false) { this.copyDescriptorIntoShadowTarget(shadowTarget, key); } valueMutated(originalTarget, key); return true; } } const getterMap = new WeakMap(); const setterMap = new WeakMap(); class ReadOnlyHandler extends BaseProxyHandler { wrapValue(value) { return this.membrane.getReadOnlyProxy(value); } wrapGetter(originalGet) { const wrappedGetter = getterMap.get(originalGet); if (!isUndefined(wrappedGetter)) { return wrappedGetter; } const handler = this; const get = function () { // invoking the original getter with the original target return handler.wrapValue(originalGet.call(unwrap(this))); }; getterMap.set(originalGet, get); return get; } wrapSetter(originalSet) { const wrappedSetter = setterMap.get(originalSet); if (!isUndefined(wrappedSetter)) { return wrappedSetter; } const set = function (v) { }; setterMap.set(originalSet, set); return set; } set(shadowTarget, key, value) { /* istanbul ignore next */ return false; } deleteProperty(shadowTarget, key) { /* istanbul ignore next */ return false; } setPrototypeOf(shadowTarget, prototype) { } preventExtensions(shadowTarget) { /* istanbul ignore next */ return false; } defineProperty(shadowTarget, key, descriptor) { /* istanbul ignore next */ return false; } } function defaultValueIsObservable(value) { // intentionally checking for null if (value === null) { return false; } // treat all non-object types, including undefined, as non-observable values if (typeof value !== 'object') { return false; } if (isArray(value)) { return true; } const proto = getPrototypeOf(value); return proto === ObjectDotPrototype || proto === null || getPrototypeOf(proto) === null; } const defaultValueObserved = (obj, key) => { /* do nothing */ }; const defaultValueMutated = (obj, key) => { /* do nothing */ }; function createShadowTarget(value) { return isArray(value) ? [] : {}; } class ObservableMembrane { constructor(options = {}) { this.readOnlyObjectGraph = new WeakMap(); this.reactiveObjectGraph = new WeakMap(); const { valueMutated, valueObserved, valueIsObservable, tagPropertyKey } = options; this.valueMutated = isFunction(valueMutated) ? valueMutated : defaultValueMutated; this.valueObserved = isFunction(valueObserved) ? valueObserved : defaultValueObserved; this.valueIsObservable = isFunction(valueIsObservable) ? valueIsObservable : defaultValueIsObservable; this.tagPropertyKey = tagPropertyKey; } getProxy(value) { const unwrappedValue = unwrap(value); if (this.valueIsObservable(unwrappedValue)) { // When trying to extract the writable version of a readonly we return the readonly. if (this.readOnlyObjectGraph.get(unwrappedValue) === value) { return value; } return this.getReactiveHandler(unwrappedValue); } return unwrappedValue; } getReadOnlyProxy(value) { value = unwrap(value); if (this.valueIsObservable(value)) { return this.getReadOnlyHandler(value); } return value; } unwrapProxy(p) { return unwrap(p); } getReactiveHandler(value) { let proxy = this.reactiveObjectGraph.get(value); if (isUndefined(proxy)) { // caching the proxy after the first time it is accessed const handler = new ReactiveProxyHandler(this, value); proxy = new Proxy(createShadowTarget(value), handler); registerProxy(proxy, value); this.reactiveObjectGraph.set(value, proxy); } return proxy; } getReadOnlyHandler(value) { let proxy = this.readOnlyObjectGraph.get(value); if (isUndefined(proxy)) { // caching the proxy after the first time it is accessed const handler = new ReadOnlyHandler(this, value); proxy = new Proxy(createShadowTarget(value), handler); registerProxy(proxy, value); this.readOnlyObjectGraph.set(value, proxy); } return proxy; } } /** version: 2.0.0 */ /* * Copyright (c) 2024, Salesforce, Inc. * All rights reserv