@asteby/metacore-runtime-react 53.20.1 → 53.21.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 (85) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/attention/apply-nav-badges.d.ts +10 -0
  3. package/dist/attention/apply-nav-badges.d.ts.map +1 -0
  4. package/dist/attention/apply-nav-badges.js +35 -0
  5. package/dist/attention/index.d.ts +4 -0
  6. package/dist/attention/index.d.ts.map +1 -0
  7. package/dist/attention/index.js +3 -0
  8. package/dist/attention/use-document-attention.d.ts +10 -0
  9. package/dist/attention/use-document-attention.d.ts.map +1 -0
  10. package/dist/attention/use-document-attention.js +66 -0
  11. package/dist/attention/use-nav-badges.d.ts +42 -0
  12. package/dist/attention/use-nav-badges.d.ts.map +1 -0
  13. package/dist/attention/use-nav-badges.js +54 -0
  14. package/dist/genui/index.d.ts +2 -0
  15. package/dist/genui/index.d.ts.map +1 -0
  16. package/dist/genui/index.js +1 -0
  17. package/dist/genui/settings-block.d.ts +31 -0
  18. package/dist/genui/settings-block.d.ts.map +1 -0
  19. package/dist/genui/settings-block.js +100 -0
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2 -0
  23. package/dist/setup/addon-config-surface.d.ts +14 -1
  24. package/dist/setup/addon-config-surface.d.ts.map +1 -1
  25. package/dist/setup/addon-config-surface.js +109 -6
  26. package/dist/setup/messages.d.ts.map +1 -1
  27. package/dist/setup/messages.js +50 -0
  28. package/dist/setup/secret-field-model.d.ts +47 -0
  29. package/dist/setup/secret-field-model.d.ts.map +1 -0
  30. package/dist/setup/secret-field-model.js +95 -0
  31. package/dist/view-system/card-spec.d.ts +24 -0
  32. package/dist/view-system/card-spec.d.ts.map +1 -0
  33. package/dist/view-system/card-spec.js +40 -0
  34. package/dist/view-system/cards-view.d.ts +17 -0
  35. package/dist/view-system/cards-view.d.ts.map +1 -0
  36. package/dist/view-system/cards-view.js +37 -0
  37. package/dist/view-system/index.d.ts +10 -0
  38. package/dist/view-system/index.d.ts.map +1 -0
  39. package/dist/view-system/index.js +9 -0
  40. package/dist/view-system/model-view.d.ts +31 -0
  41. package/dist/view-system/model-view.d.ts.map +1 -0
  42. package/dist/view-system/model-view.js +50 -0
  43. package/dist/view-system/saved-views.d.ts +22 -0
  44. package/dist/view-system/saved-views.d.ts.map +1 -0
  45. package/dist/view-system/saved-views.js +53 -0
  46. package/dist/view-system/types.d.ts +63 -0
  47. package/dist/view-system/types.d.ts.map +1 -0
  48. package/dist/view-system/types.js +1 -0
  49. package/dist/view-system/use-view-mode.d.ts +26 -0
  50. package/dist/view-system/use-view-mode.d.ts.map +1 -0
  51. package/dist/view-system/use-view-mode.js +60 -0
  52. package/dist/view-system/view-state.d.ts +19 -0
  53. package/dist/view-system/view-state.d.ts.map +1 -0
  54. package/dist/view-system/view-state.js +66 -0
  55. package/dist/view-system/view-switcher.d.ts +14 -0
  56. package/dist/view-system/view-switcher.d.ts.map +1 -0
  57. package/dist/view-system/view-switcher.js +26 -0
  58. package/dist/view-system/view-toolbar.d.ts +19 -0
  59. package/dist/view-system/view-toolbar.d.ts.map +1 -0
  60. package/dist/view-system/view-toolbar.js +33 -0
  61. package/package.json +14 -5
  62. package/src/__tests__/addon-config-surface.test.tsx +67 -1
  63. package/src/__tests__/attention-view-system.test.tsx +128 -0
  64. package/src/__tests__/genui-settings-block.test.tsx +73 -0
  65. package/src/attention/apply-nav-badges.ts +42 -0
  66. package/src/attention/index.ts +11 -0
  67. package/src/attention/use-document-attention.ts +62 -0
  68. package/src/attention/use-nav-badges.ts +94 -0
  69. package/src/genui/index.ts +1 -0
  70. package/src/genui/settings-block.tsx +123 -0
  71. package/src/index.ts +2 -0
  72. package/src/setup/addon-config-surface.tsx +297 -16
  73. package/src/setup/messages.ts +50 -0
  74. package/src/setup/secret-field-model.test.ts +67 -0
  75. package/src/setup/secret-field-model.ts +104 -0
  76. package/src/view-system/card-spec.tsx +78 -0
  77. package/src/view-system/cards-view.tsx +61 -0
  78. package/src/view-system/index.ts +9 -0
  79. package/src/view-system/model-view.tsx +105 -0
  80. package/src/view-system/saved-views.ts +66 -0
  81. package/src/view-system/types.ts +63 -0
  82. package/src/view-system/use-view-mode.ts +79 -0
  83. package/src/view-system/view-state.ts +61 -0
  84. package/src/view-system/view-switcher.tsx +53 -0
  85. package/src/view-system/view-toolbar.tsx +119 -0
@@ -17,7 +17,7 @@ import { createContext, useContext, useEffect, useId, useRef, useState } from 'r
17
17
  import { useMutation } from '@tanstack/react-query';
18
18
  import { useTranslation } from 'react-i18next';
19
19
  import { toast } from 'sonner';
20
- import { AlertCircle, Cable, Check, Eye, EyeOff, Link2, Loader2, Pencil, RefreshCw, Settings, X } from 'lucide-react';
20
+ import { AlertCircle, Cable, Check, Copy, Eye, EyeOff, Link2, Loader2, Pencil, RefreshCw, Settings, Sparkles, X } from 'lucide-react';
21
21
  import { Badge, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Input, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch, } from '@asteby/metacore-ui/primitives';
22
22
  import { cn } from '@asteby/metacore-ui/lib';
23
23
  import { useApi } from '../api-context';
@@ -25,6 +25,8 @@ import { evaluateVisibleWhen, getVisibleWhen } from '../dynamic-form-schema';
25
25
  import { useSetupT } from './messages';
26
26
  import { StepStatusBadge } from './step-status-badge';
27
27
  import { ConnectorBlocks, CopyValue, HelpText } from './connector-blocks';
28
+ import { copyText } from './records-table';
29
+ import { generateSecret, generatedLength, secretMinLength, secretStrength, splitHelp, tooShortSecrets, } from './secret-field-model';
28
30
  import { buildWizardSteps, errorMessage, hasExplicitTest, normalizeBlockResult, stepStatus, } from './connector-blocks-model';
29
31
  import { isSecretCredential, missingRequired, applicableFields, visibleSections, parseSaveError, shapeMismatch, textOrFallback, } from './connector-form-model';
30
32
  // Empty write_only value (typed then erased) must not overwrite the stored secret.
@@ -50,10 +52,18 @@ const ConnectorFormStateContext = createContext({
50
52
  idPrefix: 'addon-config',
51
53
  expectedOptionKinds: {},
52
54
  });
55
+ // Field help: a short lead sentence, with the technical remainder (endpoints,
56
+ // header names…) behind a collapsible «Cómo se usa» so the form stays calm.
57
+ function FieldHelp({ text }) {
58
+ const st = useSetupT();
59
+ const { lead, detail } = splitHelp(text);
60
+ return (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsx(HelpText, { text: lead }), detail ? (_jsxs("details", { className: 'group text-xs text-muted-foreground', children: [_jsx("summary", { className: 'flex min-h-11 w-fit cursor-pointer items-center gap-1 font-medium text-primary select-none focus-visible:outline-2 focus-visible:outline-ring sm:min-h-6', children: st('secret.how_to_use') }), _jsx("p", { className: 'pb-1 leading-relaxed break-words whitespace-pre-line', children: detail })] })) : null] }));
61
+ }
53
62
  function ConnectorCredentialFieldControl({ field, value, connected, provider, onChange, stored = false, onReveal, resetKey, }) {
54
63
  const { t } = useTranslation();
55
64
  const st = useSetupT();
56
65
  const form = useContext(ConnectorFormStateContext);
66
+ const canManage = form.canManage !== false;
57
67
  // label/description are i18n keys (addon locales are loaded into i18next);
58
68
  // never surface a raw dotted key: fall back to the humanized field key.
59
69
  const humanize = (k) => k.replace(/[_-]+/g, ' ').replace(/\b\w/g, (m) => m.toUpperCase());
@@ -71,12 +81,20 @@ function ConnectorCredentialFieldControl({ field, value, connected, provider, on
71
81
  const [revealed, setRevealed] = useState(null);
72
82
  const [revealing, setRevealing] = useState(false);
73
83
  const [armed, setArmed] = useState(false);
84
+ const [confirmRotate, setConfirmRotate] = useState(false);
85
+ const [generated, setGenerated] = useState(false);
86
+ const [genError, setGenError] = useState(false);
87
+ const [copyState, setCopyState] = useState('idle');
88
+ const copyTimer = useRef(undefined);
89
+ useEffect(() => () => clearTimeout(copyTimer.current), []);
74
90
  const initial = useRef('');
75
91
  const locked = stored && !editing;
76
92
  useEffect(() => {
77
93
  setEditing(false);
78
94
  setVisible(false);
79
95
  setRevealed(null);
96
+ setConfirmRotate(false);
97
+ setGenerated(false);
80
98
  }, [resetKey]);
81
99
  const canEye = isSecret ? (locked ? !!onReveal : true) : false;
82
100
  const toggleEye = async () => {
@@ -115,8 +133,40 @@ function ConnectorCredentialFieldControl({ field, value, connected, provider, on
115
133
  onChange(initial.current);
116
134
  setVisible(false);
117
135
  setEditing(false);
136
+ setGenerated(false);
118
137
  };
119
- const error = form.errors[field.key];
138
+ // Generate: a CSPRNG value at least as long as the manifest's minimum, shown
139
+ // so it can be copied before saving. Rotating a STORED secret goes through
140
+ // an explicit confirmation first (confirmRotate).
141
+ const minLen = isSecret ? secretMinLength(field) : 0;
142
+ const generate = () => {
143
+ try {
144
+ const next = generateSecret(generatedLength(field));
145
+ if (stored && !editing) {
146
+ initial.current = value;
147
+ setEditing(true);
148
+ }
149
+ setArmed(true);
150
+ setVisible(true);
151
+ setRevealed(null);
152
+ setGenerated(true);
153
+ setGenError(false);
154
+ setConfirmRotate(false);
155
+ onChange(next);
156
+ }
157
+ catch {
158
+ setGenError(true);
159
+ }
160
+ };
161
+ const copyValue = async () => {
162
+ const ok = await copyText(value);
163
+ setCopyState(ok ? 'copied' : 'failed');
164
+ clearTimeout(copyTimer.current);
165
+ copyTimer.current = setTimeout(() => setCopyState('idle'), 2500);
166
+ };
167
+ const strength = isSecret ? secretStrength(value, minLen) : 'empty';
168
+ const shortBy = isSecret && minLen > 0 && value !== '' && value.length < minLen;
169
+ const error = form.errors[field.key] ?? (shortBy ? st('secret.too_short', { min: minLen, n: value.length }) : undefined);
120
170
  const mismatch = shapeMismatch(field, value, form.fields);
121
171
  const target = mismatch?.suggestedKey
122
172
  ? form.fields.find((f) => f.key === mismatch.suggestedKey)
@@ -130,7 +180,16 @@ function ConnectorCredentialFieldControl({ field, value, connected, provider, on
130
180
  // Browsers ignore autocomplete=off and fill the text field that
131
181
  // precedes a password input; a field stays read-only until the user
132
182
  // focuses it (and while locked) so nothing is filled behind their back.
133
- autoComplete: isSecret ? 'new-password' : 'off', "data-1p-ignore": true, "data-lpignore": 'true', "data-form-type": 'other', readOnly: locked || !armed, onFocus: () => setArmed(true), spellCheck: false, autoCapitalize: 'off', "aria-invalid": !!error || undefined, "aria-describedby": error ? `${form.idPrefix}-cred-${field.key}-error` : undefined, className: cn(error && 'border-destructive focus-visible:ring-destructive/40', locked && 'bg-muted/40 text-muted-foreground'), placeholder: (connected || stored) && isSecret ? '••••••••' : '', value: locked && isSecret ? (revealed ?? '') : value, onChange: (e) => onChange(e.target.value) }), canEye && (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', disabled: revealing, "aria-label": visible ? st('installed_addons.field_hide', { defaultValue: 'Ocultar' }) : st('installed_addons.field_view', { defaultValue: 'Ver' }), onClick: () => void toggleEye(), children: revealing ? _jsx(Loader2, { className: 'size-4 animate-spin' }) : visible ? _jsx(EyeOff, { className: 'size-4' }) : _jsx(Eye, { className: 'size-4' }) })), locked ? (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', "aria-label": st('installed_addons.field_edit', { defaultValue: 'Editar' }), onClick: startEdit, children: _jsx(Pencil, { className: 'size-4' }) })) : stored ? (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', "aria-label": st('installed_addons.field_cancel_edit', { defaultValue: 'Cancelar edición' }), onClick: cancelEdit, children: _jsx(X, { className: 'size-4' }) })) : null] })), error ? (_jsx("p", { id: `${form.idPrefix}-cred-${field.key}-error`, role: 'alert', className: 'text-xs text-destructive', children: error })) : null, warning ? (_jsx("p", { className: 'text-xs text-amber-600 dark:text-amber-400', role: 'status', children: warning })) : null, help ? _jsx(HelpText, { text: help }) : null] }));
183
+ autoComplete: isSecret ? 'new-password' : 'off', "data-1p-ignore": true, "data-lpignore": 'true', "data-form-type": 'other', readOnly: locked || !armed, onFocus: () => setArmed(true), spellCheck: false, autoCapitalize: 'off', "aria-invalid": !!error || undefined, "aria-describedby": error ? `${form.idPrefix}-cred-${field.key}-error` : undefined, className: cn(error && 'border-destructive focus-visible:ring-destructive/40', locked && 'bg-muted/40 text-muted-foreground'), placeholder: (connected || stored) && isSecret ? '••••••••' : '', value: locked && isSecret ? (revealed ?? '') : value, onChange: (e) => {
184
+ setGenerated(false);
185
+ onChange(e.target.value);
186
+ } }), canEye && (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', disabled: revealing, "aria-label": visible ? st('installed_addons.field_hide', { defaultValue: 'Ocultar' }) : st('installed_addons.field_view', { defaultValue: 'Ver' }), onClick: () => void toggleEye(), children: revealing ? _jsx(Loader2, { className: 'size-4 animate-spin' }) : visible ? _jsx(EyeOff, { className: 'size-4' }) : _jsx(Eye, { className: 'size-4' }) })), locked ? (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', "aria-label": st('installed_addons.field_edit', { defaultValue: 'Editar' }), onClick: startEdit, children: _jsx(Pencil, { className: 'size-4' }) })) : stored ? (_jsx(Button, { type: 'button', variant: 'ghost', size: 'icon', className: 'size-9 shrink-0', "aria-label": st('installed_addons.field_cancel_edit', { defaultValue: 'Cancelar edición' }), onClick: cancelEdit, children: _jsx(X, { className: 'size-4' }) })) : null] })), isSecret && !isDynamic && field.type !== 'select' ? (_jsxs("div", { className: 'flex flex-col gap-2', children: [_jsxs("div", { className: 'flex flex-wrap items-center gap-2', children: [locked ? (canManage ? (_jsxs(Button, { type: 'button', variant: 'outline', size: 'sm', className: 'h-11 gap-1.5 sm:h-8', "aria-expanded": confirmRotate, onClick: () => setConfirmRotate(true), children: [_jsx(RefreshCw, { "aria-hidden": 'true', className: 'size-3.5' }), st('secret.rotate')] })) : null) : (_jsxs(_Fragment, { children: [canManage ? (_jsxs(Button, { type: 'button', variant: 'outline', size: 'sm', className: 'h-11 gap-1.5 sm:h-8', onClick: generate, children: [_jsx(Sparkles, { "aria-hidden": 'true', className: 'size-3.5' }), generated ? st('secret.regenerate') : st('secret.generate')] })) : null, value !== '' ? (_jsxs(Button, { type: 'button', variant: 'outline', size: 'sm', className: 'h-11 gap-1.5 sm:h-8', "aria-label": st('blocks.copy_label', { what: st('secret.copy_what') }), onClick: () => void copyValue(), children: [copyState === 'copied' ? (_jsx(Check, { "aria-hidden": 'true', className: 'size-3.5' })) : (_jsx(Copy, { "aria-hidden": 'true', className: 'size-3.5' })), copyState === 'copied' ? st('records.copied') : st('secret.copy')] })) : null] })), _jsx("span", { className: 'sr-only', role: 'status', "aria-live": 'polite', children: copyState === 'copied' ? st('records.copied') : copyState === 'failed' ? st('records.copy_failed') : '' })] }), confirmRotate ? (_jsxs("div", { role: 'group', "aria-labelledby": `${form.idPrefix}-rot-${field.key}`, className: 'flex flex-col gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3', children: [_jsx("p", { id: `${form.idPrefix}-rot-${field.key}`, className: 'text-sm font-medium', children: st('secret.rotate_title') }), _jsx("p", { className: 'text-xs text-muted-foreground', children: st('secret.rotate_body') }), _jsxs("div", { className: 'flex flex-wrap gap-2', children: [_jsx(Button, { type: 'button', size: 'sm', className: 'h-11 sm:h-8', onClick: generate, children: st('secret.rotate_confirm') }), _jsx(Button, { type: 'button', size: 'sm', variant: 'ghost', className: 'h-11 sm:h-8', autoFocus: true, onClick: () => setConfirmRotate(false), children: st('secret.rotate_cancel') })] })] })) : null, value !== '' && !locked ? (_jsxs("div", { className: 'flex items-center gap-2', "data-strength": strength, children: [_jsx("span", { "aria-hidden": 'true', className: 'flex flex-1 gap-1', children: [0, 1, 2].map((i) => (_jsx("span", { className: cn('h-1.5 flex-1 rounded-full transition-colors', i <= (strength === 'strong' ? 2 : strength === 'fair' ? 1 : 0)
187
+ ? strength === 'strong'
188
+ ? 'bg-emerald-500'
189
+ : strength === 'fair'
190
+ ? 'bg-amber-500'
191
+ : 'bg-destructive'
192
+ : 'bg-muted') }, i))) }), _jsxs("span", { className: 'shrink-0 text-xs text-muted-foreground', children: [st('secret.strength'), ": ", st(`secret.strength_${strength === 'empty' ? 'weak' : strength}`)] })] })) : null, generated && value !== '' ? (_jsx("p", { role: 'status', className: 'text-xs text-emerald-700 dark:text-emerald-400', children: st('secret.generated_hint') })) : null, genError ? (_jsx("p", { role: 'alert', className: 'text-xs text-destructive', children: st('secret.generate_unavailable') })) : null] })) : null, error ? (_jsx("p", { id: `${form.idPrefix}-cred-${field.key}-error`, role: form.errors[field.key] ? 'alert' : undefined, className: 'text-xs text-destructive', children: error })) : null, warning ? (_jsx("p", { className: 'text-xs text-amber-600 dark:text-amber-400', role: 'status', children: warning })) : null, help ? _jsx(FieldHelp, { text: help }) : null] }));
134
193
  }
135
194
  // useApi() hands every component its own wrapper object, so the cache cannot be
136
195
  // keyed by client: it is module-level, keyed by provider + export, and dropped
@@ -224,7 +283,7 @@ function DynamicConnectorSelect({ field, value, provider, connected, onChange, }
224
283
  // Fixed header + footer, scrollable body — a connector can declare many fields
225
284
  // (env, keys, RFC, régimen, CP, base_url, stamp/cancel path) that would
226
285
  // otherwise overflow the viewport.
227
- export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer = true, canRevealSecrets = false, activeBranch = null, ensureAddonBundle, notify = toast, client, expectedOptionKinds = NO_OPTION_KINDS, displayName, onConnectOAuth, }) {
286
+ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSaved, canManageIssuer = true, canRevealSecrets = false, activeBranch = null, ensureAddonBundle, notify = toast, client, expectedOptionKinds = NO_OPTION_KINDS, displayName, logo, onConnectOAuth, version, }) {
228
287
  const idPrefix = useId();
229
288
  const { t, i18n } = useTranslation();
230
289
  const st = useSetupT();
@@ -643,6 +702,19 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
643
702
  return;
644
703
  }
645
704
  }
705
+ const short = connector && canManageIssuer ? tooShortSecrets(activeFields, credValues) : [];
706
+ if (short.length > 0) {
707
+ const errs = {};
708
+ for (const x of short) {
709
+ errs[x.key] = st('secret.too_short', { min: x.min, n: (credValues[x.key] ?? '').length });
710
+ }
711
+ setFieldErrors(errs);
712
+ setFormError(st('secret.fix_fields', {
713
+ fields: short.map((x) => credLabel(credFields.find((f) => f.key === x.key))).join(', '),
714
+ }));
715
+ focusFirstInvalid(short.map((x) => x.key));
716
+ return;
717
+ }
646
718
  setFieldErrors({});
647
719
  saveMutation.mutate();
648
720
  };
@@ -662,6 +734,14 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
662
734
  fields: miss.map((k) => credLabel(credFields.find((f) => f.key === k))).join(', '),
663
735
  });
664
736
  }
737
+ const short = tooShortSecrets(activeFields, credValues);
738
+ if (short.length > 0) {
739
+ const errs = {};
740
+ for (const x of short)
741
+ errs[x.key] = st('secret.too_short', { min: x.min, n: (credValues[x.key] ?? '').length });
742
+ setFieldErrors(errs);
743
+ return st('secret.too_short', { min: short[0].min, n: (credValues[short[0].key] ?? '').length });
744
+ }
665
745
  const payload = {};
666
746
  for (const [k, v] of Object.entries(credValues)) {
667
747
  if (v != null && v !== '' && isSendable(k))
@@ -880,10 +960,33 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
880
960
  : justSaved
881
961
  ? 'saved'
882
962
  : 'clean';
963
+ // Closing with unsaved edits asks first (Esc, overlay click, X and Cancelar
964
+ // all land here); a save in flight never closes the dialog under it.
965
+ const [confirmDiscard, setConfirmDiscard] = useState(false);
966
+ const keepEditingRef = useRef(null);
967
+ useEffect(() => {
968
+ if (!open)
969
+ setConfirmDiscard(false);
970
+ }, [open]);
971
+ useEffect(() => {
972
+ if (confirmDiscard)
973
+ keepEditingRef.current?.focus();
974
+ }, [confirmDiscard]);
975
+ const requestClose = (next) => {
976
+ if (next)
977
+ return onOpenChange(true);
978
+ if (saveMutation.isPending)
979
+ return;
980
+ if (dirty)
981
+ return setConfirmDiscard(true);
982
+ onOpenChange(false);
983
+ };
984
+ const headerVersion = version ?? addon.manifest.version;
985
+ const configured = connector ? !!connector.connected : null;
883
986
  const hasAnyBlocks = layoutSections.some((s) => (s.blocks?.length ?? 0) > 0) || extraBlocks.length > 0;
884
987
  const nothingToConfigure = !hasCredentials && !hasSettings && !isOAuth && !hasAnyBlocks && autoFields.length === 0;
885
988
  const nothingToSave = !hasCredentials && !hasSettings;
886
- return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsx(DialogContent, { className: 'flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4', children: _jsxs(ConnectorFormStateContext.Provider, { value: { fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds, reloadNonce }, children: [_jsxs(DialogHeader, { className: 'shrink-0 pe-8 text-start', children: [_jsx(DialogTitle, { className: 'leading-snug', children: st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name }) }), _jsx(DialogDescription, { children: st('installed_addons.configure_description') })] }), _jsx("div", { className: '-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2', children: loading ? (_jsx("div", { className: 'flex justify-center py-8', children: _jsx(Loader2, { className: 'h-5 w-5 animate-spin text-muted-foreground' }) })) : useStepper ? (_jsxs("div", { className: 'flex flex-col gap-5', children: [_jsxs("nav", { "aria-label": st('wizard.steps'), className: 'flex flex-col gap-2', children: [_jsx("ol", { className: 'flex items-center', children: wizardSteps.map((s, i) => {
989
+ return (_jsx(Dialog, { open: open, onOpenChange: requestClose, children: _jsx(DialogContent, { className: 'flex max-h-[85vh] flex-col max-sm:max-h-[calc(100dvh-1rem)] max-sm:gap-3 max-sm:p-4', children: _jsxs(ConnectorFormStateContext.Provider, { value: { fields: credFields, errors: fieldErrors, idPrefix, client: api, expectedOptionKinds, reloadNonce, canManage: canManageIssuer }, children: [_jsxs(DialogHeader, { className: 'shrink-0 pe-8 text-start', children: [_jsxs("div", { className: 'flex items-center gap-3', children: [logo, _jsxs("div", { className: 'flex min-w-0 flex-1 flex-col gap-1', children: [_jsx(DialogTitle, { className: 'leading-snug break-words', children: st('installed_addons.configure_title', { name: displayName ?? addon.manifest.display_name ?? addon.manifest.name }) }), _jsxs("div", { className: 'flex flex-wrap items-center gap-2', children: [headerVersion ? (_jsx(Badge, { variant: 'outline', className: 'text-[10px] tabular-nums', children: st('header.version', { version: String(headerVersion).replace(/^v/i, '') }) })) : null, configured !== null ? (_jsx(StepStatusBadge, { status: configured ? 'ok' : 'pending', label: configured ? st('header.configured') : st('header.pending') })) : null] })] })] }), _jsx(DialogDescription, { className: 'sr-only', children: st('header.description') })] }), _jsx("div", { className: '-mr-2 flex min-h-0 flex-col gap-6 overflow-y-auto py-2 pr-2', children: loading ? (_jsx("div", { className: 'flex justify-center py-8', children: _jsx(Loader2, { className: 'h-5 w-5 animate-spin text-muted-foreground' }) })) : useStepper ? (_jsxs("div", { className: 'flex flex-col gap-5', children: [_jsxs("nav", { "aria-label": st('wizard.steps'), className: 'flex flex-col gap-2', children: [_jsx("ol", { className: 'flex items-center', children: wizardSteps.map((s, i) => {
887
990
  const status = stepState(i);
888
991
  const active = i === stepIdx;
889
992
  const title = t(s.title ?? '', { defaultValue: humanizeKey(s.title) });
@@ -908,5 +1011,5 @@ export function AddonConfigSurface({ addon, connector, open, onOpenChange, onSav
908
1011
  if (fields.length === 0 && (sec.blocks?.length ?? 0) === 0)
909
1012
  return null;
910
1013
  return (_jsxs("div", { className: 'flex flex-col gap-3 rounded-md border border-border/60 px-3 py-3', children: [sec.title && (_jsxs("div", { className: 'flex flex-col gap-1', children: [_jsx("h4", { className: 'text-sm font-medium', children: t(sec.title, { defaultValue: sec.title }) }), sec.description && (_jsx(HelpText, { text: addonText(sec.description) }))] })), renderBlocks(leadBlocks(sec.blocks)), fields.map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), renderBlocks(trailBlocks(sec.blocks))] }, sec.key));
911
- })) : (_jsxs(_Fragment, { children: [activeFields.filter((f) => f.required).map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), activeFields.some((f) => !f.required) && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: activeFields.filter((f) => !f.required).some((f) => !!fieldErrors[f.key]) || undefined, children: [_jsx("summary", { className: 'flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8', children: st('installed_addons.advanced') }), _jsx("div", { className: 'flex flex-col gap-3 pt-3', children: activeFields.filter((f) => !f.required).map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))) })] }))] }))] })), extraBlocks.length > 0 && renderBlocks(extraBlocks), hasSettings && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Settings, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_settings') })] }), targetPicker, shownDefs.map(renderSetting)] })), nothingToConfigure && (_jsxs("div", { className: 'flex flex-col items-start gap-1 rounded-lg border border-dashed p-4', children: [_jsx("p", { className: 'text-sm font-medium', children: st('empty.title') }), _jsx(HelpText, { text: st('empty.help') })] }))] })) }), formError ? (_jsx("div", { ref: errorRef, role: 'alert', className: 'max-h-40 shrink-0 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive', children: formError })) : null, _jsx(DialogFooter, { "data-wizard-footer": '', className: 'flex shrink-0 flex-col gap-2 border-t pt-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between sm:space-x-0', children: nothingToSave && !useStepper ? (_jsx(Button, { className: 'h-11 w-full sm:ml-auto sm:h-9 sm:w-auto', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs("p", { role: 'status', "aria-live": 'polite', "data-save-status": saveStatus, className: cn('flex shrink-0 items-center gap-1.5 whitespace-nowrap text-xs', saveStatus === 'dirty' ? 'font-medium text-amber-600 dark:text-amber-400' : 'text-muted-foreground', saveStatus === 'saved' && 'text-emerald-600 dark:text-emerald-400'), children: [saveStatus === 'saving' ? (_jsx(Loader2, { className: 'h-3.5 w-3.5 animate-spin' })) : saveStatus === 'saved' ? (_jsx(Check, { className: 'h-3.5 w-3.5' })) : (_jsx("span", { "aria-hidden": true, className: cn('h-2 w-2 rounded-full', saveStatus === 'dirty' ? 'bg-amber-500' : 'bg-muted-foreground/40') })), st(`form.status_${saveStatus}`)] }), _jsxs("div", { className: 'flex flex-wrap items-center gap-2 sm:ml-auto sm:flex-nowrap sm:justify-end', children: [_jsx(Button, { variant: 'ghost', className: 'h-11 px-3 sm:h-9', onClick: () => onOpenChange(false), children: dirty ? st('common.cancel') : st('common.close') }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), useStepper && !isLastStep && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: handleNext, children: st('common.next') })), !nothingToSave && (_jsxs(Button, { className: 'h-11 flex-1 sm:h-9 sm:flex-none', onClick: handleSave, disabled: saveMutation.isPending || loading, "data-testid": 'config-save', children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), st('common.save')] }))] })] })) })] }) }) }));
1014
+ })) : (_jsxs(_Fragment, { children: [activeFields.filter((f) => f.required).map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))), activeFields.some((f) => !f.required) && (_jsxs("details", { className: 'rounded-md border border-border/60 px-3 py-2', open: activeFields.filter((f) => !f.required).some((f) => !!fieldErrors[f.key]) || undefined, children: [_jsx("summary", { className: 'flex min-h-11 cursor-pointer items-center text-sm font-medium text-muted-foreground select-none sm:min-h-8', children: st('installed_addons.advanced') }), _jsx("div", { className: 'flex flex-col gap-3 pt-3', children: activeFields.filter((f) => !f.required).map((f) => (_jsx(ConnectorCredentialFieldControl, { field: f, connected: !!connector?.connected, provider: connector?.provider ?? '', ...storedProps(f.key), value: credValues[f.key] ?? '', onChange: (val) => setCred(f.key, val) }, f.key))) })] }))] }))] })), extraBlocks.length > 0 && renderBlocks(extraBlocks), hasSettings && (_jsxs("section", { className: 'flex flex-col gap-3', children: [_jsxs("div", { className: 'flex items-center gap-2', children: [_jsx(Settings, { className: 'h-4 w-4 text-muted-foreground' }), _jsx("h3", { className: 'text-sm font-semibold', children: st('installed_addons.section_settings') })] }), targetPicker, shownDefs.map(renderSetting)] })), nothingToConfigure && (_jsxs("div", { className: 'flex flex-col items-start gap-1 rounded-lg border border-dashed p-4', children: [_jsx("p", { className: 'text-sm font-medium', children: st('empty.title') }), _jsx(HelpText, { text: st('empty.help') })] }))] })) }), formError ? (_jsx("div", { ref: errorRef, role: 'alert', className: 'max-h-40 shrink-0 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive', children: formError })) : null, _jsx(DialogFooter, { "data-wizard-footer": '', className: 'flex shrink-0 flex-col gap-2 border-t pt-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between sm:space-x-0', children: confirmDiscard ? (_jsxs("div", { role: 'alertdialog', "aria-labelledby": `${idPrefix}-discard`, className: 'flex w-full flex-col gap-2 sm:flex-row sm:items-center sm:justify-between', children: [_jsx("p", { id: `${idPrefix}-discard`, className: 'text-sm font-medium', children: st('discard.title') }), _jsxs("div", { className: 'flex flex-wrap gap-2 sm:justify-end', children: [_jsx(Button, { ref: keepEditingRef, className: 'h-11 sm:h-9', onClick: () => setConfirmDiscard(false), children: st('discard.keep') }), _jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => onOpenChange(false), children: st('discard.confirm') })] })] })) : nothingToSave && !useStepper ? (_jsx(Button, { className: 'h-11 w-full sm:ml-auto sm:h-9 sm:w-auto', onClick: () => onOpenChange(false), children: st('common.close') })) : (_jsxs(_Fragment, { children: [_jsxs("p", { role: 'status', "aria-live": 'polite', "data-save-status": saveStatus, className: cn('flex shrink-0 items-center gap-1.5 whitespace-nowrap text-xs', saveStatus === 'dirty' ? 'font-medium text-amber-600 dark:text-amber-400' : 'text-muted-foreground', saveStatus === 'saved' && 'text-emerald-600 dark:text-emerald-400'), children: [saveStatus === 'saving' ? (_jsx(Loader2, { className: 'h-3.5 w-3.5 animate-spin' })) : saveStatus === 'saved' ? (_jsx(Check, { className: 'h-3.5 w-3.5' })) : (_jsx("span", { "aria-hidden": true, className: cn('h-2 w-2 rounded-full', saveStatus === 'dirty' ? 'bg-amber-500' : 'bg-muted-foreground/40') })), st(`form.status_${saveStatus}`)] }), _jsxs("div", { className: 'flex flex-wrap items-center gap-2 sm:ml-auto sm:flex-nowrap sm:justify-end', children: [_jsx(Button, { variant: 'ghost', className: 'h-11 px-3 sm:h-9', onClick: () => requestClose(false), children: dirty ? st('common.cancel') : st('common.close') }), useStepper && stepIdx > 0 && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: () => goToStep(Math.max(0, stepIdx - 1)), children: st('common.back') })), useStepper && !isLastStep && (_jsx(Button, { variant: 'outline', className: 'h-11 sm:h-9', onClick: handleNext, children: st('common.next') })), !nothingToSave && (_jsxs(Button, { className: 'h-11 flex-1 sm:h-9 sm:flex-none', onClick: handleSave, disabled: saveMutation.isPending || loading, "data-testid": 'config-save', children: [saveMutation.isPending && _jsx(Loader2, { className: 'mr-2 h-4 w-4 animate-spin' }), st('common.save')] }))] })] })) })] }) }) }));
912
1015
  }
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/setup/messages.ts"],"names":[],"mappings":"AAMA,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB,EAAE,IAoK/B,CAAA;AAED,eAAO,MAAM,iBAAiB,EAAE,IAiK/B,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAA;AAOzE,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,IAAI,GAAG,CAa/B"}
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/setup/messages.ts"],"names":[],"mappings":"AAMA,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB,EAAE,IA6L/B,CAAA;AAED,eAAO,MAAM,iBAAiB,EAAE,IA0L/B,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAA;AAOzE,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAGjE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,IAAI,GAAG,CAa/B"}
@@ -165,6 +165,31 @@ export const SETUP_MESSAGES_ES = {
165
165
  'form.status_dirty': 'Cambios sin guardar',
166
166
  'form.status_saved': 'Guardado',
167
167
  'form.status_saving': 'Guardando…',
168
+ 'header.description': 'Credenciales y ajustes de este addon.',
169
+ 'header.version': 'v{{version}}',
170
+ 'header.configured': 'Configurado',
171
+ 'header.pending': 'Por configurar',
172
+ 'secret.fix_fields': 'Revisa estos campos: {{fields}}.',
173
+ 'secret.generate': 'Generar',
174
+ 'secret.regenerate': 'Generar otra',
175
+ 'secret.rotate': 'Rotar',
176
+ 'secret.rotate_title': '¿Rotar esta clave?',
177
+ 'secret.rotate_body': 'Se reemplaza la clave actual. Lo que la use dejará de funcionar hasta que le pongas la nueva.',
178
+ 'secret.rotate_confirm': 'Sí, rotar',
179
+ 'secret.rotate_cancel': 'Cancelar',
180
+ 'secret.copy': 'Copiar',
181
+ 'secret.copy_what': 'la clave',
182
+ 'secret.generated_hint': 'Clave generada. Cópiala y guarda para activarla.',
183
+ 'secret.generate_unavailable': 'Tu navegador no permite generar claves seguras.',
184
+ 'secret.strength': 'Fuerza',
185
+ 'secret.strength_weak': 'Débil',
186
+ 'secret.strength_fair': 'Aceptable',
187
+ 'secret.strength_strong': 'Fuerte',
188
+ 'secret.too_short': 'Mínimo {{min}} caracteres (llevas {{n}}).',
189
+ 'secret.how_to_use': 'Cómo se usa',
190
+ 'discard.title': '¿Descartar los cambios sin guardar?',
191
+ 'discard.keep': 'Seguir editando',
192
+ 'discard.confirm': 'Descartar',
168
193
  };
169
194
  export const SETUP_MESSAGES_EN = {
170
195
  'status.pending': 'Pending',
@@ -326,6 +351,31 @@ export const SETUP_MESSAGES_EN = {
326
351
  'form.status_dirty': 'Unsaved changes',
327
352
  'form.status_saved': 'Saved',
328
353
  'form.status_saving': 'Saving…',
354
+ 'header.description': 'Credentials and settings for this addon.',
355
+ 'header.version': 'v{{version}}',
356
+ 'header.configured': 'Configured',
357
+ 'header.pending': 'Not configured',
358
+ 'secret.fix_fields': 'Check these fields: {{fields}}.',
359
+ 'secret.generate': 'Generate',
360
+ 'secret.regenerate': 'Generate another',
361
+ 'secret.rotate': 'Rotate',
362
+ 'secret.rotate_title': 'Rotate this key?',
363
+ 'secret.rotate_body': 'The current key is replaced. Anything using it stops working until you give it the new one.',
364
+ 'secret.rotate_confirm': 'Yes, rotate',
365
+ 'secret.rotate_cancel': 'Cancel',
366
+ 'secret.copy': 'Copy',
367
+ 'secret.copy_what': 'the key',
368
+ 'secret.generated_hint': 'Key generated. Copy it and save to activate it.',
369
+ 'secret.generate_unavailable': 'Your browser cannot generate secure keys.',
370
+ 'secret.strength': 'Strength',
371
+ 'secret.strength_weak': 'Weak',
372
+ 'secret.strength_fair': 'Fair',
373
+ 'secret.strength_strong': 'Strong',
374
+ 'secret.too_short': 'At least {{min}} characters ({{n}} so far).',
375
+ 'secret.how_to_use': 'How it is used',
376
+ 'discard.title': 'Discard unsaved changes?',
377
+ 'discard.keep': 'Keep editing',
378
+ 'discard.confirm': 'Discard',
329
379
  };
330
380
  function interpolate(s, vars) {
331
381
  if (!vars)
@@ -0,0 +1,47 @@
1
+ /** What these helpers need from a credential definition. */
2
+ export interface SecretFieldLike {
3
+ key: string;
4
+ validation?: string;
5
+ }
6
+ /** Length used by "Generar" when the field declares no minimum. */
7
+ export declare const DEFAULT_GENERATED_LENGTH = 32;
8
+ /**
9
+ * Minimum length the manifest declares for a credential, from its `validation`
10
+ * hint. Understands `min_length:32` / `minlength=32` / `min:32` and the regex
11
+ * form `^.{32,}$`. Returns 0 when nothing is declared.
12
+ */
13
+ export declare function secretMinLength(field: SecretFieldLike): number;
14
+ /** Length "Generar" produces: the declared minimum (never below the default). */
15
+ export declare function generatedLength(field: SecretFieldLike): number;
16
+ type RandomSource = Pick<Crypto, 'getRandomValues'>;
17
+ /**
18
+ * Random secret of `length` chars over [A-Za-z0-9] using crypto.getRandomValues.
19
+ * Rejection sampling keeps every character equally likely (no modulo bias).
20
+ * Throws when no CSPRNG exists: a weak fallback is never acceptable here.
21
+ */
22
+ export declare function generateSecret(length: number, source?: RandomSource): string;
23
+ export type SecretStrength = 'empty' | 'weak' | 'fair' | 'strong';
24
+ /**
25
+ * Coarse grade for the strength bar: length against the declared minimum
26
+ * (or 16/32 when none), plus character variety and repetition.
27
+ */
28
+ export declare function secretStrength(value: string, min?: number): SecretStrength;
29
+ /** Keys of non-empty secret values shorter than the minimum their field declares. */
30
+ export declare function tooShortSecrets(fields: (SecretFieldLike & {
31
+ secret?: boolean;
32
+ type?: string;
33
+ })[], values: Record<string, string>): {
34
+ key: string;
35
+ min: number;
36
+ }[];
37
+ /**
38
+ * Splits a long help sentence into a short lead and the technical remainder
39
+ * (shown under a collapsible "Cómo se usa"). Splits at the first `;`, `.` or
40
+ * line break; short texts are returned whole.
41
+ */
42
+ export declare function splitHelp(text: string, maxLead?: number): {
43
+ lead: string;
44
+ detail: string;
45
+ };
46
+ export {};
47
+ //# sourceMappingURL=secret-field-model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-field-model.d.ts","sourceRoot":"","sources":["../../src/setup/secret-field-model.ts"],"names":[],"mappings":"AAKA,4DAA4D;AAC5D,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,mEAAmE;AACnE,eAAO,MAAM,wBAAwB,KAAK,CAAA;AAM1C;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAQ9D;AAED,iFAAiF;AACjF,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAE9D;AAED,KAAK,YAAY,GAAG,IAAI,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAA;AAEnD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,GAAG,MAAM,CAc5E;AAED,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAA;AAEjE;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,SAAI,GAAG,cAAc,CAQrE;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAC7B,MAAM,EAAE,CAAC,eAAe,GAAG;IAAE,MAAM,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,EACjE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC7B;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,CAShC;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,SAAK,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAMtF"}
@@ -0,0 +1,95 @@
1
+ // Pure helpers for connector secret fields (no React, no i18n): the minimum
2
+ // length a field declares, a CSPRNG generator that honours it, and a strength
3
+ // grade. Provider-agnostic on purpose: they read only how the field itself is
4
+ // declared (`validation` hint on a credential), so any addon benefits.
5
+ /** Length used by "Generar" when the field declares no minimum. */
6
+ export const DEFAULT_GENERATED_LENGTH = 32;
7
+ /** Hard ceiling so a bad hint never produces an absurd secret. */
8
+ const MAX_GENERATED_LENGTH = 128;
9
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
10
+ /**
11
+ * Minimum length the manifest declares for a credential, from its `validation`
12
+ * hint. Understands `min_length:32` / `minlength=32` / `min:32` and the regex
13
+ * form `^.{32,}$`. Returns 0 when nothing is declared.
14
+ */
15
+ export function secretMinLength(field) {
16
+ const v = (field.validation ?? '').trim();
17
+ if (!v)
18
+ return 0;
19
+ const named = /^(?:min_?length|min)\s*[:=]\s*(\d{1,4})$/i.exec(v);
20
+ if (named)
21
+ return Number(named[1]);
22
+ const rx = /^\^?\(?(?:\.|\\S|\[[^\]]+\])\{(\d{1,4}),(?:\d{0,4})\}\)?\$?$/.exec(v);
23
+ if (rx)
24
+ return Number(rx[1]);
25
+ return 0;
26
+ }
27
+ /** Length "Generar" produces: the declared minimum (never below the default). */
28
+ export function generatedLength(field) {
29
+ return Math.min(MAX_GENERATED_LENGTH, Math.max(DEFAULT_GENERATED_LENGTH, secretMinLength(field)));
30
+ }
31
+ /**
32
+ * Random secret of `length` chars over [A-Za-z0-9] using crypto.getRandomValues.
33
+ * Rejection sampling keeps every character equally likely (no modulo bias).
34
+ * Throws when no CSPRNG exists: a weak fallback is never acceptable here.
35
+ */
36
+ export function generateSecret(length, source) {
37
+ const rng = source ?? (typeof globalThis !== 'undefined' ? globalThis.crypto : undefined);
38
+ if (!rng?.getRandomValues)
39
+ throw new Error('crypto.getRandomValues unavailable');
40
+ const n = Math.max(1, Math.min(MAX_GENERATED_LENGTH, Math.floor(length)));
41
+ const limit = 256 - (256 % ALPHABET.length);
42
+ let out = '';
43
+ while (out.length < n) {
44
+ const buf = new Uint8Array(n * 2);
45
+ rng.getRandomValues(buf);
46
+ for (const b of buf) {
47
+ if (b < limit && out.length < n)
48
+ out += ALPHABET[b % ALPHABET.length];
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+ /**
54
+ * Coarse grade for the strength bar: length against the declared minimum
55
+ * (or 16/32 when none), plus character variety and repetition.
56
+ */
57
+ export function secretStrength(value, min = 0) {
58
+ if (!value)
59
+ return 'empty';
60
+ const unique = new Set(value).size;
61
+ const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((r) => r.test(value)).length;
62
+ const floor = Math.max(min, 16);
63
+ if (value.length < floor || unique < 6)
64
+ return 'weak';
65
+ if (value.length >= Math.max(min, 32) && classes >= 2 && unique >= 12)
66
+ return 'strong';
67
+ return 'fair';
68
+ }
69
+ /** Keys of non-empty secret values shorter than the minimum their field declares. */
70
+ export function tooShortSecrets(fields, values) {
71
+ const out = [];
72
+ for (const f of fields) {
73
+ if (!f.secret && f.type !== 'secret')
74
+ continue;
75
+ const min = secretMinLength(f);
76
+ const v = values[f.key] ?? '';
77
+ if (min > 0 && v !== '' && v.length < min)
78
+ out.push({ key: f.key, min });
79
+ }
80
+ return out;
81
+ }
82
+ /**
83
+ * Splits a long help sentence into a short lead and the technical remainder
84
+ * (shown under a collapsible "Cómo se usa"). Splits at the first `;`, `.` or
85
+ * line break; short texts are returned whole.
86
+ */
87
+ export function splitHelp(text, maxLead = 90) {
88
+ const t = text.trim();
89
+ if (t.length <= maxLead)
90
+ return { lead: t, detail: '' };
91
+ const m = /^(.+?)(?:[;.]\s+|\n+)(.+)$/s.exec(t);
92
+ if (!m || m[1].length > 160)
93
+ return { lead: t, detail: '' };
94
+ return { lead: m[1].replace(/[;.]$/, '').trim(), detail: m[2].trim() };
95
+ }
@@ -0,0 +1,24 @@
1
+ import { type Severity } from '@asteby/metacore-ui/layout';
2
+ import type { CardSpec } from './types';
3
+ export interface ResolvedCard {
4
+ title: string;
5
+ subtitle?: string;
6
+ badge?: {
7
+ text: string;
8
+ tone: Severity;
9
+ };
10
+ chips: string[];
11
+ meta: {
12
+ label?: string;
13
+ value: string;
14
+ }[];
15
+ }
16
+ /** Pure: row + manifest CardSpec -> display model. Missing fields are skipped, never throw. */
17
+ export declare function resolveCard(spec: CardSpec, row: Record<string, unknown>, locale?: string): ResolvedCard;
18
+ export declare function ConfigurableCard({ spec, row, onClick, locale }: {
19
+ spec: CardSpec;
20
+ row: Record<string, unknown>;
21
+ onClick?: () => void;
22
+ locale?: string;
23
+ }): import("react").JSX.Element;
24
+ //# sourceMappingURL=card-spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"card-spec.d.ts","sourceRoot":"","sources":["../../src/view-system/card-spec.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,QAAQ,EAAE,MAAM,4BAA4B,CAAA;AAE5E,OAAO,KAAK,EAAiB,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEtD,MAAM,WAAW,YAAY;IACzB,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,QAAQ,CAAA;KAAE,CAAA;IACxC,KAAK,EAAE,MAAM,EAAE,CAAA;IACf,IAAI,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CAC5C;AAgBD,+FAA+F;AAC/F,wBAAgB,WAAW,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,YAAY,CAUvG;AAED,wBAAgB,gBAAgB,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,+BAsCvJ"}
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { BADGE_TONE_CLASS } from '@asteby/metacore-ui/layout';
3
+ import { cn } from '@asteby/metacore-ui/lib';
4
+ function fmt(v, f = 'text', locale) {
5
+ if (v == null || v === '')
6
+ return '';
7
+ try {
8
+ if (f === 'number')
9
+ return new Intl.NumberFormat(locale).format(Number(v));
10
+ if (f === 'percent')
11
+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(Number(v))}%`;
12
+ if (f === 'currency')
13
+ return new Intl.NumberFormat(locale, { style: 'currency', currency: 'MXN' }).format(Number(v));
14
+ if (f === 'date')
15
+ return new Date(String(v)).toLocaleDateString(locale);
16
+ if (f === 'datetime')
17
+ return new Date(String(v)).toLocaleString(locale);
18
+ }
19
+ catch {
20
+ /* fall through */
21
+ }
22
+ return String(v);
23
+ }
24
+ /** Pure: row + manifest CardSpec -> display model. Missing fields are skipped, never throw. */
25
+ export function resolveCard(spec, row, locale) {
26
+ const bv = spec.badge ? row[spec.badge.field] : undefined;
27
+ const key = bv == null ? '' : String(bv);
28
+ return {
29
+ title: fmt(row[spec.title]) || '—',
30
+ subtitle: spec.subtitle ? fmt(row[spec.subtitle]) || undefined : undefined,
31
+ badge: spec.badge && key ? { text: spec.badge.labels?.[key] ?? key, tone: spec.badge.tones?.[key] ?? 'info' } : undefined,
32
+ chips: (spec.chips ?? []).map((f) => fmt(row[f])).filter(Boolean),
33
+ meta: (spec.meta ?? []).map((m) => ({ label: m.label, value: fmt(row[m.field], m.format, locale) })).filter((m) => m.value),
34
+ };
35
+ }
36
+ export function ConfigurableCard({ spec, row, onClick, locale }) {
37
+ const c = resolveCard(spec, row, locale);
38
+ const Tag = onClick ? 'button' : 'div';
39
+ return (_jsxs(Tag, { ...(onClick ? { type: 'button', onClick } : {}), className: cn('flex w-full flex-col gap-2 rounded-xl border bg-card p-4 text-start', onClick && 'transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'), children: [_jsxs("div", { className: 'flex items-start justify-between gap-2', children: [_jsx("span", { className: 'line-clamp-2 font-medium', children: c.title }), c.badge && (_jsx("span", { "data-tone": c.badge.tone, className: cn('shrink-0 rounded-full px-2 text-xs font-semibold leading-5 ring-1 ring-inset', BADGE_TONE_CLASS[c.badge.tone].replace(/motion-safe:animate-pulse/, '')), children: c.badge.text }))] }), c.subtitle && _jsx("span", { className: 'line-clamp-2 text-sm text-muted-foreground', children: c.subtitle }), c.chips.length > 0 && (_jsx("div", { className: 'flex flex-wrap gap-1', children: c.chips.map((x, i) => (_jsx("span", { className: 'rounded-md bg-muted px-1.5 py-0.5 text-xs text-muted-foreground', children: x }, i))) })), c.meta.length > 0 && (_jsx("dl", { className: 'mt-auto grid grid-cols-2 gap-x-3 gap-y-1 text-xs text-muted-foreground', children: c.meta.map((m, i) => (_jsxs("div", { className: 'min-w-0', children: [m.label && _jsx("dt", { className: 'sr-only', children: m.label }), _jsx("dd", { className: 'truncate', children: m.value })] }, i))) }))] }));
40
+ }
@@ -0,0 +1,17 @@
1
+ import type { CardSpec } from './types';
2
+ export interface CardsViewProps {
3
+ model: string;
4
+ endpoint?: string;
5
+ card: CardSpec;
6
+ /** Server params from `viewStateToParams` — the SAME filters the table uses. */
7
+ params: Record<string, string>;
8
+ pageSize?: number;
9
+ onOpen?: (row: Record<string, unknown>) => void;
10
+ /** Reports the filtered total so the shell can render "7,358 hallazgos". */
11
+ onTotal?: (total: number) => void;
12
+ /** Bump to refetch (e.g. realtime tick). */
13
+ refreshTrigger?: unknown;
14
+ }
15
+ /** Card grid over the same list endpoint DynamicTable uses; "load more" pagination. */
16
+ export declare function CardsView({ model, endpoint, card, params, pageSize, onOpen, onTotal, refreshTrigger }: CardsViewProps): import("react").JSX.Element;
17
+ //# sourceMappingURL=cards-view.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cards-view.d.ts","sourceRoot":"","sources":["../../src/view-system/cards-view.tsx"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEvC,MAAM,WAAW,cAAc;IAC3B,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,QAAQ,CAAA;IACd,gFAAgF;IAChF,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;IAC/C,4EAA4E;IAC5E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IACjC,4CAA4C;IAC5C,cAAc,CAAC,EAAE,OAAO,CAAA;CAC3B;AAED,uFAAuF;AACvF,wBAAgB,SAAS,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,QAAa,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,EAAE,cAAc,+BAqC1H"}
@@ -0,0 +1,37 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useState } from 'react';
3
+ import { useQuery } from '@tanstack/react-query';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { Button } from '@asteby/metacore-ui/primitives';
6
+ import { useApi } from '../api-context';
7
+ import { ConfigurableCard } from './card-spec';
8
+ /** Card grid over the same list endpoint DynamicTable uses; "load more" pagination. */
9
+ export function CardsView({ model, endpoint, card, params, pageSize = 24, onOpen, onTotal, refreshTrigger }) {
10
+ const api = useApi();
11
+ const { t, i18n } = useTranslation();
12
+ const [pages, setPages] = useState(1);
13
+ const key = JSON.stringify(params);
14
+ useEffect(() => setPages(1), [key]);
15
+ const q = useQuery({
16
+ queryKey: ['view-cards', model, endpoint, key, pages, refreshTrigger],
17
+ queryFn: async () => {
18
+ const res = await api.get(endpoint ?? `/data/${model}`, { params: { ...params, page: 1, per_page: pageSize * pages } });
19
+ const b = res.data;
20
+ const rows = (Array.isArray(b?.data) ? b.data : Array.isArray(b) ? b : []);
21
+ return { rows, total: Number(b?.meta?.total ?? rows.length) };
22
+ },
23
+ placeholderData: (prev) => prev,
24
+ });
25
+ useEffect(() => {
26
+ if (q.data)
27
+ onTotal?.(q.data.total);
28
+ }, [q.data, onTotal]);
29
+ if (q.isLoading)
30
+ return _jsx("div", { className: 'p-6 text-sm text-muted-foreground', children: t('common.loading', { defaultValue: 'Cargando…' }) });
31
+ if (q.isError)
32
+ return _jsx("div", { role: 'alert', className: 'p-6 text-sm text-destructive', children: t('views.error', { defaultValue: 'No se pudo cargar la lista' }) });
33
+ const rows = q.data?.rows ?? [];
34
+ if (rows.length === 0)
35
+ return _jsx("div", { className: 'p-6 text-sm text-muted-foreground', children: t('views.empty', { defaultValue: 'Sin resultados' }) });
36
+ return (_jsxs("div", { className: 'flex flex-col gap-4', children: [_jsx("div", { className: 'grid gap-3 sm:grid-cols-2 xl:grid-cols-3', children: rows.map((r, i) => (_jsx(ConfigurableCard, { spec: card, row: r, locale: i18n.language, onClick: onOpen ? () => onOpen(r) : undefined }, String(r.id ?? i)))) }), rows.length < (q.data?.total ?? 0) && (_jsx(Button, { variant: 'outline', className: 'self-center', onClick: () => setPages((p) => p + 1), children: t('views.load_more', { defaultValue: 'Cargar más' }) }))] }));
37
+ }
@@ -0,0 +1,10 @@
1
+ export * from './types';
2
+ export { parseViewState, serializeViewState, viewStateToParams, isViewStateEmpty, EMPTY_VIEW_STATE } from './view-state';
3
+ export { useViewMode, resolveViewMode, viewPrefKey, DEFAULT_MODES, type UseViewModeOptions } from './use-view-mode';
4
+ export { ViewSwitcher, type ViewSwitcherProps } from './view-switcher';
5
+ export { ViewToolbar, type ViewToolbarProps } from './view-toolbar';
6
+ export { useSavedViews, localSavedViewsAdapter, upsertSavedView, removeSavedView, MAX_SAVED_VIEWS, type SavedViewsAdapter } from './saved-views';
7
+ export { ConfigurableCard, resolveCard, type ResolvedCard } from './card-spec';
8
+ export { CardsView, type CardsViewProps } from './cards-view';
9
+ export { ModelView, type ModelViewProps, type ModelViewRendererProps } from './model-view';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/view-system/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA;AACvB,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAA;AACxH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,WAAW,EAAE,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AACnH,OAAO,EAAE,YAAY,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AACtE,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAA;AACnE,OAAO,EAAE,aAAa,EAAE,sBAAsB,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAAE,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAChJ,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAA;AAC9E,OAAO,EAAE,SAAS,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,KAAK,cAAc,EAAE,KAAK,sBAAsB,EAAE,MAAM,cAAc,CAAA"}
@@ -0,0 +1,9 @@
1
+ export * from './types';
2
+ export { parseViewState, serializeViewState, viewStateToParams, isViewStateEmpty, EMPTY_VIEW_STATE } from './view-state';
3
+ export { useViewMode, resolveViewMode, viewPrefKey, DEFAULT_MODES } from './use-view-mode';
4
+ export { ViewSwitcher } from './view-switcher';
5
+ export { ViewToolbar } from './view-toolbar';
6
+ export { useSavedViews, localSavedViewsAdapter, upsertSavedView, removeSavedView, MAX_SAVED_VIEWS } from './saved-views';
7
+ export { ConfigurableCard, resolveCard } from './card-spec';
8
+ export { CardsView } from './cards-view';
9
+ export { ModelView } from './model-view';