"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.hydrate = hydrate;
exports.version = void 0;
require("../build/polyfills/polyfill-module");
var _client = _interopRequireDefault(require("react-dom/client"));
var _react = _interopRequireDefault(require("react"));
var _reactServerDomWebpack = require("next/dist/compiled/react-server-dom-webpack");
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _asyncToGenerator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
// eslint-disable-next-line no-undef
const getChunkScriptFilename = __webpack_require__.u;
const chunkFilenameMap = {};
// eslint-disable-next-line no-undef
__webpack_require__.u = (chunkId)=>{
    return chunkFilenameMap[chunkId] || getChunkScriptFilename(chunkId);
};
// Ignore the module ID transform in client.
// eslint-disable-next-line no-undef
// @ts-expect-error TODO: fix type
self.__next_require__ = __webpack_require__;
self.__next_chunk_load__ = (chunk)=>{
    if (!chunk) return Promise.resolve();
    if (chunk.endsWith('.css')) {
        const existingTag = document.querySelector(`link[href="${chunk}"]`);
        if (!existingTag) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = '/_next/' + chunk;
            document.head.appendChild(link);
        }
        return Promise.resolve();
    }
    const [chunkId, chunkFileName] = chunk.split(':');
    chunkFilenameMap[chunkId] = `static/chunks/${chunkFileName}.js`;
    // @ts-ignore
    // eslint-disable-next-line no-undef
    return __webpack_chunk_load__(chunkId);
};
const version = "12.2.3-canary.4";
exports.version = version;
const appElement = document;
let reactRoot = null;
function renderReactElement(domEl, fn) {
    const reactEl = fn();
    if (!reactRoot) {
        // Unlike with createRoot, you don't need a separate root.render() call here
        reactRoot = _client.default.hydrateRoot(domEl, reactEl);
    } else {
        reactRoot.render(reactEl);
    }
}
const getCacheKey = ()=>{
    const { pathname , search  } = location;
    return pathname + search;
};
const encoder = new TextEncoder();
const loadedCss = new Set();
let initialServerDataBuffer = undefined;
let initialServerDataWriter = undefined;
let initialServerDataLoaded = false;
let initialServerDataFlushed = false;
function nextServerDataCallback(seg) {
    if (seg[0] === 0) {
        initialServerDataBuffer = [];
    } else {
        if (!initialServerDataBuffer) throw new Error('Unexpected server data: missing bootstrap script.');
        if (initialServerDataWriter) {
            initialServerDataWriter.enqueue(encoder.encode(seg[2]));
        } else {
            initialServerDataBuffer.push(seg[2]);
        }
    }
}
// There might be race conditions between `nextServerDataRegisterWriter` and
// `DOMContentLoaded`. The former will be called when React starts to hydrate
// the root, the latter will be called when the DOM is fully loaded.
// For streaming, the former is called first due to partial hydration.
// For non-streaming, the latter can be called first.
// Hence, we use two variables `initialServerDataLoaded` and
// `initialServerDataFlushed` to make sure the writer will be closed and
// `initialServerDataBuffer` will be cleared in the right time.
function nextServerDataRegisterWriter(ctr) {
    if (initialServerDataBuffer) {
        initialServerDataBuffer.forEach((val)=>{
            ctr.enqueue(encoder.encode(val));
        });
        if (initialServerDataLoaded && !initialServerDataFlushed) {
            ctr.close();
            initialServerDataFlushed = true;
            initialServerDataBuffer = undefined;
        }
    }
    initialServerDataWriter = ctr;
}
// When `DOMContentLoaded`, we can close all pending writers to finish hydration.
const DOMContentLoaded = function() {
    if (initialServerDataWriter && !initialServerDataFlushed) {
        initialServerDataWriter.close();
        initialServerDataFlushed = true;
        initialServerDataBuffer = undefined;
    }
    initialServerDataLoaded = true;
};
// It's possible that the DOM is already loaded.
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
} else {
    DOMContentLoaded();
}
const nextServerDataLoadingGlobal = self.__next_s = self.__next_s || [];
nextServerDataLoadingGlobal.forEach(nextServerDataCallback);
nextServerDataLoadingGlobal.push = nextServerDataCallback;
function createResponseCache() {
    return new Map();
}
const rscCache = createResponseCache();
function loadCss(cssChunkInfoJson) {
    return _loadCss.apply(this, arguments);
}
function _loadCss() {
    _loadCss = _asyncToGenerator(function*(cssChunkInfoJson) {
        const data = JSON.parse(cssChunkInfoJson);
        yield Promise.all(data.chunks.map((chunkId)=>{
            // load css related chunks
            return self.__next_chunk_load__(chunkId);
        }));
        // In development mode, import css in dev when it's wrapped by style loader.
        // In production mode, css are standalone chunk that doesn't need to be imported.
        if (data.id) {
            return self.__next_require__(data.id);
        }
        return Promise.resolve();
    });
    return _loadCss.apply(this, arguments);
}
function createLoadFlightCssStream(callback) {
    const cssLoadingPromises = [];
    const loadCssFromStreamData = (data)=>{
        if (data.startsWith('CSS')) {
            const cssJson = data.slice(4).trim();
            if (!loadedCss.has(cssJson)) {
                loadedCss.add(cssJson);
                cssLoadingPromises.push(loadCss(cssJson));
            }
        }
    };
    // TODO-APP: Refine the buffering code here to make it more correct.
    let buffer = '';
    const loadCssFromFlight = new TransformStream({
        transform (chunk, controller) {
            const process = (buf)=>{
                if (buf) {
                    if (buf.startsWith('CSS:')) {
                        loadCssFromStreamData(buf);
                    } else {
                        controller.enqueue(new TextEncoder().encode(buf));
                    }
                }
            };
            const data = new TextDecoder().decode(chunk);
            buffer += data;
            let index;
            while((index = buffer.indexOf('\n')) !== -1){
                const line = buffer.slice(0, index + 1);
                buffer = buffer.slice(index + 1);
                process(line);
            }
            process(buffer);
            buffer = '';
        }
    });
    if (process.env.NODE_ENV === 'development') {
        Promise.all(cssLoadingPromises).then(()=>{
            // TODO: find better timing for css injection
            setTimeout(()=>{
                callback == null ? void 0 : callback();
            });
        });
    }
    return loadCssFromFlight;
}
function useInitialServerResponse(cacheKey, onFlightCssLoaded) {
    const response = rscCache.get(cacheKey);
    if (response) return response;
    const readable = new ReadableStream({
        start (controller) {
            nextServerDataRegisterWriter(controller);
        }
    });
    const newResponse = (0, _reactServerDomWebpack).createFromReadableStream(readable.pipeThrough(createLoadFlightCssStream(onFlightCssLoaded)));
    rscCache.set(cacheKey, newResponse);
    return newResponse;
}
function ServerRoot({ cacheKey , onFlightCssLoaded  }) {
    _react.default.useEffect(()=>{
        rscCache.delete(cacheKey);
    });
    const response = useInitialServerResponse(cacheKey, onFlightCssLoaded);
    const root = response.readRoot();
    return root;
}
function Root({ children  }) {
    if (process.env.__NEXT_TEST_MODE) {
        // eslint-disable-next-line react-hooks/rules-of-hooks
        _react.default.useEffect(()=>{
            window.__NEXT_HYDRATED = true;
            if (window.__NEXT_HYDRATED_CB) {
                window.__NEXT_HYDRATED_CB();
            }
        }, []);
    }
    return children;
}
function RSCComponent(props) {
    const cacheKey = getCacheKey();
    return /*#__PURE__*/ _react.default.createElement(ServerRoot, Object.assign({}, props, {
        cacheKey: cacheKey
    }));
}
function hydrate(opts) {
    renderReactElement(appElement, ()=>{
        /*#__PURE__*/ return _react.default.createElement(_react.default.StrictMode, null, /*#__PURE__*/ _react.default.createElement(Root, null, /*#__PURE__*/ _react.default.createElement(RSCComponent, {
            onFlightCssLoaded: opts == null ? void 0 : opts.onFlightCssLoaded
        })));
    });
}

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=app-index.js.map