import * as __rspack_external_node_fs_5ea92f0c from "node:fs";
import { antiEscapeScriptTag, escapeScriptTag } from "@midscene/shared/utils";
var __webpack_modules__ = {
    "node:fs" (module) {
        module.exports = __rspack_external_node_fs_5ea92f0c;
    }
};
var __webpack_module_cache__ = {};
function __webpack_require__(moduleId) {
    var cachedModule = __webpack_module_cache__[moduleId];
    if (void 0 !== cachedModule) return cachedModule.exports;
    var module = __webpack_module_cache__[moduleId] = {
        exports: {}
    };
    __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
    return module.exports;
}
var external_node_fs_ = __webpack_require__("node:fs");
const escapeContent = escapeScriptTag;
const unescapeContent = antiEscapeScriptTag;
const STREAMING_CHUNK_SIZE = 65536;
function streamScanTags(filePath, openTag, closeTag, onMatch) {
    const fd = (0, external_node_fs_.openSync)(filePath, 'r');
    const fileSize = (0, external_node_fs_.statSync)(filePath).size;
    const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);
    let position = 0;
    let leftover = '';
    let capturing = false;
    let currentContent = '';
    try {
        while(position < fileSize){
            const bytesRead = (0, external_node_fs_.readSync)(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);
            const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);
            position += bytesRead;
            let searchStart = 0;
            while(searchStart < chunk.length)if (capturing) {
                const endIdx = chunk.indexOf(closeTag, searchStart);
                if (-1 !== endIdx) {
                    currentContent += chunk.slice(searchStart, endIdx);
                    const shouldStop = onMatch(currentContent);
                    if (shouldStop) return;
                    capturing = false;
                    currentContent = '';
                    searchStart = endIdx + closeTag.length;
                } else {
                    currentContent += chunk.slice(searchStart, -closeTag.length);
                    leftover = chunk.slice(-closeTag.length);
                    break;
                }
            } else {
                const startIdx = chunk.indexOf(openTag, searchStart);
                if (-1 !== startIdx) {
                    capturing = true;
                    currentContent = chunk.slice(startIdx + openTag.length);
                    const endIdx = currentContent.indexOf(closeTag);
                    if (-1 !== endIdx) {
                        const shouldStop = onMatch(currentContent.slice(0, endIdx));
                        if (shouldStop) return;
                        capturing = false;
                        currentContent = '';
                        searchStart = startIdx + openTag.length + endIdx + closeTag.length;
                    } else {
                        leftover = currentContent.slice(-closeTag.length);
                        currentContent = currentContent.slice(0, -closeTag.length);
                        break;
                    }
                } else {
                    leftover = chunk.slice(-openTag.length);
                    break;
                }
            }
        }
    } finally{
        (0, external_node_fs_.closeSync)(fd);
    }
}
function extractImageByIdSync(htmlPath, imageId) {
    const targetTag = `<script type="midscene-image" data-id="${imageId}">`;
    const closeTag = "<\/script>";
    let result = null;
    streamScanTags(htmlPath, targetTag, closeTag, (content)=>{
        result = unescapeContent(content);
        return true;
    });
    return result;
}
function streamImageScriptsToFile(srcFilePath, destFilePath) {
    const { appendFileSync } = __webpack_require__("node:fs");
    const openTag = '<script type="midscene-image"';
    const closeTag = "<\/script>";
    streamScanTags(srcFilePath, openTag, closeTag, (content)=>{
        appendFileSync(destFilePath, `${openTag}${content}${closeTag}\n`);
        return false;
    });
}
function extractLastDumpScriptSync(filePath) {
    const openTagPrefix = '<script type="midscene_web_dump"';
    const closeTag = "<\/script>";
    let lastContent = '';
    const fd = (0, external_node_fs_.openSync)(filePath, 'r');
    const fileSize = (0, external_node_fs_.statSync)(filePath).size;
    const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);
    let position = 0;
    let leftover = '';
    let capturing = false;
    let currentContent = '';
    try {
        while(position < fileSize){
            const bytesRead = (0, external_node_fs_.readSync)(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);
            const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);
            position += bytesRead;
            let searchStart = 0;
            while(searchStart < chunk.length)if (capturing) {
                const endIdx = chunk.indexOf(closeTag, searchStart);
                if (-1 !== endIdx) {
                    currentContent += chunk.slice(searchStart, endIdx);
                    lastContent = currentContent.trim();
                    capturing = false;
                    currentContent = '';
                    searchStart = endIdx + closeTag.length;
                } else {
                    currentContent += chunk.slice(searchStart, -closeTag.length);
                    leftover = chunk.slice(-closeTag.length);
                    break;
                }
            } else {
                const startIdx = chunk.indexOf(openTagPrefix, searchStart);
                if (-1 !== startIdx) {
                    const tagEndIdx = chunk.indexOf('>', startIdx);
                    if (-1 !== tagEndIdx) {
                        capturing = true;
                        currentContent = chunk.slice(tagEndIdx + 1);
                        const endIdx = currentContent.indexOf(closeTag);
                        if (-1 !== endIdx) {
                            lastContent = currentContent.slice(0, endIdx).trim();
                            capturing = false;
                            currentContent = '';
                            searchStart = tagEndIdx + 1 + endIdx + closeTag.length;
                        } else {
                            leftover = currentContent.slice(-closeTag.length);
                            currentContent = currentContent.slice(0, -closeTag.length);
                            break;
                        }
                    } else {
                        leftover = chunk.slice(startIdx);
                        break;
                    }
                } else {
                    leftover = chunk.slice(-openTagPrefix.length);
                    break;
                }
            }
        }
    } finally{
        (0, external_node_fs_.closeSync)(fd);
    }
    return lastContent;
}
function parseImageScripts(html) {
    const imageMap = {};
    const regex = /<script type="midscene-image" data-id="([^"]+)">([\s\S]*?)<\/script>/g;
    for (const match of html.matchAll(regex)){
        const [, id, content] = match;
        imageMap[id] = unescapeContent(content);
    }
    return imageMap;
}
function parseDumpScript(html) {
    const scriptOpenTag = '<script type="midscene_web_dump"';
    const scriptCloseTag = "<\/script>";
    const lastOpenIndex = html.lastIndexOf(scriptOpenTag);
    if (-1 === lastOpenIndex) throw new Error("No dump script found in HTML");
    const tagEndIndex = html.indexOf('>', lastOpenIndex);
    if (-1 === tagEndIndex) throw new Error("No dump script found in HTML");
    const closeIndex = html.indexOf(scriptCloseTag, tagEndIndex);
    if (-1 === closeIndex) throw new Error("No dump script found in HTML");
    const content = html.substring(tagEndIndex + 1, closeIndex);
    return unescapeContent(content);
}
function parseDumpScriptAttributes(html) {
    const regex = /<script type="midscene_web_dump"([^>]*)>/;
    const match = regex.exec(html);
    if (!match) return {};
    const attrString = match[1];
    const attributes = {};
    const attrRegex = /(\w+)="([^"]*)"/g;
    for (const attrMatch of attrString.matchAll(attrRegex)){
        const [, key, value] = attrMatch;
        if ('type' !== key) attributes[key] = decodeURIComponent(value);
    }
    return attributes;
}
function generateImageScriptTag(id, data) {
    return '<script type="midscene-image" data-id="' + id + '">' + escapeContent(data) + "<\/script>";
}
const BASE_URL_FIX_SCRIPT = '\n<script>(function(){var p=window.location.pathname;if(p.endsWith("/")||/\\.\\w+$/.test(p))return;var b=document.createElement("base");b.href=p+"/";document.head.insertBefore(b,document.head.firstChild)})()<\\/script>\n';
function generateDumpScriptTag(json, attributes) {
    let attrString = '';
    if (attributes && Object.keys(attributes).length > 0) attrString = ' ' + Object.entries(attributes).map(([k, v])=>k + '="' + encodeURIComponent(v) + '"').join(' ');
    return '<script type="midscene_web_dump"' + attrString + '>' + escapeContent(json) + "<\/script>";
}
export { BASE_URL_FIX_SCRIPT, STREAMING_CHUNK_SIZE, escapeContent, extractImageByIdSync, extractLastDumpScriptSync, generateDumpScriptTag, generateImageScriptTag, parseDumpScript, parseDumpScriptAttributes, parseImageScripts, streamImageScriptsToFile, streamScanTags, unescapeContent };

//# sourceMappingURL=html-utils.mjs.map