'use strict';

var zod = require('zod');

// src/shared/identifiers.zod.ts
var SystemIdentifierSchema = zod.z.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, {
  message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")'
}).describe("System identifier (lowercase with underscores or dots)");
var SnakeCaseIdentifierSchema = zod.z.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, {
  message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")'
}).describe("Snake case identifier (lowercase with underscores only)");
var EventNameSchema = zod.z.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, {
  message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")'
}).describe("Event name (lowercase with dot notation for namespacing)");
var TransformTypeSchema = zod.z.discriminatedUnion("type", [
  zod.z.object({
    type: zod.z.literal("constant"),
    value: zod.z.unknown().describe("Constant value to use")
  }).describe("Set a constant value"),
  zod.z.object({
    type: zod.z.literal("cast"),
    targetType: zod.z.enum(["string", "number", "boolean", "date"]).describe("Target data type")
  }).describe("Cast to a specific data type"),
  zod.z.object({
    type: zod.z.literal("lookup"),
    table: zod.z.string().describe("Lookup table name"),
    keyField: zod.z.string().describe("Field to match on"),
    valueField: zod.z.string().describe("Field to retrieve")
  }).describe("Lookup value from another table"),
  zod.z.object({
    type: zod.z.literal("javascript"),
    expression: zod.z.string().describe('JavaScript expression (e.g., "value.toUpperCase()")')
  }).describe("Custom JavaScript transformation"),
  zod.z.object({
    type: zod.z.literal("map"),
    mappings: zod.z.record(zod.z.string(), zod.z.unknown()).describe('Value mappings (e.g., {"Active": "active"})')
  }).describe("Map values using a dictionary")
]);
var FieldMappingSchema = zod.z.object({
  /**
   * Source field name
   */
  source: zod.z.string().describe("Source field name"),
  /**
   * Target field name (should be snake_case for ObjectStack)
   */
  target: zod.z.string().describe("Target field name"),
  /**
   * Transformation to apply
   */
  transform: TransformTypeSchema.optional().describe("Transformation to apply"),
  /**
   * Default value if source is null/undefined
   */
  defaultValue: zod.z.unknown().optional().describe("Default if source is null/undefined")
});
var HttpMethod = zod.z.enum([
  "GET",
  "POST",
  "PUT",
  "DELETE",
  "PATCH",
  "HEAD",
  "OPTIONS"
]);
var HttpMethodSchema = zod.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]);
var HttpRequestSchema = zod.z.object({
  url: zod.z.string().describe("API endpoint URL"),
  method: HttpMethodSchema.optional().default("GET").describe("HTTP method"),
  headers: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Custom HTTP headers"),
  params: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Query parameters"),
  body: zod.z.unknown().optional().describe("Request body for POST/PUT/PATCH")
});
var CorsConfigSchema = zod.z.object({
  /**
   * Enable CORS
   */
  enabled: zod.z.boolean().default(true).describe("Enable CORS"),
  /**
   * Allowed origins (* for all)
   */
  origins: zod.z.union([
    zod.z.string(),
    zod.z.array(zod.z.string())
  ]).default("*").describe("Allowed origins (* for all)"),
  /**
   * Allowed HTTP methods
   */
  methods: zod.z.array(HttpMethod).optional().describe("Allowed HTTP methods"),
  /**
   * Allow credentials (cookies, authorization headers)
   */
  credentials: zod.z.boolean().default(false).describe("Allow credentials (cookies, authorization headers)"),
  /**
   * Preflight cache duration in seconds
   */
  maxAge: zod.z.number().int().optional().describe("Preflight cache duration in seconds")
});
var RateLimitConfigSchema = zod.z.object({
  /**
   * Enable rate limiting
   */
  enabled: zod.z.boolean().default(false).describe("Enable rate limiting"),
  /**
   * Time window in milliseconds
   */
  windowMs: zod.z.number().int().default(6e4).describe("Time window in milliseconds"),
  /**
   * Max requests per window
   */
  maxRequests: zod.z.number().int().default(100).describe("Max requests per window")
});
var StaticMountSchema = zod.z.object({
  /**
   * URL path to serve from
   */
  path: zod.z.string().describe("URL path to serve from"),
  /**
   * Physical directory to serve
   */
  directory: zod.z.string().describe("Physical directory to serve"),
  /**
   * Cache-Control header value
   */
  cacheControl: zod.z.string().optional().describe("Cache-Control header value")
});
var AggregationFunctionEnum = zod.z.enum([
  "count",
  "sum",
  "avg",
  "min",
  "max",
  "count_distinct",
  "percentile",
  "median",
  "stddev",
  "variance"
]).describe("Standard aggregation functions");
var SortDirectionEnum = zod.z.enum(["asc", "desc"]).describe("Sort order direction");
var SortItemSchema = zod.z.object({
  field: zod.z.string().describe("Field name to sort by"),
  order: SortDirectionEnum.describe("Sort direction")
}).describe("Sort field and direction pair");
var MutationEventEnum = zod.z.enum([
  "insert",
  "update",
  "delete",
  "upsert"
]).describe("Data mutation event types");
var IsolationLevelEnum = zod.z.enum([
  "read_uncommitted",
  "read_committed",
  "repeatable_read",
  "serializable",
  "snapshot"
]).describe("Transaction isolation levels (snake_case standard)");
var CacheStrategyEnum = zod.z.enum(["lru", "lfu", "ttl", "fifo"]).describe("Cache eviction strategy");
var MetadataFormatSchema = zod.z.enum(["yaml", "json", "typescript", "javascript"]).describe("Metadata file format");
var BaseMetadataRecordSchema = zod.z.object({
  id: zod.z.string().describe("Unique metadata record identifier"),
  type: zod.z.string().describe('Metadata type (e.g. "object", "view", "flow")'),
  name: SnakeCaseIdentifierSchema.describe("Machine name (snake_case)"),
  format: MetadataFormatSchema.optional().describe("Source file format")
}).describe("Base metadata record fields shared across kernel and system");

// src/shared/branded-types.zod.ts
var ObjectNameSchema = SnakeCaseIdentifierSchema.brand().describe("Branded object name (snake_case, no dots)");
var FieldNameSchema = SnakeCaseIdentifierSchema.brand().describe("Branded field name (snake_case, no dots)");
var ViewNameSchema = SystemIdentifierSchema.brand().describe("Branded view name (system identifier)");
var AppNameSchema = SystemIdentifierSchema.brand().describe("Branded app name (system identifier)");
var FlowNameSchema = SystemIdentifierSchema.brand().describe("Branded flow name (system identifier)");
var RoleNameSchema = SystemIdentifierSchema.brand().describe("Branded role name (system identifier)");
var EncryptionAlgorithmSchema = zod.z.enum([
  "aes-256-gcm",
  "aes-256-cbc",
  "chacha20-poly1305"
]).describe("Supported encryption algorithm");
var KeyManagementProviderSchema = zod.z.enum([
  "local",
  "aws-kms",
  "azure-key-vault",
  "gcp-kms",
  "hashicorp-vault"
]).describe("Key management service provider");
var KeyRotationPolicySchema = zod.z.object({
  enabled: zod.z.boolean().default(false).describe("Enable automatic key rotation"),
  frequencyDays: zod.z.number().min(1).default(90).describe("Rotation frequency in days"),
  retainOldVersions: zod.z.number().default(3).describe("Number of old key versions to retain"),
  autoRotate: zod.z.boolean().default(true).describe("Automatically rotate without manual approval")
}).describe("Policy for automatic encryption key rotation");
var EncryptionConfigSchema = zod.z.object({
  enabled: zod.z.boolean().default(false).describe("Enable field-level encryption"),
  algorithm: EncryptionAlgorithmSchema.default("aes-256-gcm").describe("Encryption algorithm"),
  keyManagement: zod.z.object({
    provider: KeyManagementProviderSchema.describe("Key management service provider"),
    keyId: zod.z.string().optional().describe("Key identifier in the provider"),
    rotationPolicy: KeyRotationPolicySchema.optional().describe("Key rotation policy")
  }).describe("Key management configuration"),
  scope: zod.z.enum(["field", "record", "table", "database"]).describe("Encryption scope level"),
  deterministicEncryption: zod.z.boolean().default(false).describe("Allows equality queries on encrypted data"),
  searchableEncryption: zod.z.boolean().default(false).describe("Allows search on encrypted data")
}).describe("Field-level encryption configuration");
zod.z.object({
  fieldName: zod.z.string().describe("Name of the field to encrypt"),
  encryptionConfig: EncryptionConfigSchema.describe("Encryption settings for this field"),
  indexable: zod.z.boolean().default(false).describe("Allow indexing on encrypted field")
}).describe("Per-field encryption assignment");
var MaskingStrategySchema = zod.z.enum([
  "redact",
  // Complete redaction: ****
  "partial",
  // Partial masking: 138****5678
  "hash",
  // Hash value: sha256(value)
  "tokenize",
  // Tokenization: token-12345
  "randomize",
  // Randomize: generate random value
  "nullify",
  // Null value: null
  "substitute"
  // Substitute with dummy data
]).describe("Data masking strategy for PII protection");
var MaskingRuleSchema = zod.z.object({
  field: zod.z.string().describe("Field name to apply masking to"),
  strategy: MaskingStrategySchema.describe("Masking strategy to use"),
  pattern: zod.z.string().optional().describe("Regex pattern for partial masking"),
  preserveFormat: zod.z.boolean().default(true).describe("Keep the original data format after masking"),
  preserveLength: zod.z.boolean().default(true).describe("Keep the original data length after masking"),
  roles: zod.z.array(zod.z.string()).optional().describe("Roles that see masked data"),
  exemptRoles: zod.z.array(zod.z.string()).optional().describe("Roles that see unmasked data")
}).describe("Masking rule for a single field");
zod.z.object({
  enabled: zod.z.boolean().default(false).describe("Enable data masking"),
  rules: zod.z.array(MaskingRuleSchema).describe("List of field-level masking rules"),
  auditUnmasking: zod.z.boolean().default(true).describe("Log when masked data is accessed unmasked")
}).describe("Top-level data masking configuration for PII protection");

// src/data/field.zod.ts
var FieldType = zod.z.enum([
  // Core Text
  "text",
  "textarea",
  "email",
  "url",
  "phone",
  "password",
  // Rich Content
  "markdown",
  "html",
  "richtext",
  // Numbers
  "number",
  "currency",
  "percent",
  // Date & Time
  "date",
  "datetime",
  "time",
  // Logic
  "boolean",
  "toggle",
  // Toggle is a distinct UI from checkbox
  // Selection
  "select",
  // Single select dropdown
  "multiselect",
  // Multi select (often tags)
  "radio",
  // Radio group
  "checkboxes",
  // Checkbox group
  // Relational
  "lookup",
  "master_detail",
  // Dynamic reference
  "tree",
  // Hierarchical reference
  // Media
  "image",
  "file",
  "avatar",
  "video",
  "audio",
  // Calculated / System
  "formula",
  "summary",
  "autonumber",
  // Enhanced Types
  "location",
  // GPS coordinates
  "address",
  // Structured address
  "code",
  // Code editor (JSON/SQL/JS)
  "json",
  // Structured JSON data
  "color",
  // Color picker
  "rating",
  // Star rating
  "slider",
  // Numeric slider
  "signature",
  // Digital signature
  "qrcode",
  // QR code / Barcode
  "progress",
  // Progress bar
  "tags",
  // Simple tag list
  // AI/ML Types
  "vector"
  // Vector embeddings for AI/ML (semantic search, RAG)
]);
var SelectOptionSchema = zod.z.object({
  label: zod.z.string().describe("Display label (human-readable, any case allowed)"),
  value: SystemIdentifierSchema.describe("Stored value (lowercase machine identifier)"),
  color: zod.z.string().optional().describe("Color code for badges/charts"),
  default: zod.z.boolean().optional().describe("Is default option")
});
zod.z.object({
  latitude: zod.z.number().min(-90).max(90).describe("Latitude coordinate"),
  longitude: zod.z.number().min(-180).max(180).describe("Longitude coordinate"),
  altitude: zod.z.number().optional().describe("Altitude in meters"),
  accuracy: zod.z.number().optional().describe("Accuracy in meters")
});
var CurrencyConfigSchema = zod.z.object({
  precision: zod.z.number().int().min(0).max(10).default(2).describe("Decimal precision (default: 2)"),
  currencyMode: zod.z.enum(["dynamic", "fixed"]).default("dynamic").describe("Currency mode: dynamic (user selectable) or fixed (single currency)"),
  defaultCurrency: zod.z.string().length(3).default("CNY").describe("Default or fixed currency code (ISO 4217, e.g., USD, CNY, EUR)")
});
zod.z.object({
  value: zod.z.number().describe("Monetary amount"),
  currency: zod.z.string().length(3).describe("Currency code (ISO 4217)")
});
zod.z.object({
  street: zod.z.string().optional().describe("Street address"),
  city: zod.z.string().optional().describe("City name"),
  state: zod.z.string().optional().describe("State/Province"),
  postalCode: zod.z.string().optional().describe("Postal/ZIP code"),
  country: zod.z.string().optional().describe("Country name or code"),
  countryCode: zod.z.string().optional().describe("ISO country code (e.g., US, GB)"),
  formatted: zod.z.string().optional().describe("Formatted address string")
});
var VectorConfigSchema = zod.z.object({
  dimensions: zod.z.number().int().min(1).max(1e4).describe("Vector dimensionality (e.g., 1536 for OpenAI embeddings)"),
  distanceMetric: zod.z.enum(["cosine", "euclidean", "dotProduct", "manhattan"]).default("cosine").describe("Distance/similarity metric for vector search"),
  normalized: zod.z.boolean().default(false).describe("Whether vectors are normalized (unit length)"),
  indexed: zod.z.boolean().default(true).describe("Whether to create a vector index for fast similarity search"),
  indexType: zod.z.enum(["hnsw", "ivfflat", "flat"]).optional().describe("Vector index algorithm (HNSW for high accuracy, IVFFlat for large datasets)")
});
var FileAttachmentConfigSchema = zod.z.object({
  /** File Size Limits */
  minSize: zod.z.number().min(0).optional().describe("Minimum file size in bytes"),
  maxSize: zod.z.number().min(1).optional().describe("Maximum file size in bytes (e.g., 10485760 = 10MB)"),
  /** File Type Restrictions */
  allowedTypes: zod.z.array(zod.z.string()).optional().describe('Allowed file extensions (e.g., [".pdf", ".docx", ".jpg"])'),
  blockedTypes: zod.z.array(zod.z.string()).optional().describe('Blocked file extensions (e.g., [".exe", ".bat", ".sh"])'),
  allowedMimeTypes: zod.z.array(zod.z.string()).optional().describe('Allowed MIME types (e.g., ["image/jpeg", "application/pdf"])'),
  blockedMimeTypes: zod.z.array(zod.z.string()).optional().describe("Blocked MIME types"),
  /** Virus Scanning */
  virusScan: zod.z.boolean().default(false).describe("Enable virus scanning for uploaded files"),
  virusScanProvider: zod.z.enum(["clamav", "virustotal", "metadefender", "custom"]).optional().describe("Virus scanning service provider"),
  virusScanOnUpload: zod.z.boolean().default(true).describe("Scan files immediately on upload"),
  quarantineOnThreat: zod.z.boolean().default(true).describe("Quarantine files if threat detected"),
  /** Storage Configuration */
  storageProvider: zod.z.string().optional().describe("Object storage provider name (references ObjectStorageConfig)"),
  storageBucket: zod.z.string().optional().describe("Target bucket name"),
  storagePrefix: zod.z.string().optional().describe('Storage path prefix (e.g., "uploads/documents/")'),
  /** Image-Specific Validation */
  imageValidation: zod.z.object({
    minWidth: zod.z.number().min(1).optional().describe("Minimum image width in pixels"),
    maxWidth: zod.z.number().min(1).optional().describe("Maximum image width in pixels"),
    minHeight: zod.z.number().min(1).optional().describe("Minimum image height in pixels"),
    maxHeight: zod.z.number().min(1).optional().describe("Maximum image height in pixels"),
    aspectRatio: zod.z.string().optional().describe('Required aspect ratio (e.g., "16:9", "1:1")'),
    generateThumbnails: zod.z.boolean().default(false).describe("Auto-generate thumbnails"),
    thumbnailSizes: zod.z.array(zod.z.object({
      name: zod.z.string().describe('Thumbnail variant name (e.g., "small", "medium", "large")'),
      width: zod.z.number().min(1).describe("Thumbnail width in pixels"),
      height: zod.z.number().min(1).describe("Thumbnail height in pixels"),
      crop: zod.z.boolean().default(false).describe("Crop to exact dimensions")
    })).optional().describe("Thumbnail size configurations"),
    preserveMetadata: zod.z.boolean().default(false).describe("Preserve EXIF metadata"),
    autoRotate: zod.z.boolean().default(true).describe("Auto-rotate based on EXIF orientation")
  }).optional().describe("Image-specific validation rules"),
  /** Upload Behavior */
  allowMultiple: zod.z.boolean().default(false).describe("Allow multiple file uploads (overrides field.multiple)"),
  allowReplace: zod.z.boolean().default(true).describe("Allow replacing existing files"),
  allowDelete: zod.z.boolean().default(true).describe("Allow deleting uploaded files"),
  requireUpload: zod.z.boolean().default(false).describe("Require at least one file when field is required"),
  /** Metadata Extraction */
  extractMetadata: zod.z.boolean().default(true).describe("Extract file metadata (name, size, type, etc.)"),
  extractText: zod.z.boolean().default(false).describe("Extract text content from documents (OCR/parsing)"),
  /** Versioning */
  versioningEnabled: zod.z.boolean().default(false).describe("Keep previous versions of replaced files"),
  maxVersions: zod.z.number().min(1).optional().describe("Maximum number of versions to retain"),
  /** Access Control */
  publicRead: zod.z.boolean().default(false).describe("Allow public read access to uploaded files"),
  presignedUrlExpiry: zod.z.number().min(60).max(604800).default(3600).describe("Presigned URL expiration in seconds (default: 1 hour)")
}).refine((data) => {
  if (data.minSize !== void 0 && data.maxSize !== void 0 && data.minSize > data.maxSize) {
    return false;
  }
  return true;
}, {
  message: "minSize must be less than or equal to maxSize"
}).refine((data) => {
  if (data.virusScanProvider !== void 0 && data.virusScan !== true) {
    return false;
  }
  return true;
}, {
  message: "virusScanProvider requires virusScan to be enabled"
});
var DataQualityRulesSchema = zod.z.object({
  /** Enforce uniqueness constraint */
  uniqueness: zod.z.boolean().default(false).describe("Enforce unique values across all records"),
  /** Completeness ratio (0-1) indicating minimum percentage of non-null values */
  completeness: zod.z.number().min(0).max(1).default(0).describe("Minimum ratio of non-null values (0-1, default: 0 = no requirement)"),
  /** Accuracy validation against authoritative source */
  accuracy: zod.z.object({
    source: zod.z.string().describe('Reference data source for validation (e.g., "api.verify.com", "master_data")'),
    threshold: zod.z.number().min(0).max(1).describe("Minimum accuracy threshold (0-1, e.g., 0.95 = 95% match required)")
  }).optional().describe("Accuracy validation configuration")
});
var ComputedFieldCacheSchema = zod.z.object({
  /** Enable caching for this computed field */
  enabled: zod.z.boolean().describe("Enable caching for computed field results"),
  /** Time-to-live in seconds */
  ttl: zod.z.number().min(0).describe("Cache TTL in seconds (0 = no expiration)"),
  /** Array of field paths that trigger cache invalidation when changed */
  invalidateOn: zod.z.array(zod.z.string()).describe('Field paths that invalidate cache (e.g., ["inventory.quantity", "pricing.base_price"])')
});
zod.z.object({
  /** Identity */
  name: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name (snake_case)").optional(),
  label: zod.z.string().optional().describe("Human readable label"),
  type: FieldType.describe("Field Data Type"),
  description: zod.z.string().optional().describe("Tooltip/Help text"),
  format: zod.z.string().optional().describe("Format string (e.g. email, phone)"),
  /** Storage Layer Mapping */
  columnName: zod.z.string().optional().describe("Physical column name in the target datasource. Defaults to the field key when not set."),
  /** Database Constraints */
  required: zod.z.boolean().default(false).describe("Is required"),
  searchable: zod.z.boolean().default(false).describe("Is searchable"),
  multiple: zod.z.boolean().default(false).describe("Allow multiple values (Stores as Array/JSON). Applicable for select, lookup, file, image."),
  unique: zod.z.boolean().default(false).describe("Is unique constraint"),
  defaultValue: zod.z.unknown().optional().describe("Default value"),
  /** Text/String Constraints */
  maxLength: zod.z.number().optional().describe("Max character length"),
  minLength: zod.z.number().optional().describe("Min character length"),
  /** Number Constraints */
  precision: zod.z.number().optional().describe("Total digits"),
  scale: zod.z.number().optional().describe("Decimal places"),
  min: zod.z.number().optional().describe("Minimum value"),
  max: zod.z.number().optional().describe("Maximum value"),
  /** Selection Options */
  options: zod.z.array(SelectOptionSchema).optional().describe("Static options for select/multiselect"),
  /**
   * Relationship Config
   * 
   * Used by `lookup` and `master_detail` field types to define cross-object references.
   * The `reference` property is **required** for these types — it identifies the target
   * object whose records this field links to. The engine uses `reference` during $expand
   * post-processing to resolve foreign key IDs into full related objects via batch queries.
   * 
   * For `master_detail` fields, the parent record controls the lifecycle of child records
   * (e.g., cascade delete). For `lookup` fields, the reference is a soft link.
   */
  reference: zod.z.string().optional().describe(
    "Target object name (snake_case) for lookup/master_detail fields. Required for relationship types. Used by $expand to resolve foreign key IDs into full objects."
  ),
  referenceFilters: zod.z.array(zod.z.string()).optional().describe('Filters applied to lookup dialogs (e.g. "active = true")'),
  writeRequiresMasterRead: zod.z.boolean().optional().describe("If true, user needs read access to master record to edit this field"),
  deleteBehavior: zod.z.enum(["set_null", "cascade", "restrict"]).optional().default("set_null").describe("What happens if referenced record is deleted"),
  /** Calculation */
  expression: zod.z.string().optional().describe("Formula expression"),
  summaryOperations: zod.z.object({
    object: zod.z.string().describe("Source child object name for roll-up"),
    field: zod.z.string().describe("Field on child object to aggregate"),
    function: zod.z.enum(["count", "sum", "min", "max", "avg"]).describe("Aggregation function to apply")
  }).optional().describe("Roll-up summary definition"),
  /** Enhanced Field Type Configurations */
  // Code field config
  language: zod.z.string().optional().describe("Programming language for syntax highlighting (e.g., javascript, python, sql)"),
  theme: zod.z.string().optional().describe("Code editor theme (e.g., dark, light, monokai)"),
  lineNumbers: zod.z.boolean().optional().describe("Show line numbers in code editor"),
  // Rating field config
  maxRating: zod.z.number().optional().describe("Maximum rating value (default: 5)"),
  allowHalf: zod.z.boolean().optional().describe("Allow half-star ratings"),
  // Location field config
  displayMap: zod.z.boolean().optional().describe("Display map widget for location field"),
  allowGeocoding: zod.z.boolean().optional().describe("Allow address-to-coordinate conversion"),
  // Address field config
  addressFormat: zod.z.enum(["us", "uk", "international"]).optional().describe("Address format template"),
  // Color field config
  colorFormat: zod.z.enum(["hex", "rgb", "rgba", "hsl"]).optional().describe("Color value format"),
  allowAlpha: zod.z.boolean().optional().describe("Allow transparency/alpha channel"),
  presetColors: zod.z.array(zod.z.string()).optional().describe("Preset color options"),
  // Slider field config
  step: zod.z.number().optional().describe("Step increment for slider (default: 1)"),
  showValue: zod.z.boolean().optional().describe("Display current value on slider"),
  marks: zod.z.record(zod.z.string(), zod.z.string()).optional().describe('Custom marks/labels at specific values (e.g., {0: "Low", 50: "Medium", 100: "High"})'),
  // QR Code / Barcode field config
  // Note: qrErrorCorrection is only applicable when barcodeFormat='qr'
  // Runtime validation should enforce this constraint
  barcodeFormat: zod.z.enum(["qr", "ean13", "ean8", "code128", "code39", "upca", "upce"]).optional().describe("Barcode format type"),
  qrErrorCorrection: zod.z.enum(["L", "M", "Q", "H"]).optional().describe('QR code error correction level (L=7%, M=15%, Q=25%, H=30%). Only applicable when barcodeFormat is "qr"'),
  displayValue: zod.z.boolean().optional().describe("Display human-readable value below barcode/QR code"),
  allowScanning: zod.z.boolean().optional().describe("Enable camera scanning for barcode/QR code input"),
  // Currency field config
  currencyConfig: CurrencyConfigSchema.optional().describe("Configuration for currency field type"),
  // Vector field config
  vectorConfig: VectorConfigSchema.optional().describe("Configuration for vector field type (AI/ML embeddings)"),
  // File attachment field config
  fileAttachmentConfig: FileAttachmentConfigSchema.optional().describe("Configuration for file and attachment field types"),
  /** Enhanced Security & Compliance */
  // Encryption configuration
  encryptionConfig: EncryptionConfigSchema.optional().describe("Field-level encryption configuration for sensitive data (GDPR/HIPAA/PCI-DSS)"),
  // Data masking rules
  maskingRule: MaskingRuleSchema.optional().describe("Data masking rules for PII protection"),
  // Audit trail
  auditTrail: zod.z.boolean().default(false).describe("Enable detailed audit trail for this field (tracks all changes with user and timestamp)"),
  /** Field Dependencies & Relationships */
  // Field dependencies
  dependencies: zod.z.array(zod.z.string()).optional().describe("Array of field names that this field depends on (for formulas, visibility rules, etc.)"),
  /** Computed Field Optimization */
  // Computed field caching
  cached: ComputedFieldCacheSchema.optional().describe("Caching configuration for computed/formula fields"),
  /** Data Quality & Governance */
  // Data quality rules
  dataQuality: DataQualityRulesSchema.optional().describe("Data quality validation and monitoring rules"),
  /** Layout & Grouping */
  group: zod.z.string().optional().describe('Field group name for organizing fields in forms and layouts (e.g., "contact_info", "billing", "system")'),
  /** Conditional Requirements */
  conditionalRequired: zod.z.string().optional().describe(`Formula expression that makes this field required when TRUE (e.g., "status = 'closed_won'")`),
  /** Security & Visibility */
  hidden: zod.z.boolean().default(false).describe("Hidden from default UI"),
  readonly: zod.z.boolean().default(false).describe("Read-only in UI"),
  sortable: zod.z.boolean().optional().default(true).describe("Whether field is sortable in list views"),
  inlineHelpText: zod.z.string().optional().describe("Help text displayed below the field in forms"),
  trackFeedHistory: zod.z.boolean().optional().describe("Track field changes in Chatter/activity feed (Salesforce pattern)"),
  caseSensitive: zod.z.boolean().optional().describe("Whether text comparisons are case-sensitive"),
  autonumberFormat: zod.z.string().optional().describe('Auto-number display format pattern (e.g., "CASE-{0000}")'),
  /** Indexing */
  index: zod.z.boolean().default(false).describe("Create standard database index"),
  externalId: zod.z.boolean().default(false).describe("Is external ID for upsert operations")
});

// src/shared/suggestions.zod.ts
function levenshteinDistance(a, b) {
  const la = a.length;
  const lb = b.length;
  if (la === 0) return lb;
  if (lb === 0) return la;
  let prev = new Array(lb + 1);
  let curr = new Array(lb + 1);
  for (let j = 0; j <= lb; j++) {
    prev[j] = j;
  }
  for (let i = 1; i <= la; i++) {
    curr[0] = i;
    for (let j = 1; j <= lb; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      curr[j] = Math.min(
        prev[j] + 1,
        // deletion
        curr[j - 1] + 1,
        // insertion
        prev[j - 1] + cost
        // substitution
      );
    }
    [prev, curr] = [curr, prev];
  }
  return prev[lb];
}
function findClosestMatches(input, candidates, maxDistance = 3, maxResults = 3) {
  const normalized = input.toLowerCase().replace(/[-\s]/g, "_");
  const scored = candidates.map((candidate) => ({
    value: candidate,
    distance: levenshteinDistance(normalized, candidate)
  })).filter((s) => s.distance <= maxDistance && s.distance > 0).sort((a, b) => a.distance - b.distance);
  return scored.slice(0, maxResults).map((s) => s.value);
}
var FIELD_TYPE_ALIASES = {
  // Common alternative names
  string: "text",
  str: "text",
  varchar: "text",
  char: "text",
  int: "number",
  integer: "number",
  float: "number",
  double: "number",
  decimal: "number",
  numeric: "number",
  bool: "boolean",
  checkbox: "boolean",
  check: "boolean",
  date_time: "datetime",
  timestamp: "datetime",
  // Common typos
  text_area: "textarea",
  textarea_: "textarea",
  textfield: "text",
  dropdown: "select",
  picklist: "select",
  enum: "select",
  multi_select: "multiselect",
  multiselect_: "multiselect",
  reference: "lookup",
  ref: "lookup",
  foreign_key: "lookup",
  fk: "lookup",
  relation: "lookup",
  master: "master_detail",
  richtext_: "richtext",
  rich_text: "richtext",
  upload: "file",
  attachment: "file",
  photo: "image",
  picture: "image",
  img: "image",
  percent_: "percent",
  percentage: "percent",
  money: "currency",
  price: "currency",
  auto_number: "autonumber",
  auto_increment: "autonumber",
  sequence: "autonumber",
  markdown_: "markdown",
  md: "markdown",
  barcode: "qrcode",
  tag: "tags",
  star: "rating",
  stars: "rating",
  geo: "location",
  gps: "location",
  coordinates: "location",
  embed: "vector",
  embedding: "vector",
  embeddings: "vector"
};
function suggestFieldType(input) {
  const normalized = input.toLowerCase().replace(/[-\s]/g, "_");
  const alias = FIELD_TYPE_ALIASES[normalized];
  if (alias) {
    return [alias];
  }
  return findClosestMatches(normalized, FieldType.options);
}
function formatSuggestion(suggestions) {
  if (suggestions.length === 0) return "";
  if (suggestions.length === 1) return `Did you mean '${suggestions[0]}'?`;
  return `Did you mean one of: ${suggestions.map((s) => `'${s}'`).join(", ")}?`;
}

// src/shared/error-map.zod.ts
var objectStackErrorMap = (issue) => {
  if (issue.code === "invalid_value") {
    const values = issue.values;
    const input = issue.input;
    const received = String(input ?? "");
    const options = values.map(String);
    const fieldTypeOptions = FieldType.options;
    const isFieldTypeEnum = options.length > 10 && fieldTypeOptions.every((ft) => options.includes(ft));
    if (isFieldTypeEnum) {
      const suggestions2 = suggestFieldType(received);
      const suggestion2 = formatSuggestion(suggestions2);
      const base2 = `Invalid field type '${received}'.`;
      return {
        message: suggestion2 ? `${base2} ${suggestion2}` : `${base2} Valid types: ${options.slice(0, 10).join(", ")}...`
      };
    }
    const suggestions = findClosestMatches(received, options);
    const suggestion = formatSuggestion(suggestions);
    const base = `Invalid value '${received}'.`;
    return {
      message: suggestion ? `${base} ${suggestion}` : `${base} Expected one of: ${options.join(", ")}.`
    };
  }
  if (issue.code === "too_small") {
    const origin = issue.origin;
    const minimum = issue.minimum;
    if (origin === "string") {
      return {
        message: `Must be at least ${minimum} character${minimum === 1 ? "" : "s"} long.`
      };
    }
  }
  if (issue.code === "too_big") {
    const origin = issue.origin;
    const maximum = issue.maximum;
    if (origin === "string") {
      return {
        message: `Must be at most ${maximum} character${maximum === 1 ? "" : "s"} long.`
      };
    }
  }
  if (issue.code === "invalid_format") {
    const format = issue.format;
    const input = issue.input;
    if (format === "regex" && input) {
      const pathArr = issue.path;
      const pathStr = pathArr?.join(".") ?? "";
      if (pathStr.endsWith("name") || pathStr === "name") {
        return {
          message: `Invalid identifier '${input}'. Must be lowercase snake_case (e.g., 'my_object', 'task_name'). No uppercase, spaces, or hyphens allowed.`
        };
      }
    }
  }
  if (issue.code === "invalid_type") {
    const expected = issue.expected;
    const input = issue.input;
    if (input === void 0) {
      const pathArr = issue.path;
      const field = pathArr?.[pathArr.length - 1] ?? "";
      return {
        message: `Required property '${field}' is missing.`
      };
    }
    const receivedType = input === null ? "null" : typeof input;
    return {
      message: `Expected ${expected} but received ${receivedType}.`
    };
  }
  if (issue.code === "unrecognized_keys") {
    const keys = issue.keys;
    const keyStr = keys.join(", ");
    return {
      message: `Unrecognized key${keys.length > 1 ? "s" : ""}: ${keyStr}. Check for typos in property names.`
    };
  }
  return null;
};
function formatZodIssue(issue) {
  const path = issue.path.length > 0 ? issue.path.join(".") : "(root)";
  return `  \u2717 ${path}: ${issue.message}`;
}
function formatZodError(error, label) {
  const count = error.issues.length;
  const header = label ? `${label} (${count} issue${count === 1 ? "" : "s"}):` : `Validation failed (${count} issue${count === 1 ? "" : "s"}):`;
  const lines = error.issues.map(formatZodIssue);
  return `${header}

${lines.join("\n")}`;
}
function safeParsePretty(schema, data, label) {
  const result = schema.safeParse(data, { error: objectStackErrorMap });
  if (result.success) {
    return { success: true, data: result.data };
  }
  return {
    success: false,
    error: result.error,
    formatted: formatZodError(result.error, label)
  };
}

// src/shared/metadata-collection.zod.ts
var MAP_SUPPORTED_FIELDS = [
  "objects",
  "apps",
  "pages",
  "dashboards",
  "reports",
  "actions",
  "themes",
  "workflows",
  "approvals",
  "flows",
  "roles",
  "permissions",
  "sharingRules",
  "policies",
  "apis",
  "webhooks",
  "agents",
  "ragPipelines",
  "hooks",
  "mappings",
  "analyticsCubes",
  "connectors",
  "datasources"
];
function normalizeMetadataCollection(value, keyField = "name") {
  if (value == null || Array.isArray(value)) return value;
  if (typeof value === "object") {
    return Object.entries(value).map(([key, item]) => {
      if (item && typeof item === "object" && !Array.isArray(item)) {
        const obj = item;
        if (!(keyField in obj) || obj[keyField] === void 0) {
          return { ...obj, [keyField]: key };
        }
        return obj;
      }
      return item;
    });
  }
  return value;
}
function normalizeStackInput(input) {
  const result = { ...input };
  for (const field of MAP_SUPPORTED_FIELDS) {
    if (field in result) {
      result[field] = normalizeMetadataCollection(result[field]);
    }
  }
  return result;
}
var METADATA_ALIASES = {
  triggers: "hooks"
};
function normalizePluginMetadata(metadata) {
  const result = { ...metadata };
  for (const [alias, canonical] of Object.entries(METADATA_ALIASES)) {
    if (alias in result) {
      const aliasValue = normalizeMetadataCollection(result[alias]);
      const canonicalValue = normalizeMetadataCollection(result[canonical]);
      if (Array.isArray(aliasValue)) {
        result[canonical] = Array.isArray(canonicalValue) ? [...canonicalValue, ...aliasValue] : aliasValue;
      }
      delete result[alias];
    }
  }
  for (const field of MAP_SUPPORTED_FIELDS) {
    if (field in result) {
      result[field] = normalizeMetadataCollection(result[field]);
    }
  }
  if (Array.isArray(result.plugins)) {
    result.plugins = result.plugins.map((p) => {
      if (p && typeof p === "object" && !Array.isArray(p)) {
        return normalizePluginMetadata(p);
      }
      return p;
    });
  }
  return result;
}

exports.AggregationFunctionEnum = AggregationFunctionEnum;
exports.AppNameSchema = AppNameSchema;
exports.BaseMetadataRecordSchema = BaseMetadataRecordSchema;
exports.CacheStrategyEnum = CacheStrategyEnum;
exports.CorsConfigSchema = CorsConfigSchema;
exports.EventNameSchema = EventNameSchema;
exports.FieldMappingSchema = FieldMappingSchema;
exports.FieldNameSchema = FieldNameSchema;
exports.FlowNameSchema = FlowNameSchema;
exports.HttpMethod = HttpMethod;
exports.HttpMethodSchema = HttpMethodSchema;
exports.HttpRequestSchema = HttpRequestSchema;
exports.IsolationLevelEnum = IsolationLevelEnum;
exports.MAP_SUPPORTED_FIELDS = MAP_SUPPORTED_FIELDS;
exports.METADATA_ALIASES = METADATA_ALIASES;
exports.MetadataFormatSchema = MetadataFormatSchema;
exports.MutationEventEnum = MutationEventEnum;
exports.ObjectNameSchema = ObjectNameSchema;
exports.RateLimitConfigSchema = RateLimitConfigSchema;
exports.RoleNameSchema = RoleNameSchema;
exports.SnakeCaseIdentifierSchema = SnakeCaseIdentifierSchema;
exports.SortDirectionEnum = SortDirectionEnum;
exports.SortItemSchema = SortItemSchema;
exports.StaticMountSchema = StaticMountSchema;
exports.SystemIdentifierSchema = SystemIdentifierSchema;
exports.TransformTypeSchema = TransformTypeSchema;
exports.ViewNameSchema = ViewNameSchema;
exports.findClosestMatches = findClosestMatches;
exports.formatSuggestion = formatSuggestion;
exports.formatZodError = formatZodError;
exports.formatZodIssue = formatZodIssue;
exports.levenshteinDistance = levenshteinDistance;
exports.normalizeMetadataCollection = normalizeMetadataCollection;
exports.normalizePluginMetadata = normalizePluginMetadata;
exports.normalizeStackInput = normalizeStackInput;
exports.objectStackErrorMap = objectStackErrorMap;
exports.safeParsePretty = safeParsePretty;
exports.suggestFieldType = suggestFieldType;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map