Two-stage codegen: React + Vue + Svelte from one schema
Stage 1 (framework-agnostic):
types.ts — OpenAPI interfaces
contexts/<name>.ts — fetchXxxContext(params) using mizanFetch
mutations/<name>.ts — callXxx(args) using mizanCall
functions/<name>.ts — callXxx(args) using mizanCall
index.ts — re-exports
Stage 2 (per framework):
react.tsx — hooks + context providers + SSR hydration
vue.ts — composables with provide/inject + ref/computed
svelte.ts — writable/derived store factories
New packages:
mizan-runtime — the kernel (~200 lines, zero framework deps)
configure(), initSession(), registerContext(), invalidate(),
mizanFetch(), mizanCall(), MizanError
mizan-vue — Vue adapter (package.json, codegen template)
mizan-svelte — Svelte adapter (package.json, codegen template)
CLI: mizan-generate --target react,vue,svelte
Config: target: 'react' (default) in django.config.mjs
Verified: codegen produces 33 functions across 2 contexts,
14 plain functions, 0 mutations, generating all three Stage 2
outputs from one schema fetch.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
160
packages/mizan-django/generate/generator/lib/adapters/react.mjs
Normal file
160
packages/mizan-django/generate/generator/lib/adapters/react.mjs
Normal file
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* React Stage 2 — Generates hooks + context providers from Stage 1 output.
|
||||
*/
|
||||
|
||||
function pascalCase(str) {
|
||||
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||
}
|
||||
|
||||
export function generateReactAdapter(schema) {
|
||||
const functions = schema['x-mizan-functions'] || []
|
||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||
const namedContexts = Object.entries(contextGroups).filter(([n]) => n !== 'global')
|
||||
const globalContexts = functions.filter(fn => fn.isContext === 'global')
|
||||
const mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||
const plainFns = functions.filter(fn => !fn.isContext && !fn.isForm && !fn.affects)
|
||||
|
||||
const lines = [
|
||||
"'use client'",
|
||||
'',
|
||||
'// AUTO-GENERATED by mizan — do not edit',
|
||||
'',
|
||||
"import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'",
|
||||
"import { registerContext, mizanCall, mizanFetch } from '@mizan/runtime'",
|
||||
'',
|
||||
]
|
||||
|
||||
// Import from Stage 1
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
stage1Imports.push(`fetch${p}Context`, `type ${p}ContextData`, `type ${p}ContextParams`)
|
||||
}
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// ── Global context hooks ────────────────────────────────────────────
|
||||
|
||||
if (globalContexts.length > 0) {
|
||||
const p = pascalCase('global')
|
||||
|
||||
lines.push(`// Global context — fetched once at app init`)
|
||||
lines.push(`const GlobalCtx = createContext<${p}ContextData | null>(null)`)
|
||||
lines.push('')
|
||||
|
||||
lines.push(`export function GlobalContextProvider({ children }: { children: ReactNode }) {`)
|
||||
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
|
||||
lines.push(` if (typeof window === 'undefined') return null`)
|
||||
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
|
||||
lines.push(` return ssr ?? null`)
|
||||
lines.push(` })`)
|
||||
lines.push('')
|
||||
lines.push(` const refetch = useCallback(async () => {`)
|
||||
lines.push(` const result = await fetch${p}Context({} as any)`)
|
||||
lines.push(` setData(result)`)
|
||||
lines.push(` }, [])`)
|
||||
lines.push('')
|
||||
lines.push(` useEffect(() => { if (!data) refetch() }, [data, refetch])`)
|
||||
lines.push(` useEffect(() => registerContext('global', {}, refetch), [refetch])`)
|
||||
lines.push('')
|
||||
lines.push(` return <GlobalCtx.Provider value={data}>{children}</GlobalCtx.Provider>`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
|
||||
for (const fn of globalContexts) {
|
||||
const hookPascal = pascalCase(fn.camelName)
|
||||
lines.push(`export function use${hookPascal}(): ${fn.outputType} {`)
|
||||
lines.push(` const ctx = useContext(GlobalCtx)`)
|
||||
lines.push(` if (!ctx) throw new Error('use${hookPascal} requires GlobalContextProvider')`)
|
||||
lines.push(` return ctx.${fn.name}`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
}
|
||||
}
|
||||
|
||||
// ── Named context providers ─────────────────────────────────────────
|
||||
|
||||
for (const [ctxName, ctxMeta] of namedContexts) {
|
||||
const p = pascalCase(ctxName)
|
||||
const ctxFunctions = functions.filter(fn => fn.isContext === ctxName)
|
||||
const paramEntries = Object.entries(ctxMeta.params || {})
|
||||
|
||||
lines.push(`// ${p} context`)
|
||||
lines.push(`const ${p}Ctx = createContext<${p}ContextData | null>(null)`)
|
||||
lines.push('')
|
||||
|
||||
// Provider
|
||||
lines.push(`export function ${p}Context({ children, ...params }: ${p}ContextParams & { children: ReactNode }) {`)
|
||||
lines.push(` const [data, setData] = useState<${p}ContextData | null>(() => {`)
|
||||
lines.push(` if (typeof window === 'undefined') return null`)
|
||||
lines.push(` const ssr = (window as any).__MIZAN_SSR_DATA__`)
|
||||
if (ctxFunctions.length > 0) {
|
||||
lines.push(` if (ssr?.${ctxFunctions[0].name} !== undefined) return ssr`)
|
||||
}
|
||||
lines.push(` return null`)
|
||||
lines.push(` })`)
|
||||
lines.push('')
|
||||
lines.push(` const refetch = useCallback(async () => {`)
|
||||
lines.push(` const result = await fetch${p}Context(params)`)
|
||||
lines.push(` setData(result)`)
|
||||
|
||||
const deps = paramEntries.map(([pName]) => `params.${pName}`)
|
||||
lines.push(` }, [${deps.join(', ')}])`)
|
||||
lines.push('')
|
||||
lines.push(` useEffect(() => { refetch() }, [refetch])`)
|
||||
lines.push(` useEffect(() => registerContext('${ctxName}', params, refetch), [${deps.join(', ')}, refetch])`)
|
||||
lines.push('')
|
||||
lines.push(` return <${p}Ctx.Provider value={data}>{children}</${p}Ctx.Provider>`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
|
||||
// Hooks
|
||||
for (const fn of ctxFunctions) {
|
||||
const hookPascal = pascalCase(fn.camelName)
|
||||
lines.push(`export function use${hookPascal}(): ${fn.outputType} | null {`)
|
||||
lines.push(` const ctx = useContext(${p}Ctx)`)
|
||||
lines.push(` return ctx?.${fn.name} ?? null`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mutation hooks ──────────────────────────────────────────────────
|
||||
|
||||
for (const fn of mutations) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
if (fn.hasInput) {
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` return useCallback((args: Parameters<typeof call${p}>[0]) => call${p}(args), [])`)
|
||||
lines.push('}')
|
||||
} else {
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` return useCallback(() => call${p}(), [])`)
|
||||
lines.push('}')
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// ── Plain function hooks ────────────────────────────────────────────
|
||||
|
||||
for (const fn of plainFns) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
if (fn.hasInput) {
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` return useCallback((args: Parameters<typeof call${p}>[0]) => call${p}(args), [])`)
|
||||
lines.push('}')
|
||||
} else {
|
||||
lines.push(`export function use${p}() {`)
|
||||
lines.push(` return useCallback(() => call${p}(), [])`)
|
||||
lines.push('}')
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Svelte Stage 2 — Generates stores from Stage 1 output.
|
||||
*/
|
||||
|
||||
function pascalCase(str) {
|
||||
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||
}
|
||||
|
||||
export function generateSvelteAdapter(schema) {
|
||||
const functions = schema['x-mizan-functions'] || []
|
||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||
const mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||
const plainFns = functions.filter(fn => !fn.isContext && !fn.isForm && !fn.affects)
|
||||
|
||||
const lines = [
|
||||
'// AUTO-GENERATED by mizan — do not edit',
|
||||
'',
|
||||
"import { writable, derived, type Readable } from 'svelte/store'",
|
||||
"import { registerContext } from '@mizan/runtime'",
|
||||
'',
|
||||
]
|
||||
|
||||
// Stage 1 imports
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
stage1Imports.push(`fetch${p}Context`, `type ${p}ContextData`, `type ${p}ContextParams`)
|
||||
}
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// ── Context stores ──────────────────────────────────────────────────
|
||||
|
||||
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 || {})
|
||||
|
||||
lines.push(`// ${p} context`)
|
||||
|
||||
if (paramEntries.length > 0) {
|
||||
lines.push(`export function create${p}Context(params: ${p}ContextParams) {`)
|
||||
} else {
|
||||
lines.push(`export function create${p}Context() {`)
|
||||
}
|
||||
|
||||
lines.push(` const data = writable<${p}ContextData | null>(null)`)
|
||||
lines.push(` const loading = writable(true)`)
|
||||
lines.push('')
|
||||
lines.push(` const refetch = async () => {`)
|
||||
lines.push(` loading.set(true)`)
|
||||
if (paramEntries.length > 0) {
|
||||
lines.push(` const result = await fetch${p}Context(params)`)
|
||||
} else {
|
||||
lines.push(` const result = await fetch${p}Context({} as any)`)
|
||||
}
|
||||
lines.push(` data.set(result)`)
|
||||
lines.push(` loading.set(false)`)
|
||||
lines.push(` }`)
|
||||
lines.push('')
|
||||
lines.push(` refetch()`)
|
||||
if (paramEntries.length > 0) {
|
||||
lines.push(` const unregister = registerContext('${ctxName}', params, refetch)`)
|
||||
} else {
|
||||
lines.push(` const unregister = registerContext('${ctxName}', {}, refetch)`)
|
||||
}
|
||||
lines.push('')
|
||||
|
||||
// Derived stores for each function
|
||||
lines.push(` return {`)
|
||||
lines.push(` data,`)
|
||||
lines.push(` loading,`)
|
||||
for (const fn of ctxFunctions) {
|
||||
const camel = fn.camelName
|
||||
lines.push(` ${camel}: derived(data, $d => $d?.${fn.name} ?? null) as Readable<${fn.outputType} | null>,`)
|
||||
}
|
||||
lines.push(` destroy: unregister,`)
|
||||
lines.push(` }`)
|
||||
lines.push('}')
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
// ── Mutation + function exports ─────────────────────────────────────
|
||||
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
const p = pascalCase(fn.camelName)
|
||||
lines.push(`export { call${p} } from '../${fn.affects ? 'mutations' : 'functions'}/${fn.camelName}'`)
|
||||
}
|
||||
lines.push('')
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
105
packages/mizan-django/generate/generator/lib/adapters/vue.mjs
Normal file
105
packages/mizan-django/generate/generator/lib/adapters/vue.mjs
Normal file
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Vue Stage 2 — Generates composables from Stage 1 output.
|
||||
*/
|
||||
|
||||
function pascalCase(str) {
|
||||
return str.split(/[.\-_]/).map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('')
|
||||
}
|
||||
|
||||
export function generateVueAdapter(schema) {
|
||||
const functions = schema['x-mizan-functions'] || []
|
||||
const contextGroups = schema['x-mizan-contexts'] || {}
|
||||
const mutations = functions.filter(fn => !fn.isContext && !fn.isForm && fn.affects)
|
||||
const plainFns = functions.filter(fn => !fn.isContext && !fn.isForm && !fn.affects)
|
||||
|
||||
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'",
|
||||
'',
|
||||
]
|
||||
|
||||
// Stage 1 imports
|
||||
const stage1Imports = []
|
||||
for (const [ctxName] of Object.entries(contextGroups)) {
|
||||
const p = pascalCase(ctxName)
|
||||
stage1Imports.push(`fetch${p}Context`, `type ${p}ContextData`, `type ${p}ContextParams`)
|
||||
}
|
||||
for (const fn of [...mutations, ...plainFns]) {
|
||||
stage1Imports.push(`call${pascalCase(fn.camelName)}`)
|
||||
}
|
||||
if (stage1Imports.length > 0) {
|
||||
lines.push(`import { ${stage1Imports.join(', ')} } from '../index'`)
|
||||
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 || {})
|
||||
|
||||
lines.push(`// ${p} context`)
|
||||
lines.push(`const ${p}Key: InjectionKey<{ data: Ref<${p}ContextData | null>, loading: Ref<boolean> }> = Symbol('${ctxName}')`)
|
||||
lines.push('')
|
||||
|
||||
// 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('')
|
||||
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(` })`)
|
||||
lines.push(` onUnmounted(() => { unregister?.() })`)
|
||||
lines.push('')
|
||||
lines.push(` provide(${p}Key, { data, loading })`)
|
||||
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('')
|
||||
}
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
Reference in New Issue
Block a user