nucleus-core-ts 0.10.191 → 0.10.192

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/.build-ok CHANGED
@@ -1 +1 @@
1
- 0.10.191
1
+ 0.10.192
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nucleus-core-ts",
3
- "version": "0.10.191",
3
+ "version": "0.10.192",
4
4
  "description": "Production-ready, enterprise-grade TypeScript framework for building multi-tenant APIs",
5
5
  "author": "Hidayet Can Özcan <hidayetcan@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -0,0 +1,73 @@
1
+ import { afterAll, describe, expect, test } from 'bun:test'
2
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { createFixtureServer } from '../fixtures'
6
+ import { captureRun } from '.'
7
+
8
+ const PAGE = `<!doctype html><meta charset="utf-8"><body style="margin:0;font:16px sans-serif">
9
+ <h1 id="title" style="position:absolute;left:20px;top:30px;width:200px;height:40px;margin:0">Start</h1>
10
+ <button id="go" onclick="document.getElementById('title').textContent='Done'">Go</button></body>`
11
+
12
+ const site = createFixtureServer({
13
+ routes: [
14
+ { path: '/', respond: () => new Response(PAGE, { headers: { 'content-type': 'text/html' } }) },
15
+ ],
16
+ })
17
+ const outDir = join(mkdtempSync(join(tmpdir(), 'nucleus-capture-test-')), 'run')
18
+ afterAll(async () => {
19
+ await site.stop()
20
+ rmSync(join(outDir, '..'), { recursive: true, force: true })
21
+ })
22
+
23
+ describe('captureRun', () => {
24
+ test('drives the page, writes the frames and a timeline the kit can play', async () => {
25
+ const result = await captureRun({
26
+ outDir,
27
+ locale: 'en',
28
+ theme: 'light',
29
+ format: 'png',
30
+ roles: { desk: { viewport: { width: 320, height: 200, scale: 2 }, url: `${site.origin}/` } },
31
+ scenario: async (director) => {
32
+ await director.settle('desk')
33
+ await director.snap({
34
+ caption: { en: 'Before' },
35
+ focus: 'desk',
36
+ seconds: 2,
37
+ highlight: { desk: '#title' },
38
+ })
39
+ await director.page('desk').click('#go')
40
+ await director.burst({
41
+ caption: { en: 'After' },
42
+ focus: 'desk',
43
+ seconds: 2,
44
+ count: 2,
45
+ everyMs: 10,
46
+ })
47
+ },
48
+ })
49
+ const { timeline } = result
50
+ expect(timeline.version).toBe(1)
51
+ expect(timeline.viewports.desk).toEqual({ width: 320, height: 200, scale: 2 })
52
+ expect(timeline.beats.map((beat) => beat.id)).toEqual(['b01', 'b02', 'b03'])
53
+ expect(timeline.beats[0]?.frames.desk?.highlight).toEqual({ x: 20, y: 30, w: 200, h: 40 })
54
+ expect(timeline.beats[1]?.seconds).toBe(1)
55
+ expect(result.frames).toBe(3)
56
+ expect(existsSync(join(outDir, 'frames', 'b01-desk.png'))).toBe(true)
57
+ expect(existsSync(result.timelinePath)).toBe(true)
58
+ }, 60_000)
59
+
60
+ test('a scenario that takes no beat writes no timeline', async () => {
61
+ const empty = join(outDir, '..', 'empty')
62
+ await expect(
63
+ captureRun({
64
+ outDir: empty,
65
+ locale: 'en',
66
+ theme: 'dark',
67
+ roles: { desk: { viewport: { width: 100, height: 100, scale: 1 } } },
68
+ scenario: async () => undefined,
69
+ })
70
+ ).rejects.toThrow('The scenario took no beats')
71
+ expect(existsSync(join(empty, 'timeline.json'))).toBe(false)
72
+ }, 60_000)
73
+ })
@@ -0,0 +1,106 @@
1
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import puppeteer, { type Browser, type Page } from 'puppeteer-core'
4
+ import type { DemoBeat, DemoTimeline } from '../../../fe/components/DemoFilm/_types'
5
+ import { resolveChromePath } from '../chrome'
6
+ import { createDirector } from './director'
7
+ import type { CaptureRole, CaptureRunOptions, CaptureRunResult } from './types'
8
+
9
+ function launch(executablePath: string, headed: boolean): Promise<Browser> {
10
+ return puppeteer.launch({
11
+ executablePath,
12
+ headless: !headed,
13
+ args: [
14
+ '--no-first-run',
15
+ '--hide-scrollbars',
16
+ '--force-color-profile=srgb',
17
+ '--disable-renderer-backgrounding',
18
+ '--disable-background-timer-throttling',
19
+ '--disable-backgrounding-occluded-windows',
20
+ ],
21
+ })
22
+ }
23
+
24
+ /** True when every role has a value: narrows the partial map without a cast. */
25
+ function isComplete<Role extends string, T>(
26
+ roles: readonly Role[],
27
+ map: Partial<Record<Role, T>>
28
+ ): map is Record<Role, T> {
29
+ return roles.every((role) => map[role] !== undefined)
30
+ }
31
+
32
+ /** One window per role (a tab behind another is hidden and stops painting). */
33
+ async function openRole<Role extends string>(
34
+ browser: Browser,
35
+ role: Role,
36
+ spec: CaptureRole,
37
+ options: CaptureRunOptions<Role>
38
+ ): Promise<Page> {
39
+ const page = await (await browser.createBrowserContext()).newPage()
40
+ page.on('pageerror', (error) => {
41
+ console.error(`[capture:${role}] ${error instanceof Error ? error.message : String(error)}`)
42
+ })
43
+ const { width, height, scale } = spec.viewport
44
+ await page.setViewport({ width, height, deviceScaleFactor: scale })
45
+ await page.emulateMediaFeatures([
46
+ { name: 'prefers-color-scheme', value: options.colorScheme ?? options.theme },
47
+ ])
48
+ if (options.preload !== undefined) await page.evaluateOnNewDocument(options.preload)
49
+ const cookies = options.cookies?.[role] ?? []
50
+ if (cookies.length > 0) await page.browserContext().setCookie(...cookies)
51
+ if (spec.url !== undefined) await page.goto(spec.url, { waitUntil: 'domcontentloaded' })
52
+ return page
53
+ }
54
+
55
+ /**
56
+ * Captures a demo run from the real product: opens a page per role in headless Chrome, hands the
57
+ * scenario a director that drives the pages and takes beats, and writes `frames/` and a
58
+ * `timeline.json` the DemoFilm kit plays and `renderFilm` encodes. A scenario that throws stops the
59
+ * run and writes no timeline, so a film is only ever made from a run that went through.
60
+ */
61
+ export async function captureRun<Role extends string>(
62
+ options: CaptureRunOptions<Role>
63
+ ): Promise<CaptureRunResult<Role>> {
64
+ const started = performance.now()
65
+ const framesDir = join(options.outDir, 'frames')
66
+ rmSync(options.outDir, { recursive: true, force: true })
67
+ mkdirSync(framesDir, { recursive: true })
68
+ const browser = await launch(resolveChromePath(options.chromePath), options.headed === true)
69
+ const beats: DemoBeat<Role>[] = []
70
+ let frames = 0
71
+ const roleNames = Object.keys(options.roles).filter((name): name is Role => name in options.roles)
72
+ try {
73
+ const pages = new Map<Role, Page>()
74
+ for (const role of roleNames)
75
+ pages.set(role, await openRole(browser, role, options.roles[role], options))
76
+ const director = createDirector({
77
+ pages,
78
+ framesDir,
79
+ format: options.format ?? 'webp',
80
+ quality: options.quality ?? 92,
81
+ beats,
82
+ onFrame: () => {
83
+ frames += 1
84
+ },
85
+ })
86
+ await options.scenario(director)
87
+ } finally {
88
+ await browser.close().catch(() => undefined)
89
+ }
90
+ if (beats.length === 0) throw new Error('The scenario took no beats')
91
+ const viewports: Partial<Record<Role, CaptureRole['viewport']>> = {}
92
+ for (const role of roleNames) viewports[role] = options.roles[role].viewport
93
+ if (!isComplete(roleNames, viewports)) throw new Error('A role has no viewport')
94
+ const timeline: DemoTimeline<Role> = {
95
+ version: 1,
96
+ locale: options.locale,
97
+ theme: options.theme,
98
+ ...(options.fixture === true ? { fixture: true } : {}),
99
+ recordedAt: new Date().toISOString(),
100
+ viewports,
101
+ beats,
102
+ }
103
+ const timelinePath = join(options.outDir, 'timeline.json')
104
+ writeFileSync(timelinePath, `${JSON.stringify(timeline, null, 2)}\n`)
105
+ return { timelinePath, timeline, frames, seconds: (performance.now() - started) / 1000 }
106
+ }
@@ -0,0 +1,110 @@
1
+ import { join } from 'node:path'
2
+ import type { Page } from 'puppeteer-core'
3
+ import type { DemoBeat, DemoBox, DemoFrame } from '../../../fe/components/DemoFilm/_types'
4
+ import type { BurstOptions, CaptureFormat, Director, SettleOptions, SnapOptions } from './types'
5
+
6
+ interface DirectorSetup<Role extends string> {
7
+ pages: ReadonlyMap<Role, Page>
8
+ framesDir: string
9
+ format: CaptureFormat
10
+ quality: number
11
+ beats: DemoBeat<Role>[]
12
+ onFrame: () => void
13
+ }
14
+
15
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
16
+
17
+ /** The next free `bNN` id after the beats taken so far. */
18
+ function nextId(beats: readonly DemoBeat<string>[]): string {
19
+ return `b${String(beats.length + 1).padStart(2, '0')}`
20
+ }
21
+
22
+ /** A selector's box on screen in CSS pixels, or the box given; a selector that matches nothing is a scenario bug and throws. */
23
+ async function boxOf(page: Page, target: string | DemoBox): Promise<DemoBox | null> {
24
+ if (typeof target !== 'string') return target
25
+ const element = await page.$(target)
26
+ if (element === null) throw new Error(`Highlight selector matched nothing: ${target}`)
27
+ const box = await element.boundingBox()
28
+ await element.dispose()
29
+ return box === null ? null : { x: box.x, y: box.y, w: box.width, h: box.height }
30
+ }
31
+
32
+ /**
33
+ * The camera a scenario holds: a page per role, a settle that waits for a still screen, and snaps
34
+ * that write each role's screen into `frames/` and record the beat for the timeline.
35
+ */
36
+ export function createDirector<Role extends string>(setup: DirectorSetup<Role>): Director<Role> {
37
+ const { pages, framesDir, format, quality, beats, onFrame } = setup
38
+
39
+ const page = (role: Role): Page => {
40
+ const found = pages.get(role)
41
+ if (found === undefined) throw new Error(`No page for role ${role}`)
42
+ return found
43
+ }
44
+
45
+ const settle = async (role: Role, options: SettleOptions = {}): Promise<void> => {
46
+ const target = page(role)
47
+ await target
48
+ .waitForNetworkIdle({ idleTime: options.idleMs ?? 400, timeout: options.timeoutMs ?? 6000 })
49
+ .catch(() => undefined)
50
+ await target.evaluate(async () => {
51
+ await document.fonts.ready
52
+ await new Promise<void>((done) =>
53
+ requestAnimationFrame(() => requestAnimationFrame(() => done()))
54
+ )
55
+ })
56
+ }
57
+
58
+ const capture = async (
59
+ id: string,
60
+ role: Role,
61
+ highlight: string | DemoBox | undefined
62
+ ): Promise<DemoFrame> => {
63
+ const name = `${id}-${role}.${format}`
64
+ await page(role).screenshot({
65
+ path: join(framesDir, name),
66
+ type: format,
67
+ ...(format === 'png' ? {} : { quality }),
68
+ })
69
+ onFrame()
70
+ return {
71
+ image: `frames/${name}`,
72
+ highlight: highlight === undefined ? null : await boxOf(page(role), highlight),
73
+ }
74
+ }
75
+
76
+ const snap = async (options: SnapOptions<Role>): Promise<string> => {
77
+ const id = options.id ?? nextId(beats)
78
+ if (beats.some((beat) => beat.id === id)) throw new Error(`Beat id ${id} is taken`)
79
+ const roles = options.roles ?? [options.focus]
80
+ const frames: Partial<Record<Role, DemoFrame>> = {}
81
+ for (const role of roles) frames[role] = await capture(id, role, options.highlight?.[role])
82
+ beats.push({
83
+ id,
84
+ caption: options.caption,
85
+ frames,
86
+ focus: options.focus,
87
+ seconds: options.seconds,
88
+ })
89
+ return id
90
+ }
91
+
92
+ const burst = async (options: BurstOptions<Role>): Promise<string[]> => {
93
+ if (options.count < 1) throw new Error('A burst needs at least one beat')
94
+ const ids: string[] = []
95
+ for (let index = 0; index < options.count; index += 1) {
96
+ if (index > 0) await sleep(options.everyMs)
97
+ ids.push(
98
+ await snap({
99
+ caption: options.caption,
100
+ focus: options.focus,
101
+ seconds: options.seconds / options.count,
102
+ highlight: index === options.count - 1 ? options.highlight : undefined,
103
+ })
104
+ )
105
+ }
106
+ return ids
107
+ }
108
+
109
+ return { page, settle, snap, burst, wait: sleep }
110
+ }
@@ -0,0 +1,12 @@
1
+ export { captureRun } from './captureRun'
2
+ export type {
3
+ BurstOptions,
4
+ CaptureCookie,
5
+ CaptureFormat,
6
+ CaptureRole,
7
+ CaptureRunOptions,
8
+ CaptureRunResult,
9
+ Director,
10
+ SettleOptions,
11
+ SnapOptions,
12
+ } from './types'
@@ -0,0 +1,102 @@
1
+ import type { Page } from 'puppeteer-core'
2
+ import type {
3
+ DemoBox,
4
+ DemoText,
5
+ DemoTheme,
6
+ DemoTimeline,
7
+ DemoViewport,
8
+ } from '../../../fe/components/DemoFilm/_types'
9
+
10
+ /** One role of a run: the screen size it is captured at and where its page opens. */
11
+ export interface CaptureRole {
12
+ viewport: DemoViewport
13
+ /** Opened before the scenario starts; the scenario may navigate anywhere after. */
14
+ url?: string
15
+ }
16
+
17
+ /** A cookie set on a role's page before its first navigation. */
18
+ export interface CaptureCookie {
19
+ name: string
20
+ value: string
21
+ /** The host the cookie belongs to, e.g. `localhost`. */
22
+ domain: string
23
+ path?: string
24
+ }
25
+
26
+ /** One beat of the film: what to say, whose screen to show, what to capture and ring. */
27
+ export interface SnapOptions<Role extends string> {
28
+ /** Stable id `b01`..`b99`; the next free one when left out. */
29
+ id?: string
30
+ caption: DemoText
31
+ /** The role the film shows for this beat. */
32
+ focus: Role
33
+ /** Seconds the film spends on this beat. */
34
+ seconds: number
35
+ /** Roles whose screen is captured now; only the focus when left out. */
36
+ roles?: Role[]
37
+ /** A CSS selector (its box on screen) or a box, per role, ringed in this beat. */
38
+ highlight?: Partial<Record<Role, string | DemoBox>>
39
+ }
40
+
41
+ /** Several beats of one role a short time apart: text streaming in, a clock, a progress bar. */
42
+ export interface BurstOptions<Role extends string> extends Omit<SnapOptions<Role>, 'id' | 'roles'> {
43
+ /** Beats to take; the burst's `seconds` are split evenly over them. */
44
+ count: number
45
+ /** Real time between two captures, in milliseconds. */
46
+ everyMs: number
47
+ }
48
+
49
+ export interface SettleOptions {
50
+ /** Network quiet for this long counts as idle; 400 ms by default. */
51
+ idleMs?: number
52
+ /** Gives up waiting for idle after this long (an open stream never idles); 6 s by default. */
53
+ timeoutMs?: number
54
+ }
55
+
56
+ /** What a scenario drives: one page per role, and the camera. */
57
+ export interface Director<Role extends string> {
58
+ page: (role: Role) => Page
59
+ /** Waits for the network to go quiet, the fonts and two painted frames: a still screen. */
60
+ settle: (role: Role, options?: SettleOptions) => Promise<void>
61
+ /** Captures the beat's roles and records the beat; returns its id. */
62
+ snap: (options: SnapOptions<Role>) => Promise<string>
63
+ /** Captures `count` beats of the focus role, `everyMs` apart; returns their ids. */
64
+ burst: (options: BurstOptions<Role>) => Promise<string[]>
65
+ /** Real time passing between two actions, in milliseconds. */
66
+ wait: (ms: number) => Promise<void>
67
+ }
68
+
69
+ export type CaptureFormat = 'webp' | 'png' | 'jpeg'
70
+
71
+ export interface CaptureRunOptions<Role extends string> {
72
+ /** The run folder: cleared, then `frames/` and `timeline.json` are written into it. */
73
+ outDir: string
74
+ roles: Record<Role, CaptureRole>
75
+ /** Caption language the film starts in. */
76
+ locale: string
77
+ theme: DemoTheme
78
+ /** Drives the product and takes the beats, in order. */
79
+ scenario: (director: Director<Role>) => Promise<void>
80
+ /** `webp` by default. */
81
+ format?: CaptureFormat
82
+ /** 0-100 for webp and jpeg; 92 by default. */
83
+ quality?: number
84
+ chromePath?: string
85
+ cookies?: Partial<Record<Role, CaptureCookie[]>>
86
+ /** Script run before the page's own on every navigation (a fixed clock, a theme switch). */
87
+ preload?: string
88
+ /** The `prefers-color-scheme` the pages see; follows `theme` when left out. */
89
+ colorScheme?: DemoTheme
90
+ /** Shows the browser windows while capturing, for writing a scenario. */
91
+ headed?: boolean
92
+ /** Marks the run as a placeholder a public page must not show. */
93
+ fixture?: boolean
94
+ }
95
+
96
+ export interface CaptureRunResult<Role extends string> {
97
+ timelinePath: string
98
+ timeline: DemoTimeline<Role>
99
+ /** Files written under `frames/`. */
100
+ frames: number
101
+ seconds: number
102
+ }
@@ -0,0 +1,66 @@
1
+ import { afterAll, describe, expect, test } from 'bun:test'
2
+ import { createFixtureServer, matchPath, sseFrame } from '.'
3
+
4
+ describe('matchPath', () => {
5
+ test('named segments become params', () => {
6
+ expect(
7
+ matchPath('/llm/api/v1/conversations/:id/messages', '/llm/api/v1/conversations/c-7/messages')
8
+ ).toEqual({ id: 'c-7' })
9
+ })
10
+ test('a different length or literal does not match', () => {
11
+ expect(matchPath('/a/:b', '/a')).toBeNull()
12
+ expect(matchPath('/a/b', '/a/c')).toBeNull()
13
+ })
14
+ test('a trailing * takes the rest of the path', () => {
15
+ expect(matchPath('/cdn/*', '/cdn/x/y.png')).toEqual({ '*': 'x/y.png' })
16
+ })
17
+ test('a RegExp hands over its named groups', () => {
18
+ expect(matchPath(/^\/agents\/(?<id>[^/]+)$/, '/agents/a1')).toEqual({ id: 'a1' })
19
+ })
20
+ })
21
+
22
+ describe('sseFrame', () => {
23
+ test('JSON data, event and id in wire order', () => {
24
+ expect(sseFrame({ data: { a: 1 }, event: 'chunk', id: '3' })).toBe(
25
+ 'event: chunk\nid: 3\ndata: {"a":1}\n\n'
26
+ )
27
+ })
28
+ test('a multi-line string becomes one data line per line', () => {
29
+ expect(sseFrame({ data: 'x\ny' })).toBe('data: x\ndata: y\n\n')
30
+ })
31
+ })
32
+
33
+ describe('createFixtureServer', () => {
34
+ const server = createFixtureServer({
35
+ routes: [
36
+ { path: '/me', json: { id: 'u1', name: 'Demo' } },
37
+ {
38
+ method: 'POST',
39
+ path: '/echo/:id',
40
+ json: async (c) => ({ id: c.params.id ?? '', body: await c.text() }),
41
+ },
42
+ { path: '/stream', sse: { events: [{ data: { n: 1 } }, { data: { n: 2 }, delayMs: 20 }] } },
43
+ ],
44
+ })
45
+ afterAll(() => server.stop())
46
+
47
+ test('answers JSON and dynamic JSON with params and body', async () => {
48
+ expect(await (await fetch(`${server.origin}/me`)).json()).toEqual({ id: 'u1', name: 'Demo' })
49
+ const echoed = await fetch(`${server.origin}/echo/42`, { method: 'POST', body: 'hi' })
50
+ expect(await echoed.json()).toEqual({ id: '42', body: 'hi' })
51
+ })
52
+
53
+ test('plays an SSE script in order', async () => {
54
+ const response = await fetch(`${server.origin}/stream`)
55
+ expect(response.headers.get('content-type')).toBe('text/event-stream')
56
+ expect(await response.text()).toBe('data: {"n":1}\n\ndata: {"n":2}\n\n')
57
+ })
58
+
59
+ test('records what no route answers, and answers CORS', async () => {
60
+ const missing = await fetch(`${server.origin}/nowhere?x=1`)
61
+ expect(missing.status).toBe(404)
62
+ expect(missing.headers.get('access-control-allow-origin')).toBe('*')
63
+ expect(server.unmatched()).toEqual([{ method: 'GET', path: '/nowhere', status: 404 }])
64
+ expect(server.hits().map((hit) => hit.path)).toContain('/me')
65
+ })
66
+ })
@@ -0,0 +1,13 @@
1
+ export { findRoute, matchPath } from './match'
2
+ export { createFixtureServer } from './server'
3
+ export { sseFrame, sseResponse } from './sse'
4
+ export type {
5
+ FixtureContext,
6
+ FixtureRequestRecord,
7
+ FixtureRoute,
8
+ FixtureServer,
9
+ FixtureServerOptions,
10
+ JsonValue,
11
+ SseEvent,
12
+ SseScript,
13
+ } from './types'
@@ -0,0 +1,46 @@
1
+ import type { FixtureRoute } from './types'
2
+
3
+ /** The params a route's path takes from `path`, or null when it does not match. */
4
+ export function matchPath(pattern: string | RegExp, path: string): Record<string, string> | null {
5
+ if (pattern instanceof RegExp) {
6
+ const found = pattern.exec(path)
7
+ if (found === null) return null
8
+ const params: Record<string, string> = {}
9
+ for (const [name, value] of Object.entries(found.groups ?? {})) {
10
+ if (value !== undefined) params[name] = value
11
+ }
12
+ return params
13
+ }
14
+ const want = pattern.split('/').filter(Boolean)
15
+ const have = path.split('/').filter(Boolean)
16
+ const rest = want.at(-1) === '*'
17
+ if (rest ? have.length < want.length - 1 : have.length !== want.length) return null
18
+ const params: Record<string, string> = {}
19
+ for (let index = 0; index < want.length; index += 1) {
20
+ const segment = want[index]
21
+ if (segment === '*' && index === want.length - 1) {
22
+ params['*'] = have.slice(index).join('/')
23
+ return params
24
+ }
25
+ const value = have[index]
26
+ if (segment === undefined || value === undefined) return null
27
+ if (segment.startsWith(':')) params[segment.slice(1)] = decodeURIComponent(value)
28
+ else if (segment !== value) return null
29
+ }
30
+ return params
31
+ }
32
+
33
+ /** The first route that answers `method` on `path`, with its params. */
34
+ export function findRoute(
35
+ routes: readonly FixtureRoute[],
36
+ method: string,
37
+ path: string
38
+ ): { route: FixtureRoute; params: Record<string, string> } | null {
39
+ for (const route of routes) {
40
+ const wanted = (route.method ?? 'GET').toUpperCase()
41
+ if (wanted !== '*' && wanted !== method.toUpperCase()) continue
42
+ const params = matchPath(route.path, path)
43
+ if (params !== null) return { route, params }
44
+ }
45
+ return null
46
+ }
@@ -0,0 +1,80 @@
1
+ import { findRoute } from './match'
2
+ import { sseResponse } from './sse'
3
+ import type {
4
+ FixtureContext,
5
+ FixtureRequestRecord,
6
+ FixtureRoute,
7
+ FixtureServer,
8
+ FixtureServerOptions,
9
+ } from './types'
10
+
11
+ const CORS: Record<string, string> = {
12
+ 'access-control-allow-origin': '*',
13
+ 'access-control-allow-methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
14
+ 'access-control-allow-headers': '*',
15
+ }
16
+
17
+ async function answer(
18
+ route: FixtureRoute,
19
+ context: FixtureContext,
20
+ headers: Record<string, string>
21
+ ) {
22
+ const status = route.status ?? 200
23
+ const all = { ...headers, ...route.headers }
24
+ if (route.respond !== undefined) return route.respond(context)
25
+ if (route.sse !== undefined) {
26
+ const script = typeof route.sse === 'function' ? await route.sse(context) : route.sse
27
+ return sseResponse(script, all)
28
+ }
29
+ const body = typeof route.json === 'function' ? await route.json(context) : (route.json ?? null)
30
+ return Response.json(body, { status, headers: all })
31
+ }
32
+
33
+ /**
34
+ * A stand-in API for capturing a product with its own UI and data you choose: every request is
35
+ * answered from the routes (JSON, a scripted SSE stream, or a handler), and every request no route
36
+ * answers is recorded, so writing a scenario is a loop of "run, read `unmatched()`, add a route".
37
+ */
38
+ export function createFixtureServer(options: FixtureServerOptions): FixtureServer {
39
+ const cors = options.cors !== false
40
+ const headers = cors ? CORS : {}
41
+ const hits: FixtureRequestRecord[] = []
42
+ const misses: FixtureRequestRecord[] = []
43
+ const server = Bun.serve({
44
+ port: options.port ?? 0,
45
+ hostname: options.hostname ?? '127.0.0.1',
46
+ idleTimeout: 0,
47
+ async fetch(request) {
48
+ const url = new URL(request.url)
49
+ if (cors && request.method === 'OPTIONS') return new Response(null, { status: 204, headers })
50
+ const found = findRoute(options.routes, request.method, url.pathname)
51
+ if (found === null) {
52
+ const status = options.unmatchedStatus ?? 404
53
+ misses.push({ method: request.method, path: url.pathname, status })
54
+ return Response.json({ error: 'no fixture', path: url.pathname }, { status, headers })
55
+ }
56
+ let body: string | null = null
57
+ const context: FixtureContext = {
58
+ request,
59
+ url,
60
+ params: found.params,
61
+ text: async () => {
62
+ body ??= await request.text()
63
+ return body
64
+ },
65
+ }
66
+ const response = await answer(found.route, context, headers)
67
+ hits.push({ method: request.method, path: url.pathname, status: response.status })
68
+ return response
69
+ },
70
+ })
71
+ return {
72
+ origin: `http://${server.hostname}:${server.port}`,
73
+ port: server.port ?? 0,
74
+ unmatched: () => [...misses],
75
+ hits: () => [...hits],
76
+ stop: async () => {
77
+ await server.stop(true)
78
+ },
79
+ }
80
+ }
@@ -0,0 +1,42 @@
1
+ import type { SseEvent, SseScript } from './types'
2
+
3
+ const encoder = new TextEncoder()
4
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
5
+
6
+ /** One event in the wire format: `event:`, `id:`, then `data:` lines and a blank line. */
7
+ export function sseFrame(event: SseEvent): string {
8
+ const body = typeof event.data === 'string' ? event.data : JSON.stringify(event.data)
9
+ const head = [
10
+ ...(event.event === undefined ? [] : [`event: ${event.event}`]),
11
+ ...(event.id === undefined ? [] : [`id: ${event.id}`]),
12
+ ]
13
+ const data = body.split('\n').map((line) => `data: ${line}`)
14
+ return `${[...head, ...data].join('\n')}\n\n`
15
+ }
16
+
17
+ /** A response that plays the script in real time: each event after its delay. */
18
+ export function sseResponse(script: SseScript, headers: Record<string, string>): Response {
19
+ let cancelled = false
20
+ const stream = new ReadableStream<Uint8Array>({
21
+ async start(controller) {
22
+ for (const event of script.events) {
23
+ if (event.delayMs !== undefined && event.delayMs > 0) await sleep(event.delayMs)
24
+ if (cancelled) return
25
+ controller.enqueue(encoder.encode(sseFrame(event)))
26
+ }
27
+ if (script.holdOpenMs !== undefined && script.holdOpenMs > 0) await sleep(script.holdOpenMs)
28
+ if (!cancelled) controller.close()
29
+ },
30
+ cancel() {
31
+ cancelled = true
32
+ },
33
+ })
34
+ return new Response(stream, {
35
+ headers: {
36
+ 'content-type': 'text/event-stream',
37
+ 'cache-control': 'no-cache',
38
+ connection: 'keep-alive',
39
+ ...headers,
40
+ },
41
+ })
42
+ }
@@ -0,0 +1,76 @@
1
+ /** Any value JSON can carry: what a fixture answers with. */
2
+ export type JsonValue =
3
+ | string
4
+ | number
5
+ | boolean
6
+ | null
7
+ | JsonValue[]
8
+ | { [key: string]: JsonValue }
9
+
10
+ /** What a dynamic fixture receives. */
11
+ export interface FixtureContext {
12
+ request: Request
13
+ url: URL
14
+ /** Values of the route's `:name` segments (or the RegExp's named groups). */
15
+ params: Record<string, string>
16
+ /** The request body as text, read once and kept. */
17
+ text: () => Promise<string>
18
+ }
19
+
20
+ /** One event of a scripted Server-Sent Events stream. */
21
+ export interface SseEvent {
22
+ /** A string is sent as is; anything else as JSON. */
23
+ data: JsonValue
24
+ event?: string
25
+ id?: string
26
+ /** Wait before this event, in milliseconds: how a reply streams in. */
27
+ delayMs?: number
28
+ }
29
+
30
+ export interface SseScript {
31
+ events: SseEvent[]
32
+ /** Keeps the stream open this long after the last event; it closes at once by default. */
33
+ holdOpenMs?: number
34
+ }
35
+
36
+ type Dynamic<T> = T | ((context: FixtureContext) => T | Promise<T>)
37
+
38
+ /** One answer of the fixture server. Exactly one of `json`, `sse` or `respond`. */
39
+ export interface FixtureRoute {
40
+ /** `GET` by default; `*` answers every method. */
41
+ method?: string
42
+ /** `/llm/api/v1/conversations/:id` style, or a RegExp tested against the path. */
43
+ path: string | RegExp
44
+ status?: number
45
+ headers?: Record<string, string>
46
+ json?: Dynamic<JsonValue>
47
+ sse?: Dynamic<SseScript>
48
+ respond?: (context: FixtureContext) => Response | Promise<Response>
49
+ }
50
+
51
+ export interface FixtureServerOptions {
52
+ routes: FixtureRoute[]
53
+ /** 0 picks a free port; 0 by default. */
54
+ port?: number
55
+ hostname?: string
56
+ /** Answers CORS preflights and adds `Access-Control-Allow-*` to every answer; on by default. */
57
+ cors?: boolean
58
+ /** Status of a request no route answers; 404 by default (the miss is recorded either way). */
59
+ unmatchedStatus?: number
60
+ }
61
+
62
+ export interface FixtureRequestRecord {
63
+ method: string
64
+ path: string
65
+ status: number
66
+ }
67
+
68
+ export interface FixtureServer {
69
+ origin: string
70
+ port: number
71
+ /** Requests no route answered, in order: the endpoints a scenario still has to describe. */
72
+ unmatched: () => FixtureRequestRecord[]
73
+ /** Every request answered, in order. */
74
+ hits: () => FixtureRequestRecord[]
75
+ stop: () => Promise<void>
76
+ }
@@ -1,11 +1,15 @@
1
1
  /**
2
- * `nucleus-core-ts/demo-film`: renders a demo film (the compositions an app builds from
3
- * `nucleus-core-ts/fe`'s DemoFilm kit) to MP4 or PNG stills with headless Chrome. Server side only,
2
+ * `nucleus-core-ts/demo-film`: captures a demo run from the real product (`captureRun`, against its
3
+ * own UI and a fixture API from `createFixtureServer`), and renders demo films (the compositions an
4
+ * app builds from `nucleus-core-ts/fe`'s DemoFilm kit) to MP4 or PNG stills with headless Chrome.
5
+ * Server side only,
4
6
  * run by Bun. `puppeteer-core` and `mp4-muxer` are optional peer dependencies: install them in the
5
7
  * app that renders.
6
8
  */
7
9
 
10
+ export * from './capture'
8
11
  export { resolveChromePath } from './chrome'
12
+ export * from './fixtures'
9
13
  export { renderFilm } from './renderFilm'
10
14
  export { renderStill } from './renderStill'
11
15
  export { runAssetBase } from './session'