# Test · Code
Each block exercises all Prism token categories: comments, keywords, strings, numbers, functions, classes, properties, operators, punctuation.
---
## Python
```python
# ── Vault Frontmatter Audit ───────────────────────────────────────────────────
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Iterator
REQUIRED_FIELDS: tuple[str, ...] = (
"created", "last", "publish", "tags"
)
SKIP_FOLDERS: tuple[str, ...] = (
"⚙️ Αρχείο", "Συνημμένα", ".obsidian"
)
MAX_DESC_LEN: int = 80
TAG_PREFIX: str = "#"
HEX_MASK: int = 0xFF
FLAG_MISSING: int = 0b0001
FLAG_OVERFLOW: int = 0b0010
FieldError = type("FieldError", (ValueError,), {})
def _parse_frontmatter(text: str) -> dict[str, str]:
"""Extract YAML frontmatter keys from a note."""
lines = text.splitlines()
if not lines or lines[0].strip() != "---":
return {}
result: dict[str, str] = {}
for line in lines[1:]:
if line.strip() == "---":
break
if ":" in line:
key, _, val = line.partition(":")
result[key.strip()] = val.strip()
return result
@dataclass
class AuditResult:
path: Path
missing: list[str] = field(default_factory=list)
desc_overflow: bool = False
@property
def ok(self) -> bool:
return not self.missing and not self.desc_overflow
@property
def flags(self) -> int:
return (FLAG_MISSING if self.missing else 0) | (
FLAG_OVERFLOW if self.desc_overflow else 0
)
@dataclass
class VaultAudit:
root: Path
skip_folders: list[str] = field(
default_factory=lambda: list(SKIP_FOLDERS)
)
def notes(self) -> Iterator[Path]:
for p in self.root.rglob("*.md"):
if any(folder in str(p) for folder in self.skip_folders):
continue
yield p
def audit(self) -> Iterator[AuditResult]:
for note_path in self.notes():
text = note_path.read_text(encoding="utf-8")
fm = _parse_frontmatter(text)
missing = [f for f in REQUIRED_FIELDS if f not in fm]
desc = fm.get("description", "").strip('"')
result = AuditResult(
path=note_path,
missing=missing,
desc_overflow=len(desc) > MAX_DESC_LEN,
)
if not result.ok:
yield result
vault = VaultAudit(root=Path.home() / "Vaults" / "Tenebrous-dragon")
try:
for result in vault.audit():
rel = result.path.relative_to(vault.root)
issues = ", ".join([
*result.missing,
*(["desc too long"] if result.desc_overflow else []),
])
print(f"[{result.flags:#04x}] {rel}: {issues}")
except (PermissionError, UnicodeDecodeError) as exc:
print(f"Audit error: {exc}")
fmt_field = lambda f: f"{TAG_PREFIX}{f}"
summary = ", ".join(fmt_field(f) for f in REQUIRED_FIELDS)
print(f"Required: {summary}")
```
---
## JavaScript (ES2022)
```javascript
// Dragon Catalogue — async fetch with error boundaries
const API_BASE = 'https://api.tenebrous-dragon.example/v2';
/** @typedef {{ id: string, name: string, cr: number, habitat: string[] }} DragonEntry */
class DragonCatalogue {
#cache = new Map();
#abortController = null;
constructor(baseUrl = API_BASE) {
this.baseUrl = baseUrl;
this.#cache.clear();
}
async fetchAll(signal) {
const url = `${this.baseUrl}/dragons?limit=100`;
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);
return /** @type {DragonEntry[]} */ (await res.json());
}
async getByHabitat(habitat) {
if (this.#cache.has(habitat)) return this.#cache.get(habitat);
this.#abortController?.abort();
this.#abortController = new AbortController();
try {
const all = await this.fetchAll(this.#abortController.signal);
const filtered = all.filter(d => d.habitat.includes(habitat));
this.#cache.set(habitat, filtered);
return filtered;
} catch (err) {
if (err.name !== 'AbortError') console.error('Fetch failed:', err);
return [];
}
}
*[Symbol.iterator]() {
for (const [key, value] of this.#cache) {
yield { habitat: key, entries: value };
}
}
}
// Destructuring, rest/spread, optional chaining, nullish coalescing
const { name = 'Unknown', cr = 0, habitat: [primary = 'unknown'] = [] } = {};
const dragons = [
{ name: 'Sapphire', cr: 15, tags: ['gem', 'psionic'] },
{ name: 'Bronze', cr: 18, tags: ['metallic', 'coastal'] },
];
const sorted = dragons
.filter(d => d.cr >= 15)
.sort((a, b) => b.cr - a.cr)
.map(({ name, cr, tags }) => ({ name, cr, primary: tags[0] ?? 'none' }));
const catalogue = new DragonCatalogue();
const coastal = await catalogue.getByHabitat('coastal');
console.log(`Coastal dragons: ${coastal.length ?? 0}`);
```
---
## TypeScript
```typescript
// ── Typed Bestiary with generics, decorators, mapped types ────────────────────
type DragonSize = 'Wyrmling' | 'Young' | 'Adult' | 'Ancient' | 'Greatwyrm';
type Alignment = `${'Lawful' | 'Neutral' | 'Chaotic'} ${'Good' | 'Neutral' | 'Evil'}`;
interface CreatureStats {
readonly hp: number;
readonly ac: number;
readonly cr: number;
speed: Partial<Record<'walk' | 'fly' | 'swim', number>>;
}
interface DragonEntry extends CreatureStats {
name: string;
colour: string;
size: DragonSize;
align: Alignment;
breath: string;
habitat: string[];
}
type PartialEntry = Partial<DragonEntry>;
type RequiredEntry = Required<DragonEntry>;
type DragonKeys = keyof DragonEntry;
// Generic repository
class Repository<T extends { name: string }> {
private readonly store = new Map<string, T>();
add(item: T): this {
this.store.set(item.name, item);
return this;
}
get(name: string): T | undefined {
return this.store.get(name);
}
filter<K extends keyof T>(key: K, value: T[K]): T[] {
return [...this.store.values()].filter(item => item[key] === value);
}
*[Symbol.iterator](): IterableIterator<T> {
yield* this.store.values();
}
}
// Decorator factory
function LogMethod(label: string) {
return function (_target: object, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value as (...args: unknown[]) => unknown;
descriptor.value = function (...args: unknown[]) {
console.log(`[${label}] ${key}(${args.join(', ')})`);
return original.apply(this, args);
};
return descriptor;
};
}
class BestiaryService {
constructor(private readonly repo: Repository<DragonEntry>) {}
@LogMethod('Bestiary')
lookup(name: string): DragonEntry | undefined {
return this.repo.get(name);
}
bySize(size: DragonSize): DragonEntry[] {
return this.repo.filter('size', size);
}
}
const repo = new Repository<DragonEntry>();
repo
.add({ name: 'Sapphire', colour: 'blue', size: 'Ancient', align: 'Lawful Neutral',
hp: 297, ac: 20, cr: 22, breath: 'Psychic', habitat: ['Underdark'],
speed: { walk: 40, fly: 80 } })
.add({ name: 'Bronze', colour: 'bronze', size: 'Adult', align: 'Lawful Good',
hp: 212, ac: 18, cr: 15, breath: 'Lightning', habitat: ['Coastal'],
speed: { walk: 40, fly: 80, swim: 40 } });
const service = new BestiaryService(repo);
const ancient = service.bySize('Ancient');
console.log(ancient.map(d => `${d.name} (CR ${d.cr})`));
```
---
## Bash
```bash
#!/usr/bin/env bash
# vault-backup.sh -- Backup Obsidian vaults to iCloud
set -euo pipefail
IFS=