@asteby/metacore-runtime-react 53.27.0 → 53.29.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 (88) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/business/customer-picker.d.ts +10 -1
  3. package/dist/business/customer-picker.d.ts.map +1 -1
  4. package/dist/business/customer-picker.js +7 -2
  5. package/dist/dialogs/create-record-dialog.d.ts +1 -1
  6. package/dist/dialogs/create-record-dialog.d.ts.map +1 -1
  7. package/dist/dialogs/create-record-dialog.js +2 -2
  8. package/dist/dialogs/dynamic-record.d.ts +19 -2
  9. package/dist/dialogs/dynamic-record.d.ts.map +1 -1
  10. package/dist/dialogs/dynamic-record.js +83 -25
  11. package/dist/dialogs/types.d.ts +6 -0
  12. package/dist/dialogs/types.d.ts.map +1 -1
  13. package/dist/dynamic-crud-page.d.ts.map +1 -1
  14. package/dist/dynamic-crud-page.js +3 -0
  15. package/dist/dynamic-form.d.ts.map +1 -1
  16. package/dist/dynamic-form.js +6 -5
  17. package/dist/field-widget-registry.d.ts +6 -0
  18. package/dist/field-widget-registry.d.ts.map +1 -1
  19. package/dist/index.d.ts +4 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +3 -1
  22. package/dist/loom/index.d.ts +9 -0
  23. package/dist/loom/index.d.ts.map +1 -0
  24. package/dist/loom/index.js +9 -0
  25. package/dist/loom/overlay.d.ts +74 -0
  26. package/dist/loom/overlay.d.ts.map +1 -0
  27. package/dist/loom/overlay.js +142 -0
  28. package/dist/loom/proposals.d.ts +26 -0
  29. package/dist/loom/proposals.d.ts.map +1 -0
  30. package/dist/loom/proposals.js +74 -0
  31. package/dist/loom/provider.d.ts +28 -0
  32. package/dist/loom/provider.d.ts.map +1 -0
  33. package/dist/loom/provider.js +31 -0
  34. package/dist/loom/resolve.d.ts +23 -0
  35. package/dist/loom/resolve.d.ts.map +1 -0
  36. package/dist/loom/resolve.js +138 -0
  37. package/dist/loom/seam.d.ts +28 -0
  38. package/dist/loom/seam.d.ts.map +1 -0
  39. package/dist/loom/seam.js +127 -0
  40. package/dist/loom/seams.d.ts +31 -0
  41. package/dist/loom/seams.d.ts.map +1 -0
  42. package/dist/loom/seams.js +21 -0
  43. package/dist/loom/store.d.ts +16 -0
  44. package/dist/loom/store.d.ts.map +1 -0
  45. package/dist/loom/store.js +72 -0
  46. package/dist/loom/types.d.ts +153 -0
  47. package/dist/loom/types.d.ts.map +1 -0
  48. package/dist/loom/types.js +1 -0
  49. package/dist/model-labels.d.ts +26 -0
  50. package/dist/model-labels.d.ts.map +1 -1
  51. package/dist/model-labels.js +22 -5
  52. package/dist/record-picker-dialog.d.ts +10 -1
  53. package/dist/record-picker-dialog.d.ts.map +1 -1
  54. package/dist/record-picker-dialog.js +18 -3
  55. package/dist/record-picker.d.ts +6 -0
  56. package/dist/record-picker.d.ts.map +1 -1
  57. package/dist/record-picker.js +4 -1
  58. package/dist/types.d.ts +10 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/package.json +6 -6
  61. package/src/__tests__/dynamic-record-seam.test.tsx +194 -0
  62. package/src/__tests__/dynamic-record-texts.test.tsx +22 -0
  63. package/src/__tests__/field-widget-set-values.test.tsx +65 -0
  64. package/src/__tests__/loom-overlay.test.ts +94 -0
  65. package/src/__tests__/loom-resolve.test.ts +108 -0
  66. package/src/__tests__/model-labels.test.tsx +41 -1
  67. package/src/__tests__/record-picker-open-on-focus.test.tsx +49 -0
  68. package/src/business/customer-picker.tsx +17 -0
  69. package/src/dialogs/create-record-dialog.tsx +6 -0
  70. package/src/dialogs/dynamic-record.tsx +131 -26
  71. package/src/dialogs/types.ts +6 -0
  72. package/src/dynamic-crud-page.tsx +3 -0
  73. package/src/dynamic-form.tsx +9 -2
  74. package/src/field-widget-registry.tsx +6 -0
  75. package/src/index.ts +4 -1
  76. package/src/loom/index.ts +36 -0
  77. package/src/loom/overlay.ts +196 -0
  78. package/src/loom/proposals.tsx +156 -0
  79. package/src/loom/provider.tsx +69 -0
  80. package/src/loom/resolve.ts +136 -0
  81. package/src/loom/seam.tsx +235 -0
  82. package/src/loom/seams.ts +42 -0
  83. package/src/loom/store.ts +81 -0
  84. package/src/loom/types.ts +167 -0
  85. package/src/model-labels.ts +45 -5
  86. package/src/record-picker-dialog.tsx +42 -1
  87. package/src/record-picker.tsx +10 -0
  88. package/src/types.ts +10 -0
@@ -0,0 +1,196 @@
1
+ // Overlays — parches declarativos sobre el grafo de bloques de una página
2
+ // («kustomize para UI»). Base de OPS + capas de preset, organización, sucursal,
3
+ // rol y usuario, fusionadas en orden fijo y de forma determinista.
4
+ //
5
+ // Reglas (RFC 0005 §7):
6
+ // - Orden de capas por alcance: preset < org < branch < role < user; empate = orden de entrada.
7
+ // - Cada capa es ATÓMICA: si una operación no aplica limpio, la capa entera se descarta y se
8
+ // reporta el conflicto; la página queda como estaba antes de esa capa (nunca a medias).
9
+ // - Una capa con `targets` (rango semver de la base) que no cumple la versión de la base no se
10
+ // aplica: si la base cambió y rompe el overlay, se cae al comportamiento base y se avisa.
11
+ // - `replace` guarda el bloque original como `fallback`: el render lo usa si el reemplazo falla.
12
+ // - Procedencia: cada bloque sabe de qué capa viene y qué capas lo tocaron (Explain).
13
+ // Función pura, sin React.
14
+ import { satisfiesSdkRange } from '../slots/sdk-range'
15
+
16
+ export interface PageBlock {
17
+ id: string
18
+ type: string
19
+ region?: string
20
+ config?: Record<string, unknown>
21
+ /** Lo rellena `replace`: el bloque al que sustituyó. */
22
+ fallback?: PageBlock
23
+ }
24
+
25
+ export interface BlockGraph {
26
+ id: string
27
+ /** Semver de la base (`1.4.0`). */
28
+ version: string
29
+ blocks: PageBlock[]
30
+ }
31
+
32
+ type Anchor = { before?: string; after?: string }
33
+
34
+ export type OverlayOp =
35
+ | ({ op: 'add'; block: PageBlock } & Anchor)
36
+ | { op: 'remove'; id: string }
37
+ | ({ op: 'move'; id: string; region?: string } & Anchor)
38
+ /** Fusión profunda de `config`; un valor `null` borra la clave. */
39
+ | { op: 'configure'; id: string; set: Record<string, unknown> }
40
+ | { op: 'replace'; id: string; with: PageBlock }
41
+
42
+ export type OverlayScope = 'preset' | 'org' | 'branch' | 'role' | 'user'
43
+
44
+ export interface OverlayLayer {
45
+ id: string
46
+ scope: OverlayScope
47
+ /** Rango semver de la base contra la que se escribió (`^1.2`). */
48
+ targets?: string
49
+ ops: OverlayOp[]
50
+ }
51
+
52
+ export type OverlayConflictReason = 'base_incompatible' | 'missing_target' | 'missing_anchor' | 'duplicate_id'
53
+
54
+ export interface OverlayConflict {
55
+ layer: string
56
+ /** Índice de la operación (-1 = la capa entera). */
57
+ index: number
58
+ reason: OverlayConflictReason
59
+ detail: string
60
+ }
61
+
62
+ export interface BlockProvenance {
63
+ /** `base` o id de la capa que lo añadió. */
64
+ origin: string
65
+ /** Capas que lo modificaron, en orden. */
66
+ touchedBy: string[]
67
+ }
68
+
69
+ export interface OverlayResult {
70
+ graph: BlockGraph
71
+ applied: string[]
72
+ conflicts: OverlayConflict[]
73
+ provenance: Record<string, BlockProvenance>
74
+ /** Bloques quitados y por qué capa (Explain: «¿por qué NO veo esto?»). */
75
+ removed: Record<string, string>
76
+ }
77
+
78
+ const RANK: Record<OverlayScope, number> = { preset: 0, org: 1, branch: 2, role: 3, user: 4 }
79
+
80
+ function isPlain(v: unknown): v is Record<string, unknown> {
81
+ return !!v && typeof v === 'object' && !Array.isArray(v)
82
+ }
83
+
84
+ /** Fusión profunda; arrays se sustituyen enteros; `null` borra. */
85
+ export function mergeConfig(base: Record<string, unknown> | undefined, set: Record<string, unknown>): Record<string, unknown> {
86
+ const out: Record<string, unknown> = { ...(base ?? {}) }
87
+ for (const [k, v] of Object.entries(set)) {
88
+ if (v === null) delete out[k]
89
+ else if (isPlain(v) && isPlain(out[k])) out[k] = mergeConfig(out[k] as Record<string, unknown>, v)
90
+ else out[k] = v
91
+ }
92
+ return out
93
+ }
94
+
95
+ function insertAt(list: PageBlock[], block: PageBlock, a: Anchor): string | null {
96
+ const ref = a.before ?? a.after
97
+ if (!ref) {
98
+ list.push(block)
99
+ return null
100
+ }
101
+ const i = list.findIndex((b) => b.id === ref)
102
+ if (i < 0) return ref
103
+ list.splice(a.before ? i : i + 1, 0, block)
104
+ return null
105
+ }
106
+
107
+ export function applyOverlays(base: BlockGraph, layers: readonly OverlayLayer[]): OverlayResult {
108
+ let blocks = base.blocks.map((b) => ({ ...b }))
109
+ let provenance: Record<string, BlockProvenance> = {}
110
+ for (const b of blocks) provenance[b.id] = { origin: 'base', touchedBy: [] }
111
+ let removed: Record<string, string> = {}
112
+ const applied: string[] = []
113
+ const conflicts: OverlayConflict[] = []
114
+
115
+ const ordered = layers.map((l, i) => ({ l, i })).sort((a, b) => RANK[a.l.scope] - RANK[b.l.scope] || a.i - b.i)
116
+
117
+ for (const { l: layer } of ordered) {
118
+ if (layer.targets && satisfiesSdkRange(base.version, layer.targets) === false) {
119
+ conflicts.push({
120
+ layer: layer.id,
121
+ index: -1,
122
+ reason: 'base_incompatible',
123
+ detail: `escrita para ${base.id}@${layer.targets}, la base es ${base.version}`,
124
+ })
125
+ continue
126
+ }
127
+ const next = blocks.map((b) => ({ ...b }))
128
+ const prov: Record<string, BlockProvenance> = {}
129
+ for (const [k, v] of Object.entries(provenance)) prov[k] = { origin: v.origin, touchedBy: [...v.touchedBy] }
130
+ const rem = { ...removed }
131
+ let failed: OverlayConflict | null = null
132
+ const fail = (index: number, reason: OverlayConflictReason, detail: string) => {
133
+ failed = { layer: layer.id, index, reason, detail }
134
+ }
135
+ const find = (id: string) => next.findIndex((b) => b.id === id)
136
+ const touch = (id: string) => prov[id]?.touchedBy.push(layer.id)
137
+
138
+ layer.ops.forEach((op, index) => {
139
+ if (failed) return
140
+ switch (op.op) {
141
+ case 'add': {
142
+ if (find(op.block.id) >= 0) return fail(index, 'duplicate_id', op.block.id)
143
+ const miss = insertAt(next, { ...op.block }, op)
144
+ if (miss) return fail(index, 'missing_anchor', miss)
145
+ prov[op.block.id] = { origin: layer.id, touchedBy: [] }
146
+ delete rem[op.block.id]
147
+ return
148
+ }
149
+ case 'remove': {
150
+ const i = find(op.id)
151
+ if (i < 0) return fail(index, 'missing_target', op.id)
152
+ next.splice(i, 1)
153
+ rem[op.id] = layer.id
154
+ delete prov[op.id]
155
+ return
156
+ }
157
+ case 'move': {
158
+ const i = find(op.id)
159
+ if (i < 0) return fail(index, 'missing_target', op.id)
160
+ const [b] = next.splice(i, 1)
161
+ const moved = op.region ? { ...b, region: op.region } : b
162
+ if (op.before ?? op.after) {
163
+ const miss = insertAt(next, moved, op)
164
+ if (miss) return fail(index, 'missing_anchor', miss)
165
+ } else next.splice(i, 0, moved)
166
+ touch(op.id)
167
+ return
168
+ }
169
+ case 'configure': {
170
+ const i = find(op.id)
171
+ if (i < 0) return fail(index, 'missing_target', op.id)
172
+ next[i] = { ...next[i], config: mergeConfig(next[i].config, op.set) }
173
+ touch(op.id)
174
+ return
175
+ }
176
+ case 'replace': {
177
+ const i = find(op.id)
178
+ if (i < 0) return fail(index, 'missing_target', op.id)
179
+ const original = next[i]
180
+ next[i] = { ...op.with, id: original.id, fallback: original.fallback ?? original }
181
+ touch(op.id)
182
+ return
183
+ }
184
+ }
185
+ })
186
+ if (failed) {
187
+ conflicts.push(failed)
188
+ continue
189
+ }
190
+ blocks = next
191
+ provenance = prov
192
+ removed = rem
193
+ applied.push(layer.id)
194
+ }
195
+ return { graph: { ...base, blocks }, applied, conflicts, provenance, removed }
196
+ }
@@ -0,0 +1,156 @@
1
+ // Proposals: un injerto no muta el formulario; propone un parche. El anfitrión
2
+ // lo muestra como diff («antes → después»), lo aplica o lo descarta, y lo
3
+ // aplicado siempre se puede deshacer. Mismo flujo para la constancia fiscal,
4
+ // una sugerencia de precio o una sugerencia de Aby.
5
+ import { useCallback, useRef, useState } from 'react'
6
+ import { useTranslation } from 'react-i18next'
7
+ import { Button } from '@asteby/metacore-ui/primitives'
8
+ import type { Proposal } from './types'
9
+
10
+ export interface ProposalQueue {
11
+ pending: Proposal[]
12
+ /** Último parche aplicado, mientras se pueda deshacer. */
13
+ applied: Proposal | null
14
+ /** Entra a la cola (o se aplica directo si `apply: 'auto'`). */
15
+ push: (p: Proposal) => void
16
+ accept: (id: string) => void
17
+ discard: (id: string) => void
18
+ undo: () => void
19
+ }
20
+
21
+ /**
22
+ * Cola de propuestas sobre unos valores. `apply` recibe el parche a fusionar; para el
23
+ * deshacer se fusionan los valores previos de las claves tocadas.
24
+ */
25
+ export function useProposalQueue(
26
+ values: Record<string, unknown>,
27
+ apply: (patch: Record<string, unknown>) => void,
28
+ ): ProposalQueue {
29
+ const [pending, setPending] = useState<Proposal[]>([])
30
+ const [applied, setApplied] = useState<Proposal | null>(null)
31
+ const valuesRef = useRef(values)
32
+ valuesRef.current = values
33
+
34
+ const commit = useCallback(
35
+ (p: Proposal) => {
36
+ // El "antes" se toma al aplicar (el usuario pudo teclear desde que llegó la propuesta).
37
+ const previous: Record<string, unknown> = {}
38
+ for (const k of Object.keys(p.patch)) previous[k] = valuesRef.current[k]
39
+ apply(p.patch)
40
+ setApplied({ ...p, previous })
41
+ },
42
+ [apply],
43
+ )
44
+
45
+ const push = useCallback(
46
+ (p: Proposal) => {
47
+ if (p.apply === 'auto') commit(p)
48
+ else setPending((list) => [...list.filter((x) => x.graft !== p.graft), p])
49
+ },
50
+ [commit],
51
+ )
52
+ const pendingRef = useRef(pending)
53
+ pendingRef.current = pending
54
+ const appliedRef = useRef(applied)
55
+ appliedRef.current = applied
56
+ const accept = useCallback(
57
+ (id: string) => {
58
+ const p = pendingRef.current.find((x) => x.id === id)
59
+ if (p) commit(p)
60
+ setPending((list) => list.filter((x) => x.id !== id))
61
+ },
62
+ [commit],
63
+ )
64
+ const discard = useCallback((id: string) => setPending((list) => list.filter((x) => x.id !== id)), [])
65
+ const undo = useCallback(() => {
66
+ const a = appliedRef.current
67
+ if (a) apply(a.previous)
68
+ setApplied(null)
69
+ }, [apply])
70
+
71
+ return { pending, applied, push, accept, discard, undo }
72
+ }
73
+
74
+ const show = (v: unknown): string => {
75
+ if (v == null || v === '') return '—'
76
+ if (typeof v === 'object') return (v as { label?: string }).label ?? JSON.stringify(v)
77
+ return String(v)
78
+ }
79
+
80
+ export interface ProposalReviewProps {
81
+ queue: ProposalQueue
82
+ /** Etiqueta del campo (la del formulario del anfitrión). */
83
+ labelOf?: (key: string) => string
84
+ /** Valores actuales, para el «antes». */
85
+ values: Record<string, unknown>
86
+ }
87
+
88
+ /** Diff revisable de las propuestas pendientes + barra de deshacer de la última aplicada. */
89
+ export function ProposalReview({ queue, labelOf, values }: ProposalReviewProps) {
90
+ const { t } = useTranslation()
91
+ const label = (p: Proposal, k: string) => p.labels?.[k] ?? labelOf?.(k) ?? k
92
+ if (!queue.pending.length && !queue.applied) return null
93
+ return (
94
+ <div className="grid gap-2" data-loom-proposals="">
95
+ {queue.pending.map((p) => {
96
+ const keys = Object.keys(p.patch)
97
+ return (
98
+ <section
99
+ key={p.id}
100
+ aria-label={p.reason ?? t('loom.proposal.title', { defaultValue: 'Cambios propuestos' })}
101
+ data-loom-proposal={p.graft}
102
+ className="rounded-lg border bg-muted/40 p-3 text-sm"
103
+ >
104
+ <p className="font-medium">
105
+ {p.reason ?? t('loom.proposal.title', { defaultValue: 'Cambios propuestos' })}
106
+ </p>
107
+ <table className="mt-2 w-full text-xs">
108
+ <thead className="sr-only">
109
+ <tr>
110
+ <th>{t('loom.proposal.field', { defaultValue: 'Campo' })}</th>
111
+ <th>{t('loom.proposal.before', { defaultValue: 'Antes' })}</th>
112
+ <th>{t('loom.proposal.after', { defaultValue: 'Después' })}</th>
113
+ </tr>
114
+ </thead>
115
+ <tbody>
116
+ {keys.map((k) => {
117
+ const same = show(values[k]) === show(p.patch[k])
118
+ return (
119
+ <tr key={k} data-field={k} className={same ? 'text-muted-foreground' : undefined}>
120
+ <td className="py-0.5 pr-2 font-medium">{label(p, k)}</td>
121
+ <td className="py-0.5 pr-2 text-muted-foreground line-through decoration-muted-foreground/50">
122
+ {same ? '' : show(values[k])}
123
+ </td>
124
+ <td className="py-0.5">{show(p.patch[k])}</td>
125
+ </tr>
126
+ )
127
+ })}
128
+ </tbody>
129
+ </table>
130
+ <div className="mt-2 flex gap-2">
131
+ <Button type="button" size="sm" onClick={() => queue.accept(p.id)}>
132
+ {t('loom.proposal.apply', { defaultValue: 'Aplicar' })}
133
+ </Button>
134
+ <Button type="button" size="sm" variant="ghost" onClick={() => queue.discard(p.id)}>
135
+ {t('loom.proposal.discard', { defaultValue: 'Descartar' })}
136
+ </Button>
137
+ </div>
138
+ </section>
139
+ )
140
+ })}
141
+ {queue.applied ? (
142
+ <div role="status" className="flex items-center justify-between gap-2 rounded-lg border px-3 py-2 text-xs" data-loom-applied="">
143
+ <span>
144
+ {t('loom.proposal.applied', {
145
+ defaultValue: 'Se aplicaron {{count}} campos',
146
+ count: Object.keys(queue.applied.patch).length,
147
+ })}
148
+ </span>
149
+ <Button type="button" size="sm" variant="ghost" onClick={queue.undo}>
150
+ {t('loom.proposal.undo', { defaultValue: 'Deshacer' })}
151
+ </Button>
152
+ </div>
153
+ ) : null}
154
+ </div>
155
+ )
156
+ }
@@ -0,0 +1,69 @@
1
+ // LoomProvider — lo que el anfitrión sabe para resolver seams: los injertos que
2
+ // el SERVIDOR autorizó (respuesta de GET /api/ui/grafts, ver RFC 0005 §5), flags,
3
+ // ajustes de la organización y el canal de telemetría. Sin provider, <Seam> sólo
4
+ // monta injertos registrados en proceso (código local de confianza).
5
+ import { createContext, useContext, useMemo, useRef, type ReactNode } from 'react'
6
+ import type { GraftDef, LoomEvent } from './types'
7
+
8
+ export interface LoomConfig {
9
+ /** Injertos servidos por el servidor (ya filtrados por RBAC/ajustes/preset). */
10
+ grafts: readonly GraftDef[]
11
+ /**
12
+ * Si es true, sólo se montan injertos cuyo id está en `grafts` (los registrados en proceso
13
+ * sin autorización del servidor se explican como `not_granted`).
14
+ */
15
+ serverAuthoritative: boolean
16
+ flags?: ReadonlySet<string>
17
+ settings?: Readonly<Record<string, unknown>>
18
+ onEvent?: (e: LoomEvent) => void
19
+ /** Pinta el inspector de seams (desarrollo). */
20
+ inspect?: boolean
21
+ }
22
+
23
+ const Ctx = createContext<LoomConfig | null>(null)
24
+
25
+ export interface LoomProviderProps {
26
+ grafts?: readonly GraftDef[]
27
+ serverAuthoritative?: boolean
28
+ flags?: Iterable<string>
29
+ settings?: Readonly<Record<string, unknown>>
30
+ onEvent?: (e: LoomEvent) => void
31
+ inspect?: boolean
32
+ children?: ReactNode
33
+ }
34
+
35
+ export function LoomProvider({
36
+ grafts = [],
37
+ serverAuthoritative = false,
38
+ flags,
39
+ settings,
40
+ onEvent,
41
+ inspect = false,
42
+ children,
43
+ }: LoomProviderProps) {
44
+ const onEventRef = useRef(onEvent)
45
+ onEventRef.current = onEvent
46
+ const flagKey = flags ? [...flags].sort().join(',') : ''
47
+ const value = useMemo<LoomConfig>(
48
+ () => ({
49
+ grafts,
50
+ serverAuthoritative,
51
+ flags: new Set(flagKey ? flagKey.split(',') : []),
52
+ settings,
53
+ inspect,
54
+ onEvent: (e) => {
55
+ try {
56
+ onEventRef.current?.(e)
57
+ } catch {
58
+ /* un reporter roto no tumba al anfitrión */
59
+ }
60
+ },
61
+ }),
62
+ [grafts, serverAuthoritative, flagKey, settings, inspect],
63
+ )
64
+ return <Ctx.Provider value={value}>{children}</Ctx.Provider>
65
+ }
66
+
67
+ export function useLoomConfig(): LoomConfig | null {
68
+ return useContext(Ctx)
69
+ }
@@ -0,0 +1,136 @@
1
+ // Resolución pura de un seam: qué injertos se montan, en qué orden y por qué
2
+ // los demás no. Sin React: la usan <Seam>, el inspector y las pruebas de contrato.
3
+ import { satisfiesSdkRange } from '../slots/sdk-range'
4
+ import { getPart } from './store'
5
+ import type { DataClass, GraftDef, LoomEnv, ResolvedSeam, SeamContract, SkippedGraft } from './types'
6
+
7
+ const bare = (model: string) => model.split('.').pop() ?? model
8
+ const asList = (v: string | string[] | undefined) => (v == null ? [] : Array.isArray(v) ? v : [v])
9
+
10
+ function hasComponent(g: GraftDef): boolean {
11
+ if (g.component || g.load) return true
12
+ if (!g.part) return false
13
+ const p = getPart(g.part)
14
+ return !!(p && (p.component || p.load))
15
+ }
16
+
17
+ function check(g: GraftDef, contract: SeamContract, env: LoomEnv): SkippedGraft | null {
18
+ const skip = (reason: SkippedGraft['reason'], detail?: string): SkippedGraft => ({ graft: g, reason, detail })
19
+ if (env.granted && !env.granted.has(g.id)) return skip('not_granted', 'el servidor no lo listó para este usuario')
20
+ if (g.requires && satisfiesSdkRange(contract.version, g.requires) === false) {
21
+ return skip('version', `pide ${contract.id}@${g.requires}, el anfitrión publica ${contract.version}`)
22
+ }
23
+ const w = g.when
24
+ if (w) {
25
+ const missing = asList(w.permission).filter((p) => !env.can(p))
26
+ if (missing.length) return skip('permission', missing.join(', '))
27
+ if (w.anyPermission?.length && !w.anyPermission.some((p) => env.can(p))) {
28
+ return skip('permission', `alguno de ${w.anyPermission.join(', ')}`)
29
+ }
30
+ if (w.flag && !env.flags?.has(w.flag)) return skip('flag', w.flag)
31
+ if (w.setting) {
32
+ const v = env.settings?.[w.setting.key]
33
+ const ok = 'equals' in w.setting ? Object.is(v, w.setting.equals) : !!v
34
+ if (!ok) return skip('setting', w.setting.key)
35
+ }
36
+ if (w.model?.length) {
37
+ const m = env.model ? bare(env.model) : undefined
38
+ if (!m || !w.model.some((x) => bare(x) === m)) return skip('model', env.model ?? '(sin modelo)')
39
+ }
40
+ if (w.mode?.length && (!env.mode || !w.mode.includes(env.mode))) return skip('mode', env.mode ?? '(sin modo)')
41
+ }
42
+ if (!hasComponent(g)) return skip('no_component', g.part ? `Part ${g.part} no registrado` : undefined)
43
+ return null
44
+ }
45
+
46
+ /** Orden canónico: `order` ascendente, luego orden de entrada (estable). */
47
+ export function resolveSeam(contract: SeamContract, candidates: readonly GraftDef[], env: LoomEnv): ResolvedSeam {
48
+ const mounted: GraftDef[] = []
49
+ const skipped: SkippedGraft[] = []
50
+ for (const g of candidates) {
51
+ if (g.seam !== contract.id) continue
52
+ const s = check(g, contract, env)
53
+ if (s) skipped.push(s)
54
+ else mounted.push(g)
55
+ }
56
+ const indexed = mounted.map((g, i) => ({ g, i }))
57
+ indexed.sort((a, b) => (a.g.order ?? 0) - (b.g.order ?? 0) || a.i - b.i)
58
+ return { mounted: indexed.map((x) => x.g), skipped }
59
+ }
60
+
61
+ /** `fiscal_data.*` cubre `fiscal_data.rfc`; un nombre exacto, sólo a sí mismo. */
62
+ export function matchesWrite(key: string, patterns: readonly string[]): boolean {
63
+ return patterns.some((p) => (p.endsWith('.*') ? key.startsWith(p.slice(0, -1)) : p === key))
64
+ }
65
+
66
+ /**
67
+ * Atenúa un parche: sólo pasan claves que el injerto declaró en `writes` Y que el seam
68
+ * acepta (`writable`). Sin `writes`, el injerto no escribe nada.
69
+ */
70
+ export function attenuatePatch(
71
+ patch: Record<string, unknown>,
72
+ writes: readonly string[] | undefined,
73
+ writable: ReadonlySet<string> | undefined,
74
+ ): { allowed: Record<string, unknown>; dropped: string[] } {
75
+ const allowed: Record<string, unknown> = {}
76
+ const dropped: string[] = []
77
+ for (const [k, v] of Object.entries(patch ?? {})) {
78
+ if (writable && writable.has(k) && writes && matchesWrite(k, writes)) allowed[k] = v
79
+ else dropped.push(k)
80
+ }
81
+ return { allowed, dropped }
82
+ }
83
+
84
+ /** Sólo las lentes declaradas, congeladas (una lente no declarada no existe para el injerto). */
85
+ export function projectLenses(
86
+ lenses: Readonly<Record<string, unknown>>,
87
+ reads: readonly string[] | undefined,
88
+ ): Readonly<Record<string, unknown>> {
89
+ const out: Record<string, unknown> = {}
90
+ for (const k of reads ?? []) if (k in lenses) out[k] = freeze(snapshot(lenses[k]))
91
+ return Object.freeze(out)
92
+ }
93
+
94
+ /**
95
+ * Copia para congelar sin tocar el estado del anfitrión. Objetos planos y arrays se copian en
96
+ * profundidad; el resto (File, Date, instancias) pasa tal cual y no se congela.
97
+ */
98
+ function snapshot<T>(v: T): T {
99
+ if (Array.isArray(v)) return v.map(snapshot) as T
100
+ if (v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) {
101
+ const o: Record<string, unknown> = {}
102
+ for (const [k, x] of Object.entries(v as object)) o[k] = snapshot(x)
103
+ return o as T
104
+ }
105
+ return v
106
+ }
107
+
108
+ function freeze<T>(v: T): T {
109
+ if (v && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype) return v
110
+ if (v && typeof v === 'object' && !Object.isFrozen(v)) {
111
+ Object.freeze(v)
112
+ for (const x of Object.values(v as object)) freeze(x)
113
+ }
114
+ return v
115
+ }
116
+
117
+ const SENSITIVE: ReadonlySet<DataClass> = new Set<DataClass>(['pii', 'pii.fiscal', 'secret'])
118
+
119
+ /** Clases sensibles que un injerto lee: si hay alguna, sus errores salen redactados. */
120
+ export function sensitiveClasses(contract: SeamContract, reads: readonly string[] | undefined): DataClass[] {
121
+ const out = new Set<DataClass>()
122
+ for (const r of reads ?? []) {
123
+ const c = contract.lenses[r]
124
+ if (c && SENSITIVE.has(c)) out.add(c)
125
+ }
126
+ return [...out]
127
+ }
128
+
129
+ /**
130
+ * Mensaje apto para telemetría. Un injerto que leyó datos sensibles puede haberlos metido en el
131
+ * mensaje de error (p. ej. `RFC XAXX010101000 inválido`): se sustituye entero.
132
+ */
133
+ export function redactMessage(message: string, classes: readonly DataClass[]): string {
134
+ if (!classes.length) return message
135
+ return `[redactado: ${classes.join(',')}]`
136
+ }