@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/dist/server.js ADDED
@@ -0,0 +1,117 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { createServer } from 'node:http'
3
+
4
+
5
+
6
+ const uiPath = new URL('../../../work/atlas-review.html', import.meta.url)
7
+ const developmentHighlighterPath = new URL('../node_modules/@highlightjs/cdn-assets/highlight.min.js', import.meta.url)
8
+ const anatomyAssets = new Map([
9
+ ['/anatomy.mjs', new URL('./anatomy.mjs', import.meta.url)],
10
+ ['/vendor/anatomy/iso-kit.mjs', new URL('./vendor/anatomy/iso-kit.mjs', import.meta.url)],
11
+ ])
12
+
13
+ export function renderPage(atlasCase , markup ) {
14
+ const data = JSON.stringify(atlasCase).replaceAll('<', '\\u003c')
15
+ return `<!doctype html>
16
+ <html lang="es">
17
+ <head>
18
+ <meta charset="utf-8">
19
+ <meta name="viewport" content="width=device-width, initial-scale=1">
20
+ <title>DeVibe</title>
21
+ <link rel="icon" type="image/svg+xml" href="./devibe.svg">
22
+ <style>
23
+ :root { color-scheme: light dark; }
24
+ :root[data-devibe-theme="light"] { color-scheme: light; }
25
+ :root[data-devibe-theme="dark"] { color-scheme: dark; }
26
+ body { margin: 0; padding: clamp(8px, 2.5vw, 32px); background: light-dark(#eff4db, #141815); }
27
+ #atlas-review { max-width: 1160px; margin: 0 auto; }
28
+ #atlas-review i[data-lucide] { display: inline-grid; place-items: center; font-style: normal; }
29
+ #atlas-review i[data-lucide="route"]::before { content: '↳'; }
30
+ #atlas-review i[data-lucide="hard-drive"]::before { content: '▣'; }
31
+ #atlas-review i[data-lucide="git-commit-horizontal"]::before { content: '⊙'; }
32
+ #atlas-review i[data-lucide="file-code-2"]::before { content: '≡'; }
33
+ #atlas-review i[data-lucide="panels-top-left"]::before { content: '▤'; }
34
+ #atlas-review i[data-lucide="arrow-right-left"]::before { content: '⇄'; }
35
+ #atlas-review i[data-lucide="database"]::before { content: '▱'; }
36
+ #atlas-review i[data-lucide="messages-square"]::before { content: '□'; }
37
+ #atlas-review i[data-lucide="chevron-right"]::before { content: '›'; }
38
+ </style>
39
+ </head>
40
+ <body>
41
+ <script id="atlas-case-data" type="application/json">${data}</script>
42
+ <script src="./highlight.min.js"></script>
43
+ ${markup}
44
+ </body>
45
+ </html>`
46
+ }
47
+
48
+
49
+
50
+
51
+
52
+
53
+ export async function startServer(atlasCase , inspection = {}) {
54
+ const [viewer, highlighter, brandIcon] = await Promise.all([
55
+ readFile(new URL('./viewer.html', import.meta.url), 'utf8').catch(error => {
56
+ if (error.code !== 'ENOENT') throw error
57
+ return readFile(uiPath, 'utf8')
58
+ }),
59
+ readFile(new URL('./highlight.min.js', import.meta.url)).catch(error => {
60
+ if (error.code !== 'ENOENT') throw error
61
+ return readFile(developmentHighlighterPath)
62
+ }),
63
+ readFile(new URL('./devibe.svg', import.meta.url)).catch(error => {
64
+ if (error.code !== 'ENOENT') throw error
65
+ return readFile(new URL('../site/devibe.svg', import.meta.url))
66
+ }),
67
+ ])
68
+ const page = renderPage(atlasCase, viewer)
69
+ const json = JSON.stringify(atlasCase)
70
+ const server = createServer(async (request, response) => {
71
+ response.setHeader('Cache-Control', 'no-store')
72
+ response.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'")
73
+ const sendJson = (code , body ) => response.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8' }).end(JSON.stringify(body))
74
+ const target = new URL(`http://127.0.0.1${request.url?.startsWith('/') ? request.url : '/'}`)
75
+ if (request.method !== 'GET') {
76
+ response.writeHead(405, { Allow: 'GET' }).end()
77
+ } else if (target.pathname === '/') {
78
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(page)
79
+ } else if (target.pathname === '/highlight.min.js') {
80
+ response.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8' }).end(highlighter)
81
+ } else if (target.pathname === '/devibe.svg') {
82
+ response.writeHead(200, { 'Content-Type': 'image/svg+xml' }).end(brandIcon)
83
+ } else if (anatomyAssets.has(target.pathname)) {
84
+ try {
85
+ const code = await readFile(anatomyAssets.get(target.pathname) )
86
+ response.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8' }).end(code)
87
+ } catch {
88
+ response.writeHead(404).end()
89
+ }
90
+ } else if (target.pathname === '/api/case') {
91
+ response.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }).end(json)
92
+ } else if (target.pathname === '/api/flow' || target.pathname === '/api/patch') {
93
+ try {
94
+ const result = target.pathname === '/api/flow'
95
+ ? await inspection.flow?.(target.searchParams.get('entry') ?? '')
96
+ : await inspection.patch?.(target.searchParams.get('file') ?? '')
97
+ if (result) sendJson(200, result)
98
+ else sendJson(404, { error: 'Esta selección no está disponible.' })
99
+ } catch {
100
+ sendJson(500, { error: 'DeVibe no pudo leer esta selección. Vuelve a abrir el repositorio y prueba otra vez.' })
101
+ }
102
+ } else {
103
+ response.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Ruta no disponible')
104
+ }
105
+ })
106
+
107
+ await new Promise ((resolve, reject) => {
108
+ server.once('error', reject)
109
+ server.listen(0, '127.0.0.1', () => {
110
+ server.off('error', reject)
111
+ resolve()
112
+ })
113
+ })
114
+ const address = server.address()
115
+ if (!address || typeof address === 'string') throw new Error('No se pudo resolver la URL local de DeVibe.')
116
+ return { server, url: `http://127.0.0.1:${address.port}` }
117
+ }
package/dist/source.js ADDED
@@ -0,0 +1,87 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { readFile } from 'node:fs/promises'
3
+ import { resolve } from 'node:path'
4
+ import { promisify } from 'node:util'
5
+
6
+ import { parseChangedFiles, parsePatch } from './diff.js'
7
+
8
+
9
+ const exec = promisify(execFile)
10
+
11
+ export function excerpt(file , source , focus , start = focus, end = focus) {
12
+ const lines = source.replace(/\r?\n$/, '').split(/\r?\n/)
13
+ if (start < 1 || start > focus || focus > end || end > lines.length) {
14
+ throw new Error(`No se encontró la referencia ${file}:${focus} en el rango ${start}–${end}.`)
15
+ }
16
+ return { file, start, focus, lines: lines.slice(start - 1, end) }
17
+ }
18
+
19
+ export async function readExample(snapshot , file ) {
20
+ return readFile(new URL(`../examples/support-desk/${snapshot}/${file}`, import.meta.url), 'utf8')
21
+ }
22
+
23
+ export class LocalGitSource {
24
+ root
25
+
26
+ constructor(path ) {
27
+ this.root = resolve(path)
28
+ }
29
+
30
+ async #git(...args ) {
31
+ try {
32
+ const { stdout } = await exec('git', args, {
33
+ cwd: this.root,
34
+ encoding: 'utf8',
35
+ maxBuffer: 3 * 1024 * 1024,
36
+ windowsHide: true,
37
+ })
38
+ return stdout
39
+ } catch (cause) {
40
+ throw new Error(`Git no pudo ejecutar ${args[0]} en ${this.root}. ${cause instanceof Error ? cause.message : ''}`, { cause })
41
+ }
42
+ }
43
+
44
+ async resolve(ref ) {
45
+ const sha = (await this.#git('rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`)).trim()
46
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha)) throw new Error(`Revisión Git inválida: ${ref}`)
47
+ return sha
48
+ }
49
+
50
+ readFile(commit , file ) {
51
+ return this.#git('show', '--no-ext-diff', '--no-textconv', `${commit}:${file}`)
52
+ }
53
+
54
+ async topLevel() {
55
+ return (await this.#git('rev-parse', '--show-toplevel')).trim()
56
+ }
57
+
58
+ async comparison(base , head ) {
59
+ const revisions = head ? [base, head] : [base]
60
+ const diffFlags = ['--no-ext-diff', '--no-textconv', '--no-color', '--find-renames']
61
+ const files = parseChangedFiles(await this.#git('diff', ...diffFlags, '--name-status', '-z', ...revisions, '--'))
62
+ if (!head) {
63
+ const untracked = (await this.#git('ls-files', '--others', '--exclude-standard', '-z')).split('\0').filter(Boolean)
64
+ for (const path of untracked) files.push({ status: '?', path })
65
+ }
66
+ const entries = new Map(files.map(file => [file.path, file]))
67
+ const snapshots = new Map ()
68
+ const read = (path ) => {
69
+ const file = entries.get(path)
70
+ if (!file) return undefined
71
+ if (file.status === '?') return Promise.resolve({ file, hunks: [], summary: ['Archivo sin seguimiento. Git todavía no lo incluye en el diff.'] })
72
+ let pending = snapshots.get(path)
73
+ if (!pending) {
74
+ pending = this.#patch(diffFlags, revisions, file)
75
+ snapshots.set(path, pending)
76
+ }
77
+ return pending
78
+ }
79
+ return { files, read }
80
+ }
81
+
82
+ async #patch(flags , revisions , file ) {
83
+ const paths = file.previous ? [file.previous, file.path] : [file.path]
84
+ const output = await this.#git('--literal-pathspecs', 'diff', ...flags, '--patch', '--unified=3', ...revisions, '--', ...paths)
85
+ return parsePatch(file, output)
86
+ }
87
+ }
@@ -0,0 +1,80 @@
1
+
2
+ import { excerpt, readExample } from './source.js'
3
+
4
+ export async function supportDesk() {
5
+ const [beforeRoute, afterRoute, beforeService, afterService] = await Promise.all([
6
+ readExample('before', 'route.ts'),
7
+ readExample('after', 'route.ts'),
8
+ readExample('before', 'ticket-service.ts'),
9
+ readExample('after', 'ticket-service.ts'),
10
+ ])
11
+
12
+ const flow = [
13
+ {
14
+ title: 'Recibir el ticket', symbol: 'POST /tickets', icon: 'panels-top-left', change: 'Misma entrada',
15
+ explanation: 'La ruta lee el JSON y requiere un título de tipo texto.',
16
+ effect: 'La comprobación inicial del tipo se conserva.',
17
+ before: excerpt('route.ts', beforeRoute, 4, 3, 7), after: excerpt('route.ts', afterRoute, 4, 3, 7),
18
+ },
19
+ {
20
+ title: 'Validar el título', symbol: 'createTicket(title, store)', icon: 'arrow-right-left', change: 'Validación nueva',
21
+ explanation: 'La ruta llama al servicio. El servicio rechaza títulos vacíos o formados solo por espacios.',
22
+ effect: 'Antes el servicio pasaba directamente al escritor. Ahora comprueba el título antes de hacerlo.',
23
+ before: excerpt('ticket-service.ts', beforeService, 6, 5, 7), after: excerpt('ticket-service.ts', afterService, 6, 5, 10),
24
+ },
25
+ {
26
+ title: 'Guardar el ticket', symbol: 'TicketStore.insert(title)', icon: 'database', change: 'Escritura condicionada',
27
+ explanation: 'El servicio llama a la interfaz de almacenamiento cuando el título supera la validación.',
28
+ effect: 'La llamada a insert sigue presente. El retorno anticipado evita que se ejecute con un título en blanco.',
29
+ before: excerpt('ticket-service.ts', beforeService, 6, 5, 7), after: excerpt('ticket-service.ts', afterService, 10, 5, 11),
30
+ },
31
+ {
32
+ title: 'Responder con el ticket', symbol: 'Response.json(ticket, { status: 201 })', icon: 'messages-square', change: 'Nueva respuesta de error',
33
+ explanation: 'La ruta devuelve 201 con el ticket creado. Si el servicio devuelve null, devuelve 422.',
34
+ effect: 'Un título válido conserva la respuesta 201. Un título en blanco ahora recibe 422.',
35
+ before: excerpt('route.ts', beforeRoute, 10, 9, 10), after: excerpt('route.ts', afterRoute, 13, 9, 13),
36
+ },
37
+ ]
38
+ const error = {
39
+ title: 'Rechazar el título vacío',
40
+ explanation: 'La validación devuelve null antes de insertar. La ruta responde con 422.',
41
+ effect: 'El mismo cuerpo antes llegaba al escritor y devolvía 201.',
42
+ before: excerpt('route.ts', beforeRoute, 10, 9, 10), after: excerpt('route.ts', afterRoute, 11, 9, 13),
43
+ }
44
+
45
+ return {
46
+ project: 'Support Desk', area: 'Tickets', title: 'Crear un ticket', environment: 'demo',
47
+ summary: 'Sigue la solicitud desde la ruta hasta la escritura y su respuesta.', base: 'antes', head: 'después',
48
+ diff: {
49
+ title: 'Validar antes de guardar',
50
+ explanation: 'Un título de solo espacios pasa de guardarse con 201 a recibir 422 sin escritura.',
51
+ files: [['route.ts', beforeRoute, afterRoute], ['ticket-service.ts', beforeService, afterService]]
52
+ .filter(([, before, after]) => before !== after).map(([file]) => file),
53
+ },
54
+ review: {
55
+ title: 'SD-01 · Rechazar tickets con título vacío', description: 'Ticket de ejemplo',
56
+ criteria: [{ id: 'reject', label: 'Devuelve 422', step: 4 }, { id: 'storage', label: 'Protege la escritura', step: 2 }],
57
+ },
58
+ labels: { request: 'POST', database: 'Escribe', response: 'Ver respuesta HTTP' },
59
+ places: {
60
+ web: { title: 'Entrada', role: 'Ruta HTTP', change: 'Misma entrada' },
61
+ api: { title: 'Servicio', role: 'Tickets', change: 'Validación' },
62
+ data: { title: 'Escritura', role: 'Almacenamiento', change: 'Condicionada' },
63
+ error: { title: '422', role: 'Título vacío', change: 'Rechazo' },
64
+ },
65
+ flow,
66
+ error,
67
+ details: {
68
+ symbol: [
69
+ { id: 'route', label: 'postTicket', kind: 'Función', layer: 'web', step: 0, item: flow[0] },
70
+ { id: 'service', label: 'createTicket', kind: 'Función', layer: 'api', step: 1, item: flow[1] },
71
+ { id: 'store', label: 'TicketStore', kind: 'Interfaz', layer: 'data', step: 2, item: flow[2] },
72
+ ],
73
+ call: [
74
+ { id: 'json', label: 'request.json()', kind: 'Llamada a un método', layer: 'web', step: 0, item: flow[0] },
75
+ { id: 'create', label: 'createTicket()', kind: 'Llamada', layer: 'api', step: 1, item: flow[1] },
76
+ { id: 'insert', label: 'store.insert()', kind: 'Llamada a un método', layer: 'data', step: 2, item: flow[2] },
77
+ ],
78
+ },
79
+ }
80
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ryan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ # Anatomy
2
+
3
+ `iso-kit.mjs` procede de [Anatomy](https://github.com/wheresryan22/anatomy/blob/1482e8469b0a9e0d8cc18ea2740a01423d29ae80/kit/iso-kit.mjs), versión fijada en `1482e8469b0a9e0d8cc18ea2740a01423d29ae80`. Se incluye sin cambios y se distribuye con su licencia MIT en `LICENSE`.