"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.processRawFragmentValue = processRawFragmentValue;
exports.processRawValue = processRawValue;
exports.processRawValueWithoutValidation = processRawValueWithoutValidation;
var _transforms = require("@atlaskit/adf-utils/transforms");
var _model = require("@atlaskit/editor-prosemirror/model");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
var _analytics = require("../analytics");
var _utilities = require("../nesting/utilities");
var _privacyFilter = require("./filter/privacy-filter");
var _trackUnsupportedContent = require("./track-unsupported-content");
var _validateUsingSpec = require("./validate-using-spec");
var transformNestedTablesWithAnalytics = function transformNestedTablesWithAnalytics(node, dispatchAnalyticsEvent) {
  try {
    var _transformNestedTable = (0, _transforms.transformNestedTablesIncomingDocument)(node),
      transformedAdf = _transformNestedTable.transformedAdf,
      isTransformed = _transformNestedTable.isTransformed;
    if ((0, _platformFeatureFlags.fg)('platform_editor_show_diff_scroll_navigation')) {
      if (isTransformed) {
        if (dispatchAnalyticsEvent) {
          dispatchAnalyticsEvent({
            action: _analytics.ACTION.NESTED_TABLE_TRANSFORMED,
            actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
            eventType: _analytics.EVENT_TYPE.OPERATIONAL
          });
        }
        return {
          transformedAdf: transformedAdf,
          isTransformed: isTransformed
        };
      }
    } else {
      if (isTransformed && dispatchAnalyticsEvent) {
        dispatchAnalyticsEvent({
          action: _analytics.ACTION.NESTED_TABLE_TRANSFORMED,
          actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
          eventType: _analytics.EVENT_TYPE.OPERATIONAL
        });
        return {
          transformedAdf: transformedAdf,
          isTransformed: isTransformed
        };
      }
    }
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error('Failed to transform one or more nested tables in the document');
    if (dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.DOCUMENT_PROCESSING_ERROR,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL,
        attributes: {
          errorMessage: "".concat(e instanceof Error && e.name === 'NodeNestingTransformError' ? 'NodeNestingTransformError - Failed to transform one or more nested tables' : undefined)
        }
      });
    }
  }
  return {
    transformedAdf: node,
    isTransformed: false
  };
};
function processRawValueWithoutValidation(schema, value, dispatchAnalyticsEvent) {
  if (!value) {
    return;
  }
  var node;
  if (typeof value === 'string') {
    try {
      node = JSON.parse(value);
    } catch (_unused) {
      // eslint-disable-next-line no-console
      console.error("Error processing value: ".concat(value, " isn't a valid JSON"));
      return;
    }
  } else {
    node = value;
  }

  // Convert nested-table extensions into nested tables
  var _transformNestedTable2 = transformNestedTablesWithAnalytics(node, dispatchAnalyticsEvent),
    transformedAdf = _transformNestedTable2.transformedAdf;
  var result = (0, _transforms.syncBlockFallbackTransform)(schema, transformedAdf);
  if (result.isTransformed && result.transformedAdf) {
    transformedAdf = result.transformedAdf;
  }
  return _model.Node.fromJSON(schema, transformedAdf);
}
function processRawValue(schema, value, providerFactory, sanitizePrivateContent, contentTransformer, dispatchAnalyticsEvent) {
  if (!value) {
    return;
  }
  var node;
  if (typeof value === 'string') {
    try {
      if (contentTransformer) {
        var doc = contentTransformer.parse(value);
        node = doc.toJSON();
      } else {
        node = JSON.parse(value);
      }
    } catch (_unused2) {
      // eslint-disable-next-line no-console
      console.error("Error processing value: ".concat(value, " isn't a valid JSON"));
      return;
    }
  } else {
    node = value;
  }
  if (Array.isArray(node)) {
    // eslint-disable-next-line no-console
    console.error("Error processing value: ".concat(node, " is an array, but it must be an object."));
    return;
  }
  try {
    // ProseMirror always require a child under doc
    if (node.type === 'doc') {
      if (Array.isArray(node.content) && node.content.length === 0) {
        node.content.push({
          type: 'paragraph',
          content: []
        });
      }
      // Just making sure doc is always valid
      if (!node.version) {
        node.version = 1;
      }
    }
    if (contentTransformer) {
      return _model.Node.fromJSON(schema, node);
    }

    // link mark on mediaSingle is deprecated, need to move link mark to child media node
    // https://product-fabric.atlassian.net/browse/ED-14043
    var _transformMediaLinkMa = (0, _transforms.transformMediaLinkMarks)(node),
      transformedAdf = _transformMediaLinkMa.transformedAdf,
      isTransformed = _transformMediaLinkMa.isTransformed;
    if (isTransformed && dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.MEDIA_LINK_TRANSFORMED,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL
      });
    }
    if ((0, _platformFeatureFlags.fg)('platform_editor_transform_invalid_media_width')) {
      // Fix mediaSingle width issues
      var _transformMediaSingle = (0, _transforms.transformMediaSingleWidth)(transformedAdf);
      transformedAdf = _transformMediaSingle.transformedAdf;
      isTransformed = _transformMediaSingle.isTransformed;
      if (isTransformed && dispatchAnalyticsEvent) {
        dispatchAnalyticsEvent({
          action: _analytics.ACTION.MEDIA_SINGLE_WIDTH_TRANSFORMED,
          actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
          eventType: _analytics.EVENT_TYPE.OPERATIONAL
        });
      }
    }

    // See: HOT-97965 https://product-fabric.atlassian.net/browse/ED-14400
    // We declared in code mark spec that links and marks should not co-exist on
    // text nodes. This util strips code marks from bad text nodes and preserves links.
    // Otherwise, prosemirror will try to repair the invalid document by stripping links
    // and preserving code marks during content changes.
    var _transformTextLinkCod = (0, _transforms.transformTextLinkCodeMarks)(transformedAdf);
    transformedAdf = _transformTextLinkCod.transformedAdf;
    isTransformed = _transformTextLinkCod.isTransformed;
    if (isTransformed && dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.TEXT_LINK_MARK_TRANSFORMED,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL
      });
    }
    var discardedMarks = [];
    var _transformDedupeMarks = (0, _transforms.transformDedupeMarks)(transformedAdf);
    transformedAdf = _transformDedupeMarks.transformedAdf;
    isTransformed = _transformDedupeMarks.isTransformed;
    discardedMarks = _transformDedupeMarks.discardedMarks;
    if (isTransformed && dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.DEDUPE_MARKS_TRANSFORMED_V2,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL,
        attributes: {
          /** UGC WARNING
           *
           * DO NOT include the `mark` attributes inside, we map here to only
           * extract the mark type as that is the only non-UGC safe information
           * that we can add to event-attributes
           *
           */
          discardedMarkTypes: discardedMarks.map(function (mark) {
            return mark.type;
          })
        }
      });
    }
    var _transformNodesMissin = (0, _transforms.transformNodesMissingContent)(transformedAdf);
    transformedAdf = _transformNodesMissin.transformedAdf;
    isTransformed = _transformNodesMissin.isTransformed;
    if (isTransformed && dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.NODES_MISSING_CONTENT_TRANSFORMED,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL
      });
    }
    var _transformIndentation = (0, _transforms.transformIndentationMarks)(transformedAdf);
    transformedAdf = _transformIndentation.transformedAdf;
    isTransformed = _transformIndentation.isTransformed;
    if (isTransformed && dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.INDENTATION_MARKS_TRANSFORMED,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL
      });
    }
    var _transformInvalidMedi = (0, _transforms.transformInvalidMediaContent)(transformedAdf);
    transformedAdf = _transformInvalidMedi.transformedAdf;
    isTransformed = _transformInvalidMedi.isTransformed;
    if (isTransformed && dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.INVALID_MEDIA_CONTENT_TRANSFORMED,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL
      });
    }
    if (dispatchAnalyticsEvent) {
      var _transformedAdf$conte;
      var hasSingleColumnLayout = (_transformedAdf$conte = transformedAdf.content) === null || _transformedAdf$conte === void 0 ? void 0 : _transformedAdf$conte.some(function (node) {
        var _node$content;
        return node && node.type === 'layoutSection' && ((_node$content = node.content) === null || _node$content === void 0 ? void 0 : _node$content.length) === 1;
      });
      if (hasSingleColumnLayout) {
        dispatchAnalyticsEvent({
          action: _analytics.ACTION.SINGLE_COL_LAYOUT_DETECTED,
          actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
          eventType: _analytics.EVENT_TYPE.OPERATIONAL
        });
      }
    }

    // Validate ADF first before converting nested-table extensions into nested tables
    // This matches the renderer's behavior in render-document.ts
    var allowNestedTables = (0, _utilities.isNestedTablesSupported)(schema);
    var allowTableInPanel = (0, _utilities.isPanelNestingTableSupported)(schema);
    var validateADFEntityOptions = allowNestedTables || allowTableInPanel ? {
      allowNestedTables: allowNestedTables || undefined,
      allowTableInPanel: allowTableInPanel || undefined
    } : undefined;
    var entity = (0, _validateUsingSpec.validateADFEntity)(schema, transformedAdf || node, dispatchAnalyticsEvent, validateADFEntityOptions);

    // Convert nested-table extensions into nested tables
    var _transformNestedTable3 = transformNestedTablesWithAnalytics(entity, dispatchAnalyticsEvent);
    transformedAdf = _transformNestedTable3.transformedAdf;
    entity = transformedAdf;
    var newEntity = maySanitizePrivateContent(entity, providerFactory, sanitizePrivateContent);
    var parsedDoc = _model.Node.fromJSON(schema, newEntity);

    // throws an error if the document is invalid
    try {
      parsedDoc.check();
    } catch (err) {
      if (dispatchAnalyticsEvent) {
        dispatchAnalyticsEvent({
          action: _analytics.ACTION.INVALID_PROSEMIRROR_DOCUMENT,
          actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
          eventType: _analytics.EVENT_TYPE.OPERATIONAL
        });
      }
      throw err;
    }
    if (dispatchAnalyticsEvent) {
      (0, _trackUnsupportedContent.findAndTrackUnsupportedContentNodes)(parsedDoc, schema, dispatchAnalyticsEvent);
    }
    return parsedDoc;
  } catch (e) {
    if (dispatchAnalyticsEvent) {
      dispatchAnalyticsEvent({
        action: _analytics.ACTION.DOCUMENT_PROCESSING_ERROR,
        actionSubject: _analytics.ACTION_SUBJECT.EDITOR,
        eventType: _analytics.EVENT_TYPE.OPERATIONAL
      });
    }

    // eslint-disable-next-line no-console
    console.error("Error processing document:\n".concat(e instanceof Error ? e.message : String(e), "\n\n"), JSON.stringify(node));
    if (isProseMirrorSchemaCheckError(e)) {
      throw e;
    }
    return;
  }
}
function processRawFragmentValue(schema, value, providerFactory, sanitizePrivateContent, contentTransformer, dispatchAnalyticsEvent) {
  if (!value) {
    return;
  }
  var adfEntities = value.map(function (item) {
    return processRawValue(schema, item, providerFactory, sanitizePrivateContent, contentTransformer, dispatchAnalyticsEvent);
  }).filter(function (item) {
    return Boolean(item);
  });
  if (adfEntities.length === 0) {
    return;
  }
  return _model.Fragment.from(adfEntities);
}
function isProseMirrorSchemaCheckError(error) {
  return error instanceof RangeError && (
  // Ignored via go/ees005
  // eslint-disable-next-line require-unicode-regexp
  !!error.message.match(/^Invalid collection of marks for node/) ||
  // Ignored via go/ees005
  // eslint-disable-next-line require-unicode-regexp
  !!error.message.match(/^Invalid content for node/));
}
var maySanitizePrivateContent = function maySanitizePrivateContent(entity, providerFactory, sanitizePrivateContent) {
  if (sanitizePrivateContent && providerFactory) {
    return (0, _privacyFilter.sanitizeNodeForPrivacy)(entity, providerFactory);
  }
  return entity;
};