"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var chunk_LZ2DWYUY_exports = {};
__export(chunk_LZ2DWYUY_exports, {
  SchemaEngineWasm: () => SchemaEngineWasm
});
module.exports = __toCommonJS(chunk_LZ2DWYUY_exports);
var import_chunk_6DDIA3ZD = require("./chunk-6DDIA3ZD.js");
var import_chunk_PEUHUCS4 = require("./chunk-PEUHUCS4.js");
var import_chunk_SKRR5WT4 = require("./chunk-SKRR5WT4.js");
var import_debug = __toESM(require("@prisma/debug"));
var import_internals = require("@prisma/internals");
var debugStderr = (0, import_debug.default)("prisma:schemaEngine:wasm:stderr");
var debugStdout = (0, import_debug.default)("prisma:schemaEngine:wasm:stdout");
var SchemaEngineWasm = class _SchemaEngineWasm {
  engine;
  errorRegistry;
  // TODO: forward enabled preview features to the Wasm engine
  enabledPreviewFeatures;
  // `isRunning` is set to true when the engine is initialized, and set to false when the engine is stopped
  isRunning = false;
  constructor({ debug, enabledPreviewFeatures, engine, errorRegistry }) {
    this.enabledPreviewFeatures = enabledPreviewFeatures;
    if (debug) {
      import_debug.default.enable("prisma:schemaEngine*");
    }
    this.engine = engine;
    this.errorRegistry = errorRegistry;
  }
  static async setup({ adapter, schemaContext, ...rest }) {
    const debug = (arg) => {
      debugStderr(arg);
    };
    const datamodels = schemaContext?.schemaFiles;
    const engine = await import_internals.wasmSchemaEngineLoader.loadSchemaEngine(
      {
        datamodels
      },
      debug,
      adapter
    );
    return new _SchemaEngineWasm({ ...rest, engine, errorRegistry: adapter.errorRegistry });
  }
  async runCommand(command, input) {
    if (process.env.FORCE_PANIC_SCHEMA_ENGINE && command !== "debugPanic") return this.debugPanic();
    this.isRunning = true;
    debugStdout("[%s] input: %o", command, input);
    try {
      const result = await this.engine[command](input);
      debugStdout("[%s] result: %o", command, result);
      return result;
    } catch (error) {
      const e = error;
      debugStdout("[%s] error: %o", command, e);
      if ((0, import_internals.isWasmPanic)(e)) {
        debugStdout("[schema-engine] it is a Wasm panic");
        const { message, stack } = (0, import_internals.getWasmError)(e);
        throw new import_internals.RustPanic(serializePanic(message), stack, command, import_internals.ErrorArea.LIFT_CLI);
      } else if ("code" in error) {
        throw new import_chunk_6DDIA3ZD.EngineError((0, import_chunk_SKRR5WT4.red)(`${error.code}

${(0, import_internals.relativizePathInPSLError)(error.message)}
`), error.code);
      } else {
        (0, import_internals.assertAlways)(
          e.name === "SchemaConnectorError",
          "Malformed error received from the engine, expected SchemaConnectorError"
        );
        debugStderr("e.message", e.message);
        debugStderr("e.cause", e.cause);
        debugStderr("e.stack", e.stack);
        throw e;
      }
    }
  }
  /**
   * Apply the migrations from the migrations directory to the database.
   * This is the command behind prisma migrate deploy.
   */
  applyMigrations(input) {
    return this.runCommand("applyMigrations", input);
  }
  /**
   * Create the next migration in the migrations history.
   * If draft is false and there are no unexecutable steps, it will also apply the newly created migration.
   * Note: This will use the shadow database on the connectors where we need one.
   */
  createMigration(input) {
    return this.runCommand("createMigration", input);
  }
  /**
   * Execute a database script directly on the specified live database.
   * Note that this may not be defined on all connectors.
   */
  async dbExecute(input) {
    await this.runCommand("dbExecute", input);
    return null;
  }
  /**
   * Make the Schema engine panic. Only useful to test client error handling.
   */
  async debugPanic() {
    await this.runCommand("debugPanic", void 0);
    return null;
  }
  /**
   * The method called at the beginning of migrate dev to decide the course of action,
   * based on the current state of the workspace.
   * It acts as a wrapper around diagnoseMigrationHistory.
   * Its role is to interpret the diagnostic output,
   * and translate it to a concrete action to be performed by the CLI.
   */
  devDiagnostic(input) {
    return this.runCommand("devDiagnostic", input);
  }
  /**
   * Read the contents of the migrations directory and the migrations table, and returns their relative statuses.
   * At this stage, the Schema engine only reads,
   * it does not write to the database nor the migrations directory, nor does it use a shadow database.
   */
  diagnoseMigrationHistory(input) {
    return this.runCommand("diagnoseMigrationHistory", input);
  }
  /**
   * Make sure the Schema engine can connect to the database from the Prisma schema.
   */
  async ensureConnectionValidity(input) {
    await this.runCommand("ensureConnectionValidity", input);
  }
  /**
   * Development command for migrations.
   * Evaluate the data loss induced by the next migration the engine would generate on the main database.
   */
  evaluateDataLoss(input) {
    return this.runCommand("evaluateDataLoss", input);
  }
  /**
   * Get the database version for error reporting.
   * If no argument is given, the version of the database associated to the Prisma schema provided
   * in the constructor will be returned.
   */
  getDatabaseVersion(input) {
    return this.runCommand("version", input);
  }
  /**
   * Given a Prisma schema, introspect the database definitions and update the schema with the results.
   * `compositeTypeDepth` is optional, and only required for MongoDB.
   */
  async introspect({
    schema,
    force = false,
    baseDirectoryPath,
    viewsDirectoryPath,
    compositeTypeDepth = -1,
    namespaces
  }) {
    const introspectResult = await this.runCommand("introspect", {
      schema,
      force,
      compositeTypeDepth,
      namespaces: namespaces ?? null,
      baseDirectoryPath
    });
    const { views } = introspectResult;
    if (views) {
      await (0, import_chunk_PEUHUCS4.handleViewsIO)({ views, viewsDirectoryPath });
    }
    return introspectResult;
  }
  /**
   * Compares two databases schemas from two arbitrary sources,
   * and display the difference as either a human-readable summary,
   * or an executable script that can be passed to dbExecute.
   * Connection to a shadow database is only necessary when either the from or the to params is a migrations directory.
   * Diffs have a direction. Which source is from and which is to matters.
   * The resulting diff should be thought of as a migration from the schema in `args.from` to the schema in `args.to`.
   * By default, we output a human-readable diff. If you want an executable script, pass the "script": true param.
   */
  async migrateDiff(input) {
    const { stdout, ...rest } = await this.runCommand("diff", input);
    if (stdout) {
      process.stdout.write(stdout);
    }
    return rest;
  }
  /**
   * Mark a migration as applied in the migrations table.
   * There are two possible outcomes:
   * - The migration is already in the table, but in a failed state. In this case, we will mark it as rolled back, then create a new entry.
   * - The migration is not in the table. We will create a new entry in the migrations table. The started_at and finished_at will be the same.
   * If it is already applied, we return a user-facing error.
   */
  async markMigrationApplied(input) {
    await this.runCommand("markMigrationApplied", input);
  }
  /**
   * Mark an existing failed migration as rolled back in the migrations table. It will still be there, but ignored for all purposes except as audit trail.
   */
  async markMigrationRolledBack(input) {
    await this.runCommand("markMigrationRolledBack", input);
  }
  /**
   * Try to make the database empty: no data and no schema.
   * On most connectors, this is implemented by dropping and recreating the database.
   * If that fails (most likely because of insufficient permissions),
   * the engine attempts a “best effort reset” by inspecting the contents of the database and dropping them individually.
   * Drop and recreate the database. The migrations will not be applied, as it would overlap with applyMigrations.
   */
  async reset(input) {
    await this.runCommand("reset", input);
  }
  /**
   * The command behind db push.
   */
  schemaPush(input) {
    return this.runCommand("schemaPush", input);
  }
  /**
   * SQL introspection that powers TypedSQL feature
   * @param args
   * @returns
   */
  introspectSql(input) {
    return this.runCommand("introspectSql", input);
  }
  /**
   * Stop the engine.
   */
  stop() {
    this.isRunning = false;
    this.engine.free();
    return Promise.resolve();
  }
};
function serializePanic(log) {
  return `${(0, import_chunk_SKRR5WT4.red)((0, import_chunk_SKRR5WT4.bold)("Error in Schema engine.\nReason: "))}${log}
`;
}
