"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 fragment_exports = {};
__export(fragment_exports, {
  fragment: () => fragment
});
module.exports = __toCommonJS(fragment_exports);
var import_deepEquals = require("../../lib/deepEquals");
var import_types = require("../../lib/types");
var import_utils = require("../utils");
const fragment = (cache) => (0, import_utils.documentPlugin)(import_types.ArtifactKind.Fragment, function() {
  let subscriptionSpec = null;
  let lastReference = null;
  return {
    start(ctx, { next, resolve, variablesChanged, marshalVariables }) {
      if (!ctx.stuff.parentID) {
        return next(ctx);
      }
      const currentReference = {
        parent: ctx.stuff.parentID,
        variables: marshalVariables(ctx)
      };
      if (!ctx.cacheParams?.disableSubscriptions && (!(0, import_deepEquals.deepEquals)(lastReference, currentReference) || variablesChanged(ctx))) {
        if (subscriptionSpec) {
          cache.unsubscribe(subscriptionSpec, subscriptionSpec.variables?.() || {});
        }
        const variables = marshalVariables(ctx);
        subscriptionSpec = {
          rootType: ctx.artifact.rootType,
          selection: ctx.artifact.selection,
          variables: () => variables,
          parentID: ctx.stuff.parentID,
          set: (newValue) => {
            resolve(ctx, {
              data: newValue,
              errors: null,
              fetching: false,
              partial: false,
              stale: false,
              source: import_types.DataSource.Cache,
              variables
            });
          }
        };
        cache.subscribe(subscriptionSpec, variables);
        lastReference = currentReference;
      }
      next(ctx);
    },
    cleanup() {
      if (subscriptionSpec) {
        cache.unsubscribe(subscriptionSpec, subscriptionSpec.variables?.());
      }
    }
  };
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  fragment
});
