goravel-vite-plugin 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 goravel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # goravel-vite-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/goravel-vite-plugin.svg)](https://www.npmjs.com/package/goravel-vite-plugin)
4
+ [![tests](https://github.com/goravel/vite-plugin/actions/workflows/tests.yml/badge.svg)](https://github.com/goravel/vite-plugin/actions/workflows/tests.yml)
5
+ [![license](https://img.shields.io/npm/l/goravel-vite-plugin.svg)](LICENSE)
6
+
7
+ Vite plugin for [Goravel](https://www.goravel.dev) applications. It is the counterpart of the framework's `vite` template function: the plugin builds your assets where the framework looks for them, and while the dev server runs it tells the framework where to find it.
8
+
9
+ - `vite build` writes to `public/build` with a `.vite/manifest.json` the framework resolves entry points through.
10
+ - The entry points are discovered from your views: whatever `{{ vite ... }}` and `{{ viteAsset ... }}` ask for is built, so the list is not kept twice.
11
+ - The paths are the framework's: the plugin asks the application where it reads the build and the hot file, so `config/vite.go` is the only place they are set.
12
+ - `vite` (the dev server) writes its URL to `public/hot`; as long as that file exists, `{{ vite ... }}` points every tag at the dev server and you get hot module replacement.
13
+ - The dev server answers every origin, so the fonts, images and modules a page loads from it are not blocked wherever the application is served from. Set `server.cors` yourself to narrow it.
14
+ - With `refresh: true`, the page reloads when a view, language or route file changes.
15
+ - `@` resolves to `resources/js`.
16
+
17
+ ## Requirements
18
+
19
+ - Node 20.19+ or 22.12+
20
+ - Vite 7 or 8
21
+ - Goravel with the `Vite` service provider installed: `./artisan package:install Vite`
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install --save-dev vite goravel-vite-plugin
27
+ ```
28
+
29
+ `vite.config.js`:
30
+
31
+ ```js
32
+ import { defineConfig } from 'vite';
33
+ import goravel from 'goravel-vite-plugin';
34
+
35
+ export default defineConfig({
36
+ plugins: [
37
+ goravel({
38
+ refresh: true,
39
+ }),
40
+ ],
41
+ });
42
+ ```
43
+
44
+ `package.json`:
45
+
46
+ ```json
47
+ {
48
+ "scripts": {
49
+ "dev": "vite",
50
+ "build": "vite build"
51
+ }
52
+ }
53
+ ```
54
+
55
+ Then load the entries from a view:
56
+
57
+ ```html
58
+ <head>
59
+ {{ vite "resources/css/app.css" "resources/js/app.js" }}
60
+ </head>
61
+ ```
62
+
63
+ The plugin asks the application where to build and which entries the views reference (see [Discovery](#discovery)), so nothing has to be listed in `vite.config.js`. Run `npm run dev` next to your Go server while developing, and `npm run build` before deploying. The built files are plain static files under `public/build`; serve them like the rest of `public/`, for example with `facades.Route().Static("build", path.Public("build"))`.
64
+
65
+ ## Options
66
+
67
+ `goravel()` takes a single entry point, a list of them, or a configuration object. Everything is optional:
68
+
69
+ | Option | Default | |
70
+ | --- | --- | --- |
71
+ | `input` | | Entry points to build, relative to the project root, in addition to the discovered ones. Required when `discover` is `false` |
72
+ | `discover` | `true` | Ask the application for its paths and for the entry points and assets the views reference. A build builds them too; the dev server only takes the paths |
73
+ | `discoverCommand` | `['go', 'run', '.', 'artisan', 'vite:inputs']` | The command that prints them, run in the project root (Vite's `root`). A string is split on whitespace |
74
+ | `discoverTimeout` | `300000` | How long to wait for the command, in milliseconds. `go run` compiles the application first, which takes a while on a cold cache |
75
+ | `discovered` | | The output of `artisan vite:inputs`, for builds that cannot run the application. The command is then not run |
76
+ | `publicDirectory` | what the application reports, else `'public'` | The directory the application serves as its web root. Set it only to override the application |
77
+ | `buildDirectory` | what the application reports, else `'build'` | The subdirectory of the public directory the build is written to. Set it only to override `vite.build_directory` |
78
+ | `hotFile` | what the application reports, else `` `${publicDirectory}/hot` `` | Where the dev server announces its URL. Set it only to override `vite.hot_file` |
79
+ | `refresh` | `false` | `true` watches `resources/views/**`, `lang/**`, `resources/lang/**` and `routes/**` (those that exist). A string, a list of globs, or a [vite-plugin-full-reload](https://github.com/ElMassimo/vite-plugin-full-reload) configuration watches exactly that; the exported `refreshPaths` lists the four, for `refresh: [...refreshPaths, 'app/**']` |
80
+ | `assets` | `[]` | Globs of files to build and version although nothing imports them, in addition to the discovered `viteAsset` files |
81
+ | `transformOnServe` | | `(code, devServerUrl) => code`, applied to everything the dev server serves |
82
+
83
+ To move the build directory, the hot file or the manifest, edit `config/vite.go` and nothing else; the plugin reads the result:
84
+
85
+ ```go
86
+ config.Add("vite", map[string]any{
87
+ "build_directory": "assets", // inside the public directory, default "build"
88
+ "hot_file": "storage/hot", // relative to the project root, default "public/hot"
89
+ "manifest": ".vite/manifest.json", // inside the build directory
90
+ })
91
+ ```
92
+
93
+ The `publicDirectory`, `buildDirectory` and `hotFile` options exist for the case where the plugin cannot ask, or has to disagree. Vite's own `build.manifest` and `build.outDir` win over everything, as usual, but the application reads only `config/vite.go`: a `build.outDir` of your own moves the build and its URLs, and a `build.manifest` of your own renames the manifest, and the plugin warns about either, because the framework keeps reading from `vite.build_directory` and `vite.manifest`. Set those instead. Likewise a `build.rollupOptions.input` (or `rolldownOptions.input` on Vite 8) of your own is built as written, and the plugin's `input` and the discovered entries are ignored; the plugin says so.
94
+
95
+ The command runs in Vite's `root`, which is the project root unless `vite.config.js` moves it, so the paths it reports and the entries it finds are relative to the same directory the framework uses.
96
+
97
+ ## Discovery
98
+
99
+ Go parses every view when the application boots, and a `{{ vite "resources/js/app.js" }}` call survives in the parsed tree as a function call with string arguments. `artisan vite:inputs` compiles the view set the same way, collects the arguments of every `vite` and `viteAsset` call, including views that packages ship in an `embed.FS`, and prints them along with the paths of `config/vite.go`:
100
+
101
+ ```bash
102
+ $ go run . artisan vite:inputs
103
+ {"inputs":["resources/css/app.css","resources/js/app.js"],"assets":["resources/images/logo.svg"],"dynamic":[],"paths":{"public_directory":"public","build_directory":"build","hot_file":"public/hot","manifest":".vite/manifest.json"}}
104
+ ```
105
+
106
+ Both commands run it. A build merges the inputs with `input` and `assets` and builds the union where `paths` say; the dev server takes `paths` to know where to write the hot file, and serves whatever the page requests, so a new `{{ vite }}` call works without a restart. The plugin knows nothing else about the application: swap the command for a compiled binary (`discoverCommand: './main artisan vite:inputs'`), or run any program that prints the same JSON.
107
+
108
+ What it cannot see is a computed argument such as `{{ vite .entry }}`. Those calls are reported under `dynamic`, the plugin warns about them, and you add the entry to `input` yourself.
109
+
110
+ ### Building without Go
111
+
112
+ Where the build runs without a Go toolchain, for example a Node-only Docker stage, save the command's output and hand it over:
113
+
114
+ ```bash
115
+ go run . artisan vite:inputs > vite-inputs.json
116
+ ```
117
+
118
+ ```js
119
+ import { readFileSync } from 'node:fs';
120
+
121
+ goravel({ discovered: JSON.parse(readFileSync('vite-inputs.json', 'utf8')) })
122
+ ```
123
+
124
+ Or turn discovery off and list the entries as before. The paths then fall back to the framework's defaults unless the options say otherwise:
125
+
126
+ ```js
127
+ goravel({ input: ['resources/css/app.css', 'resources/js/app.js'], discover: false })
128
+ ```
129
+
130
+ ## Environment
131
+
132
+ The plugin reads your `.env` from Vite's `envDir`, so `envDir: false` leaves only the process environment:
133
+
134
+ | Variable | |
135
+ | --- | --- |
136
+ | `APP_URL` | Shown in the dev server banner and on the page the dev server serves when it is opened directly |
137
+ | `ASSET_URL` | Prefixes the build's `base`, for assets served from a CDN. Set `app.asset_url` in the framework to match |
138
+ | `VITE_DEV_SERVER_KEY`, `VITE_DEV_SERVER_CERT` | Serve the dev server over TLS with these files, relative to the project root. The host is taken from `APP_URL` |
139
+ | `CI` | The dev server refuses to start when this is set; set `GORAVEL_BYPASS_ENV_CHECK=1` to start it anyway |
140
+
141
+ ## Other devices on the network
142
+
143
+ The hot file carries the address the plugin works out from the socket Vite bound. A wildcard bind (`server.host: true`) is handed out as `localhost`, which only works on this machine. For a phone or another machine, name the address they reach this machine at:
144
+
145
+ ```js
146
+ export default defineConfig({
147
+ server: {
148
+ host: true,
149
+ hmr: { host: '192.168.1.5' },
150
+ // Only needed when the address above is a name rather than an IP
151
+ allowedHosts: ['dev.example.test'],
152
+ },
153
+ plugins: [goravel({ refresh: true })],
154
+ })
155
+ ```
156
+
157
+ To state the whole URL, behind a reverse proxy, a tunnel or an HTTPS terminator, set [`server.origin`](https://vite.dev/config/server-options#server-origin) instead. It wins over `server.hmr.host` and the bound address, and is what the hot file carries and what Vite writes into asset URLs, so both agree. It has to be an `http` or `https` URL; anything else is reported and ignored.
158
+
159
+ ## Reloading
160
+
161
+ Go templates are parsed when the application boots, so a change to a `.tmpl` file reaches the browser only once the Go process has restarted. `refresh: true` is most useful next to a watcher such as [air](https://github.com/air-verse/air) that rebuilds the server for you: the reload then shows the restarted server's output.
162
+
163
+ ## Template functions
164
+
165
+ The framework registers three functions for every view once the `Vite` provider is installed:
166
+
167
+ | Function | |
168
+ | --- | --- |
169
+ | `{{ vite "resources/js/app.js" }}` | The tags that load the entry points: stylesheets, module preloads and module scripts, or the dev server equivalents |
170
+ | `{{ viteAsset "resources/images/logo.svg" }}` | The URL of a built asset |
171
+ | `{{ viteReactRefresh }}` | The preamble `@vitejs/plugin-react` needs; empty outside the dev server |
172
+
173
+ ## Development
174
+
175
+ ```bash
176
+ pnpm install
177
+ pnpm test
178
+ ```
179
+
180
+ The tests run a real Vite build and dev server in a temporary directory. Node stands in for Go, so no Go toolchain is needed to run them.
181
+
182
+ ### Releasing
183
+
184
+ 1. Bump `version` in `package.json` and move the `Unreleased` entries in [CHANGELOG.md](CHANGELOG.md) under the new version.
185
+ 2. Commit, tag `vX.Y.Z` and push the tag. The [`publish`](.github/workflows/publish.yml) workflow builds, tests and stages the release with `npm stage publish`; a hyphenated version (`v0.2.0-beta.1`) stages to the `next` dist-tag instead of `latest`.
186
+ 3. Approve the staged release with 2FA. The job summary carries the command:
187
+ ```bash
188
+ npm stage approve <stage-id>
189
+ ```
190
+ You can also approve on npmjs.com under *Staged Packages*. Nothing is installable before that. A version can be staged only once — to rebuild, `npm stage reject <stage-id>`, fix, and push the tag again.
191
+ 4. To rehearse, run the workflow by hand and leave *dry run* on: it needs no credentials and stages nothing.
192
+
193
+ Staging uses npm [trusted publishing](https://docs.npmjs.com/trusted-publishers) and [staged publishing](https://docs.npmjs.com/staged-publishing), so no npm token is stored here. The trusted publisher on npmjs.com is organization `goravel`, repository `vite-plugin`, workflow `publish.yml`, no environment, and it is stage-only: it allows `npm stage publish`, while `npm publish` and `npm dist-tag` are deliberately left disallowed — that is npm's maximum-security posture, and a dist-tag grant could repoint `latest` without any staged approval. `0.1.0` went out by hand before the workflow existed.
194
+
195
+ ## Contributing
196
+
197
+ Issues and pull requests are welcome at [goravel/vite-plugin](https://github.com/goravel/vite-plugin). The framework side of this integration lives in [goravel/framework](https://github.com/goravel/framework).
198
+
199
+ ## License
200
+
201
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,108 @@
1
+ import type { Config as FullReloadConfig } from 'vite-plugin-full-reload';
2
+ import { type DiscoveredInputs } from './discover.js';
3
+ /** The framework's default manifest path, used when the application reports none. */
4
+ export declare const defaultManifest = ".vite/manifest.json";
5
+ /** An entry point, a list of them or a map of names to entry points, as Vite's `build.rollupOptions.input` takes it. */
6
+ export type InputOption = string | string[] | Record<string, string>;
7
+ export type DevServerUrl = `${'http' | 'https'}://${string}:${number}`;
8
+ export interface RefreshConfig {
9
+ paths: string[];
10
+ config?: FullReloadConfig;
11
+ }
12
+ export interface PluginConfig {
13
+ /** Entry points to build, relative to the project root. Added to the discovered ones; required when discovery is off. */
14
+ input?: InputOption;
15
+ /**
16
+ * Ask the application for its paths (`config/vite.go`) and the entries and
17
+ * assets its views reference. A build builds those along with `input` and
18
+ * `assets`; the dev server only takes the paths.
19
+ *
20
+ * @default true
21
+ */
22
+ discover?: boolean;
23
+ /**
24
+ * The command that prints the discovered inputs as JSON, run in the project root. A string is split on whitespace.
25
+ *
26
+ * @default ['go', 'run', '.', 'artisan', 'vite:inputs']
27
+ */
28
+ discoverCommand?: string | string[];
29
+ /**
30
+ * How long to wait for the discovery command, in milliseconds. `go run` compiles the
31
+ * application first, which takes a while on a cold cache.
32
+ *
33
+ * @default 300000
34
+ */
35
+ discoverTimeout?: number;
36
+ /** The output of `artisan vite:inputs`, for builds that cannot run the application. When given, the command is not run. */
37
+ discovered?: DiscoveredInputs;
38
+ /**
39
+ * The web root. Overrides what the application reports.
40
+ *
41
+ * @default what the application reports, or 'public'
42
+ */
43
+ publicDirectory?: string;
44
+ /**
45
+ * The build directory inside the public directory. Overrides `vite.build_directory`.
46
+ *
47
+ * @default what the application reports, or 'build'
48
+ */
49
+ buildDirectory?: string;
50
+ /**
51
+ * The file the dev server announces its URL in, relative to the project root (Vite's `root`). Overrides `vite.hot_file`.
52
+ *
53
+ * @default what the application reports, or `${publicDirectory}/hot`
54
+ */
55
+ hotFile?: string;
56
+ /**
57
+ * Reload the page when a file outside the module graph changes. `true` watches
58
+ * the view, language and route directories that exist.
59
+ *
60
+ * {@link https://github.com/ElMassimo/vite-plugin-full-reload}
61
+ * @default false
62
+ */
63
+ refresh?: boolean | string | string[] | RefreshConfig | RefreshConfig[];
64
+ /**
65
+ * Globs of files to build and version although nothing imports them, e.g.
66
+ * images used with `viteAsset`. Relative to the project root.
67
+ *
68
+ * @default []
69
+ */
70
+ assets?: string | string[];
71
+ /** Transform the code the dev server serves, after the placeholder origin is replaced with the dev server URL. */
72
+ transformOnServe?: (code: string, url: DevServerUrl) => string;
73
+ }
74
+ export interface ResolvedPluginConfig {
75
+ input: InputOption | undefined;
76
+ discover: boolean;
77
+ discoverCommand: string[];
78
+ discoverTimeout: number;
79
+ discovered: DiscoveredInputs | null;
80
+ /** As the options set them; undefined where the application decides. The hot file is resolved against the root by `resolvePaths`. */
81
+ publicDirectory: string | undefined;
82
+ buildDirectory: string | undefined;
83
+ hotFile: string | undefined;
84
+ refresh: boolean | string | string[] | RefreshConfig | RefreshConfig[];
85
+ assets: string[];
86
+ transformOnServe: (code: string, url: DevServerUrl) => string;
87
+ }
88
+ /** The paths of this run, once the application has been asked. */
89
+ export interface ResolvedPaths {
90
+ publicDirectory: string;
91
+ buildDirectory: string;
92
+ /** Absolute. */
93
+ hotFile: string;
94
+ /** Relative to the build directory. */
95
+ manifest: string;
96
+ }
97
+ /** The directories `refresh: true` watches: views, language files and routes. */
98
+ export declare const refreshPaths: readonly string[];
99
+ /** Those of `refreshPaths` that exist under the given directory. */
100
+ export declare function existingRefreshPaths(cwd: string): string[];
101
+ /** @param cwd - The working directory, which the refresh paths are relative to; the other paths wait for Vite's root. */
102
+ export declare function resolvePluginConfig(config: string | string[] | PluginConfig | undefined, cwd: string): ResolvedPluginConfig;
103
+ /**
104
+ * The paths of this run: an option wins, then what the application reported, then the framework's defaults.
105
+ *
106
+ * @param root - Vite's resolved root, which the project-relative paths are resolved against.
107
+ */
108
+ export declare function resolvePaths(config: ResolvedPluginConfig, discovered: DiscoveredInputs | null, root: string): ResolvedPaths;
package/dist/config.js ADDED
@@ -0,0 +1,72 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { defaultDiscoverCommand, defaultDiscoverTimeout, validateInputs } from './discover.js';
4
+ /** The framework's default manifest path, used when the application reports none. */
5
+ export const defaultManifest = '.vite/manifest.json';
6
+ /** The directories `refresh: true` watches: views, language files and routes. */
7
+ export const refreshPaths = ['lang/**', 'resources/lang/**', 'resources/views/**', 'routes/**'];
8
+ /** Those of `refreshPaths` that exist under the given directory. */
9
+ export function existingRefreshPaths(cwd) {
10
+ return refreshPaths.filter((pattern) => existsSync(path.resolve(cwd, pattern.replace(/\*\*$/, ''))));
11
+ }
12
+ /** @param cwd - The working directory, which the refresh paths are relative to; the other paths wait for Vite's root. */
13
+ export function resolvePluginConfig(config, cwd) {
14
+ if (typeof config === 'undefined') {
15
+ throw new Error('goravel-vite-plugin: missing configuration.');
16
+ }
17
+ if (typeof config === 'string' || Array.isArray(config)) {
18
+ config = { input: config };
19
+ }
20
+ const discover = config.discover ?? true;
21
+ if (typeof config.input === 'undefined' && !discover) {
22
+ throw new Error('goravel-vite-plugin: missing configuration for "input", and discovery is off.');
23
+ }
24
+ const discoverCommand = typeof config.discoverCommand === 'string' ? config.discoverCommand.trim().split(/\s+/) : (config.discoverCommand ?? defaultDiscoverCommand);
25
+ if (discoverCommand.length === 0 || discoverCommand[0] === '') {
26
+ throw new Error('goravel-vite-plugin: discoverCommand must name a command.');
27
+ }
28
+ const discoverTimeout = config.discoverTimeout ?? defaultDiscoverTimeout;
29
+ if (!Number.isFinite(discoverTimeout) || discoverTimeout <= 0) {
30
+ throw new Error('goravel-vite-plugin: discoverTimeout must be a number of milliseconds greater than zero.');
31
+ }
32
+ return {
33
+ input: config.input,
34
+ discover,
35
+ discoverCommand,
36
+ discoverTimeout,
37
+ discovered: config.discovered ? validateInputs(config.discovered) : null,
38
+ publicDirectory: subdirectory(config.publicDirectory, 'publicDirectory'),
39
+ buildDirectory: subdirectory(config.buildDirectory, 'buildDirectory'),
40
+ hotFile: config.hotFile,
41
+ refresh: config.refresh === true ? [{ paths: existingRefreshPaths(cwd) }] : (config.refresh ?? false),
42
+ assets: typeof config.assets === 'string' ? [config.assets] : (config.assets ?? []),
43
+ transformOnServe: config.transformOnServe ?? ((code) => code),
44
+ };
45
+ }
46
+ /**
47
+ * The paths of this run: an option wins, then what the application reported, then the framework's defaults.
48
+ *
49
+ * @param root - Vite's resolved root, which the project-relative paths are resolved against.
50
+ */
51
+ export function resolvePaths(config, discovered, root) {
52
+ const reported = discovered?.paths;
53
+ const publicDirectory = config.publicDirectory ?? (reported ? subdirectory(reported.public_directory, 'public_directory') : undefined) ?? 'public';
54
+ const buildDirectory = config.buildDirectory ?? (reported ? subdirectory(reported.build_directory, 'build_directory') : undefined) ?? 'build';
55
+ return {
56
+ publicDirectory,
57
+ buildDirectory,
58
+ hotFile: path.resolve(root, config.hotFile ?? reported?.hot_file ?? path.join(publicDirectory, 'hot')),
59
+ manifest: reported?.manifest ?? defaultManifest,
60
+ };
61
+ }
62
+ /** Trims a directory and refuses one that would mean the project root itself. */
63
+ function subdirectory(value, option) {
64
+ if (typeof value !== 'string') {
65
+ return undefined;
66
+ }
67
+ const trimmed = value.trim().replace(/^\/+/, '').replace(/\/+$/, '');
68
+ if (trimmed === '') {
69
+ throw new Error(`goravel-vite-plugin: ${option} must be a subdirectory, not the project root.`);
70
+ }
71
+ return trimmed;
72
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The output of `artisan vite:inputs`: the entries and assets the views reference
3
+ * and where the framework reads the build and the hot file.
4
+ */
5
+ export interface DiscoveredInputs {
6
+ inputs: string[];
7
+ assets: string[];
8
+ /** Calls whose arguments are computed at render time. */
9
+ dynamic?: {
10
+ template: string;
11
+ function: string;
12
+ }[];
13
+ /** The paths of config/vite.go; absent from a framework that does not report them. */
14
+ paths?: DiscoveredPaths;
15
+ }
16
+ /** The paths as `config/vite.go` sets them. */
17
+ export interface DiscoveredPaths {
18
+ /** The web root, relative to the project root. */
19
+ public_directory: string;
20
+ /** The build directory inside the public directory. */
21
+ build_directory: string;
22
+ /** Relative to the project root, or absolute. */
23
+ hot_file: string;
24
+ /** Relative to the build directory. */
25
+ manifest: string;
26
+ }
27
+ /** Artisan through `go run`. */
28
+ export declare const defaultDiscoverCommand: string[];
29
+ /** Five minutes: enough for `go run` to download the modules and compile the application. */
30
+ export declare const defaultDiscoverTimeout = 300000;
31
+ /** Runs the command in the project root and parses the JSON object on its last line. */
32
+ export declare function discoverInputs(command: string[], root: string, timeout?: number): DiscoveredInputs;
33
+ /** Checks the shape of the command's output or of the `discovered` option. */
34
+ export declare function validateInputs(value: unknown): DiscoveredInputs;
@@ -0,0 +1,77 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ /** Artisan through `go run`. */
3
+ export const defaultDiscoverCommand = ['go', 'run', '.', 'artisan', 'vite:inputs'];
4
+ /** Five minutes: enough for `go run` to download the modules and compile the application. */
5
+ export const defaultDiscoverTimeout = 300_000;
6
+ /** Runs the command in the project root and parses the JSON object on its last line. */
7
+ export function discoverInputs(command, root, timeout = defaultDiscoverTimeout) {
8
+ const [executable, ...args] = command;
9
+ const result = spawnSync(executable, args, { cwd: root, encoding: 'utf8', env: process.env, timeout });
10
+ if (result.error && 'code' in result.error && result.error.code === 'ETIMEDOUT') {
11
+ throw new Error(`goravel-vite-plugin: "${command.join(' ')}" did not finish within ${timeout / 1000}s. ` +
12
+ "Raise the 'discoverTimeout' option if the application takes longer to start. " +
13
+ explainAlternatives());
14
+ }
15
+ if (result.error) {
16
+ throw new Error(`goravel-vite-plugin: could not run "${command.join(' ')}" to discover the entry points: ${result.error.message}. ` +
17
+ explainAlternatives());
18
+ }
19
+ if (result.status !== 0) {
20
+ throw new Error(`goravel-vite-plugin: "${command.join(' ')}" failed with exit code ${result.status}:\n${(result.stderr + result.stdout).trim()}\n` +
21
+ explainAlternatives());
22
+ }
23
+ // Artisan colours piped output too; strip the codes before looking for the JSON.
24
+ const line = stripAnsi(result.stdout)
25
+ .split(/\r?\n/)
26
+ .map((line) => line.trim())
27
+ .filter((line) => line.startsWith('{'))
28
+ .at(-1);
29
+ if (line === undefined) {
30
+ throw new Error(`goravel-vite-plugin: "${command.join(' ')}" printed no JSON object:\n${result.stdout.trim()}\n` + explainAlternatives());
31
+ }
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(line);
35
+ }
36
+ catch (error) {
37
+ throw new Error(`goravel-vite-plugin: "${command.join(' ')}" printed a line that is not JSON (${error.message}):\n${line}\n` +
38
+ explainAlternatives());
39
+ }
40
+ return validateInputs(parsed);
41
+ }
42
+ /** Checks the shape of the command's output or of the `discovered` option. */
43
+ export function validateInputs(value) {
44
+ const { inputs, assets, dynamic, paths } = (value ?? {});
45
+ if (!isStringList(inputs) ||
46
+ !isStringList(assets) ||
47
+ (dynamic !== undefined &&
48
+ (!Array.isArray(dynamic) ||
49
+ dynamic.some((call) => typeof call?.template !== 'string' || typeof call?.function !== 'string'))) ||
50
+ (paths !== undefined && !isPaths(paths))) {
51
+ throw new Error('goravel-vite-plugin: discovered inputs must look like { inputs: string[], assets: string[], dynamic?: { template: string, function: string }[], paths?: { public_directory: string, build_directory: string, hot_file: string, manifest: string } }, got ' +
52
+ JSON.stringify(value));
53
+ }
54
+ return {
55
+ inputs,
56
+ assets,
57
+ ...(dynamic === undefined ? {} : { dynamic }),
58
+ ...(paths === undefined ? {} : { paths }),
59
+ };
60
+ }
61
+ function isPaths(value) {
62
+ const paths = value;
63
+ return (typeof paths === 'object' &&
64
+ paths !== null &&
65
+ ['public_directory', 'build_directory', 'hot_file', 'manifest'].every((key) => typeof paths[key] === 'string' && paths[key] !== ''));
66
+ }
67
+ // eslint-disable-next-line no-control-regex
68
+ const ansiPattern = /\x1b\[[0-9;]*[A-Za-z]/g;
69
+ function stripAnsi(text) {
70
+ return text.replace(ansiPattern, '');
71
+ }
72
+ function isStringList(value) {
73
+ return Array.isArray(value) && value.every((item) => typeof item === 'string');
74
+ }
75
+ function explainAlternatives() {
76
+ return "Set the 'discoverCommand' option to the command that runs Artisan, pass its output through the 'discovered' option, or set 'discover: false' and list the 'input' yourself.";
77
+ }
@@ -0,0 +1,27 @@
1
+ import { type ConfigEnv, type Plugin, type UserConfig } from 'vite';
2
+ import { refreshPaths, type PluginConfig } from './config.js';
3
+ export type { DevServerUrl, InputOption, PluginConfig, RefreshConfig, ResolvedPaths, ResolvedPluginConfig } from './config.js';
4
+ export type { DiscoveredInputs, DiscoveredPaths } from './discover.js';
5
+ interface GoravelPlugin extends Plugin {
6
+ config: (config: UserConfig, env: ConfigEnv) => UserConfig;
7
+ }
8
+ /** The directories `refresh: true` watches (those that exist); extend them with `refresh: [...refreshPaths, 'app/**']`. */
9
+ export { refreshPaths };
10
+ /**
11
+ * Goravel plugin for Vite.
12
+ *
13
+ * plugins: [goravel({ refresh: true })]
14
+ *
15
+ * Builds into the directory the framework's `vite` template function reads, with
16
+ * the manifest it resolves entries through, and writes the dev server URL to the
17
+ * hot file so the same function points at the dev server while it runs. Unless
18
+ * `discover` is false, the paths and the entries the views reference come from
19
+ * the application, so `config/vite.go` is the only place they are set.
20
+ *
21
+ * Paths are relative to Vite's `root`, which is the project root unless the
22
+ * configuration moves it.
23
+ *
24
+ * @param config - A configuration object, or the entry point(s) to build.
25
+ */
26
+ export declare function goravel(config?: string | string[] | PluginConfig): [GoravelPlugin, ...Plugin[]];
27
+ export default goravel;
package/dist/index.js ADDED
@@ -0,0 +1,400 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import colors from 'picocolors';
4
+ import { globSync } from 'tinyglobby';
5
+ import { createLogger, loadEnv, version as viteVersion } from 'vite';
6
+ import fullReload from 'vite-plugin-full-reload';
7
+ import { defaultManifest, refreshPaths, resolvePaths, resolvePluginConfig, } from './config.js';
8
+ import { discoverInputs } from './discover.js';
9
+ import { configuredOrigin, devServerIndex, ensureCommandShouldRunInEnvironment, goravelVersion, placeholderOrigin, pluginVersion, resolveDevServerUrl, resolveEnvironmentServerConfig, } from './server.js';
10
+ /** The directories `refresh: true` watches (those that exist); extend them with `refresh: [...refreshPaths, 'app/**']`. */
11
+ export { refreshPaths };
12
+ const logger = createLogger('info', { prefix: '[goravel-vite-plugin]' });
13
+ /** The hot files of the dev servers running in this process, and what each wrote, removed when the process exits. */
14
+ const hotFiles = new Map();
15
+ let exitHandlersBound = false;
16
+ /** Writes the hot file, creating its directory; a failure is reported rather than thrown, since the server is already listening. */
17
+ function claimHotFile(hotFile, content, viteLogger) {
18
+ try {
19
+ const directory = path.dirname(hotFile);
20
+ const created = !fs.existsSync(directory);
21
+ fs.mkdirSync(directory, { recursive: true });
22
+ fs.writeFileSync(hotFile, content);
23
+ if (created) {
24
+ const realpath = fs.realpathSync(directory);
25
+ setTimeout(() => {
26
+ logger.info(`Hot file directory created ${colors.dim(realpath)}`, { clear: true, timestamp: true });
27
+ }, 200);
28
+ }
29
+ }
30
+ catch (error) {
31
+ viteLogger.error(colors.red(`goravel-vite-plugin: could not write the hot file at '${hotFile}': ${error.message}. ` +
32
+ 'The application reads it to find the dev server, and renders the build until it can. Set vite.hot_file to a path it can write.'));
33
+ return false;
34
+ }
35
+ hotFiles.set(hotFile, content);
36
+ return true;
37
+ }
38
+ /** Removes the hot file, unless another server has since written its own URL into it. */
39
+ function releaseHotFile(hotFile, content) {
40
+ if (hotFiles.get(hotFile) === content) {
41
+ hotFiles.delete(hotFile);
42
+ }
43
+ try {
44
+ if (fs.readFileSync(hotFile, 'utf8') === content) {
45
+ fs.rmSync(hotFile);
46
+ }
47
+ }
48
+ catch {
49
+ // Already gone, or never written.
50
+ }
51
+ }
52
+ /**
53
+ * Goravel plugin for Vite.
54
+ *
55
+ * plugins: [goravel({ refresh: true })]
56
+ *
57
+ * Builds into the directory the framework's `vite` template function reads, with
58
+ * the manifest it resolves entries through, and writes the dev server URL to the
59
+ * hot file so the same function points at the dev server while it runs. Unless
60
+ * `discover` is false, the paths and the entries the views reference come from
61
+ * the application, so `config/vite.go` is the only place they are set.
62
+ *
63
+ * Paths are relative to Vite's `root`, which is the project root unless the
64
+ * configuration moves it.
65
+ *
66
+ * @param config - A configuration object, or the entry point(s) to build.
67
+ */
68
+ export function goravel(config = {}) {
69
+ const pluginConfig = resolvePluginConfig(config, process.cwd());
70
+ const assets = new Set(pluginConfig.assets);
71
+ return [
72
+ resolveGoravelPlugin(pluginConfig, assets),
73
+ resolveAssetPlugin(assets),
74
+ ...resolveFullReloadConfig(pluginConfig),
75
+ ];
76
+ }
77
+ /** @param assets - The `assets` option; discovery adds to the set before the assets plugin reads it. */
78
+ function resolveGoravelPlugin(pluginConfig, assets) {
79
+ let resolvedConfig;
80
+ let userConfig;
81
+ let paths;
82
+ const defaultAliases = {
83
+ '@': '/resources/js',
84
+ };
85
+ // The URL the browser reaches the dev server at, known once it listens (or from
86
+ // server.origin); undefined where there is no server of its own to listen.
87
+ let devServerUrl;
88
+ let setDevServerUrl;
89
+ const awaitDevServerUrl = () => {
90
+ devServerUrl = new Promise((resolve) => {
91
+ setDevServerUrl = resolve;
92
+ });
93
+ };
94
+ awaitDevServerUrl();
95
+ let warnedUnknownUrl = false;
96
+ // A server.origin of the user's own, once validated.
97
+ let origin;
98
+ return {
99
+ name: 'goravel',
100
+ enforce: 'post',
101
+ config: (config, { command, mode }) => {
102
+ userConfig = config;
103
+ // Vite resolves its own paths against this; so does the plugin, and the application runs here.
104
+ const root = path.resolve(userConfig.root ?? process.cwd());
105
+ // Vite's envDir, relative to the root; false leaves only the process environment, as it does for Vite.
106
+ const env = loadEnv(mode, userConfig.envDir === false ? false : path.resolve(root, userConfig.envDir ?? ''), '');
107
+ const assetUrl = env.ASSET_URL ?? '';
108
+ const serverConfig = command === 'serve' ? resolveEnvironmentServerConfig(env, root) : undefined;
109
+ ensureCommandShouldRunInEnvironment(command, env);
110
+ // The application says where to build and which entries the views reference;
111
+ // the dev server serves whatever the page asks for, so only a build needs the entries.
112
+ const discovered = pluginConfig.discover ? (pluginConfig.discovered ?? runDiscovery(pluginConfig, root)) : null;
113
+ paths = resolvePaths(pluginConfig, discovered, root);
114
+ // Entries the user named in the Vite config are built as written; the plugin's are then ignored.
115
+ const userNamedTheEntries = userInputKey(userConfig) !== undefined;
116
+ if (command === 'build' && userNamedTheEntries) {
117
+ logger.warn(`${userInputKey(userConfig)} is set in your Vite config, so it is built as written and the plugin's 'input' is ignored, ` +
118
+ 'along with the entries discovered from the views. Name the entries in one place or the other.', { timestamp: true });
119
+ }
120
+ // Absolute, so Rollup (Vite 7) finds the entries under a root that is not the working directory.
121
+ const input = absoluteInput(command === 'build' ? resolveBuildInput(pluginConfig, discovered, assets, userNamedTheEntries) : (pluginConfig.input ?? []), root);
122
+ return {
123
+ base: userConfig.base ?? (command === 'build' ? resolveBase(userBuildDirectory(userConfig, paths, root) ?? paths.buildDirectory, assetUrl) : ''),
124
+ // Vite's own public directory would be copied into the build; Goravel serves public/ itself.
125
+ publicDir: userConfig.publicDir ?? false,
126
+ build: {
127
+ // Written where the framework reads it, whatever Vite's default.
128
+ manifest: userConfig.build?.manifest ?? paths.manifest,
129
+ outDir: userConfig.build?.outDir ?? path.join(paths.publicDirectory, paths.buildDirectory),
130
+ ...bundlerOptions(userConfig, input),
131
+ // Every asset gets a file and a manifest entry, so viteAsset can find it.
132
+ assetsInlineLimit: userConfig.build?.assetsInlineLimit ?? 0,
133
+ },
134
+ server: {
135
+ origin: userConfig.server?.origin ?? placeholderOrigin,
136
+ // Fonts and modules are fetched in CORS mode from wherever the application is served; Vite admits only localhost by default.
137
+ cors: userConfig.server?.cors ?? true,
138
+ ...(serverConfig
139
+ ? {
140
+ host: userConfig.server?.host ?? serverConfig.host,
141
+ hmr: userConfig.server?.hmr === false
142
+ ? false
143
+ : {
144
+ ...serverConfig.hmr,
145
+ ...(typeof userConfig.server?.hmr === 'object' ? userConfig.server.hmr : {}),
146
+ },
147
+ https: userConfig.server?.https ?? serverConfig.https,
148
+ }
149
+ : undefined),
150
+ },
151
+ resolve: {
152
+ alias: Array.isArray(userConfig.resolve?.alias)
153
+ ? [
154
+ ...(userConfig.resolve?.alias ?? []),
155
+ ...Object.keys(defaultAliases).map((alias) => ({
156
+ find: alias,
157
+ replacement: defaultAliases[alias],
158
+ })),
159
+ ]
160
+ : {
161
+ ...defaultAliases,
162
+ ...userConfig.resolve?.alias,
163
+ },
164
+ },
165
+ };
166
+ },
167
+ configResolved(config) {
168
+ resolvedConfig = config;
169
+ if (config.command === 'build') {
170
+ warnAboutTheManifest(config, paths);
171
+ }
172
+ // An origin of the user's own is the URL from the start, before (or without) a server listening.
173
+ origin = configuredOrigin(config);
174
+ if (origin) {
175
+ setDevServerUrl(origin);
176
+ }
177
+ },
178
+ async transform(code) {
179
+ if (resolvedConfig.command !== 'serve') {
180
+ return;
181
+ }
182
+ // Vite warms files up before the server listens; those wait here rather than keep the placeholder.
183
+ const url = await devServerUrl;
184
+ if (url === undefined) {
185
+ // No server of its own (middleware mode), so no origin to put in: the URLs stay relative to the page.
186
+ if (!code.includes(placeholderOrigin)) {
187
+ return;
188
+ }
189
+ if (!warnedUnknownUrl) {
190
+ warnedUnknownUrl = true;
191
+ resolvedConfig.logger.warn(colors.yellow('goravel-vite-plugin: the dev server URL is unknown, so asset URLs are left relative to the page that loads them. ' +
192
+ "Set 'server.origin' to the URL Vite is reachable at."));
193
+ }
194
+ return code.replaceAll(placeholderOrigin, '');
195
+ }
196
+ return pluginConfig.transformOnServe(code.replaceAll(placeholderOrigin, url), url);
197
+ },
198
+ configureServer(server) {
199
+ const appUrl = loadEnv(resolvedConfig.mode, resolvedConfig.envDir, 'APP_URL').APP_URL ?? 'undefined';
200
+ // A restarted server binds anew, unless the origin was configured.
201
+ if (!origin) {
202
+ awaitDevServerUrl();
203
+ }
204
+ if (!server.httpServer) {
205
+ setDevServerUrl(origin);
206
+ }
207
+ server.httpServer?.once('listening', () => {
208
+ const address = server.httpServer?.address();
209
+ if (typeof address !== 'object' || address === null) {
210
+ setDevServerUrl(origin);
211
+ return;
212
+ }
213
+ const viteDevServerUrl = origin ?? resolveDevServerUrl(address, server.config);
214
+ setDevServerUrl(viteDevServerUrl);
215
+ const hotFileContent = `${viteDevServerUrl}${server.config.base.replace(/\/$/, '')}`;
216
+ claimHotFile(paths.hotFile, hotFileContent, server.config.logger);
217
+ // A closed server no longer serves anything, so its hot file goes with it.
218
+ server.httpServer?.once('close', () => releaseHotFile(paths.hotFile, hotFileContent));
219
+ setTimeout(() => {
220
+ server.config.logger.info(`\n ${colors.red(`${colors.bold('GORAVEL')} ${goravelVersion(server.config.root)}`)} ${colors.dim('plugin')} ${colors.bold(`v${pluginVersion()}`)}`);
221
+ server.config.logger.info('');
222
+ server.config.logger.info(` ${colors.green('➜')} ${colors.bold('APP_URL')}: ${colors.cyan(appUrl.replace(/:(\d+)/, (_, port) => `:${colors.bold(port)}`))}`);
223
+ }, 100);
224
+ });
225
+ // Bound once for the process; every running server's hot file is in the map.
226
+ if (!exitHandlersBound) {
227
+ process.on('exit', () => {
228
+ for (const [hotFile, content] of [...hotFiles]) {
229
+ releaseHotFile(hotFile, content);
230
+ }
231
+ });
232
+ process.on('SIGINT', () => process.exit());
233
+ process.on('SIGTERM', () => process.exit());
234
+ process.on('SIGHUP', () => process.exit());
235
+ exitHandlersBound = true;
236
+ }
237
+ return () => server.middlewares.use((req, res, next) => {
238
+ if (req.url === '/index.html') {
239
+ res.statusCode = 404;
240
+ res.end(devServerIndex(appUrl));
241
+ return;
242
+ }
243
+ next();
244
+ });
245
+ },
246
+ };
247
+ }
248
+ /** The build entries: `input` plus the discovered ones. Discovered assets go into the set. */
249
+ /**
250
+ * Warns when Vite writes its manifest under a name the application does not read. The
251
+ * directory is the build directory's concern, warned about where the base is derived.
252
+ */
253
+ function warnAboutTheManifest(config, paths) {
254
+ const readFrom = path.join(config.root, config.build.outDir, paths.manifest);
255
+ if (config.build.manifest === false) {
256
+ logger.warn(`build.manifest is false, so Vite writes no manifest, and the application resolves every asset it renders through one: it expects to read "${readFrom}".`, { timestamp: true });
257
+ return;
258
+ }
259
+ const written = config.build.manifest === true ? defaultManifest : config.build.manifest;
260
+ if (path.normalize(written) !== path.normalize(paths.manifest)) {
261
+ logger.warn(`Vite writes its manifest to "${path.join(config.root, config.build.outDir, written)}", but the application reads it from "${readFrom}" ` +
262
+ 'and will report the build as missing. Drop build.manifest from your Vite config, or set vite.manifest in config/vite.go to the file Vite writes.', { timestamp: true });
263
+ }
264
+ }
265
+ /** The key under which the user named the entries in the Vite config, if they did. */
266
+ function userInputKey(userConfig) {
267
+ if (userConfig.build?.rolldownOptions?.input !== undefined) {
268
+ return 'build.rolldownOptions.input';
269
+ }
270
+ return userConfig.build?.rollupOptions?.input !== undefined ? 'build.rollupOptions.input' : undefined;
271
+ }
272
+ /** @param userNamedTheEntries - The user's own entries are built instead, so having none here is no error. */
273
+ function resolveBuildInput(pluginConfig, discovered, assets, userNamedTheEntries) {
274
+ if (discovered === null) {
275
+ return pluginConfig.input ?? [];
276
+ }
277
+ for (const asset of discovered.assets) {
278
+ assets.add(asset);
279
+ }
280
+ for (const call of discovered.dynamic ?? []) {
281
+ logger.warn(`${call.function} is called with a computed argument in ${call.template}; add that entry to 'input' yourself.`, { timestamp: true });
282
+ }
283
+ const input = mergeInput(pluginConfig.input, discovered.inputs);
284
+ if (!userNamedTheEntries && (Array.isArray(input) ? input.length === 0 : typeof input === 'object' && Object.keys(input).length === 0)) {
285
+ throw new Error('goravel-vite-plugin: nothing to build. No view calls {{ vite ... }} with a constant entry point and no "input" is configured.');
286
+ }
287
+ return input;
288
+ }
289
+ function runDiscovery(pluginConfig, root) {
290
+ logger.info(`Asking the application for its paths and entry points with "${pluginConfig.discoverCommand.join(' ')}"`, { timestamp: true });
291
+ return discoverInputs(pluginConfig.discoverCommand, root, pluginConfig.discoverTimeout);
292
+ }
293
+ /** Adds the discovered entries to `input` without changing its shape or repeating an entry. */
294
+ function mergeInput(input, discovered) {
295
+ if (input === undefined) {
296
+ return discovered;
297
+ }
298
+ if (typeof input === 'string') {
299
+ return [input, ...discovered.filter((entry) => entry !== input)];
300
+ }
301
+ if (Array.isArray(input)) {
302
+ return [...input, ...discovered.filter((entry) => !input.includes(entry))];
303
+ }
304
+ // The name only shapes the hashed file name; the path cannot clash with another entry or a user's name.
305
+ const named = { ...input };
306
+ const known = new Set(Object.values(input));
307
+ for (const entry of discovered) {
308
+ if (!known.has(entry)) {
309
+ named[entry] = entry;
310
+ }
311
+ }
312
+ return named;
313
+ }
314
+ /** The entries resolved against the root. Keys and manifest entries stay as they are; only the lookup changes. */
315
+ function absoluteInput(input, root) {
316
+ if (typeof input === 'string') {
317
+ return path.resolve(root, input);
318
+ }
319
+ if (Array.isArray(input)) {
320
+ return input.map((entry) => path.resolve(root, entry));
321
+ }
322
+ return Object.fromEntries(Object.entries(input).map(([name, entry]) => [name, path.resolve(root, entry)]));
323
+ }
324
+ /** The entries under the key the installed Vite expects: `rolldownOptions` from Vite 8, `rollupOptions` before. */
325
+ function bundlerOptions(userConfig, input) {
326
+ const userInput = userConfig.build?.rolldownOptions?.input ?? userConfig.build?.rollupOptions?.input ?? input;
327
+ return parseInt(viteVersion) >= 8 ? { rolldownOptions: { input: userInput } } : { rollupOptions: { input: userInput } };
328
+ }
329
+ /** The public URL of the build directory, under ASSET_URL when one is set. */
330
+ function resolveBase(buildDirectory, assetUrl) {
331
+ return assetUrl + (!assetUrl.endsWith('/') ? '/' : '') + buildDirectory + '/';
332
+ }
333
+ /**
334
+ * Where a `build.outDir` of the user's own sits inside the public directory, so the
335
+ * URLs in the build match the files; undefined when it is outside. Either way the
336
+ * application reads only `vite.build_directory`, so a different directory is warned about.
337
+ */
338
+ function userBuildDirectory(userConfig, paths, root) {
339
+ const outDir = userConfig.build?.outDir;
340
+ if (!outDir) {
341
+ return undefined;
342
+ }
343
+ const relative = path.relative(path.resolve(root, paths.publicDirectory), path.resolve(root, outDir));
344
+ const inside = relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
345
+ const buildDirectory = inside ? relative.split(path.sep).join('/') : undefined;
346
+ if (buildDirectory !== paths.buildDirectory) {
347
+ logger.warn(`build.outDir "${outDir}" is not the application's build directory "${path.join(paths.publicDirectory, paths.buildDirectory)}", ` +
348
+ `where it reads the manifest from. Set vite.build_directory in config/vite.go instead.`, { timestamp: true });
349
+ }
350
+ return buildDirectory;
351
+ }
352
+ /** Emits the `assets` option and the discovered assets into the build, so they are versioned and in the manifest. */
353
+ function resolveAssetPlugin(assets) {
354
+ let root;
355
+ return {
356
+ name: 'goravel:assets',
357
+ apply: 'build',
358
+ configResolved(config) {
359
+ root = config.root;
360
+ },
361
+ buildStart() {
362
+ if (assets.size === 0) {
363
+ return;
364
+ }
365
+ // Globs are relative to the root, and so are the manifest keys.
366
+ for (const file of globSync([...assets], { cwd: root })) {
367
+ const absolute = path.join(root, file);
368
+ if (fs.statSync(absolute).isFile()) {
369
+ this.emitFile({
370
+ type: 'asset',
371
+ name: path.basename(file),
372
+ originalFileName: file,
373
+ source: fs.readFileSync(absolute),
374
+ });
375
+ }
376
+ }
377
+ },
378
+ };
379
+ }
380
+ /** One full-reload plugin per refresh configuration. */
381
+ function resolveFullReloadConfig({ refresh: config }) {
382
+ if (typeof config === 'boolean') {
383
+ return [];
384
+ }
385
+ if (typeof config === 'string') {
386
+ config = [{ paths: [config] }];
387
+ }
388
+ if (!Array.isArray(config)) {
389
+ config = [config];
390
+ }
391
+ if (config.some((c) => typeof c === 'string')) {
392
+ config = [{ paths: config }];
393
+ }
394
+ return config.flatMap((c) => {
395
+ const plugin = fullReload(c.paths, c.config);
396
+ plugin.__goravel_plugin_config = c;
397
+ return plugin;
398
+ });
399
+ }
400
+ export default goravel;
@@ -0,0 +1,37 @@
1
+ import type { AddressInfo } from 'node:net';
2
+ import type { ResolvedConfig } from 'vite';
3
+ import type { DevServerUrl } from './config.js';
4
+ /** The origin the dev server uses until its address is known; `transform` rewrites served code to the real URL. */
5
+ export declare const placeholderOrigin = "http://__goravel_vite_placeholder__.test";
6
+ /**
7
+ * The `server.origin` of the user's own, trimmed of trailing slashes, or undefined where
8
+ * there is none. One that is not an http(s) URL is reported and ignored: the hot file
9
+ * has to carry a URL the browser can reach.
10
+ */
11
+ export declare function configuredOrigin(config: ResolvedConfig): DevServerUrl | undefined;
12
+ /**
13
+ * The dev server URL as the browser reaches it: the host from `server.hmr.host` or
14
+ * `server.host` when one is named, else the bound address, with a wildcard or IPv6
15
+ * loopback bind handed out as `localhost`, which browsers and CSP accept.
16
+ */
17
+ export declare function resolveDevServerUrl(address: AddressInfo, config: ResolvedConfig): DevServerUrl;
18
+ /** TLS for the dev server from VITE_DEV_SERVER_KEY and VITE_DEV_SERVER_CERT, as laravel-vite-plugin reads them. */
19
+ export interface EnvironmentServerConfig {
20
+ hmr: {
21
+ host: string;
22
+ };
23
+ host: string;
24
+ https: {
25
+ key: Buffer;
26
+ cert: Buffer;
27
+ };
28
+ }
29
+ /** @param root - What relative certificate paths are resolved against. */
30
+ export declare function resolveEnvironmentServerConfig(env: Record<string, string>, root: string): EnvironmentServerConfig | undefined;
31
+ /** Refuses to start the HMR server in CI unless GORAVEL_BYPASS_ENV_CHECK=1. */
32
+ export declare function ensureCommandShouldRunInEnvironment(command: 'build' | 'serve', env: Record<string, string>): void;
33
+ /** The framework version from go.mod, for the dev server banner. */
34
+ export declare function goravelVersion(root: string): string;
35
+ export declare function pluginVersion(): string;
36
+ /** The page shown when the dev server is opened in a browser by mistake. */
37
+ export declare function devServerIndex(appUrl: string): string;
package/dist/server.js ADDED
@@ -0,0 +1,154 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import colors from 'picocolors';
4
+ /** The origin the dev server uses until its address is known; `transform` rewrites served code to the real URL. */
5
+ export const placeholderOrigin = 'http://__goravel_vite_placeholder__.test';
6
+ /**
7
+ * The `server.origin` of the user's own, trimmed of trailing slashes, or undefined where
8
+ * there is none. One that is not an http(s) URL is reported and ignored: the hot file
9
+ * has to carry a URL the browser can reach.
10
+ */
11
+ export function configuredOrigin(config) {
12
+ const origin = config.server.origin;
13
+ if (!origin || origin === placeholderOrigin) {
14
+ return undefined;
15
+ }
16
+ const trimmed = origin.replace(/\/+$/, '');
17
+ let protocol = '';
18
+ try {
19
+ protocol = new URL(trimmed).protocol;
20
+ }
21
+ catch {
22
+ // Not a URL at all.
23
+ }
24
+ if (protocol !== 'http:' && protocol !== 'https:') {
25
+ config.logger.warn(colors.yellow(`goravel-vite-plugin: 'server.origin' is '${origin}', which is not an http or https URL. ` +
26
+ 'The application reads the hot file to find the dev server and needs one, so the address Vite binds is written instead.'));
27
+ return undefined;
28
+ }
29
+ return trimmed;
30
+ }
31
+ /**
32
+ * The dev server URL as the browser reaches it: the host from `server.hmr.host` or
33
+ * `server.host` when one is named, else the bound address, with a wildcard or IPv6
34
+ * loopback bind handed out as `localhost`, which browsers and CSP accept.
35
+ */
36
+ export function resolveDevServerUrl(address, config) {
37
+ const configHmrProtocol = typeof config.server.hmr === 'object' ? config.server.hmr.protocol : null;
38
+ const clientProtocol = configHmrProtocol ? (configHmrProtocol === 'wss' ? 'https' : 'http') : null;
39
+ const serverProtocol = config.server.https ? 'https' : 'http';
40
+ const protocol = clientProtocol ?? serverProtocol;
41
+ const configHmrHost = typeof config.server.hmr === 'object' ? config.server.hmr.host : null;
42
+ const configHost = typeof config.server.host === 'string' ? config.server.host : null;
43
+ const usableConfigHost = [configHmrHost, configHost].find((host) => typeof host === 'string' && host !== '' && !isWildcard(host));
44
+ const serverAddress = isWildcard(address.address) || isIpv6Loopback(address.address) ? 'localhost' : isIpv6(address) ? `[${address.address}]` : address.address;
45
+ const host = usableConfigHost ? bracketIpv6(usableConfigHost) : serverAddress;
46
+ if (!usableConfigHost && isWildcard(address.address)) {
47
+ config.logger.warn(colors.yellow(`goravel-vite-plugin: Vite is exposed to the network (it is bound to '${address.address}'), but the hot file points browsers at '${host}', ` +
48
+ "which only works on this machine. For other devices, set 'server.hmr.host' to the address they reach this machine at, " +
49
+ "and 'server.allowedHosts' too if that address is a name rather than an IP."));
50
+ }
51
+ const configHmrClientPort = typeof config.server.hmr === 'object' ? config.server.hmr.clientPort : null;
52
+ const port = configHmrClientPort ?? address.port;
53
+ return `${protocol}://${host}:${port}`;
54
+ }
55
+ function bracketIpv6(host) {
56
+ return !host.includes(':') || host.startsWith('[') ? host : `[${host}]`;
57
+ }
58
+ function isWildcard(host) {
59
+ return host === '::' || host === '[::]' || host === '0.0.0.0';
60
+ }
61
+ function isIpv6Loopback(host) {
62
+ return host === '::1' || host === '[::1]' || host === '0000:0000:0000:0000:0000:0000:0000:0001';
63
+ }
64
+ function isIpv6(address) {
65
+ return address.family === 'IPv6' || address.family === 6;
66
+ }
67
+ /** @param root - What relative certificate paths are resolved against. */
68
+ export function resolveEnvironmentServerConfig(env, root) {
69
+ if (!env.VITE_DEV_SERVER_KEY && !env.VITE_DEV_SERVER_CERT) {
70
+ return;
71
+ }
72
+ const key = path.resolve(root, env.VITE_DEV_SERVER_KEY ?? '');
73
+ const cert = path.resolve(root, env.VITE_DEV_SERVER_CERT ?? '');
74
+ if (!env.VITE_DEV_SERVER_KEY || !env.VITE_DEV_SERVER_CERT || !fs.existsSync(key) || !fs.existsSync(cert)) {
75
+ throw Error(`Unable to find the certificate files specified in your environment. Ensure you have correctly configured VITE_DEV_SERVER_KEY: [${env.VITE_DEV_SERVER_KEY}] and VITE_DEV_SERVER_CERT: [${env.VITE_DEV_SERVER_CERT}].`);
76
+ }
77
+ const host = resolveHostFromEnv(env);
78
+ if (!host) {
79
+ throw Error(`Unable to determine the host from the environment's APP_URL: [${env.APP_URL}].`);
80
+ }
81
+ return {
82
+ hmr: { host },
83
+ host,
84
+ https: {
85
+ key: fs.readFileSync(key),
86
+ cert: fs.readFileSync(cert),
87
+ },
88
+ };
89
+ }
90
+ function resolveHostFromEnv(env) {
91
+ try {
92
+ return new URL(env.APP_URL).host;
93
+ }
94
+ catch {
95
+ return;
96
+ }
97
+ }
98
+ /** Refuses to start the HMR server in CI unless GORAVEL_BYPASS_ENV_CHECK=1. */
99
+ export function ensureCommandShouldRunInEnvironment(command, env) {
100
+ if (command === 'build' || env.GORAVEL_BYPASS_ENV_CHECK === '1') {
101
+ return;
102
+ }
103
+ if (typeof env.CI !== 'undefined') {
104
+ throw Error('You should not run the Vite HMR server in CI environments. You should build your assets for production instead. To disable this ENV check you may set GORAVEL_BYPASS_ENV_CHECK=1');
105
+ }
106
+ }
107
+ /** The framework version from go.mod, for the dev server banner. */
108
+ export function goravelVersion(root) {
109
+ try {
110
+ const match = /^\s*github\.com\/goravel\/framework\s+(\S+)/m.exec(fs.readFileSync(path.join(root, 'go.mod'), 'utf8'));
111
+ return match?.[1] ?? '';
112
+ }
113
+ catch {
114
+ return '';
115
+ }
116
+ }
117
+ export function pluginVersion() {
118
+ try {
119
+ const packageJson = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
120
+ return packageJson.version ?? '';
121
+ }
122
+ catch {
123
+ return '';
124
+ }
125
+ }
126
+ /** The page shown when the dev server is opened in a browser by mistake. */
127
+ export function devServerIndex(appUrl) {
128
+ const href = escapeHtml(appUrl);
129
+ return `<!DOCTYPE html>
130
+ <html lang="en">
131
+ <head>
132
+ <meta charset="utf-8">
133
+ <meta name="viewport" content="width=device-width, initial-scale=1">
134
+ <title>Goravel Vite</title>
135
+ <style>
136
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f3f4f6; color: #4b5563; font: 16px/1.5 system-ui, sans-serif; }
137
+ main { background: #fff; padding: 2.5rem; border-radius: .5rem; box-shadow: 0 10px 25px rgb(0 0 0 / .08); max-width: 36rem; }
138
+ h1 { margin: 0 0 1rem; font-size: 1.25rem; color: #111827; }
139
+ a { color: #dc2626; }
140
+ @media (prefers-color-scheme: dark) { body { background: #111827; color: #9ca3af; } main { background: #1f2937; } h1 { color: #f3f4f6; } }
141
+ </style>
142
+ </head>
143
+ <body>
144
+ <main>
145
+ <h1>This is the Vite dev server.</h1>
146
+ <p>It only serves your assets. Open your Goravel application instead: <a href="${href}">${href}</a>.</p>
147
+ </main>
148
+ </body>
149
+ </html>
150
+ `;
151
+ }
152
+ function escapeHtml(value) {
153
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
154
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
- "name": "goravel-vite-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "goravel-vite-plugin",
3
+ "version": "0.1.1",
4
+ "description": "Vite plugin for Goravel applications.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "goravel",
8
+ "go",
9
+ "golang",
10
+ "vite",
11
+ "vite-plugin",
12
+ "hmr",
13
+ "assets"
14
+ ],
15
+ "license": "MIT",
16
+ "author": "Goravel",
17
+ "homepage": "https://github.com/goravel/vite-plugin#readme",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/goravel/vite-plugin.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/goravel/vite-plugin/issues"
24
+ },
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ "./package.json": "./package.json",
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist/**/*"
36
+ ],
37
+ "sideEffects": false,
38
+ "engines": {
39
+ "node": "^20.19.0 || >=22.12.0"
40
+ },
41
+ "packageManager": "pnpm@^12.18.0",
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.json",
47
+ "dev": "tsc -p tsconfig.json --watch",
48
+ "typecheck": "tsc -p tsconfig.json --noEmit",
49
+ "test": "npm run build && npm run test:run",
50
+ "test:run": "node --test \"tests/**/*.test.mjs\"",
51
+ "prepublishOnly": "npm run test"
52
+ },
53
+ "devDependencies": {
54
+ "@types/node": "^22.18.1",
55
+ "typescript": "^5.9.2",
56
+ "vite": "^8.0.0"
57
+ },
58
+ "peerDependencies": {
59
+ "vite": "^7.0.0 || ^8.0.0"
60
+ },
61
+ "dependencies": {
62
+ "picocolors": "^1.1.1",
63
+ "tinyglobby": "^0.2.14",
64
+ "vite-plugin-full-reload": "^1.2.0"
65
+ }
66
+ }