UNPKG

@storybook/channel-websocket

Version:

Storybook Websocket Channel is a channel for Storybook that can be used when the Storybook Renderer should communicate with the Storybook Manager over the network. A channel can be created using the `createChannel` function.

2 lines (1 loc) 2.31 kB
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __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 __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var src_exports={};__export(src_exports,{WebsocketTransport:()=>WebsocketTransport,createChannel:()=>createChannel,default:()=>src_default});module.exports=__toCommonJS(src_exports);var import_global=require("@storybook/global"),import_channels=require("@storybook/channels"),import_client_logger=require("@storybook/client-logger"),import_telejson=require("telejson"),{WebSocket}=import_global.global,WebsocketTransport=class{constructor({url,onError}){this.buffer=[];this.isReady=!1;this.connect(url,onError)}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_telejson.stringify)(event,{maxDepth:15,allowFunction:!0});this.socket.send(data)}flush(){let{buffer}=this;this.buffer=[],buffer.forEach(event=>this.send(event))}connect(url,onError){this.socket=new WebSocket(url),this.socket.onopen=()=>{this.isReady=!0,this.flush()},this.socket.onmessage=({data})=>{let event=typeof data=="string"&&(0,import_telejson.isJSON)(data)?(0,import_telejson.parse)(data):data;this.handler(event)},this.socket.onerror=e=>{onError&&onError(e)}}};function createChannel({url,async=!1,onError=err=>import_client_logger.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 import_channels.Channel({transport,async})}var src_default=createChannel;0&&(module.exports={WebsocketTransport,createChannel});