@cslug/vue 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Compile a `.vue` SFC for the server (SSR) or the browser, with cslug's island rewrite. Shared by the runtime
3
+ * loader (server) and the `Bun.build` plugin (browser), so both sides compile identical input.
4
+ */
5
+ import { existsSync, readFileSync, statSync } from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import { join, relative } from 'node:path'
8
+ import { pathToFileURL } from 'node:url'
9
+ import { compileScript, compileStyle, compileTemplate, MagicString, parse } from 'vue/compiler-sfc'
10
+
11
+ export type CompiledSfc = { code: string; css: string; id: string }
12
+ export type CompileOptions = {
13
+ /** The app root; `@/` and island ids are relative to `<root>/resources`. */
14
+ root: string
15
+ ssr: boolean
16
+ /** Production: no dev-only checks. */
17
+ production?: boolean
18
+ }
19
+
20
+ // Vue compiler-core AST node types (not exported by vue/compiler-sfc)
21
+ const ELEMENT = 1
22
+ const TEXT = 2
23
+ const COMMENT = 3
24
+ const COMPONENT = 1
25
+ const ATTRIBUTE = 6
26
+ const DIRECTIVE = 7
27
+
28
+ type AstNode = {
29
+ type: number
30
+ tag?: string
31
+ tagType?: number
32
+ isSelfClosing?: boolean
33
+ content?: string
34
+ loc: { start: { offset: number }; end: { offset: number } }
35
+ props?: {
36
+ type: number
37
+ name: string
38
+ value?: { content: string }
39
+ arg?: { content: string }
40
+ exp?: { content: string }
41
+ loc: AstNode['loc']
42
+ }[]
43
+ children?: AstNode[]
44
+ }
45
+
46
+ const pascal = (tag: string) => tag.replace(/(^|-)(\w)/g, (_m, _d, c: string) => c.toUpperCase())
47
+
48
+ /**
49
+ * `<X hydrate="visible" …/>` → `<CslugIsland :island-component="X" island-hydrate="visible" …/>`, in the source,
50
+ * before Vue compiles it (a compiler nodeTransform only reaches the browser build: the SSR compiler resolves
51
+ * components first; see spikes/a-vue-islands). Slot content is an error, except a `#fallback` template, which
52
+ * is shown until a `:ssr="false"` island mounts.
53
+ */
54
+ export function rewriteIslands(source: string, filename: string): string {
55
+ const { descriptor } = parse(source, { filename })
56
+ const ast = descriptor.template?.ast as AstNode | undefined
57
+ if (!ast) return source
58
+ const out = new MagicString(source)
59
+ const visit = (nodes: AstNode[]) => {
60
+ for (const node of nodes) {
61
+ if (node.type === ELEMENT && node.tagType === COMPONENT && node.tag && node.tag !== 'CslugIsland') {
62
+ const attr = node.props?.find((p) => p.type === ATTRIBUTE && p.name === 'hydrate')
63
+ const bound = node.props?.find((p) => p.type === DIRECTIVE && p.name === 'bind' && p.arg?.content === 'hydrate')
64
+ if (bound)
65
+ throw new Error(
66
+ `${filename}: <${node.tag} :hydrate> must be a literal (hydrate="visible"): the build needs to see it`,
67
+ )
68
+ if (attr) {
69
+ const mode = attr.value?.content ?? 'load'
70
+ if (!/^(load|idle|visible|none|media:.+)$/.test(mode)) {
71
+ throw new Error(`${filename}: <${node.tag} hydrate="${mode}">: use load, idle, visible, none or media:(…)`)
72
+ }
73
+ const content = (node.children ?? []).filter(
74
+ (c) => c.type !== COMMENT && !(c.type === TEXT && !c.content?.trim()),
75
+ )
76
+ const onlyFallback = content.every(
77
+ (c) =>
78
+ c.tag === 'template' &&
79
+ c.props?.some((p) => p.type === DIRECTIVE && p.name === 'slot' && p.arg?.content === 'fallback'),
80
+ )
81
+ if (content.length && !onlyFallback) {
82
+ throw new Error(
83
+ `${filename}: <${node.tag} hydrate> cannot receive slot content (it would be lost when the island hydrates); pass props instead`,
84
+ )
85
+ }
86
+ const start = node.loc.start.offset
87
+ out.overwrite(start + 1, start + 1 + node.tag.length, 'CslugIsland')
88
+ out.overwrite(
89
+ attr.loc.start.offset,
90
+ attr.loc.end.offset,
91
+ `:island-component="${pascal(node.tag)}" island-hydrate="${mode}"`,
92
+ )
93
+ if (!node.isSelfClosing) {
94
+ const close = source.lastIndexOf(`</${node.tag}`, node.loc.end.offset)
95
+ out.overwrite(close + 2, close + 2 + node.tag.length, 'CslugIsland')
96
+ }
97
+ }
98
+ }
99
+ if (node.children) visit(node.children)
100
+ }
101
+ }
102
+ visit(ast.children ?? [])
103
+ return out.toString()
104
+ }
105
+
106
+ /** The id of a component: its path under `resources/` without `.vue` (`components/day-card`). */
107
+ export function componentId(filename: string, root: string): string {
108
+ const resources = join(root, 'resources')
109
+ const base = filename.startsWith(resources) ? resources : root
110
+ return relative(base, filename)
111
+ .replace(/\\/g, '/')
112
+ .replace(/\.vue$/, '')
113
+ }
114
+
115
+ /** SCSS → CSS with `sass` (optional peer), `@/` resolving to `resources/`. */
116
+ export function compileScss(source: string, filename: string, root: string): string {
117
+ let sass: typeof import('sass')
118
+ try {
119
+ sass = createRequire(join(root, 'package.json'))('sass')
120
+ } catch {
121
+ throw new Error(`${filename}: <style lang="scss"> needs the sass package: bun add -d sass`)
122
+ }
123
+ const resources = join(root, 'resources')
124
+ return sass.compileString(source, {
125
+ url: pathToFileURL(filename),
126
+ loadPaths: [resources, root],
127
+ importers: [
128
+ {
129
+ findFileUrl: (url: string) =>
130
+ url.startsWith('@/') ? new URL(pathToFileURL(join(resources, url.slice(2)))) : null,
131
+ },
132
+ ],
133
+ }).css
134
+ }
135
+
136
+ /** Compile one `.vue` file to a module (server or client build), with its scoped CSS. */
137
+ export function compileSfc(filename: string, options: CompileOptions): CompiledSfc {
138
+ const source = rewriteIslands(readFileSync(filename, 'utf8'), filename)
139
+ const id = componentId(filename, options.root)
140
+ const hash = Bun.hash(id).toString(16).slice(0, 8)
141
+ const { descriptor, errors } = parse(source, { filename })
142
+ if (errors.length)
143
+ throw new Error(`${filename}: ${errors.map((e) => (e instanceof Error ? e.message : String(e))).join('; ')}`)
144
+ if (!descriptor.script && !descriptor.scriptSetup && !descriptor.template)
145
+ throw new Error(`${filename}: empty component`)
146
+
147
+ const scoped = descriptor.styles.some((s) => s.scoped)
148
+ const scopeId = `data-v-${hash}`
149
+ let code: string
150
+ if (descriptor.script || descriptor.scriptSetup) {
151
+ code = compileScript(descriptor, {
152
+ id: hash,
153
+ inlineTemplate: true,
154
+ genDefaultAs: '_sfc_main',
155
+ isProd: options.production,
156
+ fs: { fileExists: existsSync, readFile: (f) => readFileSync(f, 'utf8') },
157
+ templateOptions: { ssr: options.ssr, ssrCssVars: [], compilerOptions: { scopeId: scoped ? scopeId : undefined } },
158
+ }).content
159
+ } else {
160
+ // template only: compile it alone
161
+ const t = compileTemplate({
162
+ source: descriptor.template?.content ?? '',
163
+ filename,
164
+ id: hash,
165
+ ssr: options.ssr,
166
+ ssrCssVars: [],
167
+ scoped,
168
+ compilerOptions: { scopeId: scoped ? scopeId : undefined },
169
+ })
170
+ if (t.errors.length) throw new Error(`${filename}: ${t.errors.join('; ')}`)
171
+ code = `${t.code}\nconst _sfc_main = { ${options.ssr ? 'ssrRender' : 'render'} }`
172
+ }
173
+
174
+ const css = descriptor.styles
175
+ .map((s) => {
176
+ const lang = s.lang ?? 'css'
177
+ if (lang !== 'css' && lang !== 'scss')
178
+ throw new Error(`${filename}: <style lang="${lang}"> is not supported (use css or scss)`)
179
+ const plain = lang === 'scss' ? compileScss(s.content, filename, options.root) : s.content
180
+ const out = compileStyle({ source: plain, filename, id: scopeId, scoped: s.scoped, isProd: options.production })
181
+ if (out.errors.length) throw new Error(`${filename}: ${out.errors.map((e) => e.message).join('; ')}`)
182
+ return out.code
183
+ })
184
+ .join('\n')
185
+
186
+ const lines = [
187
+ code,
188
+ `_sfc_main.__cslugId = ${JSON.stringify(id)}`,
189
+ scoped ? `_sfc_main.__scopeId = ${JSON.stringify(scopeId)}` : '',
190
+ options.production ? '' : `_sfc_main.__file = ${JSON.stringify(filename)}`,
191
+ ]
192
+ // server: record that this component rendered (its CSS goes into the page) and which namespaces islands need
193
+ if (options.ssr) {
194
+ lines.push(
195
+ `import { useSSRContext as __cslugCtx } from 'vue'`,
196
+ `const __cslugSetup = _sfc_main.setup`,
197
+ `_sfc_main.setup = function (props, ctx) { const s = __cslugCtx(); if (s && s.modules) s.modules.add(${JSON.stringify(id)}); return __cslugSetup ? __cslugSetup.call(this, props, ctx) : undefined }`,
198
+ )
199
+ }
200
+ lines.push('export default _sfc_main')
201
+ return { code: lines.filter(Boolean).join('\n'), css, id }
202
+ }
203
+
204
+ /** Compiled results by file, reused while the file is unchanged. */
205
+ export class SfcCache {
206
+ private readonly entries = new Map<string, { mtime: number; result: CompiledSfc }>()
207
+ get(filename: string, options: CompileOptions): CompiledSfc {
208
+ const key = `${options.ssr ? 's' : 'c'}:${filename}`
209
+ const mtime = statSync(filename).mtimeMs
210
+ const hit = this.entries.get(key)
211
+ if (hit && hit.mtime === mtime) return hit.result
212
+ const result = compileSfc(filename, options)
213
+ this.entries.set(key, { mtime, result })
214
+ return result
215
+ }
216
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Composables for views and components. These are the server versions; the browser build (M4b) resolves
3
+ * `@cslug/vue` to versions with the same names and signatures.
4
+ */
5
+ import { type AuthUser, currentApp, currentLocale, formatDate, formatMoney, Translator, t, tr } from '@cslug/core'
6
+ import { route as httpRoute, Router, type UrlOptions } from '@cslug/http'
7
+ import { renderState } from './render'
8
+ import { formatDurationIn } from './shared/format'
9
+
10
+ export type RequestInfo = {
11
+ locale: string
12
+ /** The signed-in user (set by @cslug/auth), or null. */
13
+ user: AuthUser | null
14
+ csrfToken: string
15
+ /** First error message per field, after a failed form post. */
16
+ errors: Record<string, string>
17
+ /** The previous form input. */
18
+ old: Record<string, unknown>
19
+ /** Flashed messages (`success`, `error`, …). */
20
+ flash: Record<string, unknown>
21
+ url: string
22
+ /** This page in each supported locale (for `<link rel="alternate" hreflang>`), when its route has `:locale`. */
23
+ alternates: { locale: string; url: string }[]
24
+ }
25
+
26
+ /** The current request, read-only, on the server. Inside a hydrated island it throws: pass props instead. */
27
+ export function useRequest(): RequestInfo {
28
+ const ctx = renderState()?.http
29
+ if (!ctx) {
30
+ return {
31
+ locale: currentLocale(),
32
+ user: null,
33
+ csrfToken: '',
34
+ errors: {},
35
+ old: {},
36
+ flash: {},
37
+ url: '',
38
+ alternates: [],
39
+ }
40
+ }
41
+ const hasSession = ctx.session.available
42
+ const errors = hasSession
43
+ ? Object.fromEntries(Object.entries(ctx.session.errors()).map(([k, v]) => [k, v[0] ?? '']))
44
+ : {}
45
+ const url = new URL(ctx.request.url)
46
+ return {
47
+ locale: ctx.locale,
48
+ user: (ctx as unknown as { user?: AuthUser | null }).user ?? null,
49
+ csrfToken: hasSession ? ctx.session.token() : '',
50
+ errors,
51
+ old: hasSession ? (ctx.session.old() as Record<string, unknown>) : {},
52
+ flash: hasSession ? ctx.session.flashed() : {},
53
+ url: url.toString(),
54
+ alternates: alternates(ctx, url),
55
+ }
56
+ }
57
+
58
+ function alternates(
59
+ ctx: NonNullable<ReturnType<typeof renderState>>['http'] & object,
60
+ url: URL,
61
+ ): RequestInfo['alternates'] {
62
+ if (!ctx.routeName || ctx.params.locale === undefined) return []
63
+ const app = currentApp()
64
+ const locales = app.resolve(Translator).locales
65
+ if (!app.resolve(Router).byName(ctx.routeName)) return []
66
+ return locales.map((locale) => ({
67
+ locale,
68
+ url: httpRoute(ctx.routeName as string, { ...ctx.params, locale }, { absolute: true }) + url.search,
69
+ }))
70
+ }
71
+
72
+ /** Translations in the current locale: `t(key, params)`, `tr(translatedColumn)`, and the formatters. */
73
+ export function useT() {
74
+ const locale = currentLocale()
75
+ return {
76
+ locale,
77
+ t: (key: string, params?: Record<string, unknown>) => t(key, params, locale),
78
+ tr: (value: Partial<Record<string, string>> | string | null | undefined) => tr(value, locale),
79
+ formatMoney: (amount: Parameters<typeof formatMoney>[0], currency?: string) =>
80
+ formatMoney(amount, currency, locale),
81
+ formatDate: (value: Parameters<typeof formatDate>[0], style?: Parameters<typeof formatDate>[1]) =>
82
+ formatDate(value, style, { locale }),
83
+ }
84
+ }
85
+
86
+ /** A URL from a route name (same as @cslug/http's `route`; also available in the browser). */
87
+ export const route = (name: string, params?: Record<string, unknown>, options?: UrlOptions): string =>
88
+ httpRoute(name, params, options)
89
+
90
+ /** Minutes as "2 h 30 min" (locale-aware unit names via Intl). */
91
+ export const formatDuration = (minutes: number, locale = currentLocale()): string => formatDurationIn(locale, minutes)
92
+
93
+ export { formatDate, formatMoney }
package/src/dev.ts ADDED
@@ -0,0 +1,72 @@
1
+ import { watch } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { type Application, Logger } from '@cslug/core'
4
+ import type { RouteRegistrar } from '@cslug/http'
5
+ import { buildAssets } from './build'
6
+
7
+ const LIVE = '/__cslug/live'
8
+ let enabled = false
9
+ const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
10
+
11
+ /** The live-reload endpoint when `cslug dev` runs (CSLUG_DEV=1), else undefined. */
12
+ export const liveReloadUrl = () => (enabled ? LIVE : undefined)
13
+
14
+ function broadcast(event: 'reload' | 'css'): void {
15
+ const chunk = new TextEncoder().encode(`event: ${event}\ndata: {}\n\n`)
16
+ for (const c of clients) {
17
+ try {
18
+ c.enqueue(chunk)
19
+ } catch {
20
+ clients.delete(c)
21
+ }
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Development: build the assets now, rebuild when resources/ changes, and tell open pages to reload (CSS-only
27
+ * changes swap the stylesheets). Server-side `.vue` changes restart the process (`bun --watch`); pages reconnect
28
+ * and reload.
29
+ */
30
+ export async function startDev(app: Application, options: Parameters<typeof buildAssets>[0]): Promise<() => void> {
31
+ enabled = true
32
+ const log = app.resolve(Logger)
33
+ const rebuild = async (css: boolean) => {
34
+ try {
35
+ const { ms } = await buildAssets(options)
36
+ log.info('vue.assets_built', { ms })
37
+ broadcast(css ? 'css' : 'reload')
38
+ } catch (error) {
39
+ log.error('vue.assets_failed', { error })
40
+ }
41
+ }
42
+ await rebuild(false)
43
+ let timer: ReturnType<typeof setTimeout> | undefined
44
+ const watcher = watch(join(app.rootDir, 'resources'), { recursive: true }, (_event, file) => {
45
+ clearTimeout(timer)
46
+ timer = setTimeout(() => rebuild(/\.(s?css)$/.test(String(file))), 50)
47
+ })
48
+ return () => {
49
+ watcher.close()
50
+ for (const c of clients) c.close()
51
+ clients.clear()
52
+ enabled = false
53
+ }
54
+ }
55
+
56
+ /** The SSE route pages connect to. */
57
+ export function liveRoute(r: RouteRegistrar): void {
58
+ r.get(LIVE, () => {
59
+ let self: ReadableStreamDefaultController<Uint8Array>
60
+ const body = new ReadableStream<Uint8Array>({
61
+ start(controller) {
62
+ self = controller
63
+ clients.add(controller)
64
+ controller.enqueue(new TextEncoder().encode(': connected\n\n'))
65
+ },
66
+ cancel() {
67
+ clients.delete(self)
68
+ },
69
+ })
70
+ return new Response(body, { headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-store' } })
71
+ })
72
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ // Stylesheets imported from client entries (`import './styles/app.scss'`) are bundled by `cslug build`.
2
+ declare module '*.scss' {}
3
+ declare module '*.css' {}
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @cslug/vue: Vue views rendered on the server, components hydrated as islands (`hydrate="…"`), composables,
3
+ * `<Assets>`, `serialize()` / `Serialized<T>`, and `renderStandalone()` for self-contained HTML files.
4
+ */
5
+ /// <reference path="./env.d.ts" />
6
+ import './types'
7
+
8
+ export { buildAssets } from './build'
9
+ export { BuildCommand, TypecheckCommand } from './commands'
10
+ export { type CompiledSfc, type CompileOptions, compileSfc, componentId, rewriteIslands } from './compiler'
11
+ export { formatDate, formatDuration, formatMoney, type RequestInfo, route, useRequest, useT } from './composables'
12
+ export { registerVueLoader } from './loader'
13
+ export { mountIslands } from './mount-stub'
14
+ export { VueProvider } from './provider'
15
+ export {
16
+ type AssetManifest,
17
+ Assets,
18
+ CslugIsland,
19
+ onView,
20
+ type RenderOptions,
21
+ type RenderState,
22
+ readManifest,
23
+ renderPage,
24
+ renderStandalone,
25
+ ViewResponse,
26
+ view,
27
+ } from './render'
28
+ export { type Serialized, serialize } from './serialize'
29
+ export { csrfHeaders, type Form, useForm } from './shared/form'
30
+ export { defineStore } from './shared/store'
package/src/loader.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { CslugError } from '@cslug/core'
2
+ import { type CompiledSfc, SfcCache } from './compiler'
3
+
4
+ /** CSS of every compiled component, by component id (collected into the page when it renders). */
5
+ export const componentStyles = new Map<string, string>()
6
+ const cache = new SfcCache()
7
+ const roots = new Map<string, { production?: boolean }>()
8
+
9
+ /** The registered app root containing `file` (the longest one), else the first registered. */
10
+ function rootOf(file: string): string {
11
+ let best: string | undefined
12
+ for (const root of roots.keys()) if (file.startsWith(`${root}/`) && (!best || root.length > best.length)) best = root
13
+ return best ?? (roots.keys().next().value as string)
14
+ }
15
+
16
+ /**
17
+ * Teach Bun to import `.vue` files (compiled for the server). `VueProvider` calls this; tests that import views
18
+ * statically need it earlier, through bunfig.toml: `[test] preload = ["@cslug/vue/register"]`.
19
+ * Several roots may be registered in one process (test suites with several fixture apps): each `.vue` file is
20
+ * compiled, and its `@/…` imports resolved, against the root that contains it.
21
+ */
22
+ export function registerVueLoader(root: string = process.cwd(), options: { production?: boolean } = {}): void {
23
+ if (roots.has(root)) return
24
+ roots.set(root, options)
25
+ if (roots.size > 1) return // the plugin is already installed
26
+ Bun.plugin({
27
+ name: 'cslug-vue-server',
28
+ setup(build) {
29
+ // `@/…` → resources/… (as in the browser build)
30
+ build.onResolve({ filter: /^@\// }, (args) => {
31
+ const base = rootOf(args.importer)
32
+ return { path: Bun.resolveSync(`${base}/resources/${args.path.slice(2)}`, base) }
33
+ })
34
+ build.onLoad({ filter: /\.vue$/ }, ({ path }) => {
35
+ const base = rootOf(path)
36
+ let compiled: CompiledSfc
37
+ try {
38
+ compiled = cache.get(path, { root: base, ssr: true, production: roots.get(base)?.production })
39
+ } catch (error) {
40
+ throw new CslugError('vue.compile', error instanceof Error ? error.message : String(error), { cause: error })
41
+ }
42
+ componentStyles.set(compiled.id, compiled.css)
43
+ return { contents: compiled.code, loader: 'ts' }
44
+ })
45
+ },
46
+ })
47
+ }
48
+
49
+ /** The first registered root. */
50
+ export const vueLoaderRoot = () => roots.keys().next().value as string | undefined
@@ -0,0 +1,11 @@
1
+ import type { App } from 'vue'
2
+
3
+ /**
4
+ * Hydrate the page's islands. Runs in the browser (resources/client.ts, bundled by `cslug build`, which resolves
5
+ * @cslug/vue to its browser entry); this server-side version only exists so client code type-checks.
6
+ */
7
+ export function mountIslands(
8
+ _options: { setup?: (app: App, island: { id: string; element: HTMLElement }) => void } = {},
9
+ ): void {
10
+ throw new Error('mountIslands() runs in the browser: call it from resources/client.ts')
11
+ }
@@ -0,0 +1,33 @@
1
+ import { ServiceProvider } from '@cslug/core'
2
+ import { Router } from '@cslug/http'
3
+ import { assetConfig, BuildCommand, TypecheckCommand } from './commands'
4
+ import { liveRoute, startDev } from './dev'
5
+ import { registerVueLoader } from './loader'
6
+
7
+ /**
8
+ * Registers the `.vue` loader (before the HTTP provider imports routes, controllers and views) and the `build`
9
+ * and `typecheck` commands. Under `cslug dev` (CSLUG_DEV=1) it also builds the assets, rebuilds them on change,
10
+ * and serves live reload.
11
+ */
12
+ export class VueProvider extends ServiceProvider {
13
+ private stopDev?: () => void
14
+
15
+ register() {
16
+ this.commands([BuildCommand, TypecheckCommand])
17
+ registerVueLoader(this.app.rootDir, { production: this.app.config('app.env') === 'production' })
18
+ }
19
+
20
+ async boot() {
21
+ if (process.env.CSLUG_DEV !== '1' || this.app.config('app.env') === 'production') return
22
+ this.app.resolve(Router).load(liveRoute)
23
+ this.stopDev = await startDev(this.app, {
24
+ root: this.app.rootDir,
25
+ dev: true,
26
+ ...(await assetConfig(this.app.rootDir)),
27
+ })
28
+ }
29
+
30
+ shutdown() {
31
+ this.stopDev?.()
32
+ }
33
+ }
@@ -0,0 +1,4 @@
1
+ /** `[test] preload = ["@cslug/vue/register"]` in bunfig.toml: import `.vue` files from the first line. */
2
+ import { registerVueLoader } from './loader'
3
+
4
+ registerVueLoader(process.cwd())