"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
0 && (module.exports = {
    useWebsocket: null,
    useSendMessage: null,
    useWebsocketPing: null
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    useWebsocket: function() {
        return useWebsocket;
    },
    useSendMessage: function() {
        return useSendMessage;
    },
    useWebsocketPing: function() {
        return useWebsocketPing;
    }
});
const _react = require("react");
const _approutercontext = require("../../../../../shared/lib/app-router-context");
const _getsocketprotocol = require("./get-socket-protocol");
function useWebsocket(assetPrefix, shouldSubscribe) {
    if (shouldSubscribe === void 0) shouldSubscribe = true;
    const webSocketRef = (0, _react.useRef)();
    (0, _react.useEffect)(()=>{
        if (webSocketRef.current || !shouldSubscribe) {
            return;
        }
        const { hostname , port  } = window.location;
        const protocol = (0, _getsocketprotocol.getSocketProtocol)(assetPrefix);
        const normalizedAssetPrefix = assetPrefix.replace(/^\/+/, "");
        let url = protocol + "://" + hostname + ":" + port + (normalizedAssetPrefix ? "/" + normalizedAssetPrefix : "");
        if (normalizedAssetPrefix.startsWith("http")) {
            url = protocol + "://" + normalizedAssetPrefix.split("://")[1];
        }
        webSocketRef.current = new window.WebSocket("" + url + "/_next/webpack-hmr");
    }, [
        assetPrefix,
        shouldSubscribe
    ]);
    return webSocketRef;
}
function useSendMessage(webSocketRef) {
    const sendMessage = (0, _react.useCallback)((data)=>{
        const socket = webSocketRef.current;
        if (!socket || socket.readyState !== socket.OPEN) {
            return;
        }
        return socket.send(data);
    }, [
        webSocketRef
    ]);
    return sendMessage;
}
function useWebsocketPing(websocketRef) {
    const sendMessage = useSendMessage(websocketRef);
    const { tree  } = (0, _react.useContext)(_approutercontext.GlobalLayoutRouterContext);
    (0, _react.useEffect)(()=>{
        // Taken from on-demand-entries-client.js
        const interval = setInterval(()=>{
            sendMessage(JSON.stringify({
                event: "ping",
                tree,
                appDirRoute: true
            }));
        }, 2500);
        return ()=>clearInterval(interval);
    }, [
        tree,
        sendMessage
    ]);
}

if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
  Object.defineProperty(exports.default, '__esModule', { value: true });
  Object.assign(exports.default, exports);
  module.exports = exports.default;
}

//# sourceMappingURL=use-websocket.js.map