waddling-errors 0.7.3

Structured, secure-by-default diagnostic codes for distributed systems with no_std and role-based documentation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/* ============================================
   ERROR CARD RENDERING
   Render error cards with collapsible sections
   ============================================ */

function renderResults() {
    if (!DOM.resultsContainer) return;
    
    const errors = AppState.filteredErrors;
    
    // Update count
    if (DOM.resultsCount) {
        DOM.resultsCount.textContent = `${errors.length} ${plural(errors.length, 'error')}`;
    }
    
    if (errors.length === 0) {
        DOM.resultsContainer.innerHTML = `
            <div class="empty-state">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <circle cx="11" cy="11" r="8"/>
                    <line x1="21" y1="21" x2="16.65" y2="16.65"/>
                </svg>
                <h3>No errors found</h3>
                <p>Try adjusting your search or filter criteria</p>
            </div>
        `;
        return;
    }
    
    // Render cards
    DOM.resultsContainer.innerHTML = '';
    errors.forEach(error => {
        const card = renderErrorCard(error);
        DOM.resultsContainer.appendChild(card);
    });
    
    // Apply Prism highlighting
    if (typeof Prism !== 'undefined') {
        Prism.highlightAllUnder(DOM.resultsContainer);
    }
}

function renderErrorCard(error) {
    const severity = (error.severity || 'info').toLowerCase();
    const sevChar = error.code?.charAt(0)?.toUpperCase() || 'I';
    
    const card = createElement('article', `error-card severity-${sevChar}`);
    card.dataset.code = error.code;
    if (error.hash) {
        card.dataset.hash = error.hash;
        card.id = `error-${error.hash}`;
    }
    
    // Click handler to update URL hash
    card.addEventListener('click', (e) => {
        // Don't update URL if clicking on interactive elements
        if (e.target.closest('button, a, .copy-code-btn, .snippet-copy-btn')) return;
        
        if (error.hash) {
            history.replaceState(null, '', `#${error.hash}`);
        }
    });
    
    // Header
    const header = renderCardHeader(error, severity, sevChar);
    
    // Body (collapsible sections)
    const body = renderCardBody(error);
    
    card.appendChild(header);
    card.appendChild(body);
    
    return card;
}

// Severity emoji mapping per WDP Part 10
const SEVERITY_EMOJI = {
    'E': '', 'B': '🚫', 'C': '🔥', 'W': '⚠️',
    'H': '💡', 'S': '', 'K': '✔️', 'I': 'ℹ️', 'T': '🔍'
};

function renderCardHeader(error, severity, sevChar) {
    const header = createElement('div', 'error-card-header');
    
    // Error code row: emoji + copy + code-group + arrow + hash + link
    const codeRow = createElement('div', 'error-code-row');
    
    // Severity emoji (per WDP Part 10)
    const emoji = createElement('span', 'severity-emoji');
    emoji.textContent = SEVERITY_EMOJI[sevChar] || 'ℹ️';
    emoji.title = severity;
    codeRow.appendChild(emoji);
    
    // Copy button (before code for clean layout)
    const copyBtn = createElement('button', 'copy-code-btn', {
        'data-code': error.code,
        title: 'Copy error code'
    });
    copyBtn.innerHTML = '📋';
    copyBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        copyToClipboard(error.code, copyBtn);
    });
    codeRow.appendChild(copyBtn);
    
    // Code group: error-code parts (clickable)
    const codeGroup = createElement('div', 'error-code-group');
    
    // Render the error code with colored, clickable parts
    const codeEl = renderErrorCode(error.code, error);
    
    codeGroup.appendChild(codeEl);
    codeRow.appendChild(codeGroup);
    
    // Arrow and hash (if hash exists)
    if (error.hash) {
        const arrow = createElement('span', 'error-arrow');
        arrow.textContent = '\u2192';
        codeRow.appendChild(arrow);
        
        const hashEl = createElement('span', 'error-hash', {
            title: 'Click to copy hash'
        });
        hashEl.textContent = error.hash;
        hashEl.addEventListener('click', (e) => {
            e.stopPropagation();
            copyToClipboard(error.hash, hashEl);
        });
        codeRow.appendChild(hashEl);
        
        // Share link button
        const shareBtn = createElement('button', 'share-link-btn', {
            title: 'Copy shareable link'
        });
        shareBtn.innerHTML = '🔗';
        shareBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const url = `${window.location.origin}${window.location.pathname}#${error.hash}`;
            copyToClipboard(url, shareBtn);
            showToast('Link Copied', `Shareable link for ${error.code}`, 'success');
        });
        codeRow.appendChild(shareBtn);
    }
    
    header.appendChild(codeRow);
    
    // Description/Message
    const desc = createElement('p', 'error-description');
    desc.innerHTML = highlightMatch(error.message || error.description, AppState.searchQuery);
    header.appendChild(desc);
    
    // Meta badges
    const meta = createElement('div', 'error-meta');
    
    // Version badge
    if (error.introduced) {
        const verBadge = createElement('span', 'meta-badge introduced');
        verBadge.textContent = `v${error.introduced}`;
        meta.appendChild(verBadge);
    }
    
    // Visibility badge
    if (error.visibility && error.visibility !== 'public') {
        const visBadge = createElement('span', `meta-badge visibility-${error.visibility}`);
        visBadge.textContent = capitalize(error.visibility);
        meta.appendChild(visBadge);
    }
    
    // Deprecated badge
    if (error.deprecated) {
        const depBadge = createElement('span', 'meta-badge deprecated');
        depBadge.textContent = 'Deprecated';
        meta.appendChild(depBadge);
    }
    
    if (meta.children.length > 0) {
        header.appendChild(meta);
    }
    
    return header;
}

function renderCardBody(error) {
    const body = createElement('div', 'error-card-body');
    
    // Determine which sections exist
    const sections = [];
    
    // CODE section (if there are code snippets)
    if (error.code_snippets && error.code_snippets.length > 0) {
        sections.push({
            id: 'code',
            title: 'Code',
            icon: '\uD83D\uDCDD',
            render: () => renderCodeSection(error)
        });
    }
    
    // HINTS section
    if (error.hints && error.hints.length > 0) {
        sections.push({
            id: 'hints',
            title: 'Hints',
            icon: '\uD83D\uDCA1',
            render: () => renderHintsSection(error)
        });
    }
    
    // RELATED section
    if (error.related_codes && error.related_codes.length > 0) {
        sections.push({
            id: 'related',
            title: 'Related',
            icon: '\uD83D\uDD17',
            render: () => renderRelatedSection(error)
        });
    }
    
    // TAGS section
    if (error.tags && error.tags.length > 0) {
        sections.push({
            id: 'tags',
            title: 'Tags',
            icon: '\uD83C\uDFF7\uFE0F',
            render: () => renderTagsSection(error)
        });
    }
    
    // If no sections, show description if available
    if (sections.length === 0) {
        if (error.description) {
            const descEl = createElement('p', 'error-description-full');
            descEl.textContent = error.description;
            body.appendChild(descEl);
        }
        return body;
    }
    
    // Render each section
    sections.forEach((section, index) => {
        const isOpen = index < 2; // First 2 sections open by default
        const sectionEl = createElement('div', `error-section${isOpen ? ' open' : ''}`);
        
        // Section toggle button
        const toggle = createElement('button', 'error-section-toggle');
        toggle.innerHTML = `
            <span class="toggle-left">
                <span>${section.icon}</span>
                <span>${section.title}</span>
            </span>
            <span class="icon">\u25BC</span>
        `;
        
        toggle.addEventListener('click', () => {
            sectionEl.classList.toggle('open');
        });
        
        // Section content
        const content = createElement('div', 'error-section-content');
        content.appendChild(section.render());
        
        sectionEl.appendChild(toggle);
        sectionEl.appendChild(content);
        body.appendChild(sectionEl);
    });
    
    return body;
}

function renderCodeSection(error) {
    const container = createElement('div', 'code-snippets-container');
    
    // Handle code_snippets array
    const snippets = error.code_snippets || [];
    
    snippets.forEach(snippet => {
        const wrapper = createElement('div', 'code-snippet');
        const code = snippet.code || '';
        const lang = snippet.language || 'rust';
        const label = snippet.label || '';
        const role = snippet.role || '';
        
        wrapper.innerHTML = `
            <div class="code-snippet-header">
                <div class="code-snippet-address-bar">
                    <span class="code-snippet-lang">${escapeHtml(lang)}</span>
                    ${label ? `<span class="code-snippet-label">${escapeHtml(label)}</span>` : ''}
                </div>
                <div class="code-snippet-right">
                    ${role ? `<span class="code-snippet-role ${role.toLowerCase()}">${escapeHtml(role)}</span>` : ''}
                    <button class="snippet-copy-btn" data-code="${escapeHtml(code)}">
                        <span>\uD83D\uDCCB</span>
                        <span class="copy-text">Copy</span>
                    </button>
                </div>
            </div>
            <div class="code-snippet-content">
                <pre><code class="language-${escapeHtml(lang)}">${escapeHtml(code)}</code></pre>
            </div>
        `;
        
        const copyBtn = wrapper.querySelector('.snippet-copy-btn');
        copyBtn.addEventListener('click', () => copyToClipboard(code, copyBtn));
        
        container.appendChild(wrapper);
    });
    
    return container;
}

function renderHintsSection(error) {
    const list = createElement('div', 'hint-list');
    
    (error.hints || []).forEach(hint => {
        const hintText = typeof hint === 'string' ? hint : hint.message;
        
        const item = createElement('div', 'hint-item');
        item.innerHTML = `
            <span class="hint-icon">\u2192</span>
            ${escapeHtml(hintText)}
        `;
        list.appendChild(item);
    });
    
    return list;
}

function renderRelatedSection(error) {
    const list = createElement('div', 'related-codes');
    
    (error.related_codes || []).forEach(related => {
        const relatedCode = typeof related === 'string' ? related : related.code;
        
        const item = createElement('span', 'related-code');
        item.textContent = relatedCode;
        item.style.cursor = 'pointer';
        
        item.addEventListener('click', () => {
            // Find and scroll to related error
            const targetCard = document.querySelector(`.error-card[data-code="${relatedCode}"]`);
            if (targetCard) {
                scrollToElement(targetCard);
                targetCard.classList.add('highlight');
                setTimeout(() => targetCard.classList.remove('highlight'), 2000);
            } else {
                // Clear filters and search for it
                DOM.searchInput.value = relatedCode;
                AppState.searchQuery = relatedCode;
                filterErrors();
                renderResults();
            }
        });
        
        list.appendChild(item);
    });
    
    return list;
}

function renderTagsSection(error) {
    const list = createElement('div', 'tags');
    
    (error.tags || []).forEach(tag => {
        const item = createElement('span', 'tag');
        item.textContent = tag;
        item.style.cursor = 'pointer';
        
        item.addEventListener('click', () => {
            setTag(tag);
        });
        
        list.appendChild(item);
    });
    
    return list;
}

function toggleCard(code) {
    const card = document.querySelector(`.error-card[data-code="${code}"]`);
    if (!card) return;
    
    if (AppState.expandedCards.has(code)) {
        AppState.expandedCards.delete(code);
        card.classList.remove('expanded');
    } else {
        AppState.expandedCards.add(code);
        card.classList.add('expanded');
        
        // Initialize open sections if not set
        if (!AppState.openSections.has(code)) {
            const firstSection = card.querySelector('.section');
            if (firstSection) {
                AppState.openSections.set(code, new Set([firstSection.dataset.section]));
            }
        }
    }
    
    // Update sidebar if viewing this error
    if (AppState.selectedErrorCode === code) {
        showErrorDetail(code);
    }
}

function toggleSection(errorCode, sectionId, sectionEl) {
    const openSections = AppState.openSections.get(errorCode) || new Set();
    
    if (openSections.has(sectionId)) {
        openSections.delete(sectionId);
        sectionEl.classList.remove('open');
    } else {
        openSections.add(sectionId);
        sectionEl.classList.add('open');
    }
    
    AppState.openSections.set(errorCode, openSections);
}

/**
 * Render error code with colored parts (e.g., E.Auth.Token.001)
 * Part order: severity.component.primary.sequence
 * 
 * IMPORTANT: Uses display format (preserves original casing from error.component/primary)
 * rather than the canonical ALL CAPS form from error.code.
 * The canonical code is stored in error.code for hashing/wire protocol.
 */
function renderErrorCode(code, error) {
    const container = createElement('div', 'error-code');
    const parts = code.split('.');
    
    // Part types in order: severity, component, primary, sequence
    const partTypes = ['severity', 'component', 'primary', 'sequence'];
    const partTitles = ['Severity', 'Component', 'Primary Category', 'Sequence Number'];
    
    // Build display parts using preserved casing from error object
    // The error.code is canonical (ALL CAPS), but error.component/primary preserve original casing
    const displayParts = [
        parts[0], // severity (always uppercase single char)
        error.component || parts[1], // use preserved casing from error.component
        error.primary || parts[2],   // use preserved casing from error.primary
        parts[3]  // sequence (numeric)
    ];
    
    displayParts.forEach((part, index) => {
        if (index > 0) {
            const dot = createElement('span', 'dot');
            dot.textContent = '.';
            container.appendChild(dot);
        }
        
        const partType = partTypes[index] || 'sequence';
        const partTitle = partTitles[index] || 'Sequence';
        
        // For sequence part, check if we should display named format
        let displayText = part;
        if (partType === 'sequence' && AppState.sequenceFormat === 'named') {
            // Try to find sequence name from metadata
            const seqNum = parseInt(part, 10);
            const seqMeta = AppState.sequences?.[seqNum];
            if (seqMeta && seqMeta.name) {
                displayText = seqMeta.name;
            }
        }
        
        const span = createElement('span', `part ${partType} clickable`, {
            'data-type': partType,
            'data-value': part,
            'data-original': parts[index], // store canonical form for reference
            title: `Click to view ${partTitle} info`
        });
        span.textContent = displayText;
        
        // Make all parts clickable - pass the display value (preserved casing)
        span.addEventListener('click', (e) => {
            e.stopPropagation();
            showPartInfo(partType, part, error);
        });
        
        container.appendChild(span);
    });
    
    return container;
}

// Show info about a code part in the sidebar
function showPartInfo(partType, value, error) {
    // Handle severity separately - show in detail panel directly
    if (partType === 'severity') {
        showSeverityDetail(value);
        return;
    }
    
    const tabMap = {
        'component': 'components',
        'primary': 'primaries', 
        'sequence': 'sequences'
    };
    
    const tabId = tabMap[partType];
    if (!tabId) return;
    
    // Use the preserved casing from error object for lookup
    // This ensures we match sidebar items which use the same casing
    let lookupValue = value;
    if (partType === 'sequence') {
        // For sequences, convert padded format ("001") to numeric key ("1")
        lookupValue = String(parseInt(value, 10));
    } else if (partType === 'component') {
        // Use error.component which has preserved casing
        lookupValue = error.component || value;
    } else if (partType === 'primary') {
        // Use error.primary which has preserved casing
        lookupValue = error.primary || value;
    }
    
    // Switch to the appropriate tab
    const tabBtn = document.querySelector(`.browse-tab[data-tab="${tabId}"]`);
    if (tabBtn) {
        // Trigger tab switch
        document.querySelectorAll('.browse-tab').forEach(t => t.classList.remove('active'));
        tabBtn.classList.add('active');
        
        // Clear previous active category when switching tabs
        AppState.activeCategory = null;
        hideDetail();
        
        // Rebuild the list for the new tab
        if (typeof buildBrowseList === 'function') {
            buildBrowseList(tabId);
        }
    }
    
    // Find and click the item in the sidebar to show detail
    // The sidebar uses data-name attribute to identify items
    setTimeout(() => {
        const item = document.querySelector(`.browse-item[data-type="${tabId}"][data-name="${lookupValue}"]`);
        if (item) {
            // Scroll into view
            item.scrollIntoView({ behavior: 'smooth', block: 'center' });
            // Simulate click to show detail
            item.click();
            // Add highlight effect
            item.classList.add('highlight-pulse');
            setTimeout(() => item.classList.remove('highlight-pulse'), 2000);
        }
    }, 100); // Small delay to let the list rebuild
}