rwsdk 0.1.5 → 0.1.6-test.20250702132719

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.
Files changed (79) hide show
  1. package/dist/runtime/client.js +6 -1
  2. package/dist/runtime/clientNavigation.d.ts +1 -0
  3. package/dist/runtime/clientNavigation.js +34 -24
  4. package/dist/runtime/clientNavigation.test.js +55 -0
  5. package/dist/runtime/lib/realtime/client.js +6 -0
  6. package/dist/runtime/lib/realtime/durableObject.js +8 -3
  7. package/dist/runtime/lib/realtime/worker.js +1 -3
  8. package/dist/runtime/render/renderRscThenableToHtmlStream.d.ts +2 -1
  9. package/dist/runtime/render/renderRscThenableToHtmlStream.js +22 -1
  10. package/dist/runtime/render/renderToStream.js +2 -1
  11. package/dist/runtime/render/transformRscToHtmlStream.d.ts +2 -1
  12. package/dist/runtime/render/transformRscToHtmlStream.js +2 -1
  13. package/dist/runtime/worker.js +1 -0
  14. package/dist/vite/createDirectiveLookupPlugin.mjs +2 -1
  15. package/package.json +1 -1
  16. package/dist/lib/smokeTests/components.d.mts +0 -8
  17. package/dist/lib/smokeTests/components.mjs +0 -194
  18. package/dist/lib/smokeTests/templates/SmokeTestInfo.template.d.ts +0 -1
  19. package/dist/lib/smokeTests/templates/SmokeTestInfo.template.js +0 -82
  20. package/dist/runtime/components/HealthCheck.d.ts +0 -13
  21. package/dist/runtime/components/HealthCheck.js +0 -56
  22. package/dist/runtime/components/HealthCheckClient.d.ts +0 -2
  23. package/dist/runtime/components/HealthCheckClient.js +0 -78
  24. package/dist/runtime/imports/NoSSRStub.d.ts +0 -1
  25. package/dist/runtime/imports/NoSSRStub.js +0 -4
  26. package/dist/runtime/lib/db/create.d.ts +0 -3
  27. package/dist/runtime/lib/db/create.js +0 -36
  28. package/dist/runtime/lib/db/logger.d.ts +0 -2
  29. package/dist/runtime/lib/db/logger.js +0 -41
  30. package/dist/runtime/lib/db/types.d.ts +0 -0
  31. package/dist/runtime/lib/db/types.js +0 -1
  32. package/dist/runtime/render/__rwsdk_ssr_bridge.d.ts +0 -10
  33. package/dist/runtime/render/__rwsdk_ssr_bridge.js +0 -9
  34. package/dist/runtime/render/__rwsdkssr_render.d.ts +0 -9
  35. package/dist/runtime/render/__rwsdkssr_render.js +0 -13
  36. package/dist/runtime/render/injectRSCPayload.d.ts +0 -3
  37. package/dist/runtime/render/injectRSCPayload.js +0 -79
  38. package/dist/runtime/render/ssrBridge.d.ts +0 -2
  39. package/dist/runtime/render/ssrBridge.js +0 -2
  40. package/dist/runtime/render/ssrRenderToReadableStream.d.ts +0 -2
  41. package/dist/runtime/render/ssrRenderToReadableStream.js +0 -2
  42. package/dist/runtime/requestInfo/__rwsdknossr_worker.d.ts +0 -5
  43. package/dist/runtime/requestInfo/__rwsdknossr_worker.js +0 -33
  44. package/dist/scripts/build-vendor-bundles.d.mts +0 -1
  45. package/dist/scripts/build-vendor-bundles.mjs +0 -92
  46. package/dist/vite/aliasedModuleResolver.d.mts +0 -9
  47. package/dist/vite/aliasedModuleResolver.mjs +0 -62
  48. package/dist/vite/aliasedSSRResolver.d.mts +0 -5
  49. package/dist/vite/aliasedSSRResolver.mjs +0 -74
  50. package/dist/vite/copyPrismaWasmPlugin.d.mts +0 -4
  51. package/dist/vite/copyPrismaWasmPlugin.mjs +0 -32
  52. package/dist/vite/ensureConfigArrays.d.mts +0 -1
  53. package/dist/vite/ensureConfigArrays.mjs +0 -12
  54. package/dist/vite/findImportSpecifiers.d.mts +0 -30
  55. package/dist/vite/findImportSpecifiers.mjs +0 -228
  56. package/dist/vite/findImportSpecifiers.test.mjs +0 -73
  57. package/dist/vite/isBareImport.d.mts +0 -1
  58. package/dist/vite/isBareImport.mjs +0 -5
  59. package/dist/vite/miniflarePlugin.d.mts +0 -9
  60. package/dist/vite/miniflarePlugin.mjs +0 -135
  61. package/dist/vite/moduleResolver.d.mts +0 -10
  62. package/dist/vite/moduleResolver.mjs +0 -74
  63. package/dist/vite/resolveModuleId.d.mts +0 -6
  64. package/dist/vite/resolveModuleId.mjs +0 -14
  65. package/dist/vite/rscDirectivesPlugin.d.mts +0 -6
  66. package/dist/vite/rscDirectivesPlugin.mjs +0 -80
  67. package/dist/vite/transformServerReferences.d.mts +0 -11
  68. package/dist/vite/transformServerReferences.mjs +0 -74
  69. package/dist/vite/useClientPlugin.d.mts +0 -8
  70. package/dist/vite/useClientPlugin.mjs +0 -299
  71. package/dist/vite/useClientPlugin.test.d.mts +0 -1
  72. package/dist/vite/useClientPlugin.test.mjs +0 -1294
  73. package/dist/vite/useServerPlugin.test.d.mts +0 -1
  74. package/dist/vite/useServerPlugin.test.mjs +0 -99
  75. package/dist/vite/virtualizedSSRPlugin.d.mts +0 -56
  76. package/dist/vite/virtualizedSSRPlugin.mjs +0 -464
  77. package/dist/vite/wasmPlugin.d.mts +0 -2
  78. package/dist/vite/wasmPlugin.mjs +0 -14
  79. /package/dist/{vite/findImportSpecifiers.test.d.mts → runtime/clientNavigation.test.d.ts} +0 -0
@@ -1,74 +0,0 @@
1
- import path from "path";
2
- import enhancedResolve from "enhanced-resolve";
3
- import debug from "debug";
4
- const baseSSRResolver = enhancedResolve.create.sync({
5
- conditionNames: ["workerd", "edge", "import", "default"],
6
- });
7
- function applyAlias(request, aliasEntries, name) {
8
- if (!aliasEntries)
9
- return request;
10
- const logPrefix = `[${name}]`;
11
- // Support both array and object forms
12
- const entries = Array.isArray(aliasEntries)
13
- ? aliasEntries
14
- : Object.entries(aliasEntries).map(([find, replacement]) => ({
15
- find,
16
- replacement,
17
- }));
18
- for (const entry of entries) {
19
- const { find, replacement } = entry;
20
- if (typeof find === "string") {
21
- if (request === find || request.startsWith(find + "/")) {
22
- debug("rwsdk:vite:aliased-ssr-resolver")("%s [applyAlias] Matched string alias: '%s' -> '%s' for request '%s'", logPrefix, find, replacement, request);
23
- return replacement + request.slice(find.length);
24
- }
25
- }
26
- else if (find instanceof RegExp) {
27
- if (find.test(request)) {
28
- debug("rwsdk:vite:aliased-ssr-resolver")("%s [applyAlias] Matched RegExp alias: %O -> '%s' for request '%s'", logPrefix, find, replacement, request);
29
- return request.replace(find, replacement);
30
- }
31
- }
32
- }
33
- return request;
34
- }
35
- export function createAliasedSSRResolver({ getResolveConfig, roots, name = "aliasedSSRResolver", }) {
36
- const log = debug("rwsdk:vite:aliased-ssr-resolver");
37
- const logPrefix = `[${name}]`;
38
- return function resolveModule(request, importer) {
39
- log("%s Called with request: '%s', importer: '%s'", logPrefix, request, importer);
40
- let normalized = request;
41
- const resolveConfig = getResolveConfig?.() || {};
42
- const aliasEntries = resolveConfig.alias;
43
- log("%s Alias entries: %O", logPrefix, aliasEntries);
44
- normalized = applyAlias(normalized, aliasEntries, name);
45
- log("%s After aliasing: '%s'", logPrefix, normalized);
46
- let rootsToTry = roots && roots.length > 0 ? roots : [];
47
- // If leading slash, treat as first root-rooted (for compatibility)
48
- if (normalized.startsWith("/")) {
49
- if (rootsToTry.length > 0) {
50
- const rooted = path.join(rootsToTry[0], normalized);
51
- log("%s Leading slash detected, resolving as root[0]-rooted: '%s'", logPrefix, rooted);
52
- normalized = rooted;
53
- rootsToTry = [rootsToTry[0]];
54
- }
55
- }
56
- const isAbsolute = path.isAbsolute(normalized);
57
- if (isAbsolute) {
58
- log("%s Resolving absolute path: '%s'", logPrefix, normalized);
59
- return normalized;
60
- }
61
- for (const root of rootsToTry) {
62
- try {
63
- log("%s Trying root: '%s'", logPrefix, root);
64
- const result = baseSSRResolver(root, normalized);
65
- log("%s Resolved to: '%s' with root '%s'", logPrefix, result, root);
66
- return result;
67
- }
68
- catch (err) {
69
- log("%s Resolution failed for '%s' from root '%s': %O", logPrefix, normalized, root, err);
70
- }
71
- }
72
- return false;
73
- };
74
- }
@@ -1,4 +0,0 @@
1
- import { Plugin } from "vite";
2
- export declare const copyPrismaWasmPlugin: ({ rootDir, }: {
3
- rootDir: string;
4
- }) => Plugin;
@@ -1,32 +0,0 @@
1
- import { copy, pathExists } from "fs-extra";
2
- import { resolve } from "node:path";
3
- import MagicString from "magic-string";
4
- import path from "path";
5
- export const copyPrismaWasmPlugin = ({ rootDir, }) => ({
6
- name: "rwsdk:copy-prisma-wasm",
7
- enforce: "post",
8
- apply: "build",
9
- async writeBundle() {
10
- const wasmFilePath = resolve(rootDir, "node_modules/.prisma/client/query_engine_bg.wasm");
11
- const fileName = path.basename(wasmFilePath);
12
- const outputPath = path.resolve(rootDir, "dist", "worker", fileName);
13
- if (await pathExists(wasmFilePath)) {
14
- await copy(wasmFilePath, outputPath);
15
- console.log(`✅ Copied ${fileName} from ${wasmFilePath} to ${outputPath}`);
16
- }
17
- },
18
- renderChunk(code) {
19
- if (!code.includes(".wasm")) {
20
- return;
21
- }
22
- const s = new MagicString(code);
23
- s.replace(/import\(["'](.+?\.wasm)["']\)/g, (_, filePath) => {
24
- const fileName = path.basename(filePath);
25
- return `import("./${fileName}")`;
26
- });
27
- return {
28
- code: s.toString(),
29
- map: s.generateMap(),
30
- };
31
- },
32
- });
@@ -1 +0,0 @@
1
- export declare const ensureConfigArrays: (config: any) => void;
@@ -1,12 +0,0 @@
1
- export const ensureConfigArrays = (config) => {
2
- config.optimizeDeps ??= {};
3
- config.optimizeDeps.include ??= [];
4
- config.optimizeDeps.esbuildOptions ??= {};
5
- config.optimizeDeps.esbuildOptions.plugins ??= [];
6
- config.resolve ??= {};
7
- config.resolve.alias ??= [];
8
- if (!Array.isArray(config.resolve.alias)) {
9
- const aliasObj = config.resolve.alias;
10
- config.resolve.alias = Object.entries(aliasObj).map(([find, replacement]) => ({ find, replacement }));
11
- }
12
- };
@@ -1,30 +0,0 @@
1
- export declare const IMPORT_PATTERNS: string[];
2
- export declare const EXPORT_PATTERNS: string[];
3
- export interface ExportInfo {
4
- name: string;
5
- isDefault: boolean;
6
- alias?: string;
7
- isReExport?: boolean;
8
- moduleSpecifier?: string;
9
- }
10
- /**
11
- * Finds import specifiers and their positions in the code using the provided patterns.
12
- * @param code The code to search for import specifiers.
13
- * @param lang The language parser to use (TypeScript or Tsx).
14
- * @param ignoredImportPatterns Array of regex patterns to ignore.
15
- * @param log Optional logger function for debug output.
16
- * @returns Array of objects with start, end, and raw import string.
17
- */
18
- export declare function findImportSpecifiers(id: string, code: string, ignoredImportPatterns: RegExp[], log?: (...args: any[]) => void): Array<{
19
- s: number;
20
- e: number;
21
- raw: string;
22
- }>;
23
- /**
24
- * Finds export information in the code using ast-grep patterns.
25
- * @param id The file identifier for language detection.
26
- * @param code The code to search for exports.
27
- * @param log Optional logger function for debug output.
28
- * @returns Array of export information objects.
29
- */
30
- export declare function findExports(id: string, code: string, log?: (...args: any[]) => void): ExportInfo[];
@@ -1,228 +0,0 @@
1
- import { parse as sgParse, Lang as SgLang, Lang } from "@ast-grep/napi";
2
- import path from "path";
3
- // These patterns are used to match import statements in code for SSR transformations.
4
- export const IMPORT_PATTERNS = [
5
- 'import { $$$ } from "$MODULE"',
6
- "import { $$$ } from '$MODULE'",
7
- 'import $DEFAULT from "$MODULE"',
8
- "import $DEFAULT from '$MODULE'",
9
- 'import * as $NS from "$MODULE"',
10
- "import * as $NS from '$MODULE'",
11
- 'import "$MODULE"',
12
- "import '$MODULE'",
13
- // Static Re-exports
14
- 'export { $$$ } from "$MODULE"',
15
- "export { $$$ } from '$MODULE'",
16
- 'export * from "$MODULE"',
17
- "export * from '$MODULE'",
18
- // Dynamic Imports
19
- 'import("$MODULE")',
20
- "import('$MODULE')",
21
- "import(`$MODULE`)",
22
- // CommonJS require
23
- 'require("$MODULE")',
24
- "require('$MODULE')",
25
- "require(`$MODULE`)",
26
- ];
27
- // These patterns are used to match export statements for client/server component transformations
28
- export const EXPORT_PATTERNS = [
29
- // Named exports
30
- "export const $NAME = $$$",
31
- "export let $NAME = $$$",
32
- "export var $NAME = $$$",
33
- "export function $NAME($$$) { $$$ }",
34
- "export async function $NAME($$$) { $$$ }",
35
- // Default exports
36
- "export default function $NAME($$$) { $$$ }",
37
- "export default function($$$) { $$$ }",
38
- "export default $$$",
39
- // Export declarations
40
- "export { $$$ }",
41
- 'export { $$$ } from "$MODULE"',
42
- "export { $$$ } from '$MODULE'",
43
- ];
44
- /**
45
- * Finds import specifiers and their positions in the code using the provided patterns.
46
- * @param code The code to search for import specifiers.
47
- * @param lang The language parser to use (TypeScript or Tsx).
48
- * @param ignoredImportPatterns Array of regex patterns to ignore.
49
- * @param log Optional logger function for debug output.
50
- * @returns Array of objects with start, end, and raw import string.
51
- */
52
- export function findImportSpecifiers(id, code, ignoredImportPatterns, log) {
53
- const ext = path.extname(id).toLowerCase();
54
- const lang = ext === ".tsx" || ext === ".jsx" ? Lang.Tsx : SgLang.TypeScript;
55
- const logger = log ?? (() => { });
56
- const results = [];
57
- try {
58
- // sgParse and lang must be provided by the consumer
59
- const root = sgParse(lang, code);
60
- for (const pattern of IMPORT_PATTERNS) {
61
- try {
62
- const matches = root.root().findAll(pattern);
63
- for (const match of matches) {
64
- const moduleCapture = match.getMatch("MODULE");
65
- if (moduleCapture) {
66
- const importPath = moduleCapture.text();
67
- if (importPath.startsWith("virtual:")) {
68
- logger(":findImportSpecifiersWithPositions: Ignoring import because it starts with 'virtual:': importPath=%s", importPath);
69
- }
70
- else if (importPath.includes("__rwsdknossr")) {
71
- logger(":findImportSpecifiersWithPositions: Ignoring import because it includes '__rwsdknossr': importPath=%s", importPath);
72
- }
73
- else if (ignoredImportPatterns.some((pattern) => pattern.test(importPath))) {
74
- logger(":findImportSpecifiersWithPositions: Ignoring import because it matches IGNORED_IMPORT_PATTERNS: importPath=%s", importPath);
75
- }
76
- else {
77
- const { start, end } = moduleCapture.range();
78
- results.push({ s: start.index, e: end.index, raw: importPath });
79
- logger(":findImportSpecifiersWithPositions: Including import specifier: importPath=%s, range=[%d, %d]", importPath, start.index, end.index);
80
- }
81
- }
82
- }
83
- }
84
- catch (err) {
85
- logger(":findImportSpecifiersWithPositions: Error processing pattern: %O", err);
86
- }
87
- }
88
- }
89
- catch (err) {
90
- logger(":findImportSpecifiersWithPositions: Error parsing content: %O", err);
91
- }
92
- return results;
93
- }
94
- /**
95
- * Finds export information in the code using ast-grep patterns.
96
- * @param id The file identifier for language detection.
97
- * @param code The code to search for exports.
98
- * @param log Optional logger function for debug output.
99
- * @returns Array of export information objects.
100
- */
101
- export function findExports(id, code, log) {
102
- const ext = path.extname(id).toLowerCase();
103
- const lang = ext === ".tsx" || ext === ".jsx" ? Lang.Tsx : SgLang.TypeScript;
104
- const logger = log ?? (() => { });
105
- const results = [];
106
- const seen = new Set(); // Track seen exports to avoid duplicates
107
- try {
108
- const root = sgParse(lang, code);
109
- // Use the existing EXPORT_PATTERNS in a specific order to avoid duplicates
110
- const orderedPatterns = [
111
- // Handle re-exports first (most specific)
112
- ...EXPORT_PATTERNS.filter((p) => p.includes('from "$MODULE"') || p.includes("from '$MODULE'")),
113
- // Then named exports
114
- ...EXPORT_PATTERNS.filter((p) => p.startsWith("export const") ||
115
- p.startsWith("export let") ||
116
- p.startsWith("export var") ||
117
- p.startsWith("export function") ||
118
- p.startsWith("export async function")),
119
- // Then default exports
120
- ...EXPORT_PATTERNS.filter((p) => p.startsWith("export default")),
121
- // Finally export declarations
122
- ...EXPORT_PATTERNS.filter((p) => p === "export { $$$ }"),
123
- ];
124
- for (const pattern of orderedPatterns) {
125
- try {
126
- const matches = root.root().findAll(pattern);
127
- for (const match of matches) {
128
- const nameCapture = match.getMatch("NAME");
129
- const moduleCapture = match.getMatch("MODULE");
130
- const matchText = match.text();
131
- if (pattern.includes('from "$MODULE"') ||
132
- pattern.includes("from '$MODULE'")) {
133
- // Re-export from module
134
- const moduleSpecifier = moduleCapture?.text();
135
- if (!moduleSpecifier)
136
- continue;
137
- if (pattern.includes("export *")) {
138
- // Skip export * for now - too complex
139
- logger("Skipping export * from %s", moduleSpecifier);
140
- continue;
141
- }
142
- // Parse the export list
143
- const exportListMatch = matchText.match(/export\s*\{\s*([^}]+)\s*\}/);
144
- if (exportListMatch) {
145
- const exportList = exportListMatch[1];
146
- const exports = exportList.split(",").map((e) => e.trim());
147
- for (const exp of exports) {
148
- const [originalName, alias] = exp.includes(" as ")
149
- ? exp.split(" as ").map((s) => s.trim())
150
- : [exp.trim(), undefined];
151
- const exportName = alias || originalName;
152
- const key = `${exportName}:${originalName === "default"}:reexport:${moduleSpecifier}`;
153
- if (seen.has(key))
154
- continue;
155
- seen.add(key);
156
- results.push({
157
- name: exportName,
158
- isDefault: originalName === "default",
159
- alias: alias !== originalName ? alias : undefined,
160
- isReExport: true,
161
- moduleSpecifier,
162
- });
163
- logger("Found re-export: %s from %s", exportName, moduleSpecifier);
164
- }
165
- }
166
- }
167
- else if (matchText.startsWith("export default")) {
168
- // Default export
169
- const name = nameCapture?.text() || "default";
170
- const key = `${name}:true:default`;
171
- if (seen.has(key))
172
- continue;
173
- seen.add(key);
174
- results.push({
175
- name,
176
- isDefault: true,
177
- });
178
- logger("Found default export: %s", name);
179
- }
180
- else if (matchText.includes("export {")) {
181
- // Local export declaration
182
- const exportListMatch = matchText.match(/export\s*\{\s*([^}]+)\s*\}/);
183
- if (exportListMatch) {
184
- const exportList = exportListMatch[1];
185
- const exports = exportList.split(",").map((e) => e.trim());
186
- for (const exp of exports) {
187
- const [originalName, alias] = exp.includes(" as ")
188
- ? exp.split(" as ").map((s) => s.trim())
189
- : [exp.trim(), undefined];
190
- const exportName = alias || originalName;
191
- const key = `${exportName}:${originalName === "default"}:local`;
192
- if (seen.has(key))
193
- continue;
194
- seen.add(key);
195
- results.push({
196
- name: exportName,
197
- isDefault: originalName === "default",
198
- alias: alias !== originalName ? alias : undefined,
199
- });
200
- logger("Found local export: %s", exportName);
201
- }
202
- }
203
- }
204
- else if (nameCapture) {
205
- // Named export (function, const, etc.)
206
- const name = nameCapture.text();
207
- const key = `${name}:false:named`;
208
- if (seen.has(key))
209
- continue;
210
- seen.add(key);
211
- results.push({
212
- name,
213
- isDefault: false,
214
- });
215
- logger("Found named export: %s", name);
216
- }
217
- }
218
- }
219
- catch (err) {
220
- logger("Error processing export pattern %s: %O", pattern, err);
221
- }
222
- }
223
- }
224
- catch (err) {
225
- logger("Error parsing code for exports: %O", err);
226
- }
227
- return results;
228
- }
@@ -1,73 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { findExports } from "./findImportSpecifiers.mjs";
3
- describe("findExports", () => {
4
- it("finds named exports", () => {
5
- const code = `
6
- export const Component = () => {};
7
- export function helper() {}
8
- export let data = {};
9
- `;
10
- const exports = findExports("/test.tsx", code);
11
- // Just check that we found the exports, order doesn't matter for our use case
12
- const names = exports.map((e) => e.name).sort();
13
- expect(names).toEqual(["Component", "data", "helper"]);
14
- // Check that none are default
15
- expect(exports.every((e) => !e.isDefault)).toBe(true);
16
- });
17
- it("finds default exports", () => {
18
- const code = `
19
- export default function Component() {}
20
- `;
21
- const exports = findExports("/test.tsx", code);
22
- // Should find at least one default export
23
- const defaultExports = exports.filter((e) => e.isDefault);
24
- expect(defaultExports.length).toBeGreaterThan(0);
25
- expect(defaultExports.some((e) => e.name === "Component")).toBe(true);
26
- });
27
- it("finds export declarations", () => {
28
- const code = `
29
- const First = () => {};
30
- const Second = () => {};
31
- export { First, Second };
32
- `;
33
- const exports = findExports("/test.tsx", code);
34
- const names = exports.map((e) => e.name).sort();
35
- expect(names).toEqual(["First", "Second"]);
36
- });
37
- it("finds export declarations with aliases", () => {
38
- const code = `
39
- const Component = () => {};
40
- export { Component as MyComponent };
41
- `;
42
- const exports = findExports("/test.tsx", code);
43
- expect(exports.some((e) => e.name === "MyComponent")).toBe(true);
44
- });
45
- it("finds re-exports", () => {
46
- const code = `
47
- export { sum } from './math';
48
- export { default as multiply } from './multiply';
49
- `;
50
- const exports = findExports("/test.tsx", code);
51
- // Should find re-exports
52
- const reExports = exports.filter((e) => e.isReExport);
53
- expect(reExports.length).toBeGreaterThan(0);
54
- const names = reExports.map((e) => e.name).sort();
55
- expect(names).toContain("sum");
56
- expect(names).toContain("multiply");
57
- });
58
- it("handles mixed export styles", () => {
59
- const code = `
60
- export const First = () => {};
61
- const Second = () => {};
62
- export default function Main() {}
63
- export { Second };
64
- `;
65
- const exports = findExports("/test.tsx", code);
66
- const names = exports.map((e) => e.name);
67
- expect(names).toContain("First");
68
- expect(names).toContain("Second");
69
- // Should have at least one default export
70
- const defaultExports = exports.filter((e) => e.isDefault);
71
- expect(defaultExports.length).toBeGreaterThan(0);
72
- });
73
- });
@@ -1 +0,0 @@
1
- export declare function isBareImport(importPath: string): boolean;
@@ -1,5 +0,0 @@
1
- export function isBareImport(importPath) {
2
- return (!importPath.startsWith(".") &&
3
- !importPath.startsWith("/") &&
4
- !importPath.startsWith("virtual:"));
5
- }
@@ -1,9 +0,0 @@
1
- import { Plugin } from "vite";
2
- import { cloudflare } from "@cloudflare/vite-plugin";
3
- type BasePluginOptions = Parameters<typeof cloudflare>[0];
4
- type MiniflarePluginOptions = BasePluginOptions & {};
5
- export declare const miniflarePlugin: (givenOptions: MiniflarePluginOptions & {
6
- rootDir: string;
7
- workerEntryPathname: string;
8
- }) => (Plugin | Plugin[])[];
9
- export {};
@@ -1,135 +0,0 @@
1
- import { cloudflare } from "@cloudflare/vite-plugin";
2
- import { resolve } from "node:path";
3
- import colors from "picocolors";
4
- import { readFile } from "node:fs/promises";
5
- import { getShortName } from "../lib/getShortName.mjs";
6
- import { pathExists } from "fs-extra";
7
- const hasEntryAsAncestor = (module, entryFile, seen = new Set()) => {
8
- // Prevent infinite recursion
9
- if (seen.has(module))
10
- return false;
11
- seen.add(module);
12
- // Check direct importers
13
- for (const importer of module.importers) {
14
- if (importer.file === entryFile)
15
- return true;
16
- // Recursively check importers
17
- if (hasEntryAsAncestor(importer, entryFile, seen))
18
- return true;
19
- }
20
- return false;
21
- };
22
- // Cache for "use client" status results
23
- const useClientCache = new Map();
24
- // Function to invalidate cache for a file
25
- const invalidateUseClientCache = (file) => {
26
- useClientCache.delete(file);
27
- };
28
- const isUseClientModule = async (ctx, file, seen = new Set()) => {
29
- // Prevent infinite recursion
30
- if (seen.has(file))
31
- return false;
32
- seen.add(file);
33
- try {
34
- // Check cache first
35
- if (useClientCache.has(file)) {
36
- return useClientCache.get(file);
37
- }
38
- // Read and check the file
39
- const content = (await pathExists(file))
40
- ? await readFile(file, "utf-8")
41
- : "";
42
- const hasUseClient = content.includes("'use client'") || content.includes('"use client"');
43
- if (hasUseClient) {
44
- useClientCache.set(file, true);
45
- return true;
46
- }
47
- // Get the module from the module graph to find importers
48
- const module = ctx.server.moduleGraph.getModuleById(file);
49
- if (!module) {
50
- useClientCache.set(file, false);
51
- return false;
52
- }
53
- // Check all importers recursively
54
- for (const importer of module.importers) {
55
- if (await isUseClientModule(ctx, importer.url, seen)) {
56
- useClientCache.set(file, true);
57
- return true;
58
- }
59
- }
60
- useClientCache.set(file, false);
61
- return false;
62
- }
63
- catch (error) {
64
- useClientCache.set(file, false);
65
- return false;
66
- }
67
- };
68
- export const miniflarePlugin = (givenOptions) => [
69
- cloudflare(givenOptions),
70
- {
71
- name: "rwsdk:miniflare-hmr",
72
- async hotUpdate(ctx) {
73
- const environment = givenOptions.viteEnvironment?.name ?? "worker";
74
- const entry = givenOptions.workerEntryPathname;
75
- if (!["client", environment].includes(this.environment.name)) {
76
- return;
77
- }
78
- // todo(justinvdm, 12 Dec 2024): Skip client references
79
- const modules = Array.from(ctx.server.environments[environment].moduleGraph.getModulesByFile(ctx.file) ?? []);
80
- const isWorkerUpdate = ctx.file === entry ||
81
- modules.some((module) => hasEntryAsAncestor(module, entry));
82
- // The worker doesnt need an update
83
- // => Short circuit HMR
84
- if (!isWorkerUpdate) {
85
- return [];
86
- }
87
- // The worker needs an update, but this is the client environment
88
- // => Notify for HMR update of any css files imported by in worker, that are also in the client module graph
89
- // Why: There may have been changes to css classes referenced, which might css modules to change
90
- if (this.environment.name === "client") {
91
- const cssModules = [];
92
- for (const [_, module] of ctx.server.environments[environment]
93
- .moduleGraph.idToModuleMap) {
94
- // todo(justinvdm, 13 Dec 2024): We check+update _all_ css files in worker module graph,
95
- // but it could just be a subset of css files that are actually affected, depending
96
- // on the importers and imports of the changed file. We should be smarter about this.
97
- if (module.file && module.file.endsWith(".css")) {
98
- const clientModules = ctx.server.environments.client.moduleGraph.getModulesByFile(module.file);
99
- if (clientModules) {
100
- cssModules.push(...clientModules.values());
101
- }
102
- }
103
- }
104
- invalidateUseClientCache(ctx.file);
105
- return (await isUseClientModule(ctx, ctx.file))
106
- ? [...ctx.modules, ...cssModules]
107
- : cssModules;
108
- }
109
- // The worker needs an update, and the hot check is for the worker environment
110
- // => Notify for custom RSC-based HMR update, then short circuit HMR
111
- if (isWorkerUpdate && this.environment.name === environment) {
112
- const shortName = getShortName(ctx.file, ctx.server.config.root);
113
- this.environment.logger.info(`${colors.green(`worker update`)} ${colors.dim(shortName)}`, {
114
- clear: true,
115
- timestamp: true,
116
- });
117
- const m = ctx.server.environments.client.moduleGraph
118
- .getModulesByFile(resolve(givenOptions.rootDir, "src", "app", "style.css"))
119
- ?.values()
120
- .next().value;
121
- if (m) {
122
- ctx.server.environments.client.moduleGraph.invalidateModule(m, new Set(), ctx.timestamp, true);
123
- }
124
- ctx.server.environments.client.hot.send({
125
- type: "custom",
126
- event: "rsc:update",
127
- data: {
128
- file: ctx.file,
129
- },
130
- });
131
- return [];
132
- }
133
- },
134
- },
135
- ];
@@ -1,10 +0,0 @@
1
- export type ModuleResolver = ReturnType<typeof createModuleResolver>;
2
- export declare function createModuleResolver({ getAliases, roots, conditionNames, name, }: {
3
- getAliases?: () => Array<{
4
- find: string | RegExp;
5
- replacement: string;
6
- }>;
7
- roots: string[];
8
- conditionNames?: string[];
9
- name: string;
10
- }): (request: string, importer?: string) => string | false;