@mayder/devibe 0.0.0-stage → 0.2.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.
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # DeVibe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Vibe code checker.** Entiende qué escribió tu IA y revisa sus cambios en tu repo local. Elige un punto de entrada, sigue el recorrido y abre el fragmento que explica cada paso.
4
+
5
+ [Sitio de DeVibe](https://devibe-xi.vercel.app/) · [Demo pública](https://devibe-xi.vercel.app/demo/) · [Paquete en npm](https://www.npmjs.com/package/@mayder/devibe)
6
+
7
+ ## Probar la demo
8
+
9
+ Requiere Node.js 24 o posterior.
10
+
11
+ ```sh
12
+ npx @mayder/devibe demo
13
+ ```
14
+
15
+ La demo de Support Desk compara dos versiones de `POST /tickets`. Un título de solo espacios pasa de guardarse a devolver `422`. Puedes ver el antes y el después, la línea que evita la escritura y el recorrido desde el mapa isométrico.
16
+
17
+ ## Así se ve
18
+
19
+ **Entender** muestra la acción, las piezas del recorrido y el código que respalda el paso seleccionado.
20
+
21
+ ![Vista Entender de DeVibe en modo claro, con el mapa isométrico y el código de la validación](https://raw.githubusercontent.com/MayderC/devibe/main/docs/learn.png)
22
+
23
+ **Ver cambios** sitúa el código anterior y el actual junto al efecto observado.
24
+
25
+ ![Vista Ver cambios de DeVibe en modo oscuro, con la condición nueva y el código resaltado](https://raw.githubusercontent.com/MayderC/devibe/main/docs/diff.png)
26
+
27
+ ## Abrir un repositorio
28
+
29
+ Desde la carpeta del repo, con Git y la CLI de Graphify Labs disponibles:
30
+
31
+ ```sh
32
+ npx @mayder/devibe open .
33
+ ```
34
+
35
+ DeVibe ejecuta Graphify con `--code-only` o puede reutilizar un grafo existente de la misma versión con `--graph graphify-out/graph.json`. **Entender** muestra las llamadas extraídas e inferidas con sus referencias cuando están disponibles. **Ver cambios** compara `HEAD` con el árbol de trabajo. Usa `--base <ref>` para elegir otra base y `--no-browser` para imprimir la URL sin abrir el navegador. [Graphify Labs](https://github.com/Graphify-Labs/graphify)
36
+
37
+ ```sh
38
+ npx @mayder/devibe open . --base main
39
+ ```
40
+
41
+ DeVibe se sirve en `127.0.0.1`. Graphify y Git se ejecutan localmente. La demo funciona con Node.js y npm, y el análisis automático de un proyecto requiere Graphify. Para usar un ejecutable en otra ubicación, define `ATLAS_GRAPHIFY` con su ruta.
42
+
43
+ El visor ofrece tema claro verde lima y tema oscuro. El tema de código **DeVibe** viene seleccionado y se puede cambiar por un tema claro u oscuro. El resaltado funciona localmente en fragmentos y diffs. [Highlight.js](https://highlightjs.org/)
44
+
45
+ ## Estado
46
+
47
+ DeVibe explora llamadas estáticas y cambios locales. En un repo abierto con Graphify puedes alternar entre **Isométrico**, **Anatomy** y **Pasos**. Las explicaciones de funciones con IA siguen en el plan de Learn.
package/bin/devibe.mjs ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../dist/cli.js'
3
+
4
+ runCli().catch(error => {
5
+ console.error(error instanceof Error ? error.message : error)
6
+ process.exitCode = 1
7
+ })
@@ -0,0 +1,146 @@
1
+ import { boxCorners, cylinder, depthOf, fitProjection, iso, pathOf, slabOf, solidSvg } from './vendor/anatomy/iso-kit.mjs'
2
+
3
+ const cameras = { diagonal: [37, 33, -50], opposite: [53, 33, 50], high: [45, 57, -30] }
4
+ const symbols = {
5
+ function: ['Función', 'M15 4H12C10 4 9 6 9 8L7 16C7 18 6 20 4 20H2M5 11H14'],
6
+ method: ['Método', 'M3 5H9V11H3ZM15 13H21V19H15ZM6 11V16H15M14 5H21M14 8H19'],
7
+ class: ['Clase', 'M3 5L12 2L21 5L12 8ZM3 5V14L12 18L21 14V5M12 8V18'],
8
+ module: ['Módulo', 'M3 6H10L12 8H21V19H3ZM3 12H21'],
9
+ database: ['Base de datos', 'M4 6C4 2 20 2 20 6S4 10 4 6ZM4 6V18C4 22 20 22 20 18V6M4 12C4 16 20 16 20 12'],
10
+ network: ['Red', 'M3 8Q12 0 21 8M6 12Q12 6 18 12M9 16Q12 13 15 16M12 19V21'],
11
+ symbol: ['Símbolo', 'M8 5L2 12L8 19M16 5L22 12L16 19M14 4L10 20'],
12
+ }
13
+
14
+ function hasPath(edges, start, target) {
15
+ const pending = [start]
16
+ const visited = new Set()
17
+ while (pending.length) {
18
+ const next = pending.pop()
19
+ if (next === target) return true
20
+ if (visited.has(next)) continue
21
+ visited.add(next)
22
+ for (const edge of edges) if (edge.from.id === next) pending.push(edge.to.id)
23
+ }
24
+ return false
25
+ }
26
+
27
+ export function layoutAnatomy(flow, entry) {
28
+ const edges = flow.flatMap((step, index) => step.call ? [{ ...step.call, index, provenance: step.provenance }] : [])
29
+ const root = edges.find(edge => edge.from.id === entry)?.from
30
+ if (!root) return { nodes: [], edges: [] }
31
+
32
+ const nodes = new Map([[entry, { ...root, level: 0 }]])
33
+ for (const level of [1, 2]) {
34
+ for (const { from, to } of edges) {
35
+ if (nodes.get(from.id)?.level === level - 1 && !nodes.has(to.id)) nodes.set(to.id, { ...to, level })
36
+ }
37
+ }
38
+ for (const level of [0, 1, 2]) {
39
+ const column = [...nodes.values()].filter(node => node.level === level)
40
+ column.forEach((node, index) => {
41
+ node.row = index - (column.length - 1) / 2
42
+ node.indices = edges.filter(edge => edge.to.id === node.id || edge.from.id === node.id).map(edge => edge.index)
43
+ node.index = edges.find(edge => level ? edge.to.id === node.id : edge.from.id === node.id).index
44
+ })
45
+ }
46
+ const visible = edges.filter(edge => nodes.has(edge.from.id) && nodes.has(edge.to.id))
47
+ for (const edge of visible) {
48
+ edge.cycle = nodes.get(edge.to.id).level <= nodes.get(edge.from.id).level && hasPath(visible, edge.to.id, edge.from.id)
49
+ }
50
+ return { nodes: [...nodes.values()], edges: visible }
51
+ }
52
+
53
+ function drawGrid(plans, projection) {
54
+ const lowX = Math.min(...plans.map(plan => plan.x)) - 44
55
+ const highX = Math.max(...plans.map(plan => plan.x)) + 44
56
+ const lowY = Math.min(...plans.map(plan => plan.y)) - 44
57
+ const highY = Math.max(...plans.map(plan => plan.y)) + 44
58
+ const line = corners => pathOf(corners.map(corner => iso([...corner, -2], projection)))
59
+ let grid = `<path class="ar-floor" d="${line([[lowX, lowY], [highX, lowY], [highX, highY], [lowX, highY], [lowX, lowY]])}"/>`
60
+ for (let x = lowX + 24; x < highX; x += 24) grid += `<path class="ar-gridline" d="${line([[x, lowY], [x, highY]])}"/>`
61
+ for (let y = lowY + 24; y < highY; y += 24) grid += `<path class="ar-gridline" d="${line([[lowX, y], [highX, y]])}"/>`
62
+ return grid
63
+ }
64
+
65
+ export function renderGraphMap(stage, flow, entry, { view, camera }) {
66
+ const { nodes, edges } = layoutAnatomy(flow, entry)
67
+ if (!nodes.length) return undefined
68
+
69
+ const classic = view === 'iso'
70
+ const [azimuth, elevation, slope] = classic ? cameras[camera] ?? cameras.diagonal : [45, 42, 10]
71
+ const angle = azimuth * Math.PI / 180
72
+ const width = 640
73
+ const rows = Math.max(...[0, 1, 2].map(level => nodes.filter(node => node.level === level).length))
74
+ const height = Math.max(classic ? 300 : 280, rows * 73 + 112)
75
+ const plans = nodes.map(node => {
76
+ const across = node.level * 175
77
+ const down = node.row * 112 + node.level * slope
78
+ return { ...node, x: across * Math.sin(angle) + down * Math.cos(angle), y: -across * Math.cos(angle) + down * Math.sin(angle), w: 65, d: 51, r: classic ? 1 : 5 }
79
+ })
80
+ const byId = new Map(plans.map(node => [node.id, node]))
81
+ const points = plans.flatMap(plan => boxCorners(plan, 0, 34))
82
+ const projection = fitProjection(points, width, height, { azimuth, elevation, pad: 64 })
83
+ const svg = stage.querySelector('svg')
84
+ const pins = stage.querySelector('.ar-anatomy-pins')
85
+ const connections = edges.map(({ from, to, index, provenance, cycle }) => {
86
+ const source = byId.get(from.id)
87
+ const target = byId.get(to.id)
88
+ const [sx, sy] = iso([source.x, source.y, 4], projection)
89
+ const [tx, ty] = iso([target.x, target.y, 4], projection)
90
+ const direction = Math.sign(tx - sx) || 1
91
+ const start = [sx + direction * 26, sy]
92
+ const end = [tx - direction * 36, ty]
93
+ const middle = (start[0] + end[0]) / 2
94
+ const route = cycle
95
+ ? source === target
96
+ ? `M ${sx + 20} ${sy} c 48 26 50 -56 13 -42`
97
+ : `M ${start.join(' ')} Q ${middle} ${Math.min(sy, ty) - 94} ${end.join(' ')}`
98
+ : pathOf(classic ? [start, end] : [start, [middle, sy], [middle, ty], end])
99
+ const classes = ['ar-anatomy-edge', provenance !== 'extracted' && 'ar-anatomy-uncertain', cycle && 'ar-anatomy-cycle'].filter(Boolean).join(' ')
100
+ return `<g class="${classes}" data-anatomy-edge="${index}"><path class="ar-anatomy-wire" d="${route}" marker-end="url(#ar-anatomy-arrow)"/><path class="ar-anatomy-hit" data-anatomy-edge="${index}" d="${route}"/></g>`
101
+ }).join('')
102
+ plans.sort((a, b) => depthOf([a.x, a.y, 0], projection) - depthOf([b.x, b.y, 0], projection))
103
+ const objects = plans.map(plan => {
104
+ const kind = Object.hasOwn(symbols, plan.kind) ? plan.kind : 'symbol'
105
+ const base = solidSvg(slabOf(plan, 0, 6, projection, 5, 1), { className: 'ar-anatomy-base' })
106
+ const slab = (w, d, z, h) => solidSvg(slabOf({ ...plan, w, d }, z, h, projection, 5, 1))
107
+ const disk = (z, h) => solidSvg(cylinder(plan.x, plan.y, 20, z, h, projection, 32, 1))
108
+ const [body, top] = {
109
+ function: () => [slab(46, 39, 6, 19) + slab(36, 28, 25, 6), 31],
110
+ method: () => [slab(43, 34, 6, 12) + slab(29, 24, 18, 10), 28],
111
+ class: () => [slab(48, 40, 6, 7) + slab(45, 36, 13, 8) + slab(41, 32, 21, 9), 30],
112
+ module: () => [slab(49, 42, 6, 14) + slab(35, 26, 20, 6), 26],
113
+ database: () => [disk(6, 10) + disk(16, 10) + disk(26, 10), 36],
114
+ network: () => [slab(44, 33, 6, 10) + slab(30, 24, 16, 16), 32],
115
+ symbol: () => [slab(40, 34, 6, 14), 20],
116
+ }[kind]()
117
+ const [x, y] = iso([plan.x, plan.y, top + 4], projection)
118
+ const pictogram = `<g class="ar-anatomy-glyph" transform="translate(${x - 10} ${y - 12}) scale(.83)"><circle cx="12" cy="12" r="15"/><path d="${symbols[kind][1]}"/></g>`
119
+ return `<g class="ar-anatomy-object" data-kind="${kind}" data-anatomy-indices="${plan.indices.join(' ')}" ${plan.level === 0 ? 'data-anatomy-root' : ''}>${base}${body}${pictogram}</g>`
120
+ }).join('')
121
+
122
+ stage.style.aspectRatio = `${width} / ${height}`
123
+ stage.dataset.graphView = view
124
+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`)
125
+ svg.innerHTML = `<defs><marker id="ar-anatomy-arrow" markerWidth="6" markerHeight="6" refX="5" refY="3" orient="auto"><path d="M0 0L6 3L0 6Z" fill="context-stroke"/></marker></defs>${classic ? drawGrid(plans, projection) : ''}${connections}${objects}`
126
+ pins.replaceChildren(...nodes.map(node => {
127
+ const plan = byId.get(node.id)
128
+ const [x, y] = iso([plan.x, plan.y, 0], projection)
129
+ const button = document.createElement('button')
130
+ button.type = 'button'
131
+ button.dataset.step = node.index
132
+ button.dataset.anatomyIndices = node.indices.join(' ')
133
+ button.style.left = `${x / width * 100}%`
134
+ button.style.top = `${(y + 21) / height * 100}%`
135
+ const [kind] = Object.hasOwn(symbols, node.kind) ? symbols[node.kind] : symbols.symbol
136
+ button.title = `${node.label} · ${kind}`
137
+ const caption = document.createElement('strong')
138
+ caption.textContent = node.label
139
+ const role = document.createElement('small')
140
+ role.textContent = node.level === 0 ? `Entrada · ${kind.toLowerCase()}` : kind
141
+ button.append(caption, role)
142
+ if (node.level === 0) button.dataset.anatomyRoot = ''
143
+ return button
144
+ }))
145
+ return edges
146
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,50 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { parseArgs } from 'node:util'
3
+ import { openGraphProject } from './graphify.js'
4
+ import { startServer, } from './server.js'
5
+ import { supportDesk } from './support-desk.js'
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+ function openBrowser(url ) {
14
+ const options = process.platform === 'win32'
15
+ ? { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] }
16
+ : { command: process.platform === 'darwin' ? 'open' : 'xdg-open', args: [url] }
17
+ const child = spawn(options.command, options.args, { stdio: 'ignore', windowsHide: true })
18
+ child.on('error', () => console.error(`Abre DeVibe en ${url}`))
19
+ child.unref()
20
+ }
21
+
22
+ export async function runCli(preset ) {
23
+ const usage = `Uso:
24
+ devibe demo [--no-browser]
25
+ devibe open [ruta] [--graph archivo.json] [--base ref] [--no-browser]${preset ? `\n devibe ${preset.name} <ruta> [--no-browser]` : ''}`
26
+ const { positionals, values } = parseArgs({
27
+ allowPositionals: true,
28
+ options: { help: { type: 'boolean', short: 'h' }, 'no-browser': { type: 'boolean' }, graph: { type: 'string' }, base: { type: 'string' } },
29
+ })
30
+ if (values.help) {
31
+ console.log(usage)
32
+ return
33
+ }
34
+ const [command = 'demo', path = '.'] = positionals
35
+ if (!['demo', 'open', preset?.name].includes(command) || positionals.length > 2 || (command === 'demo' && positionals.length > 1)
36
+ || (command !== 'open' && (values.graph !== undefined || values.base !== undefined))) {
37
+ throw new Error(usage)
38
+ }
39
+ if (command === 'open') console.log(values.graph ? 'DeVibe · Leyendo grafo y cambios locales…' : 'DeVibe · Extrayendo llamadas con Graphify…')
40
+ const inspection = command === 'open' ? await openGraphProject(path, values)
41
+ : command === preset?.name ? await preset.open(path) : { atlasCase: await supportDesk() }
42
+ const { atlasCase, ...routes } = inspection
43
+ const { server, url } = await startServer(atlasCase, routes)
44
+ console.log(`DeVibe · ${atlasCase.project}`)
45
+ console.log(url)
46
+ console.log('Ctrl+C para cerrar DeVibe.')
47
+ process.once('SIGINT', () => server.close())
48
+ process.once('SIGTERM', () => server.close())
49
+ if (!values['no-browser']) openBrowser(url)
50
+ }
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2
+ <rect width="32" height="32" rx="8" fill="#e9f5ba"/>
3
+ <path fill="#355413" fill-rule="evenodd" d="M9 7h6c6 0 9 3.7 9 9s-3 9-9 9H9zm4 3.5v11h2c3.3 0 5-2 5-5.5s-1.7-5.5-5-5.5z"/>
4
+ </svg>
package/dist/diff.js ADDED
@@ -0,0 +1,61 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ export function parseChangedFiles(output ) {
21
+ const parts = output.split('\0')
22
+ const entries = []
23
+ for (let i = 0; i < parts.length && parts[i];) {
24
+ const status = parts[i++]
25
+ const first = parts[i++]
26
+ if (/^[RC]/.test(status)) {
27
+ entries.push({ status, previous: first, path: parts[i++] })
28
+ } else {
29
+ entries.push({ status, path: first })
30
+ }
31
+ }
32
+ return entries
33
+ }
34
+
35
+ export function parsePatch(file , output ) {
36
+ const patch = { file, hunks: [], summary: [] }
37
+ let hunk
38
+ let before = 0
39
+ let after = 0
40
+ for (const line of output.replace(/\n$/, '').split('\n')) {
41
+ const header = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line)
42
+ if (header) {
43
+ hunk = { header: line, lines: [] }
44
+ patch.hunks.push(hunk)
45
+ before = Number(header[1])
46
+ after = Number(header[2])
47
+ } else if (!hunk || line.startsWith('diff --git ')) {
48
+ hunk = undefined
49
+ if (/^(Binary files|old mode|new mode|similarity index|rename (?:from|to) )/.test(line)) patch.summary.push(line)
50
+ } else if (line.startsWith('+')) {
51
+ hunk.lines.push({ kind: 'add', after: after++, text: line.slice(1) })
52
+ } else if (line.startsWith('-')) {
53
+ hunk.lines.push({ kind: 'remove', before: before++, text: line.slice(1) })
54
+ } else if (line.startsWith(' ')) {
55
+ hunk.lines.push({ kind: 'context', before: before++, after: after++, text: line.slice(1) })
56
+ } else if (line.startsWith('\\')) {
57
+ hunk.lines.push({ kind: 'note', text: line })
58
+ }
59
+ }
60
+ return patch
61
+ }
@@ -0,0 +1,155 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { access, mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises'
3
+ import { homedir, tmpdir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+
7
+ import { excerpt, LocalGitSource } from './source.js'
8
+
9
+ const exec = promisify(execFile)
10
+
11
+
12
+
13
+
14
+
15
+ const declaredKinds = new Set(['function', 'method', 'class', 'module', 'database', 'network'])
16
+
17
+ function symbolKind(label , declared ) {
18
+ if (declaredKinds.has(declared)) return declared
19
+ if (/^(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis):\/\//i.test(label)) return 'database'
20
+ if (/^https?:\/\//i.test(label)) return 'network'
21
+ if (/^(?:[\w$]+)?\.[\w$]+\(\)$/.test(label)) return 'method'
22
+ if (/^[\w$]+\(\)$/.test(label)) return 'function'
23
+ if (/\.[cm]?[jt]sx?$|\.(?:py|rs|go|java|rb|php|cpp|cs)$/i.test(label)) return 'module'
24
+ return 'symbol'
25
+ }
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+ export function parseGraph(value ) {
36
+ if (!value || typeof value !== 'object' || !('nodes' in value) || !('links' in value) || !Array.isArray(value.nodes) || !Array.isArray(value.links)) {
37
+ throw new Error('El grafo debe contener los campos nodes y links de Graphify.')
38
+ }
39
+ const nodes = new Map ()
40
+ for (const node of value.nodes) {
41
+ if (!node || typeof node.id !== 'string' || typeof node.label !== 'string') continue
42
+ nodes.set(node.id, { id: node.id, label: node.label, kind: symbolKind(node.label, node.kind ?? node.type), file: typeof node.source_file === 'string' ? node.source_file : undefined })
43
+ }
44
+ const outgoing = new Map ()
45
+ for (const edge of value.links) {
46
+ if (!edge || edge.relation !== 'calls' || !nodes.has(edge.source) || !nodes.has(edge.target)) continue
47
+ const location = typeof edge.source_location === 'string' ? /^L(\d+)\b/.exec(edge.source_location) : null
48
+ const provenance = edge.confidence === 'EXTRACTED' ? 'extracted' : edge.confidence === 'INFERRED' ? 'inferred' : 'unknown'
49
+ const entry = { source: edge.source, target: edge.target, file: typeof edge.source_file === 'string' ? edge.source_file : undefined, line: location ? Number(location[1]) : undefined, provenance }
50
+ const relations = outgoing.get(entry.source) ?? []
51
+ relations.push(entry)
52
+ outgoing.set(entry.source, relations)
53
+ }
54
+ return { nodes, outgoing }
55
+ }
56
+
57
+ async function extract(root ) {
58
+ const installed = join(homedir(), '.local', 'bin', process.platform === 'win32' ? 'graphify.exe' : 'graphify')
59
+ const executable = process.env.ATLAS_GRAPHIFY || await access(installed).then(() => installed, () => process.platform === 'win32' ? 'graphify.exe' : 'graphify')
60
+ const tempRoot = resolve(tmpdir())
61
+ const temp = await mkdtemp(join(tempRoot, 'atlas-graph-'))
62
+ try {
63
+ await exec(executable, ['extract', '.', '--code-only', '--out', temp], {
64
+ cwd: root, env: { ...process.env, GRAPHIFY_BACKEND: 'none' }, windowsHide: true, maxBuffer: 4 * 1024 * 1024,
65
+ })
66
+ return await readFile(join(temp, 'graphify-out', 'graph.json'), 'utf8')
67
+ } catch (cause) {
68
+ const detail = cause instanceof Error ? ` ${cause.message}` : ''
69
+ throw new Error(`Graphify Labs no pudo extraer el código. Instala la CLI con uv tool install graphifyy, indica ATLAS_GRAPHIFY o usa --graph con un grafo existente.${detail}`, { cause })
70
+ } finally {
71
+ if (dirname(temp) === tempRoot && basename(temp).startsWith('atlas-graph-')) await rm(temp, { recursive: true, force: true })
72
+ }
73
+ }
74
+
75
+ function inside(root , file ) {
76
+ const path = relative(root, resolve(root, file))
77
+ return path && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path) ? path.replaceAll(sep, '/') : undefined
78
+ }
79
+
80
+ export async function openGraphProject(path , options = {}) {
81
+ const root = await realpath(await new LocalGitSource(path).topLevel())
82
+ const git = new LocalGitSource(root)
83
+ const base = await git.resolve(options.base ?? 'HEAD')
84
+ const graphFile = options.graph ? resolve(options.graph) : undefined
85
+ const graphFolder = graphFile ? dirname(graphFile) : undefined
86
+ const referenceRoot = graphFolder && basename(graphFolder) === 'graphify-out' ? dirname(graphFolder) : root
87
+ const sourcePath = (file ) => inside(root, resolve(referenceRoot, file)) ?? inside(root, file)
88
+ const [raw, comparison] = await Promise.all([
89
+ graphFile ? readFile(graphFile, 'utf8') : extract(root), git.comparison(base),
90
+ ])
91
+ const { nodes, outgoing } = parseGraph(JSON.parse(raw.replace(/^\uFEFF/, '')))
92
+ const changed = new Map(comparison.files.map(file => [file.path, file]))
93
+ const entries = [...outgoing].map(([id, edges]) => {
94
+ const node = nodes.get(id)
95
+ const file = node.file ? sourcePath(node.file) ?? '' : ''
96
+ return { id, label: node.label, file, count: edges.length }
97
+ }).sort((a, b) => Number(changed.has(b.file)) - Number(changed.has(a.file)) || b.count - a.count || a.label.localeCompare(b.label))
98
+ const snapshots = new Map ()
99
+
100
+ async function readWorkingFile(file ) {
101
+ const real = await realpath(resolve(root, file))
102
+ if (!inside(root, real)) return undefined
103
+ const info = await stat(real)
104
+ if (!info.isFile() || info.size > 2 * 1024 * 1024) return undefined
105
+ const content = await readFile(real, 'utf8')
106
+ return content.includes('\0') ? undefined : content
107
+ }
108
+
109
+ async function evidence(edge ) {
110
+ const file = edge.file && sourcePath(edge.file)
111
+ if (!file || !edge.line) return undefined
112
+ if (!snapshots.has(file)) snapshots.set(file, readWorkingFile(file).catch(() => undefined))
113
+ const content = await snapshots.get(file)
114
+ if (!content) return undefined
115
+ const lines = content.replace(/\r?\n$/, '').split(/\r?\n/)
116
+ const focus = edge.line
117
+ if (focus > lines.length) return undefined
118
+ return excerpt(file, content, focus, Math.max(1, focus - 1), Math.min(lines.length, focus + 2))
119
+ }
120
+
121
+ async function flow(entry ) {
122
+ const direct = outgoing.get(entry)
123
+ if (!direct) return undefined
124
+ const next = direct.flatMap(edge => edge.target === entry ? [] : outgoing.get(edge.target) ?? [])
125
+ const sketch = [...new Set([...direct, ...next])].slice(0, 8)
126
+ return Promise.all(sketch.map(async edge => {
127
+ const from = nodes.get(edge.source)
128
+ const to = nodes.get(edge.target)
129
+ const after = await evidence(edge)
130
+ const file = after && changed.get(after.file)
131
+ const patch = file ? await comparison.read(file.path)?.catch(() => undefined) : undefined
132
+ const changedLine = patch?.hunks.some(hunk => hunk.lines.some(line => line.kind === 'add' && line.after === after?.focus))
133
+ const change = changedLine ? 'Línea añadida o editada' : file ? 'Archivo en el diff' : after ? 'Fuera del diff' : 'Sin ubicación verificada'
134
+ const description = `Graphify relaciona ${from.label} con ${to.label}.`
135
+ return {
136
+ title: to.label, symbol: `${from.label} → ${to.label}`, icon: 'arrow-right-left', change,
137
+ explanation: description, effect: `${description} ${change}.`, after, provenance: edge.provenance,
138
+ call: { from: { id: from.id, label: from.label, kind: from.kind }, to: { id: to.id, label: to.label, kind: to.kind } },
139
+ }
140
+ }))
141
+ }
142
+
143
+ const selected = entries[0]?.id ?? ''
144
+ const atlasCase = {
145
+ project: basename(root), area: options.graph ? 'Grafo importado' : 'Graphify local', title: 'Explorar llamadas del repo', environment: 'local',
146
+ summary: 'Hasta ocho conexiones de dos niveles. El grafo muestra relaciones estáticas.', base, head: 'árbol de trabajo',
147
+ diff: { title: 'Cambios locales', explanation: 'Git compara la revisión base con el árbol de trabajo. Cada archivo se puede abrir por separado.', files: comparison.files.map(file => file.path) },
148
+ review: { title: 'Revisión local', description: 'Selecciona una llamada y abre el diff del archivo.', criteria: [] },
149
+ labels: { request: '', database: '', response: '' },
150
+ places: { web: { title: '', role: '', change: '' }, api: { title: '', role: '', change: '' }, data: { title: '', role: '', change: '' }, error: { title: '', role: '', change: '' } },
151
+ flow: (await flow(selected)) ?? [], error: { title: '', explanation: '', effect: '' }, details: { symbol: [], call: [] },
152
+ graph: { entries, selected }, hasPatches: true,
153
+ }
154
+ return { atlasCase, flow, patch: comparison.read }
155
+ }
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2006, Ivan Sagalaev.
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.