@rpcbase/vite 0.148.0 → 0.149.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,10 +2,10 @@ import fs, { existsSync, readFileSync } from "node:fs";
2
2
  import path from "path";
3
3
  import dotenv from "dotenv";
4
4
  import { expand } from "dotenv-expand";
5
- import { createServer as createServer$1, mergeConfig, loadEnv } from "vite";
5
+ import babel from "@rolldown/plugin-babel";
6
+ import { createServer as createServer$1, loadEnv, mergeConfig } from "vite";
6
7
  import { viteSingleFile } from "vite-plugin-singlefile";
7
- import react from "@vitejs/plugin-react";
8
- import { createHtmlPlugin } from "vite-plugin-html";
8
+ import react, { reactCompilerPreset } from "@vitejs/plugin-react";
9
9
  import { analyzer } from "vite-bundle-analyzer";
10
10
  import { createRequire } from "node:module";
11
11
  import { spawn } from "node:child_process";
@@ -14,800 +14,691 @@ import { fileURLToPath } from "node:url";
14
14
  import MagicString from "magic-string";
15
15
  import * as ts from "typescript";
16
16
  import { globSync } from "glob";
17
- const envFilePath = path.resolve(process.cwd(), ".env");
17
+ //#region src/dotEnvExpand.ts
18
+ var envFilePath = path.resolve(process.cwd(), ".env");
18
19
  if (fs.existsSync(envFilePath)) {
19
- const parsedFile = dotenv.parse(fs.readFileSync(envFilePath));
20
- const expanded = expand({
21
- parsed: parsedFile
22
- }).parsed || {};
23
- Object.assign(process.env, expanded);
20
+ const expanded = expand({ parsed: dotenv.parse(fs.readFileSync(envFilePath)) }).parsed || {};
21
+ Object.assign(process.env, expanded);
24
22
  }
25
- const require$1 = createRequire(import.meta.url);
26
- const splitPackageSpecifier = (specifier) => {
27
- if (!specifier) return {
28
- pkgName: specifier,
29
- subpath: ""
30
- };
31
- if (specifier.startsWith("@")) {
32
- const segments = specifier.split("/");
33
- if (segments.length < 2) return {
34
- pkgName: specifier,
35
- subpath: ""
36
- };
37
- return {
38
- pkgName: `${segments[0]}/${segments[1]}`,
39
- subpath: segments.slice(2).join("/")
40
- };
41
- }
42
- const [pkgName, ...rest] = specifier.split("/");
43
- return {
44
- pkgName,
45
- subpath: rest.join("/")
46
- };
23
+ //#endregion
24
+ //#region src/resolveIntegratedPackagePath.ts
25
+ var require = createRequire(import.meta.url);
26
+ var splitPackageSpecifier = (specifier) => {
27
+ if (!specifier) return {
28
+ pkgName: specifier,
29
+ subpath: ""
30
+ };
31
+ if (specifier.startsWith("@")) {
32
+ const segments = specifier.split("/");
33
+ if (segments.length < 2) return {
34
+ pkgName: specifier,
35
+ subpath: ""
36
+ };
37
+ return {
38
+ pkgName: `${segments[0]}/${segments[1]}`,
39
+ subpath: segments.slice(2).join("/")
40
+ };
41
+ }
42
+ const [pkgName, ...rest] = specifier.split("/");
43
+ return {
44
+ pkgName,
45
+ subpath: rest.join("/")
46
+ };
47
47
  };
48
- const withTrailingSep = (p) => p.endsWith(path.sep) ? p : p + path.sep;
49
- const resolvePackageRoot = (pkg) => {
50
- const {
51
- pkgName
52
- } = splitPackageSpecifier(pkg);
53
- if (!pkgName) return pkg;
54
- try {
55
- const pkgJson = require$1.resolve(`${pkgName}/package.json`);
56
- return path.dirname(pkgJson);
57
- } catch (err) {
58
- const entry = require$1.resolve(pkgName);
59
- let dir = path.dirname(entry);
60
- while (true) {
61
- const pkgJsonPath = path.join(dir, "package.json");
62
- if (existsSync(pkgJsonPath)) {
63
- try {
64
- const json = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
65
- if (json && json.name === pkgName) return dir;
66
- } catch {
67
- }
68
- }
69
- const parent = path.dirname(dir);
70
- if (parent === dir) break;
71
- dir = parent;
72
- }
73
- const nmMarker = `${path.sep}node_modules${path.sep}`;
74
- const idx = entry.lastIndexOf(nmMarker);
75
- if (idx !== -1) {
76
- const nmRoot = entry.slice(0, idx + nmMarker.length);
77
- return path.join(nmRoot, pkgName);
78
- }
79
- throw err;
80
- }
48
+ var withTrailingSep = (p) => p.endsWith(path.sep) ? p : p + path.sep;
49
+ var resolvePackageRoot = (pkg) => {
50
+ const { pkgName } = splitPackageSpecifier(pkg);
51
+ if (!pkgName) return pkg;
52
+ try {
53
+ const pkgJson = require.resolve(`${pkgName}/package.json`);
54
+ return path.dirname(pkgJson);
55
+ } catch (err) {
56
+ const entry = require.resolve(pkgName);
57
+ let dir = path.dirname(entry);
58
+ while (true) {
59
+ const pkgJsonPath = path.join(dir, "package.json");
60
+ if (existsSync(pkgJsonPath)) try {
61
+ const json = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
62
+ if (json && json.name === pkgName) return dir;
63
+ } catch {}
64
+ const parent = path.dirname(dir);
65
+ if (parent === dir) break;
66
+ dir = parent;
67
+ }
68
+ const nmMarker = `${path.sep}node_modules${path.sep}`;
69
+ const idx = entry.lastIndexOf(nmMarker);
70
+ if (idx !== -1) {
71
+ const nmRoot = entry.slice(0, idx + nmMarker.length);
72
+ return path.join(nmRoot, pkgName);
73
+ }
74
+ throw err;
75
+ }
81
76
  };
82
- const resolveIntegratedPackagePath = (specifier) => {
83
- const {
84
- pkgName,
85
- subpath
86
- } = splitPackageSpecifier(specifier);
87
- if (!pkgName) return specifier;
88
- const root = resolvePackageRoot(pkgName);
89
- if (!subpath) {
90
- return withTrailingSep(root);
91
- }
92
- const subDir = path.join(root, subpath);
93
- const pkgJsonPath = path.join(subDir, "package.json");
94
- if (existsSync(pkgJsonPath)) {
95
- try {
96
- const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
97
- const entry = pkgJson.module || pkgJson.main;
98
- if (entry) {
99
- return path.join(subDir, entry);
100
- }
101
- } catch {
102
- }
103
- }
104
- try {
105
- return require$1.resolve(specifier);
106
- } catch {
107
- return withTrailingSep(subDir);
108
- }
77
+ var resolveIntegratedPackagePath = (specifier) => {
78
+ const { pkgName, subpath } = splitPackageSpecifier(specifier);
79
+ if (!pkgName) return specifier;
80
+ const root = resolvePackageRoot(pkgName);
81
+ if (!subpath) return withTrailingSep(root);
82
+ const subDir = path.join(root, subpath);
83
+ const pkgJsonPath = path.join(subDir, "package.json");
84
+ if (existsSync(pkgJsonPath)) try {
85
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
86
+ const entry = pkgJson.module || pkgJson.main;
87
+ if (entry) return path.join(subDir, entry);
88
+ } catch {}
89
+ try {
90
+ return require.resolve(specifier);
91
+ } catch {
92
+ return withTrailingSep(subDir);
93
+ }
109
94
  };
110
- const __dirname$1 = path$1.dirname(fileURLToPath(import.meta.url));
95
+ //#endregion
96
+ //#region src/plugins/posthog-sourcemaps/index.ts
97
+ var __dirname = path$1.dirname(fileURLToPath(import.meta.url));
111
98
  function run(bin, args) {
112
- return new Promise((resolve, reject) => {
113
- const p = spawn(bin, args, {
114
- stdio: "inherit"
115
- });
116
- p.on("close", (code) => code === 0 ? resolve() : reject(new Error(`posthog-cli exited ${code}`)));
117
- });
99
+ return new Promise((resolve, reject) => {
100
+ spawn(bin, args, { stdio: "inherit" }).on("close", (code) => code === 0 ? resolve() : reject(/* @__PURE__ */ new Error(`posthog-cli exited ${code}`)));
101
+ });
118
102
  }
119
103
  function resolvePosthogCliBin() {
120
- const binName = "posthog-cli";
121
- const fromCwd = path$1.join(process.cwd(), "node_modules", ".bin", binName);
122
- if (fs.existsSync(fromCwd)) return fromCwd;
123
- let dir = __dirname$1;
124
- while (true) {
125
- const candidate = path$1.join(dir, "node_modules", ".bin", binName);
126
- if (fs.existsSync(candidate)) return candidate;
127
- const parent = path$1.dirname(dir);
128
- if (parent === dir) break;
129
- dir = parent;
130
- }
131
- return binName;
104
+ const binName = "posthog-cli";
105
+ const fromCwd = path$1.join(process.cwd(), "node_modules", ".bin", binName);
106
+ if (fs.existsSync(fromCwd)) return fromCwd;
107
+ let dir = __dirname;
108
+ while (true) {
109
+ const candidate = path$1.join(dir, "node_modules", ".bin", binName);
110
+ if (fs.existsSync(candidate)) return candidate;
111
+ const parent = path$1.dirname(dir);
112
+ if (parent === dir) break;
113
+ dir = parent;
114
+ }
115
+ return binName;
132
116
  }
133
117
  function posthogSourcemapsPlugin(opts = {}) {
134
- const {
135
- directory = "build/dist",
136
- version,
137
- host = process.env.RB_PUBLIC_POSTHOG_HOST || "https://eu.posthog.com",
138
- deleteAfterUpload = true
139
- } = opts;
140
- const bin = resolvePosthogCliBin();
141
- const globalArgs = ["--host", host];
142
- return {
143
- name: "posthog-sourcemaps",
144
- apply: "build",
145
- closeBundle: async () => {
146
- const orange = "\x1B[38;5;208m";
147
- const reset = "\x1B[0m";
148
- const envId = process.env.POSTHOG_CLI_ENV_ID;
149
- const token = process.env.POSTHOG_CLI_TOKEN;
150
- if (!envId || !token) {
151
- console.warn(`${orange}posthog-sourcemaps: plugin is enabled but no env vars for auth configured (POSTHOG_CLI_ENV_ID/POSTHOG_CLI_TOKEN). Skipping without failing.${reset}`);
152
- return;
153
- }
154
- const injectArgs = ["sourcemap", "inject", "--directory", directory];
155
- if (version) injectArgs.push("--version", version);
156
- const uploadArgs = ["sourcemap", "upload", "--directory", directory];
157
- if (deleteAfterUpload) uploadArgs.push("--delete-after");
158
- await run(bin, [...globalArgs, ...injectArgs]);
159
- await run(bin, [...globalArgs, ...uploadArgs]);
160
- }
161
- };
118
+ const { directory = "build/dist", version, host = process.env.RB_PUBLIC_POSTHOG_HOST || "https://eu.posthog.com", deleteAfterUpload = true } = opts;
119
+ const bin = resolvePosthogCliBin();
120
+ const globalArgs = ["--host", host];
121
+ return {
122
+ name: "posthog-sourcemaps",
123
+ apply: "build",
124
+ closeBundle: async () => {
125
+ const orange = "\x1B[38;5;208m";
126
+ const reset = "\x1B[0m";
127
+ const envId = process.env.POSTHOG_CLI_ENV_ID;
128
+ const token = process.env.POSTHOG_CLI_TOKEN;
129
+ if (!envId || !token) {
130
+ console.warn(`${orange}posthog-sourcemaps: plugin is enabled but no env vars for auth configured (POSTHOG_CLI_ENV_ID/POSTHOG_CLI_TOKEN). Skipping without failing.${reset}`);
131
+ return;
132
+ }
133
+ const injectArgs = [
134
+ "sourcemap",
135
+ "inject",
136
+ "--directory",
137
+ directory
138
+ ];
139
+ if (version) injectArgs.push("--version", version);
140
+ const uploadArgs = [
141
+ "sourcemap",
142
+ "upload",
143
+ "--directory",
144
+ directory
145
+ ];
146
+ if (deleteAfterUpload) uploadArgs.push("--delete-after");
147
+ await run(bin, [...globalArgs, ...injectArgs]);
148
+ await run(bin, [...globalArgs, ...uploadArgs]);
149
+ }
150
+ };
162
151
  }
152
+ //#endregion
153
+ //#region src/plugins/prune-models-for-client/transformSource.ts
163
154
  function isForbiddenModuleSource(source) {
164
- if (source === "mongoose") return true;
165
- if (source.startsWith("node:")) return true;
166
- if (source.endsWith("/extendMongooseSchema") || source.endsWith("./extendMongooseSchema") || source.endsWith("extendMongooseSchema")) {
167
- return true;
168
- }
169
- return false;
155
+ if (source === "mongoose") return true;
156
+ if (source.startsWith("node:")) return true;
157
+ if (source.endsWith("/extendMongooseSchema") || source.endsWith("./extendMongooseSchema") || source.endsWith("extendMongooseSchema")) return true;
158
+ return false;
170
159
  }
171
160
  function getModuleSpecifierValue(importDeclaration) {
172
- const moduleSpecifier = importDeclaration.moduleSpecifier;
173
- if (!ts.isStringLiteralLike(moduleSpecifier)) return null;
174
- return moduleSpecifier.text;
161
+ const moduleSpecifier = importDeclaration.moduleSpecifier;
162
+ if (!ts.isStringLiteralLike(moduleSpecifier)) return null;
163
+ return moduleSpecifier.text;
175
164
  }
176
165
  function isTypeOnlyImport(importDeclaration) {
177
- const importClause = importDeclaration.importClause;
178
- if (!importClause) return false;
179
- return importClause.isTypeOnly === true;
166
+ const importClause = importDeclaration.importClause;
167
+ if (!importClause) return false;
168
+ return importClause.isTypeOnly === true;
180
169
  }
181
170
  function getImportValueLocals(importDeclaration) {
182
- if (isTypeOnlyImport(importDeclaration)) return [];
183
- const importClause = importDeclaration.importClause;
184
- if (!importClause) return [];
185
- const locals = [];
186
- if (importClause.name) locals.push(importClause.name.text);
187
- const namedBindings = importClause.namedBindings;
188
- if (namedBindings) {
189
- if (ts.isNamespaceImport(namedBindings)) {
190
- locals.push(namedBindings.name.text);
191
- } else if (ts.isNamedImports(namedBindings)) {
192
- for (const specifier of namedBindings.elements) {
193
- if (specifier.isTypeOnly) continue;
194
- locals.push(specifier.name.text);
195
- }
196
- }
197
- }
198
- return locals;
171
+ if (isTypeOnlyImport(importDeclaration)) return [];
172
+ const importClause = importDeclaration.importClause;
173
+ if (!importClause) return [];
174
+ const locals = [];
175
+ if (importClause.name) locals.push(importClause.name.text);
176
+ const namedBindings = importClause.namedBindings;
177
+ if (namedBindings) {
178
+ if (ts.isNamespaceImport(namedBindings)) locals.push(namedBindings.name.text);
179
+ else if (ts.isNamedImports(namedBindings)) for (const specifier of namedBindings.elements) {
180
+ if (specifier.isTypeOnly) continue;
181
+ locals.push(specifier.name.text);
182
+ }
183
+ }
184
+ return locals;
199
185
  }
200
186
  function getNamedImportSpecifiers(importDeclaration) {
201
- const importClause = importDeclaration.importClause;
202
- if (!importClause) return null;
203
- if (!importClause.namedBindings) return null;
204
- if (!ts.isNamedImports(importClause.namedBindings)) return null;
205
- return importClause.namedBindings.elements;
187
+ const importClause = importDeclaration.importClause;
188
+ if (!importClause) return null;
189
+ if (!importClause.namedBindings) return null;
190
+ if (!ts.isNamedImports(importClause.namedBindings)) return null;
191
+ return importClause.namedBindings.elements;
206
192
  }
207
193
  function rewriteRpcbaseDbImport(importDeclaration, forbiddenIdentifiers) {
208
- const valueLocals = getImportValueLocals(importDeclaration);
209
- const zLocals = /* @__PURE__ */ new Set();
210
- const namedImports = getNamedImportSpecifiers(importDeclaration);
211
- if (namedImports && !isTypeOnlyImport(importDeclaration)) {
212
- for (const specifier of namedImports) {
213
- if (specifier.isTypeOnly) continue;
214
- const imported = specifier.propertyName?.text ?? specifier.name.text;
215
- if (imported !== "z") continue;
216
- zLocals.add(specifier.name.text);
217
- }
218
- }
219
- for (const local of valueLocals) {
220
- if (!zLocals.has(local)) forbiddenIdentifiers.add(local);
221
- }
222
- if (zLocals.size === 0) {
223
- return {
224
- rewriteText: null,
225
- remainingValueLocals: []
226
- };
227
- }
228
- const specifierText = Array.from(zLocals).map((local) => local === "z" ? "z" : `z as ${local}`).join(", ");
229
- return {
230
- rewriteText: `import { ${specifierText} } from "@rpcbase/db"`,
231
- remainingValueLocals: Array.from(zLocals)
232
- };
194
+ const valueLocals = getImportValueLocals(importDeclaration);
195
+ const zLocals = /* @__PURE__ */ new Set();
196
+ const namedImports = getNamedImportSpecifiers(importDeclaration);
197
+ if (namedImports && !isTypeOnlyImport(importDeclaration)) for (const specifier of namedImports) {
198
+ if (specifier.isTypeOnly) continue;
199
+ if ((specifier.propertyName?.text ?? specifier.name.text) !== "z") continue;
200
+ zLocals.add(specifier.name.text);
201
+ }
202
+ for (const local of valueLocals) if (!zLocals.has(local)) forbiddenIdentifiers.add(local);
203
+ if (zLocals.size === 0) return {
204
+ rewriteText: null,
205
+ remainingValueLocals: []
206
+ };
207
+ return {
208
+ rewriteText: `import { ${Array.from(zLocals).map((local) => local === "z" ? "z" : `z as ${local}`).join(", ")} } from "@rpcbase/db"`,
209
+ remainingValueLocals: Array.from(zLocals)
210
+ };
233
211
  }
234
212
  function collectBindingNames(name, out) {
235
- if (ts.isIdentifier(name)) {
236
- out.push(name.text);
237
- return;
238
- }
239
- for (const element of name.elements) {
240
- if (ts.isOmittedExpression(element)) continue;
241
- collectBindingNames(element.name, out);
242
- }
213
+ if (ts.isIdentifier(name)) {
214
+ out.push(name.text);
215
+ return;
216
+ }
217
+ for (const element of name.elements) {
218
+ if (ts.isOmittedExpression(element)) continue;
219
+ collectBindingNames(element.name, out);
220
+ }
243
221
  }
244
222
  function getTopLevelBindings(statement) {
245
- if (ts.isVariableStatement(statement)) {
246
- const names = [];
247
- for (const decl of statement.declarationList.declarations) {
248
- collectBindingNames(decl.name, names);
249
- }
250
- return names;
251
- }
252
- if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) {
253
- return statement.name ? [statement.name.text] : [];
254
- }
255
- return [];
223
+ if (ts.isVariableStatement(statement)) {
224
+ const names = [];
225
+ for (const decl of statement.declarationList.declarations) collectBindingNames(decl.name, names);
226
+ return names;
227
+ }
228
+ if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) return statement.name ? [statement.name.text] : [];
229
+ return [];
256
230
  }
257
231
  function isRuntimeReferenceIdentifier(identifier) {
258
- const parent = identifier.parent;
259
- if (!parent) return true;
260
- if (ts.isVariableDeclaration(parent) && parent.name === identifier) return false;
261
- if (ts.isParameter(parent) && parent.name === identifier) return false;
262
- if ((ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent)) && parent.name === identifier) return false;
263
- if ((ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) && parent.name === identifier) return false;
264
- if (ts.isEnumDeclaration(parent) && parent.name === identifier) return false;
265
- if (ts.isTypeAliasDeclaration(parent) && parent.name === identifier) return false;
266
- if (ts.isInterfaceDeclaration(parent) && parent.name === identifier) return false;
267
- if (ts.isModuleDeclaration(parent) && parent.name === identifier) return false;
268
- if (ts.isTypeParameterDeclaration(parent) && parent.name === identifier) return false;
269
- if (ts.isImportClause(parent) && parent.name === identifier) return false;
270
- if (ts.isNamespaceImport(parent) && parent.name === identifier) return false;
271
- if (ts.isImportSpecifier(parent) && parent.name === identifier) return false;
272
- if (ts.isImportEqualsDeclaration(parent) && parent.name === identifier) return false;
273
- if (ts.isBindingElement(parent)) {
274
- if (parent.name === identifier) return false;
275
- if (parent.propertyName === identifier) return false;
276
- }
277
- if (ts.isPropertyAccessExpression(parent) && parent.name === identifier) return false;
278
- if (ts.isQualifiedName(parent)) return false;
279
- if (ts.isPropertyAssignment(parent) && parent.name === identifier) return false;
280
- if (ts.isPropertyDeclaration(parent) && parent.name === identifier) return false;
281
- if (ts.isPropertySignature(parent) && parent.name === identifier) return false;
282
- if (ts.isMethodDeclaration(parent) && parent.name === identifier) return false;
283
- if (ts.isMethodSignature(parent) && parent.name === identifier) return false;
284
- if (ts.isGetAccessorDeclaration(parent) && parent.name === identifier) return false;
285
- if (ts.isSetAccessorDeclaration(parent) && parent.name === identifier) return false;
286
- if (ts.isShorthandPropertyAssignment(parent) && parent.name === identifier) return true;
287
- if (ts.isExportSpecifier(parent)) {
288
- const local = parent.propertyName ?? parent.name;
289
- return identifier === local;
290
- }
291
- if (ts.isLabeledStatement(parent) && parent.label === identifier) return false;
292
- if ((ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) && parent.label === identifier) return false;
293
- return true;
232
+ const parent = identifier.parent;
233
+ if (!parent) return true;
234
+ if (ts.isVariableDeclaration(parent) && parent.name === identifier) return false;
235
+ if (ts.isParameter(parent) && parent.name === identifier) return false;
236
+ if ((ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent)) && parent.name === identifier) return false;
237
+ if ((ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) && parent.name === identifier) return false;
238
+ if (ts.isEnumDeclaration(parent) && parent.name === identifier) return false;
239
+ if (ts.isTypeAliasDeclaration(parent) && parent.name === identifier) return false;
240
+ if (ts.isInterfaceDeclaration(parent) && parent.name === identifier) return false;
241
+ if (ts.isModuleDeclaration(parent) && parent.name === identifier) return false;
242
+ if (ts.isTypeParameterDeclaration(parent) && parent.name === identifier) return false;
243
+ if (ts.isImportClause(parent) && parent.name === identifier) return false;
244
+ if (ts.isNamespaceImport(parent) && parent.name === identifier) return false;
245
+ if (ts.isImportSpecifier(parent) && parent.name === identifier) return false;
246
+ if (ts.isImportEqualsDeclaration(parent) && parent.name === identifier) return false;
247
+ if (ts.isBindingElement(parent)) {
248
+ if (parent.name === identifier) return false;
249
+ if (parent.propertyName === identifier) return false;
250
+ }
251
+ if (ts.isPropertyAccessExpression(parent) && parent.name === identifier) return false;
252
+ if (ts.isQualifiedName(parent)) return false;
253
+ if (ts.isPropertyAssignment(parent) && parent.name === identifier) return false;
254
+ if (ts.isPropertyDeclaration(parent) && parent.name === identifier) return false;
255
+ if (ts.isPropertySignature(parent) && parent.name === identifier) return false;
256
+ if (ts.isMethodDeclaration(parent) && parent.name === identifier) return false;
257
+ if (ts.isMethodSignature(parent) && parent.name === identifier) return false;
258
+ if (ts.isGetAccessorDeclaration(parent) && parent.name === identifier) return false;
259
+ if (ts.isSetAccessorDeclaration(parent) && parent.name === identifier) return false;
260
+ if (ts.isShorthandPropertyAssignment(parent) && parent.name === identifier) return true;
261
+ if (ts.isExportSpecifier(parent)) return identifier === (parent.propertyName ?? parent.name);
262
+ if (ts.isLabeledStatement(parent) && parent.label === identifier) return false;
263
+ if ((ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) && parent.label === identifier) return false;
264
+ return true;
294
265
  }
295
266
  function referencesForbiddenRuntime(statement, forbidden) {
296
- if (forbidden.size === 0) return false;
297
- if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) return false;
298
- let found = false;
299
- const visit = (node) => {
300
- if (found) return;
301
- if (ts.isTypeNode(node)) return;
302
- if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
303
- if (ts.isIdentifier(node)) {
304
- if (forbidden.has(node.text) && isRuntimeReferenceIdentifier(node)) {
305
- found = true;
306
- return;
307
- }
308
- }
309
- ts.forEachChild(node, visit);
310
- };
311
- visit(statement);
312
- return found;
267
+ if (forbidden.size === 0) return false;
268
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) return false;
269
+ let found = false;
270
+ const visit = (node) => {
271
+ if (found) return;
272
+ if (ts.isTypeNode(node)) return;
273
+ if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
274
+ if (ts.isIdentifier(node)) {
275
+ if (forbidden.has(node.text) && isRuntimeReferenceIdentifier(node)) {
276
+ found = true;
277
+ return;
278
+ }
279
+ }
280
+ ts.forEachChild(node, visit);
281
+ };
282
+ visit(statement);
283
+ return found;
313
284
  }
314
285
  function scriptKindFromFilePath(filePath) {
315
- const ext = path$1.extname(filePath).toLowerCase();
316
- if (ext === ".tsx") return ts.ScriptKind.TSX;
317
- return ts.ScriptKind.TS;
286
+ if (path$1.extname(filePath).toLowerCase() === ".tsx") return ts.ScriptKind.TSX;
287
+ return ts.ScriptKind.TS;
318
288
  }
319
289
  function collectRuntimeIdentifierReferences(statement, out) {
320
- const visit = (node) => {
321
- if (ts.isTypeNode(node)) return;
322
- if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
323
- if (ts.isIdentifier(node) && isRuntimeReferenceIdentifier(node)) {
324
- out.add(node.text);
325
- }
326
- ts.forEachChild(node, visit);
327
- };
328
- visit(statement);
290
+ const visit = (node) => {
291
+ if (ts.isTypeNode(node)) return;
292
+ if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
293
+ if (ts.isIdentifier(node) && isRuntimeReferenceIdentifier(node)) out.add(node.text);
294
+ ts.forEachChild(node, visit);
295
+ };
296
+ visit(statement);
329
297
  }
330
298
  function createTransformSource() {
331
- return ({
332
- code,
333
- filePath
334
- }) => {
335
- const forbiddenIdentifiers = /* @__PURE__ */ new Set();
336
- const scriptKind = scriptKindFromFilePath(filePath);
337
- const sourceFile = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true, scriptKind);
338
- const importActions = /* @__PURE__ */ new Map();
339
- for (const statement of sourceFile.statements) {
340
- if (!ts.isImportDeclaration(statement)) continue;
341
- const source = getModuleSpecifierValue(statement);
342
- if (!source) continue;
343
- if (source === "@rpcbase/db") {
344
- const {
345
- rewriteText,
346
- remainingValueLocals
347
- } = rewriteRpcbaseDbImport(statement, forbiddenIdentifiers);
348
- if (!rewriteText) importActions.set(statement, {
349
- type: "remove"
350
- });
351
- else importActions.set(statement, {
352
- type: "overwrite",
353
- text: rewriteText,
354
- remainingValueLocals
355
- });
356
- continue;
357
- }
358
- if (!isForbiddenModuleSource(source)) continue;
359
- getImportValueLocals(statement).forEach((local) => forbiddenIdentifiers.add(local));
360
- importActions.set(statement, {
361
- type: "remove"
362
- });
363
- }
364
- let changed = true;
365
- const statementsToRemove = /* @__PURE__ */ new Set();
366
- while (changed) {
367
- changed = false;
368
- for (const statement of sourceFile.statements) {
369
- if (ts.isImportDeclaration(statement)) continue;
370
- if (statementsToRemove.has(statement)) continue;
371
- if (!referencesForbiddenRuntime(statement, forbiddenIdentifiers)) continue;
372
- getTopLevelBindings(statement).forEach((name) => forbiddenIdentifiers.add(name));
373
- statementsToRemove.add(statement);
374
- changed = true;
375
- }
376
- }
377
- const usedRuntimeIdentifiers = /* @__PURE__ */ new Set();
378
- for (const statement of sourceFile.statements) {
379
- if (ts.isImportDeclaration(statement)) continue;
380
- if (statementsToRemove.has(statement)) continue;
381
- collectRuntimeIdentifierReferences(statement, usedRuntimeIdentifiers);
382
- }
383
- for (const statement of sourceFile.statements) {
384
- if (!ts.isImportDeclaration(statement)) continue;
385
- const currentAction = importActions.get(statement);
386
- if (currentAction?.type === "remove") continue;
387
- const remainingValueLocals = currentAction?.type === "overwrite" ? currentAction.remainingValueLocals : getImportValueLocals(statement);
388
- if (remainingValueLocals.length === 0) continue;
389
- if (remainingValueLocals.some((local) => usedRuntimeIdentifiers.has(local))) continue;
390
- importActions.set(statement, {
391
- type: "remove"
392
- });
393
- }
394
- const s = new MagicString(code);
395
- for (const [importDeclaration, action] of importActions) {
396
- if (action.type === "remove") {
397
- s.remove(importDeclaration.pos, importDeclaration.end);
398
- continue;
399
- }
400
- const start = importDeclaration.getStart(sourceFile);
401
- s.overwrite(start, importDeclaration.end, action.text);
402
- }
403
- for (const statement of statementsToRemove) {
404
- s.remove(statement.pos, statement.end);
405
- }
406
- if (!s.hasChanged()) return null;
407
- const map = JSON.parse(s.generateMap({
408
- hires: true,
409
- includeContent: true,
410
- source: filePath,
411
- file: filePath
412
- }).toString());
413
- map.file = filePath;
414
- map.sources = [filePath];
415
- return {
416
- code: s.toString(),
417
- map: JSON.stringify(map)
418
- };
419
- };
299
+ return ({ code, filePath }) => {
300
+ const forbiddenIdentifiers = /* @__PURE__ */ new Set();
301
+ const scriptKind = scriptKindFromFilePath(filePath);
302
+ const sourceFile = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true, scriptKind);
303
+ const importActions = /* @__PURE__ */ new Map();
304
+ for (const statement of sourceFile.statements) {
305
+ if (!ts.isImportDeclaration(statement)) continue;
306
+ const source = getModuleSpecifierValue(statement);
307
+ if (!source) continue;
308
+ if (source === "@rpcbase/db") {
309
+ const { rewriteText, remainingValueLocals } = rewriteRpcbaseDbImport(statement, forbiddenIdentifiers);
310
+ if (!rewriteText) importActions.set(statement, { type: "remove" });
311
+ else importActions.set(statement, {
312
+ type: "overwrite",
313
+ text: rewriteText,
314
+ remainingValueLocals
315
+ });
316
+ continue;
317
+ }
318
+ if (!isForbiddenModuleSource(source)) continue;
319
+ getImportValueLocals(statement).forEach((local) => forbiddenIdentifiers.add(local));
320
+ importActions.set(statement, { type: "remove" });
321
+ }
322
+ let changed = true;
323
+ const statementsToRemove = /* @__PURE__ */ new Set();
324
+ while (changed) {
325
+ changed = false;
326
+ for (const statement of sourceFile.statements) {
327
+ if (ts.isImportDeclaration(statement)) continue;
328
+ if (statementsToRemove.has(statement)) continue;
329
+ if (!referencesForbiddenRuntime(statement, forbiddenIdentifiers)) continue;
330
+ getTopLevelBindings(statement).forEach((name) => forbiddenIdentifiers.add(name));
331
+ statementsToRemove.add(statement);
332
+ changed = true;
333
+ }
334
+ }
335
+ const usedRuntimeIdentifiers = /* @__PURE__ */ new Set();
336
+ for (const statement of sourceFile.statements) {
337
+ if (ts.isImportDeclaration(statement)) continue;
338
+ if (statementsToRemove.has(statement)) continue;
339
+ collectRuntimeIdentifierReferences(statement, usedRuntimeIdentifiers);
340
+ }
341
+ for (const statement of sourceFile.statements) {
342
+ if (!ts.isImportDeclaration(statement)) continue;
343
+ const currentAction = importActions.get(statement);
344
+ if (currentAction?.type === "remove") continue;
345
+ const remainingValueLocals = currentAction?.type === "overwrite" ? currentAction.remainingValueLocals : getImportValueLocals(statement);
346
+ if (remainingValueLocals.length === 0) continue;
347
+ if (remainingValueLocals.some((local) => usedRuntimeIdentifiers.has(local))) continue;
348
+ importActions.set(statement, { type: "remove" });
349
+ }
350
+ const s = new MagicString(code);
351
+ for (const [importDeclaration, action] of importActions) {
352
+ if (action.type === "remove") {
353
+ s.remove(importDeclaration.pos, importDeclaration.end);
354
+ continue;
355
+ }
356
+ const start = importDeclaration.getStart(sourceFile);
357
+ s.overwrite(start, importDeclaration.end, action.text);
358
+ }
359
+ for (const statement of statementsToRemove) s.remove(statement.pos, statement.end);
360
+ if (!s.hasChanged()) return null;
361
+ const map = JSON.parse(s.generateMap({
362
+ hires: true,
363
+ includeContent: true,
364
+ source: filePath,
365
+ file: filePath
366
+ }).toString());
367
+ map.file = filePath;
368
+ map.sources = [filePath];
369
+ return {
370
+ code: s.toString(),
371
+ map: JSON.stringify(map)
372
+ };
373
+ };
420
374
  }
375
+ //#endregion
376
+ //#region src/plugins/prune-models-for-client/index.ts
421
377
  function inferIsSsrTransform(transformOptions) {
422
- if (typeof transformOptions === "boolean") return transformOptions;
423
- if (!transformOptions || typeof transformOptions !== "object") return false;
424
- return transformOptions.ssr === true;
378
+ if (typeof transformOptions === "boolean") return transformOptions;
379
+ if (!transformOptions || typeof transformOptions !== "object") return false;
380
+ return transformOptions.ssr === true;
425
381
  }
426
382
  function isPrunableModelsFilePath(filePath) {
427
- const normalized = filePath.replaceAll("\\", "/");
428
- const parts = normalized.split("/");
429
- if (parts.includes("node_modules")) return false;
430
- if (parts.length < 2) return false;
431
- if (!parts.some((part, index) => part === "models" && index < parts.length - 1)) return false;
432
- if (normalized.endsWith(".d.ts")) return false;
433
- const ext = path$1.posix.extname(normalized);
434
- return ext === ".ts" || ext === ".tsx";
383
+ const normalized = filePath.replaceAll("\\", "/");
384
+ const parts = normalized.split("/");
385
+ if (parts.includes("node_modules")) return false;
386
+ if (parts.length < 2) return false;
387
+ if (!parts.some((part, index) => part === "models" && index < parts.length - 1)) return false;
388
+ if (normalized.endsWith(".d.ts")) return false;
389
+ const ext = path$1.posix.extname(normalized);
390
+ return ext === ".ts" || ext === ".tsx";
435
391
  }
436
392
  function pruneModelsForClientPlugin() {
437
- const prune = createTransformSource();
438
- return {
439
- name: "lz-models-prune-for-browser",
440
- enforce: "pre",
441
- transform(code, id, transformOptions) {
442
- if (inferIsSsrTransform(transformOptions)) return;
443
- const filePath = id.split("?", 1)[0] ?? id;
444
- if (!isPrunableModelsFilePath(filePath)) return;
445
- const result = prune({
446
- code,
447
- filePath
448
- });
449
- if (!result) return;
450
- return result;
451
- }
452
- };
393
+ const prune = createTransformSource();
394
+ return {
395
+ name: "lz-models-prune-for-browser",
396
+ enforce: "pre",
397
+ transform(code, id, transformOptions) {
398
+ if (inferIsSsrTransform(transformOptions)) return;
399
+ const filePath = id.split("?", 1)[0] ?? id;
400
+ if (!isPrunableModelsFilePath(filePath)) return;
401
+ const result = prune({
402
+ code,
403
+ filePath
404
+ });
405
+ if (!result) return;
406
+ return result;
407
+ }
408
+ };
453
409
  }
454
- const toPosixPath = (p) => p.split(path$1.sep).join("/");
455
- const computeInputs = (args) => {
456
- const {
457
- root,
458
- pattern,
459
- specDir
460
- } = args;
461
- const specDirAbs = path$1.resolve(root, specDir);
462
- const filesAbs = globSync(pattern, {
463
- cwd: root,
464
- absolute: true,
465
- nodir: true
466
- });
467
- const inputs = {};
468
- for (const fileAbs of filesAbs) {
469
- const relFromSpec = path$1.relative(specDirAbs, fileAbs);
470
- const outputName = toPosixPath(relFromSpec).replace(/\.ts$/, "");
471
- inputs[outputName] = fileAbs;
472
- }
473
- return inputs;
410
+ //#endregion
411
+ //#region src/plugins/spec-inputs/index.ts
412
+ var toPosixPath = (p) => p.split(path$1.sep).join("/");
413
+ var computeInputs = (args) => {
414
+ const { root, pattern, specDir } = args;
415
+ const specDirAbs = path$1.resolve(root, specDir);
416
+ const filesAbs = globSync(pattern, {
417
+ cwd: root,
418
+ absolute: true,
419
+ nodir: true
420
+ });
421
+ const inputs = {};
422
+ for (const fileAbs of filesAbs) {
423
+ const outputName = toPosixPath(path$1.relative(specDirAbs, fileAbs)).replace(/\.ts$/, "");
424
+ inputs[outputName] = fileAbs;
425
+ }
426
+ return inputs;
474
427
  };
475
- const inputsKey = (inputs) => Object.keys(inputs).sort().join("\n");
476
- const hasRollupInput = (input) => {
477
- if (!input) return false;
478
- if (typeof input === "string") return true;
479
- if (Array.isArray(input)) return input.length > 0;
480
- if (typeof input === "object") return Object.keys(input).length > 0;
481
- return false;
428
+ var inputsKey = (inputs) => Object.keys(inputs).sort().join("\n");
429
+ var hasRollupInput = (input) => {
430
+ if (!input) return false;
431
+ if (typeof input === "string") return true;
432
+ if (Array.isArray(input)) return input.length > 0;
433
+ if (typeof input === "object") return Object.keys(input).length > 0;
434
+ return false;
482
435
  };
483
436
  function specInputsPlugin(opts = {}) {
484
- const {
485
- pattern = "spec/**/*.spec{,.desktop,.mobile}.ts",
486
- specDir = "spec"
487
- } = opts;
488
- let rootAbs;
489
- let specDirAbs;
490
- let outDirAbs;
491
- let active = false;
492
- let inputsDirty = true;
493
- let currentInputs;
494
- let lastInputsKey;
495
- return {
496
- name: "rb-spec-inputs",
497
- apply: "build",
498
- configResolved(config) {
499
- rootAbs = config.root;
500
- specDirAbs = path$1.resolve(rootAbs, specDir);
501
- outDirAbs = path$1.resolve(rootAbs, config.build.outDir);
502
- },
503
- options(inputOptions) {
504
- if (!rootAbs) return;
505
- active = !hasRollupInput(inputOptions.input);
506
- if (!active) return;
507
- if (!currentInputs || inputsDirty) {
508
- currentInputs = computeInputs({
509
- root: rootAbs,
510
- pattern,
511
- specDir
512
- });
513
- inputsDirty = false;
514
- }
515
- inputOptions.input = currentInputs;
516
- return inputOptions;
517
- },
518
- watchChange(id, change) {
519
- if (!active) return;
520
- if (!rootAbs || !specDirAbs) return;
521
- const absId = path$1.isAbsolute(id) ? id : path$1.resolve(rootAbs, id);
522
- if (absId === specDirAbs) {
523
- inputsDirty = true;
524
- return;
525
- }
526
- if (!absId.startsWith(specDirAbs + path$1.sep)) return;
527
- if (!/\.spec(?:\.(?:desktop|mobile))?\.ts$/.test(absId)) return;
528
- if (change.event === "create" || change.event === "delete") {
529
- inputsDirty = true;
530
- }
531
- if (change.event === "update") {
532
- const relFromSpec = path$1.relative(specDirAbs, absId);
533
- const outputName = toPosixPath(relFromSpec).replace(/\.ts$/, "");
534
- if (!currentInputs || currentInputs[outputName] !== absId) {
535
- inputsDirty = true;
536
- }
537
- }
538
- },
539
- buildStart() {
540
- if (!active) return;
541
- if (!specDirAbs) return;
542
- this.addWatchFile(specDirAbs);
543
- if (!outDirAbs || !currentInputs) return;
544
- const key = inputsKey(currentInputs);
545
- if (lastInputsKey && lastInputsKey !== key) {
546
- fs.rmSync(outDirAbs, {
547
- recursive: true,
548
- force: true
549
- });
550
- }
551
- lastInputsKey = key;
552
- }
553
- };
437
+ const { pattern = "spec/**/*.spec{,.desktop,.mobile}.ts", specDir = "spec" } = opts;
438
+ let rootAbs;
439
+ let specDirAbs;
440
+ let outDirAbs;
441
+ let active = false;
442
+ let inputsDirty = true;
443
+ let currentInputs;
444
+ let lastInputsKey;
445
+ return {
446
+ name: "rb-spec-inputs",
447
+ apply: "build",
448
+ configResolved(config) {
449
+ const root = config.root;
450
+ rootAbs = root;
451
+ specDirAbs = path$1.resolve(root, specDir);
452
+ outDirAbs = path$1.resolve(root, config.build.outDir);
453
+ },
454
+ options(inputOptions) {
455
+ if (!rootAbs) return;
456
+ active = !hasRollupInput(inputOptions.input);
457
+ if (!active) return;
458
+ if (!currentInputs || inputsDirty) {
459
+ currentInputs = computeInputs({
460
+ root: rootAbs,
461
+ pattern,
462
+ specDir
463
+ });
464
+ inputsDirty = false;
465
+ }
466
+ inputOptions.input = currentInputs;
467
+ return inputOptions;
468
+ },
469
+ watchChange(id, change) {
470
+ if (!active) return;
471
+ if (!rootAbs || !specDirAbs) return;
472
+ const absId = path$1.isAbsolute(id) ? id : path$1.resolve(rootAbs, id);
473
+ if (absId === specDirAbs) {
474
+ inputsDirty = true;
475
+ return;
476
+ }
477
+ if (!absId.startsWith(specDirAbs + path$1.sep)) return;
478
+ if (!/\.spec(?:\.(?:desktop|mobile))?\.ts$/.test(absId)) return;
479
+ if (change.event === "create" || change.event === "delete") inputsDirty = true;
480
+ if (change.event === "update") {
481
+ const outputName = toPosixPath(path$1.relative(specDirAbs, absId)).replace(/\.ts$/, "");
482
+ if (!currentInputs || currentInputs[outputName] !== absId) inputsDirty = true;
483
+ }
484
+ },
485
+ buildStart() {
486
+ if (!active) return;
487
+ if (!specDirAbs) return;
488
+ this.addWatchFile(specDirAbs);
489
+ if (!outDirAbs || !currentInputs) return;
490
+ const key = inputsKey(currentInputs);
491
+ if (lastInputsKey && lastInputsKey !== key) fs.rmSync(outDirAbs, {
492
+ recursive: true,
493
+ force: true
494
+ });
495
+ lastInputsKey = key;
496
+ }
497
+ };
554
498
  }
555
- const shouldAnalyze = process.env.ANALYZE === "1";
556
- const ensureEnvPolyfillInjectPath = () => {
557
- const injectDir = path.resolve(process.cwd(), "node_modules/.rpcbase");
558
- const injectPath = path.join(injectDir, "rb-env-polyfill-inject.js");
559
- const injectContents = 'import "@rpcbase/env/polyfill"\n';
560
- fs.mkdirSync(injectDir, {
561
- recursive: true
562
- });
563
- try {
564
- const existing = fs.readFileSync(injectPath, "utf8");
565
- if (existing === injectContents) {
566
- return injectPath;
567
- }
568
- } catch {
569
- }
570
- fs.writeFileSync(injectPath, injectContents, "utf8");
571
- return injectPath;
499
+ //#endregion
500
+ //#region src/index.ts
501
+ var shouldAnalyze = process.env.ANALYZE === "1";
502
+ var isCI = [
503
+ "true",
504
+ "yes",
505
+ "1"
506
+ ].includes(process.env.CI?.trim());
507
+ var isProduction = process.env.NODE_ENV === "production";
508
+ var ALLOWED_ENV_PREFIXES = ["RB_PUBLIC_", ...isProduction ? [] : ["NODE_ENV", "APP_NAME"]];
509
+ var resolveAliases = {
510
+ "@/api": path.resolve(process.cwd(), "./src/api/"),
511
+ "@/models": path.resolve(process.cwd(), "./src/models/"),
512
+ "@/shared": path.resolve(process.cwd(), "./src/shared/"),
513
+ "@/types": path.resolve(process.cwd(), "./src/types/"),
514
+ "@": path.resolve(process.cwd(), "./src/client/")
572
515
  };
573
- const esbuildInjectPath = ensureEnvPolyfillInjectPath();
574
- const esbuildInject = [esbuildInjectPath];
575
- const esbuildInjectPlugins = [{
576
- name: "rb-env-polyfill-inject",
577
- setup(build) {
578
- build.onResolve({
579
- filter: /.*/
580
- }, (args) => {
581
- if (args.path === esbuildInjectPath) {
582
- return {
583
- path: esbuildInjectPath,
584
- namespace: "file"
585
- };
586
- }
587
- return void 0;
588
- });
589
- }
590
- }];
591
- const isCI = ["true", "yes", "1"].includes(process.env.CI?.trim());
592
- const isProduction = process.env.NODE_ENV === "production";
593
- const ALLOWED_DEV_ENV = ["NODE_ENV", "APP_NAME"];
594
- const ALLOWED_ENV_PREFIXES = ["RB_PUBLIC_", ...isProduction ? [] : ALLOWED_DEV_ENV];
595
- const htmlMinifyOptions = {
596
- collapseWhitespace: true,
597
- keepClosingSlash: true,
598
- removeComments: false,
599
- removeRedundantAttributes: true,
600
- removeScriptTypeAttributes: true,
601
- removeStyleLinkTypeAttributes: true,
602
- useShortDoctype: true,
603
- minifyCSS: true
604
- };
605
- const resolveAliases = {
606
- "@/api": path.resolve(process.cwd(), "./src/api/"),
607
- "@/models": path.resolve(process.cwd(), "./src/models/"),
608
- "@/shared": path.resolve(process.cwd(), "./src/shared/"),
609
- "@/types": path.resolve(process.cwd(), "./src/types/"),
610
- "@": path.resolve(process.cwd(), "./src/client/")
611
- };
612
- const integratedPackages = ["@hookform/resolvers", "axios", "events", "libphonenumber-js", "posthog-js", "posthog-js/react", "posthog-node", "react-router", "react-hook-form"];
613
- integratedPackages.forEach((pkg) => {
614
- const resolved = resolveIntegratedPackagePath(pkg);
615
- resolveAliases[pkg] = resolved;
516
+ [
517
+ "@hookform/resolvers",
518
+ "axios",
519
+ "events",
520
+ "libphonenumber-js",
521
+ "posthog-js",
522
+ "posthog-js/react",
523
+ "posthog-node",
524
+ "react-router",
525
+ "react-hook-form"
526
+ ].forEach((pkg) => {
527
+ resolveAliases[pkg] = resolveIntegratedPackagePath(pkg);
616
528
  });
617
529
  resolveAliases["node:events"] = resolveIntegratedPackagePath("events");
618
- const posthogReactEsm = resolveIntegratedPackagePath("posthog-js/react/dist/esm/index.js");
530
+ var posthogReactEsm = resolveIntegratedPackagePath("posthog-js/react/dist/esm/index.js");
619
531
  resolveAliases["posthog-js/react"] = posthogReactEsm;
620
532
  resolveAliases["posthog-js/react/dist/esm/index.js"] = posthogReactEsm;
621
- const rbPackagesNeedingEnvPolyfill = [
622
- "@rpcbase/auth",
623
- "@rpcbase/env",
624
- // "@rpcbase/env/polyfill",
625
- "@rpcbase/client",
626
- "@rpcbase/form",
627
- "@rpcbase/router"
533
+ var rbPackagesNeedingEnvPolyfill = [
534
+ "@rpcbase/auth",
535
+ "@rpcbase/env",
536
+ "@rpcbase/client",
537
+ "@rpcbase/form",
538
+ "@rpcbase/router"
628
539
  ];
629
- const rbSsrNoExternalPackages = [...rbPackagesNeedingEnvPolyfill, "@rpcbase/server"];
630
- const rpcbaseDedupePackages = ["@rpcbase/api", "@rpcbase/auth", "@rpcbase/client", "@rpcbase/db", "@rpcbase/debug", "@rpcbase/env", "@rpcbase/form", "@rpcbase/router", "@rpcbase/server", "@rpcbase/ui", "@rpcbase/worker"];
631
- const createRuntimeEnv = (args) => {
632
- const {
633
- env,
634
- configEnv
635
- } = args;
636
- const {
637
- command,
638
- mode,
639
- isSsrBuild
640
- } = configEnv;
641
- const isDevCommand = command === "serve";
642
- const mergedEnv = {
643
- ...env
644
- };
645
- return {
646
- ...mergedEnv,
647
- BASE_URL: mergedEnv.BASE_URL ?? "/",
648
- MODE: mode,
649
- DEV: isDevCommand,
650
- PROD: !isDevCommand,
651
- SSR: Boolean(isSsrBuild)
652
- };
540
+ var rbSsrNoExternalPackages = [...rbPackagesNeedingEnvPolyfill, "@rpcbase/server"];
541
+ var normalizePath = (id) => id.replaceAll("\\", "/");
542
+ var isRbPackageNeedingEnvPolyfillPath = (id) => {
543
+ const normalizedId = normalizePath(id);
544
+ return rbPackagesNeedingEnvPolyfill.some((pkg) => {
545
+ const packageName = pkg.slice(9);
546
+ return normalizedId.includes(`/node_modules/${pkg}/`) || normalizedId.includes(`/pkg/${packageName}/`);
547
+ });
548
+ };
549
+ var isRbEnvPolyfillPath = (id) => {
550
+ const normalizedId = normalizePath(id);
551
+ return normalizedId.includes("/@rpcbase/env/polyfill") || normalizedId.includes("/pkg/env/") && /\/polyfill(?:\.node)?\.[cm]?[jt]s$/.test(normalizedId);
653
552
  };
654
- const getBaseConfig = (configEnv) => {
655
- const {
656
- mode
657
- } = configEnv;
658
- const env = loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES);
659
- const runtimeEnv = createRuntimeEnv({
660
- env,
661
- configEnv
662
- });
663
- return {
664
- clearScreen: false,
665
- plugins: [pruneModelsForClientPlugin(), react({
666
- babel: {
667
- plugins: [["babel-plugin-react-compiler", {
668
- target: "19"
669
- }]]
670
- }
671
- }), createHtmlPlugin({
672
- // IMPORTANT: minify removes comments by default, which are used by the app ssr
673
- minify: htmlMinifyOptions
674
- }), viteSingleFile({
675
- useRecommendedBuildConfig: false,
676
- deleteInlinedFiles: true,
677
- inlinePattern: ["**/*.css"],
678
- removeViteModuleLoader: false
679
- }), isProduction && isCI && posthogSourcemapsPlugin({}), shouldAnalyze && analyzer()].filter(Boolean),
680
- define: {
681
- __vite_env__: runtimeEnv
682
- },
683
- envPrefix: ALLOWED_ENV_PREFIXES,
684
- publicDir: path.join(process.cwd(), "./src/client/public"),
685
- build: {
686
- sourcemap: isProduction ? "hidden" : false,
687
- cssCodeSplit: false,
688
- outDir: "./build/dist/",
689
- rollupOptions: {
690
- input: {
691
- app: "./src/client/index.html"
692
- }
693
- },
694
- commonjsOptions: {
695
- transformMixedEsModules: true
696
- }
697
- },
698
- server: {
699
- allowedHosts: true,
700
- headers: {
701
- // "X-Custom-Header": "test-custom",
702
- },
703
- watch: {
704
- ignored: ["**/build/playwright/**"]
705
- }
706
- },
707
- resolve: {
708
- alias: {
709
- ...resolveAliases
710
- },
711
- dedupe: ["react", "react-dom", "react-router", "react-hook-form", ...rpcbaseDedupePackages],
712
- preserveSymlinks: true
713
- },
714
- ssr: {
715
- external: [
716
- // "react", "react-dom",
717
- "cookie",
718
- "mongoose",
719
- "mongodb"
720
- ],
721
- noExternal: [
722
- ...rbSsrNoExternalPackages
723
- // "react-use",
724
- ]
725
- },
726
- optimizeDeps: {
727
- include: [
728
- // Force RPC Base packages through esbuild so rb-env-polyfill injects before their dist code touches globalThis.__rb_env__
729
- ...rbPackagesNeedingEnvPolyfill,
730
- "hoist-non-react-statics"
731
- // "react", "react-dom", "react-dom/server"
732
- // "cookie"
733
- ],
734
- exclude: [
735
- "@radix-ui/*",
736
- "@rpcbase/ui"
737
- // TMP only in sample app?
738
- // "react", "react-dom/server",
739
- // "react-hook-form",
740
- // "react-dom"
741
- ],
742
- esbuildOptions: {
743
- inject: esbuildInject,
744
- plugins: esbuildInjectPlugins
745
- }
746
- }
747
- // future: {
748
- // removeSsrLoadModule: true
749
- // },
750
- };
553
+ var rbEnvPolyfillOptimizeDepsPlugin = () => ({
554
+ name: "rb-env-polyfill-optimize-deps",
555
+ transform(code, id) {
556
+ if (!isRbPackageNeedingEnvPolyfillPath(id)) return null;
557
+ if (isRbEnvPolyfillPath(id)) return null;
558
+ if (!code.includes("__rb_env__") && !code.includes("globalThis.__rb_env__")) return null;
559
+ if (code.includes("\"@rpcbase/env/polyfill\"")) return null;
560
+ return {
561
+ code: `import "@rpcbase/env/polyfill"\n${code}`,
562
+ map: null
563
+ };
564
+ }
565
+ });
566
+ var rpcbaseDedupePackages = [
567
+ "@rpcbase/api",
568
+ "@rpcbase/auth",
569
+ "@rpcbase/client",
570
+ "@rpcbase/db",
571
+ "@rpcbase/debug",
572
+ "@rpcbase/env",
573
+ "@rpcbase/form",
574
+ "@rpcbase/router",
575
+ "@rpcbase/server",
576
+ "@rpcbase/ui",
577
+ "@rpcbase/worker"
578
+ ];
579
+ var createRuntimeEnv = (args) => {
580
+ const { env, configEnv } = args;
581
+ const { command, mode, isSsrBuild } = configEnv;
582
+ const isDevCommand = command === "serve";
583
+ const mergedEnv = { ...env };
584
+ return {
585
+ ...mergedEnv,
586
+ BASE_URL: mergedEnv.BASE_URL ?? "/",
587
+ MODE: mode,
588
+ DEV: isDevCommand,
589
+ PROD: !isDevCommand,
590
+ SSR: Boolean(isSsrBuild)
591
+ };
751
592
  };
752
- const extendConfig = (userConfig) => {
753
- return async (configEnv) => {
754
- const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
755
- const baseConfig = getBaseConfig(configEnv);
756
- return mergeConfig(baseConfig, config);
757
- };
593
+ var getBaseConfig = (configEnv) => {
594
+ const { mode } = configEnv;
595
+ const runtimeEnv = createRuntimeEnv({
596
+ env: loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES),
597
+ configEnv
598
+ });
599
+ return {
600
+ clearScreen: false,
601
+ plugins: [
602
+ pruneModelsForClientPlugin(),
603
+ react(),
604
+ babel({ presets: [reactCompilerPreset()] }),
605
+ viteSingleFile({
606
+ useRecommendedBuildConfig: false,
607
+ deleteInlinedFiles: true,
608
+ inlinePattern: ["**/*.css"],
609
+ removeViteModuleLoader: false
610
+ }),
611
+ isProduction && isCI && posthogSourcemapsPlugin({}),
612
+ shouldAnalyze && analyzer()
613
+ ].filter(Boolean),
614
+ define: { __vite_env__: runtimeEnv },
615
+ envPrefix: ALLOWED_ENV_PREFIXES,
616
+ publicDir: path.join(process.cwd(), "./src/client/public"),
617
+ build: {
618
+ sourcemap: isProduction ? "hidden" : false,
619
+ cssCodeSplit: false,
620
+ outDir: "./build/dist/",
621
+ rollupOptions: { input: { app: "./src/client/index.html" } },
622
+ commonjsOptions: { transformMixedEsModules: true }
623
+ },
624
+ server: {
625
+ allowedHosts: true,
626
+ headers: {},
627
+ watch: { ignored: ["**/build/playwright/**"] }
628
+ },
629
+ resolve: {
630
+ alias: { ...resolveAliases },
631
+ dedupe: [
632
+ "react",
633
+ "react-dom",
634
+ "react-router",
635
+ "react-hook-form",
636
+ ...rpcbaseDedupePackages
637
+ ],
638
+ preserveSymlinks: true
639
+ },
640
+ ssr: {
641
+ external: [
642
+ "cookie",
643
+ "mongoose",
644
+ "mongodb"
645
+ ],
646
+ noExternal: [...rbSsrNoExternalPackages]
647
+ },
648
+ optimizeDeps: {
649
+ include: [...rbPackagesNeedingEnvPolyfill, "hoist-non-react-statics"],
650
+ exclude: ["@radix-ui/*", "@rpcbase/ui"],
651
+ rolldownOptions: { plugins: [rbEnvPolyfillOptimizeDepsPlugin()] }
652
+ }
653
+ };
758
654
  };
759
- const getSpecBaseConfig = (configEnv) => {
760
- const {
761
- mode
762
- } = configEnv;
763
- const env = loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES);
764
- const runtimeEnv = createRuntimeEnv({
765
- env,
766
- configEnv
767
- });
768
- return {
769
- clearScreen: false,
770
- define: {
771
- __vite_env__: runtimeEnv
772
- },
773
- envPrefix: ALLOWED_ENV_PREFIXES,
774
- plugins: [specInputsPlugin()],
775
- build: {
776
- outDir: "./build/spec/",
777
- ssr: true,
778
- rollupOptions: {
779
- input: {}
780
- },
781
- commonjsOptions: {
782
- transformMixedEsModules: true
783
- }
784
- },
785
- resolve: {
786
- alias: {
787
- ...resolveAliases
788
- },
789
- dedupe: ["react", "react-dom", "react-router", "react-hook-form", ...rpcbaseDedupePackages],
790
- preserveSymlinks: true
791
- },
792
- ssr: {
793
- external: ["mongoose"],
794
- noExternal: ["@rpcbase/*"]
795
- }
796
- };
655
+ var extendConfig = (userConfig) => {
656
+ return async (configEnv) => {
657
+ const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
658
+ return mergeConfig(getBaseConfig(configEnv), config);
659
+ };
797
660
  };
798
- const extendSpecConfig = (userConfig) => {
799
- return async (configEnv) => {
800
- const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
801
- const baseConfig = getSpecBaseConfig(configEnv);
802
- return mergeConfig(baseConfig, config);
803
- };
661
+ var getSpecBaseConfig = (configEnv) => {
662
+ const { mode } = configEnv;
663
+ return {
664
+ clearScreen: false,
665
+ define: { __vite_env__: createRuntimeEnv({
666
+ env: loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES),
667
+ configEnv
668
+ }) },
669
+ envPrefix: ALLOWED_ENV_PREFIXES,
670
+ plugins: [specInputsPlugin()],
671
+ build: {
672
+ outDir: "./build/spec/",
673
+ ssr: true,
674
+ rollupOptions: { input: {} },
675
+ commonjsOptions: { transformMixedEsModules: true }
676
+ },
677
+ resolve: {
678
+ alias: { ...resolveAliases },
679
+ dedupe: [
680
+ "react",
681
+ "react-dom",
682
+ "react-router",
683
+ "react-hook-form",
684
+ ...rpcbaseDedupePackages
685
+ ],
686
+ preserveSymlinks: true
687
+ },
688
+ ssr: {
689
+ external: ["mongoose"],
690
+ noExternal: ["@rpcbase/*"]
691
+ }
692
+ };
804
693
  };
805
- const createServer = createServer$1;
806
- export {
807
- createServer,
808
- extendConfig,
809
- extendSpecConfig,
810
- pruneModelsForClientPlugin,
811
- resolveAliases
694
+ var extendSpecConfig = (userConfig) => {
695
+ return async (configEnv) => {
696
+ const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
697
+ return mergeConfig(getSpecBaseConfig(configEnv), config);
698
+ };
812
699
  };
813
- //# sourceMappingURL=index.js.map
700
+ var createServer = createServer$1;
701
+ //#endregion
702
+ export { createServer, extendConfig, extendSpecConfig, pruneModelsForClientPlugin, resolveAliases };
703
+
704
+ //# sourceMappingURL=index.js.map