vitrify 0.2.5 → 0.3.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.
@@ -1,9 +1,9 @@
1
1
  /// <reference types="node" />
2
2
  import type { FastifyInstance } from 'fastify';
3
- import type { SsrFunction } from '../../vitrify-config.js';
4
- export declare const createApp: ({ setup, appDir, baseUrl, ssrFunctions }: {
3
+ import type { OnRenderedHook } from '../../vitrify-config.js';
4
+ export declare const createApp: ({ setup, appDir, baseUrl, onRenderedHooks }: {
5
5
  setup: (fastify: FastifyInstance) => any;
6
6
  appDir: URL;
7
7
  baseUrl?: string | undefined;
8
- ssrFunctions?: SsrFunction[] | undefined;
8
+ onRenderedHooks?: OnRenderedHook[] | undefined;
9
9
  }) => FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance> & PromiseLike<FastifyInstance<import("http").Server, import("http").IncomingMessage, import("http").ServerResponse, import("fastify").FastifyLoggerInstance>>;
@@ -1,23 +1,4 @@
1
1
  /// <reference types="node" />
2
2
  import type { Server } from 'net';
3
3
  import type { ResolvedConfig } from 'vite';
4
- export declare const clearConsole: () => void;
5
- export declare const log: (msg?: string | undefined) => void;
6
- export declare const warn: (msg?: string | undefined, pill?: string | undefined) => void;
7
- export declare const fatal: (msg?: string | undefined, pill?: string | undefined) => never;
8
- /**
9
- * Extended approach - Compilation status & pills
10
- */
11
- export declare const successPill: (msg?: string | undefined) => string;
12
- export declare const infoPill: (msg?: string | undefined) => string;
13
- export declare const errorPill: (msg?: string | undefined) => string;
14
- export declare const warningPill: (msg?: string | undefined) => string;
15
- export declare const success: (msg?: string | undefined, title?: string) => void;
16
- export declare const getSuccess: (msg?: string | undefined, title?: string | undefined) => string;
17
- export declare const info: (msg?: string | undefined, title?: string) => void;
18
- export declare const getInfo: (msg?: string | undefined, title?: string | undefined) => string;
19
- export declare const error: (msg?: string | undefined, title?: string) => void;
20
- export declare const getError: (msg?: string | undefined, title?: string) => string;
21
- export declare const warning: (msg?: string | undefined, title?: string) => void;
22
- export declare const getWarning: (msg?: string | undefined, title?: string) => string;
23
4
  export declare function printHttpServerUrls(server: Server, config: ResolvedConfig): void;
@@ -7,32 +7,43 @@ export declare type BootFunction = ({ app, ssrContext, staticImports }: {
7
7
  ssrContext: Record<string, unknown>;
8
8
  staticImports: Record<string, any>;
9
9
  }) => Promise<void> | void;
10
+ export declare type OnBootHook = ({ app, ssrContext, staticImports }: {
11
+ app: any;
12
+ ssrContext: Record<string, unknown>;
13
+ staticImports: Record<string, any>;
14
+ }) => Promise<void> | void;
10
15
  export declare type OnMountedHook = (instance: ComponentInternalInstance) => Promise<void> | void;
11
16
  export declare type StaticImports = Record<string, string[]>;
12
17
  export declare type SsrFunction = (html: string, ssrContext: Record<string, any>) => string;
18
+ export declare type OnRenderedHook = (html: string, ssrContext: Record<string, any>) => string;
19
+ export declare type OnSetupHook = (fastify: FastifyInstance) => any;
13
20
  export interface VitrifyConfig extends UserConfig {
14
21
  vitrify?: {
15
22
  /**
16
23
  * Global CSS imports
17
24
  */
18
25
  globalCss?: string[];
19
- /**
20
- * Functions which run after initializing the app
21
- */
22
- bootFunctions?: BootFunction[];
23
- /**
24
- * Functions which run on the server after rendering the app
25
- */
26
- ssrFunctions?: SsrFunction[];
27
26
  /**
28
27
  * Static imports in the app: packageName: [imports]
29
28
  */
30
29
  staticImports?: StaticImports;
31
30
  hooks?: {
31
+ /**
32
+ * setup() is called directly after instantiating fastify. Use it to register your own plugins, routes etc.
33
+ */
34
+ onSetup?: OnSetupHook[];
32
35
  /**
33
36
  * Functions which run in the onMounted hook of the app
34
37
  */
35
- onMounted: OnMountedHook[];
38
+ onMounted?: OnMountedHook[];
39
+ /**
40
+ * Functions which run after initializing the app
41
+ */
42
+ onBoot?: OnBootHook[];
43
+ /**
44
+ * Functions which run after rendering the app (SSR)
45
+ */
46
+ onRendered?: OnRenderedHook[];
36
47
  };
37
48
  /**
38
49
  * Global SASS variables
@@ -41,12 +52,6 @@ export interface VitrifyConfig extends UserConfig {
41
52
  variables?: Record<string, string>;
42
53
  additionalData?: string[];
43
54
  };
44
- fastify?: {
45
- /**
46
- * setup() is called directly after instantiating fastify. Use it to register your own plugins, routes etc.
47
- */
48
- setup: (fastify: FastifyInstance) => any;
49
- };
50
55
  /**
51
56
  * Product name of the application. Will be used for the HTML title tag
52
57
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitrify",
3
- "version": "0.2.5",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "author": "Stefan van Herwijnen",
6
6
  "description": "Pre-configured Vite CLI for your framework",
@@ -14,7 +14,6 @@ export const getCliDir = () => getPkgJsonDir(new URL('./', import.meta.url))
14
14
  export const getCliViteDir = (cliDir: URL) => new URL('src/vite/', cliDir)
15
15
  export const getSrcDir = (appDir: URL) => new URL('src/', appDir)
16
16
  export const getCwd = () => new URL(`file://${process.cwd()}/`)
17
- // export const quasarDir = getPkgJsonDir(new URL('./', await resolve('quasar', appDir.href)))
18
17
 
19
18
  export const parsePath = (path: string, basePath: URL) => {
20
19
  if (path) {
@@ -1,53 +1,6 @@
1
1
  #!/usr/bin/node --experimental-specifier-resolution=node
2
2
  import { baseConfig } from '../index.js'
3
- // import { promises as fs } from 'fs'
4
- // import { routesToPaths } from '../helpers/routes.js'
5
3
  import { build as viteBuild } from 'vite'
6
- // import { SsrFunction } from '../vitrify-config.js'
7
-
8
- // export const prerender = async ({
9
- // outDir,
10
- // templatePath,
11
- // manifestPath,
12
- // entryServerPath,
13
- // injectSsrContext
14
- // }: {
15
- // outDir: string
16
- // templatePath: string
17
- // manifestPath: string
18
- // entryServerPath: string
19
- // injectSsrContext: SsrFunction
20
- // }) => {
21
- // let template
22
- // let manifest
23
- // const promises = []
24
- // template = (await fs.readFile(templatePath)).toString()
25
- // manifest = await fs.readFile(manifestPath)
26
- // let { render, getRoutes } = await import(entryServerPath)
27
- // const routes = await getRoutes()
28
- // const paths = routesToPaths(routes).filter(
29
- // (i) => !i.includes(':') && !i.includes('*')
30
- // )
31
- // for (let url of paths) {
32
- // const filename =
33
- // (url.endsWith('/') ? 'index' : url.replace(/^\//g, '')) + '.html'
34
- // console.log(`Generating ${filename}`)
35
- // const ssrContext = {
36
- // req: { headers: {}, url },
37
- // res: {}
38
- // }
39
- // const [appHtml, preloadLinks] = await render(url, manifest, ssrContext)
40
-
41
- // let html = template
42
- // .replace(`<!--preload-links-->`, preloadLinks)
43
- // .replace(`<!--app-html-->`, appHtml)
44
-
45
- // html = injectSsrContext(html, ssrContext)
46
-
47
- // promises.push(fs.writeFile(outDir + filename, html, 'utf-8'))
48
- // }
49
- // return Promise.all(promises)
50
- // }
51
4
 
52
5
  export async function build(opts: {
53
6
  ssr?: 'client' | 'server' | 'ssg'
@@ -17,7 +17,7 @@ cli
17
17
  .action(async (options) => {
18
18
  const { build } = await import('./build.js')
19
19
  let appDir: URL
20
- let prerender, ssrFunctions
20
+ let prerender, onRenderedHooks
21
21
  if (options.appDir) {
22
22
  if (options.appDir.slice(-1) !== '/') options.appDir += '/'
23
23
  appDir = new URL(`file://${options.appDir}`)
@@ -68,7 +68,7 @@ cli
68
68
  ...args,
69
69
  outDir: new URL('ssr/server/', baseOutDir).pathname
70
70
  })
71
- ;({ prerender, ssrFunctions } = await import(
71
+ ;({ prerender, onRenderedHooks } = await import(
72
72
  new URL('ssr/server/prerender.mjs', baseOutDir).pathname
73
73
  ))
74
74
  prerender({
@@ -78,7 +78,7 @@ cli
78
78
  .pathname,
79
79
  entryServerPath: new URL('ssr/server/entry-server.mjs', baseOutDir)
80
80
  .pathname,
81
- ssrFunctions
81
+ onRenderedHooks
82
82
  })
83
83
  break
84
84
  default:
@@ -28,7 +28,7 @@ export async function createServer({
28
28
  const cliDir = getCliDir()
29
29
  if (!appDir) appDir = getAppDir()
30
30
  const { fastifySsrPlugin } = await import(
31
- `../${framework}/fastify-ssr-plugin.js`
31
+ `../frameworks/${framework}/fastify-ssr-plugin.js`
32
32
  )
33
33
 
34
34
  /**
@@ -84,51 +84,7 @@ export async function createServer({
84
84
  vite,
85
85
  productName
86
86
  })
87
- // await app.register(middie)
88
- // app.use(vite.middlewares)
89
87
 
90
- // app.get('*', async (req, res) => {
91
- // try {
92
- // // const url = req.originalUrl
93
- // const url = req.raw.url
94
- // let template
95
- // let render
96
- // const ssrContext = {
97
- // req,
98
- // res
99
- // }
100
- // // always read fresh template in dev
101
- // // template = readFileSync(resolve('index.html'), 'utf-8')
102
- // template = readFileSync(new URL('index.html', cliDir)).toString()
103
-
104
- // // template = await vite.transformIndexHtml(url, template)
105
- // const entryUrl = new URL('ssr/entry-server.ts', cliDir).pathname
106
- // render = (await vite.ssrLoadModule(entryUrl)).render
107
- // let manifest
108
- // // TODO: https://github.com/vitejs/vite/issues/2282
109
- // try {
110
- // manifest = {}
111
- // } catch (e) {
112
- // manifest = {}
113
- // }
114
-
115
- // const [appHtml, preloadLinks] = await render(url, manifest, ssrContext)
116
- // const html = template
117
- // .replace(`<!--preload-links-->`, preloadLinks)
118
- // .replace(`<!--app-html-->`, appHtml)
119
- // .replace('<!--product-name-->', productName)
120
-
121
- // res.code(200)
122
- // res.type('text/html')
123
- // res.send(html)
124
- // // res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
125
- // } catch (e: any) {
126
- // console.error(e.stack)
127
- // vite && vite.ssrFixStacktrace(e)
128
- // res.code(500)
129
- // res.send(e.stack)
130
- // }
131
- // })
132
88
  await app.listen(port || 3000, host)
133
89
  server = app.server
134
90
  } else {
@@ -15,9 +15,6 @@ export async function test(opts: { appDir: URL }) {
15
15
 
16
16
  globals: true,
17
17
  environment: 'happy-dom'
18
- // include: [
19
- // `${opts.appDir.pathname}**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}`
20
- // ]
21
18
  },
22
19
  config
23
20
  )
@@ -5,9 +5,8 @@ import type {
5
5
  } from 'fastify'
6
6
  import fastifyStatic from 'fastify-static'
7
7
  import { readFileSync } from 'fs'
8
- // import { injectSsrContext } from '../helpers/ssr.js'
9
8
  import type { ViteDevServer } from 'vite'
10
- import type { SsrFunction } from '../../vitrify-config.js'
9
+ import type { OnRenderedHook } from '../../vitrify-config.js'
11
10
 
12
11
  export interface FastifySsrOptions {
13
12
  baseUrl?: string
@@ -19,7 +18,7 @@ export interface FastifySsrOptions {
19
18
  cliDir?: URL
20
19
  appDir?: URL
21
20
  productName?: string
22
- ssrFunctions?: SsrFunction[]
21
+ onRenderedHooks?: OnRenderedHook[]
23
22
  }
24
23
 
25
24
  const fastifySsrPlugin: FastifyPluginCallback<FastifySsrOptions> = async (
@@ -35,19 +34,15 @@ const fastifySsrPlugin: FastifyPluginCallback<FastifySsrOptions> = async (
35
34
 
36
35
  fastify.get('*', async (req, res) => {
37
36
  try {
38
- // const url = req.originalUrl
39
37
  const url = req.raw.url
40
38
  const ssrContext = {
41
39
  req,
42
40
  res
43
41
  }
44
- // always read fresh template in dev
45
- // template = readFileSync(resolve('index.html'), 'utf-8')
46
42
  const template = readFileSync(
47
43
  new URL('index.html', options.cliDir)
48
44
  ).toString()
49
45
 
50
- // template = await vite.transformIndexHtml(url, template)
51
46
  const entryUrl = new URL('ssr/entry-server.ts', options.cliDir).pathname
52
47
  const render = (await options.vite!.ssrLoadModule(entryUrl)).render
53
48
  let manifest
@@ -93,9 +88,6 @@ const fastifySsrPlugin: FastifyPluginCallback<FastifySsrOptions> = async (
93
88
  provide
94
89
  }
95
90
 
96
- // template = readFileSync(new URL('../client/index.html', import.meta.url).pathname).toString()
97
- // manifest = JSON.parse(readFileSync(new URL('../client/ssr-manifest.json', import.meta.url)).toString())
98
- // render = (await import(new URL('./entry-server.mjs', import.meta.url).pathname)).render
99
91
  const template = readFileSync(
100
92
  new URL('./dist/ssr/client/index.html', options.appDir).pathname
101
93
  ).toString()
@@ -119,8 +111,8 @@ const fastifySsrPlugin: FastifyPluginCallback<FastifySsrOptions> = async (
119
111
  .replace(`<!--preload-links-->`, preloadLinks)
120
112
  .replace(`<!--app-html-->`, appHtml)
121
113
 
122
- if (options.ssrFunctions?.length) {
123
- for (const ssrFunction of options.ssrFunctions) {
114
+ if (options.onRenderedHooks?.length) {
115
+ for (const ssrFunction of options.onRenderedHooks) {
124
116
  html = ssrFunction(html, ssrContext)
125
117
  }
126
118
  }
@@ -1,19 +1,19 @@
1
1
  import { promises as fs } from 'fs'
2
2
  import { routesToPaths } from '../../helpers/routes.js'
3
- import type { SsrFunction } from '../../vitrify-config.js'
3
+ import type { OnRenderedHook } from '../../vitrify-config.js'
4
4
 
5
5
  export const prerender = async ({
6
6
  outDir,
7
7
  templatePath,
8
8
  manifestPath,
9
9
  entryServerPath,
10
- ssrFunctions
10
+ onRenderedHooks
11
11
  }: {
12
12
  outDir: string
13
13
  templatePath: string
14
14
  manifestPath: string
15
15
  entryServerPath: string
16
- ssrFunctions: SsrFunction[]
16
+ onRenderedHooks: OnRenderedHook[]
17
17
  }) => {
18
18
  const promises = []
19
19
  const template = (await fs.readFile(templatePath)).toString()
@@ -37,8 +37,8 @@ export const prerender = async ({
37
37
  .replace(`<!--preload-links-->`, preloadLinks)
38
38
  .replace(`<!--app-html-->`, appHtml)
39
39
 
40
- if (ssrFunctions?.length) {
41
- for (const ssrFunction of ssrFunctions) {
40
+ if (onRenderedHooks?.length) {
41
+ for (const ssrFunction of onRenderedHooks) {
42
42
  html = ssrFunction(html, ssrContext)
43
43
  }
44
44
  }
@@ -1,20 +1,18 @@
1
1
  import type { FastifyInstance } from 'fastify'
2
2
  import fastify from 'fastify'
3
- import type { SsrFunction } from '../../vitrify-config.js'
4
- // import { setup } from 'virtual:fastify-setup'
3
+ import type { OnRenderedHook } from '../../vitrify-config.js'
5
4
  import { fastifySsrPlugin } from './fastify-ssr-plugin.js'
6
- // import { getPkgJsonDir } from '../app-urls.js'
7
5
 
8
6
  export const createApp = ({
9
7
  setup,
10
8
  appDir,
11
9
  baseUrl,
12
- ssrFunctions
10
+ onRenderedHooks
13
11
  }: {
14
12
  setup: (fastify: FastifyInstance) => any
15
13
  appDir: URL
16
14
  baseUrl?: string
17
- ssrFunctions?: SsrFunction[]
15
+ onRenderedHooks?: OnRenderedHook[]
18
16
  }) => {
19
17
  const app = fastify({
20
18
  logger: true
@@ -23,16 +21,10 @@ export const createApp = ({
23
21
  app.register(fastifySsrPlugin, {
24
22
  baseUrl,
25
23
  appDir,
26
- ssrFunctions
24
+ onRenderedHooks
27
25
  })
28
26
 
29
27
  setup(app)
30
28
 
31
29
  return app
32
30
  }
33
-
34
- // const app = createApp({
35
- // setup
36
- // })
37
-
38
- // app.listen(process.env.PORT || 3000, process.env.HOST || '127.0.0.1')
@@ -1,98 +1,11 @@
1
1
  // https://github.com/quasarframework/quasar/blob/dev/app/lib/helpers/logger.js
2
2
  import chalk from 'chalk'
3
- const { bgGreen, green, inverse, bgRed, red, bgYellow, yellow } = chalk
4
- import readline from 'readline'
5
3
  import type { AddressInfo, Server } from 'net'
6
4
  import type { ResolvedConfig, Logger } from 'vite'
7
5
  import os from 'os'
8
6
  import type { Hostname } from '../helpers/utils.js'
9
7
  import { resolveHostname } from '../helpers/utils.js'
10
8
 
11
- /**
12
- * Main approach - App CLI related
13
- */
14
-
15
- const dot = '•'
16
- const banner = 'App ' + dot
17
- const greenBanner = green(banner)
18
- const redBanner = red(banner)
19
- const yellowBanner = yellow(banner)
20
-
21
- export const clearConsole = process.stdout.isTTY
22
- ? () => {
23
- // Fill screen with blank lines. Then move to 0 (beginning of visible part) and clear it
24
- const blank = '\n'.repeat(process.stdout.rows)
25
- console.log(blank)
26
- readline.cursorTo(process.stdout, 0, 0)
27
- readline.clearScreenDown(process.stdout)
28
- }
29
- : () => {}
30
-
31
- export const log = function (msg?: string) {
32
- console.log(msg ? ` ${greenBanner} ${msg}` : '')
33
- }
34
-
35
- export const warn = function (msg?: string, pill?: string) {
36
- if (msg !== void 0) {
37
- const pillBanner = pill !== void 0 ? bgYellow.black('', pill, '') + ' ' : ''
38
-
39
- console.warn(` ${yellowBanner} ⚠️ ${pillBanner}${msg}`)
40
- } else {
41
- console.warn()
42
- }
43
- }
44
-
45
- export const fatal = function (msg?: string, pill?: string) {
46
- if (msg !== void 0) {
47
- const pillBanner = pill !== void 0 ? errorPill(pill) + ' ' : ''
48
-
49
- console.error(`\n ${redBanner} ⚠️ ${pillBanner}${msg}\n`)
50
- } else {
51
- console.error()
52
- }
53
-
54
- process.exit(1)
55
- }
56
-
57
- /**
58
- * Extended approach - Compilation status & pills
59
- */
60
-
61
- export const successPill = (msg?: string) => bgGreen.black('', msg, '')
62
- export const infoPill = (msg?: string) => inverse('', msg, '')
63
- export const errorPill = (msg?: string) => bgRed.white('', msg, '')
64
- export const warningPill = (msg?: string) => bgYellow.black('', msg, '')
65
-
66
- export const success = function (msg?: string, title = 'SUCCESS') {
67
- console.log(` ${greenBanner} ${successPill(title)} ${green(dot + ' ' + msg)}`)
68
- }
69
- export const getSuccess = function (msg?: string, title?: string) {
70
- return ` ${greenBanner} ${successPill(title)} ${green(dot + ' ' + msg)}`
71
- }
72
-
73
- export const info = function (msg?: string, title = 'INFO') {
74
- console.log(` ${greenBanner} ${infoPill(title)} ${green(dot)} ${msg}`)
75
- }
76
- export const getInfo = function (msg?: string, title?: string) {
77
- return ` ${greenBanner} ${infoPill(title)} ${green(dot)} ${msg}`
78
- }
79
-
80
- export const error = function (msg?: string, title = 'ERROR') {
81
- console.log(` ${redBanner} ${errorPill(title)} ${red(dot + ' ' + msg)}`)
82
- }
83
- export const getError = function (msg?: string, title = 'ERROR') {
84
- return ` ${redBanner} ${errorPill(title)} ${red(dot + ' ' + msg)}`
85
- }
86
-
87
- export const warning = function (msg?: string, title = 'WARNING') {
88
- console.log(
89
- ` ${yellowBanner} ${warningPill(title)} ${yellow(dot + ' ' + msg)}`
90
- )
91
- }
92
- export const getWarning = function (msg?: string, title = 'WARNING') {
93
- return ` ${yellowBanner} ${warningPill(title)} ${yellow(dot + ' ' + msg)}`
94
- }
95
-
96
9
  export function printHttpServerUrls(
97
10
  server: Server,
98
11
  config: ResolvedConfig