C6: Runtime kernel owns data, status, error — adapters subscribe

The kernel is no longer a blind refetch pipe. Each context entry has:
  { data, status: idle|loading|success|error, error }

registerContext() returns { getState, subscribe, refetch, unregister }.
Adapters subscribe to state changes via callbacks. The kernel does
the fetch and notifies subscribers with the new state.

React adapter uses useSyncExternalStore for tear-free reads.
Vue adapter uses ref + subscribe callback.
Svelte adapter uses readable store backed by kernel subscription.

All three adapters also get:
- Mutation hooks with { mutate, isPending, error } (fixes H5)
- Vue: onServerPrefetch for Nuxt SSR (fixes M9)
- Svelte: readable store auto-cleans up on unsubscribe (fixes H9)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-07 12:38:53 -04:00
parent 07f1c7842c
commit bb88fd984b
7 changed files with 586 additions and 361 deletions

View File

@@ -1,5 +1,7 @@
/**
* Vue Stage 2 — Generates composables from Stage 1 output.
*
* Subscribes to the kernel for state. Vue reactivity wraps kernel notifications.
*/
function pascalCase(str) {
@@ -15,12 +17,11 @@ export function generateVueAdapter(schema) {
const lines = [
'// AUTO-GENERATED by mizan — do not edit',
'',
"import { ref, computed, watch, onMounted, onUnmounted, provide, inject, type Ref, type ComputedRef, type InjectionKey } from 'vue'",
"import { registerContext } from '@mizan/runtime'",
"import { ref, computed, onMounted, onUnmounted, onServerPrefetch, type ComputedRef } from 'vue'",
"import { registerContext, type ContextState } from '@mizan/runtime'",
'',
]
// Stage 1 imports
const stage1Imports = []
for (const [ctxName] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
@@ -34,72 +35,70 @@ export function generateVueAdapter(schema) {
lines.push('')
}
// ── Context composables ─────────────────────────────────────────────
for (const [ctxName, ctxMeta] of Object.entries(contextGroups)) {
const p = pascalCase(ctxName)
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
const paramEntries = Object.entries(ctxMeta.params || {})
const paramsArg = paramEntries.length > 0 ? 'params' : '{} as any'
lines.push(`// ${p} context`)
lines.push(`const ${p}Key: InjectionKey<{ data: Ref<${p}ContextData | null>, loading: Ref<boolean> }> = Symbol('${ctxName}')`)
lines.push('')
if (paramEntries.length > 0) {
lines.push(`export function use${p}Context(params: ${p}ContextParams) {`)
} else {
lines.push(`export function use${p}Context() {`)
}
// Provider composable
if (paramEntries.length > 0) {
lines.push(`export function provide${p}Context(params: { ${paramEntries.map(([k, v]) => `${k}: ${v.type === 'integer' || v.type === 'number' ? 'number' : 'string'}`).join(', ')} }) {`)
} else {
lines.push(`export function provide${p}Context() {`)
}
lines.push(` const data = ref<${p}ContextData | null>(null)`)
lines.push(` const loading = ref(true)`)
lines.push(` const state = ref<ContextState<${p}ContextData>>({ data: null, status: 'idle', error: null })`)
lines.push(` let handle: ReturnType<typeof registerContext> | null = null`)
lines.push('')
lines.push(` const refetch = async () => {`)
lines.push(` loading.value = true`)
lines.push(` try {`)
if (paramEntries.length > 0) {
lines.push(` data.value = await fetch${p}Context(params as any)`)
} else {
lines.push(` data.value = await fetch${p}Context({} as any)`)
}
lines.push(` } catch (e) { console.error('[mizan] ${ctxName} fetch failed:', e) }`)
lines.push(` loading.value = false`)
lines.push(` }`)
lines.push('')
lines.push(` let unregister: (() => void) | null = null`)
lines.push(` onMounted(() => {`)
lines.push(` refetch()`)
if (paramEntries.length > 0) {
lines.push(` unregister = registerContext('${ctxName}', params, refetch)`)
} else {
lines.push(` unregister = registerContext('${ctxName}', {}, refetch)`)
}
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
lines.push(` handle.subscribe(() => { state.value = handle!.getState() })`)
lines.push(` handle.refetch()`)
lines.push(` })`)
lines.push(` onUnmounted(() => { unregister?.() })`)
lines.push('')
lines.push(` provide(${p}Key, { data, loading })`)
lines.push(` onServerPrefetch(async () => {`)
lines.push(` handle = registerContext('${ctxName}', ${paramsArg}, () => fetch${p}Context(${paramsArg}))`)
lines.push(` await handle.refetch()`)
lines.push(` state.value = handle.getState()`)
lines.push(` })`)
lines.push('')
lines.push(` onUnmounted(() => { handle?.unregister() })`)
lines.push('')
lines.push(` return {`)
lines.push(` state,`)
for (const fn of ctxFunctions) {
lines.push(` ${fn.camelName}: computed(() => state.value.data?.${fn.name} ?? null) as ComputedRef<${fn.outputType} | null>,`)
}
lines.push(` loading: computed(() => state.value.status === 'loading'),`)
lines.push(` error: computed(() => state.value.error),`)
lines.push(` }`)
lines.push('}')
lines.push('')
// Consumer composables
for (const fn of ctxFunctions) {
const hookPascal = pascalCase(fn.camelName)
lines.push(`export function use${hookPascal}(): ComputedRef<${fn.outputType} | null> {`)
lines.push(` const ctx = inject(${p}Key)`)
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires provide${p}Context in a parent')`)
lines.push(` return computed(() => ctx.data.value?.${fn.name} ?? null)`)
lines.push('}')
lines.push('')
}
}
// ── Mutation composables ────────────────────────────────────────────
for (const fn of [...mutations, ...plainFns]) {
const p = pascalCase(fn.camelName)
lines.push(`export const use${p} = call${p}`)
lines.push(`export function use${p}() {`)
lines.push(` const isPending = ref(false)`)
lines.push(` const error = ref<Error | null>(null)`)
if (fn.hasInput) {
lines.push(` async function mutate(args: Parameters<typeof call${p}>[0]) {`)
} else {
lines.push(` async function mutate() {`)
}
lines.push(` isPending.value = true; error.value = null`)
lines.push(` try { return await call${p}(${fn.hasInput ? 'args' : ''}) }`)
lines.push(` catch (e) { error.value = e as Error; throw e }`)
lines.push(` finally { isPending.value = false }`)
lines.push(` }`)
lines.push(` return { mutate, isPending, error }`)
lines.push('}')
lines.push('')
}
lines.push("export type { ContextState } from '@mizan/runtime'")
lines.push("export { configure, initSession, MizanError } from '@mizan/runtime'")
lines.push('')
return lines.join('\n')
}