All files / layers interfaces.ts

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
// =============================================================================
// 3-Layer Frontend Architecture — Type Contracts
// =============================================================================
// Architecture authority: docs/UX/architecture-overview.md
// Layer contracts:       docs/UX/layer-contracts/{L1,L2-invariant,L2-variant,L3-feature}.md
//
// This file defines the type-level contracts between architectural layers.
// It contains zero runtime code — only interfaces, types, and type helpers.
//
// Generic parameter conventions:
//   TEntity      — entity shape from OpenAPI schemas
//   TCreateBody  — create mutation request body (OpenAPI-derived, replaceable via codegen)
//   TUpdateBody  — update mutation request body (OpenAPI-derived, replaceable via codegen)
//   TListQuery   — list endpoint query parameter record (OpenAPI-derived, replaceable via codegen)
//   TForm        — form model (may differ from TEntity when form transforms fields)
// =============================================================================
 
import type { EntityPath } from '@/layers/L1/contracts'
import type { ReactNode } from 'react'
 
// ---------------------------------------------------------------------------
// L3 — Feature Config Surface
// ---------------------------------------------------------------------------
 
export interface PageConfig {
  title: string
  breadcrumbs?: { label: string; href?: string }[]
  actions?: ReactNode
}
 
export interface ListConfig {
  entityPath: EntityPath
  prefix: string
  columns: ColumnConfig[]
  sort?: { field: string; order?: 'asc' | 'desc' }
  filters?: FilterConfig[]
  entityName?: string
  createLabel?: string
  createTarget?: string
  rowTarget?: string
  rowTargetOverride?: (row: Record<string, unknown>) => void
  fixedParams?: Record<string, string | number | boolean>
  sse?: { enabled: boolean }
}
 
export interface DetailConfig {
  entityPath: EntityPath
  title?: string
  editTargetOverride?: string
  onDeleteSuccess?: () => void
  actionTargets?: {
    edit?: string
    delete?: boolean
  }
 
  readGrouping?: { label: string; fields: string[] }[]
  fieldFormatters?: Record<string, (value: unknown, entity: Record<string, unknown>) => React.ReactNode>
}
 
export type CrudFieldType =
  | 'text'
  | 'textarea'
  | 'password'
  | 'checkbox'
  | 'entity-select'
  | 'kv-editor'
  | 'yaml'
 
export interface EntitySelectSource {
  entityPath: EntityPath
  idField?: string
  nameField?: string
  descriptionField?: string
}
 
export interface CrudFieldValidation {
  required?: boolean
  minLength?: number
  maxLength?: number
  pattern?: string
  patternMessage?: string
}
 
export interface CrudFieldConfig {
  field: string
  title?: string
  tooltip?: string
  description?: string
  validation?: CrudFieldValidation
}
 
export interface CrudConfig {
  entityPath: EntityPath
  fieldSet: CrudFieldConfig[]
  title?: string
  fieldTypes?: Record<string, CrudFieldType>
  entitySelectSources?: Record<string, EntitySelectSource>
  successTarget?: string
  cancelTarget?: string
  onSuccess?: () => void
  onCancel?: () => void
  renderForm?: React.ComponentType<CrudFormComponentProps & React.RefAttributes<{ submit: () => Promise<void> }>>
}
 
export interface CrudFormComponentProps {
  mode: 'add' | 'edit'
  entityId: string | null
  existingEntity: Record<string, unknown> | null
  isLoading: boolean
  onDirtyChange: (dirty: boolean) => void
  onPendingChange: (pending: boolean) => void
  onSuccess: (result?: { id?: string }) => void
}
 
export interface ColumnConfig {
  field: string
  label: string
  sortable?: boolean
  width?: string
  render?: (row: Record<string, unknown>) => React.ReactNode
}
 
export interface FilterConfig {
  field: string
  label: string
  type: 'text' | 'select' | 'date'
  options?: { value: string; label: string }[]
}
 
// ---------------------------------------------------------------------------
// Route Context — Provided by Router, Consumed by L2 + L3
//   Discriminated by page type. CRUD mode is bounded to page context:
//     - collection: may carry add only
//     - detail:     may carry add or edit
//   detail without id is a compile-time error.
// ---------------------------------------------------------------------------
 
export type RouteContext =
  | { page: 'collection'; crud?: { mode: 'add'; owner: string; prefix?: string } }
  | { page: 'detail'; id: string; crud?: { mode: 'add' | 'edit'; owner: string; prefix?: string } }
 
// ---------------------------------------------------------------------------
// Shared — Cross-layer Types
// ---------------------------------------------------------------------------
 
export interface OfflineState {
  isOnline: boolean
  pendingCount: number
  lastSynced: Date | null
}
 
// ---------------------------------------------------------------------------
// L1 — Data Layer Contract
//   ApiContract is the root type: it carries OpenAPI-derived entity metadata,
//   endpoint paths, subscription identity, and payload types. All downstream
//   contracts derive their types from it.
//
//   Generic parameter defaults (Partial<T>, QueryParams) are placeholders.
//   Replace with OpenAPI-derived types via codegen — do not widen.
// ---------------------------------------------------------------------------
 
export type QueryMode = 'cache' | 'live'
 
export interface ListQueryOptions {
  queryMode?: QueryMode
  /** When true, sets staleTime to Infinity — relies on SSE cache updates instead of HTTP refetch */
  sseMode?: boolean
}
 
export interface ApiContract<
  TEntity extends { id: string },
  TCreateBody = Partial<TEntity>,
  TUpdateBody = Partial<TEntity>,
  TListQuery = QueryParams,
> {
  /** Entity id extractor — supports non-standard id field names */
  idOf: (entity: TEntity) => string
 
  /** Plularised resource name used for cache keys and route composition */
  entityPath: string
 
  /** CRUD endpoint path templates */
  endpoints: {
    list: string
    detail: (id: string) => string
    create: string
    update: (id: string) => string
    remove?: (id: string) => string
  }
 
  /** Optional typed request normalizers (OpenAPI-first hook for payload typing) */
  request?: {
    create: (input: TCreateBody) => TCreateBody
    update: (input: TUpdateBody) => TUpdateBody
  }
 
  /**
   * Maps create body fields to endpoint path template tokens.
   * When the create endpoint is a template (e.g. /projects/{projectId}/pipelines),
   * this resolver provides the values for each token from the request body.
   * Must cover every template token in endpoints.create — missing tokens
   * will throw at runtime via resolveEndpointTemplate.
   */
  createPathParams?: (input: TCreateBody, context?: QueryParams) => QueryParams
 
  /** SSE subscription metadata */
  subscription?: {
    ssePath: string
    entityName: string
  }
 
  /** Default list query parameters (applied when caller omits them) */
  defaultListQuery?: TListQuery
}
 
export interface EntityHooks<
  TEntity extends { id: string },
  TCreateBody = Partial<TEntity>,
  TUpdateBody = Partial<TEntity>,
  TListQuery = QueryParams,
> {
  apiContract: ApiContract<TEntity, TCreateBody, TUpdateBody, TListQuery>
 
  useEntityList: (params: TListQuery, options?: ListQueryOptions) => ListResult<TEntity>
  useEntityDetail: (id: string) => DetailResult<TEntity>
  useMutation: () => MutationHandle<TEntity, TCreateBody, TUpdateBody>
  useSubscription: (
    params: TListQuery,
  ) => SubscriptionHandle
}
 
export interface QueryParams {
  [key: string]: string | number | boolean | undefined
}
 
export interface ListResult<TEntity> {
  data: TEntity[]
  total?: number
  hasMore?: boolean
  totalEstimate?: number
  isLoading: boolean
  isFetching: boolean
  error: unknown
  refetch: () => void
}
 
export interface DetailResult<TEntity> {
  data: TEntity | null
  isLoading: boolean
  isFetching: boolean
  error: unknown
  refetch: () => void
}
 
export interface MutationHandle<
  TEntity,
  TCreateBody = Partial<TEntity>,
  TUpdateBody = Partial<TEntity>,
> {
  create: (input: TCreateBody, context?: QueryParams) => void
  update: (id: string, input: TUpdateBody) => void
  remove: (id: string) => void
  isPending: boolean
  isError: boolean
  error: unknown
  lastMutationData: TEntity | null
}
 
export type ConnectionState = 'connected' | 'reconnecting' | 'lost'
 
export interface SubscriptionHandle {
  connectionState: ConnectionState
  reconnect: () => void
}
 
// ---------------------------------------------------------------------------
// L2 Invariant — Coordinator State and Behavior Contract
//   TForm represents the form model shape. Defaults to TEntity when the form
//   maps 1:1 to the entity shape. Feature implementations may use a narrower
//   TForm when the form model diverges from the API entity.
// ---------------------------------------------------------------------------
 
export interface BehaviorContract<
  TEntity,
  TForm = TEntity,
  TCreateBody = Partial<TEntity>,
  TUpdateBody = Partial<TEntity>,
> {
  defaults: () => TForm
  populate: (entity: TEntity) => TForm
  toCreate: (form: TForm) => TCreateBody
  toUpdate: (form: TForm) => TUpdateBody
  fieldPolicy: (mode: 'add' | 'edit') => FieldPolicy
}
 
export interface FieldPolicy {
  [field: string]: {
    visible: boolean
    editable: boolean
  }
}
 
export interface DeleteState {
  showConfirm: boolean
  isPending: boolean
  error: unknown | null
  requestDelete: () => void
  confirmDelete: () => void
  cancelDelete: () => void
}
 
export interface EntitySelectOptionData {
  options: Array<{ value: string; label: string; description?: string }>
  isLoading: boolean
  error: unknown
}
 
export interface CoordinatorSnapshot<TForm> {
  activeCrud: CrudContext | null
  formModel: TForm
  fieldPolicy: FieldPolicy
  bridge: FormBridge
  submit: () => void
  failure: FailureIntent | null
  closeIntent: { type: 'success' | 'cancel' } | null
  lastMutationData: unknown
  deleteState: DeleteState | null
  entitySelectData: Record<string, EntitySelectOptionData>
}
 
export interface CrudContext {
  mode: 'add' | 'edit'
  owner: string
  prefix?: string
}
 
export interface FormBridge {
  dirty: boolean
  pending: boolean
}
 
export interface FailureIntent {
  cause: unknown
  retry: () => void
}
 
// ---------------------------------------------------------------------------
// L2 Variant — Surface Props Contracts
//   TForm is required — no default. The coordinator snapshot carries the
//   concrete form type through the generic.
// ---------------------------------------------------------------------------
 
export interface ListSurfaceProps<TForm> {
  config: ListConfig
  routeContext: RouteContext
  coordinatorSnapshot: CoordinatorSnapshot<TForm>
  overrides?: ListVisualOverrides
}
 
export interface DetailSurfaceProps<TForm> {
  config: DetailConfig
  routeContext: RouteContext
  coordinatorSnapshot: CoordinatorSnapshot<TForm>
  overrides?: DetailVisualOverrides
  onDeleteSuccess?: () => void
}
 
export interface CrudSurfaceProps<TForm> {
  coordinatorSnapshot: CoordinatorSnapshot<TForm>
  routeContext: RouteContext
  onClose: () => void
  onSuccess: () => void
  overrides?: CrudVisualOverrides
}
 
// ---------------------------------------------------------------------------
// L3 Override Types — Bounded Visual Override Contract
// ---------------------------------------------------------------------------
 
export interface ListVisualOverrides {
  labels?: Record<string, string>
  columns?: { hidden?: string[]; order?: string[] }
  fragments?: {
    loading?: React.ReactNode
    empty?: React.ReactNode
    error?: React.ReactNode
  }
  layoutWrapper?: React.ComponentType<{ children: React.ReactNode }>
}
 
export interface DetailVisualOverrides {
  fragments?: {
    loading?: React.ReactNode
    empty?: React.ReactNode
    error?: React.ReactNode
  }
  layoutWrapper?: React.ComponentType<{ children: React.ReactNode }>
}
 
export interface CrudVisualOverrides {
  labels?: { title?: string; save?: string; cancel?: string }
  fieldOrder?: string[]
  fragments?: {
    loading?: React.ReactNode
    error?: React.ReactNode
  }
}