@asteby/metacore-runtime-react 53.4.1 → 53.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +73 -0
  3. package/dist/index.d.ts +2 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +4 -0
  6. package/dist/setup/addon-config-surface.d.ts +119 -0
  7. package/dist/setup/addon-config-surface.d.ts.map +1 -0
  8. package/dist/setup/addon-config-surface.js +662 -0
  9. package/dist/setup/connector-blocks-model.d.ts +79 -0
  10. package/dist/setup/connector-blocks-model.d.ts.map +1 -0
  11. package/dist/setup/connector-blocks-model.js +96 -0
  12. package/dist/setup/connector-blocks.d.ts +48 -0
  13. package/dist/setup/connector-blocks.d.ts.map +1 -0
  14. package/dist/setup/connector-blocks.js +132 -0
  15. package/dist/setup/connector-form-model.d.ts +40 -0
  16. package/dist/setup/connector-form-model.d.ts.map +1 -0
  17. package/dist/setup/connector-form-model.js +76 -0
  18. package/dist/setup/flow-model.d.ts +49 -0
  19. package/dist/setup/flow-model.d.ts.map +1 -0
  20. package/dist/setup/flow-model.js +124 -0
  21. package/dist/setup/health-card.d.ts +25 -0
  22. package/dist/setup/health-card.d.ts.map +1 -0
  23. package/dist/setup/health-card.js +21 -0
  24. package/dist/setup/index.d.ts +13 -0
  25. package/dist/setup/index.d.ts.map +1 -0
  26. package/dist/setup/index.js +15 -0
  27. package/dist/setup/messages.d.ts +15 -0
  28. package/dist/setup/messages.d.ts.map +1 -0
  29. package/dist/setup/messages.js +320 -0
  30. package/dist/setup/records-table.d.ts +24 -0
  31. package/dist/setup/records-table.d.ts.map +1 -0
  32. package/dist/setup/records-table.js +80 -0
  33. package/dist/setup/setup-flow.d.ts +30 -0
  34. package/dist/setup/setup-flow.d.ts.map +1 -0
  35. package/dist/setup/setup-flow.js +277 -0
  36. package/dist/setup/setup-form-step.d.ts +20 -0
  37. package/dist/setup/setup-form-step.d.ts.map +1 -0
  38. package/dist/setup/setup-form-step.js +173 -0
  39. package/dist/setup/step-status-badge.d.ts +12 -0
  40. package/dist/setup/step-status-badge.d.ts.map +1 -0
  41. package/dist/setup/step-status-badge.js +21 -0
  42. package/dist/setup/tone.d.ts +8 -0
  43. package/dist/setup/tone.d.ts.map +1 -0
  44. package/dist/setup/tone.js +33 -0
  45. package/dist/setup/types.d.ts +130 -0
  46. package/dist/setup/types.d.ts.map +1 -0
  47. package/dist/setup/types.js +1 -0
  48. package/package.json +9 -5
  49. package/src/__tests__/addon-config-surface.test.tsx +260 -0
  50. package/src/__tests__/connector-blocks.test.tsx +302 -0
  51. package/src/__tests__/setup-components.test.tsx +147 -0
  52. package/src/__tests__/setup-flow-model.test.ts +117 -0
  53. package/src/__tests__/setup-flow.test.tsx +424 -0
  54. package/src/index.ts +29 -0
  55. package/src/setup/addon-config-surface.tsx +1426 -0
  56. package/src/setup/connector-blocks-model.ts +163 -0
  57. package/src/setup/connector-blocks.tsx +341 -0
  58. package/src/setup/connector-form-model.ts +115 -0
  59. package/src/setup/flow-model.ts +156 -0
  60. package/src/setup/health-card.tsx +131 -0
  61. package/src/setup/index.ts +35 -0
  62. package/src/setup/messages.ts +334 -0
  63. package/src/setup/records-table.tsx +186 -0
  64. package/src/setup/setup-flow.tsx +562 -0
  65. package/src/setup/setup-form-step.tsx +342 -0
  66. package/src/setup/step-status-badge.tsx +47 -0
  67. package/src/setup/tone.ts +44 -0
  68. package/src/setup/types.ts +147 -0
@@ -0,0 +1,156 @@
1
+ // Pure logic of a setup flow (no React): effective status with `depends_on`,
2
+ // which step is active, progress, completion and the polling cadence. Kept
3
+ // apart so it is tested without rendering anything.
4
+ import type { SetupFlowState, SetupStepDef, SetupStepState, StepStatus } from './types'
5
+
6
+ export const STEP_STATUSES: StepStatus[] = ['pending', 'running', 'ok', 'warn', 'error', 'blocked']
7
+
8
+ /** Accepts the array or the by-key map the server may send. */
9
+ export function normalizeState(raw: SetupFlowState | null | undefined): Record<string, SetupStepState> {
10
+ const out: Record<string, SetupStepState> = {}
11
+ const steps = raw?.steps
12
+ if (!steps) return out
13
+ if (Array.isArray(steps)) {
14
+ for (const s of steps) if (s?.key) out[s.key] = s
15
+ } else {
16
+ for (const [k, s] of Object.entries(steps)) if (s) out[k] = { ...s, key: s.key ?? k }
17
+ }
18
+ return out
19
+ }
20
+
21
+ /** A step counts as satisfied (unblocks dependants) when ok, warn or skipped. */
22
+ export function isSatisfied(st: SetupStepState | undefined): boolean {
23
+ if (!st) return false
24
+ return st.status === 'ok' || st.status === 'warn' || st.skipped === true
25
+ }
26
+
27
+ /** Steps this one waits on that are not satisfied yet. */
28
+ export function unmetDependencies(
29
+ def: SetupStepDef,
30
+ states: Record<string, SetupStepState>,
31
+ ): string[] {
32
+ return (def.depends_on ?? []).filter((k) => !isSatisfied(states[k]))
33
+ }
34
+
35
+ /**
36
+ * Status shown for a step: the server's, except that a step whose
37
+ * dependencies are unmet is `blocked` (unless it is already running/ok, which
38
+ * the server decides). A skipped step reads as `ok`.
39
+ */
40
+ export function effectiveStatus(
41
+ def: SetupStepDef,
42
+ states: Record<string, SetupStepState>,
43
+ ): StepStatus {
44
+ const st = states[def.key]
45
+ if (st?.skipped) return 'ok'
46
+ const own = st?.status ?? 'pending'
47
+ if (own === 'ok' || own === 'running') return own
48
+ if (unmetDependencies(def, states).length > 0) return 'blocked'
49
+ return own === 'blocked' ? 'pending' : own
50
+ }
51
+
52
+ /** First step that needs the person: not satisfied and not blocked; else the last. */
53
+ export function pickActiveStep(
54
+ defs: SetupStepDef[],
55
+ states: Record<string, SetupStepState>,
56
+ ): string | undefined {
57
+ if (defs.length === 0) return undefined
58
+ const open = defs.find((d) => {
59
+ const eff = effectiveStatus(d, states)
60
+ return eff !== 'blocked' && !isSatisfied(states[d.key])
61
+ })
62
+ return (open ?? defs[defs.length - 1]).key
63
+ }
64
+
65
+ export interface FlowProgress {
66
+ done: number
67
+ total: number
68
+ percent: number
69
+ complete: boolean
70
+ }
71
+
72
+ /**
73
+ * Progress over the REQUIRED steps (optional ones do not hold completion
74
+ * back, but count as done when they are). The flow is complete when every
75
+ * required step is satisfied; an error step is never satisfied.
76
+ */
77
+ export function flowProgress(
78
+ defs: SetupStepDef[],
79
+ states: Record<string, SetupStepState>,
80
+ serverCompleted?: boolean,
81
+ ): FlowProgress {
82
+ const required = defs.filter((d) => !d.optional)
83
+ const total = required.length
84
+ const done = required.filter((d) => isSatisfied(states[d.key])).length
85
+ const complete = serverCompleted === true || (total > 0 && done === total)
86
+ const shown = serverCompleted === true ? total : done
87
+ return {
88
+ done: shown,
89
+ total,
90
+ percent: total === 0 ? 100 : Math.round((shown / total) * 100),
91
+ complete,
92
+ }
93
+ }
94
+
95
+ export interface BackoffOptions {
96
+ baseMs?: number
97
+ factor?: number
98
+ maxMs?: number
99
+ /** Ceiling honoured for a server `retry_after_s`. */
100
+ maxRetryAfterMs?: number
101
+ }
102
+
103
+ /**
104
+ * Delay before the next poll. Without a hint: exponential from `baseMs`
105
+ * (2s, 3.2s, 5.1s…) capped at `maxMs` (30s). A server `retry_after_s` wins,
106
+ * but never below 1s nor above `maxRetryAfterMs` (5 min).
107
+ */
108
+ export function nextPollDelayMs(
109
+ attempt: number,
110
+ retryAfterS?: number,
111
+ opts: BackoffOptions = {},
112
+ ): number {
113
+ const { baseMs = 2000, factor = 1.6, maxMs = 30000, maxRetryAfterMs = 300000 } = opts
114
+ if (typeof retryAfterS === 'number' && Number.isFinite(retryAfterS) && retryAfterS > 0) {
115
+ return Math.min(Math.max(retryAfterS * 1000, 1000), maxRetryAfterMs)
116
+ }
117
+ const n = Math.max(0, Math.floor(attempt))
118
+ return Math.min(Math.round(baseMs * Math.pow(factor, n)), maxMs)
119
+ }
120
+
121
+ /** Only http(s) and app-relative paths may be opened from a `fix.url`. */
122
+ export function safeUrl(url: string | undefined): string | null {
123
+ if (!url) return null
124
+ const u = url.trim()
125
+ // Browsers strip tabs/newlines and treat `\` as `/`, so `/\evil.com` or
126
+ // `/<TAB>/evil.com` resolve to another host: reject control chars and
127
+ // backslashes outright, then require the resolved origin to be ours.
128
+ // eslint-disable-next-line no-control-regex
129
+ if (/[\\\u0000-\u001f\u007f]/.test(u)) return null
130
+ if (u.startsWith('/')) {
131
+ if (u.startsWith('//')) return null
132
+ const origin = typeof location !== 'undefined' && location.origin ? location.origin : 'http://localhost'
133
+ try {
134
+ return new URL(u, origin).origin === origin ? u : null
135
+ } catch {
136
+ return null
137
+ }
138
+ }
139
+ try {
140
+ const p = new URL(u)
141
+ return p.protocol === 'https:' || p.protocol === 'http:' ? p.toString() : null
142
+ } catch {
143
+ return null
144
+ }
145
+ }
146
+
147
+ /** Merges a runStep/skipStep answer (step or whole flow) into the local map. */
148
+ export function mergeAnswer(
149
+ current: Record<string, SetupStepState>,
150
+ key: string,
151
+ answer: SetupStepState | SetupFlowState | void | undefined,
152
+ ): { next: Record<string, SetupStepState>; needsRefetch: boolean } {
153
+ if (!answer) return { next: current, needsRefetch: true }
154
+ if ('steps' in answer) return { next: normalizeState(answer), needsRefetch: false }
155
+ return { next: { ...current, [key]: { ...answer, key: answer.key ?? key } }, needsRefetch: false }
156
+ }
@@ -0,0 +1,131 @@
1
+ import { AlertTriangle, CheckCircle2, HelpCircle, Info, RefreshCw, XCircle } from 'lucide-react'
2
+ import { Button } from '@asteby/metacore-ui/primitives'
3
+ import { cn } from '@asteby/metacore-ui/lib'
4
+ import { useSetupT } from './messages'
5
+ import { TONE_BADGE, TONE_TEXT, metricTone, type Tone } from './tone'
6
+ import type { DiagnosticSeverity, HealthIssue, HealthMetric, HealthStatus, SetupFix } from './types'
7
+
8
+ const STATUS_TONE: Record<HealthStatus, Tone> = { ok: 'good', warn: 'warn', error: 'bad', unknown: 'neutral' }
9
+ const STATUS_ICON = { ok: CheckCircle2, warn: AlertTriangle, error: XCircle, unknown: HelpCircle } as const
10
+ const SEVERITY_ICON: Record<DiagnosticSeverity, typeof Info> = { info: Info, warn: AlertTriangle, error: XCircle }
11
+ const SEVERITY_TONE: Record<DiagnosticSeverity, Tone> = { info: 'info', warn: 'warn', error: 'bad' }
12
+
13
+ export interface HealthCardProps {
14
+ title?: string
15
+ status: HealthStatus
16
+ /** One line under the status. */
17
+ summary?: string
18
+ metrics?: HealthMetric[]
19
+ issues?: HealthIssue[]
20
+ /** ISO date or preformatted text shown as "Checked …". */
21
+ checkedAt?: string
22
+ /** Setup progress, for a card in the installed-addons list. */
23
+ progress?: { done: number; total: number }
24
+ onFix?: (fix: SetupFix, issue: HealthIssue) => void
25
+ onRefresh?: () => void
26
+ refreshing?: boolean
27
+ /** Shows "Continue setup" (resumes the setup page). */
28
+ onContinue?: () => void
29
+ className?: string
30
+ }
31
+
32
+ /** Status + metrics (with tone) + issues (with fix) of an addon's health probe. */
33
+ export function HealthCard({
34
+ title,
35
+ status,
36
+ summary,
37
+ metrics,
38
+ issues,
39
+ checkedAt,
40
+ progress,
41
+ onFix,
42
+ onRefresh,
43
+ refreshing,
44
+ onContinue,
45
+ className,
46
+ }: HealthCardProps) {
47
+ const t = useSetupT()
48
+ const known: HealthStatus = status in STATUS_TONE ? status : 'unknown'
49
+ const Icon = STATUS_ICON[known]
50
+ const pct = progress && progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : null
51
+ return (
52
+ <section className={cn('flex flex-col gap-4 rounded-lg border bg-card p-4 text-card-foreground', className)} aria-label={title ?? t('health.metrics')}>
53
+ <header className='flex flex-wrap items-start justify-between gap-3'>
54
+ <div className='min-w-0'>
55
+ {title ? <h3 className='truncate text-sm font-semibold'>{title}</h3> : null}
56
+ <div className='flex items-center gap-2 pt-1'>
57
+ <span data-health-status={known} className={cn('inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium', TONE_BADGE[STATUS_TONE[known]])}>
58
+ <Icon className='h-3.5 w-3.5' aria-hidden='true' />
59
+ {t(`health.status.${known}`)}
60
+ </span>
61
+ {checkedAt ? <span className='text-xs text-muted-foreground'>{t('health.checked_at', { when: checkedAt })}</span> : null}
62
+ </div>
63
+ {summary ? <p className='pt-2 text-sm text-muted-foreground'>{summary}</p> : null}
64
+ </div>
65
+ <div className='flex items-center gap-2'>
66
+ {onRefresh ? (
67
+ <Button type='button' variant='outline' size='sm' onClick={onRefresh} disabled={refreshing} className='gap-2'>
68
+ <RefreshCw className={cn('h-3.5 w-3.5', refreshing && 'animate-spin motion-reduce:animate-none')} aria-hidden='true' />
69
+ {t('health.refresh')}
70
+ </Button>
71
+ ) : null}
72
+ {onContinue ? (
73
+ <Button type='button' size='sm' onClick={onContinue}>
74
+ {t('health.continue')}
75
+ </Button>
76
+ ) : null}
77
+ </div>
78
+ </header>
79
+
80
+ {pct !== null && progress ? (
81
+ <div className='flex flex-col gap-1'>
82
+ <div role='progressbar' aria-valuemin={0} aria-valuemax={100} aria-valuenow={pct} aria-label={t('flow.progress')} className='h-1.5 w-full overflow-hidden rounded-full bg-muted'>
83
+ <div className='h-full rounded-full bg-primary transition-all motion-reduce:transition-none' style={{ width: `${pct}%` }} />
84
+ </div>
85
+ <span className='text-xs text-muted-foreground'>{t('health.progress', { done: progress.done, total: progress.total })}</span>
86
+ </div>
87
+ ) : null}
88
+
89
+ {metrics && metrics.length > 0 ? (
90
+ <dl className='grid grid-cols-2 gap-3 sm:grid-cols-3'>
91
+ {metrics.map((m) => (
92
+ <div key={m.key} className='min-w-0 rounded-md border px-3 py-2' data-metric-tone={metricTone(m.tone)}>
93
+ <dt className='truncate text-xs text-muted-foreground'>{m.label}</dt>
94
+ <dd className={cn('truncate text-lg font-semibold tabular-nums', TONE_TEXT[metricTone(m.tone)])}>
95
+ {m.value}
96
+ {m.unit ? <span className='pl-1 text-xs font-normal text-muted-foreground'>{m.unit}</span> : null}
97
+ </dd>
98
+ {m.hint ? <p className='truncate text-xs text-muted-foreground'>{m.hint}</p> : null}
99
+ </div>
100
+ ))}
101
+ </dl>
102
+ ) : null}
103
+
104
+ {issues && issues.length > 0 ? (
105
+ <ul className='flex flex-col gap-2' aria-label={t('health.issues')}>
106
+ {issues.map((is, i) => {
107
+ const SevIcon = SEVERITY_ICON[is.severity] ?? Info
108
+ return (
109
+ <li key={is.id ?? i} className='flex flex-wrap items-start justify-between gap-2 rounded-md border px-3 py-2' data-severity={is.severity}>
110
+ <div className='flex min-w-0 flex-1 items-start gap-2'>
111
+ <SevIcon className={cn('mt-0.5 h-4 w-4 shrink-0', TONE_TEXT[SEVERITY_TONE[is.severity] ?? 'info'])} aria-hidden='true' />
112
+ <p className='min-w-0 text-sm'>
113
+ {is.message}
114
+ {is.detail ? <span className='block break-words text-xs text-muted-foreground'>{is.detail}</span> : null}
115
+ </p>
116
+ </div>
117
+ {is.fix && onFix ? (
118
+ <Button type='button' size='sm' variant='outline' className='h-7' onClick={() => onFix(is.fix!, is)}>
119
+ {is.fix.label ?? t('flow.fix')}
120
+ </Button>
121
+ ) : null}
122
+ </li>
123
+ )
124
+ })}
125
+ </ul>
126
+ ) : issues ? (
127
+ <p className='text-sm text-muted-foreground'>{t('health.no_issues')}</p>
128
+ ) : null}
129
+ </section>
130
+ )
131
+ }
@@ -0,0 +1,35 @@
1
+ // Setup flow + health components (kernel `contributions.setup` / `.health`) and
2
+ // the unified addon configuration surface. Import from the package root or from
3
+ // `@asteby/metacore-runtime-react/setup` to pull only this slice.
4
+ export * from './types'
5
+ export * from './flow-model'
6
+ export { useSetupT, SETUP_MESSAGES_ES, SETUP_MESSAGES_EN } from './messages'
7
+ export { StepStatusBadge, type StepStatusBadgeProps } from './step-status-badge'
8
+ export { RecordsTable, copyText, type RecordsTableProps } from './records-table'
9
+ export { HealthCard, type HealthCardProps } from './health-card'
10
+ export { SetupFlow, type SetupFlowProps, type SetupCustomStepProps } from './setup-flow'
11
+ export { SetupFormStep, type SetupFormStepProps } from './setup-form-step'
12
+ export {
13
+ AddonConfigSurface,
14
+ clearConnectorLookupCache,
15
+ type AddonConfigSurfaceProps,
16
+ type AddonConfigAddon,
17
+ type AddonConfigNotifier,
18
+ type AddonSettingDef,
19
+ type ConnectorEntry,
20
+ type ConnectorCredentialField,
21
+ type ConnectorFormLayout,
22
+ } from './addon-config-surface'
23
+ export * from './connector-form-model'
24
+ export * from './connector-blocks-model'
25
+ export {
26
+ ConnectorBlocks,
27
+ WebhookUrlBlock,
28
+ InstructionsBlock,
29
+ ActionBlock,
30
+ BlockResultView,
31
+ HelpText,
32
+ CopyValue,
33
+ type ConnectorBlocksProps,
34
+ type ActionBlockProps,
35
+ } from './connector-blocks'
@@ -0,0 +1,334 @@
1
+ // i18n for the setup / health components. Every string resolves through
2
+ // react-i18next (`setup.*` keys, so a host can override any of them) with the
3
+ // bundled es/en text as the default. No bundle has to be registered.
4
+ import { useCallback } from 'react'
5
+ import { useTranslation } from 'react-i18next'
6
+
7
+ type Dict = Record<string, string>
8
+
9
+ export const SETUP_MESSAGES_ES: Dict = {
10
+ 'status.pending': 'Pendiente',
11
+ 'status.running': 'En curso',
12
+ 'status.ok': 'Listo',
13
+ 'status.warn': 'Con avisos',
14
+ 'status.error': 'Con error',
15
+ 'status.blocked': 'Bloqueado',
16
+ 'status.skipped': 'Omitido',
17
+ 'record.status.ok': 'Correcto',
18
+ 'record.status.missing': 'No encontrado',
19
+ 'record.status.wrong_value': 'Valor distinto',
20
+ 'record.status.propagating': 'Propagando',
21
+ 'record.status.pending': 'Sin verificar',
22
+ 'record.status.error': 'Error',
23
+ 'health.status.ok': 'Todo en orden',
24
+ 'health.status.warn': 'Requiere atención',
25
+ 'health.status.error': 'Con problemas',
26
+ 'health.status.unknown': 'Sin datos',
27
+ 'health.metrics': 'Métricas',
28
+ 'health.issues': 'Avisos',
29
+ 'health.no_issues': 'Sin avisos.',
30
+ 'health.checked_at': 'Revisado {{when}}',
31
+ 'health.refresh': 'Actualizar',
32
+ 'health.continue': 'Continuar configuración',
33
+ 'health.progress': '{{done}} de {{total}} pasos',
34
+ 'records.type': 'Tipo',
35
+ 'records.name': 'Nombre',
36
+ 'records.value': 'Valor',
37
+ 'records.status': 'Estado',
38
+ 'records.copy': 'Copiar',
39
+ 'records.copy_label': 'Copiar {{what}}',
40
+ 'records.copied': 'Copiado',
41
+ 'records.copy_failed': 'No se pudo copiar. Selecciona el texto y cópialo a mano.',
42
+ 'records.empty': 'No hay registros por mostrar.',
43
+ 'records.found': 'Encontrado: {{value}}',
44
+ 'records.recheck': 'Verificar ahora',
45
+ 'flow.steps': 'Pasos de configuración',
46
+ 'flow.progress': 'Progreso de la configuración',
47
+ 'flow.step_of': 'Paso {{n}} de {{total}}',
48
+ 'flow.loading': 'Cargando configuración…',
49
+ 'flow.load_error': 'No se pudo cargar el estado de la configuración.',
50
+ 'flow.retry': 'Reintentar',
51
+ 'flow.complete': 'La configuración está completa.',
52
+ 'flow.optional': 'Opcional',
53
+ 'flow.skip': 'Omitir este paso',
54
+ 'flow.run': 'Ejecutar',
55
+ 'flow.check': 'Verificar',
56
+ 'flow.recheck': 'Volver a verificar',
57
+ 'flow.refresh': 'Revisar ahora',
58
+ 'flow.running': 'En curso…',
59
+ 'flow.waiting_for': 'Antes completa: {{steps}}',
60
+ 'flow.next_check': 'Próxima revisión en {{s}} s',
61
+ 'flow.poll_stopped': 'Dejamos de revisar solo. Pulsa «Revisar ahora» para actualizar.',
62
+ 'flow.step_failed': 'No se pudo ejecutar el paso.',
63
+ 'flow.custom_missing': 'Este paso no tiene una pantalla disponible.',
64
+ 'flow.fix': 'Arreglar',
65
+ 'flow.go_to_step': 'Ir al paso',
66
+ 'flow.open_link': 'Abrir',
67
+ 'flow.status_changed': '{{step}}: {{status}}',
68
+ 'form.continue': 'Guardar y continuar',
69
+ 'form.back': 'Atrás',
70
+ 'form.next': 'Siguiente',
71
+ 'form.saving': 'Guardando…',
72
+ 'form.saved': 'Guardado automáticamente',
73
+ 'form.save_error': 'No se pudo guardar automáticamente.',
74
+ 'form.missing': 'Faltan campos obligatorios: {{fields}}.',
75
+ 'form.field_required': 'Falta completar este campo.',
76
+ 'form.stored': 'Guardado. Escribe un valor nuevo solo si quieres cambiarlo.',
77
+ 'form.choose': 'Elige una opción',
78
+ 'form.step': 'Paso',
79
+ // Connector setup blocks + wizard
80
+ 'blocks.more': 'Ver más',
81
+ 'blocks.less': 'Ver menos',
82
+ 'blocks.copy_label': 'Copiar {{what}}',
83
+ 'blocks.value': 'Valor',
84
+ 'blocks.webhook_title': 'URL del webhook',
85
+ 'blocks.webhook_help': 'Pega esta URL en el panel del proveedor, en la sección de webhooks o notificaciones.',
86
+ 'blocks.webhook_unavailable': 'El servidor todavía no informa la URL de este webhook. Actualiza OPS o pide ayuda a soporte.',
87
+ 'blocks.run': 'Ejecutar prueba',
88
+ 'blocks.running': 'Probando…',
89
+ 'blocks.retry_with': 'Reintentar: {{label}}',
90
+ 'blocks.open_link': 'Abrir enlace',
91
+ 'blocks.save_first': 'Se guardarán tus cambios antes de probar.',
92
+ 'blocks.failed': 'No se pudo completar la prueba.',
93
+ 'blocks.result.ok': 'Correcto',
94
+ 'blocks.result.warn': 'Con avisos',
95
+ 'blocks.result.error': 'Falló',
96
+ 'blocks.result.pending': 'Pendiente',
97
+ 'blocks.result.running': 'En curso',
98
+ 'blocks.result.blocked': 'Bloqueado',
99
+ 'blocks.test_title': 'Verifica la conexión',
100
+ 'blocks.test_help': 'Usa las credenciales guardadas para hacer una llamada de solo lectura al proveedor.',
101
+ 'blocks.sync_title': 'Sincronización',
102
+ 'wizard.steps': 'Pasos de la configuración',
103
+ 'wizard.step_label': 'Paso {{n}} de {{total}}: {{title}} ({{status}})',
104
+ 'wizard.save': 'Guardar',
105
+ 'wizard.finish': 'Guardar y terminar',
106
+ 'oauth.title': 'Cuenta conectada',
107
+ 'oauth.connected': 'Conectado',
108
+ 'oauth.not_connected': 'Sin conectar',
109
+ 'oauth.help': 'Este addon se conecta con tu cuenta del proveedor. Te llevamos a su página para autorizarlo.',
110
+ 'oauth.connect': 'Conectar cuenta',
111
+ 'oauth.reconnect': 'Volver a conectar',
112
+ 'empty.title': 'Nada que configurar',
113
+ 'empty.help': 'Este addon funciona sin configuración. Si necesitas cambiar algo, revisa su documentación o abre el addon.',
114
+ // AddonConfigSurface (same keys the ops host already ships)
115
+ 'installed_addons.configure_title': 'Configurar {{name}}',
116
+ 'installed_addons.configure_description': 'Credenciales y ajustes del addon.',
117
+ 'installed_addons.section_credentials': 'Credenciales',
118
+ 'installed_addons.section_settings': 'Ajustes',
119
+ 'installed_addons.advanced': 'Avanzado',
120
+ 'installed_addons.no_settings': 'Este addon no tiene nada que configurar.',
121
+ 'installed_addons.config_saved': 'Configuración guardada',
122
+ 'installed_addons.settings_error': 'No se pudo guardar la configuración',
123
+ 'installed_addons.test_connection': 'Probar conexión',
124
+ 'installed_addons.test_ok': 'Conexión válida',
125
+ 'installed_addons.test_failed': 'No se pudo conectar',
126
+ 'installed_addons.sync_now': 'Sincronizar ahora',
127
+ 'installed_addons.sync_skipped': 'Sincronización omitida',
128
+ 'installed_addons.sync_done': 'Sincronizado: {{licenses}} licencias, {{instances}} instancias, {{accounts}} cuentas',
129
+ 'installed_addons.sync_failed': 'No se pudo sincronizar',
130
+ 'installed_addons.issuer_admin_only':
131
+ 'Solo un administrador de la organización puede ver y guardar los datos del emisor y el certificado. Pide a un administrador que los configure.',
132
+ 'installed_addons.field_required': 'Falta completar este campo.',
133
+ 'installed_addons.missing_fields': 'Faltan campos obligatorios: {{fields}}.',
134
+ 'installed_addons.shape_public_key': 'Este valor tiene forma de {{target}}. Pégalo en ese campo.',
135
+ 'installed_addons.shape_secret_key': 'Este valor tiene forma de una clave secreta. Pégalo en {{target}}.',
136
+ 'installed_addons.dynamic_select_error':
137
+ 'No se pudieron listar las opciones. Guarda la conexión y vuelve a intentar.',
138
+ 'installed_addons.dynamic_select_choose': 'Elige una opción',
139
+ 'installed_addons.dynamic_select_placeholder': 'Guarda la conexión y actualiza para elegir',
140
+ 'installed_addons.dynamic_select_refresh': 'Actualizar opciones',
141
+ 'installed_addons.per_branch': 'Por sucursal',
142
+ 'installed_addons.inherit_pending': 'Heredará de la organización al guardar',
143
+ 'installed_addons.branch_own': 'Valor propio de esta sucursal',
144
+ 'installed_addons.branch_inherited': 'Hereda de la organización',
145
+ 'installed_addons.inherit': 'Heredar de la organización',
146
+ 'installed_addons.applies_to': 'Los ajustes aplican a:',
147
+ 'installed_addons.whole_org': 'Toda la organización',
148
+ 'installed_addons.only_branch': 'Solo {{name}}',
149
+ 'installed_addons.secret_stored': 'Hay un valor guardado. Déjalo vacío para conservarlo.',
150
+ 'common.back': 'Atrás',
151
+ 'common.next': 'Siguiente',
152
+ 'common.cancel': 'Cancelar',
153
+ 'common.save': 'Guardar',
154
+ 'common.close': 'Cerrar',
155
+ }
156
+
157
+ export const SETUP_MESSAGES_EN: Dict = {
158
+ 'status.pending': 'Pending',
159
+ 'status.running': 'In progress',
160
+ 'status.ok': 'Done',
161
+ 'status.warn': 'Has warnings',
162
+ 'status.error': 'Has errors',
163
+ 'status.blocked': 'Blocked',
164
+ 'status.skipped': 'Skipped',
165
+ 'record.status.ok': 'Correct',
166
+ 'record.status.missing': 'Not found',
167
+ 'record.status.wrong_value': 'Different value',
168
+ 'record.status.propagating': 'Propagating',
169
+ 'record.status.pending': 'Not checked',
170
+ 'record.status.error': 'Error',
171
+ 'health.status.ok': 'All good',
172
+ 'health.status.warn': 'Needs attention',
173
+ 'health.status.error': 'Has problems',
174
+ 'health.status.unknown': 'No data',
175
+ 'health.metrics': 'Metrics',
176
+ 'health.issues': 'Issues',
177
+ 'health.no_issues': 'No issues.',
178
+ 'health.checked_at': 'Checked {{when}}',
179
+ 'health.refresh': 'Refresh',
180
+ 'health.continue': 'Continue setup',
181
+ 'health.progress': '{{done}} of {{total}} steps',
182
+ 'records.type': 'Type',
183
+ 'records.name': 'Name',
184
+ 'records.value': 'Value',
185
+ 'records.status': 'Status',
186
+ 'records.copy': 'Copy',
187
+ 'records.copy_label': 'Copy {{what}}',
188
+ 'records.copied': 'Copied',
189
+ 'records.copy_failed': 'Could not copy. Select the text and copy it by hand.',
190
+ 'records.empty': 'No records to show.',
191
+ 'records.found': 'Found: {{value}}',
192
+ 'records.recheck': 'Check now',
193
+ 'flow.steps': 'Setup steps',
194
+ 'flow.progress': 'Setup progress',
195
+ 'flow.step_of': 'Step {{n}} of {{total}}',
196
+ 'flow.loading': 'Loading setup…',
197
+ 'flow.load_error': 'Could not load the setup state.',
198
+ 'flow.retry': 'Try again',
199
+ 'flow.complete': 'Setup is complete.',
200
+ 'flow.optional': 'Optional',
201
+ 'flow.skip': 'Skip this step',
202
+ 'flow.run': 'Run',
203
+ 'flow.check': 'Check',
204
+ 'flow.recheck': 'Check again',
205
+ 'flow.refresh': 'Check now',
206
+ 'flow.running': 'In progress…',
207
+ 'flow.waiting_for': 'Finish first: {{steps}}',
208
+ 'flow.next_check': 'Next check in {{s}} s',
209
+ 'flow.poll_stopped': 'We stopped checking automatically. Press "Check now" to refresh.',
210
+ 'flow.step_failed': 'The step could not be run.',
211
+ 'flow.custom_missing': 'This step has no screen available.',
212
+ 'flow.fix': 'Fix',
213
+ 'flow.go_to_step': 'Go to step',
214
+ 'flow.open_link': 'Open',
215
+ 'flow.status_changed': '{{step}}: {{status}}',
216
+ 'form.continue': 'Save and continue',
217
+ 'form.back': 'Back',
218
+ 'form.next': 'Next',
219
+ 'form.saving': 'Saving…',
220
+ 'form.saved': 'Saved automatically',
221
+ 'form.save_error': 'Could not save automatically.',
222
+ 'form.missing': 'Required fields are missing: {{fields}}.',
223
+ 'form.field_required': 'This field is required.',
224
+ 'form.stored': 'Saved. Type a new value only if you want to change it.',
225
+ 'form.choose': 'Choose an option',
226
+ 'form.step': 'Step',
227
+ 'blocks.more': 'Show more',
228
+ 'blocks.less': 'Show less',
229
+ 'blocks.copy_label': 'Copy {{what}}',
230
+ 'blocks.value': 'Value',
231
+ 'blocks.webhook_title': 'Webhook URL',
232
+ 'blocks.webhook_help': "Paste this URL in the provider's panel, in its webhooks or notifications section.",
233
+ 'blocks.webhook_unavailable': 'The server does not report this webhook URL yet. Update OPS or ask support.',
234
+ 'blocks.run': 'Run test',
235
+ 'blocks.running': 'Testing…',
236
+ 'blocks.retry_with': 'Retry: {{label}}',
237
+ 'blocks.open_link': 'Open link',
238
+ 'blocks.save_first': 'Your changes will be saved before testing.',
239
+ 'blocks.failed': 'The test could not be completed.',
240
+ 'blocks.result.ok': 'Passed',
241
+ 'blocks.result.warn': 'Has warnings',
242
+ 'blocks.result.error': 'Failed',
243
+ 'blocks.result.pending': 'Pending',
244
+ 'blocks.result.running': 'In progress',
245
+ 'blocks.result.blocked': 'Blocked',
246
+ 'blocks.test_title': 'Check the connection',
247
+ 'blocks.test_help': 'Uses the saved credentials to make a read-only call to the provider.',
248
+ 'blocks.sync_title': 'Sync',
249
+ 'wizard.steps': 'Setup steps',
250
+ 'wizard.step_label': 'Step {{n}} of {{total}}: {{title}} ({{status}})',
251
+ 'wizard.save': 'Save',
252
+ 'wizard.finish': 'Save and finish',
253
+ 'oauth.title': 'Connected account',
254
+ 'oauth.connected': 'Connected',
255
+ 'oauth.not_connected': 'Not connected',
256
+ 'oauth.help': "This addon connects to your provider account. We'll take you to its page to authorize it.",
257
+ 'oauth.connect': 'Connect account',
258
+ 'oauth.reconnect': 'Reconnect',
259
+ 'empty.title': 'Nothing to configure',
260
+ 'empty.help': 'This addon works without configuration. If you need to change something, check its documentation or open the addon.',
261
+ 'installed_addons.configure_title': 'Configure {{name}}',
262
+ 'installed_addons.configure_description': 'Credentials and settings for this addon.',
263
+ 'installed_addons.section_credentials': 'Credentials',
264
+ 'installed_addons.section_settings': 'Settings',
265
+ 'installed_addons.advanced': 'Advanced',
266
+ 'installed_addons.no_settings': 'This addon has nothing to configure.',
267
+ 'installed_addons.config_saved': 'Configuration saved',
268
+ 'installed_addons.settings_error': 'Could not save the configuration',
269
+ 'installed_addons.test_connection': 'Test connection',
270
+ 'installed_addons.test_ok': 'Connection is valid',
271
+ 'installed_addons.test_failed': 'Could not connect',
272
+ 'installed_addons.sync_now': 'Sync now',
273
+ 'installed_addons.sync_skipped': 'Sync skipped',
274
+ 'installed_addons.sync_done': 'Synced: {{licenses}} licenses, {{instances}} instances, {{accounts}} accounts',
275
+ 'installed_addons.sync_failed': 'Could not sync',
276
+ 'installed_addons.issuer_admin_only':
277
+ 'Only an organization administrator can view and save the issuer and certificate data. Ask an administrator to set them up.',
278
+ 'installed_addons.field_required': 'This field is required.',
279
+ 'installed_addons.missing_fields': 'Required fields are missing: {{fields}}.',
280
+ 'installed_addons.shape_public_key': 'This value looks like {{target}}. Paste it in that field.',
281
+ 'installed_addons.shape_secret_key': 'This value looks like a secret key. Paste it in {{target}}.',
282
+ 'installed_addons.dynamic_select_error': 'Could not list the options. Save the connection and try again.',
283
+ 'installed_addons.dynamic_select_choose': 'Choose an option',
284
+ 'installed_addons.dynamic_select_placeholder': 'Save the connection and refresh to choose',
285
+ 'installed_addons.dynamic_select_refresh': 'Refresh options',
286
+ 'installed_addons.per_branch': 'Per branch',
287
+ 'installed_addons.inherit_pending': 'Will inherit from the organization on save',
288
+ 'installed_addons.branch_own': "This branch's own value",
289
+ 'installed_addons.branch_inherited': 'Inherits from the organization',
290
+ 'installed_addons.inherit': 'Inherit from the organization',
291
+ 'installed_addons.applies_to': 'Settings apply to:',
292
+ 'installed_addons.whole_org': 'Whole organization',
293
+ 'installed_addons.only_branch': 'Only {{name}}',
294
+ 'installed_addons.secret_stored': 'A value is stored. Leave it empty to keep it.',
295
+ 'common.back': 'Back',
296
+ 'common.next': 'Next',
297
+ 'common.cancel': 'Cancel',
298
+ 'common.save': 'Save',
299
+ 'common.close': 'Close',
300
+ }
301
+
302
+ export type TFn = (key: string, vars?: Record<string, unknown>) => string
303
+
304
+ function interpolate(s: string, vars?: Record<string, unknown>): string {
305
+ if (!vars) return s
306
+ return s.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => (vars[k] == null ? '' : String(vars[k])))
307
+ }
308
+
309
+ /** Resolves the bundled text for `lang` (es default; any `en*` → English). */
310
+ export function defaultMessage(key: string, lang?: string): string {
311
+ const dict = lang && lang.toLowerCase().startsWith('en') ? SETUP_MESSAGES_EN : SETUP_MESSAGES_ES
312
+ return dict[key] ?? SETUP_MESSAGES_ES[key] ?? key
313
+ }
314
+
315
+ /**
316
+ * Translator for the setup components. Keys that start with `setup.` (or are
317
+ * the shared `installed_addons.*` / `common.*` ones) go through i18next first,
318
+ * so a host can override; the bundled es/en text is the default value.
319
+ * Interpolation is done here too, so it works even without an i18next instance.
320
+ */
321
+ export function useSetupT(): TFn {
322
+ const { t, i18n } = useTranslation()
323
+ const lang = i18n?.language
324
+ return useCallback(
325
+ (key, vars) => {
326
+ const hostKey = key.includes('.') && /^(installed_addons|common)\./.test(key) ? key : `setup.${key}`
327
+ const fallback = defaultMessage(key, lang)
328
+ const out = t(hostKey, { ...(vars ?? {}), defaultValue: fallback }) as string
329
+ // Mocked / minimal `t` implementations may ignore interpolation.
330
+ return interpolate(typeof out === 'string' ? out : fallback, vars)
331
+ },
332
+ [t, lang],
333
+ )
334
+ }