@web-widget/web-widget
Version:
Web front-end application container
1,006 lines (992 loc) • 30 kB
JavaScript
import {
getClientModuleId,
unsafePropsToAttrs
} from "./chunk-L7YKSBOA.js";
import {
__objRest,
__privateAdd,
__privateGet,
__privateMethod,
__privateSet,
__spreadProps,
__spreadValues
} from "./chunk-PFFVE7GG.js";
// src/element.ts
import {
mountLifecycleCacheLayer,
callSyncCacheProvider
} from "@web-widget/lifecycle-cache/client";
// src/event.ts
var _value;
var WebWidgetUpdateEvent = class extends Event {
constructor(type, init = { value: null }) {
super(type, init);
__privateAdd(this, _value);
__privateSet(this, _value, init.value);
}
get value() {
return __privateGet(this, _value);
}
};
_value = new WeakMap();
// src/modules/controller.ts
import { rebaseMeta, mergeMeta } from "@web-widget/helpers";
// src/modules/status.ts
var status = {
INITIAL: "initial",
LOADING: "loading",
LOADED: "loaded",
BOOTSTRAPPING: "bootstrapping",
BOOTSTRAPPED: "bootstrapped",
MOUNTING: "mounting",
MOUNTED: "mounted",
UPDATING: "updating",
UNMOUNTING: "unmounting",
UNLOADING: "unloading",
LOAD_ERROR: "load-error",
BOOTSTRAP_ERROR: "bootstrap-error",
MOUNT_ERROR: "mount-error",
UPDATE_ERROR: "update-error",
UNMOUNT_ERROR: "unmount-error",
UNLOAD_ERROR: "unload-error"
};
// src/modules/timeouts.ts
function reasonableTime(task, timeout, bail = false, errorMessage) {
return new Promise((resolve, reject) => {
let finished = false;
task().then((val) => {
finished = true;
resolve(val);
}).catch((val) => {
finished = true;
reject(val);
});
function maybeTimingOut() {
if (!finished) {
if (bail) {
reject(new Error(errorMessage));
} else {
console.error(new Error(errorMessage));
}
}
}
setTimeout(() => maybeTimingOut(), timeout);
});
}
// src/modules/flow.ts
var {
BOOTSTRAPPED,
BOOTSTRAPPING,
BOOTSTRAP_ERROR,
INITIAL,
LOADED,
LOADING,
LOAD_ERROR,
MOUNTED,
MOUNTING,
MOUNT_ERROR,
UNLOADING,
UNLOAD_ERROR,
UNMOUNTING,
UNMOUNT_ERROR,
UPDATE_ERROR,
UPDATING
} = status;
var rules = {
load: {
creator: true,
timeout: 12e3,
status: [INITIAL, LOADING, LOADED, LOAD_ERROR]
},
bootstrap: {
pre: "load",
timeout: 4e3,
status: [LOADED, BOOTSTRAPPING, BOOTSTRAPPED, BOOTSTRAP_ERROR]
},
mount: {
pre: "bootstrap",
timeout: 3e3,
status: [BOOTSTRAPPED, MOUNTING, MOUNTED, MOUNT_ERROR]
},
update: {
verify: true,
timeout: 3e3,
status: [MOUNTED, UPDATING, MOUNTED, UPDATE_ERROR]
},
unmount: {
timeout: 3e3,
status: [MOUNTED, UNMOUNTING, BOOTSTRAPPED, UNMOUNT_ERROR]
},
unload: {
pre: "unmount",
timeout: 3e3,
status: [BOOTSTRAPPED, UNLOADING, INITIAL, UNLOAD_ERROR]
}
};
// src/modules/controller.ts
var _moduleLoader, _handler, _lifecycle, _pending, _statusChangeCallback, _timeouts, _status, _LifecycleController_instances, setStatus_fn;
var LifecycleController = class {
constructor(moduleLoader, options) {
__privateAdd(this, _LifecycleController_instances);
__privateAdd(this, _moduleLoader);
__privateAdd(this, _handler);
__privateAdd(this, _lifecycle);
__privateAdd(this, _pending);
__privateAdd(this, _statusChangeCallback);
__privateAdd(this, _timeouts);
__privateAdd(this, _status);
__privateSet(this, _moduleLoader, moduleLoader);
__privateSet(this, _handler, options.handler);
__privateSet(this, _lifecycle, /* @__PURE__ */ Object.create(null));
__privateSet(this, _status, status.INITIAL);
__privateSet(this, _statusChangeCallback, options.statusChangeCallback);
__privateSet(this, _timeouts, options.timeouts);
}
get status() {
return __privateGet(this, _status);
}
async run(name) {
let importer;
const bail = typeof __privateGet(this, _timeouts)[name] === "number";
const rule = rules[name];
const timeout = bail ? __privateGet(this, _timeouts)[name] : rule.timeout;
const [initial, pending, fulfilled, rejected] = rule.status;
if (!rule) {
throw new TypeError(`Cannot ${name}`);
}
if (__privateGet(this, _pending)) {
await __privateGet(this, _pending);
}
if (rule.creator && !__privateGet(this, _lifecycle)[name]) {
__privateGet(this, _lifecycle)[name] = async (context) => {
var _a, _b, _c, _d, _e;
const widgetModule = await __privateGet(this, _moduleLoader).call(this);
const render = widgetModule.render;
if (!render) {
throw new Error(`Module does not export render function.`);
}
const meta = rebaseMeta(
mergeMeta(
(_a = widgetModule.meta) != null ? _a : {},
(_b = context.meta) != null ? _b : {}
),
importer
);
if ((_c = meta.script) == null ? void 0 : _c.length) {
console.warn(`Script tags in meta will be ignored.`);
}
let body;
const styleLinks = meta.link ? meta.link.filter(({ rel }) => rel === "stylesheet") : [];
const styles = (_d = meta.style) != null ? _d : [];
const hasStyle = (_e = styleLinks.length) != null ? _e : styles.length;
const renderContext = Object.freeze({
children: void 0,
// TODO
get container() {
var _a2;
const tag = "web-widget.body";
return body != null ? body : body = hasStyle ? context.recovering ? (_a2 = context.container.querySelector(tag.replace(".", "\\."))) != null ? _a2 : context.container : context.container.appendChild(document.createElement(tag)) : context.container;
},
data: context.data,
meta,
module: widgetModule,
recovering: context.recovering,
/**@deprecated*/
update: Reflect.get(context, "update")
});
const lifecycle = await render(renderContext);
Object.assign(
// @ts-ignore
__privateGet(this, _lifecycle),
{
bootstrap() {
if (!hasStyle && !context.recovering) {
return;
}
const fragment = document.createDocumentFragment();
const loading = styleLinks.map(
(attrs) => new Promise((resolve, reject) => {
const element = document.createElement("link");
element.addEventListener("load", resolve, {
once: true
});
element.addEventListener("error", reject, {
once: true
});
Object.entries(attrs).forEach(([name2, value]) => {
element.setAttribute(name2, value);
});
fragment.appendChild(element);
})
);
styles.forEach((attrs) => {
var _a2;
const element = document.createElement("style");
element.textContent = (_a2 = attrs.content) != null ? _a2 : "";
Object.entries(attrs).forEach(([name2, value]) => {
element.setAttribute(name2, value);
});
fragment.appendChild(element);
});
context.container.appendChild(fragment);
return Promise.all(loading);
}
},
lifecycle != null ? lifecycle : {}
);
};
}
if (initial !== __privateGet(this, _status) && rule.pre) {
await this.run(rule.pre);
}
if (![initial, rejected].includes(__privateGet(this, _status))) {
if (rule.verify) {
throw new Error(`Cannot ${name}: status: ${__privateGet(this, _status)}`);
}
return void 0;
}
__privateMethod(this, _LifecycleController_instances, setStatus_fn).call(this, pending);
if (!__privateGet(this, _lifecycle)[name]) {
__privateMethod(this, _LifecycleController_instances, setStatus_fn).call(this, fulfilled);
return void 0;
}
__privateSet(this, _pending, reasonableTime(
async () => {
const { context, importer: baseUrl } = __privateGet(this, _handler).call(this);
importer = baseUrl;
return __privateGet(this, _lifecycle)[name](context);
},
timeout,
bail,
`Lifecycle function did not complete within ${timeout} ms: ${name}`
).then(() => {
__privateMethod(this, _LifecycleController_instances, setStatus_fn).call(this, fulfilled);
__privateSet(this, _pending, null);
}).catch((error) => {
__privateMethod(this, _LifecycleController_instances, setStatus_fn).call(this, rejected);
__privateSet(this, _pending, null);
throw error;
}));
return __privateGet(this, _pending);
}
};
_moduleLoader = new WeakMap();
_handler = new WeakMap();
_lifecycle = new WeakMap();
_pending = new WeakMap();
_statusChangeCallback = new WeakMap();
_timeouts = new WeakMap();
_status = new WeakMap();
_LifecycleController_instances = new WeakSet();
setStatus_fn = function(value) {
if (value !== __privateGet(this, _status)) {
__privateSet(this, _status, value);
__privateGet(this, _statusChangeCallback).call(this, value);
}
};
// src/utils/idle.ts
var supportRequestIdleCallback = "requestIdleCallback" in window;
var createIdleObserver = (element, callback, options = {}) => {
let id;
if (supportRequestIdleCallback) {
id = requestIdleCallback(callback, options);
} else {
id = setTimeout(callback, 200);
}
const disconnect = () => {
if (supportRequestIdleCallback) {
cancelIdleCallback(id);
} else {
clearTimeout(id);
}
};
return disconnect;
};
// src/utils/lazy.ts
var placeholder = Symbol();
var isBox = (element) => ["contents", "none"].includes(getComputedStyle(element).display);
var createPlaceholderElement = () => Object.assign(document.createElement("span"), {
[placeholder]: true
});
var isPlaceholderElement = (element) => element[placeholder];
var createVisibleObserver = (element, callback, options = {}) => {
let observer = new IntersectionObserver(
(entries) => {
for (const { isIntersecting, target } of entries) {
if (!isIntersecting) {
continue;
}
disconnect();
if (isPlaceholderElement(target)) {
target.remove();
}
callback();
break;
}
},
__spreadValues({
rootMargin: "80%"
}, options)
);
const disconnect = () => {
if (observer) {
observer.disconnect();
observer = null;
}
};
if (isBox(element)) {
const children = Array.from(element.children).filter(
(node) => !isBox(node)
);
if (children.length) {
for (const child of children) {
observer.observe(child);
}
} else {
const placeholderElement = createPlaceholderElement();
element.firstChild ? element.insertBefore(placeholderElement, element.firstChild) : element.appendChild(placeholderElement);
observer.observe(placeholderElement);
}
} else {
observer.observe(element);
}
return disconnect;
};
// src/utils/module-preload.ts
function triggerModulePreload(href, { fetchPriority = "high", rel = "modulepreload" } = {}) {
const link = Array.from(
document.querySelectorAll(`link[rel="${rel}"]`)
).find((link2) => link2.href === href);
if (link) {
Object.assign(link, { fetchPriority });
} else {
document.head.appendChild(
Object.assign(document.createElement("link"), {
href,
rel,
fetchPriority
})
);
}
}
// src/utils/queue-microtask.ts
var promise;
var queueMicrotask = typeof window.queueMicrotask === "function" ? window.queueMicrotask.bind(window) : (callback) => (promise || (promise = Promise.resolve())).then(callback).catch(
(error) => setTimeout(() => {
throw error;
}, 0)
);
// src/utils/report-error.ts
var reportError = typeof window.reportError === "function" ? window.reportError.bind(window) : (error) => {
queueMicrotask(() => {
throw error;
});
};
// src/element.ts
var globalTimeouts = /* @__PURE__ */ Object.create(null);
var innerHTMLDescriptor = Object.getOwnPropertyDescriptor(
Element.prototype,
"innerHTML"
);
var innerHTMLSetter = innerHTMLDescriptor.set;
var INNER_HTML_PLACEHOLDER = `<!--web-widget:placeholder-->`;
var _loader, _lifecycleController, _data, _disconnectObserver, _meta, _context, _isFirstConnect, _timeouts2, _status2, _internals, _HTMLWebWidgetElement_instances, autoMount_fn, firstConnectedCallback_fn, trigger_fn, statusChangeCallback_fn, name_get, throwGlobalError_fn;
var _HTMLWebWidgetElement = class _HTMLWebWidgetElement extends HTMLElement {
constructor() {
super();
__privateAdd(this, _HTMLWebWidgetElement_instances);
__privateAdd(this, _loader, null);
__privateAdd(this, _lifecycleController);
__privateAdd(this, _data, null);
__privateAdd(this, _disconnectObserver);
__privateAdd(this, _meta, null);
__privateAdd(this, _context, null);
__privateAdd(this, _isFirstConnect, false);
__privateAdd(this, _timeouts2, null);
__privateAdd(this, _status2, status.INITIAL);
__privateAdd(this, _internals);
__privateSet(this, _lifecycleController, new LifecycleController(
() => {
if (!this.loader) {
this.loader = this.createLoader();
}
return this.loader();
},
{
handler: () => {
if (!this.context) {
this.context = this.createContext();
}
return {
importer: this.import,
context: this.context
};
},
statusChangeCallback: (status2) => {
__privateMethod(this, _HTMLWebWidgetElement_instances, statusChangeCallback_fn).call(this, status2);
},
timeouts: this.timeouts || {}
}
));
if (this.attachInternals) {
__privateSet(this, _internals, this.attachInternals());
}
}
/**
* WidgetModule loader.
* @default null
*/
get loader() {
return __privateGet(this, _loader) || null;
}
set loader(value) {
if (typeof value === "function") {
__privateSet(this, _loader, value);
if (this.loading === "eager") {
__privateMethod(this, _HTMLWebWidgetElement_instances, autoMount_fn).call(this);
}
}
}
/**
* WidgetModule base.
*/
get base() {
const value = this.getAttribute("base");
return value === null ? this.baseURI : new URL(value, this.baseURI).href;
}
set base(value) {
this.setAttribute("base", value);
}
/**
* WidgetModule data.
* @deprecated Use `contextData` instead.
*/
get data() {
console.warn("`data` is deprecated. Use `contextData` instead.");
return this.contextData;
}
set data(value) {
if (typeof value === "object") {
this.setAttribute("data", JSON.stringify(value));
}
}
/**
* WidgetModule data.
*/
get contextData() {
var _a;
if (!__privateGet(this, _data)) {
const dataAttr = (_a = this.getAttribute("contextdata")) != null ? _a : (
// @deprecated
this.getAttribute("data")
);
if (dataAttr) {
try {
__privateSet(this, _data, JSON.parse(dataAttr));
} catch (error) {
__privateMethod(this, _HTMLWebWidgetElement_instances, throwGlobalError_fn).call(this, error);
__privateSet(this, _data, {});
}
} else if (Object.entries(this.dataset).length) {
__privateSet(this, _data, __spreadValues({}, this.dataset));
}
}
return __privateGet(this, _data);
}
set contextData(value) {
if (typeof value === "object") {
__privateSet(this, _data, value);
}
}
/**
* WidgetModule meta.
*/
get contextMeta() {
if (!__privateGet(this, _meta)) {
const dataAttr = this.getAttribute("contextmeta");
if (dataAttr) {
try {
__privateSet(this, _meta, JSON.parse(dataAttr));
} catch (error) {
__privateMethod(this, _HTMLWebWidgetElement_instances, throwGlobalError_fn).call(this, error);
__privateSet(this, _meta, {});
}
}
}
return __privateGet(this, _meta);
}
set contextMeta(value) {
if (typeof value === "object") {
this.setAttribute("contextmeta", JSON.stringify(value));
}
}
/**
* WidgetModule context.
*/
get context() {
return __privateGet(this, _context);
}
set context(value) {
if (typeof value === "object" && value !== null) {
__privateSet(this, _context, value);
}
}
/**
* Whether the module is inactive.
*/
get inactive() {
return this.hasAttribute("inactive");
}
set inactive(value) {
if (value) {
this.setAttribute("inactive", "");
} else {
this.removeAttribute("inactive");
}
}
/**
* Hydration mode.
* @default false
*/
get recovering() {
return this.hasAttribute("recovering");
}
set recovering(value) {
if (value) {
this.setAttribute("recovering", "");
} else {
this.removeAttribute("recovering");
}
}
/**
* Indicates how the browser should load the module.
* @default "eager"
*/
get loading() {
return this.getAttribute("loading") || "eager";
}
set loading(value) {
this.setAttribute("loading", value);
}
/**
* WidgetModule container status.
* @default "initial"
*/
get status() {
return __privateGet(this, _status2);
}
/**
* WidgetModule module url.
* @default ""
*/
get import() {
let value = this.getAttribute("import");
const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
if (value && !bareImportRE.test(value)) {
value = new URL(value, this.base).href;
}
return value === null ? "" : value;
}
set import(value) {
this.setAttribute("import", value);
}
/**
* WidgetModule render target.
* @default "shadow"
*/
get renderTarget() {
return this.getAttribute("rendertarget") || "shadow";
}
set renderTarget(value) {
this.setAttribute("rendertarget", value);
}
/**
* WidgetModule timeouts.
*/
get timeouts() {
if (!__privateGet(this, _timeouts2)) {
__privateSet(this, _timeouts2, __spreadValues({}, _HTMLWebWidgetElement.timeouts));
}
return __privateGet(this, _timeouts2);
}
set timeouts(value) {
__privateSet(this, _timeouts2, value || null);
}
// NOTE: This is a temporary solution for React.
// NOTE: Prevent React components from clearing innerHTML when re-rendering on the client side.
set innerHTML(value) {
if (value === INNER_HTML_PLACEHOLDER) {
return;
} else {
innerHTMLSetter.call(this, value);
}
}
/**
* Hook: Create the module's context.
*/
createContext() {
var _a, _b;
let container;
let customContext = this.context;
const view = this;
if (!customContext) {
const context2 = this.getAttribute("context");
if (context2) {
try {
customContext = JSON.parse(context2);
} catch (error) {
__privateMethod(this, _HTMLWebWidgetElement_instances, throwGlobalError_fn).call(this, error);
}
}
}
const context = /* @__PURE__ */ Object.create({
get container() {
if (!container) {
container = view.createContainer();
}
return container;
},
data: (_a = view.contextData) != null ? _a : {},
meta: (_b = view.contextMeta) != null ? _b : {},
recovering: view.recovering,
/**@deprecated*/
update: this.update.bind(this)
});
return Object.assign(context, customContext || {});
}
/**
* Hook: Create the module's render node.
*/
createContainer() {
var _a, _b;
let container = null;
if (this.renderTarget === "shadow") {
if (this.recovering) {
container = (_b = (_a = __privateGet(this, _internals)) == null ? void 0 : _a.shadowRoot) != null ? _b : null;
}
if (!container) {
container = this.attachShadow({ mode: "open" });
}
} else if (this.renderTarget === "light") {
container = this;
}
if (container && !Reflect.has(container, "update")) {
["mount", "update", "unmount"].forEach((name) => {
if (!container[name]) {
Reflect.defineProperty(container, name, {
// @ts-ignore
value: (context) => this[name](context)
});
}
});
}
return container;
}
/**
* Hook: Create Create the module's loader.
*/
createLoader() {
const supportsImportMaps = HTMLScriptElement.supports && HTMLScriptElement.supports("importmap");
function importModule(target) {
if (!supportsImportMaps && typeof importShim === "function") {
return importShim(target);
}
return import(
/* @vite-ignore */
/* webpackIgnore: true */
target
);
}
return () => importModule(this.import);
}
/**
* Trigger the loading of the module.
*/
async load() {
await __privateMethod(this, _HTMLWebWidgetElement_instances, trigger_fn).call(this, "load");
}
/**
* Trigger the bootstrapping of the module.
*/
async bootstrap() {
await __privateMethod(this, _HTMLWebWidgetElement_instances, trigger_fn).call(this, "bootstrap");
}
/**
* Trigger the mounting of the module.
*/
async mount() {
await callSyncCacheProvider(() => __privateMethod(this, _HTMLWebWidgetElement_instances, trigger_fn).call(this, "mount"));
}
/**
* Trigger the updating of the module.
*/
async update(context = {}) {
if (this.context && this.dispatchEvent(
new WebWidgetUpdateEvent("update", {
value: context,
cancelable: true
})
)) {
Object.assign(this.context, context);
await __privateMethod(this, _HTMLWebWidgetElement_instances, trigger_fn).call(this, "update");
} else {
throw new Error(`Can't update`);
}
}
/**
* Trigger the unmounting of the module.
*/
async unmount() {
await __privateMethod(this, _HTMLWebWidgetElement_instances, trigger_fn).call(this, "unmount");
}
/**
* Trigger the unloading of the module.
*/
async unload() {
const context = this.context || {};
await __privateMethod(this, _HTMLWebWidgetElement_instances, trigger_fn).call(this, "unload");
Object.getOwnPropertyNames(context).forEach((key) => {
Reflect.deleteProperty(context, key);
});
}
connectedCallback() {
if (!__privateGet(this, _isFirstConnect)) {
__privateMethod(this, _HTMLWebWidgetElement_instances, firstConnectedCallback_fn).call(this);
__privateSet(this, _isFirstConnect, true);
}
}
disconnectedCallback() {
queueMicrotask(() => {
if (!this.isConnected) {
this.destroyedCallback();
}
});
}
attributeChangedCallback(name) {
if (name === "contextdata" || // @deprecated
name === "data") {
__privateSet(this, _data, null);
}
if (name === "contextmeta") {
__privateSet(this, _meta, null);
}
if (this.loading === "eager") {
__privateMethod(this, _HTMLWebWidgetElement_instances, autoMount_fn).call(this);
}
}
destroyedCallback() {
if (__privateGet(this, _disconnectObserver)) {
__privateGet(this, _disconnectObserver).call(this);
}
if (!this.inactive) {
this.unload().catch(__privateMethod(this, _HTMLWebWidgetElement_instances, throwGlobalError_fn).bind(this));
}
}
static get observedAttributes() {
return [
"data",
// @deprecated
"contextdata",
"inactive",
"loading",
"import",
"meta",
// @deprecated
"contextmeta"
];
}
static get timeouts() {
return globalTimeouts;
}
static set timeouts(value) {
globalTimeouts = value;
}
};
_loader = new WeakMap();
_lifecycleController = new WeakMap();
_data = new WeakMap();
_disconnectObserver = new WeakMap();
_meta = new WeakMap();
_context = new WeakMap();
_isFirstConnect = new WeakMap();
_timeouts2 = new WeakMap();
_status2 = new WeakMap();
_internals = new WeakMap();
_HTMLWebWidgetElement_instances = new WeakSet();
autoMount_fn = function() {
if (this.status === status.INITIAL && !this.inactive && this.isConnected && (this.import || this.loader)) {
queueMicrotask(
() => this.mount().catch(__privateMethod(this, _HTMLWebWidgetElement_instances, throwGlobalError_fn).bind(this))
);
}
};
firstConnectedCallback_fn = function() {
const options = {
once: true,
passive: true
};
const preload = () => {
if (this.import) {
triggerModulePreload(this.import);
}
};
["mousemove", "touchstart"].forEach(
(type) => this.addEventListener(type, preload, options)
);
if (this.loading === "eager") {
__privateMethod(this, _HTMLWebWidgetElement_instances, autoMount_fn).call(this);
} else if (this.loading === "lazy") {
__privateSet(this, _disconnectObserver, createVisibleObserver(
this,
() => __privateMethod(this, _HTMLWebWidgetElement_instances, autoMount_fn).call(this)
));
} else if (this.loading === "idle") {
__privateSet(this, _disconnectObserver, createIdleObserver(
this,
() => __privateMethod(this, _HTMLWebWidgetElement_instances, autoMount_fn).call(this)
));
}
};
trigger_fn = function(name) {
return __privateGet(this, _lifecycleController).run(name);
};
statusChangeCallback_fn = function(value) {
var _a;
__privateSet(this, _status2, value);
if ((_a = __privateGet(this, _internals)) == null ? void 0 : _a.states) {
try {
__privateGet(this, _internals).states.clear();
__privateGet(this, _internals).states.add(value);
} catch (error) {
this.setAttribute("status", value);
}
} else {
this.setAttribute("status", value);
}
if (value === status.MOUNTED) {
this.removeAttribute("recovering");
}
try {
const name = this.localName;
const markNameSpace = `${name}:statusChange`;
const detail = {
name: __privateGet(this, _HTMLWebWidgetElement_instances, name_get),
import: this.import
};
performance.mark(`${markNameSpace}:${value}`, {
detail
});
switch (value) {
case status.LOADED:
performance.measure(`${name}:load`, {
start: `${markNameSpace}:${status.LOADING}`,
end: `${markNameSpace}:${status.LOADED}`,
detail
});
break;
case status.MOUNTED:
performance.measure(`${name}:mount`, {
start: `${markNameSpace}:${status.MOUNTING}`,
end: `${markNameSpace}:${status.MOUNTED}`,
detail
});
break;
}
} catch (e) {
}
this.dispatchEvent(new Event("statuschange"));
};
name_get = function() {
return this.id || this.getAttribute("name") || this.import || this.localName;
};
throwGlobalError_fn = function(error) {
const moduleName = __privateGet(this, _HTMLWebWidgetElement_instances, name_get);
const prefix = `Web Widget module (${moduleName})`;
if (typeof error !== "object") {
error = new Error(error, {
cause: error
});
}
if (!error.message.includes(prefix)) {
Reflect.defineProperty(error, "message", {
value: `${prefix}: ${error.message}`,
writable: true,
configurable: true
});
}
reportError(error);
};
var HTMLWebWidgetElement = _HTMLWebWidgetElement;
Object.assign(HTMLWebWidgetElement, status);
Object.assign(window, {
HTMLWebWidgetElement
});
mountLifecycleCacheLayer(() => {
queueMicrotask(() => {
customElements.define("web-widget", HTMLWebWidgetElement);
});
});
// src/client.ts
function unsafeAttrsToHtml(attrs) {
return Object.entries(attrs).map(
([attrName, attrValue]) => `${attrName}${attrValue === "" ? "" : '="' + attrValue + '"'}`
).join(" ");
}
var _clientImport, _options;
var ClientWebWidgetRenderer = class {
constructor(loader, _a) {
__privateAdd(this, _clientImport);
__privateAdd(this, _options);
this.localName = "web-widget";
var _b = _a, { children = "", renderStage } = _b, options = __objRest(_b, ["children", "renderStage"]);
if (children && options.renderTarget !== "shadow") {
throw new Error(
`Rendering content in a slot requires "renderTarget: 'shadow'".`
);
}
if (renderStage === "server") {
throw new Error(
`"renderStage: 'server'" usually comes from server-side rendering, it doesn't make sense to enable it on the client side.`
);
}
__privateSet(this, _clientImport, getClientModuleId(loader, options));
__privateSet(this, _options, options);
}
get attributes() {
const clientImport = __privateGet(this, _clientImport);
const _a = __privateGet(this, _options), { data: contextdata, meta: contextmeta } = _a, options = __objRest(_a, ["data", "meta"]);
const attrs = unsafePropsToAttrs(__spreadProps(__spreadValues({}, options), {
// base: options.base?.startsWith("file://") ? undefined : options.base,
contextdata: JSON.stringify(contextdata),
contextmeta: JSON.stringify(contextmeta),
import: clientImport,
recovering: false
}));
if (attrs.contextdata === "{}") {
delete attrs.contextdata;
}
if (attrs.contextmeta === "{}") {
delete attrs.contextmeta;
}
return attrs;
}
async renderInnerHTMLToString() {
return INNER_HTML_PLACEHOLDER;
}
async renderOuterHTMLToString() {
const tag = this.localName;
const attributes = this.attributes;
const children = await this.renderInnerHTMLToString();
return `<${tag} ${unsafeAttrsToHtml(attributes)}>${children}</${tag}>`;
}
};
_clientImport = new WeakMap();
_options = new WeakMap();
var WebWidgetRenderer = ClientWebWidgetRenderer;
export {
HTMLWebWidgetElement,
INNER_HTML_PLACEHOLDER,
WebWidgetRenderer,
WebWidgetUpdateEvent
};
//# sourceMappingURL=web-widget.client.js.map