rwsdk 0.2.0-alpha.6-test.20250806102744 → 0.2.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,6 @@
1
1
  import { Kysely } from "kysely";
2
- import { requestInfo } from "../../requestInfo/worker.js";
2
+ import { requestInfo, waitForRequestInfo } from "../../requestInfo/worker.js";
3
3
  import { DOWorkerDialect } from "./DOWorkerDialect.js";
4
- const moduleLevelDbCache = new Map();
5
4
  const createDurableObjectDb = (durableObjectBinding, name = "main") => {
6
5
  const durableObjectId = durableObjectBinding.idFromName(name);
7
6
  const stub = durableObjectBinding.get(durableObjectId);
@@ -11,23 +10,26 @@ const createDurableObjectDb = (durableObjectBinding, name = "main") => {
11
10
  });
12
11
  };
13
12
  export function createDb(durableObjectBinding, name = "main") {
14
- const getDb = () => {
15
- let db = moduleLevelDbCache.get(name);
13
+ const cacheKey = `${durableObjectBinding}_${name}`;
14
+ const doCreateDb = () => {
15
+ if (!requestInfo.rw) {
16
+ throw new Error(`
17
+ rwsdk: A database created using createDb() was accessed before requestInfo was available.
18
+
19
+ Please make sure database access is happening in a request handler or action handler.
20
+ `);
21
+ }
22
+ let db = requestInfo.rw.databases.get(cacheKey);
16
23
  if (!db) {
17
24
  db = createDurableObjectDb(durableObjectBinding, name);
18
- moduleLevelDbCache.set(name, db);
19
- }
20
- if (requestInfo.rw) {
21
- if (!requestInfo.rw.databases) {
22
- requestInfo.rw.databases = new Map();
23
- }
24
- requestInfo.rw.databases.set(name, db);
25
+ requestInfo.rw.databases.set(cacheKey, db);
25
26
  }
26
27
  return db;
27
28
  };
29
+ waitForRequestInfo().then(() => doCreateDb());
28
30
  return new Proxy({}, {
29
- get(target, prop) {
30
- const db = getDb();
31
+ get(target, prop, receiver) {
32
+ const db = doCreateDb();
31
33
  const value = db[prop];
32
34
  if (typeof value === "function") {
33
35
  return value.bind(db);
@@ -1,11 +1,10 @@
1
1
  /**
2
- * Finds __vite_ssr_import__ and __vite_ssr_dynamic_import__ specifiers in the code.
3
- * @param id The file identifier for language detection.
4
- * @param code The code to search for SSR imports.
5
- * @param log Optional logger function for debug output.
6
- * @returns Object with arrays of static and dynamic import specifiers.
2
+ * Finds callsites for __vite_ssr_import__ and __vite_ssr_dynamic_import__ with their ranges.
3
+ * The returned ranges can be used with MagicString to overwrite the entire call expression.
7
4
  */
8
- export declare function findSsrImportSpecifiers(id: string, code: string, log?: (...args: any[]) => void): {
9
- imports: string[];
10
- dynamicImports: string[];
11
- };
5
+ export declare function findSsrImportCallSites(id: string, code: string, log?: (...args: any[]) => void): Array<{
6
+ start: number;
7
+ end: number;
8
+ specifier: string;
9
+ kind: "import" | "dynamic_import";
10
+ }>;
@@ -1,67 +1,69 @@
1
1
  import { parse as sgParse, Lang as SgLang, Lang } from "@ast-grep/napi";
2
2
  import path from "path";
3
3
  /**
4
- * Finds __vite_ssr_import__ and __vite_ssr_dynamic_import__ specifiers in the code.
5
- * @param id The file identifier for language detection.
6
- * @param code The code to search for SSR imports.
7
- * @param log Optional logger function for debug output.
8
- * @returns Object with arrays of static and dynamic import specifiers.
4
+ * Finds callsites for __vite_ssr_import__ and __vite_ssr_dynamic_import__ with their ranges.
5
+ * The returned ranges can be used with MagicString to overwrite the entire call expression.
9
6
  */
10
- export function findSsrImportSpecifiers(id, code, log) {
7
+ export function findSsrImportCallSites(id, code, log) {
11
8
  const ext = path.extname(id).toLowerCase();
12
9
  const lang = ext === ".tsx" || ext === ".jsx" ? Lang.Tsx : SgLang.TypeScript;
13
10
  const logger = process.env.VERBOSE ? (log ?? (() => { })) : () => { };
14
- const imports = [];
15
- const dynamicImports = [];
11
+ const results = [];
16
12
  try {
17
13
  const root = sgParse(lang, code);
18
14
  const patterns = [
19
15
  {
20
16
  pattern: `__vite_ssr_import__("$SPECIFIER")`,
21
- list: imports,
17
+ kind: "import",
22
18
  },
23
19
  {
24
20
  pattern: `__vite_ssr_import__('$SPECIFIER')`,
25
- list: imports,
21
+ kind: "import",
26
22
  },
27
23
  {
28
24
  pattern: `__vite_ssr_dynamic_import__("$SPECIFIER")`,
29
- list: dynamicImports,
25
+ kind: "dynamic_import",
30
26
  },
31
27
  {
32
28
  pattern: `__vite_ssr_dynamic_import__('$SPECIFIER')`,
33
- list: dynamicImports,
29
+ kind: "dynamic_import",
34
30
  },
35
31
  {
36
32
  pattern: `__vite_ssr_import__("$SPECIFIER", $$$REST)`,
37
- list: imports,
33
+ kind: "import",
38
34
  },
39
35
  {
40
36
  pattern: `__vite_ssr_import__('$SPECIFIER', $$$REST)`,
41
- list: imports,
37
+ kind: "import",
42
38
  },
43
39
  {
44
40
  pattern: `__vite_ssr_dynamic_import__("$SPECIFIER", $$$REST)`,
45
- list: dynamicImports,
41
+ kind: "dynamic_import",
46
42
  },
47
43
  {
48
44
  pattern: `__vite_ssr_dynamic_import__('$SPECIFIER', $$$REST)`,
49
- list: dynamicImports,
45
+ kind: "dynamic_import",
50
46
  },
51
47
  ];
52
- for (const { pattern, list } of patterns) {
48
+ for (const { pattern, kind } of patterns) {
53
49
  const matches = root.root().findAll(pattern);
54
50
  for (const match of matches) {
55
51
  const specifier = match.getMatch("SPECIFIER")?.text();
56
52
  if (specifier) {
57
- list.push(specifier);
58
- logger(`Found SSR import specifier: %s in pattern: %s`, specifier, pattern);
53
+ const range = match.range();
54
+ results.push({
55
+ start: range.start.index,
56
+ end: range.end.index,
57
+ specifier,
58
+ kind,
59
+ });
60
+ logger(`Found SSR import callsite: %s [%s] at %d-%d`, specifier, kind, range.start.index, range.end.index);
59
61
  }
60
62
  }
61
63
  }
62
64
  }
63
65
  catch (err) {
64
- logger("Error parsing code for SSR imports: %O", err);
66
+ logger("Error parsing code for SSR import callsites: %O", err);
65
67
  }
66
- return { imports, dynamicImports };
68
+ return results;
67
69
  }
@@ -1,6 +1,7 @@
1
1
  import debug from "debug";
2
2
  import { SSR_BRIDGE_PATH } from "../lib/constants.mjs";
3
- import { findSsrImportSpecifiers } from "./findSsrSpecifiers.mjs";
3
+ import { findSsrImportCallSites } from "./findSsrSpecifiers.mjs";
4
+ import MagicString from "magic-string";
4
5
  const log = debug("rwsdk:vite:ssr-bridge-plugin");
5
6
  export const VIRTUAL_SSR_PREFIX = "virtual:rwsdk:ssr:";
6
7
  export const ssrBridgePlugin = ({ clientFiles, serverFiles, }) => {
@@ -108,35 +109,27 @@ export const ssrBridgePlugin = ({ clientFiles, serverFiles, }) => {
108
109
  return "export default {};";
109
110
  }
110
111
  log("Fetched SSR module code length: %d", code?.length || 0);
111
- const { imports, dynamicImports } = findSsrImportSpecifiers(idForFetch, code || "", log);
112
- const allSpecifiers = [
113
- ...new Set([...imports, ...dynamicImports]),
114
- ].map((id) => id.startsWith("/@id/") ? id.slice("/@id/".length) : id);
115
- const switchCases = allSpecifiers
116
- .map((specifier) => ` case "${specifier}": void import("${VIRTUAL_SSR_PREFIX}${specifier}");`)
117
- .join("\n");
118
- const transformedCode = `
119
- await (async function(__vite_ssr_import__, __vite_ssr_dynamic_import__) {${code}})(
120
- __ssrImport.bind(null, false),
121
- __ssrImport.bind(null, true)
122
- );
123
-
124
- function __ssrImport(isDynamic, id, ...args) {
125
- id = id.startsWith('/@id/') ? id.slice('/@id/'.length) : id;
126
-
127
- switch (id) {
128
- ${switchCases}
129
- }
130
-
131
- return isDynamic
132
- ? __vite_ssr_dynamic_import__("/@id/${VIRTUAL_SSR_PREFIX}" + id, ...args)
133
- : __vite_ssr_import__("/@id/${VIRTUAL_SSR_PREFIX}" + id, ...args);
134
- }
135
- `;
136
- log("Transformed SSR module code length: %d", transformedCode.length);
112
+ const s = new MagicString(code || "");
113
+ const callsites = findSsrImportCallSites(idForFetch, code || "", log);
114
+ for (const site of callsites) {
115
+ const normalized = site.specifier.startsWith("/@id/")
116
+ ? site.specifier.slice("/@id/".length)
117
+ : site.specifier;
118
+ // context(justinvdm, 11 Aug 2025):
119
+ // - We replace __vite_ssr_import__ and __vite_ssr_dynamic_import__
120
+ // with import() calls so that the module graph can be built
121
+ // correctly (vite looks for imports and import()s to build module
122
+ // graph)
123
+ // - We prepend /@id/$VIRTUAL_SSR_PREFIX to the specifier so that we
124
+ // can stay within the SSR subgraph of the worker module graph
125
+ const replacement = `import("/@id/${VIRTUAL_SSR_PREFIX}${normalized}")`;
126
+ s.overwrite(site.start, site.end, replacement);
127
+ }
128
+ const out = s.toString();
129
+ log("Transformed SSR module code length: %d", out.length);
137
130
  process.env.VERBOSE &&
138
- log("Transformed SSR module code for realId=%s: %s", realId, transformedCode);
139
- return transformedCode;
131
+ log("Transformed SSR module code for realId=%s: %s", realId, out);
132
+ return out;
140
133
  }
141
134
  }
142
135
  process.env.VERBOSE && log("No load handling for id=%s", id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rwsdk",
3
- "version": "0.2.0-alpha.6-test.20250806102744",
3
+ "version": "0.2.0-alpha.7",
4
4
  "description": "Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime",
5
5
  "type": "module",
6
6
  "bin": {