1- import './WebSocketPolyfill.ts' ;
2- import { connectWebSocket , WebSocket } from 'https://deno.land/std/ws/mod.ts' ;
31import {
42 serializeStructure ,
53 deserializeStructure ,
@@ -18,43 +16,39 @@ let ports = new Map<number | string, MessagePortData>();
1816init ( ) ;
1917
2018async function init ( ) {
21- const socket = await connectWebSocket ( address ) ;
19+ const socket = new WebSocket ( address ) ;
2220
2321 let onMessage = patchGlobalThis ( ( json ) => socket . send ( json ) ) ;
2422
25- const messages = async ( ) : Promise < void > => {
26- for await ( const message of socket ) {
27- if ( typeof message === 'string' ) {
28- onMessage ( message ) ;
29- }
30- }
23+ socket . onmessage = ( message ) => {
24+ onMessage ( message . data ) ;
3125 } ;
32-
33- messages ( ) . catch ( ( err ) => {
26+ socket . onerror = ( err ) => {
3427 console . error ( err ) ;
35- if ( ! socket . isClosed ) {
28+ if ( socket . readyState !== WebSocket . CLOSED ) {
3629 socket . close ( ) ;
3730 }
38- } ) ;
39-
40- sendMessage (
41- {
42- type : 'init' ,
43- } ,
44- socket
45- ) ;
46-
47- if ( scriptType === 'script' ) {
48- Function ( script ) ( ) ;
49- } else if ( scriptType === 'import' ) {
50- import ( script ) ;
51- } else {
52- throw new Error ( 'Unsupported scrypt type: ' + scriptType ) ;
53- }
31+ } ;
32+ socket . onopen = ( ) => {
33+ sendMessage (
34+ {
35+ type : 'init' ,
36+ } ,
37+ socket
38+ ) ;
39+
40+ if ( scriptType === 'script' ) {
41+ Function ( script ) ( ) ;
42+ } else if ( scriptType === 'import' ) {
43+ import ( script ) ;
44+ } else {
45+ throw new Error ( 'Unsupported scrypt type: ' + scriptType ) ;
46+ }
47+ } ;
5448}
5549
5650async function sendMessage ( message : any , socket : WebSocket ) {
57- if ( socket . isClosed ) {
51+ if ( socket . readyState !== WebSocket . OPEN ) {
5852 return ;
5953 }
6054 const structured = serializeStructure ( message ) ;
0 commit comments