@analogjs/platform 3.0.0-beta.24 → 3.0.0-beta.26
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/package.json +3 -2
- package/src/lib/nx-plugin/src/utils/versions/versions.d.ts +6 -6
- package/src/lib/nx-plugin/src/utils/versions/versions.js +6 -6
- package/src/lib/nx-plugin/src/utils/versions/versions.js.map +1 -1
- package/src/lib/options.d.ts +7 -7
- package/src/lib/server-plugin.js +16 -8
- package/src/lib/server-plugin.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@analogjs/platform",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.26",
|
|
4
4
|
"description": "The fullstack meta-framework for Angular",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"author": "Brandon Roberts <robertsbt@gmail.com>",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"url": "https://github.com/sponsors/brandonroberts"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@analogjs/vite-plugin-angular": "3.0.0-beta.
|
|
34
|
+
"@analogjs/vite-plugin-angular": "3.0.0-beta.26",
|
|
35
35
|
"es-toolkit": "^1.45.1",
|
|
36
36
|
"front-matter": "^4.0.2",
|
|
37
37
|
"magic-string": "^0.30.21",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"ofetch": "2.0.0-alpha.3",
|
|
40
40
|
"oxc-parser": "^0.124.0",
|
|
41
41
|
"rolldown": "^1.0.0-rc.13",
|
|
42
|
+
"srvx": "^1.0.8",
|
|
42
43
|
"tinyglobby": "^0.2.15",
|
|
43
44
|
"vitefu": "^1.1.2",
|
|
44
45
|
"xmlbuilder2": "^4.0.3"
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
export declare const ANALOG_JS_ROUTER = "^3.0.0-beta.
|
|
2
|
-
export declare const ANALOG_JS_CONTENT = "^3.0.0-beta.
|
|
1
|
+
export declare const ANALOG_JS_ROUTER = "^3.0.0-beta.26";
|
|
2
|
+
export declare const ANALOG_JS_CONTENT = "^3.0.0-beta.26";
|
|
3
3
|
export declare const MARKED = "^18.0.0";
|
|
4
4
|
export declare const MARKED_GFM_HEADING_ID = "^4.1.1";
|
|
5
5
|
export declare const MARKED_HIGHLIGHT = "^2.2.1";
|
|
6
6
|
export declare const MARKED_MANGLE = "^1.1.10";
|
|
7
7
|
export declare const PRISMJS = "^1.29.0";
|
|
8
8
|
export declare const H3 = "^1.15.11";
|
|
9
|
-
export declare const ANALOG_JS_PLATFORM = "^3.0.0-beta.
|
|
10
|
-
export declare const ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.
|
|
11
|
-
export declare const ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.
|
|
12
|
-
export declare const ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.
|
|
9
|
+
export declare const ANALOG_JS_PLATFORM = "^3.0.0-beta.26";
|
|
10
|
+
export declare const ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.26";
|
|
11
|
+
export declare const ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.26";
|
|
12
|
+
export declare const ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.26";
|
|
13
13
|
export declare const JSDOM = "^22.0.0";
|
|
14
14
|
export declare const VITE_TSCONFIG_PATHS = "^4.2.0";
|
|
15
15
|
export declare const VITE = "^8.0.0";
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
//#region packages/nx-plugin/src/utils/versions/versions.ts
|
|
2
|
-
var ANALOG_JS_ROUTER = "^3.0.0-beta.
|
|
3
|
-
var ANALOG_JS_CONTENT = "^3.0.0-beta.
|
|
2
|
+
var ANALOG_JS_ROUTER = "^3.0.0-beta.26";
|
|
3
|
+
var ANALOG_JS_CONTENT = "^3.0.0-beta.26";
|
|
4
4
|
var MARKED = "^18.0.0";
|
|
5
5
|
var MARKED_GFM_HEADING_ID = "^4.1.1";
|
|
6
6
|
var MARKED_HIGHLIGHT = "^2.2.1";
|
|
7
7
|
var MARKED_MANGLE = "^1.1.10";
|
|
8
8
|
var PRISMJS = "^1.29.0";
|
|
9
9
|
var H3 = "^1.15.11";
|
|
10
|
-
var ANALOG_JS_PLATFORM = "^3.0.0-beta.
|
|
11
|
-
var ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.
|
|
12
|
-
var ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.
|
|
13
|
-
var ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.
|
|
10
|
+
var ANALOG_JS_PLATFORM = "^3.0.0-beta.26";
|
|
11
|
+
var ANALOG_JS_VITE_PLUGIN_ANGULAR = "^3.0.0-beta.26";
|
|
12
|
+
var ANALOG_JS_VITEST_ANGULAR = "^3.0.0-beta.26";
|
|
13
|
+
var ANALOG_JS_VITE_PLUGIN_NITRO = "^3.0.0-beta.26";
|
|
14
14
|
var JSDOM = "^22.0.0";
|
|
15
15
|
var VITE_TSCONFIG_PATHS = "^4.2.0";
|
|
16
16
|
var VITE = "^8.0.0";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"versions.js","names":[],"sources":["../../../../../../../../nx-plugin/src/utils/versions/versions.ts"],"sourcesContent":["// dependencies\nexport const ANALOG_JS_ROUTER = '^3.0.0-beta.
|
|
1
|
+
{"version":3,"file":"versions.js","names":[],"sources":["../../../../../../../../nx-plugin/src/utils/versions/versions.ts"],"sourcesContent":["// dependencies\nexport const ANALOG_JS_ROUTER = '^3.0.0-beta.26';\nexport const ANALOG_JS_CONTENT = '^3.0.0-beta.26';\nexport const MARKED = '^18.0.0';\nexport const MARKED_GFM_HEADING_ID = '^4.1.1';\nexport const MARKED_HIGHLIGHT = '^2.2.1';\nexport const MARKED_MANGLE = '^1.1.10';\nexport const PRISMJS = '^1.29.0';\nexport const H3 = '^1.15.11';\n\n// devDependencies\nexport const ANALOG_JS_PLATFORM = '^3.0.0-beta.26';\nexport const ANALOG_JS_VITE_PLUGIN_ANGULAR = '^3.0.0-beta.26';\nexport const ANALOG_JS_VITEST_ANGULAR = '^3.0.0-beta.26';\nexport const ANALOG_JS_VITE_PLUGIN_NITRO = '^3.0.0-beta.26';\nexport const JSDOM = '^22.0.0';\nexport const VITE_TSCONFIG_PATHS = '^4.2.0';\nexport const VITE = '^8.0.0';\nexport const VITE_7 = '^7.0.0';\nexport const VITE_6 = '^6.4.0';\nexport const VITEST = '^5.0.0';\n"],"mappings":";AACA,IAAa,mBAAmB;AAChC,IAAa,oBAAoB;AACjC,IAAa,SAAS;AACtB,IAAa,wBAAwB;AACrC,IAAa,mBAAmB;AAChC,IAAa,gBAAgB;AAC7B,IAAa,UAAU;AACvB,IAAa,KAAK;AAGlB,IAAa,qBAAqB;AAClC,IAAa,gCAAgC;AAC7C,IAAa,2BAA2B;AACxC,IAAa,8BAA8B;AAC3C,IAAa,QAAQ;AACrB,IAAa,sBAAsB;AACnC,IAAa,OAAO;AACpB,IAAa,SAAS;AACtB,IAAa,SAAS;AACtB,IAAa,SAAS"}
|
package/src/lib/options.d.ts
CHANGED
|
@@ -65,9 +65,9 @@ export interface I18nOptions {
|
|
|
65
65
|
}
|
|
66
66
|
export interface ServerOptions {
|
|
67
67
|
/**
|
|
68
|
-
* The server entry, relative to the project root
|
|
69
|
-
* `
|
|
70
|
-
*
|
|
68
|
+
* The server entry, relative to the project root: a Fetchable module whose
|
|
69
|
+
* default export has `fetch(request)`, and optionally `close()`, which the
|
|
70
|
+
* dev server calls before reloading the entry. TypeScript in the entry's
|
|
71
71
|
* directory is compiled by Vite.
|
|
72
72
|
*/
|
|
73
73
|
entry: string;
|
|
@@ -75,10 +75,10 @@ export interface ServerOptions {
|
|
|
75
75
|
export interface Options {
|
|
76
76
|
ssr?: boolean;
|
|
77
77
|
/**
|
|
78
|
-
* Serve the app from your own server entry (
|
|
79
|
-
* instead of Nitro, using `
|
|
80
|
-
* `
|
|
81
|
-
*
|
|
78
|
+
* Serve the app from your own Fetchable server entry (plain, Hono, Express,
|
|
79
|
+
* NestJS, …) instead of Nitro, using `createAnalogRequestHandler()` or
|
|
80
|
+
* `createAnalogHandler()` from `@analogjs/router/server`. Don't add `nitro()`
|
|
81
|
+
* alongside it.
|
|
82
82
|
*/
|
|
83
83
|
server?: ServerOptions;
|
|
84
84
|
/**
|
package/src/lib/server-plugin.js
CHANGED
|
@@ -3,6 +3,7 @@ import { getServerFnHandlers } from "./nitro/get-server-fn-handlers.js";
|
|
|
3
3
|
import { relative, resolve } from "node:path";
|
|
4
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
5
|
import { normalizePath } from "vite";
|
|
6
|
+
import { toNodeHandler } from "srvx/node";
|
|
6
7
|
//#region packages/platform/src/lib/server-plugin.ts
|
|
7
8
|
var MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \{\}/;
|
|
8
9
|
var DEV_TEMPLATE = Symbol.for("@analogjs/platform/dev-template");
|
|
@@ -128,31 +129,38 @@ function serverPlugin(server, options = {}) {
|
|
|
128
129
|
}
|
|
129
130
|
}
|
|
130
131
|
/**
|
|
131
|
-
* Hands every request Vite doesn't serve to the entry's
|
|
132
|
+
* Hands every request Vite doesn't serve to the entry's `fetch`. The handler is
|
|
132
133
|
* recreated when the server module graph changes (ssrLoadModule returns a new
|
|
133
|
-
* module) and the previous
|
|
134
|
+
* module), and the previous entry's `close()` is called.
|
|
134
135
|
*/
|
|
135
136
|
function devMiddleware(viteServer, entry) {
|
|
136
137
|
let current;
|
|
137
|
-
async function
|
|
138
|
+
async function getHandler() {
|
|
138
139
|
const loaded = await viteServer.ssrLoadModule(entry);
|
|
139
140
|
if (current?.entry !== loaded) {
|
|
140
|
-
const previous = current;
|
|
141
|
+
const previous = current?.entry.default;
|
|
141
142
|
current = {
|
|
142
143
|
entry: loaded,
|
|
143
|
-
|
|
144
|
+
handle: toHandler(loaded)
|
|
144
145
|
};
|
|
145
|
-
|
|
146
|
+
Promise.resolve().then(() => previous?.close?.()).catch(() => void 0);
|
|
146
147
|
}
|
|
147
|
-
return current.
|
|
148
|
+
return current.handle;
|
|
148
149
|
}
|
|
149
150
|
return (req, res, next) => {
|
|
150
|
-
|
|
151
|
+
getHandler().then((handle) => handle(req, res)).catch((error) => {
|
|
151
152
|
viteServer.ssrFixStacktrace(error);
|
|
152
153
|
next(error);
|
|
153
154
|
});
|
|
154
155
|
};
|
|
155
156
|
}
|
|
157
|
+
/** A Node handler around the `fetch` of a Fetchable entry (https://fetchable.org). */
|
|
158
|
+
function toHandler(entry) {
|
|
159
|
+
const fetchable = entry.default;
|
|
160
|
+
const handleRequest = fetchable?.fetch;
|
|
161
|
+
if (typeof handleRequest !== "function") throw new Error("[@analogjs/platform] The server entry must be a Fetchable module: a default export with `fetch(request)`. `createApp()` entries are no longer supported; see https://analogjs.org/docs/features/server/custom-server.");
|
|
162
|
+
return toNodeHandler((request) => handleRequest.call(fetchable, request));
|
|
163
|
+
}
|
|
156
164
|
function removeHtmlMiddlewares(middlewares) {
|
|
157
165
|
middlewares.stack = middlewares.stack.filter((layer) => !HTML_MIDDLEWARES.includes(layer.handle.name ?? ""));
|
|
158
166
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-plugin.js","names":[],"sources":["../../../src/lib/server-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { relative, resolve } from 'node:path';\nimport {\n normalizePath,\n type Connect,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\n\nimport { getPageEndpoints } from './get-page-endpoints.js';\nimport { getServerFnHandlers } from './nitro/get-server-fn-handlers.js';\nimport type { Options, ServerOptions } from './options.js';\n\nconst MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \\{\\}/;\nconst DEV_TEMPLATE = Symbol.for('@analogjs/platform/dev-template');\nconst HTML_MIDDLEWARES = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n];\nconst NITRO_PLUGINS = ['nitro:main', '@analogjs/vite-plugin-nitro'];\n\ntype ServerApp = {\n handle: (\n req: IncomingMessage,\n res: ServerResponse,\n next: (error?: unknown) => void,\n ) => void;\n close?: () => Promise<void>;\n};\ntype ServerEntry = { createApp: () => Promise<ServerApp> };\n\n/**\n * Builds and serves the app from `server.entry` instead of Nitro: the client\n * and one server bundle in `vite build`, and the entry's app behind Vite's\n * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder\n * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.\n */\nexport function serverPlugin(\n server: ServerOptions,\n options: Options = {},\n): Plugin {\n const workspaceRoot =\n options.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n const apiPrefix = options.apiPrefix ?? 'api';\n let root = process.cwd();\n let isBuild = false;\n let builtTemplate: string | undefined;\n let manifestId: string | undefined;\n\n const rootDir = () => relative(workspaceRoot, root) || '.';\n const indexHtml = () => resolve(root, options.index ?? 'index.html');\n\n return {\n name: '@analogjs/platform-server',\n config(config, { command }) {\n const plugins = ((config.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { name?: string }\n | null\n | undefined\n )[];\n if (plugins.some((p) => NITRO_PLUGINS.includes(p?.name ?? ''))) {\n throw new Error(\n '[@analogjs/platform] `analog({ server })` replaces Nitro; remove `nitro()` from the Vite plugins.',\n );\n }\n if (options.i18n?.workers === true) {\n throw new Error(\n '[@analogjs/platform] `i18n.workers` needs Nitro; remove it to use `analog({ server })`, which renders without locale workers.',\n );\n }\n root = normalizePath(resolve(config.root ?? process.cwd()));\n isBuild = command === 'build';\n const outDir = (name: string) =>\n resolve(workspaceRoot, 'dist', rootDir(), name);\n return {\n // Build-time values the router reads, as `nitro()` defines them.\n define: {\n ANALOG_API_PREFIX: JSON.stringify(apiPrefix),\n ...(options.i18n && {\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(\n options.i18n.defaultLocale,\n ),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n }),\n },\n environments: {\n client: {\n build: {\n outDir: outDir('client'),\n rollupOptions: { input: indexHtml() },\n },\n },\n ssr: {\n build: {\n outDir: outDir('server'),\n copyPublicDir: false,\n rollupOptions: { input: { main: resolve(root, server.entry) } },\n },\n },\n },\n builder: {\n // One plugin instance for both builds, so the server build sees\n // the document captured from the client build.\n sharedPlugins: true,\n async buildApp(builder) {\n await builder.build(builder.environments['client']);\n await builder.build(builder.environments['ssr']);\n },\n },\n };\n },\n // The server bundle renders around the built document, so take it from\n // the client build's own output.\n writeBundle(_options, bundle) {\n if (this.environment.name === 'client') {\n const document = bundle[normalizePath(relative(root, indexHtml()))];\n if (document?.type === 'asset') {\n builtTemplate = String(document.source);\n }\n }\n },\n transform: {\n filter: { code: 'ANALOG_SERVER_MANIFEST' },\n handler(code, id) {\n if (!MANIFEST_PLACEHOLDER.test(code)) {\n return undefined;\n }\n manifestId = id;\n return code.replace(\n MANIFEST_PLACEHOLDER,\n `ANALOG_SERVER_MANIFEST = ${serverManifest()}`,\n );\n },\n },\n configureServer(viteServer) {\n (globalThis as Record<symbol, unknown>)[DEV_TEMPLATE] = (url: string) =>\n viteServer.transformIndexHtml(url, readFileSync(indexHtml(), 'utf-8'));\n\n // New or removed page endpoints and server functions change the manifest.\n const invalidateManifest = (file: string) => {\n const graph = viteServer.environments['ssr'].moduleGraph;\n const mod = manifestId && graph.getModuleById(manifestId);\n if (file.endsWith('.server.ts') && mod) {\n graph.invalidateModule(mod);\n }\n };\n viteServer.watcher.on('add', invalidateManifest);\n viteServer.watcher.on('unlink', invalidateManifest);\n\n return () => {\n removeHtmlMiddlewares(viteServer.middlewares);\n viteServer.middlewares.use(\n devMiddleware(viteServer, resolve(root, server.entry)),\n );\n };\n },\n };\n\n function requireBuiltTemplate(): string {\n if (builtTemplate === undefined) {\n throw new Error(\n `[@analogjs/platform] The client build didn't emit ${relative(root, indexHtml())}, which the server renders around.`,\n );\n }\n return builtTemplate;\n }\n\n /**\n * The manifest object literal: the template, and lazy imports of the SSR\n * renderer, the server config, every server function module, and page\n * endpoints keyed by route.\n */\n function serverManifest(): string {\n const src = `${root}/src`;\n const lazy = (file: string) => `() => import(${JSON.stringify(file)})`;\n const appConfig = [\n `${src}/app/app.config.server.ts`,\n `${src}/app.config.server.ts`,\n ].find((file) => existsSync(file));\n const discovery = {\n workspaceRoot,\n sourceRoot: 'src',\n rootDir: rootDir(),\n };\n const pageEndpoints = getPageEndpoints({\n ...discovery,\n additionalPagesDirs: options.additionalPagesDirs,\n }).map(\n ({ file, route }) =>\n `${JSON.stringify(`/${apiPrefix}/_analog${route}`)}: ${lazy(normalizePath(file))}`,\n );\n const serverFnModules = getServerFnHandlers(discovery).map(({ file }) =>\n lazy(file),\n );\n const template = isBuild\n ? `async () => ${JSON.stringify(requireBuiltTemplate())}`\n : `(url) => globalThis[Symbol.for('@analogjs/platform/dev-template')](url)`;\n\n return `{\n apiPrefix: ${JSON.stringify(apiPrefix)},\n template: ${template},\n render: () => import(${JSON.stringify(normalizePath(resolve(root, options.entryServer ?? 'src/main.server.ts')))}).then((m) => m.default),\n config: ${\n appConfig\n ? `() => import(${JSON.stringify(appConfig)}).then((m) => m.config)`\n : `async () => ({ providers: [] })`\n },\n serverFnModules: [${serverFnModules.join(', ')}],\n pageEndpoints: {${pageEndpoints.join(', ')}},\n}`;\n }\n}\n\n/**\n * Hands every request Vite doesn't serve to the entry's app. The app is\n * recreated when the server module graph changes (ssrLoadModule returns a new\n * module) and the previous one is closed.\n */\nfunction devMiddleware(\n viteServer: ViteDevServer,\n entry: string,\n): Connect.NextHandleFunction {\n let current: { entry: ServerEntry; app: Promise<ServerApp> } | undefined;\n\n async function getApp(): Promise<ServerApp> {\n const loaded = (await viteServer.ssrLoadModule(entry)) as ServerEntry;\n if (current?.entry !== loaded) {\n const previous = current;\n current = { entry: loaded, app: loaded.createApp() };\n void previous?.app.then(\n (app) => app.close?.(),\n () => undefined,\n );\n }\n return current.app;\n }\n\n return (req, res, next) => {\n getApp()\n .then((app) => app.handle(req, res, next))\n .catch((error: Error) => {\n viteServer.ssrFixStacktrace(error);\n next(error);\n });\n };\n}\n\nfunction removeHtmlMiddlewares(middlewares: Connect.Server): void {\n middlewares.stack = middlewares.stack.filter(\n (layer) =>\n !HTML_MIDDLEWARES.includes(\n (layer.handle as { name?: string }).name ?? '',\n ),\n );\n}\n"],"mappings":";;;;;;AAcA,IAAM,uBAAuB;AAC7B,IAAM,eAAe,OAAO,IAAI,iCAAiC;AACjE,IAAM,mBAAmB;CACvB;CACA;CACA;CACA;AACF;AACA,IAAM,gBAAgB,CAAC,cAAc,6BAA6B;;;;;;;AAkBlE,SAAgB,aACd,QACA,UAAmB,CAAC,GACZ;CACR,MAAM,gBACJ,QAAQ,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAC3E,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,QAAQ,IAAI;CACvB,IAAI,UAAU;CACd,IAAI;CACJ,IAAI;CAEJ,MAAM,gBAAgB,SAAS,eAAe,IAAI,KAAK;CACvD,MAAM,kBAAkB,QAAQ,MAAM,QAAQ,SAAS,YAAY;CAEnE,OAAO;EACL,MAAM;EACN,OAAO,QAAQ,EAAE,WAAW;GAM1B,KALkB,OAAO,WAAW,CAAC,EAAA,CAAiB,KAAK,QAKvD,CAAA,CAAQ,MAAM,MAAM,cAAc,SAAS,GAAG,QAAQ,EAAE,CAAC,GAC3D,MAAM,IAAI,MACR,mGACF;GAEF,IAAI,QAAQ,MAAM,YAAY,MAC5B,MAAM,IAAI,MACR,+HACF;GAEF,OAAO,cAAc,QAAQ,OAAO,QAAQ,QAAQ,IAAI,CAAC,CAAC;GAC1D,UAAU,YAAY;GACtB,MAAM,UAAU,SACd,QAAQ,eAAe,QAAQ,QAAQ,GAAG,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AAE;;CAE3C;AACF;;;;;;AAOA,SAAS,cACP,YACA,OAC4B;CAC5B,IAAI;CAEJ,eAAe,SAA6B;EAC1C,MAAM,SAAU,MAAM,WAAW,cAAc,KAAK;EACpD,IAAI,SAAS,UAAU,QAAQ;GAC7B,MAAM,WAAW;GACjB,UAAU;IAAE,OAAO;IAAQ,KAAK,OAAO,UAAU;GAAE;GACnD,UAAe,IAAI,MAChB,QAAQ,IAAI,QAAQ,SACf,KAAA,CACR;EACF;EACA,OAAO,QAAQ;CACjB;CAEA,QAAQ,KAAK,KAAK,SAAS;EACzB,OAAO,CAAC,CACL,MAAM,QAAQ,IAAI,OAAO,KAAK,KAAK,IAAI,CAAC,CAAC,CACzC,OAAO,UAAiB;GACvB,WAAW,iBAAiB,KAAK;GACjC,KAAK,KAAK;EACZ,CAAC;CACL;AACF;AAEA,SAAS,sBAAsB,aAAmC;CAChE,YAAY,QAAQ,YAAY,MAAM,QACnC,UACC,CAAC,iBAAiB,SACf,MAAM,OAA6B,QAAQ,EAC9C,CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"server-plugin.js","names":[],"sources":["../../../src/lib/server-plugin.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { relative, resolve } from 'node:path';\nimport type { NodeHttp1Handler } from 'srvx';\nimport { toNodeHandler } from 'srvx/node';\nimport {\n normalizePath,\n type Connect,\n type Plugin,\n type ViteDevServer,\n} from 'vite';\n\nimport { getPageEndpoints } from './get-page-endpoints.js';\nimport { getServerFnHandlers } from './nitro/get-server-fn-handlers.js';\nimport type { Options, ServerOptions } from './options.js';\n\nconst MANIFEST_PLACEHOLDER = /ANALOG_SERVER_MANIFEST = \\{\\}/;\nconst DEV_TEMPLATE = Symbol.for('@analogjs/platform/dev-template');\nconst HTML_MIDDLEWARES = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n];\nconst NITRO_PLUGINS = ['nitro:main', '@analogjs/vite-plugin-nitro'];\n\ntype ServerEntry = {\n default?: {\n fetch?: (request: Request) => Response | Promise<Response>;\n close?: () => unknown;\n };\n};\n\n/**\n * Builds and serves the app from `server.entry` instead of Nitro: the client\n * and one server bundle in `vite build`, and the entry's app behind Vite's\n * own middleware in dev. Fills in the `ANALOG_SERVER_MANIFEST` placeholder\n * that `createAnalogRequestHandler()` in `@analogjs/router/server` reads.\n */\nexport function serverPlugin(\n server: ServerOptions,\n options: Options = {},\n): Plugin {\n const workspaceRoot =\n options.workspaceRoot ?? process.env['NX_WORKSPACE_ROOT'] ?? process.cwd();\n const apiPrefix = options.apiPrefix ?? 'api';\n let root = process.cwd();\n let isBuild = false;\n let builtTemplate: string | undefined;\n let manifestId: string | undefined;\n\n const rootDir = () => relative(workspaceRoot, root) || '.';\n const indexHtml = () => resolve(root, options.index ?? 'index.html');\n\n return {\n name: '@analogjs/platform-server',\n config(config, { command }) {\n const plugins = ((config.plugins ?? []) as unknown[]).flat(Infinity) as (\n | { name?: string }\n | null\n | undefined\n )[];\n if (plugins.some((p) => NITRO_PLUGINS.includes(p?.name ?? ''))) {\n throw new Error(\n '[@analogjs/platform] `analog({ server })` replaces Nitro; remove `nitro()` from the Vite plugins.',\n );\n }\n if (options.i18n?.workers === true) {\n throw new Error(\n '[@analogjs/platform] `i18n.workers` needs Nitro; remove it to use `analog({ server })`, which renders without locale workers.',\n );\n }\n root = normalizePath(resolve(config.root ?? process.cwd()));\n isBuild = command === 'build';\n const outDir = (name: string) =>\n resolve(workspaceRoot, 'dist', rootDir(), name);\n return {\n // Build-time values the router reads, as `nitro()` defines them.\n define: {\n ANALOG_API_PREFIX: JSON.stringify(apiPrefix),\n ...(options.i18n && {\n ANALOG_I18N_DEFAULT_LOCALE: JSON.stringify(\n options.i18n.defaultLocale,\n ),\n ANALOG_I18N_LOCALES: JSON.stringify(options.i18n.locales),\n }),\n },\n environments: {\n client: {\n build: {\n outDir: outDir('client'),\n rollupOptions: { input: indexHtml() },\n },\n },\n ssr: {\n build: {\n outDir: outDir('server'),\n copyPublicDir: false,\n rollupOptions: { input: { main: resolve(root, server.entry) } },\n },\n },\n },\n builder: {\n // One plugin instance for both builds, so the server build sees\n // the document captured from the client build.\n sharedPlugins: true,\n async buildApp(builder) {\n await builder.build(builder.environments['client']);\n await builder.build(builder.environments['ssr']);\n },\n },\n };\n },\n // The server bundle renders around the built document, so take it from\n // the client build's own output.\n writeBundle(_options, bundle) {\n if (this.environment.name === 'client') {\n const document = bundle[normalizePath(relative(root, indexHtml()))];\n if (document?.type === 'asset') {\n builtTemplate = String(document.source);\n }\n }\n },\n transform: {\n filter: { code: 'ANALOG_SERVER_MANIFEST' },\n handler(code, id) {\n if (!MANIFEST_PLACEHOLDER.test(code)) {\n return undefined;\n }\n manifestId = id;\n return code.replace(\n MANIFEST_PLACEHOLDER,\n `ANALOG_SERVER_MANIFEST = ${serverManifest()}`,\n );\n },\n },\n configureServer(viteServer) {\n (globalThis as Record<symbol, unknown>)[DEV_TEMPLATE] = (url: string) =>\n viteServer.transformIndexHtml(url, readFileSync(indexHtml(), 'utf-8'));\n\n // New or removed page endpoints and server functions change the manifest.\n const invalidateManifest = (file: string) => {\n const graph = viteServer.environments['ssr'].moduleGraph;\n const mod = manifestId && graph.getModuleById(manifestId);\n if (file.endsWith('.server.ts') && mod) {\n graph.invalidateModule(mod);\n }\n };\n viteServer.watcher.on('add', invalidateManifest);\n viteServer.watcher.on('unlink', invalidateManifest);\n\n return () => {\n removeHtmlMiddlewares(viteServer.middlewares);\n viteServer.middlewares.use(\n devMiddleware(viteServer, resolve(root, server.entry)),\n );\n };\n },\n };\n\n function requireBuiltTemplate(): string {\n if (builtTemplate === undefined) {\n throw new Error(\n `[@analogjs/platform] The client build didn't emit ${relative(root, indexHtml())}, which the server renders around.`,\n );\n }\n return builtTemplate;\n }\n\n /**\n * The manifest object literal: the template, and lazy imports of the SSR\n * renderer, the server config, every server function module, and page\n * endpoints keyed by route.\n */\n function serverManifest(): string {\n const src = `${root}/src`;\n const lazy = (file: string) => `() => import(${JSON.stringify(file)})`;\n const appConfig = [\n `${src}/app/app.config.server.ts`,\n `${src}/app.config.server.ts`,\n ].find((file) => existsSync(file));\n const discovery = {\n workspaceRoot,\n sourceRoot: 'src',\n rootDir: rootDir(),\n };\n const pageEndpoints = getPageEndpoints({\n ...discovery,\n additionalPagesDirs: options.additionalPagesDirs,\n }).map(\n ({ file, route }) =>\n `${JSON.stringify(`/${apiPrefix}/_analog${route}`)}: ${lazy(normalizePath(file))}`,\n );\n const serverFnModules = getServerFnHandlers(discovery).map(({ file }) =>\n lazy(file),\n );\n const template = isBuild\n ? `async () => ${JSON.stringify(requireBuiltTemplate())}`\n : `(url) => globalThis[Symbol.for('@analogjs/platform/dev-template')](url)`;\n\n return `{\n apiPrefix: ${JSON.stringify(apiPrefix)},\n template: ${template},\n render: () => import(${JSON.stringify(normalizePath(resolve(root, options.entryServer ?? 'src/main.server.ts')))}).then((m) => m.default),\n config: ${\n appConfig\n ? `() => import(${JSON.stringify(appConfig)}).then((m) => m.config)`\n : `async () => ({ providers: [] })`\n },\n serverFnModules: [${serverFnModules.join(', ')}],\n pageEndpoints: {${pageEndpoints.join(', ')}},\n}`;\n }\n}\n\n/**\n * Hands every request Vite doesn't serve to the entry's `fetch`. The handler is\n * recreated when the server module graph changes (ssrLoadModule returns a new\n * module), and the previous entry's `close()` is called.\n */\nfunction devMiddleware(\n viteServer: ViteDevServer,\n entry: string,\n): Connect.NextHandleFunction {\n let current: { entry: ServerEntry; handle: NodeHttp1Handler } | undefined;\n\n async function getHandler(): Promise<NodeHttp1Handler> {\n const loaded = (await viteServer.ssrLoadModule(entry)) as ServerEntry;\n if (current?.entry !== loaded) {\n const previous = current?.entry.default;\n current = { entry: loaded, handle: toHandler(loaded) };\n void Promise.resolve()\n .then(() => previous?.close?.())\n .catch(() => undefined);\n }\n return current.handle;\n }\n\n return (req, res, next) => {\n getHandler()\n .then((handle) => handle(req, res))\n .catch((error: Error) => {\n viteServer.ssrFixStacktrace(error);\n next(error);\n });\n };\n}\n\n/** A Node handler around the `fetch` of a Fetchable entry (https://fetchable.org). */\nfunction toHandler(entry: ServerEntry): NodeHttp1Handler {\n const fetchable = entry.default;\n const handleRequest = fetchable?.fetch;\n if (typeof handleRequest !== 'function') {\n throw new Error(\n '[@analogjs/platform] The server entry must be a Fetchable module: a default export with `fetch(request)`. `createApp()` entries are no longer supported; see https://analogjs.org/docs/features/server/custom-server.',\n );\n }\n // Connect middleware is typed with the HTTP/1 request and response.\n return toNodeHandler((request) =>\n handleRequest.call(fetchable, request),\n ) as NodeHttp1Handler;\n}\n\nfunction removeHtmlMiddlewares(middlewares: Connect.Server): void {\n middlewares.stack = middlewares.stack.filter(\n (layer) =>\n !HTML_MIDDLEWARES.includes(\n (layer.handle as { name?: string }).name ?? '',\n ),\n );\n}\n"],"mappings":";;;;;;;AAeA,IAAM,uBAAuB;AAC7B,IAAM,eAAe,OAAO,IAAI,iCAAiC;AACjE,IAAM,mBAAmB;CACvB;CACA;CACA;CACA;AACF;AACA,IAAM,gBAAgB,CAAC,cAAc,6BAA6B;;;;;;;AAelE,SAAgB,aACd,QACA,UAAmB,CAAC,GACZ;CACR,MAAM,gBACJ,QAAQ,iBAAiB,QAAQ,IAAI,wBAAwB,QAAQ,IAAI;CAC3E,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,QAAQ,IAAI;CACvB,IAAI,UAAU;CACd,IAAI;CACJ,IAAI;CAEJ,MAAM,gBAAgB,SAAS,eAAe,IAAI,KAAK;CACvD,MAAM,kBAAkB,QAAQ,MAAM,QAAQ,SAAS,YAAY;CAEnE,OAAO;EACL,MAAM;EACN,OAAO,QAAQ,EAAE,WAAW;GAM1B,KALkB,OAAO,WAAW,CAAC,EAAA,CAAiB,KAAK,QAKvD,CAAA,CAAQ,MAAM,MAAM,cAAc,SAAS,GAAG,QAAQ,EAAE,CAAC,GAC3D,MAAM,IAAI,MACR,mGACF;GAEF,IAAI,Q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