@cslug/vue 0.0.0-stage → 0.1.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.
- package/README.md +10 -2
- package/docs/README.md +25 -0
- package/docs/api.md +28 -0
- package/package.json +53 -4
- package/src/build-entry.ts +2 -0
- package/src/build.ts +190 -0
- package/src/client/data.ts +26 -0
- package/src/client/index.ts +124 -0
- package/src/commands.ts +56 -0
- package/src/compiler.ts +215 -0
- package/src/composables.ts +93 -0
- package/src/dev.ts +72 -0
- package/src/env.d.ts +3 -0
- package/src/index.ts +29 -0
- package/src/loader.ts +41 -0
- package/src/mount-stub.ts +11 -0
- package/src/provider.ts +33 -0
- package/src/register.ts +4 -0
- package/src/render.ts +248 -0
- package/src/serialize.ts +50 -0
- package/src/shared/form.ts +88 -0
- package/src/shared/format.ts +52 -0
- package/src/shared/store.ts +33 -0
- package/src/shared/url.ts +35 -0
- package/src/types.ts +12 -0
package/src/compiler.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
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
|
+
export function compileSfc(filename: string, options: CompileOptions): CompiledSfc {
|
|
137
|
+
const source = rewriteIslands(readFileSync(filename, 'utf8'), filename)
|
|
138
|
+
const id = componentId(filename, options.root)
|
|
139
|
+
const hash = Bun.hash(id).toString(16).slice(0, 8)
|
|
140
|
+
const { descriptor, errors } = parse(source, { filename })
|
|
141
|
+
if (errors.length)
|
|
142
|
+
throw new Error(`${filename}: ${errors.map((e) => (e instanceof Error ? e.message : String(e))).join('; ')}`)
|
|
143
|
+
if (!descriptor.script && !descriptor.scriptSetup && !descriptor.template)
|
|
144
|
+
throw new Error(`${filename}: empty component`)
|
|
145
|
+
|
|
146
|
+
const scoped = descriptor.styles.some((s) => s.scoped)
|
|
147
|
+
const scopeId = `data-v-${hash}`
|
|
148
|
+
let code: string
|
|
149
|
+
if (descriptor.script || descriptor.scriptSetup) {
|
|
150
|
+
code = compileScript(descriptor, {
|
|
151
|
+
id: hash,
|
|
152
|
+
inlineTemplate: true,
|
|
153
|
+
genDefaultAs: '_sfc_main',
|
|
154
|
+
isProd: options.production,
|
|
155
|
+
fs: { fileExists: existsSync, readFile: (f) => readFileSync(f, 'utf8') },
|
|
156
|
+
templateOptions: { ssr: options.ssr, ssrCssVars: [], compilerOptions: { scopeId: scoped ? scopeId : undefined } },
|
|
157
|
+
}).content
|
|
158
|
+
} else {
|
|
159
|
+
// template only: compile it alone
|
|
160
|
+
const t = compileTemplate({
|
|
161
|
+
source: descriptor.template?.content ?? '',
|
|
162
|
+
filename,
|
|
163
|
+
id: hash,
|
|
164
|
+
ssr: options.ssr,
|
|
165
|
+
ssrCssVars: [],
|
|
166
|
+
scoped,
|
|
167
|
+
compilerOptions: { scopeId: scoped ? scopeId : undefined },
|
|
168
|
+
})
|
|
169
|
+
if (t.errors.length) throw new Error(`${filename}: ${t.errors.join('; ')}`)
|
|
170
|
+
code = `${t.code}\nconst _sfc_main = { ${options.ssr ? 'ssrRender' : 'render'} }`
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const css = descriptor.styles
|
|
174
|
+
.map((s) => {
|
|
175
|
+
const lang = s.lang ?? 'css'
|
|
176
|
+
if (lang !== 'css' && lang !== 'scss')
|
|
177
|
+
throw new Error(`${filename}: <style lang="${lang}"> is not supported (use css or scss)`)
|
|
178
|
+
const plain = lang === 'scss' ? compileScss(s.content, filename, options.root) : s.content
|
|
179
|
+
const out = compileStyle({ source: plain, filename, id: scopeId, scoped: s.scoped, isProd: options.production })
|
|
180
|
+
if (out.errors.length) throw new Error(`${filename}: ${out.errors.map((e) => e.message).join('; ')}`)
|
|
181
|
+
return out.code
|
|
182
|
+
})
|
|
183
|
+
.join('\n')
|
|
184
|
+
|
|
185
|
+
const lines = [
|
|
186
|
+
code,
|
|
187
|
+
`_sfc_main.__cslugId = ${JSON.stringify(id)}`,
|
|
188
|
+
scoped ? `_sfc_main.__scopeId = ${JSON.stringify(scopeId)}` : '',
|
|
189
|
+
options.production ? '' : `_sfc_main.__file = ${JSON.stringify(filename)}`,
|
|
190
|
+
]
|
|
191
|
+
// server: record that this component rendered (its CSS goes into the page) and which namespaces islands need
|
|
192
|
+
if (options.ssr) {
|
|
193
|
+
lines.push(
|
|
194
|
+
`import { useSSRContext as __cslugCtx } from 'vue'`,
|
|
195
|
+
`const __cslugSetup = _sfc_main.setup`,
|
|
196
|
+
`_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 }`,
|
|
197
|
+
)
|
|
198
|
+
}
|
|
199
|
+
lines.push('export default _sfc_main')
|
|
200
|
+
return { code: lines.filter(Boolean).join('\n'), css, id }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Compiled results by file, reused while the file is unchanged. */
|
|
204
|
+
export class SfcCache {
|
|
205
|
+
private readonly entries = new Map<string, { mtime: number; result: CompiledSfc }>()
|
|
206
|
+
get(filename: string, options: CompileOptions): CompiledSfc {
|
|
207
|
+
const key = `${options.ssr ? 's' : 'c'}:${filename}`
|
|
208
|
+
const mtime = statSync(filename).mtimeMs
|
|
209
|
+
const hit = this.entries.get(key)
|
|
210
|
+
if (hit && hit.mtime === mtime) return hit.result
|
|
211
|
+
const result = compileSfc(filename, options)
|
|
212
|
+
this.entries.set(key, { mtime, result })
|
|
213
|
+
return result
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -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 { 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: unknown
|
|
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.constructor.name !== 'MissingSession'
|
|
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?: unknown }).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
package/src/index.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
type RenderOptions,
|
|
20
|
+
type RenderState,
|
|
21
|
+
readManifest,
|
|
22
|
+
renderPage,
|
|
23
|
+
renderStandalone,
|
|
24
|
+
ViewResponse,
|
|
25
|
+
view,
|
|
26
|
+
} from './render'
|
|
27
|
+
export { type Serialized, serialize } from './serialize'
|
|
28
|
+
export { csrfHeaders, type Form, useForm } from './shared/form'
|
|
29
|
+
export { defineStore } from './shared/store'
|
package/src/loader.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
let registered: string | undefined
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Teach Bun to import `.vue` files (compiled for the server). `VueProvider` calls this; tests that import views
|
|
11
|
+
* statically need it earlier, through bunfig.toml: `[test] preload = ["@cslug/vue/register"]`.
|
|
12
|
+
*/
|
|
13
|
+
export function registerVueLoader(root: string = process.cwd(), options: { production?: boolean } = {}): void {
|
|
14
|
+
if (registered) {
|
|
15
|
+
if (registered !== root)
|
|
16
|
+
throw new CslugError('vue.loader_root', `The .vue loader is already registered for ${registered}`)
|
|
17
|
+
return
|
|
18
|
+
}
|
|
19
|
+
registered = root
|
|
20
|
+
Bun.plugin({
|
|
21
|
+
name: 'cslug-vue-server',
|
|
22
|
+
setup(build) {
|
|
23
|
+
// `@/…` → resources/… (as in the browser build)
|
|
24
|
+
build.onResolve({ filter: /^@\// }, (args) => ({
|
|
25
|
+
path: Bun.resolveSync(`${root}/resources/${args.path.slice(2)}`, root),
|
|
26
|
+
}))
|
|
27
|
+
build.onLoad({ filter: /\.vue$/ }, ({ path }) => {
|
|
28
|
+
let compiled: CompiledSfc
|
|
29
|
+
try {
|
|
30
|
+
compiled = cache.get(path, { root, ssr: true, production: options.production })
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw new CslugError('vue.compile', error instanceof Error ? error.message : String(error), { cause: error })
|
|
33
|
+
}
|
|
34
|
+
componentStyles.set(compiled.id, compiled.css)
|
|
35
|
+
return { contents: compiled.code, loader: 'ts' }
|
|
36
|
+
})
|
|
37
|
+
},
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const vueLoaderRoot = () => registered
|
|
@@ -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
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -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
|
+
}
|
package/src/register.ts
ADDED