index.js 10 KB

1
  1. "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{Channel:()=>Channel,PostMessageTransport:()=>PostMessageTransport,WebsocketTransport:()=>WebsocketTransport,createBrowserChannel:()=>createBrowserChannel,createPostMessageChannel:()=>createChannel,createWebSocketChannel:()=>createChannel2,default:()=>src_default});module.exports=__toCommonJS(src_exports);var import_global3=require("@storybook/global");var isMulti=args=>args.transports!==void 0,generateRandomId=()=>Math.random().toString(16).slice(2),Channel=class{constructor(input={}){this.sender=generateRandomId();this.events={};this.data={};this.transports=[];this.isAsync=input.async||!1,isMulti(input)?(this.transports=input.transports||[],this.transports.forEach(t=>{t.setHandler(event=>this.handleEvent(event))})):this.transports=input.transport?[input.transport]:[],this.transports.forEach(t=>{t.setHandler(event=>this.handleEvent(event))})}get hasTransport(){return this.transports.length>0}addListener(eventName,listener){this.events[eventName]=this.events[eventName]||[],this.events[eventName].push(listener)}emit(eventName,...args){let event={type:eventName,args,from:this.sender},options={};args.length>=1&&args[0]&&args[0].options&&(options=args[0].options);let handler=()=>{this.transports.forEach(t=>{t.send(event,options)}),this.handleEvent(event)};this.isAsync?setImmediate(handler):handler()}last(eventName){return this.data[eventName]}eventNames(){return Object.keys(this.events)}listenerCount(eventName){let listeners=this.listeners(eventName);return listeners?listeners.length:0}listeners(eventName){return this.events[eventName]||void 0}once(eventName,listener){let onceListener=this.onceListener(eventName,listener);this.addListener(eventName,onceListener)}removeAllListeners(eventName){eventName?this.events[eventName]&&delete this.events[eventName]:this.events={}}removeListener(eventName,listener){let listeners=this.listeners(eventName);listeners&&(this.events[eventName]=listeners.filter(l=>l!==listener))}on(eventName,listener){this.addListener(eventName,listener)}off(eventName,listener){this.removeListener(eventName,listener)}handleEvent(event){let listeners=this.listeners(event.type);listeners&&listeners.length&&listeners.forEach(fn=>{fn.apply(event,event.args)}),this.data[event.type]=event.args}onceListener(eventName,listener){let onceListener=(...args)=>(this.removeListener(eventName,onceListener),listener(...args));return onceListener}};var import_global=require("@storybook/global"),EVENTS=__toESM(require("@storybook/core-events")),import_client_logger2=require("@storybook/client-logger"),import_telejson=require("telejson"),import_qs=__toESM(require("qs")),import_tiny_invariant=__toESM(require("tiny-invariant"));var import_client_logger=require("@storybook/client-logger"),getEventSourceUrl=event=>{let frames=Array.from(document.querySelectorAll("iframe[data-is-storybook]")),[frame,...remainder]=frames.filter(element=>{try{return element.contentWindow===event.source}catch{}let src2=element.getAttribute("src"),origin;try{if(!src2)return!1;({origin}=new URL(src2,document.location.toString()))}catch{return!1}return origin===event.origin}),src=frame==null?void 0:frame.getAttribute("src");if(src&&remainder.length===0){let{protocol,host,pathname}=new URL(src,document.location.toString());return`${protocol}//${host}${pathname}`}return remainder.length>0&&import_client_logger.logger.error("found multiple candidates for event source"),null};var{document:document2,location}=import_global.global,KEY="storybook-channel",defaultEventOptions={allowFunction:!0,maxDepth:25},PostMessageTransport=class{constructor(config){this.config=config;this.connected=!1;var _a;if(this.buffer=[],typeof((_a=import_global.global)==null?void 0:_a.addEventListener)=="function"&&import_global.global.addEventListener("message",this.handleEvent.bind(this),!1),config.page!=="manager"&&config.page!=="preview")throw new Error(`postmsg-channel: "config.page" cannot be "${config.page}"`)}setHandler(handler){this.handler=(...args)=>{handler.apply(this,args),!this.connected&&this.getLocalFrame().length&&(this.flush(),this.connected=!0)}}send(event,options){let{target,allowRegExp,allowFunction,allowSymbol,allowDate,allowError,allowUndefined,allowClass,maxDepth,space,lazyEval}=options||{},eventOptions=Object.fromEntries(Object.entries({allowRegExp,allowFunction,allowSymbol,allowDate,allowError,allowUndefined,allowClass,maxDepth,space,lazyEval}).filter(([k,v])=>typeof v<"u")),stringifyOptions={...defaultEventOptions,...import_global.global.CHANNEL_OPTIONS||{},...eventOptions},frames=this.getFrames(target),query=import_qs.default.parse((location==null?void 0:location.search)||"",{ignoreQueryPrefix:!0}),data=(0,import_telejson.stringify)({key:KEY,event,refId:query.refId},stringifyOptions);return frames.length?(this.buffer.length&&this.flush(),frames.forEach(f=>{try{f.postMessage(data,"*")}catch{import_client_logger2.logger.error("sending over postmessage fail")}}),Promise.resolve(null)):new Promise((resolve,reject)=>{this.buffer.push({event,resolve,reject})})}flush(){let{buffer}=this;this.buffer=[],buffer.forEach(item=>{this.send(item.event).then(item.resolve).catch(item.reject)})}getFrames(target){if(this.config.page==="manager"){let list=Array.from(document2.querySelectorAll("iframe[data-is-storybook][data-is-loaded]")).flatMap(e=>{try{return e.contentWindow&&e.dataset.isStorybook!==void 0&&e.id===target?[e.contentWindow]:[]}catch{return[]}});return list!=null&&list.length?list:this.getCurrentFrames()}return import_global.global&&import_global.global.parent&&import_global.global.parent!==import_global.global.self?[import_global.global.parent]:[]}getCurrentFrames(){return this.config.page==="manager"?Array.from(document2.querySelectorAll('[data-is-storybook="true"]')).flatMap(e=>e.contentWindow?[e.contentWindow]:[]):import_global.global&&import_global.global.parent?[import_global.global.parent]:[]}getLocalFrame(){return this.config.page==="manager"?Array.from(document2.querySelectorAll("#storybook-preview-iframe")).flatMap(e=>e.contentWindow?[e.contentWindow]:[]):import_global.global&&import_global.global.parent?[import_global.global.parent]:[]}handleEvent(rawEvent){try{let{data}=rawEvent,{key,event,refId}=typeof data=="string"&&(0,import_telejson.isJSON)(data)?(0,import_telejson.parse)(data,import_global.global.CHANNEL_OPTIONS||{}):data;if(key===KEY){let pageString=this.config.page==="manager"?'<span style="color: #37D5D3; background: black"> manager </span>':'<span style="color: #1EA7FD; background: black"> preview </span>',eventString=Object.values(EVENTS).includes(event.type)?`<span style="color: #FF4785">${event.type}</span>`:`<span style="color: #FFAE00">${event.type}</span>`;if(refId&&(event.refId=refId),event.source=this.config.page==="preview"?rawEvent.origin:getEventSourceUrl(rawEvent),!event.source){import_client_logger2.pretty.error(`${pageString} received ${eventString} but was unable to determine the source of the event`);return}let message=`${pageString} received ${eventString} (${data.length})`;import_client_logger2.pretty.debug(location.origin!==event.source?message:`${message} <span style="color: gray">(on ${location.origin} from ${event.source})</span>`,...event.args),(0,import_tiny_invariant.default)(this.handler,"ChannelHandler should be set"),this.handler(event)}}catch(error){import_client_logger2.logger.error(error)}}},PostmsgTransport=PostMessageTransport;function createChannel({page}){let transport=new PostmsgTransport({page});return new Channel({transport})}var import_global2=require("@storybook/global"),import_client_logger3=require("@storybook/client-logger"),import_telejson2=require("telejson"),import_tiny_invariant2=__toESM(require("tiny-invariant"));var{WebSocket}=import_global2.global,WebsocketTransport=class{constructor({url,onError}){this.buffer=[];this.isReady=!1;this.socket=new WebSocket(url),this.socket.onopen=()=>{this.isReady=!0,this.flush()},this.socket.onmessage=({data})=>{let event=typeof data=="string"&&(0,import_telejson2.isJSON)(data)?(0,import_telejson2.parse)(data):data;(0,import_tiny_invariant2.default)(this.handler,"WebsocketTransport handler should be set"),this.handler(event)},this.socket.onerror=e=>{onError&&onError(e)}}setHandler(handler){this.handler=handler}send(event){this.isReady?this.sendNow(event):this.sendLater(event)}sendLater(event){this.buffer.push(event)}sendNow(event){let data=(0,import_telejson2.stringify)(event,{maxDepth:15,allowFunction:!0});this.socket.send(data)}flush(){let{buffer}=this;this.buffer=[],buffer.forEach(event=>this.send(event))}};function createChannel2({url,async=!1,onError=err=>import_client_logger3.logger.warn(err)}){let channelUrl=url;if(!channelUrl){let protocol=window.location.protocol==="http:"?"ws":"wss",{hostname,port}=window.location;channelUrl=`${protocol}://${hostname}:${port}/storybook-server-channel`}let transport=new WebsocketTransport({url:channelUrl,onError});return new Channel({transport,async})}var{CONFIG_TYPE}=import_global3.global,src_default=Channel;function createBrowserChannel({page,extraTransports=[]}){let transports=[new PostMessageTransport({page}),...extraTransports];if(CONFIG_TYPE==="DEVELOPMENT"){let protocol=window.location.protocol==="http:"?"ws":"wss",{hostname,port}=window.location,channelUrl=`${protocol}://${hostname}:${port}/storybook-server-channel`;transports.push(new WebsocketTransport({url:channelUrl,onError:()=>{}}))}return new Channel({transports})}0&&(module.exports={Channel,PostMessageTransport,WebsocketTransport,createBrowserChannel,createPostMessageChannel,createWebSocketChannel});