Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@netless/app-embedded-page-sdk

Package Overview
Dependencies
Maintainers
10
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@netless/app-embedded-page-sdk - npm Package Compare versions

Comparing version 0.0.3 to 0.0.4

dist/EmbeddedApp.d.ts

80

dist/index.d.ts

@@ -1,71 +0,8 @@

import type { ReceiveMessages, SendMessages, DiffOne, InitData } from "@netless/app-embedded-page";
declare type CheckSendMessageType<T extends {
type: keyof ReceiveMessages;
}> = T;
export declare type SendMessage<State = any, Message = any> = CheckSendMessageType<{
type: "GetState";
} | {
type: "SetState";
payload: Partial<State>;
} | {
type: "SendMessage";
payload: Message;
} | {
type: "GetPage";
} | {
type: "SetPage";
payload: string;
} | {
type: "GetWritable";
}>;
export declare type Diff<State> = State extends Record<infer K, unknown> ? Record<K, DiffOne<State[K]>> : never;
declare type CheckIncomingMessageType<T extends {
type: keyof SendMessages;
}> = T;
export declare type IncomingMessage<State = any, Message = any> = CheckIncomingMessageType<{
type: "Init";
payload: InitData;
} | {
type: "GetState";
payload: State;
} | {
type: "StateChanged";
payload: Diff<State>;
} | {
type: "ReceiveMessage";
payload: Message;
} | {
type: "GetPage";
payload: string | undefined;
} | {
type: "PageChanged";
payload: DiffOne<string>;
} | {
type: "GetWritable";
payload: boolean;
} | {
type: "WritableChanged";
payload: DiffOne<boolean>;
}>;
export declare type Listener<T> = (event: T) => void;
export interface Emitter<T> {
dispatch(event: T): void;
addListener(listener: Listener<T>): void;
removeListener(listener: Listener<T>): void;
import type { DefaultState } from "@netless/app-embedded-page";
import type { LoggerDebugLevel } from "@netless/app-shared";
import { EmbeddedApp } from "./EmbeddedApp";
export interface EmbeddedAppConfig<TState> {
ensureState: TState;
debug?: LoggerDebugLevel;
}
export interface EmbeddedApp<State = Record<string, any>, Message = any> {
readonly state: Readonly<State>;
readonly page?: string;
readonly isWritable: boolean;
readonly meta: Readonly<InitData["meta"]>;
ensureState(partialState: Partial<State>): void;
setState(partialState: Partial<State>): void;
setPage(page: string): void;
sendMessage(message: Message): void;
destroy(): void;
onStateChanged: Emitter<Diff<State>>;
onPageChanged: Emitter<DiffOne<string>>;
onWritableChanged: Emitter<DiffOne<boolean>>;
onMessage: Emitter<Message>;
}
/**

@@ -79,3 +16,4 @@ * @example

*/
export declare function createEmbeddedApp<State = Record<string, any>, Message = any>(callback?: (app: EmbeddedApp<State, Message>) => void): Promise<EmbeddedApp<State, Message>>;
export {};
export declare function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(): Promise<EmbeddedApp<TState | Record<string, unknown>, TMessage>>;
export declare function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(config: EmbeddedAppConfig<TState>): Promise<EmbeddedApp<TState, TMessage>>;
export declare function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(config: Partial<EmbeddedAppConfig<TState>>): Promise<EmbeddedApp<TState | Record<string, unknown>, TMessage>>;

@@ -1,2 +0,2 @@

"use strict";var D=Object.defineProperty;var I=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,E=Object.prototype.propertyIsEnumerable;var b=(n,e,t)=>e in n?D(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,g=(n,e)=>{for(var t in e||(e={}))C.call(e,t)&&b(n,t,e[t]);if(I)for(var t of I(e))E.call(e,t)&&b(n,t,e[t]);return n};Object.defineProperty(exports,"__esModule",{value:!0});exports[Symbol.toStringTag]="Module";class M{constructor(){this.disposers=new Map,this.disposerIDGenCount=-1}add(e,t=this.genDisposerID()){return this.flush(t),this.disposers.set(t,e()),t}addEventListener(e,t,r,o,i=this.genDisposerID()){return this.add(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),i),i}setTimeout(e,t,r=this.genDisposerID()){return this.add(()=>{const o=window.setTimeout(()=>{this.remove(r),e()},t);return()=>window.clearTimeout(o)},r)}setInterval(e,t,r=this.genDisposerID()){return this.add(()=>{const o=window.setInterval(e,t);return()=>window.clearInterval(o)},r)}remove(e){const t=this.disposers.get(e);return this.disposers.delete(e),t}flush(e){const t=this.remove(e);if(t)try{t()}catch(r){console.error(r)}}flushAll(){this.disposers.forEach(e=>{try{e()}catch(t){console.error(t)}}),this.disposers.clear()}genDisposerID(){const{MAX_SAFE_INTEGER:e=9007199254740991}=Number;return this.disposerIDGenCount=(this.disposerIDGenCount+1)%e,`disposer-${this.disposerIDGenCount}`}}function P(n){return typeof n=="object"&&n!==null}function l(){const n=new Set;return{dispatch:o=>n.forEach(i=>i(o)),addListener:o=>n.add(o),removeListener:o=>n.delete(o)}}function G(n){let e,t,r=!1,o;const i=l(),y=l(),f=l(),v=l(),m=l(),w=new M;let c,h,u;function p(a){parent.postMessage(a,"*")}w.addEventListener(window,"message",a=>{if(!P(a.data)){console.warn("window message data should be object, instead got",a.data);return}const s=a.data;if(s.type==="Init"){const{payload:d}=s;e=d.state,t=d.page,r=d.writable,o=d.meta,i.dispatch(d)}else s.type==="ReceiveMessage"?y.dispatch(s.payload):(s.type==="StateChanged"?(c=s.payload,p({type:"GetState"})):s.type==="GetState"&&(e=s.payload,c&&(f.dispatch(c),c=void 0)),s.type==="PageChanged"?(h=s.payload,p({type:"GetPage"})):s.type==="GetPage"&&(t=s.payload,h&&(v.dispatch(h),h=void 0)),s.type==="WritableChanged"?(u=s.payload,p({type:"GetWritable"})):s.type==="GetWritable"&&(r=s.payload,u&&(m.dispatch(u),u=void 0)))});const S={get state(){return e},get page(){return t},get isWritable(){return r},get meta(){return o},ensureState:a=>{e=g(g({},a),e)},setState:a=>{for(const[s,d]of Object.entries(a))d===void 0?delete e[s]:e[s]=d;p({type:"SetState",payload:a})},setPage:a=>{t=a,p({type:"SetPage",payload:a})},sendMessage:a=>{p({type:"SendMessage",payload:a})},destroy:()=>w.flushAll(),onStateChanged:f,onPageChanged:v,onWritableChanged:m,onMessage:y};return new Promise(a=>{const s=()=>{i.removeListener(s),n==null||n(S),a(S)};i.addListener(s)})}exports.createEmbeddedApp=G;
"use strict";var H=Object.defineProperty;var K=(u,e,s)=>e in u?H(u,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[e]=s;var A=(u,e,s)=>(K(u,typeof e!="symbol"?e+"":e,s),s);Object.defineProperty(exports,"__esModule",{value:!0});exports[Symbol.toStringTag]="Module";class X{constructor(){this.disposers=new Map,this.disposerIDGenCount=-1}add(e,s=this.genDisposerID()){return this.flush(s),this.disposers.set(s,e()),s}addEventListener(e,s,r,o,l=this.genDisposerID()){return this.add(()=>(e.addEventListener(s,r,o),()=>e.removeEventListener(s,r,o)),l),l}setTimeout(e,s,r=this.genDisposerID()){return this.add(()=>{const o=window.setTimeout(()=>{this.remove(r),e()},s);return()=>window.clearTimeout(o)},r)}setInterval(e,s,r=this.genDisposerID()){return this.add(()=>{const o=window.setInterval(e,s);return()=>window.clearInterval(o)},r)}remove(e){const s=this.disposers.get(e);return this.disposers.delete(e),s}flush(e){const s=this.remove(e);if(s)try{s()}catch(r){console.error(r)}}flushAll(){this.disposers.forEach(e=>{try{e()}catch(s){console.error(s)}}),this.disposers.clear()}genDisposerID(){const{MAX_SAFE_INTEGER:e=9007199254740991}=Number;return this.disposerIDGenCount=(this.disposerIDGenCount+1)%e,`disposer-${this.disposerIDGenCount}`}}var q=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},P={exports:{}};(function(u,e){(function(s,r){{var o=r();u&&u.exports&&(e=u.exports=o),e.randomColor=o}})(q,function(){var s=null,r={};O();var o=[],l=function(t){if(t=t||{},t.seed!==void 0&&t.seed!==null&&t.seed===parseInt(t.seed,10))s=t.seed;else if(typeof t.seed=="string")s=F(t.seed);else{if(t.seed!==void 0&&t.seed!==null)throw new TypeError("The seed value must be an integer or string");s=null}var n,a,i;if(t.count!==null&&t.count!==void 0){for(var h=t.count,g=[],c=0;c<t.count;c++)o.push(!1);for(t.count=null;h>g.length;){var w=l(t);s!==null&&(t.seed=s),g.push(w)}return t.count=h,g}return n=d(t),a=f(n,t),i=_(n,a,t),m([n,a,i],t)};function d(t){if(o.length>0){var n=j(t.hue),a=R(n),i=(n[1]-n[0])/o.length,h=parseInt((a-n[0])/i);o[h]===!0?h=(h+2)%o.length:o[h]=!0;var g=(n[0]+h*i)%359,c=(n[0]+(h+1)*i)%359;return n=[g,c],a=R(n),a<0&&(a=360+a),a}else{var n=L(t.hue);return a=R(n),a<0&&(a=360+a),a}}function f(t,n){if(n.hue==="monochrome")return 0;if(n.luminosity==="random")return R([0,100]);var a=W(t),i=a[0],h=a[1];switch(n.luminosity){case"bright":i=55;break;case"dark":i=h-10;break;case"light":h=55;break}return R([i,h])}function _(t,n,a){var i=x(t,n),h=100;switch(a.luminosity){case"dark":h=i+20;break;case"light":i=(h+i)/2;break;case"random":i=0,h=100;break}return R([i,h])}function m(t,n){switch(n.format){case"hsvArray":return t;case"hslArray":return V(t);case"hsl":var a=V(t);return"hsl("+a[0]+", "+a[1]+"%, "+a[2]+"%)";case"hsla":var i=V(t),h=n.alpha||Math.random();return"hsla("+i[0]+", "+i[1]+"%, "+i[2]+"%, "+h+")";case"rgbArray":return y(t);case"rgb":var g=y(t);return"rgb("+g.join(", ")+")";case"rgba":var c=y(t),h=n.alpha||Math.random();return"rgba("+c.join(", ")+", "+h+")";default:return G(t)}}function x(t,n){for(var a=D(t).lowerBounds,i=0;i<a.length-1;i++){var h=a[i][0],g=a[i][1],c=a[i+1][0],w=a[i+1][1];if(n>=h&&n<=c){var C=(w-g)/(c-h),p=g-C*h;return C*n+p}}return 0}function L(t){if(typeof parseInt(t)=="number"){var n=parseInt(t);if(n<360&&n>0)return[n,n]}if(typeof t=="string"){if(r[t]){var a=r[t];if(a.hueRange)return a.hueRange}else if(t.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var i=T(t)[0];return[i,i]}}return[0,360]}function W(t){return D(t).saturationRange}function D(t){t>=334&&t<=360&&(t-=360);for(var n in r){var a=r[n];if(a.hueRange&&t>=a.hueRange[0]&&t<=a.hueRange[1])return r[n]}return"Color not found"}function R(t){if(s===null){var n=.618033988749895,a=Math.random();return a+=n,a%=1,Math.floor(t[0]+a*(t[1]+1-t[0]))}else{var i=t[1]||1,h=t[0]||0;s=(s*9301+49297)%233280;var g=s/233280;return Math.floor(h+g*(i-h))}}function G(t){var n=y(t);function a(h){var g=h.toString(16);return g.length==1?"0"+g:g}var i="#"+a(n[0])+a(n[1])+a(n[2]);return i}function v(t,n,a){var i=a[0][0],h=a[a.length-1][0],g=a[a.length-1][1],c=a[0][1];r[t]={hueRange:n,lowerBounds:a,saturationRange:[i,h],brightnessRange:[g,c]}}function O(){v("monochrome",null,[[0,0],[100,0]]),v("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),v("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),v("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),v("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),v("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),v("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),v("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function y(t){var n=t[0];n===0&&(n=1),n===360&&(n=359),n=n/360;var a=t[1]/100,i=t[2]/100,h=Math.floor(n*6),g=n*6-h,c=i*(1-a),w=i*(1-g*a),C=i*(1-(1-g)*a),p=256,M=256,S=256;switch(h){case 0:p=i,M=C,S=c;break;case 1:p=w,M=i,S=c;break;case 2:p=c,M=i,S=C;break;case 3:p=c,M=w,S=i;break;case 4:p=C,M=c,S=i;break;case 5:p=i,M=c,S=w;break}var B=[Math.floor(p*255),Math.floor(M*255),Math.floor(S*255)];return B}function T(t){t=t.replace(/^#/,""),t=t.length===3?t.replace(/(.)/g,"$1$1"):t;var n=parseInt(t.substr(0,2),16)/255,a=parseInt(t.substr(2,2),16)/255,i=parseInt(t.substr(4,2),16)/255,h=Math.max(n,a,i),g=h-Math.min(n,a,i),c=h?g/h:0;switch(h){case n:return[60*((a-i)/g%6)||0,c,h];case a:return[60*((i-n)/g+2)||0,c,h];case i:return[60*((n-a)/g+4)||0,c,h]}}function V(t){var n=t[0],a=t[1]/100,i=t[2]/100,h=(2-a)*i;return[n,Math.round(a*i/(h<1?h:2-h)*1e4)/100,h/2*100]}function F(t){for(var n=0,a=0;a!==t.length&&!(n>=Number.MAX_SAFE_INTEGER);a++)n+=t.charCodeAt(a);return n}function j(t){if(isNaN(t)){if(typeof t=="string"){if(r[t]){var a=r[t];if(a.hueRange)return a.hueRange}else if(t.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var i=T(t)[0];return D(i).hueRange}}}else{var n=parseInt(t);if(n<360&&n>0)return D(t).hueRange}return[0,360]}return l})})(P,P.exports);var z=P.exports;class J{constructor(e="NetlessApp",s="error"){A(this,"kind");A(this,"debug");A(this,"color",z({luminosity:"dark"}));this.kind=e,this.debug=s}log(...e){if(this.debug===!0||this.debug==="log")return this._log("log",e)}warn(...e){if(this.debug&&this.debug!=="error")return this._log("warn",e)}error(...e){if(this.debug)return this._log("error",e)}_log(e,s){console[e](`%c[${this.kind}]:`,`color: ${this.color}; font-weight: bold;`,...s)}}class E{constructor(){this.listeners=new Set}get length(){return this.listeners.size}dispatch(e){this.listeners.forEach(s=>s(e))}addListener(e){this.listeners.add(e)}removeListener(e){this.listeners.delete(e)}}const k=(u,e)=>Object.prototype.hasOwnProperty.call(u,e),N=Object.keys;function b(u){return typeof u=="object"&&u!==null}const Q=b;function $(u){return Boolean(b(u)&&u.__isRef)}function U(u){return{k:Y(),v:u,__isRef:!0}}function Y(){return Date.now().toString().slice(6)+Math.random().toString().slice(2,8)}class Z{constructor({id:e,state:s,onSetState:r,getIsWritable:o,logger:l=console}){this.onStateChanged=new E,this._destroyed=!1,this.onDestroyed=new E,this._kMap=new WeakMap,this._lastValue=new Map,this.id=e,this._onSetState=r,this.getIsWritable=o,this._logger=l,this._state={},s&&N(s).forEach(d=>{const f=s[d];if($(f)){const{k:_,v:m}=f;this._state[d]=m,b(m)&&this._kMap.set(m,_)}else this._state[d]=f})}get state(){return this._state}ensureState(e){return this.setState(N(e).reduce((s,r)=>(k(this._state,r)||(s[r]=e[r]),s),{}))}setState(e){if(this._destroyed){this._logger.error(`Cannot call setState on Store ${this.id} which is destroyed.`);return}if(!this.getIsWritable()){this._logger.error(`Cannot setState on store ${this.id} without writable access`,e);return}const s=N(e);if(s.length>0){const r={};s.forEach(o=>{const l=e[o];if(l===void 0)this._lastValue.set(o,this._state[o]),delete this._state[o],r[o]=l;else if(l!==this._state[o])if(this._lastValue.set(o,this._state[o]),this._state[o]=l,b(l)){const d=U(l);this._kMap.set(d.v,d.k),r[o]=d}else r[o]=l}),Object.keys(r).length>0&&this._onSetState(r)}}get destroyed(){return this._destroyed}_destroy(){this._destroyed=!0,this.onDestroyed.dispatch()}_updateProperties(e){if(this._destroyed){this._logger.error(`Cannot call _updateProperties on Store ${this.id} which is destroyed.`);return}if(e.length>0){const s={};e.forEach(({key:r,value:o,kind:l})=>{switch(l){case 2:{k(this._state,r)&&(this._lastValue.set(r,this._state[r]),delete this._state[r]),s[r]={oldValue:this._lastValue.get(r)};break}default:{let d=o;if($(o)){const{k:f,v:_}=o,m=this._state[r];b(m)&&this._kMap.get(m)===f?d=m:(d=_,b(_)&&this._kMap.set(_,f))}d!==this._state[r]&&(this._lastValue.set(r,this._state[r]),this._state[r]=d),s[r]={newValue:d,oldValue:this._lastValue.get(r)};break}}}),this.onStateChanged.dispatch(s)}}}class ee{constructor(e,s,r,o,l){this.onRoomMembersChanged=new E,this.onMessage=new E,this.onWritableChanged=new E,this.onPageChanged=new E,this._stores=new Map,this.sideEffect=new X,this.postMessage=r,this.storeNSPrefix=e.storeConfig.nsPrefix,this.mainStoreId=e.storeConfig.mainId,this._storeRawData=e.store||{[this.getStoreNamespace(this.mainStoreId)]:{}},this._writable=e.writable,this._page=e.page,this._meta=e.meta,this._roomMembers=e.roomMembers,this.logger=l,this.sideEffect.add(()=>o(d=>{const{type:f,payload:_}=d;if(f){const m=`_handleMsg${f}`;this[m]&&this[m](_)}})),this._mainStore=this.connectStore(e.storeConfig.mainId,s),this.onStateChanged=this._mainStore.onStateChanged}get meta(){return this._meta}get roomMembers(){return this._roomMembers}_handleMsgRoomMembersChanged(e){if(e==null||Array.isArray(e)){const s=this._roomMembers;this._roomMembers=e,this.onRoomMembersChanged.dispatch({newValue:this._roomMembers,oldValue:s})}}moveCamera(e){this.postMessage({type:"MoveCamera",payload:e})}sendMessage(e){this.postMessage({type:"SendMagixMessage",payload:e})}_handleMsgReceiveMagixMessage(e){this.onMessage.dispatch(e)}get isWritable(){return this._writable}_handleMsgWritableChanged(e){const s=Boolean(e),r=this._writable;s!==r&&(this._writable=s,this.onWritableChanged.dispatch({oldValue:r,newValue:s}))}get page(){return this._page}setPage(e){this._page=e,this.postMessage({type:"SetPage",payload:e})}_handleMsgPageChanged(e){Q(e)&&(this._page=e.newValue,this.onPageChanged.dispatch(e))}connectStore(e,s){const r=this.getStoreNamespace(e);let o=this._stores.get(r);if(!o){if(!k(this._storeRawData,r)){const l={};this.postMessage({type:"SetStore",payload:{[r]:l}}),this._storeRawData[r]=l}o=new Z({id:e,state:this._storeRawData[r],logger:this.logger,getIsWritable:()=>this._writable,onSetState:l=>this.postMessage({type:"SetState",payload:{namespace:r,state:l}})}),this._stores.set(r,o)}return s&&o.ensureState(s),o}hasStore(e){return this._stores.has(this.getStoreNamespace(e))}removeStore(e){if(e===this.mainStoreId){this.logger.error(`Store "${e}" is not removable.`);return}const s=this.getStoreNamespace(e),r=this._stores.get(s);r&&(this._stores.delete(s),r._destroy()),this._storeRawData[s]&&this.postMessage({type:"SetStore",payload:{[s]:void 0}})}_handleMsgStoreChanged(e){Array.isArray(e)&&e.length>0&&e.forEach(({key:r,value:o,kind:l})=>{switch(l){case 2:{delete this._storeRawData[r];const d=this._stores.get(r);d&&(this._stores.delete(r),d._destroy());break}default:{this._storeRawData[r]=o;break}}})}getStoreNamespace(e){return this.storeNSPrefix+e}get state(){return this._mainStore.state}ensureState(e){return this._mainStore.ensureState(e)}setState(e){return this._mainStore.setState(e)}_handleMsgStateChanged(e){if(b(e)&&e.namespace&&Array.isArray(e.actions)&&e.actions.length>0){const{namespace:s,actions:r}=e;r.forEach(({key:l,value:d,kind:f})=>{switch(f){case 2:{const _=this._storeRawData[s];b(_)&&delete _[l];break}default:{const _=this._storeRawData[s];b(_)&&(_[l]=d);break}}});const o=this._stores.get(s);o&&o._updateProperties(r)}}destroy(){this.sideEffect.flushAll()}}let I;function te(u={}){if(!parent)throw new Error("[EmbeddedPageSDK]: SDK is not running in a iframe.");if(I)return Promise.resolve(I);const e=new J("EmbeddedPageSDK",u.debug),s=o=>{e.log("Message to parent",o),parent.postMessage(o,"*")},r=(o,l)=>{const d=({data:f,source:_})=>{if(!(!parent||_!==parent)){if(!b(f)){console.warn("window message data should be object, instead got",f);return}e.log("Message from parent",f),o(f)}};return window.addEventListener("message",d,l),()=>{window.removeEventListener("message",d,l)}};return s({type:"Init"}),new Promise(o=>{const l=r(d=>{if(I){l(),o(I);return}if(d.type==="Init"){l();const f=new ee(d.payload,u.ensureState||{},s,r,e);I=f,o(f)}})})}exports.createEmbeddedApp=te;
//# sourceMappingURL=main.cjs.js.map
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};

@@ -68,128 +58,748 @@ class s {

}
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var randomColor$1 = { exports: {} };
(function(module, exports) {
(function(root, factory) {
{
var randomColor2 = factory();
if (module && module.exports) {
exports = module.exports = randomColor2;
}
exports.randomColor = randomColor2;
}
})(commonjsGlobal, function() {
var seed = null;
var colorDictionary = {};
loadColorBounds();
var colorRanges = [];
var randomColor2 = function(options) {
options = options || {};
if (options.seed !== void 0 && options.seed !== null && options.seed === parseInt(options.seed, 10)) {
seed = options.seed;
} else if (typeof options.seed === "string") {
seed = stringToInteger(options.seed);
} else if (options.seed !== void 0 && options.seed !== null) {
throw new TypeError("The seed value must be an integer or string");
} else {
seed = null;
}
var H, S, B;
if (options.count !== null && options.count !== void 0) {
var totalColors = options.count, colors = [];
for (var i = 0; i < options.count; i++) {
colorRanges.push(false);
}
options.count = null;
while (totalColors > colors.length) {
var color = randomColor2(options);
if (seed !== null) {
options.seed = seed;
}
colors.push(color);
}
options.count = totalColors;
return colors;
}
H = pickHue(options);
S = pickSaturation(H, options);
B = pickBrightness(H, S, options);
return setFormat([H, S, B], options);
};
function pickHue(options) {
if (colorRanges.length > 0) {
var hueRange = getRealHueRange(options.hue);
var hue = randomWithin(hueRange);
var step = (hueRange[1] - hueRange[0]) / colorRanges.length;
var j = parseInt((hue - hueRange[0]) / step);
if (colorRanges[j] === true) {
j = (j + 2) % colorRanges.length;
} else {
colorRanges[j] = true;
}
var min = (hueRange[0] + j * step) % 359, max = (hueRange[0] + (j + 1) * step) % 359;
hueRange = [min, max];
hue = randomWithin(hueRange);
if (hue < 0) {
hue = 360 + hue;
}
return hue;
} else {
var hueRange = getHueRange(options.hue);
hue = randomWithin(hueRange);
if (hue < 0) {
hue = 360 + hue;
}
return hue;
}
}
function pickSaturation(hue, options) {
if (options.hue === "monochrome") {
return 0;
}
if (options.luminosity === "random") {
return randomWithin([0, 100]);
}
var saturationRange = getSaturationRange(hue);
var sMin = saturationRange[0], sMax = saturationRange[1];
switch (options.luminosity) {
case "bright":
sMin = 55;
break;
case "dark":
sMin = sMax - 10;
break;
case "light":
sMax = 55;
break;
}
return randomWithin([sMin, sMax]);
}
function pickBrightness(H, S, options) {
var bMin = getMinimumBrightness(H, S), bMax = 100;
switch (options.luminosity) {
case "dark":
bMax = bMin + 20;
break;
case "light":
bMin = (bMax + bMin) / 2;
break;
case "random":
bMin = 0;
bMax = 100;
break;
}
return randomWithin([bMin, bMax]);
}
function setFormat(hsv, options) {
switch (options.format) {
case "hsvArray":
return hsv;
case "hslArray":
return HSVtoHSL(hsv);
case "hsl":
var hsl = HSVtoHSL(hsv);
return "hsl(" + hsl[0] + ", " + hsl[1] + "%, " + hsl[2] + "%)";
case "hsla":
var hslColor = HSVtoHSL(hsv);
var alpha = options.alpha || Math.random();
return "hsla(" + hslColor[0] + ", " + hslColor[1] + "%, " + hslColor[2] + "%, " + alpha + ")";
case "rgbArray":
return HSVtoRGB(hsv);
case "rgb":
var rgb = HSVtoRGB(hsv);
return "rgb(" + rgb.join(", ") + ")";
case "rgba":
var rgbColor = HSVtoRGB(hsv);
var alpha = options.alpha || Math.random();
return "rgba(" + rgbColor.join(", ") + ", " + alpha + ")";
default:
return HSVtoHex(hsv);
}
}
function getMinimumBrightness(H, S) {
var lowerBounds = getColorInfo(H).lowerBounds;
for (var i = 0; i < lowerBounds.length - 1; i++) {
var s1 = lowerBounds[i][0], v1 = lowerBounds[i][1];
var s2 = lowerBounds[i + 1][0], v2 = lowerBounds[i + 1][1];
if (S >= s1 && S <= s2) {
var m = (v2 - v1) / (s2 - s1), b = v1 - m * s1;
return m * S + b;
}
}
return 0;
}
function getHueRange(colorInput) {
if (typeof parseInt(colorInput) === "number") {
var number = parseInt(colorInput);
if (number < 360 && number > 0) {
return [number, number];
}
}
if (typeof colorInput === "string") {
if (colorDictionary[colorInput]) {
var color = colorDictionary[colorInput];
if (color.hueRange) {
return color.hueRange;
}
} else if (colorInput.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)) {
var hue = HexToHSB(colorInput)[0];
return [hue, hue];
}
}
return [0, 360];
}
function getSaturationRange(hue) {
return getColorInfo(hue).saturationRange;
}
function getColorInfo(hue) {
if (hue >= 334 && hue <= 360) {
hue -= 360;
}
for (var colorName in colorDictionary) {
var color = colorDictionary[colorName];
if (color.hueRange && hue >= color.hueRange[0] && hue <= color.hueRange[1]) {
return colorDictionary[colorName];
}
}
return "Color not found";
}
function randomWithin(range) {
if (seed === null) {
var golden_ratio = 0.618033988749895;
var r = Math.random();
r += golden_ratio;
r %= 1;
return Math.floor(range[0] + r * (range[1] + 1 - range[0]));
} else {
var max = range[1] || 1;
var min = range[0] || 0;
seed = (seed * 9301 + 49297) % 233280;
var rnd = seed / 233280;
return Math.floor(min + rnd * (max - min));
}
}
function HSVtoHex(hsv) {
var rgb = HSVtoRGB(hsv);
function componentToHex(c) {
var hex2 = c.toString(16);
return hex2.length == 1 ? "0" + hex2 : hex2;
}
var hex = "#" + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);
return hex;
}
function defineColor(name, hueRange, lowerBounds) {
var sMin = lowerBounds[0][0], sMax = lowerBounds[lowerBounds.length - 1][0], bMin = lowerBounds[lowerBounds.length - 1][1], bMax = lowerBounds[0][1];
colorDictionary[name] = {
hueRange,
lowerBounds,
saturationRange: [sMin, sMax],
brightnessRange: [bMin, bMax]
};
}
function loadColorBounds() {
defineColor("monochrome", null, [[0, 0], [100, 0]]);
defineColor("red", [-26, 18], [[20, 100], [30, 92], [40, 89], [50, 85], [60, 78], [70, 70], [80, 60], [90, 55], [100, 50]]);
defineColor("orange", [18, 46], [[20, 100], [30, 93], [40, 88], [50, 86], [60, 85], [70, 70], [100, 70]]);
defineColor("yellow", [46, 62], [[25, 100], [40, 94], [50, 89], [60, 86], [70, 84], [80, 82], [90, 80], [100, 75]]);
defineColor("green", [62, 178], [[30, 100], [40, 90], [50, 85], [60, 81], [70, 74], [80, 64], [90, 50], [100, 40]]);
defineColor("blue", [178, 257], [[20, 100], [30, 86], [40, 80], [50, 74], [60, 60], [70, 52], [80, 44], [90, 39], [100, 35]]);
defineColor("purple", [257, 282], [[20, 100], [30, 87], [40, 79], [50, 70], [60, 65], [70, 59], [80, 52], [90, 45], [100, 42]]);
defineColor("pink", [282, 334], [[20, 100], [30, 90], [40, 86], [60, 84], [80, 80], [90, 75], [100, 73]]);
}
function HSVtoRGB(hsv) {
var h = hsv[0];
if (h === 0) {
h = 1;
}
if (h === 360) {
h = 359;
}
h = h / 360;
var s2 = hsv[1] / 100, v = hsv[2] / 100;
var h_i = Math.floor(h * 6), f = h * 6 - h_i, p = v * (1 - s2), q = v * (1 - f * s2), t = v * (1 - (1 - f) * s2), r = 256, g = 256, b = 256;
switch (h_i) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
var result = [Math.floor(r * 255), Math.floor(g * 255), Math.floor(b * 255)];
return result;
}
function HexToHSB(hex) {
hex = hex.replace(/^#/, "");
hex = hex.length === 3 ? hex.replace(/(.)/g, "$1$1") : hex;
var red = parseInt(hex.substr(0, 2), 16) / 255, green = parseInt(hex.substr(2, 2), 16) / 255, blue = parseInt(hex.substr(4, 2), 16) / 255;
var cMax = Math.max(red, green, blue), delta = cMax - Math.min(red, green, blue), saturation = cMax ? delta / cMax : 0;
switch (cMax) {
case red:
return [60 * ((green - blue) / delta % 6) || 0, saturation, cMax];
case green:
return [60 * ((blue - red) / delta + 2) || 0, saturation, cMax];
case blue:
return [60 * ((red - green) / delta + 4) || 0, saturation, cMax];
}
}
function HSVtoHSL(hsv) {
var h = hsv[0], s2 = hsv[1] / 100, v = hsv[2] / 100, k = (2 - s2) * v;
return [
h,
Math.round(s2 * v / (k < 1 ? k : 2 - k) * 1e4) / 100,
k / 2 * 100
];
}
function stringToInteger(string) {
var total = 0;
for (var i = 0; i !== string.length; i++) {
if (total >= Number.MAX_SAFE_INTEGER)
break;
total += string.charCodeAt(i);
}
return total;
}
function getRealHueRange(colorHue) {
if (!isNaN(colorHue)) {
var number = parseInt(colorHue);
if (number < 360 && number > 0) {
return getColorInfo(colorHue).hueRange;
}
} else if (typeof colorHue === "string") {
if (colorDictionary[colorHue]) {
var color = colorDictionary[colorHue];
if (color.hueRange) {
return color.hueRange;
}
} else if (colorHue.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)) {
var hue = HexToHSB(colorHue)[0];
return getColorInfo(hue).hueRange;
}
}
return [0, 360];
}
return randomColor2;
});
})(randomColor$1, randomColor$1.exports);
var randomColor = randomColor$1.exports;
class Logger {
constructor(kind = "NetlessApp", debug = "error") {
__publicField(this, "kind");
__publicField(this, "debug");
__publicField(this, "color", randomColor({ luminosity: "dark" }));
this.kind = kind;
this.debug = debug;
}
log(...messages) {
if (this.debug === true || this.debug === "log") {
return this._log("log", messages);
}
}
warn(...messages) {
if (this.debug && this.debug !== "error") {
return this._log("warn", messages);
}
}
error(...messages) {
if (this.debug) {
return this._log("error", messages);
}
}
_log(type, messages) {
console[type](`%c[${this.kind}]:`, `color: ${this.color}; font-weight: bold;`, ...messages);
}
}
class EmbeddedPageEvent {
constructor() {
this.listeners = new Set();
}
get length() {
return this.listeners.size;
}
dispatch(message) {
this.listeners.forEach((callback) => callback(message));
}
addListener(listener) {
this.listeners.add(listener);
}
removeListener(listener) {
this.listeners.delete(listener);
}
}
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const plainObjectKeys = Object.keys;
function isObj(e) {
return typeof e === "object" && e !== null;
}
function createEmitter() {
const listeners = new Set();
const dispatch = (event) => listeners.forEach((f) => f(event));
const addListener = (listener) => listeners.add(listener);
const removeListener = (listener) => listeners.delete(listener);
return { dispatch, addListener, removeListener };
const isDiffOne = isObj;
function isRef(e) {
return Boolean(isObj(e) && e.__isRef);
}
function createEmbeddedApp(callback) {
let state;
let page;
let writable = false;
let meta;
const onInit = createEmitter();
const onMessage = createEmitter();
const onStateChanged = createEmitter();
const onPageChanged = createEmitter();
const onWritableChanged = createEmitter();
const sideEffectManager = new s();
let onStateChangedPayload;
let onPageChangedPayload;
let onWritableChangedPayload;
function postMessage(message) {
parent.postMessage(message, "*");
function makeRef(v) {
return { k: genId(), v, __isRef: true };
}
function genId() {
return Date.now().toString().slice(6) + Math.random().toString().slice(2, 8);
}
class StoreImpl {
constructor({ id, state, onSetState, getIsWritable, logger = console }) {
this.onStateChanged = new EmbeddedPageEvent();
this._destroyed = false;
this.onDestroyed = new EmbeddedPageEvent();
this._kMap = new WeakMap();
this._lastValue = new Map();
this.id = id;
this._onSetState = onSetState;
this.getIsWritable = getIsWritable;
this._logger = logger;
this._state = {};
if (state) {
plainObjectKeys(state).forEach((key) => {
const rawValue = state[key];
if (isRef(rawValue)) {
const { k, v } = rawValue;
this._state[key] = v;
if (isObj(v)) {
this._kMap.set(v, k);
}
} else {
this._state[key] = rawValue;
}
});
}
}
sideEffectManager.addEventListener(window, "message", (e) => {
if (!isObj(e.data)) {
console.warn("window message data should be object, instead got", e.data);
get state() {
return this._state;
}
ensureState(state) {
return this.setState(plainObjectKeys(state).reduce((payload, key) => {
if (!has(this._state, key)) {
payload[key] = state[key];
}
return payload;
}, {}));
}
setState(state) {
if (this._destroyed) {
this._logger.error(`Cannot call setState on Store ${this.id} which is destroyed.`);
return;
}
const event = e.data;
if (event.type === "Init") {
const { payload } = event;
state = payload.state;
page = payload.page;
writable = payload.writable;
meta = payload.meta;
onInit.dispatch(payload);
} else if (event.type === "ReceiveMessage") {
onMessage.dispatch(event.payload);
} else {
if (event.type === "StateChanged") {
onStateChangedPayload = event.payload;
postMessage({ type: "GetState" });
} else if (event.type === "GetState") {
state = event.payload;
if (onStateChangedPayload) {
onStateChanged.dispatch(onStateChangedPayload);
onStateChangedPayload = void 0;
if (!this.getIsWritable()) {
this._logger.error(`Cannot setState on store ${this.id} without writable access`, state);
return;
}
const keys = plainObjectKeys(state);
if (keys.length > 0) {
const payload = {};
keys.forEach((key) => {
const value = state[key];
if (value === void 0) {
this._lastValue.set(key, this._state[key]);
delete this._state[key];
payload[key] = value;
} else if (value !== this._state[key]) {
this._lastValue.set(key, this._state[key]);
this._state[key] = value;
if (isObj(value)) {
const refValue = makeRef(value);
this._kMap.set(refValue.v, refValue.k);
payload[key] = refValue;
} else {
payload[key] = value;
}
}
});
if (Object.keys(payload).length > 0) {
this._onSetState(payload);
}
if (event.type === "PageChanged") {
onPageChangedPayload = event.payload;
postMessage({ type: "GetPage" });
} else if (event.type === "GetPage") {
page = event.payload;
if (onPageChangedPayload) {
onPageChanged.dispatch(onPageChangedPayload);
onPageChangedPayload = void 0;
}
}
get destroyed() {
return this._destroyed;
}
_destroy() {
this._destroyed = true;
this.onDestroyed.dispatch();
}
_updateProperties(actions) {
if (this._destroyed) {
this._logger.error(`Cannot call _updateProperties on Store ${this.id} which is destroyed.`);
return;
}
if (actions.length > 0) {
const diffs = {};
actions.forEach(({ key, value, kind }) => {
switch (kind) {
case 2: {
if (has(this._state, key)) {
this._lastValue.set(key, this._state[key]);
delete this._state[key];
}
diffs[key] = { oldValue: this._lastValue.get(key) };
break;
}
default: {
let realValue = value;
if (isRef(value)) {
const { k, v } = value;
const curValue = this._state[key];
if (isObj(curValue) && this._kMap.get(curValue) === k) {
realValue = curValue;
} else {
realValue = v;
if (isObj(v)) {
this._kMap.set(v, k);
}
}
}
if (realValue !== this._state[key]) {
this._lastValue.set(key, this._state[key]);
this._state[key] = realValue;
}
diffs[key] = { newValue: realValue, oldValue: this._lastValue.get(key) };
break;
}
}
});
this.onStateChanged.dispatch(diffs);
}
}
}
class EmbeddedApp {
constructor(initData, ensureState, postMessage, addMessageListener, logger) {
this.onRoomMembersChanged = new EmbeddedPageEvent();
this.onMessage = new EmbeddedPageEvent();
this.onWritableChanged = new EmbeddedPageEvent();
this.onPageChanged = new EmbeddedPageEvent();
this._stores = new Map();
this.sideEffect = new s();
this.postMessage = postMessage;
this.storeNSPrefix = initData.storeConfig.nsPrefix;
this.mainStoreId = initData.storeConfig.mainId;
this._storeRawData = initData.store || {
[this.getStoreNamespace(this.mainStoreId)]: {}
};
this._writable = initData.writable;
this._page = initData.page;
this._meta = initData.meta;
this._roomMembers = initData.roomMembers;
this.logger = logger;
this.sideEffect.add(() => addMessageListener((message) => {
const { type, payload } = message;
if (type) {
const method = `_handleMsg${type}`;
if (this[method]) {
this[method](payload);
}
}
if (event.type === "WritableChanged") {
onWritableChangedPayload = event.payload;
postMessage({ type: "GetWritable" });
} else if (event.type === "GetWritable") {
writable = event.payload;
if (onWritableChangedPayload) {
onWritableChanged.dispatch(onWritableChangedPayload);
onWritableChangedPayload = void 0;
}));
this._mainStore = this.connectStore(initData.storeConfig.mainId, ensureState);
this.onStateChanged = this._mainStore.onStateChanged;
}
get meta() {
return this._meta;
}
get roomMembers() {
return this._roomMembers;
}
_handleMsgRoomMembersChanged(payload) {
if (payload == null || Array.isArray(payload)) {
const oldRoomMembers = this._roomMembers;
this._roomMembers = payload;
this.onRoomMembersChanged.dispatch({
newValue: this._roomMembers,
oldValue: oldRoomMembers
});
}
}
moveCamera(camera) {
this.postMessage({ type: "MoveCamera", payload: camera });
}
sendMessage(payload) {
this.postMessage({ type: "SendMagixMessage", payload });
}
_handleMsgReceiveMagixMessage(payload) {
this.onMessage.dispatch(payload);
}
get isWritable() {
return this._writable;
}
_handleMsgWritableChanged(payload) {
const newValue = Boolean(payload);
const oldValue = this._writable;
if (newValue !== oldValue) {
this._writable = newValue;
this.onWritableChanged.dispatch({ oldValue, newValue });
}
}
get page() {
return this._page;
}
setPage(page) {
this._page = page;
this.postMessage({ type: "SetPage", payload: page });
}
_handleMsgPageChanged(payload) {
if (isDiffOne(payload)) {
this._page = payload.newValue;
this.onPageChanged.dispatch(payload);
}
}
connectStore(id, ensureState) {
const namespace = this.getStoreNamespace(id);
let store = this._stores.get(namespace);
if (!store) {
if (!has(this._storeRawData, namespace)) {
const storeState = {};
this.postMessage({ type: "SetStore", payload: { [namespace]: storeState } });
this._storeRawData[namespace] = storeState;
}
store = new StoreImpl({
id,
state: this._storeRawData[namespace],
logger: this.logger,
getIsWritable: () => this._writable,
onSetState: (state) => this.postMessage({ type: "SetState", payload: { namespace, state } })
});
this._stores.set(namespace, store);
}
if (ensureState) {
store.ensureState(ensureState);
}
return store;
}
hasStore(id) {
return this._stores.has(this.getStoreNamespace(id));
}
removeStore(id) {
if (id === this.mainStoreId) {
this.logger.error(`Store "${id}" is not removable.`);
return;
}
const namespace = this.getStoreNamespace(id);
const store = this._stores.get(namespace);
if (store) {
this._stores.delete(namespace);
store._destroy();
}
if (this._storeRawData[namespace]) {
this.postMessage({ type: "SetStore", payload: { [namespace]: void 0 } });
}
}
_handleMsgStoreChanged(payload) {
if (Array.isArray(payload) && payload.length > 0) {
const actions = payload;
actions.forEach(({ key, value, kind }) => {
switch (kind) {
case 2: {
delete this._storeRawData[key];
const store = this._stores.get(key);
if (store) {
this._stores.delete(key);
store._destroy();
}
break;
}
default: {
this._storeRawData[key] = value;
break;
}
}
});
}
}
getStoreNamespace(id) {
return this.storeNSPrefix + id;
}
get state() {
return this._mainStore.state;
}
ensureState(state) {
return this._mainStore.ensureState(state);
}
setState(state) {
return this._mainStore.setState(state);
}
_handleMsgStateChanged(payload) {
if (isObj(payload) && payload.namespace && Array.isArray(payload.actions) && payload.actions.length > 0) {
const { namespace, actions } = payload;
actions.forEach(({ key, value, kind }) => {
switch (kind) {
case 2: {
const storeData = this._storeRawData[namespace];
if (isObj(storeData)) {
delete storeData[key];
}
break;
}
default: {
const storeData = this._storeRawData[namespace];
if (isObj(storeData)) {
storeData[key] = value;
}
break;
}
}
});
const store = this._stores.get(namespace);
if (store) {
store._updateProperties(actions);
}
}
});
const ensureState = (initialState) => {
state = __spreadValues(__spreadValues({}, initialState), state);
}
destroy() {
this.sideEffect.flushAll();
}
}
let singleApp;
function createEmbeddedApp(config = {}) {
if (!parent) {
throw new Error("[EmbeddedPageSDK]: SDK is not running in a iframe.");
}
if (singleApp) {
return Promise.resolve(singleApp);
}
const logger = new Logger("EmbeddedPageSDK", config.debug);
const postMessage = (message) => {
logger.log("Message to parent", message);
parent.postMessage(message, "*");
};
const setState = (newState) => {
for (const [key, value] of Object.entries(newState)) {
if (value === void 0) {
delete state[key];
} else {
state[key] = value;
const addMessageListener = (listener, options) => {
const handler = ({
data,
source
}) => {
if (!parent || source !== parent)
return;
if (!isObj(data)) {
console.warn("window message data should be object, instead got", data);
return;
}
}
postMessage({ type: "SetState", payload: newState });
logger.log("Message from parent", data);
listener(data);
};
window.addEventListener("message", handler, options);
return () => {
window.removeEventListener("message", handler, options);
};
};
const setPage = (newPage) => {
page = newPage;
postMessage({ type: "SetPage", payload: newPage });
};
const sendMessage = (payload) => {
postMessage({ type: "SendMessage", payload });
};
const destroy = () => sideEffectManager.flushAll();
const app = {
get state() {
return state;
},
get page() {
return page;
},
get isWritable() {
return writable;
},
get meta() {
return meta;
},
ensureState,
setState,
setPage,
sendMessage,
destroy,
onStateChanged,
onPageChanged,
onWritableChanged,
onMessage
};
postMessage({ type: "Init" });
return new Promise((resolve) => {
const handler = () => {
onInit.removeListener(handler);
callback == null ? void 0 : callback(app);
resolve(app);
};
onInit.addListener(handler);
const disposer = addMessageListener((message) => {
if (singleApp) {
disposer();
resolve(singleApp);
return;
}
if (message.type === "Init") {
disposer();
const app = new EmbeddedApp(message.payload, config.ensureState || {}, postMessage, addMessageListener, logger);
singleApp = app;
resolve(app);
}
});
});

@@ -196,0 +806,0 @@ }

@@ -1,2 +0,2 @@

(()=>{var M=Object.defineProperty;var E=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable;var C=(r,i,d)=>i in r?M(r,i,{enumerable:!0,configurable:!0,writable:!0,value:d}):r[i]=d,v=(r,i)=>{for(var d in i||(i={}))G.call(i,d)&&C(r,d,i[d]);if(E)for(var d of E(i))L.call(i,d)&&C(r,d,i[d]);return r};var O=function(r){"use strict";class i{constructor(){this.disposers=new Map,this.disposerIDGenCount=-1}add(e,t=this.genDisposerID()){return this.flush(t),this.disposers.set(t,e()),t}addEventListener(e,t,o,a,l=this.genDisposerID()){return this.add(()=>(e.addEventListener(t,o,a),()=>e.removeEventListener(t,o,a)),l),l}setTimeout(e,t,o=this.genDisposerID()){return this.add(()=>{const a=window.setTimeout(()=>{this.remove(o),e()},t);return()=>window.clearTimeout(a)},o)}setInterval(e,t,o=this.genDisposerID()){return this.add(()=>{const a=window.setInterval(e,t);return()=>window.clearInterval(a)},o)}remove(e){const t=this.disposers.get(e);return this.disposers.delete(e),t}flush(e){const t=this.remove(e);if(t)try{t()}catch(o){console.error(o)}}flushAll(){this.disposers.forEach(e=>{try{e()}catch(t){console.error(t)}}),this.disposers.clear()}genDisposerID(){const{MAX_SAFE_INTEGER:e=9007199254740991}=Number;return this.disposerIDGenCount=(this.disposerIDGenCount+1)%e,`disposer-${this.disposerIDGenCount}`}}function d(p){return typeof p=="object"&&p!==null}function u(){const p=new Set;return{dispatch:a=>p.forEach(l=>l(a)),addListener:a=>p.add(a),removeListener:a=>p.delete(a)}}function P(p){let e,t,o=!1,a;const l=u(),m=u(),w=u(),S=u(),b=u(),I=new i;let g,y,f;function h(n){parent.postMessage(n,"*")}I.addEventListener(window,"message",n=>{if(!d(n.data)){console.warn("window message data should be object, instead got",n.data);return}const s=n.data;if(s.type==="Init"){const{payload:c}=s;e=c.state,t=c.page,o=c.writable,a=c.meta,l.dispatch(c)}else s.type==="ReceiveMessage"?m.dispatch(s.payload):(s.type==="StateChanged"?(g=s.payload,h({type:"GetState"})):s.type==="GetState"&&(e=s.payload,g&&(w.dispatch(g),g=void 0)),s.type==="PageChanged"?(y=s.payload,h({type:"GetPage"})):s.type==="GetPage"&&(t=s.payload,y&&(S.dispatch(y),y=void 0)),s.type==="WritableChanged"?(f=s.payload,h({type:"GetWritable"})):s.type==="GetWritable"&&(o=s.payload,f&&(b.dispatch(f),f=void 0)))});const D={get state(){return e},get page(){return t},get isWritable(){return o},get meta(){return a},ensureState:n=>{e=v(v({},n),e)},setState:n=>{for(const[s,c]of Object.entries(n))c===void 0?delete e[s]:e[s]=c;h({type:"SetState",payload:n})},setPage:n=>{t=n,h({type:"SetPage",payload:n})},sendMessage:n=>{h({type:"SendMessage",payload:n})},destroy:()=>I.flushAll(),onStateChanged:w,onPageChanged:S,onWritableChanged:b,onMessage:m};return new Promise(n=>{const s=()=>{l.removeListener(s),p==null||p(D),n(D)};l.addListener(s)})}return r.createEmbeddedApp=P,Object.defineProperty(r,"__esModule",{value:!0}),r[Symbol.toStringTag]="Module",r}({});})();
(()=>{var te=Object.defineProperty;var se=(b,v,S)=>v in b?te(b,v,{enumerable:!0,configurable:!0,writable:!0,value:S}):b[v]=S;var k=(b,v,S)=>(se(b,typeof v!="symbol"?v+"":v,S),S);var ae=function(b){"use strict";class v{constructor(){this.disposers=new Map,this.disposerIDGenCount=-1}add(e,a=this.genDisposerID()){return this.flush(a),this.disposers.set(a,e()),a}addEventListener(e,a,s,o,l=this.genDisposerID()){return this.add(()=>(e.addEventListener(a,s,o),()=>e.removeEventListener(a,s,o)),l),l}setTimeout(e,a,s=this.genDisposerID()){return this.add(()=>{const o=window.setTimeout(()=>{this.remove(s),e()},a);return()=>window.clearTimeout(o)},s)}setInterval(e,a,s=this.genDisposerID()){return this.add(()=>{const o=window.setInterval(e,a);return()=>window.clearInterval(o)},s)}remove(e){const a=this.disposers.get(e);return this.disposers.delete(e),a}flush(e){const a=this.remove(e);if(a)try{a()}catch(s){console.error(s)}}flushAll(){this.disposers.forEach(e=>{try{e()}catch(a){console.error(a)}}),this.disposers.clear()}genDisposerID(){const{MAX_SAFE_INTEGER:e=9007199254740991}=Number;return this.disposerIDGenCount=(this.disposerIDGenCount+1)%e,`disposer-${this.disposerIDGenCount}`}}var S=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},N={exports:{}};(function(c,e){(function(a,s){{var o=s();c&&c.exports&&(e=c.exports=o),e.randomColor=o}})(S,function(){var a=null,s={};U();var o=[],l=function(t){if(t=t||{},t.seed!==void 0&&t.seed!==null&&t.seed===parseInt(t.seed,10))a=t.seed;else if(typeof t.seed=="string")a=Y(t.seed);else{if(t.seed!==void 0&&t.seed!==null)throw new TypeError("The seed value must be an integer or string");a=null}var n,r,i;if(t.count!==null&&t.count!==void 0){for(var h=t.count,u=[],g=0;g<t.count;g++)o.push(!1);for(t.count=null;h>u.length;){var R=l(t);a!==null&&(t.seed=a),u.push(R)}return t.count=h,u}return n=d(t),r=f(n,t),i=_(n,r,t),m([n,r,i],t)};function d(t){if(o.length>0){var n=Z(t.hue),r=A(n),i=(n[1]-n[0])/o.length,h=parseInt((r-n[0])/i);o[h]===!0?h=(h+2)%o.length:o[h]=!0;var u=(n[0]+h*i)%359,g=(n[0]+(h+1)*i)%359;return n=[u,g],r=A(n),r<0&&(r=360+r),r}else{var n=z(t.hue);return r=A(n),r<0&&(r=360+r),r}}function f(t,n){if(n.hue==="monochrome")return 0;if(n.luminosity==="random")return A([0,100]);var r=J(t),i=r[0],h=r[1];switch(n.luminosity){case"bright":i=55;break;case"dark":i=h-10;break;case"light":h=55;break}return A([i,h])}function _(t,n,r){var i=q(t,n),h=100;switch(r.luminosity){case"dark":h=i+20;break;case"light":i=(h+i)/2;break;case"random":i=0,h=100;break}return A([i,h])}function m(t,n){switch(n.format){case"hsvArray":return t;case"hslArray":return L(t);case"hsl":var r=L(t);return"hsl("+r[0]+", "+r[1]+"%, "+r[2]+"%)";case"hsla":var i=L(t),h=n.alpha||Math.random();return"hsla("+i[0]+", "+i[1]+"%, "+i[2]+"%, "+h+")";case"rgbArray":return P(t);case"rgb":var u=P(t);return"rgb("+u.join(", ")+")";case"rgba":var g=P(t),h=n.alpha||Math.random();return"rgba("+g.join(", ")+", "+h+")";default:return Q(t)}}function q(t,n){for(var r=V(t).lowerBounds,i=0;i<r.length-1;i++){var h=r[i][0],u=r[i][1],g=r[i+1][0],R=r[i+1][1];if(n>=h&&n<=g){var D=(R-u)/(g-h),w=u-D*h;return D*n+w}}return 0}function z(t){if(typeof parseInt(t)=="number"){var n=parseInt(t);if(n<360&&n>0)return[n,n]}if(typeof t=="string"){if(s[t]){var r=s[t];if(r.hueRange)return r.hueRange}else if(t.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var i=W(t)[0];return[i,i]}}return[0,360]}function J(t){return V(t).saturationRange}function V(t){t>=334&&t<=360&&(t-=360);for(var n in s){var r=s[n];if(r.hueRange&&t>=r.hueRange[0]&&t<=r.hueRange[1])return s[n]}return"Color not found"}function A(t){if(a===null){var n=.618033988749895,r=Math.random();return r+=n,r%=1,Math.floor(t[0]+r*(t[1]+1-t[0]))}else{var i=t[1]||1,h=t[0]||0;a=(a*9301+49297)%233280;var u=a/233280;return Math.floor(h+u*(i-h))}}function Q(t){var n=P(t);function r(h){var u=h.toString(16);return u.length==1?"0"+u:u}var i="#"+r(n[0])+r(n[1])+r(n[2]);return i}function M(t,n,r){var i=r[0][0],h=r[r.length-1][0],u=r[r.length-1][1],g=r[0][1];s[t]={hueRange:n,lowerBounds:r,saturationRange:[i,h],brightnessRange:[u,g]}}function U(){M("monochrome",null,[[0,0],[100,0]]),M("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),M("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),M("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),M("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),M("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),M("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),M("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function P(t){var n=t[0];n===0&&(n=1),n===360&&(n=359),n=n/360;var r=t[1]/100,i=t[2]/100,h=Math.floor(n*6),u=n*6-h,g=i*(1-r),R=i*(1-u*r),D=i*(1-(1-u)*r),w=256,C=256,E=256;switch(h){case 0:w=i,C=D,E=g;break;case 1:w=R,C=i,E=g;break;case 2:w=g,C=i,E=D;break;case 3:w=g,C=R,E=i;break;case 4:w=D,C=g,E=i;break;case 5:w=i,C=g,E=R;break}var ee=[Math.floor(w*255),Math.floor(C*255),Math.floor(E*255)];return ee}function W(t){t=t.replace(/^#/,""),t=t.length===3?t.replace(/(.)/g,"$1$1"):t;var n=parseInt(t.substr(0,2),16)/255,r=parseInt(t.substr(2,2),16)/255,i=parseInt(t.substr(4,2),16)/255,h=Math.max(n,r,i),u=h-Math.min(n,r,i),g=h?u/h:0;switch(h){case n:return[60*((r-i)/u%6)||0,g,h];case r:return[60*((i-n)/u+2)||0,g,h];case i:return[60*((n-r)/u+4)||0,g,h]}}function L(t){var n=t[0],r=t[1]/100,i=t[2]/100,h=(2-r)*i;return[n,Math.round(r*i/(h<1?h:2-h)*1e4)/100,h/2*100]}function Y(t){for(var n=0,r=0;r!==t.length&&!(n>=Number.MAX_SAFE_INTEGER);r++)n+=t.charCodeAt(r);return n}function Z(t){if(isNaN(t)){if(typeof t=="string"){if(s[t]){var r=s[t];if(r.hueRange)return r.hueRange}else if(t.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var i=W(t)[0];return V(i).hueRange}}}else{var n=parseInt(t);if(n<360&&n>0)return V(t).hueRange}return[0,360]}return l})})(N,N.exports);var G=N.exports;class O{constructor(e="NetlessApp",a="error"){k(this,"kind");k(this,"debug");k(this,"color",G({luminosity:"dark"}));this.kind=e,this.debug=a}log(...e){if(this.debug===!0||this.debug==="log")return this._log("log",e)}warn(...e){if(this.debug&&this.debug!=="error")return this._log("warn",e)}error(...e){if(this.debug)return this._log("error",e)}_log(e,a){console[e](`%c[${this.kind}]:`,`color: ${this.color}; font-weight: bold;`,...a)}}class I{constructor(){this.listeners=new Set}get length(){return this.listeners.size}dispatch(e){this.listeners.forEach(a=>a(e))}addListener(e){this.listeners.add(e)}removeListener(e){this.listeners.delete(e)}}const T=(c,e)=>Object.prototype.hasOwnProperty.call(c,e),$=Object.keys;function p(c){return typeof c=="object"&&c!==null}const F=p;function x(c){return Boolean(p(c)&&c.__isRef)}function j(c){return{k:B(),v:c,__isRef:!0}}function B(){return Date.now().toString().slice(6)+Math.random().toString().slice(2,8)}class H{constructor({id:e,state:a,onSetState:s,getIsWritable:o,logger:l=console}){this.onStateChanged=new I,this._destroyed=!1,this.onDestroyed=new I,this._kMap=new WeakMap,this._lastValue=new Map,this.id=e,this._onSetState=s,this.getIsWritable=o,this._logger=l,this._state={},a&&$(a).forEach(d=>{const f=a[d];if(x(f)){const{k:_,v:m}=f;this._state[d]=m,p(m)&&this._kMap.set(m,_)}else this._state[d]=f})}get state(){return this._state}ensureState(e){return this.setState($(e).reduce((a,s)=>(T(this._state,s)||(a[s]=e[s]),a),{}))}setState(e){if(this._destroyed){this._logger.error(`Cannot call setState on Store ${this.id} which is destroyed.`);return}if(!this.getIsWritable()){this._logger.error(`Cannot setState on store ${this.id} without writable access`,e);return}const a=$(e);if(a.length>0){const s={};a.forEach(o=>{const l=e[o];if(l===void 0)this._lastValue.set(o,this._state[o]),delete this._state[o],s[o]=l;else if(l!==this._state[o])if(this._lastValue.set(o,this._state[o]),this._state[o]=l,p(l)){const d=j(l);this._kMap.set(d.v,d.k),s[o]=d}else s[o]=l}),Object.keys(s).length>0&&this._onSetState(s)}}get destroyed(){return this._destroyed}_destroy(){this._destroyed=!0,this.onDestroyed.dispatch()}_updateProperties(e){if(this._destroyed){this._logger.error(`Cannot call _updateProperties on Store ${this.id} which is destroyed.`);return}if(e.length>0){const a={};e.forEach(({key:s,value:o,kind:l})=>{switch(l){case 2:{T(this._state,s)&&(this._lastValue.set(s,this._state[s]),delete this._state[s]),a[s]={oldValue:this._lastValue.get(s)};break}default:{let d=o;if(x(o)){const{k:f,v:_}=o,m=this._state[s];p(m)&&this._kMap.get(m)===f?d=m:(d=_,p(_)&&this._kMap.set(_,f))}d!==this._state[s]&&(this._lastValue.set(s,this._state[s]),this._state[s]=d),a[s]={newValue:d,oldValue:this._lastValue.get(s)};break}}}),this.onStateChanged.dispatch(a)}}}class K{constructor(e,a,s,o,l){this.onRoomMembersChanged=new I,this.onMessage=new I,this.onWritableChanged=new I,this.onPageChanged=new I,this._stores=new Map,this.sideEffect=new v,this.postMessage=s,this.storeNSPrefix=e.storeConfig.nsPrefix,this.mainStoreId=e.storeConfig.mainId,this._storeRawData=e.store||{[this.getStoreNamespace(this.mainStoreId)]:{}},this._writable=e.writable,this._page=e.page,this._meta=e.meta,this._roomMembers=e.roomMembers,this.logger=l,this.sideEffect.add(()=>o(d=>{const{type:f,payload:_}=d;if(f){const m=`_handleMsg${f}`;this[m]&&this[m](_)}})),this._mainStore=this.connectStore(e.storeConfig.mainId,a),this.onStateChanged=this._mainStore.onStateChanged}get meta(){return this._meta}get roomMembers(){return this._roomMembers}_handleMsgRoomMembersChanged(e){if(e==null||Array.isArray(e)){const a=this._roomMembers;this._roomMembers=e,this.onRoomMembersChanged.dispatch({newValue:this._roomMembers,oldValue:a})}}moveCamera(e){this.postMessage({type:"MoveCamera",payload:e})}sendMessage(e){this.postMessage({type:"SendMagixMessage",payload:e})}_handleMsgReceiveMagixMessage(e){this.onMessage.dispatch(e)}get isWritable(){return this._writable}_handleMsgWritableChanged(e){const a=Boolean(e),s=this._writable;a!==s&&(this._writable=a,this.onWritableChanged.dispatch({oldValue:s,newValue:a}))}get page(){return this._page}setPage(e){this._page=e,this.postMessage({type:"SetPage",payload:e})}_handleMsgPageChanged(e){F(e)&&(this._page=e.newValue,this.onPageChanged.dispatch(e))}connectStore(e,a){const s=this.getStoreNamespace(e);let o=this._stores.get(s);if(!o){if(!T(this._storeRawData,s)){const l={};this.postMessage({type:"SetStore",payload:{[s]:l}}),this._storeRawData[s]=l}o=new H({id:e,state:this._storeRawData[s],logger:this.logger,getIsWritable:()=>this._writable,onSetState:l=>this.postMessage({type:"SetState",payload:{namespace:s,state:l}})}),this._stores.set(s,o)}return a&&o.ensureState(a),o}hasStore(e){return this._stores.has(this.getStoreNamespace(e))}removeStore(e){if(e===this.mainStoreId){this.logger.error(`Store "${e}" is not removable.`);return}const a=this.getStoreNamespace(e),s=this._stores.get(a);s&&(this._stores.delete(a),s._destroy()),this._storeRawData[a]&&this.postMessage({type:"SetStore",payload:{[a]:void 0}})}_handleMsgStoreChanged(e){Array.isArray(e)&&e.length>0&&e.forEach(({key:s,value:o,kind:l})=>{switch(l){case 2:{delete this._storeRawData[s];const d=this._stores.get(s);d&&(this._stores.delete(s),d._destroy());break}default:{this._storeRawData[s]=o;break}}})}getStoreNamespace(e){return this.storeNSPrefix+e}get state(){return this._mainStore.state}ensureState(e){return this._mainStore.ensureState(e)}setState(e){return this._mainStore.setState(e)}_handleMsgStateChanged(e){if(p(e)&&e.namespace&&Array.isArray(e.actions)&&e.actions.length>0){const{namespace:a,actions:s}=e;s.forEach(({key:l,value:d,kind:f})=>{switch(f){case 2:{const _=this._storeRawData[a];p(_)&&delete _[l];break}default:{const _=this._storeRawData[a];p(_)&&(_[l]=d);break}}});const o=this._stores.get(a);o&&o._updateProperties(s)}}destroy(){this.sideEffect.flushAll()}}let y;function X(c={}){if(!parent)throw new Error("[EmbeddedPageSDK]: SDK is not running in a iframe.");if(y)return Promise.resolve(y);const e=new O("EmbeddedPageSDK",c.debug),a=o=>{e.log("Message to parent",o),parent.postMessage(o,"*")},s=(o,l)=>{const d=({data:f,source:_})=>{if(!(!parent||_!==parent)){if(!p(f)){console.warn("window message data should be object, instead got",f);return}e.log("Message from parent",f),o(f)}};return window.addEventListener("message",d,l),()=>{window.removeEventListener("message",d,l)}};return a({type:"Init"}),new Promise(o=>{const l=s(d=>{if(y){l(),o(y);return}if(d.type==="Init"){l();const f=new K(d.payload,c.ensureState||{},a,s,e);y=f,o(f)}})})}return b.createEmbeddedApp=X,Object.defineProperty(b,"__esModule",{value:!0}),b[Symbol.toStringTag]="Module",b}({});})();
//# sourceMappingURL=main.iife.js.map

@@ -1,1 +0,17 @@

export declare function isObj(e: unknown): e is Record<string, any>;
import type { DiffOne } from "@netless/app-embedded-page";
export declare type RefValue<TValue> = {
k: string;
v: TValue;
__isRef: true;
};
export declare type ExtractRawValue<TValue> = TValue extends RefValue<infer RefValue> ? RefValue : TValue;
export declare type AutoRefValue<TValue> = RefValue<ExtractRawValue<TValue>>;
export declare type MaybeRefValue<TValue> = TValue | AutoRefValue<TValue>;
export declare const has: (o: unknown, k: string | number | symbol) => boolean;
export declare const plainObjectKeys: <T>(o: T) => Extract<keyof T, string>[];
export declare function isObj<T = Record<string, unknown>>(e: unknown): e is T;
export declare const isDiffOne: <T>(e: unknown) => e is DiffOne<T>;
export declare function isRef<TValue = unknown>(e: unknown): e is RefValue<TValue>;
export declare function makeRef<TValue>(v: TValue): RefValue<TValue>;
export declare function makeAutoRef<TValue>(v: TValue): AutoRefValue<TValue>;
export declare function genId(): string;
{
"name": "@netless/app-embedded-page-sdk",
"version": "0.0.3",
"version": "0.0.4",
"main": "dist/main.cjs.js",

@@ -5,0 +5,0 @@ "module": "dist/main.es.js",

@@ -119,2 +119,16 @@ ## @netless/app-embedded-page-sdk

- **app.moveCamera(partialCameraState)**
移动上层白板的视角。
**partialCameraState**
类型: `Partial<{ x: number, y: number, scale: number }>`
默认的视角状态是 `{ x: 0, y: 0, scale: 1 }`,与页面正中间对齐。
```js
app.moveCamera({ scale: 0.5 });
```
- **app.onStateChanged**

@@ -152,3 +166,3 @@

app.onWritableChanged.addListener(diff => {
console.log("现在是否可写", app.writable);
console.log("现在是否可写", app.isWritable);
});

@@ -155,0 +169,0 @@ ```

## @netless/app-embedded-page-sdk
SDK for storing shared replayable states and sending/receiving replayable events inside [@netless/app-embedded-page](https://github.com/netless-io/netless-app/tree/master/packages/app-embedded-page).
SDK for storing shared replayable states and sending/receiving replayable events inside [`@netless/app-embedded-page`](https://github.com/netless-io/netless-app/tree/master/packages/app-embedded-page).

@@ -122,2 +122,16 @@ [中文](./README-zh.md)

- **app.moveCamera(partialCameraState)**
Change the whiteboard scene's position on top of your page.
**partialCameraState**
Type: `Partial<{ x: number, y: number, scale: number }>`
The default camera state is `{ x: 0, y: 0, scale: 1 }`, at the center of your page.
```js
app.moveCamera({ scale: 0.5 });
```
- **app.onStateChanged**

@@ -155,3 +169,3 @@

app.onWritableChanged.addListener(diff => {
console.log("my writable becomes", app.writable);
console.log("my writable becomes", app.isWritable);
});

@@ -158,0 +172,0 @@ ```

/* eslint-disable @typescript-eslint/no-explicit-any */
import type { ReceiveMessages, SendMessages, DiffOne, InitData } from "@netless/app-embedded-page";
import { SideEffectManager } from "side-effect-manager";
import type {
FromSDKMessage,
ToSDKMessage,
ToSDKMessageKey,
DefaultState,
FromSDKMessageKey,
} from "@netless/app-embedded-page";
import type { LoggerDebugLevel } from "@netless/app-shared";
import { Logger } from "@netless/app-shared";
import { EmbeddedApp } from "./EmbeddedApp";
import type { MaybeRefValue } from "./utils";
import { isObj } from "./utils";
type CheckSendMessageType<T extends { type: keyof ReceiveMessages }> = T;
export type SendMessage<State = any, Message = any> = CheckSendMessageType<
| { type: "GetState" }
| { type: "SetState"; payload: Partial<State> }
| { type: "SendMessage"; payload: Message }
| { type: "GetPage" }
| { type: "SetPage"; payload: string }
| { type: "GetWritable" }
>;
export type Diff<State> = State extends Record<infer K, unknown>
? Record<K, DiffOne<State[K]>>
: never;
type CheckIncomingMessageType<T extends { type: keyof SendMessages }> = T;
export type IncomingMessage<State = any, Message = any> = CheckIncomingMessageType<
| { type: "Init"; payload: InitData }
| { type: "GetState"; payload: State }
| { type: "StateChanged"; payload: Diff<State> }
| { type: "ReceiveMessage"; payload: Message }
| { type: "GetPage"; payload: string | undefined }
| { type: "PageChanged"; payload: DiffOne<string> }
| { type: "GetWritable"; payload: boolean }
| { type: "WritableChanged"; payload: DiffOne<boolean> }
>;
export type Listener<T> = (event: T) => void;
export interface Emitter<T> {
dispatch(event: T): void;
addListener(listener: Listener<T>): void;
removeListener(listener: Listener<T>): void;
export interface EmbeddedAppConfig<TState> {
ensureState: TState;
debug?: LoggerDebugLevel;
}
function createEmitter<T>(): Emitter<T> {
const listeners = new Set<Listener<T>>();
let singleApp: EmbeddedApp<any, any> | undefined;
const dispatch = (event: T) => listeners.forEach(f => f(event));
const addListener = (listener: Listener<T>) => listeners.add(listener);
const removeListener = (listener: Listener<T>) => listeners.delete(listener);
return { dispatch, addListener, removeListener };
}
export interface EmbeddedApp<State = Record<string, any>, Message = any> {
readonly state: Readonly<State>;
readonly page?: string;
readonly isWritable: boolean;
readonly meta: Readonly<InitData["meta"]>;
ensureState(partialState: Partial<State>): void;
setState(partialState: Partial<State>): void;
setPage(page: string): void;
sendMessage(message: Message): void;
destroy(): void;
onStateChanged: Emitter<Diff<State>>;
onPageChanged: Emitter<DiffOne<string>>;
onWritableChanged: Emitter<DiffOne<boolean>>;
onMessage: Emitter<Message>;
}
/**

@@ -76,137 +31,79 @@ * @example

*/
export function createEmbeddedApp<State = Record<string, any>, Message = any>(
callback?: (app: EmbeddedApp<State, Message>) => void
): Promise<EmbeddedApp<State, Message>> {
let state: State;
let page: string | undefined;
let writable = false;
let meta: Readonly<InitData["meta"]>;
export function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(): Promise<
EmbeddedApp<TState | Record<string, unknown>, TMessage>
>;
export function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(
config: EmbeddedAppConfig<TState>
): Promise<EmbeddedApp<TState, TMessage>>;
export function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(
config: Partial<EmbeddedAppConfig<TState>>
): Promise<EmbeddedApp<TState | Record<string, unknown>, TMessage>>;
export function createEmbeddedApp<TState = DefaultState, TMessage = unknown>(
config: Partial<EmbeddedAppConfig<TState>> = {}
): Promise<EmbeddedApp<TState | Record<string, unknown>, TMessage>> {
if (!parent) {
throw new Error("[EmbeddedPageSDK]: SDK is not running in a iframe.");
}
const onInit = createEmitter<InitData>();
const onMessage = createEmitter<Message>();
if (singleApp) {
return Promise.resolve(singleApp);
}
const onStateChanged = createEmitter<Diff<State>>();
const onPageChanged = createEmitter<DiffOne<string>>();
const onWritableChanged = createEmitter<DiffOne<boolean>>();
const logger = new Logger("EmbeddedPageSDK", config.debug);
const sideEffectManager = new SideEffectManager();
let onStateChangedPayload: Diff<State> | undefined;
let onPageChangedPayload: DiffOne<string> | undefined;
let onWritableChangedPayload: DiffOne<boolean> | undefined;
function postMessage(message: SendMessage) {
const postMessage = <S = TState, TType extends FromSDKMessageKey = FromSDKMessageKey>(
message: FromSDKMessage<TType, { [K in keyof S]: MaybeRefValue<S[K]> }, TMessage>
): void => {
logger.log("Message to parent", message);
parent.postMessage(message, "*");
}
sideEffectManager.addEventListener(window, "message", e => {
if (!isObj(e.data)) {
console.warn("window message data should be object, instead got", e.data);
return;
}
const event = e.data as IncomingMessage<State, Message>;
if (event.type === "Init") {
const { payload } = event;
state = payload.state as unknown as State;
page = payload.page;
writable = payload.writable;
meta = payload.meta;
onInit.dispatch(payload);
} else if (event.type === "ReceiveMessage") {
onMessage.dispatch(event.payload);
} else {
if (event.type === "StateChanged") {
onStateChangedPayload = event.payload;
postMessage({ type: "GetState" });
} else if (event.type === "GetState") {
state = event.payload;
if (onStateChangedPayload) {
onStateChanged.dispatch(onStateChangedPayload);
onStateChangedPayload = void 0;
}
}
if (event.type === "PageChanged") {
onPageChangedPayload = event.payload;
postMessage({ type: "GetPage" });
} else if (event.type === "GetPage") {
page = event.payload;
if (onPageChangedPayload) {
onPageChanged.dispatch(onPageChangedPayload);
onPageChangedPayload = void 0;
}
}
if (event.type === "WritableChanged") {
onWritableChangedPayload = event.payload;
postMessage({ type: "GetWritable" });
} else if (event.type === "GetWritable") {
writable = event.payload;
if (onWritableChangedPayload) {
onWritableChanged.dispatch(onWritableChangedPayload);
onWritableChangedPayload = void 0;
}
}
}
});
const ensureState = (initialState: Partial<State>) => {
state = { ...initialState, ...state };
};
const setState = (newState: Partial<State>) => {
for (const [key, value] of Object.entries(newState)) {
if (value === void 0) {
delete state[key as keyof State];
} else {
state[key as keyof State] = value as State[keyof State];
const addMessageListener = (
listener: (message: ToSDKMessage<ToSDKMessageKey, TState, TMessage>) => any,
options?: boolean | AddEventListenerOptions
): (() => void) => {
const handler = ({
data,
source,
}: MessageEvent<ToSDKMessage<ToSDKMessageKey, TState, TMessage>>) => {
if (!parent || source !== parent) return;
if (!isObj(data)) {
console.warn("window message data should be object, instead got", data);
return;
}
}
postMessage({ type: "SetState", payload: newState });
};
logger.log("Message from parent", data);
listener(data);
};
const setPage = (newPage: string) => {
page = newPage;
postMessage({ type: "SetPage", payload: newPage });
};
window.addEventListener("message", handler, options);
const sendMessage = (payload: Message) => {
postMessage({ type: "SendMessage", payload });
return () => {
window.removeEventListener("message", handler, options);
};
};
const destroy = () => sideEffectManager.flushAll();
postMessage({ type: "Init" });
const app: EmbeddedApp<State, Message> = {
get state() {
return state;
},
get page() {
return page;
},
get isWritable() {
return writable;
},
get meta() {
return meta;
},
ensureState,
setState,
setPage,
sendMessage,
destroy,
onStateChanged,
onPageChanged,
onWritableChanged,
onMessage,
};
return new Promise(resolve => {
const disposer = addMessageListener(message => {
if (singleApp) {
disposer();
resolve(singleApp);
return;
}
return new Promise(resolve => {
const handler = () => {
onInit.removeListener(handler);
callback?.(app);
resolve(app);
};
onInit.addListener(handler);
if (message.type === "Init") {
disposer();
const app = new EmbeddedApp<TState | Record<string, unknown>, TMessage>(
message.payload,
config.ensureState || {},
postMessage,
addMessageListener,
logger
);
singleApp = app;
resolve(app);
}
});
});
}

@@ -1,5 +0,36 @@

/* eslint-disable @typescript-eslint/no-explicit-any */
import type { DiffOne } from "@netless/app-embedded-page";
export function isObj(e: unknown): e is Record<string, any> {
export type RefValue<TValue> = { k: string; v: TValue; __isRef: true };
export type ExtractRawValue<TValue> = TValue extends RefValue<infer RefValue> ? RefValue : TValue;
export type AutoRefValue<TValue> = RefValue<ExtractRawValue<TValue>>;
export type MaybeRefValue<TValue> = TValue | AutoRefValue<TValue>;
export const has = (o: unknown, k: string | number | symbol): boolean =>
Object.prototype.hasOwnProperty.call(o, k);
export const plainObjectKeys = Object.keys as <T>(o: T) => Array<Extract<keyof T, string>>;
export function isObj<T = Record<string, unknown>>(e: unknown): e is T {
return typeof e === "object" && e !== null;
}
export const isDiffOne = isObj as <T>(e: unknown) => e is DiffOne<T>;
export function isRef<TValue = unknown>(e: unknown): e is RefValue<TValue> {
return Boolean(isObj(e) && e.__isRef);
}
export function makeRef<TValue>(v: TValue): RefValue<TValue> {
return { k: genId(), v, __isRef: true };
}
export function makeAutoRef<TValue>(v: TValue): AutoRefValue<TValue> {
return isRef<ExtractRawValue<TValue>>(v) ? v : makeRef(v as ExtractRawValue<TValue>);
}
export function genId(): string {
return Date.now().toString().slice(6) + Math.random().toString().slice(2, 8);
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc