LSPlugin.caller.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import Debug from 'debug'
  2. import { Postmate, Model, ParentAPI, ChildAPI } from './postmate'
  3. import EventEmitter from 'eventemitter3'
  4. import { PluginLocal } from './LSPlugin.core'
  5. import { deferred, IS_DEV } from './helpers'
  6. import { LSPluginShadowFrame } from './LSPlugin.shadow'
  7. const debug = Debug('LSPlugin:caller')
  8. type DeferredActor = ReturnType<typeof deferred>
  9. export const FLAG_AWAIT = '#await#response#'
  10. export const LSPMSG = '#lspmsg#'
  11. export const LSPMSG_ERROR_TAG = '#lspmsg#error#'
  12. export const LSPMSG_SETTINGS = '#lspmsg#settings#'
  13. export const LSPMSG_BEFORE_UNLOAD = '#lspmsg#beforeunload#'
  14. export const LSPMSG_SYNC = '#lspmsg#reply#'
  15. export const LSPMSG_READY = '#lspmsg#ready#'
  16. export const LSPMSGFn = (id: string) => `${LSPMSG}${id}`
  17. export const AWAIT_LSPMSGFn = (id: string) => `${FLAG_AWAIT}${id}`
  18. /**
  19. * Call between core and user
  20. */
  21. class LSPluginCaller extends EventEmitter {
  22. private _connected: boolean = false
  23. private _parent?: ParentAPI
  24. private _child?: ChildAPI
  25. private _shadow?: LSPluginShadowFrame
  26. private _status?: 'pending' | 'timeout'
  27. private _userModel: any = {}
  28. private _call?: (
  29. type: string,
  30. payload: any,
  31. actor?: DeferredActor
  32. ) => Promise<any>
  33. private _callUserModel?: (type: string, ...payloads: any[]) => Promise<any>
  34. private _debugTag = ''
  35. constructor(private _pluginLocal: PluginLocal | null) {
  36. super()
  37. if (_pluginLocal) {
  38. this._debugTag = _pluginLocal.debugTag
  39. }
  40. }
  41. async connectToChild() {
  42. if (this._connected) return
  43. const { shadow } = this._pluginLocal!
  44. if (shadow) {
  45. await this._setupShadowSandbox()
  46. } else {
  47. await this._setupIframeSandbox()
  48. }
  49. }
  50. // run in sandbox
  51. async connectToParent(userModel = {}) {
  52. if (this._connected) return
  53. const caller = this
  54. const isShadowMode = this._pluginLocal != null
  55. let syncGCTimer: any = 0
  56. let syncTag = 0
  57. const syncActors = new Map<number, DeferredActor>()
  58. const readyDeferred = deferred(1000 * 60)
  59. const model: any = this._extendUserModel({
  60. [LSPMSG_READY]: async (baseInfo) => {
  61. // dynamically setup common msg handler
  62. model[LSPMSGFn(baseInfo?.pid)] = ({
  63. type,
  64. payload,
  65. }: {
  66. type: string
  67. payload: any
  68. }) => {
  69. debug(`[host (_call) -> *user] ${this._debugTag}`, type, payload)
  70. // host._call without async
  71. caller.emit(type, payload)
  72. }
  73. await readyDeferred.resolve()
  74. },
  75. [LSPMSG_BEFORE_UNLOAD]: async (e) => {
  76. const actor = deferred(10 * 1000)
  77. caller.emit('beforeunload', Object.assign({ actor }, e))
  78. await actor.promise
  79. },
  80. [LSPMSG_SETTINGS]: async ({ type, payload }) => {
  81. caller.emit('settings:changed', payload)
  82. },
  83. [LSPMSG]: async ({ ns, type, payload }: any) => {
  84. debug(
  85. `[host (async) -> *user] ${this._debugTag} ns=${ns} type=${type}`,
  86. payload
  87. )
  88. if (ns && ns.startsWith('hook')) {
  89. caller.emit(`${ns}:${type}`, payload)
  90. return
  91. }
  92. caller.emit(type, payload)
  93. },
  94. [LSPMSG_SYNC]: ({ _sync, result }: any) => {
  95. debug(`[sync host -> *user] #${_sync}`, result)
  96. if (syncActors.has(_sync)) {
  97. const actor = syncActors.get(_sync)
  98. if (actor) {
  99. if (result?.hasOwnProperty(LSPMSG_ERROR_TAG)) {
  100. actor.reject(result[LSPMSG_ERROR_TAG])
  101. } else {
  102. actor.resolve(result)
  103. }
  104. syncActors.delete(_sync)
  105. }
  106. }
  107. },
  108. ...userModel,
  109. })
  110. if (isShadowMode) {
  111. await readyDeferred.promise
  112. return JSON.parse(JSON.stringify(this._pluginLocal?.toJSON()))
  113. }
  114. const pm = new Model(model)
  115. const handshake = pm.sendHandshakeReply()
  116. this._status = 'pending'
  117. await handshake
  118. .then((refParent: ChildAPI) => {
  119. this._child = refParent
  120. this._connected = true
  121. this._call = async (type, payload = {}, actor) => {
  122. if (actor) {
  123. const tag = ++syncTag
  124. syncActors.set(tag, actor)
  125. payload._sync = tag
  126. actor.setTag(`async call #${tag}`)
  127. debug(`async call #${tag}`)
  128. }
  129. refParent.emit(LSPMSGFn(model.baseInfo.id), { type, payload })
  130. return actor?.promise as Promise<any>
  131. }
  132. this._callUserModel = async (type, payload) => {
  133. try {
  134. model[type](payload)
  135. } catch (e) {
  136. debug(`[model method] #${type} not existed`)
  137. }
  138. }
  139. // actors GC
  140. syncGCTimer = setInterval(() => {
  141. if (syncActors.size > 100) {
  142. for (const [k, v] of syncActors) {
  143. if (v.settled) {
  144. syncActors.delete(k)
  145. }
  146. }
  147. }
  148. }, 1000 * 60 * 30)
  149. })
  150. .finally(() => {
  151. this._status = undefined
  152. })
  153. await readyDeferred.promise
  154. return model.baseInfo
  155. }
  156. async call(type: any, payload: any = {}) {
  157. return this._call?.call(this, type, payload)
  158. }
  159. // only for callable apis for sdk user
  160. async callAsync(type: any, payload: any = {}) {
  161. const actor = deferred(1000 * 10)
  162. return this._call?.call(this, type, payload, actor)
  163. }
  164. async callUserModel(type: string, ...args: any[]) {
  165. return this._callUserModel?.apply(this, [type, ...args])
  166. }
  167. async callUserModelAsync(type: string, ...args: any[]) {
  168. type = AWAIT_LSPMSGFn(type)
  169. return this._callUserModel?.apply(this, [type, ...args])
  170. }
  171. // run in host
  172. async _setupIframeSandbox() {
  173. const pl = this._pluginLocal!
  174. const id = pl.id
  175. const domId = `${id}_lsp_main`
  176. const url = new URL(pl.options.entry!)
  177. url.searchParams.set(
  178. `__v__`,
  179. IS_DEV ? Date.now().toString() : pl.options.version
  180. )
  181. // clear zombie sandbox
  182. const zb = document.querySelector(`#${domId}`)
  183. if (zb) zb.parentElement.removeChild(zb)
  184. const cnt = document.createElement('div')
  185. cnt.classList.add('lsp-iframe-sandbox-container')
  186. cnt.id = domId
  187. cnt.dataset.pid = id
  188. // TODO: apply any container layout data
  189. try {
  190. const mainLayoutInfo = (await this._pluginLocal._loadLayoutsData())?.$$0
  191. if (mainLayoutInfo) {
  192. cnt.dataset.inited_layout = 'true'
  193. let { width, height, left, top, vw, vh } = mainLayoutInfo
  194. left = Math.max(left, 0)
  195. left =
  196. typeof vw === 'number'
  197. ? `${Math.min((left * 100) / vw, 99)}%`
  198. : `${left}px`
  199. // 45 is height of headbar
  200. top = Math.max(top, 45)
  201. top =
  202. typeof vh === 'number'
  203. ? `${Math.min((top * 100) / vh, 99)}%`
  204. : `${top}px`
  205. Object.assign(cnt.style, {
  206. width: width + 'px',
  207. height: height + 'px',
  208. left,
  209. top,
  210. })
  211. }
  212. } catch (e) {
  213. console.error('[Restore Layout Error]', e)
  214. }
  215. document.body.appendChild(cnt)
  216. const pt = new Postmate({
  217. id: id + '_iframe',
  218. container: cnt,
  219. url: url.href,
  220. classListArray: ['lsp-iframe-sandbox'],
  221. model: { baseInfo: JSON.parse(JSON.stringify(pl.toJSON())) },
  222. })
  223. let handshake = pt.sendHandshake()
  224. this._status = 'pending'
  225. // timeout for handshake
  226. let timer
  227. return new Promise((resolve, reject) => {
  228. timer = setTimeout(() => {
  229. reject(new Error(`handshake Timeout`))
  230. pt.destroy()
  231. }, 8 * 1000) // 8 secs
  232. handshake
  233. .then((refChild: ParentAPI) => {
  234. this._parent = refChild
  235. this._connected = true
  236. this.emit('connected')
  237. refChild.on(LSPMSGFn(pl.id), ({ type, payload }: any) => {
  238. debug(`[user -> *host] `, type, payload)
  239. this._pluginLocal?.emit(type, payload || {})
  240. this._pluginLocal?.caller.emit(type, payload || {})
  241. })
  242. this._call = async (...args: any) => {
  243. // parent all will get message before handshake
  244. await refChild.call(LSPMSGFn(pl.id), {
  245. type: args[0],
  246. payload: Object.assign(args[1] || {}, {
  247. $$pid: pl.id,
  248. }),
  249. })
  250. }
  251. this._callUserModel = async (type, ...payloads: any[]) => {
  252. if (type.startsWith(FLAG_AWAIT)) {
  253. return await refChild.get(
  254. type.replace(FLAG_AWAIT, ''),
  255. ...payloads
  256. )
  257. } else {
  258. refChild.call(type, payloads?.[0])
  259. }
  260. }
  261. resolve(null)
  262. })
  263. .catch((e) => {
  264. reject(e)
  265. })
  266. .finally(() => {
  267. clearTimeout(timer)
  268. })
  269. })
  270. .catch((e) => {
  271. debug('[iframe sandbox] error', e)
  272. throw e
  273. })
  274. .finally(() => {
  275. this._status = undefined
  276. })
  277. }
  278. async _setupShadowSandbox() {
  279. const pl = this._pluginLocal!
  280. const shadow = (this._shadow = new LSPluginShadowFrame(pl))
  281. try {
  282. this._status = 'pending'
  283. await shadow.load()
  284. this._connected = true
  285. this.emit('connected')
  286. this._call = async (type, payload = {}, actor) => {
  287. actor && (payload.actor = actor)
  288. // @ts-ignore Call in same thread
  289. this._pluginLocal?.emit(
  290. type,
  291. Object.assign(payload, {
  292. $$pid: pl.id,
  293. })
  294. )
  295. return actor?.promise
  296. }
  297. this._callUserModel = async (...args: any) => {
  298. let type = args[0] as string
  299. if (type?.startsWith(FLAG_AWAIT)) {
  300. type = type.replace(FLAG_AWAIT, '')
  301. }
  302. const payload = args[1] || {}
  303. const fn = this._userModel[type]
  304. if (typeof fn === 'function') {
  305. await fn.call(null, payload)
  306. }
  307. }
  308. } catch (e) {
  309. debug('[shadow sandbox] error', e)
  310. throw e
  311. } finally {
  312. this._status = undefined
  313. }
  314. }
  315. _extendUserModel(model: any) {
  316. return Object.assign(this._userModel, model)
  317. }
  318. _getSandboxIframeContainer() {
  319. return this._parent?.frame.parentNode as HTMLDivElement
  320. }
  321. _getSandboxShadowContainer() {
  322. return this._shadow?.frame.parentNode as HTMLDivElement
  323. }
  324. _getSandboxIframeRoot() {
  325. return this._parent?.frame
  326. }
  327. _getSandboxShadowRoot() {
  328. return this._shadow?.frame
  329. }
  330. set debugTag(value: string) {
  331. this._debugTag = value
  332. }
  333. async destroy() {
  334. let root: HTMLElement = null
  335. if (this._parent) {
  336. root = this._getSandboxIframeContainer()
  337. await this._parent.destroy()
  338. }
  339. if (this._shadow) {
  340. root = this._getSandboxShadowContainer()
  341. this._shadow.destroy()
  342. }
  343. root?.parentNode.removeChild(root)
  344. }
  345. }
  346. export { LSPluginCaller }