LSPlugin.caller.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 = (typeof vw === 'number') ?
  196. `${Math.min(left * 100 / vw, 99)}%` : `${left}px`
  197. // 45 is height of headbar
  198. top = Math.max(top, 45)
  199. top = (typeof vh === 'number') ?
  200. `${Math.min(top * 100 / vh, 99)}%` : `${top}px`
  201. Object.assign(cnt.style, {
  202. width: width + 'px',
  203. height: height + 'px',
  204. left, top
  205. })
  206. }
  207. } catch (e) {
  208. console.error('[Restore Layout Error]', e)
  209. }
  210. document.body.appendChild(cnt)
  211. const pt = new Postmate({
  212. id: id + '_iframe',
  213. container: cnt,
  214. url: url.href,
  215. classListArray: ['lsp-iframe-sandbox'],
  216. model: { baseInfo: JSON.parse(JSON.stringify(pl.toJSON())) },
  217. })
  218. let handshake = pt.sendHandshake()
  219. this._status = 'pending'
  220. // timeout for handshake
  221. let timer
  222. return new Promise((resolve, reject) => {
  223. timer = setTimeout(() => {
  224. reject(new Error(`handshake Timeout`))
  225. pt.destroy()
  226. }, 4 * 1000) // 4 secs
  227. handshake
  228. .then((refChild: ParentAPI) => {
  229. this._parent = refChild
  230. this._connected = true
  231. this.emit('connected')
  232. refChild.on(LSPMSGFn(pl.id), ({ type, payload }: any) => {
  233. debug(`[user -> *host] `, type, payload)
  234. this._pluginLocal?.emit(type, payload || {})
  235. this._pluginLocal?.caller.emit(type, payload || {})
  236. })
  237. this._call = async (...args: any) => {
  238. // parent all will get message before handshake
  239. await refChild.call(LSPMSGFn(pl.id), {
  240. type: args[0],
  241. payload: Object.assign(args[1] || {}, {
  242. $$pid: pl.id,
  243. }),
  244. })
  245. }
  246. this._callUserModel = async (type, ...payloads: any[]) => {
  247. if (type.startsWith(FLAG_AWAIT)) {
  248. return await refChild.get(
  249. type.replace(FLAG_AWAIT, ''),
  250. ...payloads
  251. )
  252. } else {
  253. refChild.call(type, payloads?.[0])
  254. }
  255. }
  256. resolve(null)
  257. })
  258. .catch((e) => {
  259. reject(e)
  260. })
  261. .finally(() => {
  262. clearTimeout(timer)
  263. })
  264. })
  265. .catch((e) => {
  266. debug('[iframe sandbox] error', e)
  267. throw e
  268. })
  269. .finally(() => {
  270. this._status = undefined
  271. })
  272. }
  273. async _setupShadowSandbox() {
  274. const pl = this._pluginLocal!
  275. const shadow = (this._shadow = new LSPluginShadowFrame(pl))
  276. try {
  277. this._status = 'pending'
  278. await shadow.load()
  279. this._connected = true
  280. this.emit('connected')
  281. this._call = async (type, payload = {}, actor) => {
  282. actor && (payload.actor = actor)
  283. // @ts-ignore Call in same thread
  284. this._pluginLocal?.emit(
  285. type,
  286. Object.assign(payload, {
  287. $$pid: pl.id,
  288. })
  289. )
  290. return actor?.promise
  291. }
  292. this._callUserModel = async (...args: any) => {
  293. let type = args[0] as string
  294. if (type?.startsWith(FLAG_AWAIT)) {
  295. type = type.replace(FLAG_AWAIT, '')
  296. }
  297. const payload = args[1] || {}
  298. const fn = this._userModel[type]
  299. if (typeof fn === 'function') {
  300. await fn.call(null, payload)
  301. }
  302. }
  303. } catch (e) {
  304. debug('[shadow sandbox] error', e)
  305. throw e
  306. } finally {
  307. this._status = undefined
  308. }
  309. }
  310. _extendUserModel(model: any) {
  311. return Object.assign(this._userModel, model)
  312. }
  313. _getSandboxIframeContainer() {
  314. return this._parent?.frame.parentNode as HTMLDivElement
  315. }
  316. _getSandboxShadowContainer() {
  317. return this._shadow?.frame.parentNode as HTMLDivElement
  318. }
  319. _getSandboxIframeRoot() {
  320. return this._parent?.frame
  321. }
  322. _getSandboxShadowRoot() {
  323. return this._shadow?.frame
  324. }
  325. set debugTag(value: string) {
  326. this._debugTag = value
  327. }
  328. async destroy() {
  329. let root: HTMLElement = null
  330. if (this._parent) {
  331. root = this._getSandboxIframeContainer()
  332. await this._parent.destroy()
  333. }
  334. if (this._shadow) {
  335. root = this._getSandboxShadowContainer()
  336. this._shadow.destroy()
  337. }
  338. root?.parentNode.removeChild(root)
  339. }
  340. }
  341. export { LSPluginCaller }