import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);

// ../../node_modules/.pnpm/valibot@1.2.0_typescript@5.8.3/node_modules/valibot/dist/index.mjs
var store$4;
// @__NO_SIDE_EFFECTS__
function getGlobalConfig(config$1) {
  return {
    lang: config$1?.lang ?? store$4?.lang,
    message: config$1?.message,
    abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
    abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
  };
}
var store$3;
// @__NO_SIDE_EFFECTS__
function getGlobalMessage(lang) {
  return store$3?.get(lang);
}
var store$2;
// @__NO_SIDE_EFFECTS__
function getSchemaMessage(lang) {
  return store$2?.get(lang);
}
var store$1;
// @__NO_SIDE_EFFECTS__
function getSpecificMessage(reference, lang) {
  return store$1?.get(reference)?.get(lang);
}
// @__NO_SIDE_EFFECTS__
function _stringify(input) {
  const type = typeof input;
  if (type === "string")
    return `"${input}"`;
  if (type === "number" || type === "bigint" || type === "boolean")
    return `${input}`;
  if (type === "object" || type === "function")
    return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
  return type;
}
function _addIssue(context, label, dataset, config$1, other) {
  const input = other && "input" in other ? other.input : dataset.value;
  const expected = other?.expected ?? context.expects ?? null;
  const received = other?.received ?? /* @__PURE__ */ _stringify(input);
  const issue = {
    kind: context.kind,
    type: context.type,
    input,
    expected,
    received,
    message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
    requirement: context.requirement,
    path: other?.path,
    issues: other?.issues,
    lang: config$1.lang,
    abortEarly: config$1.abortEarly,
    abortPipeEarly: config$1.abortPipeEarly
  };
  const isSchema = context.kind === "schema";
  const message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
  if (message$1 !== void 0)
    issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
  if (isSchema)
    dataset.typed = false;
  if (dataset.issues)
    dataset.issues.push(issue);
  else
    dataset.issues = [issue];
}
// @__NO_SIDE_EFFECTS__
function _getStandardProps(context) {
  return {
    version: 1,
    vendor: "valibot",
    validate(value$1) {
      return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
    }
  };
}
// @__NO_SIDE_EFFECTS__
function _isValidObjectKey(object$1, key) {
  return Object.hasOwn(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
}
// @__NO_SIDE_EFFECTS__
function _joinExpects(values$1, separator) {
  const list = [...new Set(values$1)];
  if (list.length > 1)
    return `(${list.join(` ${separator} `)})`;
  return list[0] ?? "never";
}
// @__NO_SIDE_EFFECTS__
function integer(message$1) {
  return {
    kind: "validation",
    type: "integer",
    reference: integer,
    async: false,
    expects: null,
    requirement: Number.isInteger,
    message: message$1,
    "~run"(dataset, config$1) {
      if (dataset.typed && !this.requirement(dataset.value))
        _addIssue(this, "integer", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function minLength(requirement, message$1) {
  return {
    kind: "validation",
    type: "min_length",
    reference: minLength,
    async: false,
    expects: `>=${requirement}`,
    requirement,
    message: message$1,
    "~run"(dataset, config$1) {
      if (dataset.typed && dataset.value.length < this.requirement)
        _addIssue(this, "length", dataset, config$1, { received: `${dataset.value.length}` });
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function minValue(requirement, message$1) {
  return {
    kind: "validation",
    type: "min_value",
    reference: minValue,
    async: false,
    expects: `>=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
    requirement,
    message: message$1,
    "~run"(dataset, config$1) {
      if (dataset.typed && !(dataset.value >= this.requirement))
        _addIssue(this, "value", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function parseJson(config$1, message$1) {
  return {
    kind: "transformation",
    type: "parse_json",
    reference: parseJson,
    config: config$1,
    message: message$1,
    async: false,
    "~run"(dataset, config$2) {
      try {
        dataset.value = JSON.parse(dataset.value, this.config?.reviver);
      } catch (error) {
        if (error instanceof Error) {
          _addIssue(this, "JSON", dataset, config$2, { received: `"${error.message}"` });
          dataset.typed = false;
        } else
          throw error;
      }
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function regex(requirement, message$1) {
  return {
    kind: "validation",
    type: "regex",
    reference: regex,
    async: false,
    expects: `${requirement}`,
    requirement,
    message: message$1,
    "~run"(dataset, config$1) {
      if (dataset.typed && !this.requirement.test(dataset.value))
        _addIssue(this, "format", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function url(message$1) {
  return {
    kind: "validation",
    type: "url",
    reference: url,
    async: false,
    expects: null,
    requirement(input) {
      try {
        new URL(input);
        return true;
      } catch {
        return false;
      }
    },
    message: message$1,
    "~run"(dataset, config$1) {
      if (dataset.typed && !this.requirement(dataset.value))
        _addIssue(this, "URL", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function getFallback(schema, dataset, config$1) {
  return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
}
// @__NO_SIDE_EFFECTS__
function getDefault(schema, dataset, config$1) {
  return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
}
// @__NO_SIDE_EFFECTS__
function array(item, message$1) {
  return {
    kind: "schema",
    type: "array",
    reference: array,
    expects: "Array",
    async: false,
    item,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      const input = dataset.value;
      if (Array.isArray(input)) {
        dataset.typed = true;
        dataset.value = [];
        for (let key = 0; key < input.length; key++) {
          const value$1 = input[key];
          const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
          if (itemDataset.issues) {
            const pathItem = {
              type: "array",
              origin: "value",
              input,
              key,
              value: value$1
            };
            for (const issue of itemDataset.issues) {
              if (issue.path)
                issue.path.unshift(pathItem);
              else
                issue.path = [pathItem];
              dataset.issues?.push(issue);
            }
            if (!dataset.issues)
              dataset.issues = itemDataset.issues;
            if (config$1.abortEarly) {
              dataset.typed = false;
              break;
            }
          }
          if (!itemDataset.typed)
            dataset.typed = false;
          dataset.value.push(itemDataset.value);
        }
      } else
        _addIssue(this, "type", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function literal(literal_, message$1) {
  return {
    kind: "schema",
    type: "literal",
    reference: literal,
    expects: /* @__PURE__ */ _stringify(literal_),
    async: false,
    literal: literal_,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      if (dataset.value === this.literal)
        dataset.typed = true;
      else
        _addIssue(this, "type", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function looseObject(entries$1, message$1) {
  return {
    kind: "schema",
    type: "loose_object",
    reference: looseObject,
    expects: "Object",
    async: false,
    entries: entries$1,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      const input = dataset.value;
      if (input && typeof input === "object") {
        dataset.typed = true;
        dataset.value = {};
        for (const key in this.entries) {
          const valueSchema = this.entries[key];
          if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
            const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
            const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
            if (valueDataset.issues) {
              const pathItem = {
                type: "object",
                origin: "value",
                input,
                key,
                value: value$1
              };
              for (const issue of valueDataset.issues) {
                if (issue.path)
                  issue.path.unshift(pathItem);
                else
                  issue.path = [pathItem];
                dataset.issues?.push(issue);
              }
              if (!dataset.issues)
                dataset.issues = valueDataset.issues;
              if (config$1.abortEarly) {
                dataset.typed = false;
                break;
              }
            }
            if (!valueDataset.typed)
              dataset.typed = false;
            dataset.value[key] = valueDataset.value;
          } else if (valueSchema.fallback !== void 0)
            dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
          else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
            _addIssue(this, "key", dataset, config$1, {
              input: void 0,
              expected: `"${key}"`,
              path: [{
                type: "object",
                origin: "key",
                input,
                key,
                value: input[key]
              }]
            });
            if (config$1.abortEarly)
              break;
          }
        }
        if (!dataset.issues || !config$1.abortEarly) {
          for (const key in input)
            if (/* @__PURE__ */ _isValidObjectKey(input, key) && !(key in this.entries))
              dataset.value[key] = input[key];
        }
      } else
        _addIssue(this, "type", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function number(message$1) {
  return {
    kind: "schema",
    type: "number",
    reference: number,
    expects: "number",
    async: false,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      if (typeof dataset.value === "number" && !isNaN(dataset.value))
        dataset.typed = true;
      else
        _addIssue(this, "type", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function object(entries$1, message$1) {
  return {
    kind: "schema",
    type: "object",
    reference: object,
    expects: "Object",
    async: false,
    entries: entries$1,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      const input = dataset.value;
      if (input && typeof input === "object") {
        dataset.typed = true;
        dataset.value = {};
        for (const key in this.entries) {
          const valueSchema = this.entries[key];
          if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
            const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
            const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
            if (valueDataset.issues) {
              const pathItem = {
                type: "object",
                origin: "value",
                input,
                key,
                value: value$1
              };
              for (const issue of valueDataset.issues) {
                if (issue.path)
                  issue.path.unshift(pathItem);
                else
                  issue.path = [pathItem];
                dataset.issues?.push(issue);
              }
              if (!dataset.issues)
                dataset.issues = valueDataset.issues;
              if (config$1.abortEarly) {
                dataset.typed = false;
                break;
              }
            }
            if (!valueDataset.typed)
              dataset.typed = false;
            dataset.value[key] = valueDataset.value;
          } else if (valueSchema.fallback !== void 0)
            dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
          else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
            _addIssue(this, "key", dataset, config$1, {
              input: void 0,
              expected: `"${key}"`,
              path: [{
                type: "object",
                origin: "key",
                input,
                key,
                value: input[key]
              }]
            });
            if (config$1.abortEarly)
              break;
          }
        }
      } else
        _addIssue(this, "type", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function optional(wrapped, default_) {
  return {
    kind: "schema",
    type: "optional",
    reference: optional,
    expects: `(${wrapped.expects} | undefined)`,
    async: false,
    wrapped,
    default: default_,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      if (dataset.value === void 0) {
        if (this.default !== void 0)
          dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
        if (dataset.value === void 0) {
          dataset.typed = true;
          return dataset;
        }
      }
      return this.wrapped["~run"](dataset, config$1);
    }
  };
}
// @__NO_SIDE_EFFECTS__
function string(message$1) {
  return {
    kind: "schema",
    type: "string",
    reference: string,
    expects: "string",
    async: false,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      if (typeof dataset.value === "string")
        dataset.typed = true;
      else
        _addIssue(this, "type", dataset, config$1);
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function _subIssues(datasets) {
  let issues;
  if (datasets)
    for (const dataset of datasets)
      if (issues)
        issues.push(...dataset.issues);
      else
        issues = dataset.issues;
  return issues;
}
// @__NO_SIDE_EFFECTS__
function union(options, message$1) {
  return {
    kind: "schema",
    type: "union",
    reference: union,
    expects: /* @__PURE__ */ _joinExpects(options.map((option) => option.expects), "|"),
    async: false,
    options,
    message: message$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      let validDataset;
      let typedDatasets;
      let untypedDatasets;
      for (const schema of this.options) {
        const optionDataset = schema["~run"]({ value: dataset.value }, config$1);
        if (optionDataset.typed)
          if (optionDataset.issues)
            if (typedDatasets)
              typedDatasets.push(optionDataset);
            else
              typedDatasets = [optionDataset];
          else {
            validDataset = optionDataset;
            break;
          }
        else if (untypedDatasets)
          untypedDatasets.push(optionDataset);
        else
          untypedDatasets = [optionDataset];
      }
      if (validDataset)
        return validDataset;
      if (typedDatasets) {
        if (typedDatasets.length === 1)
          return typedDatasets[0];
        _addIssue(this, "type", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(typedDatasets) });
        dataset.typed = true;
      } else if (untypedDatasets?.length === 1)
        return untypedDatasets[0];
      else
        _addIssue(this, "type", dataset, config$1, { issues: /* @__PURE__ */ _subIssues(untypedDatasets) });
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function pipe(...pipe$1) {
  return {
    ...pipe$1[0],
    pipe: pipe$1,
    get "~standard"() {
      return /* @__PURE__ */ _getStandardProps(this);
    },
    "~run"(dataset, config$1) {
      for (const item of pipe$1)
        if (item.kind !== "metadata") {
          if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
            dataset.typed = false;
            break;
          }
          if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly)
            dataset = item["~run"](dataset, config$1);
        }
      return dataset;
    }
  };
}
// @__NO_SIDE_EFFECTS__
function safeParse(schema, input, config$1) {
  const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));
  return {
    typed: dataset.typed,
    success: !dataset.issues,
    output: dataset.value,
    issues: dataset.issues
  };
}

// ../../dev/server/src/api-key.ts
var POSTGRES_PROTOCOL_REGEX = /^(postgres|postgresql):\/\//;
var decodedAPIKeySchema = pipe(
  string(),
  parseJson(),
  object({
    databaseUrl: pipe(string(), url(), regex(POSTGRES_PROTOCOL_REGEX)),
    name: optional(pipe(string(), minLength(1))),
    shadowDatabaseUrl: pipe(string(), url(), regex(POSTGRES_PROTOCOL_REGEX))
  })
);
function encodeAPIKey(payload) {
  return Buffer.from(
    // we sort the keys to ensure consistent encoding
    JSON.stringify(Object.fromEntries(Object.entries(payload).sort(([[key0], [key1]]) => key0.localeCompare(key1)))),
    "utf8"
  ).toString("base64url");
}
function decodeAPIKey(apiKey) {
  const serialized = Buffer.from(apiKey, "base64url").toString("utf8");
  const { issues, output, success } = safeParse(decodedAPIKeySchema, serialized, { abortEarly: true });
  if (!success) {
    return [issues];
  }
  return [null, output];
}
var apiKeyValidator = async (value, ctx) => {
  const { authorization } = value;
  const { HTTPException } = await import("hono/http-exception");
  if (!authorization) {
    throw new HTTPException(401, { message: "Missing API Key" });
  }
  const [keyType, apiKey = "", extras] = authorization.split(" ");
  if (keyType !== "Bearer" || extras) {
    throw new HTTPException(401, { message: "Invalid API Key" });
  }
  const [issues, decodedAPIKey] = decodeAPIKey(apiKey);
  if (issues) {
    throw new HTTPException(401, { message: "Invalid API Key", cause: issues.join(", ") });
  }
  const { databaseUrl, name, shadowDatabaseUrl } = decodedAPIKey;
  const { name: expectedName } = ctx.get("serverState");
  if (!name) {
    throw new HTTPException(401, {
      message: `Wrong API Key; The Prisma Dev server running at port ${ctx.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${expectedName}" server's output for the updated \`DATABASE_URL\` value.`
    });
  }
  if (name !== expectedName) {
    throw new HTTPException(401, {
      message: `Wrong API Key; The Prisma Dev server running at port ${ctx.get("port")} is named "${expectedName}", but the API Key is for "${name}"`
    });
  }
  const { hostname, port } = new URL(databaseUrl);
  const { port: expectedPort } = ctx.get("db");
  const { hostname: shadowHostname, port: shadowPort } = new URL(shadowDatabaseUrl);
  const expectedShadowPort = ctx.get("shadowDBPort");
  if (hostname !== "localhost" || Number(port) !== expectedPort || shadowHostname !== "localhost" || Number(shadowPort) !== expectedShadowPort) {
    throw new HTTPException(401, {
      message: "Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"
    });
  }
  return { decodedAPIKey };
};

// ../../dev/server/src/engine.ts
import { spawn } from "child_process";
import { once } from "events";
import { mkdir as mkdir2 } from "fs/promises";
import { join } from "path";
import { setTimeout } from "timers/promises";

// ../../common/stuff/with-resolvers.ts
function withResolvers(options) {
  let succeed, fail;
  const promise = new Promise((resolve2, reject) => {
    succeed = resolve2;
    fail = reject;
  });
  let failOnce = (reason) => {
    failOnce = succeedOnce = null;
    fail(reason);
    options?.onRejected?.(reason);
    options?.onFulfilled?.();
  };
  let succeedOnce = (value) => {
    succeedOnce = failOnce = null;
    succeed(value);
    options?.onResolved?.(value);
    options?.onFulfilled?.();
  };
  return {
    isFulfilled: () => succeedOnce === failOnce,
    promise,
    reject: (reason) => failOnce?.(reason),
    resolve: (value) => succeedOnce?.(value)
  };
}

// ../../node_modules/.pnpm/std-env@3.9.0/node_modules/std-env/dist/index.mjs
var r = /* @__PURE__ */ Object.create(null);
var i = (e) => globalThis.process?.env || import.meta.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (e ? r : globalThis);
var o = new Proxy(r, { get(e, s) {
  return i()[s] ?? r[s];
}, has(e, s) {
  const E = i();
  return s in E || s in r;
}, set(e, s, E) {
  const B = i(true);
  return B[s] = E, true;
}, deleteProperty(e, s) {
  if (!s)
    return false;
  const E = i(true);
  return delete E[s], true;
}, ownKeys() {
  const e = i(true);
  return Object.keys(e);
} });
var t = typeof process < "u" && process.env && process.env.NODE_ENV || "";
var f = [["APPVEYOR"], ["AWS_AMPLIFY", "AWS_APP_ID", { ci: true }], ["AZURE_PIPELINES", "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"], ["AZURE_STATIC", "INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN"], ["APPCIRCLE", "AC_APPCIRCLE"], ["BAMBOO", "bamboo_planKey"], ["BITBUCKET", "BITBUCKET_COMMIT"], ["BITRISE", "BITRISE_IO"], ["BUDDY", "BUDDY_WORKSPACE_ID"], ["BUILDKITE"], ["CIRCLE", "CIRCLECI"], ["CIRRUS", "CIRRUS_CI"], ["CLOUDFLARE_PAGES", "CF_PAGES", { ci: true }], ["CLOUDFLARE_WORKERS", "WORKERS_CI", { ci: true }], ["CODEBUILD", "CODEBUILD_BUILD_ARN"], ["CODEFRESH", "CF_BUILD_ID"], ["DRONE"], ["DRONE", "DRONE_BUILD_EVENT"], ["DSARI"], ["GITHUB_ACTIONS"], ["GITLAB", "GITLAB_CI"], ["GITLAB", "CI_MERGE_REQUEST_ID"], ["GOCD", "GO_PIPELINE_LABEL"], ["LAYERCI"], ["HUDSON", "HUDSON_URL"], ["JENKINS", "JENKINS_URL"], ["MAGNUM"], ["NETLIFY"], ["NETLIFY", "NETLIFY_LOCAL", { ci: false }], ["NEVERCODE"], ["RENDER"], ["SAIL", "SAILCI"], ["SEMAPHORE"], ["SCREWDRIVER"], ["SHIPPABLE"], ["SOLANO", "TDDIUM"], ["STRIDER"], ["TEAMCITY", "TEAMCITY_VERSION"], ["TRAVIS"], ["VERCEL", "NOW_BUILDER"], ["VERCEL", "VERCEL", { ci: false }], ["VERCEL", "VERCEL_ENV", { ci: false }], ["APPCENTER", "APPCENTER_BUILD_ID"], ["CODESANDBOX", "CODESANDBOX_SSE", { ci: false }], ["CODESANDBOX", "CODESANDBOX_HOST", { ci: false }], ["STACKBLITZ"], ["STORMKIT"], ["CLEAVR"], ["ZEABUR"], ["CODESPHERE", "CODESPHERE_APP_ID", { ci: true }], ["RAILWAY", "RAILWAY_PROJECT_ID"], ["RAILWAY", "RAILWAY_SERVICE_ID"], ["DENO-DEPLOY", "DENO_DEPLOYMENT_ID"], ["FIREBASE_APP_HOSTING", "FIREBASE_APP_HOSTING", { ci: true }]];
function b() {
  if (globalThis.process?.env)
    for (const e of f) {
      const s = e[1] || e[0];
      if (globalThis.process?.env[s])
        return { name: e[0].toLowerCase(), ...e[2] };
    }
  return globalThis.process?.env?.SHELL === "/bin/jsh" && globalThis.process?.versions?.webcontainer ? { name: "stackblitz", ci: false } : { name: "", ci: false };
}
var l = b();
var p = l.name;
function n(e) {
  return e ? e !== "false" : false;
}
var I = globalThis.process?.platform || "";
var T = n(o.CI) || l.ci !== false;
var R = n(globalThis.process?.stdout && globalThis.process?.stdout.isTTY);
var d = n(o.DEBUG);
var a = t === "test" || n(o.TEST);
var v = n(o.MINIMAL) || T || a || !R;
var A = /^win/i.test(I);
var M = /^linux/i.test(I);
var m = /^darwin/i.test(I);
var Y = !n(o.NO_COLOR) && (n(o.FORCE_COLOR) || (R || A) && o.TERM !== "dumb" || T);
var C = (globalThis.process?.versions?.node || "").replace(/^v/, "") || null;
var V = Number(C?.split(".")[0]) || null;
var W = globalThis.process || /* @__PURE__ */ Object.create(null);
var _ = { versions: {} };
var y = new Proxy(W, { get(e, s) {
  if (s === "env")
    return o;
  if (s in e)
    return e[s];
  if (s in _)
    return _[s];
} });
var O = globalThis.process?.release?.name === "node";
var c = !!globalThis.Bun || !!globalThis.process?.versions?.bun;
var D = !!globalThis.Deno;
var L = !!globalThis.fastly;
var S = !!globalThis.Netlify;
var u = !!globalThis.EdgeRuntime;
var N = globalThis.navigator?.userAgent === "Cloudflare-Workers";
var F = [[S, "netlify"], [u, "edge-light"], [N, "workerd"], [L, "fastly"], [D, "deno"], [c, "bun"], [O, "node"]];
function G() {
  const e = F.find((s) => s[0]);
  if (e)
    return { name: e[1] };
}
var P = G();
var K = P?.name || "";

// ../../dev/server/src/filesystem.ts
import { createWriteStream, WriteStream } from "fs";
import { access, chmod, constants, mkdir, readdir, readFile, rm, writeFile } from "fs/promises";
import { promisify } from "util";
import { unzip } from "zlib";

// ../../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
import path from "path";
import os from "os";
import process2 from "process";
var homedir = os.homedir();
var tmpdir = os.tmpdir();
var { env } = process2;
var macos = (name) => {
  const library = path.join(homedir, "Library");
  return {
    data: path.join(library, "Application Support", name),
    config: path.join(library, "Preferences", name),
    cache: path.join(library, "Caches", name),
    log: path.join(library, "Logs", name),
    temp: path.join(tmpdir, name)
  };
};
var windows = (name) => {
  const appData = env.APPDATA || path.join(homedir, "AppData", "Roaming");
  const localAppData = env.LOCALAPPDATA || path.join(homedir, "AppData", "Local");
  return {
    // Data/config/cache/log are invented by me as Windows isn't opinionated about this
    data: path.join(localAppData, name, "Data"),
    config: path.join(appData, name, "Config"),
    cache: path.join(localAppData, name, "Cache"),
    log: path.join(localAppData, name, "Log"),
    temp: path.join(tmpdir, name)
  };
};
var linux = (name) => {
  const username = path.basename(homedir);
  return {
    data: path.join(env.XDG_DATA_HOME || path.join(homedir, ".local", "share"), name),
    config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, ".config"), name),
    cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, ".cache"), name),
    // https://wiki.debian.org/XDGBaseDirectorySpecification#state
    log: path.join(env.XDG_STATE_HOME || path.join(homedir, ".local", "state"), name),
    temp: path.join(tmpdir, username, name)
  };
};
function envPaths(name, { suffix = "nodejs" } = {}) {
  if (typeof name !== "string") {
    throw new TypeError(`Expected a string, got ${typeof name}`);
  }
  if (suffix) {
    name += `-${suffix}`;
  }
  if (process2.platform === "darwin") {
    return macos(name);
  }
  if (process2.platform === "win32") {
    return windows(name);
  }
  return linux(name);
}

// ../../node_modules/.pnpm/grammex@3.1.10/node_modules/grammex/dist/utils.js
var isArray = (value) => {
  return Array.isArray(value);
};
var isFunction = (value) => {
  return typeof value === "function";
};
var isFunctionNullary = (value) => {
  return value.length === 0;
};
var isFunctionStrictlyNullaryOrUnary = (() => {
  const { toString } = Function.prototype;
  const re = /(?:^\(\s*(?:[^,.()]|\.(?!\.\.))*\s*\)\s*=>|^\s*[a-zA-Z$_][a-zA-Z0-9$_]*\s*=>)/;
  return (value) => {
    return (value.length === 0 || value.length === 1) && re.test(toString.call(value));
  };
})();
var isNumber = (value) => {
  return typeof value === "number";
};
var isObject = (value) => {
  return typeof value === "object" && value !== null;
};
var isRegExp = (value) => {
  return value instanceof RegExp;
};
var isRegExpCapturing = /* @__PURE__ */ (() => {
  const sourceRe = /\\\(|\((?!\?(?::|=|!|<=|<!))/;
  return (re) => {
    return sourceRe.test(re.source);
  };
})();
var isRegExpStatic = /* @__PURE__ */ (() => {
  const sourceRe = /^[a-zA-Z0-9_-]+$/;
  return (re) => {
    return sourceRe.test(re.source) && !re.flags.includes("i");
  };
})();
var isString = (value) => {
  return typeof value === "string";
};
var isUndefined = (value) => {
  return value === void 0;
};
var memoize = (fn) => {
  const cache = /* @__PURE__ */ new Map();
  return (arg) => {
    const cached = cache.get(arg);
    if (cached !== void 0)
      return cached;
    const value = fn(arg);
    cache.set(arg, value);
    return value;
  };
};

// ../../node_modules/.pnpm/grammex@3.1.10/node_modules/grammex/dist/index.js
var parse = (input, rule, options = {}) => {
  const state = { cache: {}, input, index: 0, indexBacktrackMax: 0, options, output: [] };
  const matched = resolve(rule)(state);
  const indexMax = Math.max(state.index, state.indexBacktrackMax);
  if (matched && state.index === input.length) {
    return state.output;
  } else {
    throw new Error(`Failed to parse at index ${indexMax}`);
  }
};
var match = (target, handler) => {
  if (isArray(target)) {
    return chars(target, handler);
  } else if (isString(target)) {
    return string2(target, handler);
  } else {
    return regex2(target, handler);
  }
};
var chars = (target, handler) => {
  const charCodes = {};
  for (const char of target) {
    if (char.length !== 1)
      throw new Error(`Invalid character: "${char}"`);
    const charCode = char.charCodeAt(0);
    charCodes[charCode] = true;
  }
  return (state) => {
    const input = state.input;
    let indexStart = state.index;
    let indexEnd = indexStart;
    while (indexEnd < input.length) {
      const charCode = input.charCodeAt(indexEnd);
      if (!(charCode in charCodes))
        break;
      indexEnd += 1;
    }
    if (indexEnd > indexStart) {
      if (!isUndefined(handler) && !state.options.silent) {
        const target2 = input.slice(indexStart, indexEnd);
        const output = isFunction(handler) ? handler(target2, input, `${indexStart}`) : handler;
        if (!isUndefined(output)) {
          state.output.push(output);
        }
      }
      state.index = indexEnd;
    }
    return true;
  };
};
var regex2 = (target, handler) => {
  if (isRegExpStatic(target)) {
    return string2(target.source, handler);
  } else {
    const source = target.source;
    const flags = target.flags.replace(/y|$/, "y");
    const re = new RegExp(source, flags);
    if (isRegExpCapturing(target) && isFunction(handler) && !isFunctionStrictlyNullaryOrUnary(handler)) {
      return regexCapturing(re, handler);
    } else {
      return regexNonCapturing(re, handler);
    }
  }
};
var regexCapturing = (re, handler) => {
  return (state) => {
    const indexStart = state.index;
    const input = state.input;
    re.lastIndex = indexStart;
    const match2 = re.exec(input);
    if (match2) {
      const indexEnd = re.lastIndex;
      if (!state.options.silent) {
        const output = handler(...match2, input, `${indexStart}`);
        if (!isUndefined(output)) {
          state.output.push(output);
        }
      }
      state.index = indexEnd;
      return true;
    } else {
      return false;
    }
  };
};
var regexNonCapturing = (re, handler) => {
  return (state) => {
    const indexStart = state.index;
    const input = state.input;
    re.lastIndex = indexStart;
    const matched = re.test(input);
    if (matched) {
      const indexEnd = re.lastIndex;
      if (!isUndefined(handler) && !state.options.silent) {
        const output = isFunction(handler) ? handler(input.slice(indexStart, indexEnd), input, `${indexStart}`) : handler;
        if (!isUndefined(output)) {
          state.output.push(output);
        }
      }
      state.index = indexEnd;
      return true;
    } else {
      return false;
    }
  };
};
var string2 = (target, handler) => {
  return (state) => {
    const indexStart = state.index;
    const input = state.input;
    const matched = input.startsWith(target, indexStart);
    if (matched) {
      if (!isUndefined(handler) && !state.options.silent) {
        const output = isFunction(handler) ? handler(target, input, `${indexStart}`) : handler;
        if (!isUndefined(output)) {
          state.output.push(output);
        }
      }
      state.index += target.length;
      return true;
    } else {
      return false;
    }
  };
};
var repeat = (rule, min, max, handler) => {
  const erule = resolve(rule);
  const isBacktrackable = min > 1;
  return memoizable(handleable(backtrackable((state) => {
    let repetitions = 0;
    while (repetitions < max) {
      const index = state.index;
      const matched = erule(state);
      if (!matched)
        break;
      repetitions += 1;
      if (state.index === index)
        break;
    }
    return repetitions >= min;
  }, isBacktrackable), handler));
};
var optional2 = (rule, handler) => {
  return repeat(rule, 0, 1, handler);
};
var star = (rule, handler) => {
  return repeat(rule, 0, Infinity, handler);
};
var and = (rules, handler) => {
  const erules = rules.map(resolve);
  return memoizable(handleable(backtrackable((state) => {
    for (let i2 = 0, l2 = erules.length; i2 < l2; i2++) {
      if (!erules[i2](state))
        return false;
    }
    return true;
  }), handler));
};
var or = (rules, handler) => {
  const erules = rules.map(resolve);
  return memoizable(handleable((state) => {
    for (let i2 = 0, l2 = erules.length; i2 < l2; i2++) {
      if (erules[i2](state))
        return true;
    }
    return false;
  }, handler));
};
var backtrackable = (rule, enabled = true, force = false) => {
  const erule = resolve(rule);
  if (!enabled)
    return erule;
  return (state) => {
    const index = state.index;
    const length = state.output.length;
    const matched = erule(state);
    if (!matched && !force) {
      state.indexBacktrackMax = Math.max(state.indexBacktrackMax, state.index);
    }
    if (!matched || force) {
      state.index = index;
      if (state.output.length !== length) {
        state.output.length = length;
      }
    }
    return matched;
  };
};
var handleable = (rule, handler) => {
  const erule = resolve(rule);
  if (!handler)
    return erule;
  return (state) => {
    if (state.options.silent)
      return erule(state);
    const length = state.output.length;
    const matched = erule(state);
    if (matched) {
      const outputs = state.output.splice(length, Infinity);
      const output = handler(outputs);
      if (!isUndefined(output)) {
        state.output.push(output);
      }
      return true;
    } else {
      return false;
    }
  };
};
var memoizable = /* @__PURE__ */ (() => {
  let RULE_ID = 0;
  return (rule) => {
    const erule = resolve(rule);
    const ruleId = RULE_ID += 1;
    return (state) => {
      var _a;
      if (state.options.memoization === false)
        return erule(state);
      const indexStart = state.index;
      const cache = (_a = state.cache)[ruleId] || (_a[ruleId] = { indexMax: -1, queue: [] });
      const cacheQueue = cache.queue;
      const isPotentiallyCached = indexStart <= cache.indexMax;
      if (isPotentiallyCached) {
        const cacheStore = cache.store || (cache.store = /* @__PURE__ */ new Map());
        if (cacheQueue.length) {
          for (let i2 = 0, l2 = cacheQueue.length; i2 < l2; i2 += 2) {
            const key = cacheQueue[i2 * 2];
            const value = cacheQueue[i2 * 2 + 1];
            cacheStore.set(key, value);
          }
          cacheQueue.length = 0;
        }
        const cached = cacheStore.get(indexStart);
        if (cached === false) {
          return false;
        } else if (isNumber(cached)) {
          state.index = cached;
          return true;
        } else if (cached) {
          state.index = cached.index;
          if (cached.output?.length) {
            state.output.push(...cached.output);
          }
          return true;
        }
      }
      const lengthStart = state.output.length;
      const matched = erule(state);
      cache.indexMax = Math.max(cache.indexMax, indexStart);
      if (matched) {
        const indexEnd = state.index;
        const lengthEnd = state.output.length;
        if (lengthEnd > lengthStart) {
          const output = state.output.slice(lengthStart, lengthEnd);
          cacheQueue.push(indexStart, { index: indexEnd, output });
        } else {
          cacheQueue.push(indexStart, indexEnd);
        }
        return true;
      } else {
        cacheQueue.push(indexStart, false);
        return false;
      }
    };
  };
})();
var lazy = (getter) => {
  let erule;
  return (state) => {
    erule || (erule = resolve(getter()));
    return erule(state);
  };
};
var resolve = memoize((rule) => {
  if (isFunction(rule)) {
    if (isFunctionNullary(rule)) {
      return lazy(rule);
    } else {
      return rule;
    }
  }
  if (isString(rule) || isRegExp(rule)) {
    return match(rule);
  }
  if (isArray(rule)) {
    return and(rule);
  }
  if (isObject(rule)) {
    return or(Object.values(rule));
  }
  throw new Error("Invalid rule");
});

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/utils.js
var identity = (value) => {
  return value;
};
var makeParser = (grammar) => {
  return (input) => {
    return parse(input, grammar, { memoization: false }).join("");
  };
};
var memoize2 = (fn) => {
  const cache = {};
  return (arg) => {
    return cache[arg] ?? (cache[arg] = fn(arg));
  };
};

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/range.js
var ALPHABET = "abcdefghijklmnopqrstuvwxyz";
var int2alpha = (int) => {
  let alpha = "";
  while (int > 0) {
    const reminder = (int - 1) % 26;
    alpha = ALPHABET[reminder] + alpha;
    int = Math.floor((int - 1) / 26);
  }
  return alpha;
};
var alpha2int = (str) => {
  let int = 0;
  for (let i2 = 0, l2 = str.length; i2 < l2; i2++) {
    int = int * 26 + ALPHABET.indexOf(str[i2]) + 1;
  }
  return int;
};
var makeRangeInt = (start, end) => {
  if (end < start)
    return makeRangeInt(end, start);
  const range = [];
  while (start <= end) {
    range.push(start++);
  }
  return range;
};
var makeRangePaddedInt = (start, end, paddingLength) => {
  return makeRangeInt(start, end).map((int) => String(int).padStart(paddingLength, "0"));
};
var makeRangeAlpha = (start, end) => {
  return makeRangeInt(alpha2int(start), alpha2int(end)).map(int2alpha);
};

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/convert/grammar.js
var Escaped = match(/\\./, identity);
var Escape = match(/[$.*+?^(){}[\]\|]/, (char) => `\\${char}`);
var Slash = match(/[\\/]/, "[\\\\/]");
var Passthrough = match(/./, identity);
var NegationOdd = match(/^(?:!!)*!(.*)$/, (_2, glob) => `(?!^${parser_default(glob)}$).*?`);
var NegationEven = match(/^(!!)+/, "");
var Negation = or([NegationOdd, NegationEven]);
var StarStarBetween = match(/\/(\*\*\/)+/, "(?:[\\\\/].+[\\\\/]|[\\\\/])");
var StarStarStart = match(/^(\*\*\/)+/, "(?:^|.*[\\\\/])");
var StarStarEnd = match(/\/(\*\*)$/, "(?:[\\\\/].*|$)");
var StarStarNone = match(/\*\*/, ".*");
var StarStar = or([StarStarBetween, StarStarStart, StarStarEnd, StarStarNone]);
var StarDouble = match(/\*\/(?!\*\*\/|\*$)/, "[^\\\\/]*[\\\\/]");
var StarSingle = match(/\*/, "[^\\\\/]*");
var Star = or([StarDouble, StarSingle]);
var Question = match("?", "[^\\\\/]");
var ClassOpen = match("[", identity);
var ClassClose = match("]", identity);
var ClassNegation = match(/[!^]/, "^\\\\/");
var ClassRange = match(/[a-z]-[a-z]|[0-9]-[0-9]/i, identity);
var ClassEscape = match(/[$.*+?^(){}[\|]/, (char) => `\\${char}`);
var ClassPassthrough = match(/[^\]]/, identity);
var ClassValue = or([Escaped, ClassEscape, ClassRange, ClassPassthrough]);
var Class = and([ClassOpen, optional2(ClassNegation), star(ClassValue), ClassClose]);
var RangeOpen = match("{", "(?:");
var RangeClose = match("}", ")");
var RangeNumeric = match(/(\d+)\.\.(\d+)/, (_2, $1, $2) => makeRangePaddedInt(+$1, +$2, Math.min($1.length, $2.length)).join("|"));
var RangeAlphaLower = match(/([a-z]+)\.\.([a-z]+)/, (_2, $1, $2) => makeRangeAlpha($1, $2).join("|"));
var RangeAlphaUpper = match(/([A-Z]+)\.\.([A-Z]+)/, (_2, $1, $2) => makeRangeAlpha($1.toLowerCase(), $2.toLowerCase()).join("|").toUpperCase());
var RangeValue = or([RangeNumeric, RangeAlphaLower, RangeAlphaUpper]);
var Range = and([RangeOpen, RangeValue, RangeClose]);
var BracesOpen = match("{", "(?:");
var BracesClose = match("}", ")");
var BracesComma = match(",", "|");
var BracesEscape = match(/[$.*+?^(){[\]\|]/, (char) => `\\${char}`);
var BracesPassthrough = match(/[^}]/, identity);
var BracesNested = lazy(() => Braces);
var BracesValue = or([StarStar, Star, Question, Class, Range, BracesNested, Escaped, BracesEscape, BracesComma, BracesPassthrough]);
var Braces = and([BracesOpen, star(BracesValue), BracesClose]);
var Grammar = star(or([Negation, StarStar, Star, Question, Class, Range, Braces, Escaped, Escape, Slash, Passthrough]));
var grammar_default = Grammar;

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/convert/parser.js
var parser = makeParser(grammar_default);
var parser_default = parser;

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/normalize/grammar.js
var Escaped2 = match(/\\./, identity);
var Passthrough2 = match(/./, identity);
var StarStarStar = match(/\*\*\*+/, "*");
var StarStarNoLeft = match(/([^/{[(!])\*\*/, (_2, $1) => `${$1}*`);
var StarStarNoRight = match(/(^|.)\*\*(?=[^*/)\]}])/, (_2, $1) => `${$1}*`);
var Grammar2 = star(or([Escaped2, StarStarStar, StarStarNoLeft, StarStarNoRight, Passthrough2]));
var grammar_default2 = Grammar2;

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/normalize/parser.js
var parser2 = makeParser(grammar_default2);
var parser_default2 = parser2;

// ../../node_modules/.pnpm/zeptomatch@2.0.2/node_modules/zeptomatch/dist/index.js
var zeptomatch = (glob, path2) => {
  if (Array.isArray(glob)) {
    const res = glob.map(zeptomatch.compile);
    const isMatch = res.some((re) => re.test(path2));
    return isMatch;
  } else {
    const re = zeptomatch.compile(glob);
    const isMatch = re.test(path2);
    return isMatch;
  }
};
zeptomatch.compile = memoize2((glob) => {
  return new RegExp(`^${parser_default(parser_default2(glob))}[\\\\/]?$`, "s");
});
var dist_default = zeptomatch;

// ../../dev/server/src/filesystem.ts
var GLOBAL_DIR_ROOT_PATH = envPaths("prisma-dev");
var unzipAsync = promisify(unzip);
function getEngineCacheDirPath(version, commitHash) {
  return `${GLOBAL_DIR_ROOT_PATH.cache}/engine/${version}/${commitHash}`;
}
function getDataDirPath(name) {
  return `${GLOBAL_DIR_ROOT_PATH.data}/${name}`;
}
async function checkFileExists(filePath) {
  try {
    await access(filePath, constants.F_OK);
    return true;
  } catch (error) {
    if (isFileNotFoundError(error)) {
      return false;
    }
    throw error;
  }
}
async function writeBinaryFile(buffer, path2) {
  const result = await unzipAsync(buffer);
  await writeFile(path2, result);
  await chmod(path2, "755");
}
async function streamAsTextTo(file, path2) {
  await file.stream().pipeTo(WriteStream.toWeb(createWriteStream(path2, { encoding: "utf-8" })));
}
function isFileNotFoundError(error) {
  return error != null && typeof error === "object" && "code" in error && error.code === "ENOENT";
}
async function readFileAsText(path2) {
  try {
    return await readFile(path2, { encoding: "utf-8" });
  } catch (error) {
    if (isFileNotFoundError(error)) {
      return null;
    }
    throw error;
  }
}
async function ensureDirectory(path2) {
  await mkdir(path2, { recursive: true });
}
async function readDirectoryNames(path2, globs) {
  try {
    const dirents = await readdir(path2, { withFileTypes: true });
    return dirents.reduce((names, dirent) => {
      if (dirent.isDirectory() && !dirent.name.startsWith(".") && (!globs || dist_default(globs, dirent.name))) {
        names.push(dirent.name);
      }
      return names;
    }, []);
  } catch (error) {
    if (isFileNotFoundError(error)) {
      return [];
    }
    throw error;
  }
}

// ../../dev/server/src/engine.ts
var {
  PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD,
  PRISMA_DEV_FORCE_ENGINE_BINARY_PATH,
  PRISMA_DEV_FORCE_NETWORK_DELAY_MS
} = y.env;
var Engine = class _Engine {
  static #enginesBySchemaAndClientVersion = /* @__PURE__ */ new Map();
  #options;
  #session;
  constructor(options) {
    this.#options = options;
    this.#session = null;
  }
  static async get(options) {
    const { debug } = options;
    const engineId = `${options.schemaHash}:${options.clientVersion}`;
    try {
      const engine = _Engine.#enginesBySchemaAndClientVersion.get(engineId);
      if (engine) {
        return engine;
      }
      const newEngine = new _Engine(options);
      _Engine.#enginesBySchemaAndClientVersion.set(engineId, newEngine);
      if (debug) {
        console.debug("[Query Engine] starting...", options);
      }
      await newEngine.start();
      if (debug) {
        console.debug("[Query Engine] started!");
      }
      return newEngine;
    } finally {
      void _Engine.stopAll(engineId);
    }
  }
  static async stopAll(excludingEngineId) {
    const results = await Promise.allSettled(
      Array.from(_Engine.#enginesBySchemaAndClientVersion.entries()).filter(([engineId]) => engineId !== excludingEngineId).map(async ([engineId, engine]) => {
        try {
          await engine.stop();
        } finally {
          _Engine.#enginesBySchemaAndClientVersion.delete(engineId);
        }
      })
    );
    const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
    if (errors.length > 0) {
      throw new AggregateError(errors, "Failed to stop engines");
    }
  }
  async commitTransaction(transactionId, headers) {
    return await this.#commitOrRollbackTransaction(transactionId, headers, "commit");
  }
  async request(body, headers) {
    const { url: url2 } = await this.start();
    const sanitizedHeaders = this.#sanitizeHeaders(headers);
    const response = await fetch(url2, {
      body: typeof body === "string" ? body : JSON.stringify(body),
      headers: { ...sanitizedHeaders, "Content-Type": "application/json" },
      method: "POST"
    });
    if (!response.ok) {
      throw await EngineHttpError.fromResponse(response);
    }
    return await response.text();
  }
  async rollbackTransaction(transactionId, headers) {
    return await this.#commitOrRollbackTransaction(transactionId, headers, "rollback");
  }
  async startTransaction(options, headers) {
    const { url: url2 } = await this.start();
    const sanitizedHeaders = this.#sanitizeHeaders(headers);
    const response = await fetch(`${url2}/transaction/start`, {
      body: JSON.stringify(options),
      headers: { ...sanitizedHeaders, "Content-Type": "application/json" },
      method: "POST"
    });
    if (!response.ok) {
      throw await EngineHttpError.fromResponse(response);
    }
    return await response.json();
  }
  async start() {
    if (this.#session != null) {
      return await this.#session;
    }
    const { promise: session, reject, resolve: resolve2 } = withResolvers();
    this.#session = session;
    const engineBinaryPath = PRISMA_DEV_FORCE_ENGINE_BINARY_PATH || await this.#getEngineBinaryPath();
    if (this.#options.debug) {
      console.debug("[Query Engine] spinning up at path...", engineBinaryPath);
    }
    const { proxySignals } = await import("foreground-child/proxy-signals");
    const childProcess = spawn(
      engineBinaryPath,
      ["--enable-raw-queries", "--enable-telemetry-in-response", "--port", "0"],
      {
        env: {
          LOG_QUERIES: "y",
          PRISMA_DML: this.#options.base64Schema,
          QE_LOG_LEVEL: "TRACE",
          RUST_BACKTRACE: "1",
          RUST_LOG: "info"
        },
        stdio: ["ignore", "pipe", "pipe"],
        windowsHide: true
      }
    );
    proxySignals(childProcess);
    childProcess.stderr.setEncoding("utf8");
    childProcess.stdout.setEncoding("utf8");
    const waitForListening = (data) => {
      const readyMessage = data.split("\n").find((line) => line.includes("Started query engine http server"));
      if (!readyMessage) {
        return;
      }
      childProcess.stdout.removeListener("data", waitForListening);
      const { fields } = JSON.parse(readyMessage);
      if (fields == null) {
        return reject(new Error(`Unexpected data during initialization, "fields" are missing: ${data}`));
      }
      const { ip, port } = fields;
      if (ip == null || port == null) {
        return reject(
          new Error(
            `This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
Received data: ${data}`
          )
        );
      }
      resolve2({ childProcess, url: `http://${ip}:${port}` });
    };
    const errorListener = (error) => {
      this.#session = null;
      reject(new EngineStartError(String(error)));
      childProcess.removeListener("exit", exitListener);
      childProcess.kill();
    };
    childProcess.once("error", errorListener);
    const exitListener = (code, signal) => {
      this.#session = null;
      reject(new EngineStartError(`Query Engine exited with code ${code} and signal ${signal}`));
    };
    childProcess.once("exit", exitListener);
    childProcess.stdout.on("data", waitForListening);
    if (this.#options.debug) {
      childProcess.stderr.on("data", console.error.bind(console, "[Query Engine]"));
      childProcess.stdout.on("data", console.debug.bind(console, "[Query Engine]"));
    }
    return await this.#session;
  }
  async stop() {
    if (this.#session == null) {
      return;
    }
    const { childProcess } = await this.#session;
    const isStillRunning = childProcess.exitCode == null && childProcess.signalCode == null;
    if (!isStillRunning) {
      return;
    }
    this.#session = null;
    childProcess.kill();
    await once(childProcess, "exit");
  }
  async #getEngineBinaryPath() {
    if (this.#options.debug) {
      console.debug(`[Query Engine] getting engine commit hash...`);
    }
    const commitHash = await this.#getEngineCommitHash();
    if (this.#options.debug) {
      console.debug("[Query Engine] got engine commit hash", commitHash);
    }
    const cacheDirectoryPath = getEngineCacheDirPath(this.#options.clientVersion, commitHash);
    if (this.#options.debug) {
      console.debug("[Query Engine] cache directory path", cacheDirectoryPath);
    }
    await mkdir2(cacheDirectoryPath, { recursive: true });
    const { binaryTarget } = this.#options.platform;
    const extension = binaryTarget === "windows" ? ".exe" : "";
    const engineBinaryPath = join(cacheDirectoryPath, `query-engine-${binaryTarget}${extension}`);
    if (this.#options.debug) {
      console.debug("[Query Engine] binary path", engineBinaryPath);
    }
    const shouldDownloadEngine = PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD === "1" || await checkFileExists(engineBinaryPath) === false;
    if (shouldDownloadEngine) {
      await this.#downloadEngineBinary({ commitHash, extension, engineBinaryPath });
    }
    return engineBinaryPath;
  }
  async #getEngineCommitHash() {
    const response = await fetch(`https://registry.npmjs.org/@prisma/client/${this.#options.clientVersion}`);
    if (!response.ok) {
      throw new Error(`Couldn't fetch package.json from npm registry, status code: ${response.status}`);
    }
    const pkg = await response.json();
    const enginesVersion = pkg.devDependencies?.["@prisma/engines-version"];
    if (!enginesVersion) {
      throw new Error(`Couldn't find engines version in package.json`);
    }
    const commitHash = enginesVersion.split(".").at(-1);
    if (!commitHash) {
      throw new Error(`Couldn't find commit hash in engines version`);
    }
    return commitHash;
  }
  async #downloadEngineBinary(options) {
    const { commitHash, extension, engineBinaryPath } = options;
    const { binaryTarget } = this.#options.platform;
    const url2 = `https://binaries.prisma.sh/all_commits/${commitHash}/${binaryTarget}/query-engine${extension}.gz`;
    if (this.#options.debug) {
      console.debug("[Query Engine] downloading engine from url", url2);
    }
    const response = await fetch(url2);
    if (!response.ok) {
      throw new Error(`Couldn't download engine. URL: ${url2}, status code: ${response.status}`);
    }
    if (PRISMA_DEV_FORCE_NETWORK_DELAY_MS) {
      await setTimeout(Number(PRISMA_DEV_FORCE_NETWORK_DELAY_MS));
    }
    await writeBinaryFile(await response.arrayBuffer(), engineBinaryPath);
    if (this.#options.debug) {
      console.debug("[Query Engine] downloaded and saved at", engineBinaryPath);
    }
  }
  #sanitizeHeaders(headers) {
    const sanitizedHeaders = {};
    for (const [key, value] of Object.entries(headers)) {
      if (value != null) {
        sanitizedHeaders[key] = value;
      }
    }
    return sanitizedHeaders;
  }
  async #commitOrRollbackTransaction(transactionId, headers, action) {
    const { url: url2 } = await this.#session;
    const sanitizedHeaders = this.#sanitizeHeaders(headers);
    const response = await fetch(`${url2}/transaction/${transactionId}/${action}`, {
      headers: { ...sanitizedHeaders, "Content-Type": "application/json" },
      method: "POST"
    });
    if (!response.ok) {
      throw await EngineHttpError.fromResponse(response);
    }
    try {
      return await response.json();
    } catch {
      return {};
    }
  }
};
function handleEngineError(error, ctx) {
  console.error(error);
  if (error instanceof EngineStartError) {
    return ctx.json({ EngineNotStarted: { reason: { EngineStartupError: { logs: [], msg: error.message } } } }, 500);
  }
  if (error instanceof EngineHttpError) {
    return ctx.text(error.responseBody, error.statusCode);
  }
  return ctx.body(null, 500);
}
var EngineStartError = class extends Error {
  name = "EngineStartError";
};
var EngineHttpError = class _EngineHttpError extends Error {
  constructor(action, statusCode, responseBody) {
    super(`${action}: Query Engine response status ${statusCode}, body: ${responseBody}`);
    this.action = action;
    this.statusCode = statusCode;
    this.responseBody = responseBody;
  }
  name = "EngineHttpError";
  static async fromResponse(response) {
    const url2 = new URL(response.url);
    const responseBody = await response.text();
    return new _EngineHttpError(url2.pathname, response.status, responseBody);
  }
};

export {
  integer,
  minLength,
  minValue,
  parseJson,
  url,
  array,
  literal,
  looseObject,
  number,
  object,
  optional,
  string,
  union,
  pipe,
  safeParse,
  encodeAPIKey,
  apiKeyValidator,
  getDataDirPath,
  streamAsTextTo,
  readFileAsText,
  ensureDirectory,
  readDirectoryNames,
  withResolvers,
  y,
  Engine,
  handleEngineError
};
