/**
 * 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 service_utils_exports = {};
__export(service_utils_exports, {
  assertFlowSurfaceComposeUniqueKeys: () => assertFlowSurfaceComposeUniqueKeys,
  assertSupportedSimpleChanges: () => assertSupportedSimpleChanges,
  buildBlockCardSettingsFromSemanticChanges: () => buildBlockCardSettingsFromSemanticChanges,
  buildBlockTitleDescriptionFromSemanticChanges: () => buildBlockTitleDescriptionFromSemanticChanges,
  buildChartCardSettingsFromSemanticChanges: () => buildChartCardSettingsFromSemanticChanges,
  buildDefaultFieldState: () => buildDefaultFieldState,
  buildDefinedPayload: () => buildDefinedPayload,
  buildPopupTabTree: () => buildPopupTabTree,
  ensureNoDirectActionScopeKey: () => ensureNoDirectActionScopeKey,
  ensureNoRawDirectAddKeys: () => ensureNoRawDirectAddKeys,
  ensureNoRawSimpleChangeKeys: () => ensureNoRawSimpleChangeKeys,
  flattenModel: () => flattenModel,
  getCatalogRecordActionContainerUse: () => getCatalogRecordActionContainerUse,
  getFieldBindingDefaultProps: () => getFieldBindingDefaultProps,
  getNodeSubModelList: () => getNodeSubModelList,
  getSingleNodeSubModel: () => getSingleNodeSubModel,
  hasDefinedValue: () => hasDefinedValue,
  hasLegacyLocatorFields: () => hasLegacyLocatorFields,
  hasMeaningfulChartSemanticPatch: () => hasMeaningfulChartSemanticPatch,
  hasOwnDefined: () => hasOwnDefined,
  isFieldNodeUse: () => isFieldNodeUse,
  isMissingRequiredResourceInitValue: () => isMissingRequiredResourceInitValue,
  joinRequiredFieldPaths: () => joinRequiredFieldPaths,
  normalizeBlockTitleDescription: () => normalizeBlockTitleDescription,
  normalizeBlockTitleDescriptionValue: () => normalizeBlockTitleDescriptionValue,
  normalizeChartCardHeightModeForWrite: () => normalizeChartCardHeightModeForWrite,
  normalizeChartCardSettings: () => normalizeChartCardSettings,
  normalizeComposeActionSpec: () => normalizeComposeActionSpec,
  normalizeComposeFieldSpec: () => normalizeComposeFieldSpec,
  normalizeFlowSurfaceComposeKey: () => normalizeFlowSurfaceComposeKey,
  normalizeGridCardColumns: () => normalizeGridCardColumns,
  normalizePublicBlockHeightMode: () => normalizePublicBlockHeightMode,
  normalizeRowSpans: () => normalizeRowSpans,
  normalizeSimpleConfirm: () => normalizeSimpleConfirm,
  normalizeSimpleLayoutValue: () => normalizeSimpleLayoutValue,
  normalizeSimpleResourceInit: () => normalizeSimpleResourceInit,
  normalizeStoredChartCardHeightMode: () => normalizeStoredChartCardHeightMode,
  resolveRequestedFieldComponent: () => resolveRequestedFieldComponent,
  resolveRequestedFieldUse: () => resolveRequestedFieldUse,
  resolveRequestedFieldUseAlias: () => resolveRequestedFieldUseAlias,
  rethrowInlineConfigurationError: () => rethrowInlineConfigurationError,
  splitComposeFieldChanges: () => splitComposeFieldChanges,
  toFlowSurfaceBatchItemError: () => toFlowSurfaceBatchItemError
});
module.exports = __toCommonJS(service_utils_exports);
var import_utils = require("@nocobase/utils");
var import_lodash = __toESM(require("lodash"));
var import_configure_options = require("./configure-options");
var import_defaults = require("./blueprint/defaults");
var import_errors = require("./errors");
var import_service_helpers = require("./service-helpers");
var import_key_registry = require("./planning/key-registry");
var import_field_type_resolver = require("./field-type-resolver");
function buildDefinedPayload(payload) {
  return import_lodash.default.pickBy(payload, (value) => !import_lodash.default.isUndefined(value));
}
function normalizeFlowSurfaceComposeKey(key, context) {
  const normalized = typeof key === "string" ? key.trim() : String(key || "").trim();
  if (!normalized) {
    (0, import_errors.throwBadRequest)(`${context} key cannot be empty`);
  }
  if (import_key_registry.FLOW_SURFACE_RESERVED_KEYS.has(normalized)) {
    (0, import_errors.throwBadRequest)(`${context} key '${normalized}' is reserved`);
  }
  return normalized;
}
function assertFlowSurfaceComposeUniqueKeys(items, context) {
  const seen = /* @__PURE__ */ new Map();
  items.forEach((item, index) => {
    const key = typeof (item == null ? void 0 : item.key) === "string" ? item.key.trim() : "";
    if (!key) {
      return;
    }
    const previousIndex = seen.get(key);
    if (previousIndex) {
      (0, import_errors.throwBadRequest)(`${context} key '${key}' is duplicated at #${previousIndex} and #${index + 1}`);
    }
    seen.set(key, index + 1);
  });
}
function normalizeChartCardSettings(cardSettings) {
  if (!import_lodash.default.isPlainObject(cardSettings)) {
    return {};
  }
  const nextCardSettings = import_lodash.default.cloneDeep(cardSettings);
  const titleDescription = normalizeBlockTitleDescription(import_lodash.default.get(nextCardSettings, ["titleDescription"]));
  if (titleDescription) {
    import_lodash.default.set(nextCardSettings, ["titleDescription"], titleDescription);
  } else {
    import_lodash.default.unset(nextCardSettings, ["titleDescription"]);
  }
  const rawHeightMode = import_lodash.default.get(nextCardSettings, ["blockHeight", "heightMode"]);
  const rawHeight = import_lodash.default.get(nextCardSettings, ["blockHeight", "height"]);
  const normalizedHeightMode = import_lodash.default.isUndefined(rawHeightMode) ? !import_lodash.default.isUndefined(rawHeight) ? "specifyValue" : void 0 : normalizeChartCardHeightModeForWrite(rawHeightMode);
  if (normalizedHeightMode) {
    import_lodash.default.set(nextCardSettings, ["blockHeight", "heightMode"], normalizedHeightMode);
    if (normalizedHeightMode === "specifyValue" && !import_lodash.default.isUndefined(rawHeight)) {
      import_lodash.default.set(nextCardSettings, ["blockHeight", "height"], rawHeight);
    } else {
      import_lodash.default.unset(nextCardSettings, ["blockHeight", "height"]);
    }
  } else {
    import_lodash.default.unset(nextCardSettings, ["blockHeight"]);
  }
  if (import_lodash.default.isEmpty(import_lodash.default.get(nextCardSettings, ["blockHeight"]))) {
    import_lodash.default.unset(nextCardSettings, ["blockHeight"]);
  }
  return nextCardSettings;
}
function normalizeBlockTitleDescriptionValue(value) {
  if (import_lodash.default.isNull(value)) {
    return "";
  }
  return typeof value === "string" ? value.trim() : value;
}
function normalizeBlockTitleDescription(titleDescription) {
  if (!import_lodash.default.isPlainObject(titleDescription)) {
    return void 0;
  }
  const nextTitleDescription = import_lodash.default.cloneDeep(titleDescription);
  const title = normalizeBlockTitleDescriptionValue(nextTitleDescription.title);
  const description = normalizeBlockTitleDescriptionValue(nextTitleDescription.description);
  if (title) {
    nextTitleDescription.title = title;
  } else {
    delete nextTitleDescription.title;
  }
  if (description) {
    nextTitleDescription.description = description;
  } else {
    delete nextTitleDescription.description;
  }
  return Object.keys(nextTitleDescription).length ? nextTitleDescription : void 0;
}
function buildBlockTitleDescriptionFromSemanticChanges(changes) {
  if (!hasDefinedValue(changes, ["title", "description"])) {
    return void 0;
  }
  return {
    titleDescription: buildDefinedPayload({
      ...hasOwnDefined(changes, "title") ? { title: normalizeBlockTitleDescriptionValue(changes.title) } : {},
      ...hasOwnDefined(changes, "description") ? { description: normalizeBlockTitleDescriptionValue(changes.description) } : {}
    })
  };
}
function buildBlockCardSettingsFromSemanticChanges(changes) {
  const nextCardSettings = buildBlockTitleDescriptionFromSemanticChanges(changes) || {};
  const hasHeightPatch = hasOwnDefined(changes, "height") || hasOwnDefined(changes, "heightMode");
  if (hasHeightPatch) {
    const nextHeightMode = hasOwnDefined(changes, "heightMode") ? normalizePublicBlockHeightMode(changes.heightMode) : hasOwnDefined(changes, "height") ? "specifyValue" : void 0;
    if (nextHeightMode) {
      import_lodash.default.set(nextCardSettings, ["blockHeight", "heightMode"], nextHeightMode);
      if (nextHeightMode === "specifyValue" && hasOwnDefined(changes, "height")) {
        import_lodash.default.set(nextCardSettings, ["blockHeight", "height"], changes.height);
      } else {
        import_lodash.default.unset(nextCardSettings, ["blockHeight", "height"]);
      }
    }
  }
  if (import_lodash.default.isEmpty(import_lodash.default.get(nextCardSettings, ["blockHeight"]))) {
    import_lodash.default.unset(nextCardSettings, ["blockHeight"]);
  }
  if (hasOwnDefined(changes, "linkageRules")) {
    import_lodash.default.set(nextCardSettings, ["linkageRules", "value"], changes.linkageRules);
  }
  return Object.keys(nextCardSettings).length ? nextCardSettings : void 0;
}
function buildChartCardSettingsFromSemanticChanges(currentCardSettings, changes) {
  const nextCardSettings = import_lodash.default.cloneDeep(currentCardSettings || {});
  const currentTitleDescription = import_lodash.default.get(currentCardSettings, ["titleDescription"]);
  const nextTitleDescription = normalizeBlockTitleDescription(
    buildDefinedPayload({
      title: hasOwnDefined(changes, "title") ? normalizeBlockTitleDescriptionValue(changes.title) : import_lodash.default.get(currentTitleDescription, ["title"]),
      description: hasOwnDefined(changes, "description") ? normalizeBlockTitleDescriptionValue(changes.description) : import_lodash.default.get(currentTitleDescription, ["description"])
    })
  );
  if (nextTitleDescription) {
    import_lodash.default.set(nextCardSettings, ["titleDescription"], nextTitleDescription);
  } else {
    import_lodash.default.unset(nextCardSettings, ["titleDescription"]);
  }
  const currentHeight = import_lodash.default.get(currentCardSettings, ["blockHeight", "height"]);
  const nextHeight = hasOwnDefined(changes, "height") ? changes.height : currentHeight;
  const currentHeightMode = normalizeStoredChartCardHeightMode(
    import_lodash.default.get(currentCardSettings, ["blockHeight", "heightMode"])
  );
  const nextHeightMode = hasOwnDefined(changes, "heightMode") ? normalizePublicBlockHeightMode(changes.heightMode) : hasOwnDefined(changes, "height") ? !import_lodash.default.isUndefined(nextHeight) ? "specifyValue" : void 0 : currentHeightMode ?? (!import_lodash.default.isUndefined(nextHeight) ? "specifyValue" : void 0);
  if (nextHeightMode) {
    import_lodash.default.set(nextCardSettings, ["blockHeight", "heightMode"], nextHeightMode);
    if (nextHeightMode === "specifyValue" && !import_lodash.default.isUndefined(nextHeight)) {
      import_lodash.default.set(nextCardSettings, ["blockHeight", "height"], nextHeight);
    } else {
      import_lodash.default.unset(nextCardSettings, ["blockHeight", "height"]);
    }
  } else {
    import_lodash.default.unset(nextCardSettings, ["blockHeight"]);
  }
  if (import_lodash.default.isEmpty(import_lodash.default.get(nextCardSettings, ["blockHeight"]))) {
    import_lodash.default.unset(nextCardSettings, ["blockHeight"]);
  }
  return normalizeChartCardSettings(nextCardSettings);
}
function buildPopupTabTree(options) {
  const tabUid = options.tabUid || (0, import_utils.uid)();
  const gridUid = options.gridUid || (0, import_utils.uid)();
  const title = options.title || "Untitled";
  return {
    uid: tabUid,
    use: "ChildPageTabModel",
    props: buildDefinedPayload({
      title,
      icon: options.icon
    }),
    stepParams: {
      pageTabSettings: {
        tab: buildDefinedPayload({
          title,
          icon: options.icon,
          documentTitle: options.documentTitle
        })
      }
    },
    ...typeof options.flowRegistry !== "undefined" ? { flowRegistry: import_lodash.default.cloneDeep(options.flowRegistry) } : {},
    subModels: {
      grid: {
        uid: gridUid,
        use: "BlockGridModel"
      }
    }
  };
}
function getSingleNodeSubModel(subModel) {
  if (!subModel || Array.isArray(subModel)) {
    return void 0;
  }
  return subModel;
}
function getNodeSubModelList(subModel) {
  if (!subModel) {
    return [];
  }
  return Array.isArray(subModel) ? subModel : [subModel];
}
function flattenModel(node, carry = {}) {
  if (!(node == null ? void 0 : node.uid)) {
    return carry;
  }
  carry[node.uid] = {
    uid: node.uid,
    use: node.use,
    props: node.props,
    decoratorProps: node.decoratorProps,
    stepParams: node.stepParams,
    flowRegistry: node.flowRegistry,
    ...node.template ? { template: node.template } : {},
    ...node.fieldsTemplate ? { fieldsTemplate: node.fieldsTemplate } : {},
    ...node.popup ? { popup: node.popup } : {}
  };
  Object.values(node.subModels || {}).forEach((value) => {
    import_lodash.default.castArray(value).forEach((child) => flattenModel(child, carry));
  });
  return carry;
}
function buildDefaultFieldState(containerUse, fieldUse, field) {
  const bindingDefaults = getFieldBindingDefaultProps(containerUse, fieldUse, field);
  return {
    wrapperProps: {},
    fieldProps: import_lodash.default.cloneDeep(bindingDefaults)
  };
}
function hasOwnDefined(input, key) {
  return Object.prototype.hasOwnProperty.call(input, key) && !import_lodash.default.isUndefined(input[key]);
}
function hasMeaningfulChartSemanticPatch(input, key) {
  if (!Object.prototype.hasOwnProperty.call(input, key)) {
    return false;
  }
  const value = input[key];
  if (import_lodash.default.isNull(value)) {
    return true;
  }
  if (import_lodash.default.isPlainObject(value)) {
    return Object.keys(value).length > 0;
  }
  return !import_lodash.default.isUndefined(value);
}
function hasDefinedValue(input, keys) {
  return keys.some((key) => hasOwnDefined(input, key));
}
function ensureNoRawSimpleChangeKeys(changes) {
  const rawKeys = [
    "props",
    "decoratorProps",
    "stepParams",
    "flowRegistry",
    "use",
    "fieldUse",
    "fieldComponent",
    "fieldModel",
    "componentFields",
    "subModels"
  ];
  const forbidden = Object.keys(changes).filter((key) => rawKeys.includes(key));
  if (forbidden.length) {
    (0, import_errors.throwBadRequest)(
      `flowSurfaces configure does not accept raw keys: ${forbidden.join(
        ", "
      )}; use catalog.configureOptions and configure.changes instead`
    );
  }
}
function ensureNoRawDirectAddKeys(actionName, values, rawKeys) {
  const forbidden = rawKeys.filter((key) => hasOwnDefined(values || {}, key));
  if (!forbidden.length) {
    return;
  }
  (0, import_errors.throwBadRequest)(
    `flowSurfaces ${actionName} does not accept raw keys: ${forbidden.join(
      ", "
    )}; use settings with catalog.configureOptions or fall back to updateSettings/apply for low-level control`
  );
}
function ensureNoDirectActionScopeKey(actionName, values) {
  if (import_lodash.default.isUndefined(values == null ? void 0 : values.scope)) {
    return;
  }
  (0, import_errors.throwBadRequest)(
    `flowSurfaces ${actionName} does not support scope; use addAction for non-record actions and addRecordAction for record actions`
  );
}
function normalizeComposeFieldSpec(input, index) {
  if (typeof input === "string") {
    const fieldPath2 = String(input || "").trim();
    if (!fieldPath2) {
      (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} cannot be empty`);
    }
    return {
      index: index + 1,
      key: fieldPath2,
      fieldPath: fieldPath2,
      settings: {},
      popup: void 0,
      __autoPopupForRelationField: true
    };
  }
  if (!import_lodash.default.isPlainObject(input)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} must be a string or object`);
  }
  (0, import_field_type_resolver.assertNoInternalFieldKeys)(input, `flowSurfaces compose field #${index + 1}`);
  (0, import_field_type_resolver.assertNoInternalFieldKeys)(input.settings, `flowSurfaces compose field #${index + 1}.settings`);
  const semanticType = String(input.type || "").trim() || void 0;
  const fieldPath = String(input.fieldPath || "").trim();
  const renderer = typeof input.renderer === "undefined" ? void 0 : String(input.renderer || "").trim();
  const fieldType = (0, import_field_type_resolver.normalizePublicFieldType)(input.fieldType, `compose field #${index + 1}`);
  const fields = (0, import_field_type_resolver.normalizePublicFieldNameList)(input.fields, `compose field #${index + 1}.fields`);
  const titleField = typeof input.titleField === "undefined" ? void 0 : String(input.titleField || "").trim();
  const openMode = typeof input.openMode === "undefined" ? void 0 : String(input.openMode || "").trim();
  const popupSize = typeof input.popupSize === "undefined" ? void 0 : String(input.popupSize || "").trim();
  const pageSize = typeof input.pageSize === "undefined" ? void 0 : Number(input.pageSize);
  const showIndex = typeof input.showIndex === "undefined" ? void 0 : !!input.showIndex;
  if (!import_lodash.default.isUndefined(input.popup) && !import_lodash.default.isPlainObject(input.popup)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} popup must be an object`);
  }
  if (!fieldPath && !semanticType) {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} requires fieldPath`);
  }
  if (semanticType && fieldPath) {
    (0, import_errors.throwBadRequest)(
      `flowSurfaces compose field #${index + 1} cannot mix fieldPath with synthetic field type '${semanticType}'`
    );
  }
  if (!import_lodash.default.isUndefined(input.target) && typeof input.target !== "string") {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} target must be a string block key`);
  }
  if (!import_lodash.default.isUndefined(input.defaultTargetUid) && typeof input.defaultTargetUid !== "string") {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} defaultTargetUid must be a string`);
  }
  if (!import_lodash.default.isUndefined(input.targetBlockUid) && typeof input.targetBlockUid !== "string") {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose field #${index + 1} targetBlockUid must be a string`);
  }
  const rawKey = String(input.key || semanticType || (renderer === "js" ? `js:${fieldPath}` : fieldPath)).trim();
  const key = normalizeFlowSurfaceComposeKey(rawKey, `flowSurfaces compose field #${index + 1}`);
  const popupDefaultsMetadata = import_lodash.default.isPlainObject(input[import_defaults.FLOW_SURFACE_APPLY_BLUEPRINT_POPUP_DEFAULTS_KEY]) ? input[import_defaults.FLOW_SURFACE_APPLY_BLUEPRINT_POPUP_DEFAULTS_KEY] : void 0;
  return {
    index: index + 1,
    key,
    ...fieldPath ? { fieldPath } : {},
    associationPathName: String(input.associationPathName || "").trim() || void 0,
    ...renderer ? { renderer } : {},
    ...semanticType ? { type: semanticType } : {},
    ...fieldType ? { fieldType } : {},
    ...!import_lodash.default.isUndefined(fields) ? { fields } : {},
    ...titleField ? { titleField } : {},
    ...openMode ? { openMode } : {},
    ...popupSize ? { popupSize } : {},
    ...!import_lodash.default.isUndefined(pageSize) && Number.isFinite(pageSize) ? { pageSize } : {},
    ...!import_lodash.default.isUndefined(showIndex) ? { showIndex } : {},
    target: typeof input.target === "string" ? String(input.target || "").trim() || void 0 : void 0,
    defaultTargetUid: typeof input.defaultTargetUid === "string" ? String(input.defaultTargetUid || "").trim() || void 0 : void 0,
    targetBlockUid: typeof input.targetBlockUid === "string" ? String(input.targetBlockUid || "").trim() || void 0 : void 0,
    settings: import_lodash.default.isPlainObject(input.settings) ? input.settings : {},
    popup: import_lodash.default.isPlainObject(input.popup) ? input.popup : void 0,
    __autoPopupForRelationField: input.__autoPopupForRelationField === true,
    ...popupDefaultsMetadata ? { [import_defaults.FLOW_SURFACE_APPLY_BLUEPRINT_POPUP_DEFAULTS_KEY]: popupDefaultsMetadata } : {}
  };
}
function resolveRequestedFieldComponent(values) {
  return void 0;
}
function resolveRequestedFieldUse(values) {
  return resolveRequestedFieldComponent(values) || resolveRequestedFieldUseAlias(values);
}
function resolveRequestedFieldUseAlias(values) {
  const legacyFieldUse = String((values == null ? void 0 : values.fieldUse) || "").trim();
  return legacyFieldUse || void 0;
}
function normalizeComposeActionSpec(input, index) {
  if (typeof input === "string") {
    const type2 = String(input || "").trim();
    if (!type2) {
      (0, import_errors.throwBadRequest)(`flowSurfaces compose action #${index + 1} cannot be empty`);
    }
    return {
      key: type2,
      type: type2,
      settings: {}
    };
  }
  if (!import_lodash.default.isPlainObject(input)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose action #${index + 1} must be a string or object`);
  }
  if (input.use || input.fieldUse || input.stepParams || input.props || input.decoratorProps || input.flowRegistry) {
    (0, import_errors.throwBadRequest)("flowSurfaces compose action only accepts public semantic action fields");
  }
  const type = String(input.type || "").trim();
  if (!type) {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose action #${index + 1} requires type`);
  }
  if (!import_lodash.default.isUndefined(input.scope)) {
    (0, import_errors.throwBadRequest)(`flowSurfaces compose action #${index + 1} does not support scope, use actions or recordActions`);
  }
  const key = normalizeFlowSurfaceComposeKey(
    String(input.key || type).trim(),
    `flowSurfaces compose action #${index + 1}`
  );
  const popup = import_lodash.default.isPlainObject(input.popup) ? input.popup : void 0;
  return {
    key,
    type,
    settings: import_lodash.default.isPlainObject(input.settings) ? input.settings : {},
    ...popup ? { popup } : {}
  };
}
function normalizeSimpleResourceInit(input) {
  if (!input) {
    return void 0;
  }
  if (!import_lodash.default.isPlainObject(input)) {
    (0, import_errors.throwBadRequest)("flowSurfaces simple resource must be an object");
  }
  const normalized = buildDefinedPayload({
    dataSourceKey: input.dataSourceKey,
    collectionName: input.collectionName,
    associationName: input.associationName,
    associationPathName: input.associationPathName,
    sourceId: input.sourceId,
    filterByTk: input.filterByTk
  });
  if (!Object.keys(normalized).length) {
    (0, import_errors.throwBadRequest)("flowSurfaces simple resource cannot be empty");
  }
  return normalized;
}
function isMissingRequiredResourceInitValue(value) {
  if (import_lodash.default.isNil(value)) {
    return true;
  }
  if (typeof value === "string") {
    return !value.trim();
  }
  return false;
}
function joinRequiredFieldPaths(paths) {
  if (paths.length <= 1) {
    return paths[0] || "";
  }
  if (paths.length === 2) {
    return `${paths[0]} and ${paths[1]}`;
  }
  return `${paths.slice(0, -1).join(", ")}, and ${paths[paths.length - 1]}`;
}
function normalizeSimpleLayoutValue(layout) {
  if (import_lodash.default.isUndefined(layout)) {
    return void 0;
  }
  if (import_lodash.default.isPlainObject(layout)) {
    return layout.layout;
  }
  return layout;
}
function normalizeGridCardColumns(columns) {
  if (import_lodash.default.isUndefined(columns)) {
    return void 0;
  }
  if (import_lodash.default.isNumber(columns) && columns > 0) {
    return {
      xs: columns,
      sm: columns,
      md: columns,
      lg: columns,
      xl: columns,
      xxl: columns
    };
  }
  if (import_lodash.default.isPlainObject(columns)) {
    const requiredBreakpoints = ["xs", "sm", "md", "lg", "xl", "xxl"];
    const missingBreakpoints = requiredBreakpoints.filter((key) => import_lodash.default.isUndefined(columns[key]));
    if (missingBreakpoints.length) {
      (0, import_errors.throwBadRequest)(
        `flowSurfaces configure gridCard columns responsive object must include xs, sm, md, lg, xl, xxl; missing: ${missingBreakpoints.join(
          ", "
        )}`
      );
    }
    const invalidBreakpoints = requiredBreakpoints.filter((key) => !import_lodash.default.isNumber(columns[key]) || columns[key] <= 0);
    if (invalidBreakpoints.length) {
      (0, import_errors.throwBadRequest)(
        `flowSurfaces configure gridCard columns responsive object values must be positive numbers; invalid: ${invalidBreakpoints.join(
          ", "
        )}`
      );
    }
    const normalized = buildDefinedPayload({
      xs: columns.xs,
      sm: columns.sm,
      md: columns.md,
      lg: columns.lg,
      xl: columns.xl,
      xxl: columns.xxl
    });
    if (!Object.keys(normalized).length) {
      (0, import_errors.throwBadRequest)("flowSurfaces configure gridCard columns cannot be empty");
    }
    return normalized;
  }
  (0, import_errors.throwBadRequest)("flowSurfaces configure gridCard columns must be a number or responsive object");
}
function normalizeSimpleConfirm(confirm) {
  if (import_lodash.default.isBoolean(confirm)) {
    return {
      enable: confirm
    };
  }
  if (import_lodash.default.isPlainObject(confirm)) {
    return buildDefinedPayload({
      enable: confirm.enable,
      title: confirm.title,
      content: confirm.content
    });
  }
  (0, import_errors.throwBadRequest)("flowSurfaces configure confirm must be a boolean or object");
}
function assertSupportedSimpleChanges(context, changes, allowedKeys) {
  const unknownKeys = Object.keys(changes).filter((key) => !allowedKeys.includes(key));
  if (!unknownKeys.length) {
    return;
  }
  (0, import_errors.throwBadRequest)(
    `flowSurfaces configure ${context} does not support: ${unknownKeys.join(
      ", "
    )}; supported configureOptions: ${allowedKeys.join(", ")}`
  );
}
function hasLegacyLocatorFields(input, options = {}) {
  if (!import_lodash.default.isPlainObject(input)) {
    return false;
  }
  const keys = ["pageSchemaUid", "tabSchemaUid", "routeId", "schemaUid"];
  if (options.allowRootUid) {
    keys.push("uid");
  }
  return keys.some((key) => Object.prototype.hasOwnProperty.call(input, key));
}
function rethrowInlineConfigurationError(error, prefix) {
  if ((0, import_errors.isFlowSurfaceAggregateError)(error)) {
    throw new import_errors.FlowSurfaceAggregateError(error.errors, `${prefix}: ${error.message}`);
  }
  const message = `${prefix}: ${(error == null ? void 0 : error.message) || String(error)}`;
  if ((0, import_errors.isFlowSurfaceError)(error)) {
    const normalized = (0, import_errors.normalizeFlowSurfaceError)(error);
    if (normalized.type === "bad_request") {
      (0, import_errors.throwBadRequest)(message, normalized.code, normalized.options);
    }
    if (normalized.type === "conflict") {
      (0, import_errors.throwConflict)(message, normalized.code);
    }
    if (normalized.type === "forbidden") {
      (0, import_errors.throwForbidden)(message, normalized.code);
    }
    (0, import_errors.throwInternalError)(message, normalized.code);
  }
  (0, import_errors.throwInternalError)(message);
}
function toFlowSurfaceBatchItemError(error) {
  if ((0, import_errors.isFlowSurfaceAggregateError)(error)) {
    return {
      code: error.code,
      status: error.status,
      type: error.type,
      ...error.toResponseBody()
    };
  }
  const normalized = (0, import_errors.normalizeFlowSurfaceError)(error);
  return {
    code: normalized.code,
    message: normalized.message,
    status: normalized.status,
    type: normalized.type
  };
}
function splitComposeFieldChanges(changes, wrapperUse) {
  ensureNoRawSimpleChangeKeys(changes);
  const supportedKeys = (0, import_configure_options.getConfigureOptionKeysForUse)(wrapperUse || "FormItemModel");
  assertSupportedSimpleChanges("field", changes, supportedKeys);
  const wrapperChanges = import_lodash.default.pick(changes, [
    "label",
    "tooltip",
    "extra",
    "showLabel",
    "width",
    "fixed",
    "sorter",
    "fieldPath",
    "associationPathName",
    "initialValue",
    "required",
    "rules",
    "disabled",
    "maxCount",
    "pattern",
    "dataIndex",
    "editable",
    "labelWidth",
    "labelWrap",
    "name",
    "fieldType",
    "fields",
    "titleField",
    "openMode",
    "popupSize",
    "pageSize",
    "showIndex",
    ...wrapperUse === "TableColumnModel" ? ["title"] : []
  ]);
  const fieldChanges = import_lodash.default.pick(changes, [
    "clickToOpen",
    "openView",
    ...wrapperUse === "TableColumnModel" ? [] : ["title"],
    "icon",
    "autoSize",
    "allowClear",
    "multiple",
    "allowMultiple",
    "quickCreate",
    "displayStyle",
    "options",
    "code",
    "version"
  ]);
  return {
    wrapperChanges: import_lodash.default.pickBy(wrapperChanges, (value) => !import_lodash.default.isUndefined(value)),
    fieldChanges: import_lodash.default.pickBy(fieldChanges, (value) => !import_lodash.default.isUndefined(value))
  };
}
function getCatalogRecordActionContainerUse(use) {
  switch (String(use || "").trim()) {
    case "TableBlockModel":
    case "TableActionsColumnModel":
      return "TableActionsColumnModel";
    case "DetailsBlockModel":
      return "DetailsBlockModel";
    case "ListBlockModel":
    case "ListItemModel":
      return "ListItemModel";
    case "GridCardBlockModel":
    case "GridCardItemModel":
      return "GridCardItemModel";
    case "CommentsBlockModel":
    case "CommentItemModel":
      return "CommentItemModel";
    default:
      return null;
  }
}
function normalizeRowSpans(spans) {
  const numericSpans = import_lodash.default.castArray(spans || []).map((span) => {
    if (import_lodash.default.isNumber(span) && span > 0) {
      return span;
    }
    return 1;
  });
  const total = numericSpans.reduce((sum, value) => sum + value, 0);
  if (!total) {
    return numericSpans.map(() => 24);
  }
  if (total === 24 && numericSpans.every((value) => Number.isInteger(value))) {
    return numericSpans;
  }
  const raw = numericSpans.map((value) => value / total * 24);
  const base = raw.map((value) => Math.max(1, Math.floor(value)));
  let remainder = 24 - base.reduce((sum, value) => sum + value, 0);
  const order = raw.map((value, index) => ({
    index,
    fraction: value - Math.floor(value)
  })).sort((left, right) => right.fraction - left.fraction || left.index - right.index);
  let cursor = 0;
  while (remainder > 0 && order.length) {
    base[order[cursor % order.length].index] += 1;
    remainder -= 1;
    cursor += 1;
  }
  while (remainder < 0 && order.length) {
    const target = order[(cursor + order.length - 1) % order.length].index;
    if (base[target] > 1) {
      base[target] -= 1;
      remainder += 1;
    }
    cursor += 1;
  }
  return base;
}
function normalizePublicBlockHeightMode(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  if (import_lodash.default.isNull(input)) {
    (0, import_errors.throwBadRequest)("flowSurfaces configure heightMode cannot be null");
  }
  const normalized = String(input || "").trim();
  if (!normalized) {
    (0, import_errors.throwBadRequest)("flowSurfaces configure heightMode cannot be empty");
  }
  const aliased = normalized === "fixed" ? "specifyValue" : normalized;
  if (!["defaultHeight", "specifyValue", "fullHeight"].includes(aliased)) {
    (0, import_errors.throwBadRequest)("flowSurfaces configure heightMode must be one of: defaultHeight, specifyValue, fullHeight");
  }
  return aliased;
}
function normalizeStoredChartCardHeightMode(input) {
  if (import_lodash.default.isUndefined(input) || import_lodash.default.isNull(input) || String(input).trim() === "") {
    return void 0;
  }
  try {
    return normalizePublicBlockHeightMode(input);
  } catch {
    return void 0;
  }
}
function normalizeChartCardHeightModeForWrite(input) {
  if (import_lodash.default.isUndefined(input)) {
    return void 0;
  }
  if (import_lodash.default.isNull(input)) {
    (0, import_errors.throwBadRequest)("flowSurfaces updateSettings chart stepParams.cardSettings.blockHeight.heightMode cannot be null");
  }
  const normalized = String(input).trim();
  if (!normalized) {
    (0, import_errors.throwBadRequest)("flowSurfaces updateSettings chart stepParams.cardSettings.blockHeight.heightMode cannot be empty");
  }
  try {
    return normalizePublicBlockHeightMode(normalized);
  } catch {
    (0, import_errors.throwBadRequest)(
      "flowSurfaces updateSettings chart stepParams.cardSettings.blockHeight.heightMode must be one of: defaultHeight, specifyValue, fullHeight"
    );
  }
}
function isFieldNodeUse(use) {
  return !!use && use.endsWith("FieldModel");
}
function getFieldBindingDefaultProps(containerUse, fieldUse, field) {
  const fieldInterface = (0, import_service_helpers.getFieldInterface)(field);
  const defaults = {};
  const isFilterField = ["FilterFormBlockModel", "FilterFormGridModel", "FilterFormItemModel"].includes(containerUse);
  if (fieldUse === "TextareaFieldModel") {
    defaults.autoSize = {
      maxRows: 10,
      minRows: 3
    };
  }
  if (fieldUse === "FilterFormRecordSelectFieldModel") {
    defaults.allowMultiple = true;
    defaults.multiple = true;
    defaults.quickCreate = "none";
  }
  if (fieldUse === "SelectFieldModel") {
    if (["select", "multipleSelect", "radioGroup"].includes(fieldInterface)) {
      defaults.allowClear = true;
    }
    if (fieldInterface === "checkboxGroup") {
      defaults.allowClear = true;
      defaults.mode = "tags";
    }
    if (isFilterField && fieldInterface === "checkbox") {
      defaults.allowClear = true;
      defaults.multiple = false;
      defaults.options = [
        {
          label: '{{t("Yes")}}',
          value: true
        },
        {
          label: '{{t("No")}}',
          value: false
        }
      ];
    }
  }
  return defaults;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  assertFlowSurfaceComposeUniqueKeys,
  assertSupportedSimpleChanges,
  buildBlockCardSettingsFromSemanticChanges,
  buildBlockTitleDescriptionFromSemanticChanges,
  buildChartCardSettingsFromSemanticChanges,
  buildDefaultFieldState,
  buildDefinedPayload,
  buildPopupTabTree,
  ensureNoDirectActionScopeKey,
  ensureNoRawDirectAddKeys,
  ensureNoRawSimpleChangeKeys,
  flattenModel,
  getCatalogRecordActionContainerUse,
  getFieldBindingDefaultProps,
  getNodeSubModelList,
  getSingleNodeSubModel,
  hasDefinedValue,
  hasLegacyLocatorFields,
  hasMeaningfulChartSemanticPatch,
  hasOwnDefined,
  isFieldNodeUse,
  isMissingRequiredResourceInitValue,
  joinRequiredFieldPaths,
  normalizeBlockTitleDescription,
  normalizeBlockTitleDescriptionValue,
  normalizeChartCardHeightModeForWrite,
  normalizeChartCardSettings,
  normalizeComposeActionSpec,
  normalizeComposeFieldSpec,
  normalizeFlowSurfaceComposeKey,
  normalizeGridCardColumns,
  normalizePublicBlockHeightMode,
  normalizeRowSpans,
  normalizeSimpleConfirm,
  normalizeSimpleLayoutValue,
  normalizeSimpleResourceInit,
  normalizeStoredChartCardHeightMode,
  resolveRequestedFieldComponent,
  resolveRequestedFieldUse,
  resolveRequestedFieldUseAlias,
  rethrowInlineConfigurationError,
  splitComposeFieldChanges,
  toFlowSurfaceBatchItemError
});
