import {
  H2O_BINDING_NAME,
  SUBREQUEST_PROFILER_ENDPOINT,
  TUNNEL_DOMAIN,
  createLogRequestEvent,
  getDebugBannerLine,
  getUtilityBannerlines,
  handleDebugNetworkRequest,
  handleMiniOxygenImportFail,
  importLocal,
  logRequestLine,
  setConstructors
} from "./chunk-2V4WLVOT.js";
import "./chunk-4KGFXEAN.js";
import "./chunk-LUHAPAT6.js";
import "./chunk-UIFACRCR.js";
import "./chunk-O5K4AU7Q.js";
import "./chunk-J3MMJFA5.js";
import "./chunk-OWRIOLFJ.js";
import "./chunk-4YRKVURS.js";
import "./chunk-EMHZBYE7.js";
import "./chunk-KLJ2TVHE.js";
import "./chunk-VSLR7ET4.js";
import "./chunk-HJBER2P6.js";
import "./chunk-BYPQXSAL.js";
import "./chunk-DD26C7GE.js";
import "./chunk-NLUGD7PZ.js";
import {
  AbortError,
  createFileReadStream,
  outputNewline,
  readFile,
  renderSuccess,
  source_default
} from "./chunk-LA4HX5WI.js";
import "./chunk-XVNW332R.js";
import "./chunk-XEDHKQZA.js";
import {
  dirname,
  resolvePath
} from "./chunk-T2GATXSP.js";
import "./chunk-CBD6UXLA.js";
import "./chunk-CBBS4CV7.js";
import "./chunk-SNOECVP4.js";
import "./chunk-NEOIQ6PN.js";
import "./chunk-7Q3MMWAC.js";
import "./chunk-MX4RJDBM.js";
import "./chunk-NB4NLOEJ.js";
import "./chunk-UBB7JKND.js";
import "./chunk-522OB3EU.js";
import "./chunk-PNN7RS7Y.js";
import {
  init_cjs_shims
} from "./chunk-POZ5MGPT.js";

// ../../node_modules/.pnpm/@shopify+cli-hydrogen@9.0.2_@graphql-codegen+cli@5.0.2_react-dom@17.0.2_react@17.0.2/node_modules/@shopify/cli-hydrogen/dist/lib/mini-oxygen/workerd.js
init_cjs_shims();
import { createRequire } from "node:module";
async function startWorkerdServer({
  root,
  appPort,
  inspectorPort: publicInspectorPort,
  assetsPort,
  debug = !1,
  watch = !1,
  buildPathWorkerFile,
  buildPathClient,
  env
}) {
  let { createMiniOxygen, Response } = await importLocal(
    "@shopify/mini-oxygen",
    root
  ).catch(handleMiniOxygenImportFail);
  setConstructors({ Response });
  async function handleCustomerAccountSchema() {
    let filePath = createRequire(import.meta.url).resolve(
      "@shopify/hydrogen/customer-account.schema.json"
    );
    return new Response(createFileReadStream(filePath), {
      headers: { "Content-Type": "application/json" }
    });
  }
  let mainWorkerName = "hydrogen", absoluteBundlePath = resolvePath(root, buildPathWorkerFile), readWorkerFile = () => readFile(absoluteBundlePath).catch((error) => {
    throw new AbortError(
      `Could not read worker file.

` + error.stack,
      "Did you build the project?"
    );
  }), miniOxygen = createMiniOxygen({
    debug,
    port: appPort,
    host: "localhost",
    liveReload: watch,
    requestHook: logRequestLine,
    inspectorPort: publicInspectorPort,
    inspectWorkerName: mainWorkerName,
    assets: { port: assetsPort, directory: buildPathClient },
    workers: [
      {
        name: "hydrogen:middleware",
        modules: !0,
        script: `export default { fetch: (request, env) => {
          const url = new URL(request.url);
          if (url.hostname.endsWith('${TUNNEL_DOMAIN.ORIGINAL}')) {
            url.hostname = url.hostname.replace(
              '${TUNNEL_DOMAIN.ORIGINAL}',
              '${TUNNEL_DOMAIN.REBRANDED}',
            );
          }

          return url.pathname === '${SUBREQUEST_PROFILER_ENDPOINT}'
            ? env.profiler.fetch(url, request)
            : url.pathname === '/graphiql/customer-account.schema.json'
            ? env.assets.fetch(url, request)
            : env.next.fetch(url, request)
          }
        }`,
        serviceBindings: {
          profiler: handleDebugNetworkRequest,
          assets: handleCustomerAccountSchema,
          next: mainWorkerName
        }
      },
      {
        name: mainWorkerName,
        modulesRoot: dirname(absoluteBundlePath),
        modules: [
          {
            type: "ESModule",
            path: absoluteBundlePath,
            contents: await readWorkerFile()
          }
        ],
        bindings: { ...env },
        serviceBindings: {
          [H2O_BINDING_NAME]: createLogRequestEvent({
            transformLocation: () => absoluteBundlePath
          })
        }
      }
    ]
  }), { workerUrl, inspectorUrl } = await miniOxygen.ready;
  return {
    port: Number(workerUrl.port),
    listeningAt: workerUrl.origin,
    reload(nextOptions) {
      return miniOxygen.reload(async ({ workers }) => {
        let mainWorker = workers.find(({ name }) => name === mainWorkerName);
        return Array.isArray(mainWorker.modules) && mainWorker.modules[0] && (mainWorker.modules[0].contents = await readWorkerFile()), nextOptions && (mainWorker.bindings = { ...nextOptions?.env ?? env }), { workers };
      });
    },
    showBanner(options) {
      outputNewline();
      let customSections = [];
      options?.host && customSections.push({ body: getUtilityBannerlines(options.host) }), inspectorUrl && customSections.push({
        body: { warn: getDebugBannerLine(Number(inspectorUrl.port)) }
      }), renderSuccess({
        headline: `${options?.headlinePrefix ?? ""}MiniOxygen (Worker Runtime) ${options?.mode ?? "development"} server running.`,
        body: [
          `View ${options?.appName ? source_default.cyan(options?.appName) : "Hydrogen"} app:`,
          { link: { url: options?.host || workerUrl.origin } }
        ],
        customSections
      }), console.log("");
    },
    async close() {
      await miniOxygen.dispose();
    }
  };
}
export {
  startWorkerdServer
};
//# sourceMappingURL=workerd-MHJJ5EMV.js.map
