New Base func

This commit is contained in:
Jakob Wennberg
2026-02-19 09:48:02 +01:00
parent afc9f69def
commit cdf1dcc4c8
73 changed files with 11036 additions and 51 deletions
+129
View File
@@ -0,0 +1,129 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { extensionRegistry } from '../registry'
import { eventBus } from '@/lib/events/bus'
import type { Extension } from '../types'
beforeEach(() => {
extensionRegistry.clear()
eventBus.clear()
})
function makeExtension(overrides: Partial<Extension> = {}): Extension {
return {
id: 'test-ext',
name: 'Test Extension',
version: '1.0.0',
...overrides,
}
}
describe('ExtensionRegistry', () => {
it('register() stores extension, queryable via get() and getAll()', () => {
const ext = makeExtension()
extensionRegistry.register(ext)
expect(extensionRegistry.get('test-ext')).toBe(ext)
expect(extensionRegistry.getAll()).toEqual([ext])
})
it('register() wires event handlers to the bus', async () => {
const handler = vi.fn()
const ext = makeExtension({
id: 'event-ext',
eventHandlers: [{ eventType: 'journal_entry.committed', handler }],
})
extensionRegistry.register(ext)
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1' },
})
expect(handler).toHaveBeenCalledWith({ entry: { id: 'e1' }, userId: 'u1' })
})
it('register() skips duplicate registration (same id)', () => {
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const ext1 = makeExtension()
const ext2 = makeExtension({ name: 'Duplicate' })
extensionRegistry.register(ext1)
extensionRegistry.register(ext2)
// Original is kept
expect(extensionRegistry.get('test-ext')!.name).toBe('Test Extension')
expect(extensionRegistry.getAll()).toHaveLength(1)
consoleSpy.mockRestore()
})
it('unregister() removes extension and unsubscribes handlers', async () => {
const handler = vi.fn()
const ext = makeExtension({
id: 'removable',
eventHandlers: [{ eventType: 'journal_entry.committed', handler }],
})
extensionRegistry.register(ext)
extensionRegistry.unregister('removable')
expect(extensionRegistry.get('removable')).toBeUndefined()
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1' },
})
expect(handler).not.toHaveBeenCalled()
})
it('getByCapability() filters correctly', () => {
const ext1 = makeExtension({
id: 'with-settings',
settingsPanel: { label: 'Test', path: '/test' },
})
const ext2 = makeExtension({ id: 'without-settings' })
extensionRegistry.register(ext1)
extensionRegistry.register(ext2)
const withSettings = extensionRegistry.getByCapability('settingsPanel')
expect(withSettings).toHaveLength(1)
expect(withSettings[0].id).toBe('with-settings')
})
it('clear() removes all extensions and unsubscribes all handlers', async () => {
const handler1 = vi.fn()
const handler2 = vi.fn()
extensionRegistry.register(
makeExtension({
id: 'ext1',
eventHandlers: [{ eventType: 'journal_entry.committed', handler: handler1 }],
})
)
extensionRegistry.register(
makeExtension({
id: 'ext2',
eventHandlers: [{ eventType: 'journal_entry.drafted', handler: handler2 }],
})
)
extensionRegistry.clear()
expect(extensionRegistry.getAll()).toHaveLength(0)
await eventBus.emit({
type: 'journal_entry.committed',
payload: { entry: { id: 'e1' } as never, userId: 'u1' },
})
await eventBus.emit({
type: 'journal_entry.drafted',
payload: { entry: { id: 'e1' } as never, userId: 'u1' },
})
expect(handler1).not.toHaveBeenCalled()
expect(handler2).not.toHaveBeenCalled()
})
})
+15
View File
@@ -0,0 +1,15 @@
export { extensionRegistry } from './registry'
export { loadExtensions } from './loader'
export type {
Extension,
RouteDefinition,
ApiRouteDefinition,
SidebarItem,
ReportDefinition,
SettingsPanelDefinition,
TaxCodeDefinition,
DimensionDefinition,
MappingRuleTypeDefinition,
ExtensionEventHandler,
ExtensionContext,
} from './types'
+30
View File
@@ -0,0 +1,30 @@
import { extensionRegistry } from './registry'
import { receiptOcrExtension } from '@/extensions/receipt-ocr'
import { aiCategorizationExtension } from '@/extensions/ai-categorization'
import type { Extension } from './types'
/**
* Explicit list of first-party extensions.
*
* Next.js bundling requires static imports — no dynamic filesystem scanning.
* Add extensions here as they are built.
*/
const FIRST_PARTY_EXTENSIONS: Extension[] = [
receiptOcrExtension,
aiCategorizationExtension,
]
let loaded = false
/**
* Load and register all first-party extensions.
* Idempotent — safe to call multiple times.
*/
export function loadExtensions(): void {
if (loaded) return
loaded = true
for (const extension of FIRST_PARTY_EXTENSIONS) {
extensionRegistry.register(extension)
}
}
+79
View File
@@ -0,0 +1,79 @@
import { eventBus } from '@/lib/events/bus'
import type { CoreEventType } from '@/lib/events/types'
import type { Extension } from './types'
/**
* Extension Registry — singleton that manages extension lifecycle.
*
* - register() stores extension and wires event handlers to the bus
* - unregister() unhooks handlers and removes extension
* - getAll(), get(), getByCapability() for querying
*/
class ExtensionRegistry {
private extensions = new Map<string, Extension>()
private unsubscribers = new Map<string, (() => void)[]>()
/**
* Register an extension: store it and wire its event handlers to the bus.
*/
register(extension: Extension): void {
if (this.extensions.has(extension.id)) {
console.warn(`[ExtensionRegistry] Extension "${extension.id}" already registered, skipping`)
return
}
this.extensions.set(extension.id, extension)
// Wire event handlers to the bus
const unsubs: (() => void)[] = []
if (extension.eventHandlers) {
for (const { eventType, handler } of extension.eventHandlers) {
// Cast is safe: the handler is stored by eventType key, so it only receives matching payloads
const unsub = eventBus.on(eventType as CoreEventType, handler)
unsubs.push(unsub)
}
}
this.unsubscribers.set(extension.id, unsubs)
}
/**
* Unregister an extension: unhook all event handlers and remove.
*/
unregister(extensionId: string): void {
const unsubs = this.unsubscribers.get(extensionId)
if (unsubs) {
for (const unsub of unsubs) {
unsub()
}
this.unsubscribers.delete(extensionId)
}
this.extensions.delete(extensionId)
}
/** Get all registered extensions. */
getAll(): Extension[] {
return [...this.extensions.values()]
}
/** Get a specific extension by ID. */
get(id: string): Extension | undefined {
return this.extensions.get(id)
}
/** Get all extensions that have a specific capability. */
getByCapability(key: keyof Extension): Extension[] {
return [...this.extensions.values()].filter(
(ext) => ext[key] !== undefined && ext[key] !== null
)
}
/** Clear all extensions (useful for testing). */
clear(): void {
for (const id of this.extensions.keys()) {
this.unregister(id)
}
}
}
/** Module-level singleton */
export const extensionRegistry = new ExtensionRegistry()
+100
View File
@@ -0,0 +1,100 @@
import type { CoreEventType } from '@/lib/events/types'
// ============================================================
// Extension Interface & Supporting Types
// ============================================================
/** A route exposed by an extension (page route) */
export interface RouteDefinition {
path: string
label: string
}
/** An API route exposed by an extension */
export interface ApiRouteDefinition {
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
path: string
handler: (request: Request) => Promise<Response>
}
/** Sidebar navigation item added by an extension */
export interface SidebarItem {
label: string
icon?: string
path: string
order?: number
}
/** Report type added by an extension */
export interface ReportDefinition {
id: string
name: string
description: string
}
/** Settings panel exposed by an extension */
export interface SettingsPanelDefinition {
label: string
path: string
}
/** Tax code definition added by an extension */
export interface TaxCodeDefinition {
code: string
rate: number
description: string
}
/** Dimension type definition added by an extension */
export interface DimensionDefinition {
id: string
name: string
description: string
}
/** Mapping rule type added by an extension */
export interface MappingRuleTypeDefinition {
id: string
name: string
description: string
}
/** Event handler registration for an extension */
export interface ExtensionEventHandler {
eventType: CoreEventType
// eslint-disable-next-line @typescript-eslint/no-explicit-any
handler: (payload: any) => Promise<void> | void
}
/** Context passed to extension lifecycle hooks */
export interface ExtensionContext {
userId: string
extensionId: string
}
/**
* Extension interface — the contract for all add-ons.
*
* Extensions declare what they provide (routes, event handlers, sidebar items, etc.)
* and the registry wires them into the system.
*/
export interface Extension {
id: string
name: string
version: string
// Surfaces
routes?: RouteDefinition[]
apiRoutes?: ApiRouteDefinition[]
sidebarItems?: SidebarItem[]
eventHandlers?: ExtensionEventHandler[]
mappingRuleTypes?: MappingRuleTypeDefinition[]
reportTypes?: ReportDefinition[]
settingsPanel?: SettingsPanelDefinition
taxCodes?: TaxCodeDefinition[]
dimensionTypes?: DimensionDefinition[]
// Lifecycle hooks
onInstall?(ctx: ExtensionContext): Promise<void>
onUninstall?(ctx: ExtensionContext): Promise<void>
}