/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 normalize_document_exports = {};
__export(normalize_document_exports, {
  prepareFlowSurfaceApplyBlueprintDocument: () => prepareFlowSurfaceApplyBlueprintDocument
});
module.exports = __toCommonJS(normalize_document_exports);
var import_lodash = __toESM(require("lodash"));
var import_errors = require("../errors");
var import_errors2 = require("../reaction/errors");
var import_service_utils = require("../service-utils");
var import_private_utils = require("./private-utils");
const APPLY_BLUEPRINT_REACTION_ITEM_ALLOWED_KEYS = ["type", "target", "rules", "expectedFingerprint"];
const APPLY_BLUEPRINT_REACTION_TYPES = [
  "setFieldValueRules",
  "setBlockLinkageRules",
  "setFieldLinkageRules",
  "setActionLinkageRules"
];
const APPLY_BLUEPRINT_REACTION_TYPE_SET = new Set(APPLY_BLUEPRINT_REACTION_TYPES);
const APPLY_BLUEPRINT_DEFAULT_COLLECTION_ALLOWED_KEYS = [
  "fieldGroups",
  "popups",
  "formBehavior",
  "formBehaviorDescriptionReview"
];
const APPLY_BLUEPRINT_DEFAULT_FIELD_GROUP_ALLOWED_KEYS = ["key", "title", "fields"];
const APPLY_BLUEPRINT_DEFAULT_FIELD_ALLOWED_KEYS = ["field", "titleField"];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_ALLOWED_KEYS = ["addNew", "edit"];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_SCENE_ALLOWED_KEYS = ["fields", "fieldLinkageRules"];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_FIELD_ALLOWED_KEYS = ["settings"];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_ALLOWED_KEYS = ["fields"];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_FIELD_ALLOWED_KEYS = ["decision", "reasonCode"];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_DECISIONS = [
  "implemented",
  "noUiBehavior",
  "unsupported"
];
const APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_REASON_CODES = [
  "no-ui-behavior",
  "ambiguous-description",
  "unsupported-cross-field-validation",
  "unsupported-association-filter",
  "workflow-or-ai-generation-out-of-scope",
  "ai-generated-content-out-of-scope"
];
const APPLY_BLUEPRINT_DEFAULT_POPUPS_ALLOWED_KEYS = ["view", "addNew", "edit", "associations"];
const APPLY_BLUEPRINT_DEFAULT_POPUP_ACTION_ALLOWED_KEYS = ["name", "description"];
const APPLY_BLUEPRINT_DEFAULT_POPUP_ASSOCIATION_ALLOWED_KEYS = ["view", "addNew", "edit"];
const APPLY_BLUEPRINT_DEFAULT_POPUP_ACTIONS = ["view", "addNew", "edit"];
function assertSupportedApplyBlueprintTopLevelKeys(input) {
  const allowedKeys = ["version", "mode", "target", "navigation", "page", "defaults", "assets", "tabs", "reaction"];
  const unsupportedKeys = Object.keys(input).filter((key) => !allowedKeys.includes(key));
  if (!unsupportedKeys.length) {
    return;
  }
  (0, import_errors.throwBadRequest)(
    `flowSurfaces applyBlueprint only accepts top-level keys ${allowedKeys.join(
      ", "
    )}; unsupported keys: ${unsupportedKeys.join(", ")}`
  );
}
function assertSupportedApplyBlueprintTarget(input) {
  if (import_lodash.default.isUndefined(input.target)) {
    return;
  }
  (0, import_private_utils.assertPlainObject)(input.target, "flowSurfaces applyBlueprint target");
  if (import_lodash.default.isPlainObject(input.target) && typeof input.target.mode !== "undefined") {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint target only accepts pageSchemaUid; use top-level mode instead`);
  }
  (0, import_private_utils.assertOnlyAllowedKeys)(input.target, "flowSurfaces applyBlueprint target", ["pageSchemaUid"]);
}
function normalizePage(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, "flowSurfaces applyBlueprint page");
  (0, import_private_utils.assertOnlyAllowedKeys)(input, "flowSurfaces applyBlueprint page", [
    "title",
    "icon",
    "documentTitle",
    "enableHeader",
    "enableTabs",
    "displayTitle"
  ]);
  const normalized = (0, import_service_utils.buildDefinedPayload)({
    title: (0, import_private_utils.readOptionalString)(input.title),
    icon: (0, import_private_utils.readOptionalString)(input.icon),
    documentTitle: (0, import_private_utils.readOptionalString)(input.documentTitle),
    enableHeader: (0, import_private_utils.readBoolean)(input.enableHeader, "flowSurfaces applyBlueprint page.enableHeader"),
    enableTabs: (0, import_private_utils.readBoolean)(input.enableTabs, "flowSurfaces applyBlueprint page.enableTabs"),
    displayTitle: (0, import_private_utils.readBoolean)(input.displayTitle, "flowSurfaces applyBlueprint page.displayTitle")
  });
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeNavigation(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, "flowSurfaces applyBlueprint navigation");
  (0, import_private_utils.assertOnlyAllowedKeys)(input, "flowSurfaces applyBlueprint navigation", ["group", "item"]);
  const normalized = (0, import_service_utils.buildDefinedPayload)({
    group: import_lodash.default.isUndefined(input.group) ? void 0 : (() => {
      (0, import_private_utils.assertPlainObject)(input.group, "flowSurfaces applyBlueprint navigation.group");
      (0, import_private_utils.assertOnlyAllowedKeys)(input.group, "flowSurfaces applyBlueprint navigation.group", [
        "routeId",
        "title",
        "icon",
        "tooltip",
        "hideInMenu"
      ]);
      const routeId = input.group.routeId;
      if (!import_lodash.default.isUndefined(routeId) && !import_lodash.default.isString(routeId) && !import_lodash.default.isNumber(routeId)) {
        (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint navigation.group.routeId must be a string or integer`);
      }
      if (!import_lodash.default.isUndefined(routeId)) {
        return {
          routeId
        };
      }
      const normalized2 = (0, import_service_utils.buildDefinedPayload)({
        title: (0, import_private_utils.readOptionalString)(input.group.title),
        icon: (0, import_private_utils.readOptionalString)(input.group.icon),
        tooltip: (0, import_private_utils.readOptionalString)(input.group.tooltip),
        hideInMenu: (0, import_private_utils.readBoolean)(input.group.hideInMenu, "flowSurfaces applyBlueprint navigation.group.hideInMenu")
      });
      if (!normalized2.title) {
        (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint navigation.group requires routeId or title`);
      }
      return normalized2;
    })(),
    item: import_lodash.default.isUndefined(input.item) ? void 0 : (() => {
      (0, import_private_utils.assertPlainObject)(input.item, "flowSurfaces applyBlueprint navigation.item");
      (0, import_private_utils.assertOnlyAllowedKeys)(input.item, "flowSurfaces applyBlueprint navigation.item", [
        "title",
        "icon",
        "tooltip",
        "hideInMenu"
      ]);
      return (0, import_service_utils.buildDefinedPayload)({
        title: (0, import_private_utils.readOptionalString)(input.item.title),
        icon: (0, import_private_utils.readOptionalString)(input.item.icon),
        tooltip: (0, import_private_utils.readOptionalString)(input.item.tooltip),
        hideInMenu: (0, import_private_utils.readBoolean)(input.item.hideInMenu, "flowSurfaces applyBlueprint navigation.item.hideInMenu")
      });
    })()
  });
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeDefaultFieldGroupField(input, context) {
  if (import_lodash.default.isString(input)) {
    return (0, import_private_utils.assertNonEmptyString)(input, context);
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_FIELD_ALLOWED_KEYS);
  return (0, import_service_utils.buildDefinedPayload)({
    field: (0, import_private_utils.assertNonEmptyString)(input.field, `${context}.field`),
    titleField: import_lodash.default.isUndefined(input.titleField) ? void 0 : (0, import_private_utils.assertNonEmptyString)(input.titleField, `${context}.titleField`)
  });
}
function normalizeDefaultFieldGroups(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  if (!Array.isArray(input) || !input.length) {
    (0, import_errors.throwBadRequest)(`${context} must be a non-empty array`);
  }
  return input.map((group, groupIndex) => {
    const groupContext = `${context}[${groupIndex}]`;
    (0, import_private_utils.assertPlainObject)(group, groupContext);
    (0, import_private_utils.assertOnlyAllowedKeys)(group, groupContext, APPLY_BLUEPRINT_DEFAULT_FIELD_GROUP_ALLOWED_KEYS);
    if (!Array.isArray(group.fields) || !group.fields.length) {
      (0, import_errors.throwBadRequest)(`${groupContext}.fields must be a non-empty array`);
    }
    return (0, import_service_utils.buildDefinedPayload)({
      key: (0, import_private_utils.readOptionalString)(group.key),
      title: (0, import_private_utils.assertNonEmptyString)(group.title, `${groupContext}.title`),
      fields: group.fields.map(
        (field, fieldIndex) => normalizeDefaultFieldGroupField(field, `${groupContext}.fields[${fieldIndex}]`)
      )
    });
  });
}
function normalizeDefaultPopupName(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_POPUP_ACTION_ALLOWED_KEYS);
  return {
    name: (0, import_private_utils.assertNonEmptyString)(input.name, `${context}.name`),
    description: (0, import_private_utils.assertNonEmptyString)(input.description, `${context}.description`)
  };
}
function normalizeDefaultPopupActionMap(input, context, allowedKeys) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, [...allowedKeys]);
  const normalized = (0, import_service_utils.buildDefinedPayload)(
    Object.fromEntries(
      APPLY_BLUEPRINT_DEFAULT_POPUP_ACTIONS.map((action) => [
        action,
        normalizeDefaultPopupName(input[action], `${context}.${action}`)
      ])
    )
  );
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeDefaultPopups(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  const actionMap = normalizeDefaultPopupActionMap(input, context, APPLY_BLUEPRINT_DEFAULT_POPUPS_ALLOWED_KEYS);
  const associationsInput = input.associations;
  const associations = import_lodash.default.isUndefined(associationsInput) ? void 0 : (() => {
    (0, import_private_utils.assertPlainObject)(associationsInput, `${context}.associations`);
    return Object.fromEntries(
      Object.entries(associationsInput).flatMap(([field, value]) => {
        const associationField = (0, import_private_utils.assertNonEmptyString)(field, `${context}.associations key`);
        const normalizedValue = normalizeDefaultPopupActionMap(
          value,
          `${context}.associations.${associationField}`,
          APPLY_BLUEPRINT_DEFAULT_POPUP_ASSOCIATION_ALLOWED_KEYS
        );
        return normalizedValue ? [[associationField, normalizedValue]] : [];
      })
    );
  })();
  const normalized = (0, import_service_utils.buildDefinedPayload)({
    ...actionMap,
    associations: associations && Object.keys(associations).length ? associations : void 0
  });
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeDefaultFormBehaviorField(input, context) {
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_FIELD_ALLOWED_KEYS);
  const settings = import_lodash.default.isUndefined(input.settings) ? void 0 : (() => {
    (0, import_private_utils.assertPlainObject)(input.settings, `${context}.settings`);
    if (!import_lodash.default.isUndefined(input.settings.rules) && !Array.isArray(input.settings.rules)) {
      (0, import_errors.throwBadRequest)(`${context}.settings.rules must be an array`);
    }
    return import_lodash.default.cloneDeep(input.settings);
  })();
  return (0, import_service_utils.buildDefinedPayload)({
    settings
  });
}
function normalizeDefaultFormBehaviorFields(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  const normalized = Object.fromEntries(
    Object.entries(input).map(([fieldPath, fieldConfig]) => {
      const normalizedFieldPath = (0, import_private_utils.assertNonEmptyString)(fieldPath, `${context} key`);
      return [normalizedFieldPath, normalizeDefaultFormBehaviorField(fieldConfig, `${context}.${normalizedFieldPath}`)];
    })
  );
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeDefaultFormBehaviorScene(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_SCENE_ALLOWED_KEYS);
  if (!import_lodash.default.isUndefined(input.fieldLinkageRules) && !Array.isArray(input.fieldLinkageRules)) {
    (0, import_errors.throwBadRequest)(`${context}.fieldLinkageRules must be an array`);
  }
  const normalized = (0, import_service_utils.buildDefinedPayload)({
    fields: normalizeDefaultFormBehaviorFields(input.fields, `${context}.fields`),
    fieldLinkageRules: Array.isArray(input.fieldLinkageRules) ? import_lodash.default.cloneDeep(input.fieldLinkageRules) : void 0
  });
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeDefaultFormBehavior(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_ALLOWED_KEYS);
  const normalized = (0, import_service_utils.buildDefinedPayload)({
    addNew: normalizeDefaultFormBehaviorScene(input.addNew, `${context}.addNew`),
    edit: normalizeDefaultFormBehaviorScene(input.edit, `${context}.edit`)
  });
  return Object.keys(normalized).length ? normalized : void 0;
}
function normalizeDefaultFormBehaviorDescriptionReview(input, context) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_ALLOWED_KEYS);
  (0, import_private_utils.assertPlainObject)(input.fields, `${context}.fields`);
  if (!Object.keys(input.fields).length) {
    (0, import_errors.throwBadRequest)(`flowSurfaces authoring ${context}.fields must be a non-empty object keyed by field path`);
  }
  const fields = {};
  Object.entries(input.fields).forEach(([fieldPath, value]) => {
    const normalizedFieldPath = (0, import_private_utils.assertNonEmptyString)(fieldPath, `${context}.fields`);
    if (import_lodash.default.isNull(value)) {
      fields[normalizedFieldPath] = null;
      return;
    }
    (0, import_private_utils.assertPlainObject)(value, `${context}.fields.${normalizedFieldPath}`);
    (0, import_private_utils.assertOnlyAllowedKeys)(
      value,
      `${context}.fields.${normalizedFieldPath}`,
      APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_FIELD_ALLOWED_KEYS
    );
    const decision = (0, import_private_utils.assertNonEmptyString)(value.decision, `${context}.fields.${normalizedFieldPath}.decision`);
    if (!APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_DECISIONS.includes(decision)) {
      (0, import_errors.throwBadRequest)(
        `flowSurfaces authoring ${context}.fields.${normalizedFieldPath}.decision must be one of ${APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_DECISIONS.join(
          ", "
        )}`
      );
    }
    const reasonCode = import_lodash.default.isUndefined(value.reasonCode) ? void 0 : (0, import_private_utils.assertNonEmptyString)(value.reasonCode, `${context}.fields.${normalizedFieldPath}.reasonCode`);
    if (!import_lodash.default.isUndefined(reasonCode) && !APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_REASON_CODES.includes(reasonCode)) {
      (0, import_errors.throwBadRequest)(
        `flowSurfaces authoring ${context}.fields.${normalizedFieldPath}.reasonCode must be one of ${APPLY_BLUEPRINT_DEFAULT_FORM_BEHAVIOR_DESCRIPTION_REVIEW_REASON_CODES.join(
          ", "
        )}`
      );
    }
    fields[normalizedFieldPath] = (0, import_service_utils.buildDefinedPayload)({
      decision,
      reasonCode
    });
  });
  return {
    fields
  };
}
function normalizeDefaultCollection(input, context) {
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, APPLY_BLUEPRINT_DEFAULT_COLLECTION_ALLOWED_KEYS);
  return (0, import_service_utils.buildDefinedPayload)({
    fieldGroups: normalizeDefaultFieldGroups(input.fieldGroups, `${context}.fieldGroups`),
    popups: normalizeDefaultPopups(input.popups, `${context}.popups`),
    formBehavior: normalizeDefaultFormBehavior(input.formBehavior, `${context}.formBehavior`),
    formBehaviorDescriptionReview: normalizeDefaultFormBehaviorDescriptionReview(
      input.formBehaviorDescriptionReview,
      `${context}.formBehaviorDescriptionReview`
    )
  });
}
function normalizeDefaultCollections(input, context, options = {}) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, context);
  return Object.fromEntries(
    Object.entries(input).map(([collectionName, collectionDefaults]) => {
      var _a;
      const normalizedCollectionName = (0, import_private_utils.assertNonEmptyString)(collectionName, `${context} key`);
      if ((_a = options.skipCollectionNames) == null ? void 0 : _a.has(normalizedCollectionName)) {
        return void 0;
      }
      return [
        normalizedCollectionName,
        normalizeDefaultCollection(collectionDefaults, `${context}.${normalizedCollectionName}`)
      ];
    }).filter((entry) => !import_lodash.default.isUndefined(entry))
  );
}
function getMainDefaultDataSourceCollectionNames(input) {
  const names = /* @__PURE__ */ new Set();
  if (!import_lodash.default.isPlainObject(input == null ? void 0 : input.dataSources)) {
    return names;
  }
  Object.entries(input.dataSources).forEach(([dataSourceKey, dataSourceDefaults]) => {
    if (String(dataSourceKey || "").trim() !== "main") {
      return;
    }
    if (!import_lodash.default.isPlainObject(dataSourceDefaults)) {
      return;
    }
    const collections = dataSourceDefaults.collections;
    if (!import_lodash.default.isPlainObject(collections)) {
      return;
    }
    Object.keys(collections).forEach((collectionName) => {
      const normalizedCollectionName = String(collectionName || "").trim();
      if (normalizedCollectionName) {
        names.add(normalizedCollectionName);
      }
    });
  });
  return names;
}
function normalizeDefaultDataSource(input, context) {
  (0, import_private_utils.assertPlainObject)(input, context);
  (0, import_private_utils.assertOnlyAllowedKeys)(input, context, ["collections"]);
  return (0, import_service_utils.buildDefinedPayload)({
    collections: normalizeDefaultCollections(input.collections, `${context}.collections`)
  });
}
function normalizeDefaultDataSources(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, "flowSurfaces applyBlueprint defaults.dataSources");
  return Object.fromEntries(
    Object.entries(input).map(([dataSourceKey, dataSourceDefaults]) => {
      const normalizedDataSourceKey = (0, import_private_utils.assertNonEmptyString)(
        dataSourceKey,
        "flowSurfaces applyBlueprint defaults.dataSources key"
      );
      return [
        normalizedDataSourceKey,
        normalizeDefaultDataSource(
          dataSourceDefaults,
          `flowSurfaces applyBlueprint defaults.dataSources.${normalizedDataSourceKey}`
        )
      ];
    })
  );
}
function normalizeDefaults(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, "flowSurfaces applyBlueprint defaults");
  (0, import_private_utils.assertOnlyAllowedKeys)(input, "flowSurfaces applyBlueprint defaults", ["collections", "dataSources"]);
  return (0, import_service_utils.buildDefinedPayload)({
    collections: normalizeDefaultCollections(input.collections, "flowSurfaces applyBlueprint defaults.collections", {
      skipCollectionNames: getMainDefaultDataSourceCollectionNames(input)
    }),
    dataSources: normalizeDefaultDataSources(input.dataSources)
  });
}
function normalizeTabs(input) {
  const seenTabKeys = /* @__PURE__ */ new Set();
  return input.map((tab, index) => {
    (0, import_private_utils.assertPlainObject)(tab, `flowSurfaces applyBlueprint tabs[${index}]`);
    (0, import_private_utils.assertOnlyAllowedKeys)(tab, `flowSurfaces applyBlueprint tabs[${index}]`, [
      "key",
      "title",
      "icon",
      "documentTitle",
      "blocks",
      "layout"
    ]);
    if (!Array.isArray(tab.blocks) || !tab.blocks.length) {
      (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint tabs[${index}].blocks must be a non-empty array`);
    }
    const explicitKey = (0, import_private_utils.readString)(tab.key);
    return {
      key: (0, import_private_utils.normalizeTabLocalKey)(tab.key, (0, import_private_utils.readString)(tab.title) || `tab_${index + 1}`, index, seenTabKeys, {
        explicit: !!explicitKey
      }),
      title: (0, import_private_utils.readOptionalString)(tab.title),
      icon: (0, import_private_utils.readOptionalString)(tab.icon),
      documentTitle: (0, import_private_utils.readOptionalString)(tab.documentTitle),
      blocks: import_lodash.default.cloneDeep(tab.blocks),
      layout: (0, import_private_utils.cloneOptionalPlainObject)(tab.layout, `flowSurfaces applyBlueprint tabs[${index}].layout`)
    };
  });
}
function normalizeReaction(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  (0, import_private_utils.assertPlainObject)(input, "flowSurfaces applyBlueprint reaction");
  (0, import_private_utils.assertOnlyAllowedKeys)(input, "flowSurfaces applyBlueprint reaction", ["items"]);
  if (!Array.isArray(input.items)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint reaction.items must be an array`);
  }
  const seenSlots = /* @__PURE__ */ new Set();
  return {
    items: input.items.map((item, index) => {
      const context = `flowSurfaces applyBlueprint reaction.items[${index}]`;
      (0, import_private_utils.assertPlainObject)(item, context);
      (0, import_private_utils.assertOnlyAllowedKeys)(item, context, [...APPLY_BLUEPRINT_REACTION_ITEM_ALLOWED_KEYS]);
      const type = (0, import_private_utils.assertNonEmptyString)(item.type, `${context}.type`);
      if (!APPLY_BLUEPRINT_REACTION_TYPE_SET.has(type)) {
        (0, import_errors.throwBadRequest)(
          `${context}.type '${type}' is unsupported; supported types: ${APPLY_BLUEPRINT_REACTION_TYPES.join(", ")}`
        );
      }
      const target = (0, import_service_utils.normalizeFlowSurfaceComposeKey)(
        (0, import_private_utils.assertNonEmptyString)(item.target, `${context}.target`),
        `${context}.target`
      );
      if (!Array.isArray(item.rules)) {
        (0, import_errors.throwBadRequest)(`${context}.rules must be an array`);
      }
      const slotKey = `${type}::${target}`;
      if (seenSlots.has(slotKey)) {
        (0, import_errors.throwBadRequest)(
          `${context} duplicates reaction slot '${type}' for target '${target}'`,
          import_errors2.FLOW_SURFACE_REACTION_DUPLICATE_SLOT
        );
      }
      seenSlots.add(slotKey);
      return (0, import_service_utils.buildDefinedPayload)({
        type,
        target,
        rules: import_lodash.default.cloneDeep(item.rules),
        expectedFingerprint: import_lodash.default.isUndefined(item.expectedFingerprint) ? void 0 : (0, import_private_utils.assertNonEmptyString)(item.expectedFingerprint, `${context}.expectedFingerprint`)
      });
    })
  };
}
function prepareFlowSurfaceApplyBlueprintDocument(input) {
  var _a, _b;
  (0, import_private_utils.assertPlainObject)(input, "flowSurfaces applyBlueprint payload");
  assertSupportedApplyBlueprintTopLevelKeys(input);
  assertSupportedApplyBlueprintTarget(input);
  const version = import_lodash.default.isUndefined(input.version) ? "1" : (0, import_private_utils.assertNonEmptyString)(input.version, "flowSurfaces applyBlueprint version");
  if (version !== "1") {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint version '${version}' is not supported`);
  }
  const mode = (0, import_private_utils.assertNonEmptyString)(input.mode, "flowSurfaces applyBlueprint mode");
  if (mode !== "create" && mode !== "replace") {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint mode must be 'create' or 'replace'`);
  }
  if (!Array.isArray(input.tabs) || !input.tabs.length) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint tabs must be a non-empty array`);
  }
  const page = normalizePage(input.page);
  const navigation = normalizeNavigation(input.navigation);
  const defaults = normalizeDefaults(input.defaults);
  if (mode === "create" && !import_lodash.default.isUndefined(input.target)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint create mode does not accept target`);
  }
  if (mode === "replace" && !import_lodash.default.isPlainObject(input.target)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint replace mode requires target.pageSchemaUid`);
  }
  if (mode === "replace" && navigation) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint replace mode does not accept navigation`);
  }
  const target = mode === "replace" ? {
    pageSchemaUid: (0, import_private_utils.assertNonEmptyString)(
      input.target.pageSchemaUid,
      "flowSurfaces applyBlueprint target.pageSchemaUid"
    )
  } : void 0;
  if (!import_lodash.default.isUndefined(input.assets)) {
    (0, import_private_utils.assertPlainObject)(input.assets, "flowSurfaces applyBlueprint assets");
    (0, import_private_utils.assertOnlyAllowedKeys)(input.assets, "flowSurfaces applyBlueprint assets", ["scripts", "charts"]);
  }
  const assets = {
    scripts: (0, import_private_utils.normalizeAssetRegistry)((_a = input.assets) == null ? void 0 : _a.scripts, "flowSurfaces applyBlueprint assets.scripts"),
    charts: (0, import_private_utils.normalizeAssetRegistry)((_b = input.assets) == null ? void 0 : _b.charts, "flowSurfaces applyBlueprint assets.charts")
  };
  const tabs = normalizeTabs(input.tabs);
  const reaction = normalizeReaction(input.reaction);
  if (tabs.length > 1 && (page == null ? void 0 : page.enableTabs) === false) {
    (0, import_errors.throwBadRequest)(`flowSurfaces applyBlueprint page.enableTabs cannot be false when tabs.length > 1`);
  }
  const normalizedPage = tabs.length === 1 ? {
    ...page || {},
    enableTabs: false
  } : page;
  return {
    version: "1",
    mode,
    ...target ? { target } : {},
    ...navigation ? { navigation } : {},
    ...normalizedPage ? { page: normalizedPage } : {},
    ...defaults ? { defaults } : {},
    tabs,
    assets,
    ...reaction ? { reaction } : {}
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  prepareFlowSurfaceApplyBlueprintDocument
});
