/**
 * 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 export_document_exports = {};
__export(export_document_exports, {
  exportFlowSurfaceBlueprintDocument: () => exportFlowSurfaceBlueprintDocument
});
module.exports = __toCommonJS(export_document_exports);
var import_lodash = __toESM(require("lodash"));
var import_catalog = require("../catalog");
var import_chart_config = require("../chart-config");
var import_errors = require("../errors");
var import_field_type_resolver = require("../field-type-resolver");
var import_service_utils = require("../service-utils");
var import_key_registry = require("../planning/key-registry");
var import_linkage = require("../reaction/linkage");
var import_field_value = require("../reaction/field-value");
var import_resolver = require("../reaction/resolver");
var import_registry = require("../reaction/registry");
var import_private_utils = require("./private-utils");
const UNSUPPORTED_MANUAL_ACTION = "Recreate this node manually or add mapper support.";
const UNSUPPORTED_BLOCK_MANUAL_ACTION = "Recreate this block manually or add mapper support.";
const APPLY_BLUEPRINT_UNSUPPORTED_BLOCK_TYPES = /* @__PURE__ */ new Set(["form", "map"]);
const DATA_BLOCK_SETTING_GROUP_BY_TYPE = {
  table: "tableSettings",
  createForm: "formModelSettings",
  editForm: "formModelSettings",
  details: "detailsSettings",
  filterForm: "formFilterBlockModelSettings",
  list: "listSettings",
  gridCard: "GridCardSettings",
  calendar: "calendarSettings",
  kanban: "kanbanSettings",
  tree: "treeSettings",
  comments: "commentsSettings",
  recordHistory: "recordHistorySettings"
};
const FIELD_GRID_BLOCK_TYPES = /* @__PURE__ */ new Set(["createForm", "editForm", "details", "filterForm"]);
const CARD_FIELD_BLOCK_TYPES = /* @__PURE__ */ new Set(["list", "gridCard", "kanban"]);
const TABLE_ACTIONS_COLUMN_USE = "TableActionsColumnModel";
const FLOW_REGISTRY_UNSUPPORTED_REASON = "unsupported-flow-registry";
const TEMPLATE_SUMMARY_UNSUPPORTED_REASON = "unsupported-template-summary";
const PUBLIC_POPUP_ACTION_TYPES = /* @__PURE__ */ new Set(["addNew", "addChild", "view", "edit", "popup", "duplicate"]);
const BASIC_ACTION_STEP_PARAM_GROUPS = /* @__PURE__ */ new Set([
  "buttonSettings",
  "deleteSettings",
  "popupSettings",
  "filterSettings",
  "clickSettings",
  "jsSettings"
]);
const BASIC_ACTION_PROP_KEYS = /* @__PURE__ */ new Set([
  "title",
  "tooltip",
  "icon",
  "iconOnly",
  "type",
  "danger",
  "color",
  "defaultFilterValue",
  "filterValue",
  "filterableFieldNames",
  "position"
]);
const BASIC_ACTION_BUTTON_GENERAL_KEYS = /* @__PURE__ */ new Set(["title", "tooltip", "icon", "iconOnly", "type", "danger", "color"]);
const BASIC_DELETE_ACTION_TYPES = /* @__PURE__ */ new Set(["delete", "bulkDelete"]);
const RECORD_HISTORY_GENERATED_ACTION_USES = /* @__PURE__ */ new Set([
  "RecordHistoryExpandActionModel",
  "RecordHistoryCollapseActionModel"
]);
const BASIC_DELETE_CONFIRM_KEYS = /* @__PURE__ */ new Set(["enable", "title", "content"]);
const BASIC_INLINE_POPUP_OPEN_VIEW_KEYS = /* @__PURE__ */ new Set(["mode", "title", "tryTemplate", "defaultType"]);
const BASIC_INLINE_POPUP_DEFAULT_RUNTIME_KEYS = /* @__PURE__ */ new Set([
  "size",
  "pageModelClass",
  "dataSourceKey",
  "collectionName",
  "associationName",
  "sourceId",
  "filterByTk"
]);
const JS_ACTION_USES = /* @__PURE__ */ new Set([
  "JSCollectionActionModel",
  "JSRecordActionModel",
  "JSFormActionModel",
  "FilterFormJSActionModel",
  "JSActionModel"
]);
const JS_ITEM_ACTION_USES = /* @__PURE__ */ new Set(["JSItemActionModel"]);
const BASIC_FIELD_STEP_PARAM_GROUPS = /* @__PURE__ */ new Set([
  "fieldSettings",
  "tableColumnSettings",
  "detailItemSettings",
  "editItemSettings",
  "filterFormItemSettings",
  "jsSettings"
]);
const EXPORTED_RESOURCE_SETTING_PATHS = [
  "init.dataSourceKey",
  "init.collectionName",
  "init.associationName",
  "init.associationPathName",
  "init.sourceId",
  "init.filterByTk"
];
const EXPORTED_DATA_BLOCK_SETTING_PATHS = ["dataScope.filter.*", "defaultSorting.sort", "pageSize.pageSize"];
const EXPORTED_LIST_BLOCK_SETTING_PATHS = [...EXPORTED_DATA_BLOCK_SETTING_PATHS, "layout.layout"];
const EXPORTED_GRID_CARD_BLOCK_SETTING_PATHS = [
  "columnCount.columnCount.xs",
  "columnCount.columnCount.sm",
  "columnCount.columnCount.md",
  "columnCount.columnCount.lg",
  "columnCount.columnCount.xl",
  "columnCount.columnCount.xxl",
  "rowCount.rowCount",
  "dataScope.filter.*",
  "defaultSorting.sort",
  "layout.layout"
];
const EXPORTED_KANBAN_BLOCK_SETTING_PATHS = [
  "grouping.groupField",
  "grouping.groupTitleField",
  "grouping.groupColorField",
  "grouping.groupOptions.*",
  "styleVariant.styleVariant",
  "defaultSorting.sort",
  "dragEnabled.dragEnabled",
  "dragSortBy.dragSortBy",
  "quickCreate.quickCreateEnabled",
  "popup.*",
  "pageSize.pageSize",
  "columnWidth.columnWidth",
  "dataScope.filter.*"
];
const EXPORTED_KANBAN_CARD_ITEM_SETTING_PATHS = [
  "click.enableCardClick",
  "popup.*",
  "layout.layout",
  "layout.labelAlign",
  "layout.labelWidth",
  "layout.labelWrap",
  "layout.colon"
];
const EXPORTED_ACTION_PANEL_BLOCK_SETTING_PATHS = ["layout.layout", "ellipsis.ellipsis"];
const EXPORTED_RECORD_HISTORY_BLOCK_SETTING_PATHS = [
  "sortOrder.order",
  "dataScope.filter.*",
  "expand.expand",
  "template.apply"
];
const EXPORTED_CALENDAR_SETTING_PATHS = [
  "titleField.titleField",
  "colorField.colorFieldName",
  "startDateField.start",
  "endDateField.end",
  "defaultView.defaultView",
  "quickCreateEvent.enableQuickCreateEvent",
  "showLunar.showLunar",
  "weekStart.weekStart",
  "quickCreatePopupSettings.*",
  "eventPopupSettings.*",
  "dataScope.filter.*"
];
const EXPORTED_TREE_BLOCK_PROP_KEYS = /* @__PURE__ */ new Set([
  "searchable",
  "defaultExpandAll",
  "includeDescendants",
  "fieldNames",
  "pageSize"
]);
const EXPORTED_CALENDAR_BLOCK_PROP_KEYS = /* @__PURE__ */ new Set([
  "fieldNames",
  "defaultView",
  "enableQuickCreateEvent",
  "showLunar",
  "weekStart",
  "quickCreatePopupSettings",
  "eventPopupSettings"
]);
const EXPORTED_CALENDAR_POPUP_KEYS = /* @__PURE__ */ new Set(["mode", "size", "title", "tryTemplate", "defaultType"]);
const IGNORED_CALENDAR_POPUP_RUNTIME_KEYS = /* @__PURE__ */ new Set([
  "uid",
  "pageModelClass",
  "collectionName",
  "dataSourceKey",
  "associationName",
  "filterByTk",
  "sourceId",
  "template",
  "popupTemplateUid",
  "popupTemplateContext",
  "popupTemplateMode",
  "popupTemplateHasFilterByTk",
  "popupTemplateHasSourceId"
]);
const EXPORTED_KANBAN_BLOCK_PROP_KEYS = /* @__PURE__ */ new Set([
  "groupField",
  "groupTitleField",
  "groupColorField",
  "groupOptions",
  "styleVariant",
  "sortField",
  "globalSort",
  "dragEnabled",
  "dragSortBy",
  "quickCreateEnabled",
  "popupMode",
  "popupSize",
  "popupTemplateUid",
  "popupPageModelClass",
  "popupTargetUid",
  "quickCreatePopupSettings",
  "pageSize",
  "columnWidth"
]);
const EXPORTED_KANBAN_CARD_ITEM_PROP_KEYS = /* @__PURE__ */ new Set([
  "enableCardClick",
  "openMode",
  "popupSize",
  "popupTemplateUid",
  "pageModelClass",
  "popupTargetUid",
  "cardPopupSettings",
  "layout",
  "labelAlign",
  "labelWidth",
  "labelWrap",
  "colon"
]);
const EXPORTED_KANBAN_POPUP_KEYS = /* @__PURE__ */ new Set(["mode", "size", "title", "tryTemplate", "defaultType"]);
const IGNORED_KANBAN_POPUP_RUNTIME_KEYS = /* @__PURE__ */ new Set([
  "uid",
  "pageModelClass",
  "collectionName",
  "dataSourceKey",
  "associationName",
  "filterByTk",
  "sourceId",
  "template",
  "popupTemplateUid",
  "popupTemplateContext",
  "popupTemplateMode",
  "popupTemplateHasFilterByTk",
  "popupTemplateHasSourceId"
]);
const EXPORTED_ACTION_PANEL_BLOCK_PROP_KEYS = /* @__PURE__ */ new Set(["layout", "ellipsis"]);
const EXPORTED_JS_BLOCK_DECORATOR_PROP_KEYS = /* @__PURE__ */ new Set(["title", "description"]);
const EXPORTED_TREE_BLOCK_SETTING_PATHS = [
  "searchable.searchable",
  "defaultExpandAll.defaultExpandAll",
  "includeDescendants.includeDescendants",
  "titleField.titleField",
  ...EXPORTED_DATA_BLOCK_SETTING_PATHS
];
const EXPORTED_BLOCK_CARD_SETTING_PATHS = [
  "titleDescription.title",
  "titleDescription.description",
  "blockHeight.height",
  "blockHeight.heightMode",
  "linkageRules.value"
];
const EXPORTED_SIMPLE_BLOCK_SETTING_PATHS_BY_TYPE = {
  markdown: ["editMarkdown.content"],
  jsBlock: ["runJs.code", "runJs.version", "showBlockCard.showBlockCard"],
  iframe: ["editIframe"]
};
const EXPORTED_BLOCK_STEP_PARAM_PATHS_BY_GROUP = {
  resourceSettings: EXPORTED_RESOURCE_SETTING_PATHS,
  TriggerChildPageSettings: EXPORTED_RESOURCE_SETTING_PATHS,
  ApprovalChildPageSettings: EXPORTED_RESOURCE_SETTING_PATHS,
  tableSettings: EXPORTED_DATA_BLOCK_SETTING_PATHS,
  formModelSettings: ["dataScope.filter.*", "defaultSorting.sort", "pageSize.pageSize", "linkageRules.value"],
  detailsSettings: ["dataScope.filter.*", "defaultSorting.sort", "pageSize.pageSize", "linkageRules.value"],
  formFilterBlockModelSettings: ["dataScope.filter.*", "defaultSorting.sort", "pageSize.pageSize"],
  listSettings: EXPORTED_LIST_BLOCK_SETTING_PATHS,
  GridCardSettings: EXPORTED_GRID_CARD_BLOCK_SETTING_PATHS,
  calendarSettings: EXPORTED_CALENDAR_SETTING_PATHS,
  kanbanSettings: EXPORTED_KANBAN_BLOCK_SETTING_PATHS,
  treeSettings: EXPORTED_TREE_BLOCK_SETTING_PATHS,
  commentsSettings: ["dataScope.filter.*", "pageSize.pageSize"],
  actionPanelBlockSetting: EXPORTED_ACTION_PANEL_BLOCK_SETTING_PATHS,
  recordHistorySettings: EXPORTED_RECORD_HISTORY_BLOCK_SETTING_PATHS,
  cardSettings: EXPORTED_BLOCK_CARD_SETTING_PATHS,
  chartSettings: ["configure.*"]
};
const EXPORTED_TABLE_COLUMN_SETTING_PATHS = [
  "title.title",
  "tooltip.tooltip",
  "width.width",
  "fixed.fixed",
  "sorter.sorter",
  "quickEdit.editable",
  "fieldNames.label",
  "linkageRules.value"
];
const EXPORTED_DETAIL_ITEM_SETTING_PATHS = [
  "showLabel.showLabel",
  "label.title",
  "tooltip.tooltip",
  "description.description",
  "fieldNames.label",
  "linkageRules.value"
];
const EXPORTED_EDIT_ITEM_SETTING_PATHS = [
  "showLabel.showLabel",
  "label.label",
  "tooltip.tooltip",
  "description.description",
  "initialValue.defaultValue",
  "required.required",
  "pattern.pattern",
  "titleField.label",
  "linkageRules.value"
];
const EXPORTED_FILTER_FORM_ITEM_SETTING_PATHS = [
  "showLabel.showLabel",
  "label.label",
  "tooltip.tooltip",
  "description.description",
  "initialValue.defaultValue"
];
const EXPORTED_JS_FIELD_SETTING_PATHS = ["runJs.code", "runJs.version"];
const EXPORTED_FIELD_DECORATOR_PROP_KEYS = /* @__PURE__ */ new Set(["labelWidth", "labelWrap"]);
const TABLE_FIELD_PUBLIC_PROP_KEYS = /* @__PURE__ */ new Set([
  "title",
  "tooltip",
  "width",
  "fixed",
  "sorter",
  "editable",
  "dataIndex",
  "titleField"
]);
const FORM_FIELD_PUBLIC_PROP_KEYS = /* @__PURE__ */ new Set([
  "label",
  "tooltip",
  "extra",
  "showLabel",
  "initialValue",
  "required",
  "rules",
  "disabled",
  "multiple",
  "allowMultiple",
  "maxCount",
  "pattern",
  "titleField",
  "name"
]);
const DETAIL_FIELD_PUBLIC_PROP_KEYS = /* @__PURE__ */ new Set([
  "label",
  "tooltip",
  "extra",
  "showLabel",
  "disabled",
  "pattern",
  "titleField"
]);
const FILTER_FIELD_PUBLIC_PROP_KEYS = /* @__PURE__ */ new Set([
  "label",
  "tooltip",
  "extra",
  "showLabel",
  "initialValue",
  "multiple",
  "allowMultiple",
  "maxCount",
  "name"
]);
const FIELD_PUBLIC_PROP_KEYS_BY_USE = {
  TableColumnModel: TABLE_FIELD_PUBLIC_PROP_KEYS,
  FormItemModel: FORM_FIELD_PUBLIC_PROP_KEYS,
  PatternFormItemModel: FORM_FIELD_PUBLIC_PROP_KEYS,
  DetailsItemModel: DETAIL_FIELD_PUBLIC_PROP_KEYS,
  ApprovalDetailsItemModel: DETAIL_FIELD_PUBLIC_PROP_KEYS,
  ApplyTaskCardDetailsItemModel: DETAIL_FIELD_PUBLIC_PROP_KEYS,
  ApprovalTaskCardDetailsItemModel: DETAIL_FIELD_PUBLIC_PROP_KEYS,
  FormAssociationItemModel: DETAIL_FIELD_PUBLIC_PROP_KEYS,
  FilterFormItemModel: FILTER_FIELD_PUBLIC_PROP_KEYS
};
const REACTION_CONTEXT_SCALAR_PATHS = /* @__PURE__ */ new Set(["role", "locale", "token", "deviceType"]);
const REACTION_CONTEXT_ROOT_PATHS = /* @__PURE__ */ new Set([
  "user",
  "collection",
  "formValues",
  "record",
  "item",
  "popup",
  "urlSearchParams"
]);
const FIELD_TYPES_WITH_NESTED_FIELDS = /* @__PURE__ */ new Set([
  "picker",
  "subForm",
  "subFormList",
  "subDetails",
  "subDetailsList",
  "subTable",
  "popupSubTable"
]);
const REACTION_KIND_TO_BLUEPRINT_TYPE = {
  fieldValue: "setFieldValueRules",
  blockLinkage: "setBlockLinkageRules",
  fieldLinkage: "setFieldLinkageRules",
  actionLinkage: "setActionLinkageRules"
};
function isNode(value) {
  return !!value && typeof value === "object" && !Array.isArray(value);
}
function castNodeArray(value) {
  return import_lodash.default.castArray(value || []).filter(isNode);
}
function getSubNode(node, key) {
  var _a;
  const value = (_a = node == null ? void 0 : node.subModels) == null ? void 0 : _a[key];
  if (Array.isArray(value)) {
    return value.find(isNode);
  }
  return isNode(value) ? value : void 0;
}
function getSubNodeArray(node, key) {
  var _a;
  return castNodeArray((_a = node == null ? void 0 : node.subModels) == null ? void 0 : _a[key]);
}
function readString(value) {
  const normalized = typeof value === "string" ? value.trim() : "";
  return normalized || void 0;
}
function readStringOrNull(value) {
  if (import_lodash.default.isNull(value)) {
    return null;
  }
  return readString(value);
}
function readBoolean(value) {
  return typeof value === "boolean" ? value : void 0;
}
function readNumber(value) {
  return typeof value === "number" ? value : void 0;
}
function clonePlainObject(value) {
  return import_lodash.default.isPlainObject(value) ? import_lodash.default.cloneDeep(value) : void 0;
}
function cloneArray(value) {
  return Array.isArray(value) ? import_lodash.default.cloneDeep(value) : void 0;
}
function cloneDefinedValue(value) {
  return import_lodash.default.isUndefined(value) ? void 0 : import_lodash.default.cloneDeep(value);
}
function firstDefined(...values) {
  return values.find((value) => !import_lodash.default.isUndefined(value));
}
function hasOwnValue(value, key) {
  return !!value && Object.prototype.hasOwnProperty.call(value, key) && !import_lodash.default.isUndefined(value[key]);
}
function getOwnValue(value, key) {
  return hasOwnValue(value, key) ? import_lodash.default.cloneDeep(value == null ? void 0 : value[key]) : void 0;
}
function hasNonEmptyPlainObject(value) {
  return import_lodash.default.isPlainObject(value) && Object.keys(value).length > 0;
}
function exportTemplateSummary(value) {
  if (!import_lodash.default.isPlainObject(value)) {
    return void 0;
  }
  const uid = readString(value.uid);
  const local = readString(value.local);
  if (!uid && !local) {
    return void 0;
  }
  return buildDefinedPayload({
    uid,
    local,
    mode: readString(value.mode)
  });
}
function exportPopupSummary(value) {
  if (!import_lodash.default.isPlainObject(value)) {
    return void 0;
  }
  const template = exportTemplateSummary(value.template);
  return template ? { template } : void 0;
}
function hasUnsupportedTemplateSummary(node) {
  const popup = node == null ? void 0 : node.popup;
  const hasUnsupportedBlockTemplate = hasNonEmptyPlainObject(node == null ? void 0 : node.template) && !exportTemplateSummary(node == null ? void 0 : node.template);
  const hasUnsupportedPopupTemplate = readString(popup == null ? void 0 : popup.mode) === "copy" || hasNonEmptyPlainObject(popup == null ? void 0 : popup.template) && !exportPopupSummary(popup);
  return hasUnsupportedBlockTemplate || hasNonEmptyPlainObject(node == null ? void 0 : node.fieldsTemplate) || hasUnsupportedPopupTemplate;
}
function templateSummaryManualAction(kind) {
  if (kind === "block") {
    return "Recreate this template-backed block manually or add mapper support.";
  }
  if (kind === "field") {
    return "Recreate this template-backed field popup manually or add mapper support.";
  }
  if (kind === "action" || kind === "recordAction") {
    return "Recreate this template-backed action popup manually or add mapper support.";
  }
  return "Recreate this template-backed surface manually or add mapper support.";
}
function isEmptyPlainContainer(value) {
  if (import_lodash.default.isUndefined(value) || value === null) {
    return true;
  }
  if (import_lodash.default.isPlainObject(value)) {
    return Object.values(value).every(isEmptyPlainContainer);
  }
  if (Array.isArray(value)) {
    return value.length === 0;
  }
  return false;
}
function collectLeafPaths(value, prefix = "") {
  if (!import_lodash.default.isPlainObject(value)) {
    return isEmptyPlainContainer(value) ? [] : [prefix];
  }
  return Object.entries(value).flatMap(([key, child]) => {
    const childPath = prefix ? `${prefix}.${key}` : key;
    if (isEmptyPlainContainer(child)) {
      return [];
    }
    return collectLeafPaths(child, childPath);
  });
}
function pathMatchesAllowed(candidate, allowedPath) {
  if (allowedPath.endsWith(".*")) {
    const prefix = allowedPath.slice(0, -2);
    return candidate === prefix || candidate.startsWith(`${prefix}.`);
  }
  return candidate === allowedPath;
}
function hasUnsupportedLeafPath(value, allowedPaths) {
  return collectLeafPaths(value).some(
    (path) => !allowedPaths.some((allowedPath) => pathMatchesAllowed(path, allowedPath))
  );
}
function getPublicStepParamKeys(stepParams) {
  return Object.keys(stepParams).filter((key) => key !== import_key_registry.FLOW_SURFACE_INTERNAL_META_KEY);
}
function buildDefinedPayload(input) {
  return import_lodash.default.pickBy(input, (value) => !import_lodash.default.isUndefined(value));
}
function getByPath(node, path) {
  return import_lodash.default.get(node, path);
}
function recordUnsupported(ctx, item) {
  ctx.unsupported.push(item);
  ctx.warnings.push(`${item.path}: ${item.reasonCode} (${item.use || item.type || item.kind})`);
}
function assertNoUnsupported(ctx) {
  if (ctx.unsupportedPolicy !== "error" || !ctx.unsupported.length) {
    return;
  }
  const first = ctx.unsupported[0];
  (0, import_errors.throwBadRequest)(
    `flowSurfaces exportBlueprint cannot export ${first.kind} '${first.use || first.type || "unknown"}' at ${first.path}: ${first.reasonCode}`
  );
}
function normalizeKeyCandidate(value, fallback, context) {
  const token = (0, import_private_utils.normalizeApplyBlueprintToken)(value, fallback);
  return (0, import_service_utils.normalizeFlowSurfaceComposeKey)(token, context);
}
function stripScopePrefix(key, scopePrefix) {
  const normalized = String(key || "").trim();
  if (!normalized || !scopePrefix) {
    return normalized;
  }
  const prefix = `${scopePrefix}.`;
  if (normalized.startsWith(prefix)) {
    return normalized.slice(prefix.length);
  }
  if (normalized.includes(".")) {
    return normalized.split(".").filter(Boolean).pop() || normalized;
  }
  return normalized;
}
function getDeclaredKey(node, scopePrefix) {
  return stripScopePrefix((0, import_key_registry.getDeclaredKeyFromNode)(node), scopePrefix);
}
function inferTabDeclaredKeyFromChildren(tab) {
  const visit = (node) => {
    const rawKey = (0, import_key_registry.getDeclaredKeyFromNode)(node);
    if (rawKey == null ? void 0 : rawKey.includes(".")) {
      return rawKey.split(".").filter(Boolean)[0];
    }
    for (const value of Object.values((node == null ? void 0 : node.subModels) || {})) {
      for (const child of castNodeArray(value)) {
        const matched = visit(child);
        if (matched) {
          return matched;
        }
      }
    }
    return void 0;
  };
  return visit(tab);
}
function dedupeKey(ctx, scope, candidate, fallback, path) {
  const normalized = normalizeKeyCandidate(candidate || fallback, fallback, path);
  if (!scope.used.has(normalized)) {
    scope.used.add(normalized);
    return normalized;
  }
  let suffix = 2;
  let next = `${normalized}_${suffix}`;
  while (scope.used.has(next)) {
    suffix += 1;
    next = `${normalized}_${suffix}`;
  }
  scope.used.add(next);
  ctx.warnings.push(`${path}: key '${normalized}' collided; exported as '${next}'`);
  return next;
}
function readPageTitle(page) {
  var _a;
  return readString(getByPath(page, ["stepParams", "pageSettings", "general", "title"])) || readString((_a = page.props) == null ? void 0 : _a.title);
}
function exportPage(ctx, page, pageRoute) {
  var _a, _b, _c, _d;
  if (hasNonEmptyPlainObject(page.flowRegistry)) {
    recordUnsupported(ctx, {
      kind: "page",
      use: readString(page.use),
      path: "$.page.flowRegistry",
      reasonCode: FLOW_REGISTRY_UNSUPPORTED_REASON,
      manualAction: "Recreate these event flows manually or add mapper support."
    });
  }
  const general = getByPath(page, ["stepParams", "pageSettings", "general"]) || {};
  return buildDefinedPayload({
    title: readPageTitle(page),
    icon: readString(general.icon) || readString((_a = page.props) == null ? void 0 : _a.icon),
    documentTitle: readString(general.documentTitle),
    enableHeader: typeof general.enableHeader === "boolean" ? general.enableHeader : typeof ((_b = page.props) == null ? void 0 : _b.enableHeader) === "boolean" ? page.props.enableHeader : void 0,
    enableTabs: typeof general.enableTabs === "boolean" ? general.enableTabs : typeof ((_c = page.props) == null ? void 0 : _c.enableTabs) === "boolean" ? page.props.enableTabs : void 0,
    displayTitle: typeof general.displayTitle === "boolean" ? general.displayTitle : typeof ((_d = page.props) == null ? void 0 : _d.displayTitle) === "boolean" ? page.props.displayTitle : void 0
  });
}
function readTabTitle(tab) {
  var _a;
  return readString(getByPath(tab, ["stepParams", "pageTabSettings", "tab", "title"])) || readString((_a = tab.props) == null ? void 0 : _a.title);
}
function exportTabChrome(tab) {
  var _a;
  const tabSettings = getByPath(tab, ["stepParams", "pageTabSettings", "tab"]) || {};
  return buildDefinedPayload({
    title: readTabTitle(tab),
    icon: readString(tabSettings.icon) || readString((_a = tab.props) == null ? void 0 : _a.icon),
    documentTitle: readString(tabSettings.documentTitle)
  });
}
function readResourceInit(block) {
  return clonePlainObject(getByPath(block, ["stepParams", "resourceSettings", "init"])) || clonePlainObject(getByPath(block, ["stepParams", "TriggerChildPageSettings", "init"])) || clonePlainObject(getByPath(block, ["stepParams", "ApprovalChildPageSettings", "init"]));
}
function readBlockResourceContext(block) {
  const resourceInit = readResourceInit(block);
  const collectionName = readString(resourceInit == null ? void 0 : resourceInit.collectionName);
  const dataSourceKey = readString(resourceInit == null ? void 0 : resourceInit.dataSourceKey) || (collectionName ? "main" : void 0);
  const associationName = readString(resourceInit == null ? void 0 : resourceInit.associationName);
  return buildDefinedPayload({
    dataSourceKey,
    collectionName,
    associationName
  });
}
function exportBlockResource(block) {
  const resourceInit = readResourceInit(block);
  if (!resourceInit) {
    return {};
  }
  const dataSourceKey = readString(resourceInit.dataSourceKey);
  const collectionName = readString(resourceInit.collectionName);
  const associationName = readString(resourceInit.associationName);
  const associationPathName = readString(resourceInit.associationPathName);
  const sourceId = resourceInit.sourceId;
  const filterByTk = resourceInit.filterByTk;
  if (collectionName && (!dataSourceKey || dataSourceKey === "main") && !associationName && !associationPathName && import_lodash.default.isUndefined(sourceId) && import_lodash.default.isUndefined(filterByTk)) {
    return {
      collection: collectionName
    };
  }
  return {
    resource: buildDefinedPayload({
      dataSourceKey: dataSourceKey || (collectionName ? "main" : void 0),
      collectionName,
      associationName,
      associationPathName,
      sourceId,
      filterByTk
    })
  };
}
function exportDataBlockSettings(block, type) {
  if (type === "recordHistory") {
    return {};
  }
  const groupKey = DATA_BLOCK_SETTING_GROUP_BY_TYPE[type];
  if (!groupKey) {
    return {};
  }
  const group = getByPath(block, ["stepParams", groupKey]) || {};
  const defaultFilter = clonePlainObject(import_lodash.default.get(group, ["dataScope", "filter"]));
  const sorting = import_lodash.default.cloneDeep(import_lodash.default.get(group, ["defaultSorting", "sort"]));
  const pageSize = import_lodash.default.get(group, ["pageSize", "pageSize"]);
  const settings = buildDefinedPayload({
    sorting: import_lodash.default.isUndefined(sorting) ? void 0 : sorting,
    pageSize: typeof pageSize === "number" ? pageSize : void 0
  });
  return buildDefinedPayload({
    defaultFilter,
    sorting: import_lodash.default.isUndefined(sorting) ? void 0 : sorting,
    pageSize: typeof pageSize === "number" ? pageSize : void 0,
    settings: Object.keys(settings).length ? settings : void 0
  });
}
function exportListBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "list") {
    return {};
  }
  const listSettings = getByPath(block, ["stepParams", "listSettings"]) || {};
  const settings = buildDefinedPayload({
    pageSize: readNumber(import_lodash.default.get(listSettings, ["pageSize", "pageSize"])),
    sorting: cloneDefinedValue(import_lodash.default.get(listSettings, ["defaultSorting", "sort"])),
    layout: readString(import_lodash.default.get(listSettings, ["layout", "layout"]))
  });
  return Object.keys(settings).length ? { settings } : {};
}
function exportGridCardBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "gridCard") {
    return {};
  }
  const gridCardSettings = getByPath(block, ["stepParams", "GridCardSettings"]) || {};
  const settings = buildDefinedPayload({
    columns: clonePlainObject(import_lodash.default.get(gridCardSettings, ["columnCount", "columnCount"])),
    rowCount: readNumber(import_lodash.default.get(gridCardSettings, ["rowCount", "rowCount"])),
    sorting: cloneDefinedValue(import_lodash.default.get(gridCardSettings, ["defaultSorting", "sort"])),
    layout: readString(import_lodash.default.get(gridCardSettings, ["layout", "layout"]))
  });
  return Object.keys(settings).length ? { settings } : {};
}
function exportTreeBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "tree") {
    return {};
  }
  const props = block.props || {};
  const treeSettings = getByPath(block, ["stepParams", "treeSettings"]) || {};
  const settings = buildDefinedPayload({
    searchable: typeof props.searchable === "boolean" ? props.searchable : typeof import_lodash.default.get(treeSettings, ["searchable", "searchable"]) === "boolean" ? import_lodash.default.get(treeSettings, ["searchable", "searchable"]) : void 0,
    defaultExpandAll: typeof props.defaultExpandAll === "boolean" ? props.defaultExpandAll : typeof import_lodash.default.get(treeSettings, ["defaultExpandAll", "defaultExpandAll"]) === "boolean" ? import_lodash.default.get(treeSettings, ["defaultExpandAll", "defaultExpandAll"]) : void 0,
    includeDescendants: typeof props.includeDescendants === "boolean" ? props.includeDescendants : typeof import_lodash.default.get(treeSettings, ["includeDescendants", "includeDescendants"]) === "boolean" ? import_lodash.default.get(treeSettings, ["includeDescendants", "includeDescendants"]) : void 0,
    fieldNames: clonePlainObject(props.fieldNames),
    titleField: readString(import_lodash.default.get(treeSettings, ["titleField", "titleField"])),
    pageSize: typeof props.pageSize === "number" ? props.pageSize : typeof import_lodash.default.get(treeSettings, ["pageSize", "pageSize"]) === "number" ? import_lodash.default.get(treeSettings, ["pageSize", "pageSize"]) : void 0
  });
  return Object.keys(settings).length ? {
    settings
  } : {};
}
function readBooleanSetting(propValue, settingValue) {
  if (typeof propValue === "boolean") {
    return propValue;
  }
  return typeof settingValue === "boolean" ? settingValue : void 0;
}
function readNumberSetting(propValue, settingValue) {
  if (typeof propValue === "number") {
    return propValue;
  }
  return typeof settingValue === "number" ? settingValue : void 0;
}
function readKanbanPopupSetting(block, key) {
  if (key === "quickCreatePopup") {
    const stepValue2 = getByPath(block, ["stepParams", "kanbanSettings", "popup"]);
    if (import_lodash.default.isPlainObject(stepValue2)) {
      return stepValue2;
    }
    const props2 = block.props || {};
    const propValue2 = import_lodash.default.isPlainObject(props2.quickCreatePopupSettings) ? props2.quickCreatePopupSettings : buildDefinedPayload({
      mode: props2.popupMode,
      size: props2.popupSize,
      popupTemplateUid: props2.popupTemplateUid,
      pageModelClass: props2.popupPageModelClass,
      uid: props2.popupTargetUid
    });
    return import_lodash.default.isPlainObject(propValue2) ? propValue2 : void 0;
  }
  const item = getSubNode(block, "item");
  const stepValue = getByPath(item, ["stepParams", "cardSettings", "popup"]);
  if (import_lodash.default.isPlainObject(stepValue)) {
    return stepValue;
  }
  const props = (item == null ? void 0 : item.props) || {};
  const propValue = import_lodash.default.isPlainObject(props.cardPopupSettings) ? props.cardPopupSettings : buildDefinedPayload({
    mode: props.openMode,
    size: props.popupSize,
    popupTemplateUid: props.popupTemplateUid,
    pageModelClass: props.pageModelClass,
    uid: props.popupTargetUid
  });
  return import_lodash.default.isPlainObject(propValue) ? propValue : void 0;
}
function exportKanbanPopupSetting(block, key) {
  const value = readKanbanPopupSetting(block, key);
  if (!value) {
    return void 0;
  }
  const exported = buildDefinedPayload({
    mode: readString(value.mode),
    size: readString(value.size),
    title: readString(value.title),
    tryTemplate: readBoolean(value.tryTemplate),
    defaultType: readString(value.defaultType)
  });
  return Object.keys(exported).length ? exported : void 0;
}
function exportKanbanBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "kanban") {
    return {};
  }
  const props = block.props || {};
  const kanbanSettings = getByPath(block, ["stepParams", "kanbanSettings"]) || {};
  const item = getSubNode(block, "item");
  const itemProps = (item == null ? void 0 : item.props) || {};
  const itemCardSettings = getByPath(item, ["stepParams", "cardSettings"]) || {};
  const styleVariant = readString(import_lodash.default.get(kanbanSettings, ["styleVariant", "styleVariant"]));
  const settings = buildDefinedPayload({
    groupField: readString(import_lodash.default.get(kanbanSettings, ["grouping", "groupField"])) || readString(props.groupField),
    groupTitleField: import_lodash.default.has(kanbanSettings, ["grouping", "groupTitleField"]) ? readStringOrNull(import_lodash.default.get(kanbanSettings, ["grouping", "groupTitleField"])) : readStringOrNull(props.groupTitleField),
    groupColorField: import_lodash.default.has(kanbanSettings, ["grouping", "groupColorField"]) ? readStringOrNull(import_lodash.default.get(kanbanSettings, ["grouping", "groupColorField"])) : readStringOrNull(props.groupColorField),
    groupOptions: firstDefined(
      cloneArray(import_lodash.default.get(kanbanSettings, ["grouping", "groupOptions"])),
      cloneArray(props.groupOptions)
    ),
    styleVariant: styleVariant || (readString(props.styleVariant) === "color" ? "filled" : readString(props.styleVariant) === "default" ? "default" : void 0),
    sorting: firstDefined(
      cloneDefinedValue(import_lodash.default.get(kanbanSettings, ["defaultSorting", "sort"])),
      cloneDefinedValue(props.globalSort)
    ),
    dragEnabled: readBooleanSetting(props.dragEnabled, import_lodash.default.get(kanbanSettings, ["dragEnabled", "dragEnabled"])),
    dragSortBy: firstDefined(
      readStringOrNull(import_lodash.default.get(kanbanSettings, ["dragSortBy", "dragSortBy"])),
      readStringOrNull(props.dragSortBy)
    ),
    quickCreateEnabled: readBooleanSetting(
      props.quickCreateEnabled,
      import_lodash.default.get(kanbanSettings, ["quickCreate", "quickCreateEnabled"])
    ),
    quickCreatePopup: exportKanbanPopupSetting(block, "quickCreatePopup"),
    enableCardClick: readBooleanSetting(
      itemProps.enableCardClick,
      import_lodash.default.get(itemCardSettings, ["click", "enableCardClick"])
    ),
    cardPopup: exportKanbanPopupSetting(block, "cardPopup"),
    cardLayout: readString(itemProps.layout) || readString(import_lodash.default.get(itemCardSettings, ["layout", "layout"])),
    cardLabelAlign: readString(itemProps.labelAlign) || readString(import_lodash.default.get(itemCardSettings, ["layout", "labelAlign"])),
    cardLabelWidth: firstDefined(
      readStringOrNull(itemProps.labelWidth),
      readStringOrNull(import_lodash.default.get(itemCardSettings, ["layout", "labelWidth"]))
    ),
    cardLabelWrap: readBooleanSetting(itemProps.labelWrap, import_lodash.default.get(itemCardSettings, ["layout", "labelWrap"])),
    cardColon: readBooleanSetting(itemProps.colon, import_lodash.default.get(itemCardSettings, ["layout", "colon"])),
    pageSize: readNumberSetting(props.pageSize, import_lodash.default.get(kanbanSettings, ["pageSize", "pageSize"])),
    columnWidth: readNumberSetting(props.columnWidth, import_lodash.default.get(kanbanSettings, ["columnWidth", "columnWidth"]))
  });
  return Object.keys(settings).length ? { settings } : {};
}
function readCalendarPopupSetting(block, key) {
  var _a;
  const stepValue = getByPath(block, ["stepParams", "calendarSettings", key]);
  if (import_lodash.default.isPlainObject(stepValue)) {
    return stepValue;
  }
  const propValue = (_a = block.props) == null ? void 0 : _a[key];
  return import_lodash.default.isPlainObject(propValue) ? propValue : void 0;
}
function exportCalendarPopupSetting(block, key) {
  const value = readCalendarPopupSetting(block, key);
  if (!value) {
    return void 0;
  }
  const exported = buildDefinedPayload({
    mode: readString(value.mode),
    size: readString(value.size),
    title: readString(value.title),
    tryTemplate: typeof value.tryTemplate === "boolean" ? value.tryTemplate : void 0,
    defaultType: readString(value.defaultType)
  });
  return Object.keys(exported).length ? exported : void 0;
}
function hasUnsupportedCalendarPopupSetting(block, key) {
  const value = readCalendarPopupSetting(block, key);
  if (!value) {
    return false;
  }
  return Object.keys(value).some((itemKey) => {
    const child = value[itemKey];
    if (import_lodash.default.isUndefined(child)) {
      return false;
    }
    return !EXPORTED_CALENDAR_POPUP_KEYS.has(itemKey) && !IGNORED_CALENDAR_POPUP_RUNTIME_KEYS.has(itemKey);
  });
}
function exportCalendarBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "calendar") {
    return {};
  }
  const props = block.props || {};
  const fieldNames = import_lodash.default.isPlainObject(props.fieldNames) ? props.fieldNames : {};
  const calendarSettings = getByPath(block, ["stepParams", "calendarSettings"]) || {};
  const settings = buildDefinedPayload({
    titleField: readString(fieldNames.title) || readString(import_lodash.default.get(calendarSettings, ["titleField", "titleField"])),
    colorField: readString(fieldNames.colorFieldName) || readString(import_lodash.default.get(calendarSettings, ["colorField", "colorFieldName"])),
    startField: readString(fieldNames.start) || readString(import_lodash.default.get(calendarSettings, ["startDateField", "start"])),
    endField: readString(fieldNames.end) || readString(import_lodash.default.get(calendarSettings, ["endDateField", "end"])),
    defaultView: readString(props.defaultView) || readString(import_lodash.default.get(calendarSettings, ["defaultView", "defaultView"])),
    quickCreateEvent: readBooleanSetting(
      props.enableQuickCreateEvent,
      import_lodash.default.get(calendarSettings, ["quickCreateEvent", "enableQuickCreateEvent"])
    ),
    showLunar: readBooleanSetting(props.showLunar, import_lodash.default.get(calendarSettings, ["showLunar", "showLunar"])),
    weekStart: readNumberSetting(props.weekStart, import_lodash.default.get(calendarSettings, ["weekStart", "weekStart"])),
    quickCreatePopup: exportCalendarPopupSetting(block, "quickCreatePopupSettings"),
    eventPopup: exportCalendarPopupSetting(block, "eventPopupSettings")
  });
  return Object.keys(settings).length ? {
    settings
  } : {};
}
function exportActionPanelBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "actionPanel") {
    return {};
  }
  const props = block.props || {};
  const group = getByPath(block, ["stepParams", "actionPanelBlockSetting"]) || {};
  const settings = buildDefinedPayload({
    layout: readString(props.layout) || readString(import_lodash.default.get(group, ["layout", "layout"])),
    ellipsis: readBooleanSetting(props.ellipsis, import_lodash.default.get(group, ["ellipsis", "ellipsis"]))
  });
  return Object.keys(settings).length ? { settings } : {};
}
function exportRecordHistoryBlockSettings(block) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "recordHistory") {
    return {};
  }
  const group = getByPath(block, ["stepParams", "recordHistorySettings"]) || {};
  const settings = buildDefinedPayload({
    sortOrder: clonePlainObject(import_lodash.default.get(group, ["sortOrder"])),
    dataScope: clonePlainObject(import_lodash.default.get(group, ["dataScope", "filter"])),
    expand: clonePlainObject(import_lodash.default.get(group, ["expand"])),
    template: clonePlainObject(import_lodash.default.get(group, ["template"]))
  });
  return Object.keys(settings).length ? { settings } : {};
}
function createChartAssetKey(ctx, publicKey) {
  const base = (0, import_private_utils.normalizeApplyBlueprintToken)(publicKey, "chart");
  let candidate = base;
  let index = 2;
  while (Object.prototype.hasOwnProperty.call(ctx.chartAssets, candidate)) {
    candidate = `${base}_${index}`;
    index += 1;
  }
  return candidate;
}
function exportChartBlockSettings(ctx, block, publicKey, path) {
  if (import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || "")) !== "chart") {
    return {};
  }
  const configure = clonePlainObject(getByPath(block, ["stepParams", "chartSettings", "configure"]));
  const semanticState = (0, import_chart_config.deriveChartSemanticState)(configure);
  if (!semanticState.query || !semanticState.visual) {
    recordUnsupported(ctx, {
      kind: "block",
      use: readString(block.use),
      type: "chart",
      path: `${path}.settings`,
      reasonCode: "unsupported-chart-configure",
      manualAction: "Recreate this chart configuration manually or add mapper support."
    });
    return null;
  }
  const assetKey = createChartAssetKey(ctx, publicKey);
  ctx.chartAssets[assetKey] = buildDefinedPayload({
    query: semanticState.query,
    visual: semanticState.visual,
    events: semanticState.events
  });
  return {
    chart: assetKey
  };
}
function exportCardSettings(block) {
  const cardSettings = getByPath(block, ["stepParams", "cardSettings"]) || {};
  const titleDescription = import_lodash.default.get(cardSettings, ["titleDescription"]);
  const blockHeight = import_lodash.default.get(cardSettings, ["blockHeight"]);
  return buildDefinedPayload({
    title: readString(titleDescription == null ? void 0 : titleDescription.title),
    description: readString(titleDescription == null ? void 0 : titleDescription.description),
    height: typeof (blockHeight == null ? void 0 : blockHeight.height) === "number" ? blockHeight.height : void 0,
    heightMode: readString(blockHeight == null ? void 0 : blockHeight.heightMode)
  });
}
function exportSimpleBlockSettings(block, type) {
  var _a, _b, _c, _d;
  if (type === "markdown") {
    const content = readString(getByPath(block, ["stepParams", "markdownBlockSettings", "editMarkdown", "content"])) || readString((_a = block.props) == null ? void 0 : _a.content) || readString((_b = block.props) == null ? void 0 : _b.value);
    return content ? { settings: { content } } : {};
  }
  if (type === "jsBlock") {
    const runJs = clonePlainObject(getByPath(block, ["stepParams", "jsSettings", "runJs"]));
    const showBlockCard = getByPath(block, ["stepParams", "jsSettings", "showBlockCard", "showBlockCard"]);
    const settings = buildDefinedPayload({
      ...runJs || {},
      showBlockCard: showBlockCard === false ? false : void 0
    });
    return buildDefinedPayload({
      title: readString((_c = block.decoratorProps) == null ? void 0 : _c.title),
      description: readString((_d = block.decoratorProps) == null ? void 0 : _d.description),
      settings: Object.keys(settings).length ? settings : void 0
    });
  }
  if (type === "iframe") {
    const editIframe = clonePlainObject(getByPath(block, ["stepParams", "iframeBlockSettings", "editIframe"]));
    return editIframe ? { settings: editIframe } : {};
  }
  return {};
}
function getAllowedBlockStepParamPaths(type, groupKey) {
  if (groupKey === "eventSettings") {
    return ["linkageRules.value"];
  }
  const simpleBlockSettings = EXPORTED_SIMPLE_BLOCK_SETTING_PATHS_BY_TYPE[type];
  if (type === "markdown" && groupKey === "markdownBlockSettings" || type === "jsBlock" && groupKey === "jsSettings" || type === "iframe" && groupKey === "iframeBlockSettings") {
    return simpleBlockSettings || [];
  }
  return EXPORTED_BLOCK_STEP_PARAM_PATHS_BY_GROUP[groupKey];
}
function hasUnsupportedBlockProps(block, type) {
  const props = block.props || {};
  const propKeys = Object.keys(props).filter((key) => !import_lodash.default.isUndefined(props[key]));
  if (!propKeys.length) {
    return false;
  }
  if (type === "markdown") {
    return propKeys.some((key) => key !== "content" && key !== "value");
  }
  if (type === "tree") {
    return propKeys.some((key) => !EXPORTED_TREE_BLOCK_PROP_KEYS.has(key));
  }
  if (type === "calendar") {
    return propKeys.some((key) => !EXPORTED_CALENDAR_BLOCK_PROP_KEYS.has(key));
  }
  if (type === "kanban") {
    return propKeys.some((key) => !EXPORTED_KANBAN_BLOCK_PROP_KEYS.has(key));
  }
  if (type === "actionPanel") {
    return propKeys.some((key) => !EXPORTED_ACTION_PANEL_BLOCK_PROP_KEYS.has(key));
  }
  if (type === "jsBlock") {
    return false;
  }
  return true;
}
function hasUnsupportedKanbanPopupSetting(block, key) {
  const value = readKanbanPopupSetting(block, key);
  if (!value) {
    return false;
  }
  return Object.keys(value).some((itemKey) => {
    const child = value[itemKey];
    if (import_lodash.default.isUndefined(child)) {
      return false;
    }
    return !EXPORTED_KANBAN_POPUP_KEYS.has(itemKey) && !IGNORED_KANBAN_POPUP_RUNTIME_KEYS.has(itemKey);
  });
}
function hasUnsupportedKanbanItemPublicState(block) {
  const item = getSubNode(block, "item");
  if (!item) {
    return false;
  }
  if (hasNonEmptyPlainObject(item.flowRegistry)) {
    return true;
  }
  const props = item.props || {};
  const propKeys = Object.keys(props).filter((key) => !import_lodash.default.isUndefined(props[key]));
  if (propKeys.some((key) => !EXPORTED_KANBAN_CARD_ITEM_PROP_KEYS.has(key))) {
    return true;
  }
  return Object.entries(item.stepParams || {}).some(([groupKey, groupValue]) => {
    if (groupKey === import_key_registry.FLOW_SURFACE_INTERNAL_META_KEY || isEmptyPlainContainer(groupValue)) {
      return false;
    }
    if (groupKey !== "cardSettings") {
      return true;
    }
    return hasUnsupportedLeafPath(groupValue, EXPORTED_KANBAN_CARD_ITEM_SETTING_PATHS);
  });
}
function hasUnsupportedJsBlockDecoratorProps(block) {
  const decoratorProps = block.decoratorProps || {};
  return Object.keys(decoratorProps).some((key) => {
    const value = decoratorProps[key];
    if (import_lodash.default.isUndefined(value)) {
      return false;
    }
    if (EXPORTED_JS_BLOCK_DECORATOR_PROP_KEYS.has(key)) {
      return false;
    }
    if (key === "className") {
      return !!readString(value);
    }
    return true;
  });
}
function hasUnsupportedBlockPublicState(block, type) {
  if (hasNonEmptyPlainObject(block.flowRegistry)) {
    return true;
  }
  if (hasUnsupportedBlockProps(block, type)) {
    return true;
  }
  if (type === "calendar" && (hasUnsupportedCalendarPopupSetting(block, "quickCreatePopupSettings") || hasUnsupportedCalendarPopupSetting(block, "eventPopupSettings"))) {
    return true;
  }
  if (type === "kanban" && (hasUnsupportedKanbanPopupSetting(block, "quickCreatePopup") || hasUnsupportedKanbanPopupSetting(block, "cardPopup") || hasUnsupportedKanbanItemPublicState(block))) {
    return true;
  }
  if (type === "jsBlock" && hasUnsupportedJsBlockDecoratorProps(block)) {
    return true;
  }
  return Object.entries(block.stepParams || {}).some(([groupKey, groupValue]) => {
    if (groupKey === import_key_registry.FLOW_SURFACE_INTERNAL_META_KEY || isEmptyPlainContainer(groupValue)) {
      return false;
    }
    const allowedPaths = getAllowedBlockStepParamPaths(type, groupKey);
    if (!allowedPaths) {
      return true;
    }
    return hasUnsupportedLeafPath(groupValue, allowedPaths);
  });
}
function readFieldInit(fieldHost) {
  return clonePlainObject(getByPath(fieldHost, ["stepParams", "fieldSettings", "init"])) || clonePlainObject(getByPath(getSubNode(fieldHost, "field"), ["stepParams", "fieldSettings", "init"]));
}
function readFieldPath(fieldHost) {
  var _a;
  return readString((_a = readFieldInit(fieldHost)) == null ? void 0 : _a.fieldPath);
}
function collectFieldBindingUids(fieldHost) {
  var _a;
  return import_lodash.default.uniq(compactStringValues([fieldHost.uid, (_a = getSubNode(fieldHost, "field")) == null ? void 0 : _a.uid]));
}
function collectNestedFieldHostCandidates(fieldHost, rootFieldPath) {
  const candidates = [];
  const seenFieldPaths = /* @__PURE__ */ new Set();
  const visit = (node) => {
    if (!node) {
      return;
    }
    const fieldPath = readFieldPath(node);
    if (fieldPath && fieldPath !== rootFieldPath && !seenFieldPaths.has(fieldPath)) {
      seenFieldPaths.add(fieldPath);
      candidates.push(node);
    }
    Object.values(node.subModels || {}).forEach((value) => {
      castNodeArray(value).forEach((child) => visit(child));
    });
  };
  Object.values(fieldHost.subModels || {}).forEach((value) => {
    castNodeArray(value).forEach((child) => visit(child));
  });
  return candidates;
}
function collectExportableNestedRelationFields(ctx, fieldHost, rootFieldPath, path) {
  const fields = [];
  const fieldPaths = [];
  const candidates = collectNestedFieldHostCandidates(fieldHost, rootFieldPath);
  candidates.forEach((candidate, index) => {
    const fieldPath = readFieldPath(candidate);
    const relativeFieldPath = (fieldPath == null ? void 0 : fieldPath.startsWith(`${rootFieldPath}.`)) ? fieldPath.slice(rootFieldPath.length + 1) : fieldPath;
    if (!fieldPath || !relativeFieldPath) {
      return;
    }
    const unsupportedReason = hasUnsupportedTemplateSummary(candidate) ? TEMPLATE_SUMMARY_UNSUPPORTED_REASON : isExportableNestedRelationField(candidate, relativeFieldPath) ? void 0 : "unsupported-node";
    if (unsupportedReason) {
      recordUnsupported(ctx, {
        kind: "field",
        use: readString(candidate.use),
        path: `${path}[${index}]`,
        reasonCode: unsupportedReason,
        manualAction: unsupportedReason === TEMPLATE_SUMMARY_UNSUPPORTED_REASON ? templateSummaryManualAction("field") : UNSUPPORTED_MANUAL_ACTION
      });
      return;
    }
    fields.push(relativeFieldPath);
    fieldPaths.push(fieldPath);
  });
  return {
    fields: import_lodash.default.uniq(fields),
    fieldPaths: import_lodash.default.uniq(fieldPaths)
  };
}
const DEFAULT_RELATION_OPEN_VIEW_SOURCE_ID = "{{ctx.view.inputArgs.sourceId}}";
const DEFAULT_RELATION_OPEN_VIEW_FILTER_BY_TK = "{{ctx.view.inputArgs.filterByTk}}";
const DEFAULT_RELATION_OPEN_VIEW_KEYS = /* @__PURE__ */ new Set([
  "dataSourceKey",
  "collectionName",
  "associationName",
  "sourceId",
  "filterByTk"
]);
function isDefaultRelationOpenViewValue(key, value) {
  if (key === "sourceId") {
    return import_lodash.default.isUndefined(value) || value === DEFAULT_RELATION_OPEN_VIEW_SOURCE_ID;
  }
  if (key === "filterByTk") {
    return import_lodash.default.isUndefined(value) || value === DEFAULT_RELATION_OPEN_VIEW_FILTER_BY_TK;
  }
  return !!readString(value);
}
function isDefaultRelationDisplayOpenView(value) {
  if (!import_lodash.default.isPlainObject(value)) {
    return false;
  }
  const entries = Object.entries(value).filter(([, child]) => !import_lodash.default.isUndefined(child));
  if (!entries.length || entries.some(([key]) => !DEFAULT_RELATION_OPEN_VIEW_KEYS.has(key))) {
    return false;
  }
  return entries.every(([key, child]) => isDefaultRelationOpenViewValue(key, child));
}
function isDefaultReferencePopupSummary(value) {
  if (import_lodash.default.isUndefined(value) || value === null) {
    return true;
  }
  if (!import_lodash.default.isPlainObject(value)) {
    return false;
  }
  const popup = value;
  if (!Object.keys(popup).length) {
    return true;
  }
  const template = popup.template;
  if (Object.keys(popup).some((key) => key !== "template") || !import_lodash.default.isPlainObject(template)) {
    return false;
  }
  const templateValue = template;
  return Object.keys(templateValue).every((key) => key === "uid" || key === "mode") && !!readString(templateValue.uid) && readString(templateValue.mode) === "reference";
}
function isDefaultRelationDisplayClickToOpenState(innerField) {
  return innerField.use === "DisplayTextFieldModel" && getByPath(innerField, ["stepParams", "displayFieldSettings", "clickToOpen", "clickToOpen"]) === true && isDefaultRelationDisplayOpenView(getByPath(innerField, ["stepParams", "popupSettings", "openView"])) && isDefaultReferencePopupSummary(innerField.popup);
}
function hasUnsupportedFieldHostProps(fieldHost) {
  const props = fieldHost.props;
  const propKeys = Object.keys(props || {}).filter((key) => !import_lodash.default.isUndefined(props == null ? void 0 : props[key]));
  if (!propKeys.length) {
    return false;
  }
  const allowedKeys = FIELD_PUBLIC_PROP_KEYS_BY_USE[String(fieldHost.use || "")] || /* @__PURE__ */ new Set();
  return propKeys.some((key) => {
    if (key === "titleField") {
      return (props == null ? void 0 : props[key]) !== null && typeof (props == null ? void 0 : props[key]) !== "string";
    }
    return !allowedKeys.has(key);
  });
}
function hasUnsupportedFieldDecoratorProps(fieldHost) {
  const decoratorProps = fieldHost.decoratorProps;
  const propKeys = Object.keys(decoratorProps || {}).filter((key) => !import_lodash.default.isUndefined(decoratorProps == null ? void 0 : decoratorProps[key]));
  if (!propKeys.length) {
    return false;
  }
  if (fieldHost.use === "TableColumnModel") {
    return true;
  }
  return propKeys.some((key) => !EXPORTED_FIELD_DECORATOR_PROP_KEYS.has(key));
}
function hasUnsupportedInnerFieldProps(innerField, options = {}) {
  const props = innerField.props;
  const propKeys = Object.keys(props || {}).filter((key) => !import_lodash.default.isUndefined(props == null ? void 0 : props[key]));
  if (!propKeys.length) {
    return false;
  }
  return propKeys.some((key) => {
    if (key === "titleField") {
      return (props == null ? void 0 : props[key]) !== null && typeof (props == null ? void 0 : props[key]) !== "string";
    }
    if (key === "clickToOpen" && options.allowDefaultClickToOpen) {
      return (props == null ? void 0 : props[key]) !== true;
    }
    return true;
  });
}
function hasUnsupportedFieldStepParams(fieldHost) {
  const stepParams = fieldHost.stepParams || {};
  return Object.entries(stepParams).some(([groupKey, groupValue]) => {
    if (groupKey === import_key_registry.FLOW_SURFACE_INTERNAL_META_KEY || isEmptyPlainContainer(groupValue)) {
      return false;
    }
    if (!BASIC_FIELD_STEP_PARAM_GROUPS.has(groupKey)) {
      return true;
    }
    if (groupKey === "fieldSettings") {
      return hasUnsupportedLeafPath(groupValue, [
        "init.dataSourceKey",
        "init.collectionName",
        "init.associationName",
        "init.associationPathName",
        "init.sourceId",
        "init.filterByTk",
        "init.fieldPath",
        "fieldType"
      ]);
    }
    if (groupKey === "tableColumnSettings") {
      return hasUnsupportedLeafPath(groupValue, EXPORTED_TABLE_COLUMN_SETTING_PATHS);
    }
    if (groupKey === "detailItemSettings") {
      return hasUnsupportedLeafPath(groupValue, EXPORTED_DETAIL_ITEM_SETTING_PATHS);
    }
    if (groupKey === "editItemSettings") {
      return hasUnsupportedLeafPath(groupValue, EXPORTED_EDIT_ITEM_SETTING_PATHS);
    }
    if (groupKey === "filterFormItemSettings") {
      return hasUnsupportedLeafPath(groupValue, EXPORTED_FILTER_FORM_ITEM_SETTING_PATHS);
    }
    if (groupKey === "jsSettings") {
      return fieldHost.use !== "JSColumnModel" && fieldHost.use !== "JSItemModel" && !isEmptyPlainContainer(groupValue) || hasUnsupportedLeafPath(groupValue, EXPORTED_JS_FIELD_SETTING_PATHS);
    }
    return true;
  });
}
function hasUnsupportedFieldPublicState(fieldHost) {
  if (hasNonEmptyPlainObject(fieldHost.flowRegistry)) {
    return true;
  }
  if (hasUnsupportedFieldHostProps(fieldHost)) {
    return true;
  }
  if (hasUnsupportedFieldDecoratorProps(fieldHost)) {
    return true;
  }
  if (hasUnsupportedFieldStepParams(fieldHost)) {
    return true;
  }
  const innerField = getSubNode(fieldHost, "field");
  if (innerField) {
    if (hasNonEmptyPlainObject(innerField.flowRegistry)) {
      return true;
    }
    if (hasUnsupportedInnerFieldProps(innerField, {
      allowDefaultClickToOpen: isDefaultRelationDisplayClickToOpenState(innerField)
    })) {
      return true;
    }
  }
  return false;
}
function readLastFieldPathSegment(fieldPath) {
  const segments = fieldPath.split(".").filter(Boolean);
  return segments[segments.length - 1];
}
function hasUnsupportedNestedFieldHostProps(props, relativeFieldPath) {
  const propKeys = Object.keys(props || {}).filter((key) => !import_lodash.default.isUndefined(props == null ? void 0 : props[key]));
  if (!propKeys.length) {
    return false;
  }
  const defaultLabel = readLastFieldPathSegment(relativeFieldPath);
  return propKeys.some((key) => {
    if (key === "label") {
      return (props == null ? void 0 : props[key]) !== defaultLabel;
    }
    return true;
  });
}
function hasUnsupportedNestedInnerFieldProps(innerField) {
  const props = innerField.props;
  const propKeys = Object.keys(props || {}).filter((key) => !import_lodash.default.isUndefined(props == null ? void 0 : props[key]));
  if (!propKeys.length) {
    return false;
  }
  return propKeys.some((key) => {
    if (key === "allowClear" && innerField.use === "SelectFieldModel") {
      return (props == null ? void 0 : props[key]) !== true;
    }
    return true;
  });
}
function isExportableNestedRelationField(candidate, relativeFieldPath) {
  if (hasNonEmptyPlainObject(candidate.flowRegistry)) {
    return false;
  }
  if (hasUnsupportedNestedFieldHostProps(candidate.props, relativeFieldPath)) {
    return false;
  }
  if (hasUnsupportedFieldStepParams(candidate)) {
    return false;
  }
  const innerField = getSubNode(candidate, "field");
  if (!innerField) {
    return true;
  }
  if (hasNonEmptyPlainObject(innerField.flowRegistry)) {
    return false;
  }
  return !hasUnsupportedNestedInnerFieldProps(innerField);
}
function inferExportFieldType(innerField) {
  const explicitFieldType = readString(getByPath(innerField, ["stepParams", "fieldSettings", "fieldType"]));
  if (explicitFieldType) {
    return explicitFieldType;
  }
  const publicFieldType = (0, import_field_type_resolver.getPublicFieldTypeForUse)(readString(getByPath(innerField, ["stepParams", "fieldBinding", "use"]))) || (0, import_field_type_resolver.getPublicFieldTypeForUse)(readString(innerField == null ? void 0 : innerField.use));
  return publicFieldType && FIELD_TYPES_WITH_NESTED_FIELDS.has(publicFieldType) ? publicFieldType : void 0;
}
function readFieldPublicSetting(fieldHost, propKey, stepParamPaths = []) {
  const propValue = getOwnValue(fieldHost.props, propKey);
  if (!import_lodash.default.isUndefined(propValue)) {
    return propValue;
  }
  for (const stepParamPath of stepParamPaths) {
    const value = getByPath(fieldHost, ["stepParams", ...stepParamPath]);
    if (!import_lodash.default.isUndefined(value)) {
      return import_lodash.default.cloneDeep(value);
    }
  }
  return void 0;
}
function readFieldDecoratorSetting(fieldHost, propKey) {
  return getOwnValue(fieldHost.decoratorProps, propKey);
}
function exportTableFieldPublicSettings(fieldHost) {
  return {
    settings: buildDefinedPayload({
      title: readFieldPublicSetting(fieldHost, "title", [["tableColumnSettings", "title", "title"]]),
      tooltip: readFieldPublicSetting(fieldHost, "tooltip", [["tableColumnSettings", "tooltip", "tooltip"]]),
      width: readFieldPublicSetting(fieldHost, "width", [["tableColumnSettings", "width", "width"]]),
      fixed: readFieldPublicSetting(fieldHost, "fixed", [["tableColumnSettings", "fixed", "fixed"]]),
      sorter: readFieldPublicSetting(fieldHost, "sorter", [["tableColumnSettings", "sorter", "sorter"]]),
      editable: readFieldPublicSetting(fieldHost, "editable", [["tableColumnSettings", "quickEdit", "editable"]]),
      dataIndex: readFieldPublicSetting(fieldHost, "dataIndex")
    })
  };
}
function exportFormFieldPublicSettings(fieldHost) {
  const settings = buildDefinedPayload({
    tooltip: readFieldPublicSetting(fieldHost, "tooltip", [["editItemSettings", "tooltip", "tooltip"]]),
    extra: readFieldPublicSetting(fieldHost, "extra", [["editItemSettings", "description", "description"]]),
    showLabel: readFieldPublicSetting(fieldHost, "showLabel", [["editItemSettings", "showLabel", "showLabel"]]),
    initialValue: readFieldPublicSetting(fieldHost, "initialValue", [
      ["editItemSettings", "initialValue", "defaultValue"]
    ]),
    required: readFieldPublicSetting(fieldHost, "required", [["editItemSettings", "required", "required"]]),
    rules: readFieldPublicSetting(fieldHost, "rules"),
    disabled: readFieldPublicSetting(fieldHost, "disabled"),
    multiple: readFieldPublicSetting(fieldHost, "multiple"),
    allowMultiple: readFieldPublicSetting(fieldHost, "allowMultiple"),
    maxCount: readFieldPublicSetting(fieldHost, "maxCount"),
    pattern: readFieldPublicSetting(fieldHost, "pattern", [["editItemSettings", "pattern", "pattern"]]),
    name: readFieldPublicSetting(fieldHost, "name"),
    labelWidth: readFieldDecoratorSetting(fieldHost, "labelWidth"),
    labelWrap: readFieldDecoratorSetting(fieldHost, "labelWrap")
  });
  return buildDefinedPayload({
    label: readString(readFieldPublicSetting(fieldHost, "label", [["editItemSettings", "label", "label"]])),
    settings: Object.keys(settings).length ? settings : void 0
  });
}
function exportDetailFieldPublicSettings(fieldHost) {
  const settings = buildDefinedPayload({
    tooltip: readFieldPublicSetting(fieldHost, "tooltip", [["detailItemSettings", "tooltip", "tooltip"]]),
    extra: readFieldPublicSetting(fieldHost, "extra", [["detailItemSettings", "description", "description"]]),
    showLabel: readFieldPublicSetting(fieldHost, "showLabel", [["detailItemSettings", "showLabel", "showLabel"]]),
    disabled: readFieldPublicSetting(fieldHost, "disabled"),
    pattern: readFieldPublicSetting(fieldHost, "pattern"),
    labelWidth: readFieldDecoratorSetting(fieldHost, "labelWidth"),
    labelWrap: readFieldDecoratorSetting(fieldHost, "labelWrap")
  });
  return buildDefinedPayload({
    label: readString(readFieldPublicSetting(fieldHost, "label", [["detailItemSettings", "label", "title"]])),
    settings: Object.keys(settings).length ? settings : void 0
  });
}
function exportFilterFieldPublicSettings(fieldHost) {
  const settings = buildDefinedPayload({
    tooltip: readFieldPublicSetting(fieldHost, "tooltip", [["filterFormItemSettings", "tooltip", "tooltip"]]),
    extra: readFieldPublicSetting(fieldHost, "extra", [["filterFormItemSettings", "description", "description"]]),
    showLabel: readFieldPublicSetting(fieldHost, "showLabel", [["filterFormItemSettings", "showLabel", "showLabel"]]),
    initialValue: readFieldPublicSetting(fieldHost, "initialValue", [
      ["filterFormItemSettings", "initialValue", "defaultValue"]
    ]),
    multiple: readFieldPublicSetting(fieldHost, "multiple"),
    allowMultiple: readFieldPublicSetting(fieldHost, "allowMultiple"),
    maxCount: readFieldPublicSetting(fieldHost, "maxCount"),
    name: readFieldPublicSetting(fieldHost, "name"),
    labelWidth: readFieldDecoratorSetting(fieldHost, "labelWidth"),
    labelWrap: readFieldDecoratorSetting(fieldHost, "labelWrap")
  });
  return buildDefinedPayload({
    label: readString(readFieldPublicSetting(fieldHost, "label", [["filterFormItemSettings", "label", "label"]])),
    settings: Object.keys(settings).length ? settings : void 0
  });
}
function exportFieldPublicSettings(fieldHost) {
  switch (fieldHost.use) {
    case "TableColumnModel":
      return exportTableFieldPublicSettings(fieldHost);
    case "FormItemModel":
    case "PatternFormItemModel":
      return exportFormFieldPublicSettings(fieldHost);
    case "DetailsItemModel":
    case "ApprovalDetailsItemModel":
    case "ApplyTaskCardDetailsItemModel":
    case "ApprovalTaskCardDetailsItemModel":
    case "FormAssociationItemModel":
      return exportDetailFieldPublicSettings(fieldHost);
    case "FilterFormItemModel":
      return exportFilterFieldPublicSettings(fieldHost);
    default:
      return {};
  }
}
function exportFieldSettings(fieldHost, nestedFields) {
  var _a, _b;
  if (hasUnsupportedFieldPublicState(fieldHost)) {
    return void 0;
  }
  if (fieldHost.use === "JSColumnModel" || fieldHost.use === "JSItemModel") {
    const runJs = clonePlainObject(getByPath(fieldHost, ["stepParams", "jsSettings", "runJs"]));
    const type = fieldHost.use === "JSColumnModel" ? "jsColumn" : "jsItem";
    return buildDefinedPayload({
      type,
      settings: runJs
    });
  }
  const init = readFieldInit(fieldHost);
  const fieldPath = readString(init == null ? void 0 : init.fieldPath);
  if (!fieldPath) {
    return void 0;
  }
  const publicSettings = exportFieldPublicSettings(fieldHost);
  const innerField = getSubNode(fieldHost, "field");
  const fieldType = inferExportFieldType(innerField);
  const titleField = readString(getByPath(fieldHost, ["stepParams", "tableColumnSettings", "fieldNames", "label"])) || readString(getByPath(fieldHost, ["stepParams", "detailItemSettings", "fieldNames", "label"])) || readString(getByPath(fieldHost, ["stepParams", "editItemSettings", "titleField", "label"])) || readString((_a = fieldHost.props) == null ? void 0 : _a.titleField) || readString((_b = innerField == null ? void 0 : innerField.props) == null ? void 0 : _b.titleField);
  const popup = exportPopupSummary(fieldHost.popup);
  return buildDefinedPayload({
    field: fieldPath,
    associationPathName: readString(init == null ? void 0 : init.associationPathName),
    fieldType,
    fields: fieldType && FIELD_TYPES_WITH_NESTED_FIELDS.has(fieldType) && (nestedFields == null ? void 0 : nestedFields.length) ? nestedFields : void 0,
    label: publicSettings.label,
    titleField,
    settings: publicSettings.settings,
    popup
  });
}
function exportFields(ctx, fieldHosts, scope, path) {
  return fieldHosts.flatMap((fieldHost, index) => {
    const fieldPath = `${path}[${index}]`;
    if (hasUnsupportedTemplateSummary(fieldHost)) {
      recordUnsupported(ctx, {
        kind: "field",
        use: readString(fieldHost.use),
        path: fieldPath,
        reasonCode: TEMPLATE_SUMMARY_UNSUPPORTED_REASON,
        manualAction: templateSummaryManualAction("field")
      });
      return [];
    }
    const rootFieldPath = readFieldPath(fieldHost);
    const nested = rootFieldPath ? collectExportableNestedRelationFields(ctx, fieldHost, rootFieldPath, `${fieldPath}.fields`) : { fields: [], fieldPaths: [] };
    const settings = exportFieldSettings(fieldHost, nested.fields);
    if (!settings) {
      recordUnsupported(ctx, {
        kind: "field",
        use: readString(fieldHost.use),
        path: fieldPath,
        reasonCode: "unsupported-node",
        manualAction: UNSUPPORTED_MANUAL_ACTION
      });
      return [];
    }
    const fallback = readString(settings.field) || `field_${index + 1}`;
    const key = dedupeKey(ctx, scope, getDeclaredKey(fieldHost, scope.prefix), fallback, `${fieldPath}.key`);
    const spec = buildDefinedPayload({
      key,
      ...settings
    });
    return [
      {
        spec,
        uid: fieldHost.uid,
        bindingUids: collectFieldBindingUids(fieldHost),
        key,
        fieldPaths: import_lodash.default.uniq(
          compactStringValues([settings.field, ...nested.fieldPaths])
        )
      }
    ];
  });
}
function getFieldHosts(block, type) {
  if (type === "table") {
    return getSubNodeArray(block, "columns").filter((item) => item.use !== TABLE_ACTIONS_COLUMN_USE);
  }
  if (FIELD_GRID_BLOCK_TYPES.has(type)) {
    return getSubNodeArray(getSubNode(block, "grid"), "items");
  }
  if (CARD_FIELD_BLOCK_TYPES.has(type)) {
    return getSubNodeArray(getSubNode(getSubNode(block, "item"), "grid"), "items");
  }
  return [];
}
function isDefaultPopupRuntimeOpenViewValue(key, value, resourceContext) {
  if (key === "size") {
    return value === "medium";
  }
  if (key === "pageModelClass") {
    return value === "ChildPageModel";
  }
  if (key === "collectionName") {
    return !!(resourceContext == null ? void 0 : resourceContext.collectionName) && readString(value) === resourceContext.collectionName;
  }
  if (key === "associationName") {
    return !!(resourceContext == null ? void 0 : resourceContext.associationName) && readString(value) === resourceContext.associationName;
  }
  if (key === "sourceId") {
    return value === DEFAULT_RELATION_OPEN_VIEW_SOURCE_ID;
  }
  if (key === "filterByTk") {
    return value === DEFAULT_RELATION_OPEN_VIEW_FILTER_BY_TK;
  }
  if (key === "dataSourceKey") {
    const expectedDataSourceKey = (resourceContext == null ? void 0 : resourceContext.dataSourceKey) || ((resourceContext == null ? void 0 : resourceContext.collectionName) ? "main" : "");
    return !!expectedDataSourceKey && readString(value) === expectedDataSourceKey;
  }
  return false;
}
function hasUnsupportedPopupSettings(popupSettings, type, resourceContext) {
  if (!popupSettings) {
    return false;
  }
  if (!PUBLIC_POPUP_ACTION_TYPES.has(type)) {
    return true;
  }
  return Object.entries(popupSettings).some(([key, value]) => {
    if (BASIC_INLINE_POPUP_OPEN_VIEW_KEYS.has(key)) {
      return false;
    }
    if (BASIC_INLINE_POPUP_DEFAULT_RUNTIME_KEYS.has(key)) {
      return !isDefaultPopupRuntimeOpenViewValue(key, value, resourceContext);
    }
    return true;
  });
}
function exportActionButtonSettings(action) {
  const general = getByPath(action, ["stepParams", "buttonSettings", "general"]) || {};
  const readValue = (key) => getOwnValue(action.props, key) ?? getOwnValue(general, key);
  return buildDefinedPayload({
    title: readValue("title"),
    tooltip: readValue("tooltip"),
    icon: readValue("icon"),
    iconOnly: readValue("iconOnly"),
    type: readValue("type"),
    danger: readValue("danger"),
    color: readValue("color")
  });
}
function exportFilterActionSettings(action) {
  const filterSettings = getByPath(action, ["stepParams", "filterSettings"]);
  if (!filterSettings) {
    return void 0;
  }
  const defaultFilter = import_lodash.default.cloneDeep(import_lodash.default.get(filterSettings, ["defaultFilter", "defaultFilter"]));
  const filterableFieldNames = import_lodash.default.cloneDeep(import_lodash.default.get(filterSettings, ["filterableFieldNames", "filterableFieldNames"]));
  return buildDefinedPayload({
    defaultFilter: import_lodash.default.isUndefined(defaultFilter) ? void 0 : defaultFilter,
    filterableFieldNames: import_lodash.default.isUndefined(filterableFieldNames) ? void 0 : filterableFieldNames
  });
}
function exportDeleteActionSettings(action, type) {
  if (!BASIC_DELETE_ACTION_TYPES.has(type)) {
    return void 0;
  }
  const confirm = clonePlainObject(getByPath(action, ["stepParams", "deleteSettings", "confirm"]));
  return confirm ? { confirm } : void 0;
}
function readActionRunJsSettings(action) {
  return clonePlainObject(getByPath(action, ["stepParams", "clickSettings", "runJs"])) || clonePlainObject(getByPath(action, ["stepParams", "jsSettings", "runJs"]));
}
function hasUnsupportedActionButtonSettings(action) {
  const buttonSettings = getByPath(action, ["stepParams", "buttonSettings"]);
  if (!buttonSettings) {
    return false;
  }
  const unsupportedGroups = Object.keys(buttonSettings).filter((key) => key !== "general" && key !== "linkageRules");
  if (unsupportedGroups.length) {
    return true;
  }
  const general = getByPath(action, ["stepParams", "buttonSettings", "general"]);
  if (!general) {
    return false;
  }
  return Object.keys(general).some((key) => !BASIC_ACTION_BUTTON_GENERAL_KEYS.has(key));
}
function hasUnsupportedActionFilterSettings(action, type) {
  const filterSettings = getByPath(action, ["stepParams", "filterSettings"]);
  if (!filterSettings) {
    return false;
  }
  if (type !== "filter") {
    return true;
  }
  const unsupportedGroups = Object.keys(filterSettings).filter(
    (key) => key !== "defaultFilter" && key !== "filterableFieldNames"
  );
  if (unsupportedGroups.length) {
    return true;
  }
  const defaultFilter = getByPath(action, ["stepParams", "filterSettings", "defaultFilter"]);
  const filterableFieldNames = getByPath(action, [
    "stepParams",
    "filterSettings",
    "filterableFieldNames"
  ]);
  return defaultFilter && Object.keys(defaultFilter).some((key) => key !== "defaultFilter") || filterableFieldNames && Object.keys(filterableFieldNames).some((key) => key !== "filterableFieldNames");
}
function hasUnsupportedActionDeleteSettings(action, type) {
  const deleteSettings = getByPath(action, ["stepParams", "deleteSettings"]);
  if (!deleteSettings) {
    return false;
  }
  if (!BASIC_DELETE_ACTION_TYPES.has(type)) {
    return true;
  }
  const unsupportedGroups = Object.keys(deleteSettings).filter((key) => key !== "confirm");
  if (unsupportedGroups.length) {
    return true;
  }
  const confirm = getByPath(action, ["stepParams", "deleteSettings", "confirm"]);
  return !!confirm && Object.keys(confirm).some((key) => !BASIC_DELETE_CONFIRM_KEYS.has(key));
}
function hasUnsupportedActionRunJsSettings(action, type) {
  const clickSettings = getByPath(action, ["stepParams", "clickSettings"]);
  const jsSettings = getByPath(action, ["stepParams", "jsSettings"]);
  if (!clickSettings && !jsSettings) {
    return false;
  }
  if (type !== "js" && type !== "jsItem") {
    return true;
  }
  const unsupportedClickSettings = clickSettings && Object.keys(clickSettings).some((key) => key !== "runJs");
  const unsupportedJsSettings = jsSettings && Object.keys(jsSettings).some((key) => key !== "runJs");
  if (unsupportedClickSettings || unsupportedJsSettings) {
    return true;
  }
  if (clickSettings && !JS_ACTION_USES.has(String(action.use || ""))) {
    return true;
  }
  if (jsSettings && !JS_ITEM_ACTION_USES.has(String(action.use || ""))) {
    return true;
  }
  const runJs = readActionRunJsSettings(action);
  return !!runJs && Object.keys(runJs).some((key) => key !== "code" && key !== "version");
}
function isActionPropExportable(action, type, key) {
  var _a, _b, _c;
  if (!BASIC_ACTION_PROP_KEYS.has(key)) {
    return false;
  }
  if (key === "position") {
    return type === "bulkDelete" && ((_a = action.props) == null ? void 0 : _a.position) === "right";
  }
  if (key === "filterableFieldNames") {
    const exportedFilter = exportFilterActionSettings(action);
    return type === "filter" && import_lodash.default.isEqual((_b = action.props) == null ? void 0 : _b.filterableFieldNames, exportedFilter == null ? void 0 : exportedFilter.filterableFieldNames);
  }
  if (key === "defaultFilterValue" || key === "filterValue") {
    const exportedFilter = exportFilterActionSettings(action);
    return type === "filter" && import_lodash.default.isEqual((_c = action.props) == null ? void 0 : _c[key], exportedFilter == null ? void 0 : exportedFilter.defaultFilter);
  }
  return true;
}
function hasUnsupportedActionPublicState(action, type, resourceContext) {
  if (type === "aiEmployee") {
    return true;
  }
  const props = action.props || {};
  if (Object.keys(props).some((key) => !isActionPropExportable(action, type, key))) {
    return true;
  }
  const stepParams = action.stepParams || {};
  if (getPublicStepParamKeys(stepParams).some((key) => !BASIC_ACTION_STEP_PARAM_GROUPS.has(key))) {
    return true;
  }
  if (hasUnsupportedActionButtonSettings(action) || hasUnsupportedActionFilterSettings(action, type) || hasUnsupportedActionDeleteSettings(action, type) || hasUnsupportedActionRunJsSettings(action, type)) {
    return true;
  }
  const popupSettings = getByPath(action, ["stepParams", "popupSettings"]);
  if (popupSettings && Object.keys(popupSettings).some((key) => key !== "openView")) {
    return true;
  }
  if (getSubNode(action, "page")) {
    return true;
  }
  const openView = getByPath(action, ["stepParams", "popupSettings", "openView"]);
  if (hasUnsupportedPopupSettings(openView, type, resourceContext)) {
    return true;
  }
  return hasNonEmptyPlainObject(action.flowRegistry);
}
function exportActionSettings(action, resourceContext) {
  const type = import_catalog.ACTION_KEY_BY_USE.get(String(action.use || ""));
  if (!type) {
    return void 0;
  }
  if (hasUnsupportedActionPublicState(action, type, resourceContext)) {
    return void 0;
  }
  const popupSettings = getByPath(action, ["stepParams", "popupSettings", "openView"]);
  const popupTemplate = exportPopupSummary(action.popup);
  const settings = buildDefinedPayload({
    ...exportActionButtonSettings(action),
    ...type === "filter" ? exportFilterActionSettings(action) : {},
    ...exportDeleteActionSettings(action, type),
    ...type === "js" || type === "jsItem" ? readActionRunJsSettings(action) : {}
  });
  const popup = import_lodash.default.isPlainObject(popupSettings) && PUBLIC_POPUP_ACTION_TYPES.has(type) ? buildDefinedPayload({
    title: readString(popupSettings.title),
    mode: readString(popupSettings.mode),
    tryTemplate: typeof popupSettings.tryTemplate === "boolean" ? popupSettings.tryTemplate : void 0,
    defaultType: type === "view" ? "view" : type === "edit" ? "edit" : readString(popupSettings.defaultType),
    ...popupTemplate
  }) : popupTemplate;
  return buildDefinedPayload({
    type,
    settings: settings && Object.keys(settings).length ? settings : void 0,
    popup: popup && Object.keys(popup).length ? popup : void 0
  });
}
function exportActions(ctx, actions, scope, kind, path, resourceContext) {
  return actions.flatMap((action, index) => {
    const actionPath = `${path}[${index}]`;
    if (hasUnsupportedTemplateSummary(action)) {
      recordUnsupported(ctx, {
        kind,
        use: readString(action.use),
        path: actionPath,
        reasonCode: TEMPLATE_SUMMARY_UNSUPPORTED_REASON,
        manualAction: templateSummaryManualAction(kind)
      });
      return [];
    }
    const settings = exportActionSettings(action, resourceContext);
    if (!(settings == null ? void 0 : settings.type)) {
      recordUnsupported(ctx, {
        kind,
        use: readString(action.use),
        path: actionPath,
        reasonCode: "unsupported-node",
        manualAction: UNSUPPORTED_MANUAL_ACTION
      });
      return [];
    }
    const key = dedupeKey(ctx, scope, getDeclaredKey(action, scope.prefix), settings.type, `${actionPath}.key`);
    const spec = buildDefinedPayload({
      key,
      ...settings
    });
    return [
      {
        spec,
        uid: action.uid,
        key
      }
    ];
  });
}
function getRecordActionHosts(block, type) {
  if (type === "table") {
    const actionsColumn = getSubNodeArray(block, "columns").find((item) => item.use === TABLE_ACTIONS_COLUMN_USE);
    return getSubNodeArray(actionsColumn, "actions");
  }
  if (type === "list" || type === "gridCard" || type === "comments") {
    return getSubNodeArray(getSubNode(block, "item"), "actions");
  }
  return [];
}
function getBlockActionHosts(block, type) {
  const actions = getSubNodeArray(block, "actions");
  if (type !== "recordHistory") {
    return actions;
  }
  return actions.filter((action) => !RECORD_HISTORY_GENERATED_ACTION_USES.has(String(action.use || "")));
}
function buildLayoutFromGrid(ctx, grid, uidToLocalKey, path) {
  var _a, _b, _c, _d, _e, _f;
  const rows = import_lodash.default.isPlainObject((_a = grid == null ? void 0 : grid.props) == null ? void 0 : _a.rows) ? (_b = grid == null ? void 0 : grid.props) == null ? void 0 : _b.rows : {};
  const rowOrder = Array.isArray((_c = grid == null ? void 0 : grid.props) == null ? void 0 : _c.rowOrder) ? ((_d = grid == null ? void 0 : grid.props) == null ? void 0 : _d.rowOrder).map((item) => String(item)).filter(Boolean) : Object.keys(rows);
  const sizes = import_lodash.default.isPlainObject((_e = grid == null ? void 0 : grid.props) == null ? void 0 : _e.sizes) ? (_f = grid == null ? void 0 : grid.props) == null ? void 0 : _f.sizes : {};
  if (!rowOrder.length) {
    return void 0;
  }
  const layoutRows = [];
  for (const rowKey of rowOrder) {
    const row = Array.isArray(rows[rowKey]) ? rows[rowKey] : [];
    const rowSizes = Array.isArray(sizes[rowKey]) ? sizes[rowKey] : [];
    const cells = row.flatMap((cell, cellIndex) => {
      const uid = Array.isArray(cell) ? readString(cell[0]) : readString(cell);
      const key = uid ? uidToLocalKey.get(uid) : void 0;
      if (!key) {
        recordUnsupported(ctx, {
          kind: "layout",
          path: `${path}.${rowKey}[${cellIndex}]`,
          reasonCode: "unsupported-layout-cell",
          manualAction: "Recreate this layout manually or add mapper support."
        });
        return [];
      }
      const span = typeof rowSizes[cellIndex] === "number" ? rowSizes[cellIndex] : void 0;
      return [span && span !== 24 ? { key, span } : key];
    });
    if (cells.length) {
      layoutRows.push(cells);
    }
  }
  return layoutRows.length ? {
    rows: layoutRows
  } : void 0;
}
function buildAutoLayoutFromKeys(keys) {
  return {
    rows: keys.map((key) => [key])
  };
}
function exportFieldsLayout(ctx, block, type, fields) {
  if (!FIELD_GRID_BLOCK_TYPES.has(type)) {
    return void 0;
  }
  const grid = getSubNode(block, "grid");
  const uidToLocalKey = /* @__PURE__ */ new Map();
  fields.forEach((field) => {
    if (field.uid && field.key) {
      uidToLocalKey.set(field.uid, field.key);
    }
  });
  return buildLayoutFromGrid(ctx, grid, uidToLocalKey, "$.fieldsLayout");
}
function prefixExportedKey(prefix, key) {
  return prefix ? `${prefix}.${key}` : key;
}
function exportBlock(ctx, block, scope, index, path) {
  const type = import_catalog.BLOCK_KEY_BY_USE.get(String(block.use || ""));
  if (!type || APPLY_BLUEPRINT_UNSUPPORTED_BLOCK_TYPES.has(type)) {
    recordUnsupported(ctx, {
      kind: "block",
      use: readString(block.use),
      type,
      path,
      reasonCode: "unsupported-node",
      manualAction: UNSUPPORTED_BLOCK_MANUAL_ACTION
    });
    return {};
  }
  if (hasUnsupportedTemplateSummary(block)) {
    recordUnsupported(ctx, {
      kind: "block",
      use: readString(block.use),
      type,
      path,
      reasonCode: TEMPLATE_SUMMARY_UNSUPPORTED_REASON,
      manualAction: templateSummaryManualAction("block")
    });
    return {};
  }
  if (hasUnsupportedBlockPublicState(block, type)) {
    recordUnsupported(ctx, {
      kind: "block",
      use: readString(block.use),
      type,
      path,
      reasonCode: "unsupported-public-state",
      manualAction: UNSUPPORTED_BLOCK_MANUAL_ACTION
    });
    return {};
  }
  const key = dedupeKey(ctx, scope, getDeclaredKey(block, scope.prefix), `${type}_${index + 1}`, `${path}.key`);
  const childScope = {
    prefix: scope.prefix ? `${scope.prefix}.${key}` : key,
    used: /* @__PURE__ */ new Set()
  };
  const resourceContext = readBlockResourceContext(block);
  const fieldHosts = getFieldHosts(block, type);
  const fieldResults = exportFields(ctx, fieldHosts, childScope, `${path}.fields`);
  const actionResults = exportActions(
    ctx,
    getBlockActionHosts(block, type),
    childScope,
    "action",
    `${path}.actions`,
    resourceContext
  );
  const recordActionResults = exportActions(
    ctx,
    getRecordActionHosts(block, type),
    childScope,
    "recordAction",
    `${path}.recordActions`,
    resourceContext
  );
  const fieldsLayout = exportFieldsLayout(ctx, block, type, fieldResults);
  const fields = fieldResults.map((item) => item.spec);
  const fieldPaths = import_lodash.default.uniq(fieldResults.flatMap((field) => field.fieldPaths || []));
  const actions = actionResults.map((item) => item.spec);
  const recordActions = recordActionResults.map((item) => item.spec);
  const blockPublicKey = prefixExportedKey(scope.prefix, key);
  const chartSettings = exportChartBlockSettings(ctx, block, blockPublicKey, path);
  if (chartSettings === null) {
    return {};
  }
  const descendantKeys = [
    ...fieldResults.flatMap(
      (item) => item.key ? (item.bindingUids || compactStringValues([item.uid])).map((bindingUid) => ({
        uid: bindingUid,
        key: prefixExportedKey(blockPublicKey, item.key),
        fieldPaths: item.fieldPaths
      })) : []
    ),
    ...[...actionResults, ...recordActionResults].flatMap(
      (item) => item.uid && item.key ? [
        {
          uid: item.uid,
          key: prefixExportedKey(blockPublicKey, item.key),
          fieldPaths
        }
      ] : []
    )
  ];
  const spec = buildDefinedPayload({
    key,
    type,
    ...exportBlockResource(block),
    ...exportCardSettings(block),
    ...exportDataBlockSettings(block, type),
    ...exportListBlockSettings(block),
    ...exportGridCardBlockSettings(block),
    ...exportKanbanBlockSettings(block),
    ...exportTreeBlockSettings(block),
    ...exportCalendarBlockSettings(block),
    ...exportActionPanelBlockSettings(block),
    ...exportRecordHistoryBlockSettings(block),
    ...chartSettings,
    ...exportSimpleBlockSettings(block, type),
    template: exportTemplateSummary(block.template),
    fields: fields.length ? fields : void 0,
    fieldsLayout,
    actions: actions.length ? actions : void 0,
    recordActions: recordActions.length ? recordActions : void 0
  });
  return {
    spec,
    uid: block.uid,
    key,
    descendantKeys,
    fieldPaths
  };
}
function extractReactionCanonicalRules(node, slot) {
  const stepRoot = import_lodash.default.get(node, ["stepParams", slot.flowKey, slot.stepKey]);
  const rawValue = slot.valuePath == null ? stepRoot : import_lodash.default.get(stepRoot, slot.valuePath);
  return Array.isArray(rawValue) ? import_lodash.default.cloneDeep(rawValue) : [];
}
function buildReactionFieldPathMaps(node, scene) {
  const uidToPath = /* @__PURE__ */ new Map();
  const visit = (current, depth) => {
    if (!current) {
      return;
    }
    const isSubFormHostRoot = scene === "subForm" && depth === 0 && (current.use === "SubFormFieldModel" || current.use === "SubFormListFieldModel");
    if (!isSubFormHostRoot) {
      const init = readFieldInit(current);
      const fieldPath = readString(init == null ? void 0 : init.fieldPath);
      if (current.uid && fieldPath && !uidToPath.has(current.uid)) {
        uidToPath.set(current.uid, fieldPath);
      }
    }
    Object.values(current.subModels || {}).forEach((value) => {
      castNodeArray(value).forEach((child) => visit(child, depth + 1));
    });
  };
  visit(node, 0);
  return uidToPath;
}
function normalizeReactionRules(kind, canonicalRules, node, scene) {
  if (kind === "fieldValue") {
    return normalizeFieldValueExportRules(canonicalRules);
  }
  if (kind === "blockLinkage") {
    return (0, import_linkage.normalizeBlockLinkageRules)(canonicalRules);
  }
  if (kind === "actionLinkage") {
    return (0, import_linkage.normalizeActionLinkageRules)(canonicalRules);
  }
  const uidToPath = buildReactionFieldPathMaps(node, scene);
  return (0, import_linkage.normalizeFieldLinkageRules)(canonicalRules, {
    scene,
    resolveFieldPath: (fieldUid) => uidToPath.get(String(fieldUid || "").trim())
  });
}
function normalizeFieldValueExportRules(canonicalRules) {
  return (0, import_field_value.normalizeFieldValueRules)(
    canonicalRules.map((rule) => {
      if (!import_lodash.default.isPlainObject(rule)) {
        return rule;
      }
      const current = rule;
      return {
        ...current,
        enabled: import_lodash.default.isUndefined(current.enabled) ? current.enable : current.enabled,
        when: import_lodash.default.isUndefined(current.when) ? current.condition : current.when
      };
    })
  );
}
function compactStringValues(values) {
  return values.filter((value) => !!value);
}
function collectSourcePathReferences(value) {
  if (Array.isArray(value)) {
    return value.flatMap((item) => collectSourcePathReferences(item));
  }
  if (!import_lodash.default.isPlainObject(value)) {
    return [];
  }
  const source = readString(value.source);
  if (source) {
    return source === "path" ? compactStringValues([readString(value.path)]) : [];
  }
  return Object.values(value).flatMap((item) => collectSourcePathReferences(item));
}
function collectReactionFilterFieldPaths(filter) {
  const visit = (node) => {
    if (Array.isArray(node)) {
      return node.flatMap((item) => visit(item));
    }
    if (!import_lodash.default.isPlainObject(node)) {
      return [];
    }
    const current = node;
    const source = readString(current.source);
    if (source) {
      return source === "path" ? compactStringValues([readString(current.path)]) : [];
    }
    const currentPath = readString(current.path);
    return import_lodash.default.uniq([
      ...currentPath ? [currentPath] : [],
      ...Object.entries(current).flatMap(([key, value]) => key === "path" ? [] : visit(value))
    ]);
  };
  return import_lodash.default.uniq(visit(filter));
}
function collectFieldLinkageReferencedPaths(rule) {
  return compactStringValues(
    import_lodash.default.uniq([
      ...collectReactionFilterFieldPaths(rule.when),
      ...(rule.then || []).flatMap((action) => {
        if (action.type === "setFieldState") {
          return action.fieldPaths || [];
        }
        if (action.type === "assignField" || action.type === "setFieldDefaultValue") {
          return (action.items || []).flatMap((item) => [
            item.targetPath,
            ...collectReactionFilterFieldPaths(item.when),
            ...collectSourcePathReferences(item.value)
          ]);
        }
        return [];
      })
    ])
  );
}
function collectFieldValueReferencedPaths(rule) {
  return compactStringValues(
    import_lodash.default.uniq([
      rule.targetPath,
      ...collectReactionFilterFieldPaths(rule.when),
      ...collectSourcePathReferences(rule.value)
    ])
  );
}
function collectBlockLinkageReferencedPaths(rule) {
  return collectReactionFilterFieldPaths(rule.when);
}
function collectActionLinkageReferencedPaths(rule) {
  return collectReactionFilterFieldPaths(rule.when);
}
function shouldCheckExportedFieldPath(path) {
  const [root] = String(path || "").trim().split(".").filter(Boolean);
  if (!root) {
    return false;
  }
  return !REACTION_CONTEXT_SCALAR_PATHS.has(root) && !REACTION_CONTEXT_ROOT_PATHS.has(root);
}
function filterUnavailableReactionFieldReferenceRules(ctx, rules, targetKey, exportedFieldPaths, collectReferencedPaths) {
  if (!exportedFieldPaths) {
    return rules;
  }
  const filtered = rules.filter(
    (rule) => collectReferencedPaths(rule).filter(shouldCheckExportedFieldPath).every((fieldPath) => exportedFieldPaths.has(fieldPath))
  );
  if (filtered.length !== rules.length) {
    recordUnsupported(ctx, {
      kind: "reaction",
      path: `$.reaction.${targetKey}`,
      reasonCode: "unsupported-reaction-target-field",
      manualAction: "Recreate reaction rules that reference skipped fields manually or add mapper support."
    });
  }
  return filtered;
}
function filterUnavailableFieldLinkageRules(ctx, rules, targetKey, exportedFieldPaths) {
  return filterUnavailableReactionFieldReferenceRules(
    ctx,
    rules,
    targetKey,
    exportedFieldPaths,
    collectFieldLinkageReferencedPaths
  );
}
function filterUnavailableFieldValueRules(ctx, rules, targetKey, exportedFieldPaths) {
  return filterUnavailableReactionFieldReferenceRules(
    ctx,
    rules,
    targetKey,
    exportedFieldPaths,
    collectFieldValueReferencedPaths
  );
}
function filterUnavailableReactionRules(ctx, kind, rules, targetKey, exportedFieldPaths) {
  if (kind === "fieldValue") {
    return filterUnavailableFieldValueRules(ctx, rules, targetKey, exportedFieldPaths);
  }
  if (kind === "fieldLinkage") {
    return filterUnavailableFieldLinkageRules(
      ctx,
      rules,
      targetKey,
      exportedFieldPaths
    );
  }
  if (kind === "blockLinkage") {
    return filterUnavailableReactionFieldReferenceRules(
      ctx,
      rules,
      targetKey,
      exportedFieldPaths,
      collectBlockLinkageReferencedPaths
    );
  }
  if (kind === "actionLinkage") {
    return filterUnavailableReactionFieldReferenceRules(
      ctx,
      rules,
      targetKey,
      exportedFieldPaths,
      collectActionLinkageReferencedPaths
    );
  }
  return rules;
}
function exportReactionItems(ctx, root, keyByUid, fieldPathsByTargetKey) {
  const items = [];
  const visit = (node) => {
    if (!(node == null ? void 0 : node.uid)) {
      return;
    }
    const targetKey = keyByUid.get(node.uid);
    if (targetKey && (0, import_registry.getReactionKindsForUse)(node.use).length) {
      try {
        const resolvedTarget = (0, import_resolver.resolveReactionTarget)({
          target: {
            uid: node.uid
          },
          node,
          use: node.use
        });
        for (const capability of resolvedTarget.capabilities) {
          const resolvedCapability = (0, import_resolver.resolveReactionCapability)(resolvedTarget, capability.kind);
          const storageNode = (0, import_resolver.resolveReactionStorageNode)(resolvedTarget, resolvedCapability);
          const canonicalRules = extractReactionCanonicalRules(storageNode, resolvedCapability.resolvedSlot);
          if (!canonicalRules.length) {
            continue;
          }
          const normalizedRules = normalizeReactionRules(
            capability.kind,
            canonicalRules,
            node,
            resolvedCapability.resolvedScene
          );
          const rules = filterUnavailableReactionRules(
            ctx,
            capability.kind,
            normalizedRules,
            targetKey,
            fieldPathsByTargetKey.get(targetKey)
          );
          if (!rules.length) {
            continue;
          }
          items.push({
            type: REACTION_KIND_TO_BLUEPRINT_TYPE[capability.kind],
            target: targetKey,
            rules
          });
        }
      } catch (error) {
        recordUnsupported(ctx, {
          kind: "reaction",
          use: readString(node.use),
          path: `$.reaction.${targetKey}`,
          reasonCode: "unsupported-reaction",
          manualAction: "Recreate these reaction rules manually or add mapper support."
        });
      }
    }
    Object.values(node.subModels || {}).forEach((value) => {
      castNodeArray(value).forEach((child) => visit(child));
    });
  };
  visit(root);
  return items.length ? { items } : void 0;
}
function exportTab(ctx, tab, index, keyByUid, fieldPathsByTargetKey) {
  if (hasNonEmptyPlainObject(tab.flowRegistry)) {
    recordUnsupported(ctx, {
      kind: "tab",
      use: readString(tab.use),
      path: `$.tabs[${index}].flowRegistry`,
      reasonCode: FLOW_REGISTRY_UNSUPPORTED_REASON,
      manualAction: "Recreate these event flows manually or add mapper support."
    });
    return void 0;
  }
  const tabScope = {
    prefix: "",
    used: /* @__PURE__ */ new Set()
  };
  const tabKey = dedupeKey(
    ctx,
    tabScope,
    getDeclaredKey(tab, "") || inferTabDeclaredKeyFromChildren(tab),
    `tab_${index + 1}`,
    `$.tabs[${index}].key`
  );
  const blockScope = {
    prefix: tabKey,
    used: /* @__PURE__ */ new Set()
  };
  const grid = getSubNode(tab, "grid");
  if (hasNonEmptyPlainObject(grid == null ? void 0 : grid.flowRegistry)) {
    recordUnsupported(ctx, {
      kind: "layout",
      use: readString(grid == null ? void 0 : grid.use),
      path: `$.tabs[${index}].grid.flowRegistry`,
      reasonCode: FLOW_REGISTRY_UNSUPPORTED_REASON,
      manualAction: "Recreate these event flows manually or add mapper support."
    });
    return void 0;
  }
  const blockResults = getSubNodeArray(grid, "items").map(
    (block, blockIndex) => exportBlock(ctx, block, blockScope, blockIndex, `$.tabs[${index}].blocks[${blockIndex}]`)
  );
  const blocks = blockResults.flatMap((item) => item.spec ? [item.spec] : []);
  blockResults.forEach((item) => {
    var _a;
    if (item.uid && item.key) {
      keyByUid.set(item.uid, `${tabKey}.${item.key}`);
      fieldPathsByTargetKey.set(`${tabKey}.${item.key}`, new Set(item.fieldPaths || []));
    }
    (_a = item.descendantKeys) == null ? void 0 : _a.forEach((binding) => {
      var _a2;
      keyByUid.set(binding.uid, binding.key);
      if ((_a2 = binding.fieldPaths) == null ? void 0 : _a2.length) {
        fieldPathsByTargetKey.set(binding.key, new Set(binding.fieldPaths));
      }
    });
  });
  const uidToLocalKey = /* @__PURE__ */ new Map();
  blockResults.forEach((item) => {
    if (item.uid && item.key) {
      uidToLocalKey.set(item.uid, item.key);
    }
  });
  const layout = buildLayoutFromGrid(ctx, grid, uidToLocalKey, `$.tabs[${index}].layout`);
  if (!blocks.length) {
    recordUnsupported(ctx, {
      kind: "tab",
      use: readString(tab.use),
      path: `$.tabs[${index}]`,
      reasonCode: "empty-tab",
      manualAction: "Add at least one supported block before exporting this tab."
    });
    return void 0;
  }
  return buildDefinedPayload({
    key: tabKey,
    ...exportTabChrome(tab),
    blocks,
    layout: layout || buildAutoLayoutFromKeys(blocks.map((block) => block.key).filter(Boolean))
  });
}
function exportFlowSurfaceBlueprintDocument(input) {
  const ctx = {
    unsupportedPolicy: input.unsupportedPolicy || "error",
    warnings: [],
    unsupported: [],
    chartAssets: {}
  };
  const keyByUid = /* @__PURE__ */ new Map();
  const fieldPathsByTargetKey = /* @__PURE__ */ new Map();
  const tabs = getSubNodeArray(input.page, "tabs").flatMap((tab, index) => {
    const exportedTab = exportTab(ctx, tab, index, keyByUid, fieldPathsByTargetKey);
    return exportedTab ? [exportedTab] : [];
  });
  if (!tabs.length) {
    recordUnsupported(ctx, {
      kind: "page",
      use: readString(input.page.use),
      path: "$.tabs",
      reasonCode: "empty-page",
      manualAction: "Add at least one supported tab before exporting this page."
    });
  }
  const page = exportPage(ctx, input.page, input.pageRoute);
  if (tabs.length === 1 && (page == null ? void 0 : page.enableTabs) === true) {
    recordUnsupported(ctx, {
      kind: "page",
      use: readString(input.page.use),
      path: "$.page.enableTabs",
      reasonCode: "unsupported-single-tab-enable-tabs",
      manualAction: "Disable page tabs for single-tab pages or add replace schema support for single-tab tab chrome."
    });
  }
  const reaction = exportReactionItems(ctx, input.page, keyByUid, fieldPathsByTargetKey);
  assertNoUnsupported(ctx);
  if (!tabs.length) {
    (0, import_errors.throwBadRequest)(`flowSurfaces exportBlueprint cannot export a page without at least one supported tab`);
  }
  const document = {
    version: "1",
    mode: "replace",
    target: {
      pageSchemaUid: input.target.pageSchemaUid
    },
    ...Object.keys(page || {}).length ? { page } : {},
    tabs,
    assets: {
      scripts: {},
      charts: ctx.chartAssets
    },
    ...reaction ? { reaction } : {}
  };
  return {
    document,
    source: {
      target: {
        pageSchemaUid: input.target.pageSchemaUid
      },
      pageTitle: readPageTitle(input.page)
    },
    warnings: ctx.warnings,
    unsupported: ctx.unsupported
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  exportFlowSurfaceBlueprintDocument
});
