"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var mutation_exports = {};
__export(mutation_exports, {
  mutation: () => mutation
});
module.exports = __toCommonJS(mutation_exports);
var import_scalars = require("../../lib/scalars");
var import_types = require("../../lib/types");
var import_utils = require("../utils");
const mutation = (cache) => (0, import_utils.documentPlugin)(import_types.ArtifactKind.Mutation, () => {
  return {
    async start(ctx, { next, marshalVariables }) {
      const layerOptimistic = cache._internal_unstable.storage.createLayer(true);
      const optimisticResponse = ctx.stuff.optimisticResponse;
      let toNotify = [];
      if (optimisticResponse) {
        toNotify = cache.write({
          selection: ctx.artifact.selection,
          data: await (0, import_scalars.marshalSelection)({
            selection: ctx.artifact.selection,
            data: optimisticResponse
          }),
          variables: marshalVariables(ctx),
          layer: layerOptimistic.id
        });
      }
      ctx.cacheParams = {
        ...ctx.cacheParams,
        layer: layerOptimistic,
        notifySubscribers: toNotify,
        forceNotify: true
      };
      next(ctx);
    },
    afterNetwork(ctx, { resolve }) {
      if (ctx.cacheParams?.layer) {
        cache.clearLayer(ctx.cacheParams.layer.id);
      }
      resolve(ctx);
    },
    end(ctx, { resolve, value }) {
      const hasErrors = value.errors && value.errors.length > 0;
      if (hasErrors) {
        if (ctx.cacheParams?.layer) {
          cache.clearLayer(ctx.cacheParams.layer.id);
        }
      }
      if (ctx.cacheParams?.layer) {
        cache._internal_unstable.storage.resolveLayer(ctx.cacheParams.layer.id);
      }
      resolve(ctx);
    },
    catch(ctx, { error }) {
      if (ctx.cacheParams?.layer) {
        const { layer } = ctx.cacheParams;
        cache.clearLayer(layer.id);
        cache._internal_unstable.storage.resolveLayer(layer.id);
      }
      throw error;
    }
  };
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  mutation
});
