@seedprotocol/vite 0.7.4-next.711.gce2b766 → 0.7.4-next.793.g6dd83dd

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.d.ts CHANGED
@@ -1,17 +1,18 @@
1
1
  import type { Plugin } from 'vite';
2
2
  export interface SeedVitePluginOptions {
3
3
  /**
4
- * Additional modules to alias to ZenFS equivalents.
4
+ * Modules to alias to ZenFS (`@zenfs/core`, or `@zenfs/core/promises` for ids
5
+ * containing "promises"). The list replaces the default; to add a module, pass
6
+ * the defaults plus yours.
5
7
  * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']
6
8
  */
7
9
  fsModules?: string[];
8
10
  /**
9
- * Whether to inject automatic ZenFS initialization script into index.html.
10
- * When true, injects a <script type="module"> that imports from '@zenfs/core'/'@zenfs/dom'.
11
- * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use
12
- * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:
13
- * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';
14
- * await configure({ mounts: { '/': IndexedDB } });
11
+ * Whether to inject a ZenFS initialization script into index.html that mounts
12
+ * IndexedDB at `/`. Leave this false with the SDK: `client.init()` mounts OPFS
13
+ * at `/` itself, so apps do not configure ZenFS, and this mount would only be
14
+ * replaced. The script also imports the bare specifiers '@zenfs/core' and
15
+ * '@zenfs/dom', which browsers cannot resolve without an import map.
15
16
  * @default false
16
17
  */
17
18
  autoInit?: boolean;
@@ -36,6 +37,8 @@ export interface SeedVitePluginOptions {
36
37
  * Applied in configureServer and configurePreviewServer, including writeHead,
37
38
  * because Vite `server.headers` is not copied onto Framework-Mode HTML responses.
38
39
  * Set `false` to disable. Pass `{ coop, coep, corp }` to override values.
40
+ * A COOP/COEP/CORP value you set yourself in `server.headers` or `preview.headers`
41
+ * (any letter case) wins over both this option and the defaults, for that server.
39
42
  * @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)
40
43
  */
41
44
  isolationHeaders?: boolean | {
@@ -50,7 +53,6 @@ export interface SeedVitePluginOptions {
50
53
  * - Aliases path → path-browserify
51
54
  * - Ensures CommonJS in SDK dist is transformed by Vite's CommonJS plugin
52
55
  * - Allowlists linked SDK / sqlocal worker paths on server.fs.allow for Vite dev
53
- * - Optionally injects a simple ZenFS initialization script
54
56
  * - Optionally wires up vite-plugin-node-polyfills with safe defaults
55
57
  *
56
58
  * This plugin assumes the SDK does not bundle Node-only code in the browser entry.
@@ -59,9 +61,7 @@ export interface SeedVitePluginOptions {
59
61
  *
60
62
  * For the renderer build:
61
63
  * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).
62
- * - When autoInit is false (default), initialize ZenFS in your entry:
63
- * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';
64
- * await configure({ mounts: { '/': IndexedDB } });
64
+ * - Do not configure ZenFS yourself: `client.init()` mounts OPFS at `/`.
65
65
  */
66
66
  export declare function seedVitePlugin(options?: SeedVitePluginOptions): Plugin[];
67
67
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,MAAM,EAA4C,MAAM,MAAM,CAAA;AASvF,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;IAEpB;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;;;OASG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAE9B;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG;QAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;KACd,CAAA;CACF;AA8lBD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,EAAE,CAkf5E"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,MAAM,EAA4C,MAAM,MAAM,CAAA;AAWvF,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,EAAE,CAAA;IAEpB;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IAEf;;;;;;;;;OASG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAE9B;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EAAE,OAAO,GAAG;QAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,IAAI,CAAC,EAAE,MAAM,CAAA;KACd,CAAA;CACF;AAixBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,EAAE,CA2c5E"}
package/dist/index.js CHANGED
@@ -1,70 +1,172 @@
1
- import e from "node:fs";
2
- import { createRequire as t } from "node:module";
3
- import n from "node:path";
4
- import { fileURLToPath as r } from "node:url";
5
- import { nodePolyfills as i } from "vite-plugin-node-polyfills";
1
+ import { parseAst as e } from "vite";
2
+ import { attachScopes as t } from "@rollup/pluginutils";
3
+ import n from "node:fs";
4
+ import { createRequire as r } from "node:module";
5
+ import i from "node:path";
6
+ import { fileURLToPath as a } from "node:url";
7
+ import { nodePolyfills as o } from "vite-plugin-node-polyfills";
6
8
  //#region src/index.ts
7
- var a = t(import.meta.url), o = {
8
- global: /\btypeof\s+global\b/,
9
- process: /\btypeof\s+process\b/,
10
- Buffer: /\btypeof\s+Buffer\b/,
11
- __dirname: /\btypeof\s+__dirname\b/,
12
- __filename: /\btypeof\s+__filename\b/
13
- };
14
- function s(e) {
15
- return e.replace(/\/\*[\s\S]*?\*\//g, (e) => " ".repeat(e.length)).replace(/\/\/[^\n]*/g, (e) => " ".repeat(e.length)).replace(/`(?:[^`\\]|\\.)*`/gs, (e) => "`" + " ".repeat(e.length - 2) + "`").replace(/"(?:[^"\\]|\\.)*"/g, (e) => "\"" + " ".repeat(e.length - 2) + "\"").replace(/'(?:[^'\\]|\\.)*'/g, (e) => "'" + " ".repeat(e.length - 2) + "'");
9
+ var s = r(import.meta.url), c = /* @__PURE__ */ new Set([
10
+ "global",
11
+ "process",
12
+ "Buffer",
13
+ "__dirname",
14
+ "__filename"
15
+ ]);
16
+ function l(e) {
17
+ return !!e && typeof e == "object" && typeof e.type == "string";
18
+ }
19
+ function u(e, t) {
20
+ switch (e.type) {
21
+ case "MemberExpression": return t !== "property" || !!e.computed;
22
+ case "Property":
23
+ case "MethodDefinition":
24
+ case "PropertyDefinition":
25
+ case "AccessorProperty": return t !== "key" || !!e.computed;
26
+ case "LabeledStatement":
27
+ case "BreakStatement":
28
+ case "ContinueStatement":
29
+ case "MetaProperty": return !1;
30
+ case "ImportSpecifier": return t !== "imported";
31
+ case "ExportSpecifier": return t !== "exported";
32
+ default: return !0;
33
+ }
16
34
  }
17
- function c(e) {
18
- let t = s(e), n = [];
19
- for (let [r, i] of Object.entries(o)) {
20
- let a = RegExp(`(?<![.\\w$])\\b${r}\\b(?!This)(?![\\w$])`, "g"), o;
21
- for (; (o = a.exec(t)) !== null;) {
22
- let a = o.index, s = t.slice(Math.max(0, a - 20), a);
23
- if (i.test(s)) continue;
24
- let c = e.slice(0, a).split("\n"), l = c.length, u = c.at(-1)?.length ?? 0, d = (e.split("\n")[l - 1] ?? "").slice(Math.max(0, u - 40), u + r.length + 40).trim();
25
- n.push({
26
- global: r,
27
- offset: a,
28
- line: l,
29
- context: d
35
+ function d(e, t) {
36
+ if (e.type === "UnaryExpression" && e.operator === "typeof" && l(e.argument) && e.argument.type === "Identifier" && e.argument.name === t) return !0;
37
+ for (let n of Object.keys(e)) {
38
+ let r = e[n];
39
+ if (Array.isArray(r)) {
40
+ if (r.some((e) => l(e) && d(e, t))) return !0;
41
+ } else if (l(r) && d(r, t)) return !0;
42
+ }
43
+ return !1;
44
+ }
45
+ function f(e, t) {
46
+ for (let n = e; n.parent; n = n.parent) {
47
+ let e = n.parent.node, r = n.key;
48
+ if ((e.type === "IfStatement" || e.type === "ConditionalExpression") && r !== "test" && d(e.test, t) || e.type === "LogicalExpression" && r === "right" && d(e.left, t) || e.type === "TryStatement" && r === "block") return !0;
49
+ }
50
+ return !1;
51
+ }
52
+ function p(n) {
53
+ let r, i;
54
+ try {
55
+ r = e(n), i = t(r, "scope");
56
+ } catch {
57
+ return [];
58
+ }
59
+ let a = [], o = [0];
60
+ for (let e = n.indexOf("\n"); e !== -1; e = n.indexOf("\n", e + 1)) o.push(e + 1);
61
+ let s = (e) => {
62
+ let t = 0, n = o.length - 1;
63
+ for (; t < n;) {
64
+ let r = t + n + 1 >> 1;
65
+ o[r] <= e ? t = r : n = r - 1;
66
+ }
67
+ return t;
68
+ }, d = [{
69
+ path: {
70
+ node: r,
71
+ key: "",
72
+ parent: null
73
+ },
74
+ scope: i
75
+ }];
76
+ for (; d.length > 0;) {
77
+ let { path: e, scope: t } = d.pop(), { node: r } = e, i = r.scope ?? t;
78
+ if (r.type === "Identifier" && c.has(r.name) && e.parent) {
79
+ let t = r.name, c = e.parent.node;
80
+ if ((c.type !== "UnaryExpression" || c.operator !== "typeof") && u(c, e.key) && !i.contains(t) && !f(e, t)) {
81
+ let e = s(r.start), i = o[e], c = o[e + 1] ?? n.length, l = n.slice(Math.max(i, r.start - 40), Math.min(c, r.end + 40)).trim();
82
+ a.push({
83
+ global: t,
84
+ offset: r.start,
85
+ line: e + 1,
86
+ context: l
87
+ });
88
+ }
89
+ continue;
90
+ }
91
+ let p = [];
92
+ for (let t of Object.keys(r)) {
93
+ if (t === "scope") continue;
94
+ let n = r[t];
95
+ if (Array.isArray(n)) for (let r of n) l(r) && p.push({
96
+ node: r,
97
+ key: t,
98
+ parent: e
99
+ });
100
+ else l(n) && p.push({
101
+ node: n,
102
+ key: t,
103
+ parent: e
30
104
  });
31
105
  }
106
+ for (let e = p.length - 1; e >= 0; e--) d.push({
107
+ path: p[e],
108
+ scope: i
109
+ });
32
110
  }
33
- return n;
111
+ return a;
34
112
  }
35
- var l = [
113
+ var m = [
36
114
  "fs",
37
115
  "fs/promises",
38
116
  "node:fs",
39
117
  "node:fs/promises"
40
- ], u = n.dirname(r(import.meta.url)), d = n.join(u, "arweave-default-shim.js"), f = n.join(u, "debug-default-shim.js"), p = n.join(u, "stream-default-shim.js"), m = [
118
+ ], h = i.dirname(a(import.meta.url)), g = i.join(h, "arweave-default-shim.js"), _ = i.join(h, "debug-default-shim.js"), v = i.join(h, "stream-default-shim.js"), y = [
41
119
  "debug",
42
120
  "random",
43
121
  "seedrandom",
44
122
  "@georgedoescode/generative-utils",
45
123
  "nanoid-dictionary"
46
- ], h = ["@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk", "@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts"], g = [
124
+ ], b = ["@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk", "@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts"], x = [
47
125
  "kerium",
48
126
  "utilium",
49
127
  "memium",
50
128
  "readable-stream",
51
129
  "viem",
52
130
  "isows"
53
- ], _ = ["pluralize"], v = {
131
+ ], S = [
132
+ "@seedprotocol/eas",
133
+ "@seedprotocol/arweave",
134
+ "@seedprotocol/query"
135
+ ];
136
+ function C(e) {
137
+ let t = [], n = [], r = j("@seedprotocol/sdk", e);
138
+ for (let i of S) j(i, e) ? (t.push(i), n.push(i)) : r && t.push(`@seedprotocol/sdk > ${i}`);
139
+ return {
140
+ include: t,
141
+ dedupe: n
142
+ };
143
+ }
144
+ var w = ["pluralize"], T = {
54
145
  "Cross-Origin-Opener-Policy": "same-origin",
55
146
  "Cross-Origin-Embedder-Policy": "credentialless",
56
147
  "Cross-Origin-Resource-Policy": "same-origin"
57
148
  };
58
- function y(e) {
149
+ function E(e) {
59
150
  if (e === !1) return null;
60
151
  let t = typeof e == "object" && e ? e : {};
61
152
  return {
62
- "Cross-Origin-Opener-Policy": t.coop ?? v["Cross-Origin-Opener-Policy"],
63
- "Cross-Origin-Embedder-Policy": t.coep ?? v["Cross-Origin-Embedder-Policy"],
64
- "Cross-Origin-Resource-Policy": t.corp ?? v["Cross-Origin-Resource-Policy"]
153
+ "Cross-Origin-Opener-Policy": t.coop ?? T["Cross-Origin-Opener-Policy"],
154
+ "Cross-Origin-Embedder-Policy": t.coep ?? T["Cross-Origin-Embedder-Policy"],
155
+ "Cross-Origin-Resource-Policy": t.corp ?? T["Cross-Origin-Resource-Policy"]
65
156
  };
66
157
  }
67
- function b(e, t) {
158
+ function D(e, t) {
159
+ let n = new Set(Object.keys(t ?? {}).map((e) => e.toLowerCase()));
160
+ return Object.fromEntries(Object.entries(e).filter(([e]) => !n.has(e.toLowerCase())));
161
+ }
162
+ function O(e, t) {
163
+ let n = new Map(Object.entries(t ?? {}).map(([e, t]) => [e.toLowerCase(), t]));
164
+ return Object.fromEntries(Object.entries(e).map(([e, t]) => {
165
+ let r = n.get(e.toLowerCase());
166
+ return [e, r == null ? t : String(r)];
167
+ }));
168
+ }
169
+ function k(e, t) {
68
170
  e.middlewares.use((e, n, r) => {
69
171
  let i = () => {
70
172
  for (let [e, r] of Object.entries(t)) n.getHeader(e) || n.setHeader(e, r);
@@ -72,90 +174,90 @@ function b(e, t) {
72
174
  n.writeHead = ((...e) => (i(), a(...e))), i(), r();
73
175
  });
74
176
  }
75
- function x(t, r, i, a) {
76
- if (!e.existsSync(t)) return;
77
- let o = r.startsWith("@") ? r.replace("/", "+") : r;
78
- for (let s of e.readdirSync(t)) (s.startsWith(`${o}@`) || s.startsWith(`${r}@`)) && a.push(n.join(t, s, `node_modules/${r}`, i));
177
+ function A(e, t, r, a) {
178
+ if (!n.existsSync(e)) return;
179
+ let o = t.startsWith("@") ? t.replace("/", "+") : t;
180
+ for (let s of n.readdirSync(e)) (s.startsWith(`${o}@`) || s.startsWith(`${t}@`)) && a.push(i.join(e, s, `node_modules/${t}`, r));
79
181
  }
80
- function S(r, i) {
81
- return (t(n.join(i, "package.json")).resolve.paths(r) ?? []).some((t) => e.existsSync(n.join(t, r, "package.json")));
182
+ function j(e, t) {
183
+ return (r(i.join(t, "package.json")).resolve.paths(e) ?? []).some((t) => n.existsSync(i.join(t, e, "package.json")));
82
184
  }
83
- function C(t, r) {
84
- let i = [], o = n.resolve(u, "..");
185
+ function M(e, t) {
186
+ let r = [], a = i.resolve(h, "..");
85
187
  try {
86
- let e = a.resolve(`${t}/package.json`);
87
- i.push(n.join(n.dirname(e), r));
188
+ let n = s.resolve(`${e}/package.json`);
189
+ r.push(i.join(i.dirname(n), t));
88
190
  } catch {
89
191
  try {
90
- let o = a.resolve(t), s = n.dirname(o);
192
+ let a = s.resolve(e), o = i.dirname(a);
91
193
  for (let a = 0; a < 8; a++) {
92
- let a = n.join(s, "package.json");
93
- if (e.existsSync(a)) try {
94
- if (JSON.parse(e.readFileSync(a, "utf8")).name === t) {
95
- i.push(n.join(s, r));
194
+ let a = i.join(o, "package.json");
195
+ if (n.existsSync(a)) try {
196
+ if (JSON.parse(n.readFileSync(a, "utf8")).name === e) {
197
+ r.push(i.join(o, t));
96
198
  break;
97
199
  }
98
200
  } catch {}
99
- let o = n.dirname(s);
100
- if (o === s) break;
101
- s = o;
201
+ let s = i.dirname(o);
202
+ if (s === o) break;
203
+ o = s;
102
204
  }
103
205
  } catch {}
104
206
  }
105
- i.push(n.join(o, "node_modules", t, r));
106
- let s = n.join(process.cwd(), "node_modules");
107
- i.push(n.join(s, t, r)), x(n.join(s, ".bun"), t, r, i), x(n.join(o, "node_modules", ".bun"), t, r, i);
108
- let c = w(o);
109
- c && x(n.join(c, "node_modules", ".bun"), t, r, i);
110
- for (let t of i) if (e.existsSync(t)) return t;
207
+ r.push(i.join(a, "node_modules", e, t));
208
+ let o = i.join(process.cwd(), "node_modules");
209
+ r.push(i.join(o, e, t)), A(i.join(o, ".bun"), e, t, r), A(i.join(a, "node_modules", ".bun"), e, t, r);
210
+ let c = N(a);
211
+ c && A(i.join(c, "node_modules", ".bun"), e, t, r);
212
+ for (let e of r) if (n.existsSync(e)) return e;
111
213
  }
112
- function w(t) {
113
- let r = n.resolve(t);
114
- for (let t = 0; t < 8; t++) {
115
- if (e.existsSync(n.join(r, "node_modules", ".bun"))) return r;
116
- let t = n.dirname(r);
117
- if (t === r) break;
118
- r = t;
214
+ function N(e) {
215
+ let t = i.resolve(e);
216
+ for (let e = 0; e < 8; e++) {
217
+ if (n.existsSync(i.join(t, "node_modules", ".bun"))) return t;
218
+ let e = i.dirname(t);
219
+ if (e === t) break;
220
+ t = e;
119
221
  }
120
222
  }
121
- function T(e, t) {
122
- let r = n.resolve(t);
223
+ function P(e, t) {
224
+ let n = i.resolve(t);
123
225
  return e.some((e) => {
124
- let t = n.resolve(String(e));
125
- return r === t || r.startsWith(t.endsWith(n.sep) ? t : t + n.sep);
226
+ let t = i.resolve(String(e));
227
+ return n === t || n.startsWith(t.endsWith(i.sep) ? t : t + i.sep);
126
228
  });
127
229
  }
128
- function E(t) {
230
+ function F(e) {
129
231
  try {
130
- return e.realpathSync(t);
232
+ return n.realpathSync(e);
131
233
  } catch {
132
- return n.resolve(t);
234
+ return i.resolve(e);
133
235
  }
134
236
  }
135
- function D() {
237
+ function I() {
136
238
  let e = /* @__PURE__ */ new Set(), t = (t) => {
137
- t && e.add(E(t));
138
- }, r;
239
+ t && e.add(F(t));
240
+ }, n;
139
241
  try {
140
- r = n.dirname(a.resolve("@seedprotocol/sdk/package.json"));
242
+ n = i.dirname(s.resolve("@seedprotocol/sdk/package.json"));
141
243
  } catch {
142
- r = n.resolve(u, "..");
244
+ n = i.resolve(h, "..");
143
245
  }
144
- t(r);
145
- let i = w(r);
146
- i && t(i);
246
+ t(n);
247
+ let r = N(n);
248
+ r && t(r);
147
249
  for (let e of ["sqlocal", "@sqlite.org/sqlite-wasm"]) {
148
- let r = C(e, "package.json");
149
- r && t(n.dirname(r));
250
+ let n = M(e, "package.json");
251
+ n && t(i.dirname(n));
150
252
  }
151
253
  return [...e];
152
254
  }
153
- function O(e) {
255
+ function L(e) {
154
256
  let t = [];
155
- for (let n of D()) T(e, n) || (e.push(n), t.push(n));
257
+ for (let n of I()) P(e, n) || (e.push(n), t.push(n));
156
258
  return t;
157
259
  }
158
- function k(e) {
260
+ function R(e) {
159
261
  return e ? Array.isArray(e) ? e.filter((e) => !!e && !!e.replacement).map((e) => ({
160
262
  find: e.find,
161
263
  replacement: e.replacement
@@ -164,7 +266,7 @@ function k(e) {
164
266
  replacement: String(t)
165
267
  })) : [];
166
268
  }
167
- function A(e, t) {
269
+ function z(e, t) {
168
270
  let n = [...e], r = (e) => typeof e == "string" ? `s:${e}` : `r:${e.toString()}`, i = new Set(n.map((e) => r(e.find)));
169
271
  for (let e of t) {
170
272
  let t = r(e.find);
@@ -172,23 +274,23 @@ function A(e, t) {
172
274
  }
173
275
  return n;
174
276
  }
175
- var j = [
277
+ var B = [
176
278
  "vite-plugin-node-polyfills/shims/buffer",
177
279
  "vite-plugin-node-polyfills/shims/global",
178
280
  "vite-plugin-node-polyfills/shims/process"
179
281
  ];
180
- function M(t) {
181
- let n = a.resolve(t);
182
- if (n.endsWith(".cjs")) {
183
- let t = n.slice(0, -4) + ".js";
184
- if (e.existsSync(t)) return t;
282
+ function V(e) {
283
+ let t = s.resolve(e);
284
+ if (t.endsWith(".cjs")) {
285
+ let e = t.slice(0, -4) + ".js";
286
+ if (n.existsSync(e)) return e;
185
287
  }
186
- return n;
288
+ return t;
187
289
  }
188
- function N() {
290
+ function H() {
189
291
  let e = {}, t = [];
190
- for (let n of j) try {
191
- let t = M(n);
292
+ for (let n of B) try {
293
+ let t = V(n);
192
294
  n.endsWith("/buffer") ? e.buffer = t : n.endsWith("/global") ? e.global = t : n.endsWith("/process") && (e.process = t);
193
295
  } catch {
194
296
  t.push(n);
@@ -198,7 +300,7 @@ function N() {
198
300
  unresolved: t
199
301
  };
200
302
  }
201
- function P(e, t) {
303
+ function U(e, t) {
202
304
  let n = e, r = !1, i = [];
203
305
  t.buffer && i.push(["vite-plugin-node-polyfills/shims/buffer", t.buffer]), t.global && i.push(["vite-plugin-node-polyfills/shims/global", t.global]), t.process && i.push(["vite-plugin-node-polyfills/shims/process", t.process]);
204
306
  for (let [e, t] of i) {
@@ -210,7 +312,7 @@ function P(e, t) {
210
312
  }
211
313
  return r ? n : null;
212
314
  }
213
- function F(e, t) {
315
+ function W(e, t) {
214
316
  t.buffer && e.push({
215
317
  find: "vite-plugin-node-polyfills/shims/buffer",
216
318
  replacement: t.buffer
@@ -237,11 +339,11 @@ function F(e, t) {
237
339
  replacement: t.process
238
340
  });
239
341
  }
240
- function I(e) {
342
+ function G(e) {
241
343
  let t = {};
242
344
  return e.buffer && (t["vite-plugin-node-polyfills/shims/buffer"] = e.buffer, t.buffer = e.buffer, t["node:buffer"] = e.buffer), e.global && (t["vite-plugin-node-polyfills/shims/global"] = e.global, t.global = e.global), e.process && (t["vite-plugin-node-polyfills/shims/process"] = e.process, t.process = e.process, t["node:process"] = e.process), t;
243
345
  }
244
- var L = /* @__PURE__ */ new Set([
346
+ var K = /* @__PURE__ */ new Set([
245
347
  "vite-plugin-node-polyfills/shims/buffer",
246
348
  "vite-plugin-node-polyfills/shims/global",
247
349
  "vite-plugin-node-polyfills/shims/process",
@@ -251,57 +353,57 @@ var L = /* @__PURE__ */ new Set([
251
353
  "node:process",
252
354
  "global"
253
355
  ]);
254
- function R(e, t) {
356
+ function q(e, t) {
255
357
  let n = [];
256
- if (F(n, t), n.length === 0) return e;
257
- let r = e.filter((e) => typeof e.find != "string" || !L.has(e.find));
358
+ if (W(n, t), n.length === 0) return e;
359
+ let r = e.filter((e) => typeof e.find != "string" || !K.has(e.find));
258
360
  return [...n, ...r];
259
361
  }
260
- function z(t) {
261
- let n = C("nanoid-dictionary", "dist/dictionary.esm.js");
262
- n && t.push({
362
+ function J(e) {
363
+ let t = M("nanoid-dictionary", "dist/dictionary.esm.js");
364
+ t && e.push({
263
365
  find: /^nanoid-dictionary$/,
264
- replacement: n
366
+ replacement: t
265
367
  });
266
- let r = C("@zenfs/core", "dist/index.js"), i = C("@zenfs/core", "dist/path.js");
267
- r && t.push({
368
+ let r = M("@zenfs/core", "dist/index.js"), i = M("@zenfs/core", "dist/path.js");
369
+ r && e.push({
268
370
  find: /^@zenfs\/core$/,
269
371
  replacement: r
270
- }), i && t.push({
372
+ }), i && e.push({
271
373
  find: /^@zenfs\/core\/path$/,
272
374
  replacement: i
273
375
  });
274
- let a = C("@zenfs/dom", "dist/index.js");
275
- a && t.push({
376
+ let a = M("@zenfs/dom", "dist/index.js");
377
+ a && e.push({
276
378
  find: /^@zenfs\/dom$/,
277
379
  replacement: a
278
- }), e.existsSync(f) && t.push({
380
+ }), n.existsSync(_) && e.push({
279
381
  find: /^debug$/,
280
- replacement: f
382
+ replacement: _
281
383
  });
282
- let o = C("debug", "src/browser.js");
283
- o && t.push({
384
+ let o = M("debug", "src/browser.js");
385
+ o && e.push({
284
386
  find: /^debug\/src\/browser\.js$/,
285
387
  replacement: o
286
- }), e.existsSync(p) && t.push({
388
+ }), n.existsSync(v) && e.push({
287
389
  find: /^stream$/,
288
- replacement: p
390
+ replacement: v
289
391
  }, {
290
392
  find: /^node:stream$/,
291
- replacement: p
393
+ replacement: v
292
394
  });
293
395
  }
294
- function B() {
295
- let e = C("debug", "src/browser.js");
396
+ function Y() {
397
+ let e = M("debug", "src/browser.js");
296
398
  return e ? { "debug/src/browser.js": e } : {};
297
399
  }
298
- function V() {
299
- return e.existsSync(p) ? {
300
- stream: p,
301
- "node:stream": p
400
+ function X() {
401
+ return n.existsSync(v) ? {
402
+ stream: v,
403
+ "node:stream": v
302
404
  } : {};
303
405
  }
304
- function H(e, t) {
406
+ function Z(e, t) {
305
407
  let n = {
306
408
  ...e?.esbuildOptions?.define,
307
409
  ...t.define
@@ -311,30 +413,31 @@ function H(e, t) {
311
413
  ...Object.keys(r).length > 0 ? { resolve: { alias: r } } : {}
312
414
  };
313
415
  }
314
- function U(e = {}) {
315
- let { fsModules: t = l, autoInit: r = !1, debug: a = !1, includeNodePolyfills: o = !0, isolationHeaders: s } = e, u = y(s), f = "production", p = (...e) => {
316
- a && console.log("[seed-vite-plugin]", ...e);
317
- }, { paths: v, unresolved: x } = N(), w = I(v);
318
- o && x.length > 0 ? console.warn("[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\n" + x.map((e) => ` - ${e}`).join("\n") + "\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.") : x.length === 0 && p("Resolved vite-plugin-node-polyfills shims to absolute paths");
319
- let T = {
416
+ function Q(e = {}) {
417
+ let { fsModules: t = m, autoInit: n = !1, debug: r = !1, includeNodePolyfills: a = !0, isolationHeaders: s } = e, c = E(s), l = c, u = c, d = "production", f = (...e) => {
418
+ r && console.log("[seed-vite-plugin]", ...e);
419
+ }, { paths: h, unresolved: _ } = H(), v = G(h);
420
+ a && _.length > 0 ? console.warn("[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\n" + _.map((e) => ` - ${e}`).join("\n") + "\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.") : _.length === 0 && f("Resolved vite-plugin-node-polyfills shims to absolute paths");
421
+ let S = {
320
422
  name: "seed-protocol:config",
321
423
  enforce: "pre",
322
424
  configResolved(e) {
323
- let t = O(e.server.fs.allow);
324
- t.length > 0 && p("Extended server.fs.allow for linked SDK / sqlocal worker paths:", t);
425
+ c && (l = O(c, e.server.headers), u = O(c, e.preview.headers));
426
+ let t = L(e.server.fs.allow);
427
+ t.length > 0 && f("Extended server.fs.allow for linked SDK / sqlocal worker paths:", t);
325
428
  },
326
- config(e, r) {
327
- r?.mode && (f = r.mode);
328
- let i = [];
429
+ config(e, n) {
430
+ n?.mode && (d = n.mode);
431
+ let r = [];
329
432
  for (let e of t) {
330
433
  let t = e.includes("promises") ? "@zenfs/core/promises" : "@zenfs/core";
331
- i.push({
434
+ r.push({
332
435
  find: e,
333
436
  replacement: t
334
437
  });
335
438
  }
336
- let a = C("eventemitter3", "dist/eventemitter3.esm.js");
337
- a && i.push({
439
+ let a = M("eventemitter3", "dist/eventemitter3.esm.js");
440
+ a && r.push({
338
441
  find: "eventemitter3",
339
442
  replacement: a
340
443
  }, {
@@ -344,22 +447,25 @@ function U(e = {}) {
344
447
  find: "eventemitter3/index.js",
345
448
  replacement: a
346
449
  });
347
- let o = C("arweave", "bundles/web.bundle.js");
348
- o && i.push({
450
+ let o = M("arweave", "bundles/web.bundle.js");
451
+ o && r.push({
349
452
  find: /^arweave$/,
350
- replacement: d
453
+ replacement: g
351
454
  }, {
352
455
  find: /^arweave\/web\/index\.js$/,
353
- replacement: d
456
+ replacement: g
354
457
  }, {
355
458
  find: /^arweave\/bundles\/web\.bundle\.js$/,
356
459
  replacement: o
357
- }), z(i), F(i, v);
358
- let s = e.resolve ?? {}, c = A(k(s.alias), i), l = [
460
+ }), J(r), e.resolve = {
461
+ ...e.resolve,
462
+ alias: z(R(e.resolve?.alias), r)
463
+ };
464
+ let s = new Set(e.resolve.dedupe ?? []), l = [
359
465
  "@zenfs/core",
360
466
  "@zenfs/dom",
361
- ...m
362
- ], p = n.resolve(e.root ?? process.cwd()), y = [...l.filter((e) => !!C(e, "package.json")), ...g.filter((e) => S(e, p))], b = e.optimizeDeps, x = B(), T = V(), E = {
467
+ ...y
468
+ ], u = i.resolve(e.root ?? process.cwd()), f = [...l.filter((e) => !!M(e, "package.json")), ...x.filter((e) => j(e, u))], p = C(u), m = e.optimizeDeps, h = Y(), _ = X(), S = {
363
469
  exclude: [
364
470
  "@seedprotocol/sdk",
365
471
  "drizzle-orm",
@@ -367,16 +473,17 @@ function U(e = {}) {
367
473
  "sqlocal"
368
474
  ],
369
475
  include: [
370
- ...y,
371
- ...h,
372
- ..._
476
+ ...f,
477
+ ...p.include,
478
+ ...b,
479
+ ...w
373
480
  ],
374
- rolldownOptions: H(b, {
481
+ rolldownOptions: Z(m, {
375
482
  define: { global: "globalThis" },
376
483
  alias: {
377
- ...x,
378
- ...T,
379
- ...w
484
+ ...h,
485
+ ..._,
486
+ ...v
380
487
  }
381
488
  })
382
489
  };
@@ -387,117 +494,85 @@ function U(e = {}) {
387
494
  "process.browser": "true",
388
495
  "process.platform": "\"browser\""
389
496
  },
390
- resolve: {
391
- ...s,
392
- alias: c,
393
- dedupe: Array.from(/* @__PURE__ */ new Set([
394
- ...s.dedupe ?? [],
395
- "react",
396
- "react-dom",
397
- "thirdweb",
398
- "xstate",
399
- "@xstate/react",
400
- "@seedprotocol/sdk",
401
- "@seedprotocol/react",
402
- "@seedprotocol/publish",
403
- "@seedprotocol/feed",
404
- "@zenfs/core",
405
- "@zenfs/dom"
406
- ]))
407
- },
408
- optimizeDeps: E,
409
- ...u ? {
410
- server: {
411
- ...e.server ?? {},
412
- headers: {
413
- ...e.server?.headers ?? {},
414
- ...u
415
- }
416
- },
417
- preview: {
418
- ...e.preview ?? {},
419
- headers: {
420
- ...e.preview?.headers ?? {},
421
- ...u
422
- }
423
- }
497
+ resolve: { dedupe: Array.from(/* @__PURE__ */ new Set([
498
+ "react",
499
+ "react-dom",
500
+ "thirdweb",
501
+ "xstate",
502
+ "@xstate/react",
503
+ "@seedprotocol/sdk",
504
+ "@seedprotocol/react",
505
+ "@seedprotocol/publish",
506
+ "@seedprotocol/feed",
507
+ ...p.dedupe,
508
+ "@zenfs/core",
509
+ "@zenfs/dom"
510
+ ])).filter((e) => !s.has(e)) },
511
+ optimizeDeps: S,
512
+ ...c ? {
513
+ server: { headers: D(c, e.server?.headers) },
514
+ ...e.preview?.headers ? { preview: { headers: D(c, e.preview.headers) } } : {}
424
515
  } : {}
425
516
  };
426
517
  }
427
- }, E = {
518
+ }, T = {
428
519
  name: "seed-protocol:polyfill-resolve",
429
520
  enforce: "post",
430
521
  config(e) {
431
- if (Object.keys(w).length !== 0) return {
432
- resolve: { alias: R(k((e.resolve ?? {}).alias), v) },
433
- optimizeDeps: { rolldownOptions: H(void 0, {
434
- define: { global: "globalThis" },
435
- alias: w
436
- }) }
437
- };
522
+ if (Object.keys(v).length !== 0) return e.resolve = {
523
+ ...e.resolve,
524
+ alias: q(R(e.resolve?.alias), h)
525
+ }, { optimizeDeps: { rolldownOptions: Z(void 0, {
526
+ define: { global: "globalThis" },
527
+ alias: v
528
+ }) } };
438
529
  },
439
530
  resolveId: {
440
531
  order: "pre",
441
532
  handler(e) {
442
- return e === "vite-plugin-node-polyfills/shims/buffer" ? v.buffer ?? null : e === "vite-plugin-node-polyfills/shims/global" ? v.global ?? null : e === "vite-plugin-node-polyfills/shims/process" ? v.process ?? null : o ? e === "buffer" || e === "node:buffer" ? v.buffer ?? null : e === "global" ? v.global ?? null : e === "process" || e === "node:process" ? v.process ?? null : null : null;
533
+ return e === "vite-plugin-node-polyfills/shims/buffer" ? h.buffer ?? null : e === "vite-plugin-node-polyfills/shims/global" ? h.global ?? null : e === "vite-plugin-node-polyfills/shims/process" ? h.process ?? null : a ? e === "buffer" || e === "node:buffer" ? h.buffer ?? null : e === "global" ? h.global ?? null : e === "process" || e === "node:process" ? h.process ?? null : null : null;
443
534
  }
444
535
  },
445
536
  transform: {
446
537
  order: "post",
447
538
  handler(e) {
448
- let t = P(e, v);
539
+ let t = U(e, h);
449
540
  return t ? {
450
541
  code: t,
451
542
  map: null
452
543
  } : null;
453
544
  }
454
545
  }
455
- }, D = [
456
- T,
546
+ }, A = [
547
+ S,
457
548
  {
458
549
  name: "seed-protocol:main",
459
550
  enforce: "post",
460
551
  configureServer(e) {
461
- u && b(e, u);
552
+ l && k(e, l);
462
553
  },
463
554
  configurePreviewServer(e) {
464
- u && b(e, u);
555
+ u && k(e, u);
465
556
  },
466
557
  config(e) {
467
- let t = e.build ?? {}, n = t.commonjsOptions ?? {}, r = t.rollupOptions ?? {}, i = t.rolldownOptions, a = r.external ?? [], o = [
468
- ...Array.isArray(n.include) ? n.include : n.include ? [n.include] : [],
469
- /node_modules/,
470
- /seed-protocol-sdk[\\/]+dist[\\/]/
471
- ], s = [...Array.isArray(n.exclude) ? n.exclude : n.exclude ? [n.exclude] : [], /node_modules[\\/]+sqlocal[\\/]/], c = {
472
- ...n,
473
- include: o,
474
- exclude: s,
558
+ let t = {
559
+ include: [/node_modules/, /seed-protocol-sdk[\\/]+dist[\\/]/],
560
+ exclude: [/node_modules[\\/]+sqlocal[\\/]/],
475
561
  transformMixedEsModules: !0
476
- }, l = ["better-sqlite3"], u = (e) => l.some((t) => e === t || e.startsWith(`${t}/`) || e.includes(`/${t}/`) || e.endsWith(`/${t}`)), d = (e, t, n) => u(e) ? !0 : typeof a == "function" ? a(e, t, n ?? !1) : Array.isArray(a) ? a.some((t) => t === e || e.startsWith(`${t}/`)) : !1, f = {
477
- ...r,
478
- external: d
479
- }, p = {
480
- ...t,
481
- commonjsOptions: c
482
- };
483
- i ? p.rolldownOptions = {
484
- ...i,
485
- external: d
486
- } : p.rollupOptions = f;
487
- let m = e.worker ?? {};
562
+ }, n = [/^better-sqlite3(?:\/|$)/, /[\\/]better-sqlite3(?:[\\/]|$)/], r = (e.build?.rolldownOptions ?? e.build?.rollupOptions)?.external;
488
563
  return {
489
- build: p,
490
- worker: {
491
- ...m,
492
- format: m.format ?? "es"
493
- }
564
+ build: {
565
+ commonjsOptions: t,
566
+ rolldownOptions: { external: typeof r == "function" ? (e, t, i) => n.some((t) => t.test(e)) || r(e, t, i) : n }
567
+ },
568
+ ...e.worker?.format ? {} : { worker: { format: "es" } }
494
569
  };
495
570
  },
496
571
  generateBundle(e, t) {
497
572
  let n = [];
498
573
  for (let [e, r] of Object.entries(t)) {
499
574
  if (r.type !== "chunk") continue;
500
- let t = c(r.code);
575
+ let t = p(r.code);
501
576
  for (let r of t) n.push({
502
577
  chunk: e,
503
578
  ...r
@@ -520,12 +595,12 @@ function U(e = {}) {
520
595
  let t = `<script>
521
596
  (function(){
522
597
  if(typeof globalThis.global==='undefined')globalThis.global=globalThis;
523
- if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${JSON.stringify(f)}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};
598
+ if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${JSON.stringify(d)}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};
524
599
  })();
525
- <\/script>`, n = e;
526
- if (n = n.includes("<head>") ? n.replace("<head>", `<head>\n${t}`) : t + n, !r) return n;
600
+ <\/script>`, r = e;
601
+ if (r = r.includes("<head>") ? r.replace("<head>", `<head>\n${t}`) : t + r, !n) return r;
527
602
  let i = "\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n<\/script>";
528
- return n.includes("</head>") ? n.replace("</head>", `${i}\n</head>`) : n + i;
603
+ return r.includes("</head>") ? r.replace("</head>", `${i}\n</head>`) : r + i;
529
604
  }
530
605
  },
531
606
  {
@@ -541,9 +616,9 @@ function U(e = {}) {
541
616
  }
542
617
  }
543
618
  ];
544
- if (o) {
545
- p("Including vite-plugin-node-polyfills with default settings");
546
- let e = i({
619
+ if (a) {
620
+ f("Including vite-plugin-node-polyfills with default settings");
621
+ let e = o({
547
622
  exclude: ["readline"],
548
623
  include: [
549
624
  "path",
@@ -559,11 +634,11 @@ function U(e = {}) {
559
634
  },
560
635
  protocolImports: !0
561
636
  });
562
- Array.isArray(e) ? D.push(...e) : D.push(e);
637
+ Array.isArray(e) ? A.push(...e) : A.push(e);
563
638
  }
564
- return Object.keys(w).length > 0 && D.push(E), D;
639
+ return Object.keys(v).length > 0 && A.push(T), A;
565
640
  }
566
641
  //#endregion
567
- export { U as seedVitePlugin };
642
+ export { Q as seedVitePlugin };
568
643
 
569
644
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fs","path","_req","createRequire","BROWSER_DANGEROUS_GLOBALS","stripStringsAndComments","code","m","findDangerousGlobals","stripped","rawCode","hits","name","typeofGuard","re","offset","before","linesBefore","line","colOffset","ctx","DEFAULT_FS_MODULES","SDK_DIST_DIR","fileURLToPath","ARWEAVE_SHIM_FILE","DEBUG_SHIM_FILE","STREAM_SHIM_FILE","FRAGILE_RENDERER_OPTIMIZE_INCLUDES","EAS_OPTIMIZE_INCLUDES","APP_OPTIONAL_OPTIMIZE_INCLUDES","CJS_OPTIMIZE_INCLUDES","DEFAULT_ISOLATION_HEADERS","resolveIsolationHeaders","option","overrides","applyIsolationHeaderMiddleware","apply","key","value","headers","res","originalWriteHead","args","next","pushBunPackageCandidates","bunDir","bunPrefix","packageName","entry","candidates","relativePath","isResolvableFromRoot","root","dir","resolvePackageFile","sdkRoot","pkgJson","i","pkgJsonPath","parent","cwdNodeModules","bunInstallRoot","findNodeModulesBunRoot","candidate","startDir","isFsAllowCovering","child","filePath","allow","uri","realpathOrResolve","p","collectDevServerFsAllowPaths","paths","add","sdkPkgDir","pkg","ensureDevServerFsAllow","added","normalizeAliasEntries","alias","find","replacement","mergeAliasEntries","merged","existing","keyOf","seen","additions","NODE_POLYFILL_SHIM_IDS","resolvePolyfillShimFile","resolved","shimId","esm","resolveNodePolyfillShimPaths","unresolved","id","abs","rewriteBarePolyfillShimImports","changed","replacements","bare","absLiteral","quote","from","addNodePolyfillShimAliases","aliasEntries","nodePolyfillShimAliasObject","POLYFILL_ALIAS_FINDS_TO_REPLACE","withPreferredPolyfillAliases","preferred","filtered","addRendererCompatibilityAliases","nanoidDictionaryEsm","zenfsCoreIndex","zenfsCorePath","zenfsDomIndex","debugBrowserEntry","debugShimOptimizeAliasObject","streamShimOptimizeAliasObject","optimizeDepsRolldownPatch","define","patch","seedVitePlugin","isolationHeadersOption","options","isolationHeaders","htmlNodeEnv","log","debug","polyfillShimPaths","unresolvedPolyfillShims","polyfillShimAliasObj","includeNodePolyfills","configPlugin","addedAllowPaths","resolvedConfig","env","mod","fsModules","target","eventEmitterEsm","arweaveBundle","existingResolve","userConfig","mergedAlias","desiredOptimizeIncludes","appRoot","resolvableOptimizeIncludes","dep","existingOptimize","debugOptimizeAliases","streamOptimizeAliases","optimizeDeps","polyfillResolvePlugin","rewritten","plugins","server","existingBuild","existingCommonjs","existingRollupOptions","existingRolldownOptions","existingExternal","include","exclude","commonjsOptions","nodeOnlyPackages","isNodeOnlyExternal","externalList","importer","isResolved","ext","rollupOptions","build","existingWorker","allHits","chunkName","asset","bundle","hit","byChunk","list","chunk","h","shimScript","result","html","autoInit","initScript","transformed","polyfillPlugins","nodePolyfills"],"sources":["../src/index.ts"],"sourcesContent":["import type { ConfigEnv, Plugin, PreviewServer, UserConfig, ViteDevServer } from 'vite'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nconst _req = createRequire(import.meta.url)\n\nexport interface SeedVitePluginOptions {\n /**\n * Additional modules to alias to ZenFS equivalents.\n * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']\n */\n fsModules?: string[]\n\n /**\n * Whether to inject automatic ZenFS initialization script into index.html.\n * When true, injects a &lt;script type=\"module\"&gt; that imports from '@zenfs/core'/'@zenfs/dom'.\n * Browsers cannot resolve those bare specifiers, so the script fails at runtime unless you use\n * an import map or load ZenFS another way. Prefer false and initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * The SDK depends on that package and aliases its injected shim imports to absolute\n * paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.\n * Default include list omits full `stream`/`crypto` polyfills (those pull\n * stream-browserify and break Vite SSR / React Router prerender). A minimal\n * `stream` stub is still aliased so sax/rss-parser do not warn. Use `false`\n * for Framework Mode / prerender.\n * @default true\n */\n includeNodePolyfills?: boolean\n\n /**\n * Cross-origin isolation headers for sqlocal / SharedArrayBuffer / OPFS.\n * Applied in configureServer and configurePreviewServer, including writeHead,\n * because Vite `server.headers` is not copied onto Framework-Mode HTML responses.\n * Set `false` to disable. Pass `{ coop, coep, corp }` to override values.\n * @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)\n */\n isolationHeaders?: boolean | {\n coop?: string\n coep?: string\n corp?: string\n }\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\n// Keyed by identifier; value is the safe typeof-guard pattern so we can skip those.\nconst BROWSER_DANGEROUS_GLOBALS: Record<string, RegExp> = {\n global: /\\btypeof\\s+global\\b/,\n process: /\\btypeof\\s+process\\b/,\n Buffer: /\\btypeof\\s+Buffer\\b/,\n __dirname: /\\btypeof\\s+__dirname\\b/,\n __filename: /\\btypeof\\s+__filename\\b/,\n}\n\n/**\n * Strip JS string literals, template literals, and comments from source text\n * so that identifier searches don't false-positive on string content.\n * This is intentionally approximate — good enough for a lint-style warning pass.\n */\nfunction stripStringsAndComments(code: string): string {\n return code\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => ' '.repeat(m.length)) // /* block comments */\n .replace(/\\/\\/[^\\n]*/g, (m) => ' '.repeat(m.length)) // // line comments\n .replace(/`(?:[^`\\\\]|\\\\.)*`/gs, (m) => '`' + ' '.repeat(m.length - 2) + '`') // template literals\n .replace(/\"(?:[^\"\\\\]|\\\\.)*\"/g, (m) => '\"' + ' '.repeat(m.length - 2) + '\"') // double-quoted strings\n .replace(/'(?:[^'\\\\]|\\\\.)*'/g, (m) => \"'\" + ' '.repeat(m.length - 2) + \"'\") // single-quoted strings\n}\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the stripped source */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\nfunction findDangerousGlobals(rawCode: string): GlobalHit[] {\n const stripped = stripStringsAndComments(rawCode)\n const hits: GlobalHit[] = []\n\n for (const [name, typeofGuard] of Object.entries(BROWSER_DANGEROUS_GLOBALS)) {\n // Skip globalThis when checking 'global'\n const re = new RegExp(`(?<![.\\\\w$])\\\\b${name}\\\\b(?!This)(?![\\\\w$])`, 'g')\n let m: RegExpExecArray | null\n while ((m = re.exec(stripped)) !== null) {\n const offset = m.index\n // Check for typeof guard in the ~20 chars before the match\n const before = stripped.slice(Math.max(0, offset - 20), offset)\n if (typeofGuard.test(before)) continue\n\n // Compute 1-based line number from raw source (positions are preserved because\n // we replace with equal-length spaces, so offsets are stable)\n const linesBefore = rawCode.slice(0, offset).split('\\n')\n const line = linesBefore.length\n const colOffset = linesBefore.at(-1)?.length ?? 0\n const rawLine = rawCode.split('\\n')[line - 1] ?? ''\n const ctx = rawLine.slice(Math.max(0, colOffset - 40), colOffset + name.length + 40).trim()\n\n hits.push({ global: name, offset, line, context: ctx })\n }\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\nconst STREAM_SHIM_FILE = path.join(SDK_DIST_DIR, 'stream-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\n/**\n * Always force-include (do not gate on resolvePackageFile): under bun these live nested\n * under @seedprotocol/sdk, and eas-sdk's ESM named-imports CJS eas-contracts. Without\n * prebundling, Vite serves raw /@fs CJS and the browser throws\n * \"does not provide an export named 'EAS__factory'\" during SchemaEncoder encode.\n */\nconst EAS_OPTIMIZE_INCLUDES = [\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk',\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts',\n] as const\n\n/**\n * Prebundled only when the app itself can resolve them. Vite resolves `include`\n * entries from the app root, so finding them under a linked SDK is not enough\n * (Vite would skip them with \"Failed to resolve dependency\"). The zenfs helpers\n * are bundled into the @zenfs chunks anyway; viem/isows come from\n * @seedprotocol/publish, not the SDK.\n */\nconst APP_OPTIONAL_OPTIMIZE_INCLUDES = [\n 'kerium',\n 'utilium',\n 'memium',\n 'readable-stream',\n 'viem',\n 'isows',\n] as const\n\n/** CJS packages Seed ESM default-imports. Always include (do not gate on resolve). */\nconst CJS_OPTIMIZE_INCLUDES = ['pluralize'] as const\n\nconst DEFAULT_ISOLATION_HEADERS = {\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'credentialless',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n} as const\n\nfunction resolveIsolationHeaders(\n option: SeedVitePluginOptions['isolationHeaders'],\n): Record<string, string> | null {\n if (option === false) return null\n const overrides = typeof option === 'object' && option ? option : {}\n return {\n 'Cross-Origin-Opener-Policy': overrides.coop ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Opener-Policy'],\n 'Cross-Origin-Embedder-Policy': overrides.coep ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Embedder-Policy'],\n 'Cross-Origin-Resource-Policy': overrides.corp ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Resource-Policy'],\n }\n}\n\nfunction applyIsolationHeaderMiddleware(\n server: ViteDevServer | PreviewServer,\n headers: Record<string, string>,\n): void {\n server.middlewares.use((_req, res, next) => {\n const apply = () => {\n for (const [key, value] of Object.entries(headers)) {\n if (!res.getHeader(key)) {\n res.setHeader(key, value)\n }\n }\n }\n const originalWriteHead = res.writeHead.bind(res)\n res.writeHead = ((...args: Parameters<typeof res.writeHead>) => {\n apply()\n return originalWriteHead(...args)\n }) as typeof res.writeHead\n apply()\n next()\n })\n}\n\ntype AliasEntry = { find: string | RegExp; replacement: string }\n\nfunction pushBunPackageCandidates(\n bunDir: string,\n packageName: string,\n relativePath: string,\n candidates: string[],\n): void {\n if (!fs.existsSync(bunDir)) return\n // Nested scopes (@scope/name) live under .bun as @scope+name@version/...\n const bunPrefix = packageName.startsWith('@')\n ? packageName.replace('/', '+')\n : packageName\n for (const entry of fs.readdirSync(bunDir)) {\n if (!entry.startsWith(`${bunPrefix}@`) && !entry.startsWith(`${packageName}@`)) continue\n candidates.push(path.join(bunDir, entry, `node_modules/${packageName}`, relativePath))\n }\n}\n\n/** Whether a package is installed where Vite's optimizer looks for it (the app root upward). */\nfunction isResolvableFromRoot(packageName: string, root: string): boolean {\n const lookupDirs = createRequire(path.join(root, 'package.json')).resolve.paths(packageName) ?? []\n return lookupDirs.some((dir) => fs.existsSync(path.join(dir, packageName, 'package.json')))\n}\n\nfunction resolvePackageFile(packageName: string, relativePath: string): string | undefined {\n const candidates: string[] = []\n const sdkRoot = path.resolve(SDK_DIST_DIR, '..')\n\n try {\n const pkgJson = _req.resolve(`${packageName}/package.json`)\n candidates.push(path.join(path.dirname(pkgJson), relativePath))\n } catch {\n // Many packages (e.g. sqlocal) omit package.json from \"exports\". Resolve an\n // entry file and walk up to the package root instead.\n try {\n const entry = _req.resolve(packageName)\n let dir = path.dirname(entry)\n for (let i = 0; i < 8; i++) {\n const pkgJsonPath = path.join(dir, 'package.json')\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgName = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')).name\n if (pkgName === packageName) {\n candidates.push(path.join(dir, relativePath))\n break\n }\n } catch {\n // ignore invalid package.json\n }\n }\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n } catch {\n // package may be hoisted/unavailable in this graph\n }\n }\n\n // Linked/file installs: deps often live under the SDK package, not the app cwd.\n candidates.push(path.join(sdkRoot, 'node_modules', packageName, relativePath))\n\n const cwdNodeModules = path.join(process.cwd(), 'node_modules')\n candidates.push(path.join(cwdNodeModules, packageName, relativePath))\n\n pushBunPackageCandidates(\n path.join(cwdNodeModules, '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n pushBunPackageCandidates(\n path.join(sdkRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n const bunInstallRoot = findNodeModulesBunRoot(sdkRoot)\n if (bunInstallRoot) {\n pushBunPackageCandidates(\n path.join(bunInstallRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate\n }\n return undefined\n}\n\n/** Walk up from startDir looking for a directory that contains node_modules/.bun. */\nfunction findNodeModulesBunRoot(startDir: string): string | undefined {\n let dir = path.resolve(startDir)\n for (let i = 0; i < 8; i++) {\n if (fs.existsSync(path.join(dir, 'node_modules', '.bun'))) return dir\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n return undefined\n}\n\nfunction isFsAllowCovering(allow: readonly string[], filePath: string): boolean {\n const child = path.resolve(filePath)\n return allow.some((uri) => {\n const parent = path.resolve(String(uri))\n return (\n child === parent ||\n child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep)\n )\n })\n}\n\nfunction realpathOrResolve(p: string): string {\n try {\n return fs.realpathSync(p)\n } catch {\n return path.resolve(p)\n }\n}\n\n/**\n * When the SDK is linked (file:/symlink) into an external app, sqlocal's worker\n * and sqlite-wasm assets resolve into the SDK install tree (often bun's .bun\n * store). Vite's default server.fs.allow only covers the consumer workspace, so\n * those absolute /@fs requests 403 unless we allowlist the install roots.\n */\nfunction collectDevServerFsAllowPaths(): string[] {\n const paths = new Set<string>()\n const add = (p?: string) => {\n if (!p) return\n paths.add(realpathOrResolve(p))\n }\n\n let sdkPkgDir: string\n try {\n sdkPkgDir = path.dirname(_req.resolve('@seedprotocol/sdk/package.json'))\n } catch {\n sdkPkgDir = path.resolve(SDK_DIST_DIR, '..')\n }\n add(sdkPkgDir)\n\n const bunInstallRoot = findNodeModulesBunRoot(sdkPkgDir)\n if (bunInstallRoot) add(bunInstallRoot)\n\n for (const pkg of ['sqlocal', '@sqlite.org/sqlite-wasm'] as const) {\n const pkgJson = resolvePackageFile(pkg, 'package.json')\n if (pkgJson) add(path.dirname(pkgJson))\n }\n\n return [...paths]\n}\n\nfunction ensureDevServerFsAllow(allow: string[]): string[] {\n const added: string[] = []\n for (const dir of collectDevServerFsAllowPaths()) {\n if (isFsAllowCovering(allow, dir)) continue\n allow.push(dir)\n added.push(dir)\n }\n return added\n}\n\nfunction normalizeAliasEntries(\n alias: NonNullable<UserConfig['resolve']>['alias'] | undefined\n): AliasEntry[] {\n if (!alias) return []\n if (Array.isArray(alias)) {\n return alias\n .filter((entry): entry is AliasEntry => !!entry && !!(entry as AliasEntry).replacement)\n .map((entry) => ({ find: entry.find, replacement: entry.replacement }))\n }\n\n return Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement: String(replacement),\n }))\n}\n\nfunction mergeAliasEntries(existing: AliasEntry[], additions: AliasEntry[]): AliasEntry[] {\n const merged = [...existing]\n const keyOf = (find: string | RegExp) =>\n typeof find === 'string' ? `s:${find}` : `r:${find.toString()}`\n const seen = new Set(merged.map((entry) => keyOf(entry.find)))\n\n for (const entry of additions) {\n const key = keyOf(entry.find)\n if (seen.has(key)) continue\n seen.add(key)\n merged.push(entry)\n }\n\n return merged\n}\n\n/** Bare IDs that vite-plugin-node-polyfills injects into every transformed module. */\nconst NODE_POLYFILL_SHIM_IDS = [\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n] as const\n\ntype NodePolyfillShimPaths = {\n buffer?: string\n global?: string\n process?: string\n}\n\n/**\n * Prefer the package \"import\" ESM build (index.js). createRequire resolves the\n * \"require\" condition (index.cjs); Vite then serves `/@fs/...cjs?import` and\n * default-import fails in the browser.\n */\nfunction resolvePolyfillShimFile(shimId: string): string {\n const resolved = _req.resolve(shimId)\n if (resolved.endsWith('.cjs')) {\n const esm = resolved.slice(0, -4) + '.js'\n if (fs.existsSync(esm)) return esm\n }\n return resolved\n}\n\nfunction resolveNodePolyfillShimPaths(): {\n paths: NodePolyfillShimPaths\n unresolved: string[]\n} {\n const paths: NodePolyfillShimPaths = {}\n const unresolved: string[] = []\n for (const id of NODE_POLYFILL_SHIM_IDS) {\n try {\n const abs = resolvePolyfillShimFile(id)\n if (id.endsWith('/buffer')) paths.buffer = abs\n else if (id.endsWith('/global')) paths.global = abs\n else if (id.endsWith('/process')) paths.process = abs\n } catch {\n unresolved.push(id)\n }\n }\n return { paths, unresolved }\n}\n\n/** Rewrite leftover bare shim package ids to absolute ESM files (post import-analysis). */\nfunction rewriteBarePolyfillShimImports(\n code: string,\n paths: NodePolyfillShimPaths,\n): string | null {\n let next = code\n let changed = false\n const replacements: Array<[string, string]> = []\n if (paths.buffer) {\n replacements.push(['vite-plugin-node-polyfills/shims/buffer', paths.buffer])\n }\n if (paths.global) {\n replacements.push(['vite-plugin-node-polyfills/shims/global', paths.global])\n }\n if (paths.process) {\n replacements.push(['vite-plugin-node-polyfills/shims/process', paths.process])\n }\n for (const [bare, abs] of replacements) {\n const absLiteral = JSON.stringify(abs)\n for (const quote of ['\"', \"'\"] as const) {\n const from = `${quote}${bare}${quote}`\n if (!next.includes(from)) continue\n next = next.split(from).join(absLiteral)\n changed = true\n }\n }\n return changed ? next : null\n}\n\n/**\n * Alias polyfill shim bare imports + buffer/process/global module ids to absolute\n * paths resolved from this package. Nested installs under @seedprotocol/sdk are\n * invisible to consumer-project resolution (and to Vite 8's Rolldown optimizer)\n * unless we rewrite to absolute files.\n */\nfunction addNodePolyfillShimAliases(\n aliasEntries: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): void {\n if (paths.buffer) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/buffer', replacement: paths.buffer },\n { find: /^buffer$/, replacement: paths.buffer },\n { find: /^node:buffer$/, replacement: paths.buffer },\n )\n }\n if (paths.global) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/global', replacement: paths.global },\n { find: /^global$/, replacement: paths.global },\n )\n }\n if (paths.process) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/process', replacement: paths.process },\n { find: /^process$/, replacement: paths.process },\n { find: /^node:process$/, replacement: paths.process },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps.rolldown/rollup resolve (string keys). */\nfunction nodePolyfillShimAliasObject(paths: NodePolyfillShimPaths): Record<string, string> {\n const alias: Record<string, string> = {}\n if (paths.buffer) {\n alias['vite-plugin-node-polyfills/shims/buffer'] = paths.buffer\n alias.buffer = paths.buffer\n alias['node:buffer'] = paths.buffer\n }\n if (paths.global) {\n alias['vite-plugin-node-polyfills/shims/global'] = paths.global\n alias.global = paths.global\n }\n if (paths.process) {\n alias['vite-plugin-node-polyfills/shims/process'] = paths.process\n alias.process = paths.process\n alias['node:process'] = paths.process\n }\n return alias\n}\n\nconst POLYFILL_ALIAS_FINDS_TO_REPLACE = new Set([\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n 'buffer',\n 'node:buffer',\n 'process',\n 'node:process',\n 'global',\n])\n\n/**\n * Put absolute polyfill aliases first and drop bare/package-id entries that\n * vite-plugin-node-polyfills may have added for the same modules (first match wins).\n */\nfunction withPreferredPolyfillAliases(\n existing: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): AliasEntry[] {\n const preferred: AliasEntry[] = []\n addNodePolyfillShimAliases(preferred, paths)\n if (preferred.length === 0) return existing\n\n const filtered = existing.filter((entry) => {\n if (typeof entry.find !== 'string') return true\n return !POLYFILL_ALIAS_FINDS_TO_REPLACE.has(entry.find)\n })\n return [...preferred, ...filtered]\n}\n\nfunction addRendererCompatibilityAliases(aliasEntries: AliasEntry[]): void {\n const nanoidDictionaryEsm = resolvePackageFile(\n 'nanoid-dictionary',\n 'dist/dictionary.esm.js',\n )\n if (nanoidDictionaryEsm) {\n aliasEntries.push({\n find: /^nanoid-dictionary$/,\n replacement: nanoidDictionaryEsm,\n })\n }\n\n const zenfsCoreIndex = resolvePackageFile('@zenfs/core', 'dist/index.js')\n const zenfsCorePath = resolvePackageFile('@zenfs/core', 'dist/path.js')\n if (zenfsCoreIndex) {\n aliasEntries.push({ find: /^@zenfs\\/core$/, replacement: zenfsCoreIndex })\n }\n if (zenfsCorePath) {\n aliasEntries.push({ find: /^@zenfs\\/core\\/path$/, replacement: zenfsCorePath })\n }\n\n const zenfsDomIndex = resolvePackageFile('@zenfs/dom', 'dist/index.js')\n if (zenfsDomIndex) {\n aliasEntries.push({ find: /^@zenfs\\/dom$/, replacement: zenfsDomIndex })\n }\n\n if (fs.existsSync(DEBUG_SHIM_FILE)) {\n // Only alias the package root. Do not alias debug/src/browser.js to this shim:\n // the shim imports that path and aliasing it back creates a circular module.\n aliasEntries.push({ find: /^debug$/, replacement: DEBUG_SHIM_FILE })\n }\n\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n if (debugBrowserEntry) {\n aliasEntries.push({\n find: /^debug\\/src\\/browser\\.js$/,\n replacement: debugBrowserEntry,\n })\n }\n\n // Minimal stream stub (not stream-browserify) so sax/rss-parser init is quiet.\n if (fs.existsSync(STREAM_SHIM_FILE)) {\n aliasEntries.push(\n { find: /^stream$/, replacement: STREAM_SHIM_FILE },\n { find: /^node:stream$/, replacement: STREAM_SHIM_FILE },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps pre-bundle (debug shim subpath). */\nfunction debugShimOptimizeAliasObject(): Record<string, string> {\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n return debugBrowserEntry ? { 'debug/src/browser.js': debugBrowserEntry } : {}\n}\n\n/** Object-form aliases so optimizeDeps prebundles (rss-parser → sax) use our stream stub. */\nfunction streamShimOptimizeAliasObject(): Record<string, string> {\n if (!fs.existsSync(STREAM_SHIM_FILE)) return {}\n return {\n stream: STREAM_SHIM_FILE,\n 'node:stream': STREAM_SHIM_FILE,\n }\n}\n\ntype OptimizeDepsConfig = NonNullable<UserConfig['optimizeDeps']>\n\n/**\n * Build a Vite 8 `optimizeDeps.rolldownOptions` patch for a plugin `config()` hook.\n *\n * Returns only what this plugin adds. Vite deep-merges hook results into the\n * user config and concatenates arrays, so echoing existing options back would\n * duplicate them — e.g. vite-plugin-node-polyfills' optimizer banner plugin,\n * which then declares `__buffer_polyfill` twice in every prebundled chunk.\n * Legacy `esbuildOptions.define` is carried into `transform.define` so\n * definitions survive the move off the deprecated key.\n */\nfunction optimizeDepsRolldownPatch(\n existing: OptimizeDepsConfig | undefined,\n patch: {\n define?: Record<string, string>\n alias?: Record<string, string>\n },\n): OptimizeDepsConfig['rolldownOptions'] {\n const define = {\n ...existing?.esbuildOptions?.define,\n ...patch.define,\n }\n const alias = patch.alias ?? {}\n\n return {\n ...(Object.keys(define).length > 0 ? { transform: { define } } : {}),\n ...(Object.keys(alias).length > 0 ? { resolve: { alias } } : {}),\n }\n}\n\n/**\n * Minimal Vite plugin to make the SDK work in browser/Electron renderer:\n * - Aliases fs → @zenfs/core (and promises variant)\n * - Aliases path → path-browserify\n * - Ensures CommonJS in SDK dist is transformed by Vite's CommonJS plugin\n * - Allowlists linked SDK / sqlocal worker paths on server.fs.allow for Vite dev\n * - Optionally injects a simple ZenFS initialization script\n * - Optionally wires up vite-plugin-node-polyfills with safe defaults\n *\n * This plugin assumes the SDK does not bundle Node-only code in the browser entry.\n * For Electron, Node-only work (e.g. better-sqlite3) should run in the\n * main process; the renderer should only use browser-safe SDK usage.\n *\n * For the renderer build:\n * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).\n * - When autoInit is false (default), initialize ZenFS in your entry:\n * import { configure } from '@zenfs/core'; import { IndexedDB } from '@zenfs/dom';\n * await configure({ mounts: { '/': IndexedDB } });\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = DEFAULT_FS_MODULES,\n autoInit = false,\n debug = false,\n includeNodePolyfills = true,\n isolationHeaders: isolationHeadersOption,\n } = options\n\n const isolationHeaders = resolveIsolationHeaders(isolationHeadersOption)\n let htmlNodeEnv = 'production'\n\n const log = (...args: unknown[]) => {\n if (debug) console.log('[seed-vite-plugin]', ...args)\n }\n\n const { paths: polyfillShimPaths, unresolved: unresolvedPolyfillShims } =\n resolveNodePolyfillShimPaths()\n const polyfillShimAliasObj = nodePolyfillShimAliasObject(polyfillShimPaths)\n\n if (includeNodePolyfills && unresolvedPolyfillShims.length > 0) {\n console.warn(\n '[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\\n' +\n unresolvedPolyfillShims.map((id) => ` - ${id}`).join('\\n') +\n '\\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.',\n )\n } else if (unresolvedPolyfillShims.length === 0) {\n log('Resolved vite-plugin-node-polyfills shims to absolute paths')\n }\n\n /**\n * Pre-plugin: configure aliases and optimizeDeps.\n */\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n const addedAllowPaths = ensureDevServerFsAllow(resolvedConfig.server.fs.allow)\n if (addedAllowPaths.length > 0) {\n log(\n 'Extended server.fs.allow for linked SDK / sqlocal worker paths:',\n addedAllowPaths,\n )\n }\n },\n\n config(userConfig, env) {\n if (env?.mode) {\n htmlNodeEnv = env.mode\n }\n const aliasEntries: AliasEntry[] = []\n for (const mod of fsModules) {\n const isPromises = mod.includes('promises')\n const target = isPromises ? '@zenfs/core/promises' : '@zenfs/core'\n aliasEntries.push({ find: mod, replacement: target })\n }\n\n const eventEmitterEsm = resolvePackageFile('eventemitter3', 'dist/eventemitter3.esm.js')\n if (eventEmitterEsm) {\n aliasEntries.push(\n { find: 'eventemitter3', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.mjs', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.js', replacement: eventEmitterEsm },\n )\n }\n\n const arweaveBundle = resolvePackageFile('arweave', 'bundles/web.bundle.js')\n if (arweaveBundle) {\n aliasEntries.push(\n { find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/web\\/index\\.js$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/bundles\\/web\\.bundle\\.js$/, replacement: arweaveBundle },\n )\n }\n\n addRendererCompatibilityAliases(aliasEntries)\n addNodePolyfillShimAliases(aliasEntries, polyfillShimPaths)\n\n const existingResolve = userConfig.resolve ?? {}\n const mergedAlias = mergeAliasEntries(\n normalizeAliasEntries(existingResolve.alias),\n aliasEntries,\n )\n\n const desiredOptimizeIncludes = [\n '@zenfs/core',\n '@zenfs/dom',\n ...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,\n ]\n const appRoot = path.resolve(userConfig.root ?? process.cwd())\n const resolvableOptimizeIncludes = [\n ...desiredOptimizeIncludes.filter((dep) => !!resolvePackageFile(dep, 'package.json')),\n ...APP_OPTIONAL_OPTIMIZE_INCLUDES.filter((dep) => isResolvableFromRoot(dep, appRoot)),\n ]\n\n const existingOptimize = userConfig.optimizeDeps\n const debugOptimizeAliases = debugShimOptimizeAliasObject()\n const streamOptimizeAliases = streamShimOptimizeAliasObject()\n\n // Only this plugin's additions: Vite concatenates them onto the user's arrays.\n const optimizeDeps: UserConfig['optimizeDeps'] = {\n exclude: [\n // Do not prebundle the SDK itself or clearly node-only tools\n '@seedprotocol/sdk',\n 'drizzle-orm',\n 'better-sqlite3',\n // sqlocal uses workers and should not be prebundled\n 'sqlocal',\n ],\n include: [\n ...resolvableOptimizeIncludes,\n ...EAS_OPTIMIZE_INCLUDES,\n ...CJS_OPTIMIZE_INCLUDES,\n ],\n // Keep `global` shim in optimizer Rolldown options; top-level Vite `define`\n // can be rejected by Rolldown in some consumer setups.\n rolldownOptions: optimizeDepsRolldownPatch(existingOptimize, {\n define: { global: 'globalThis' },\n alias: {\n ...debugOptimizeAliases,\n ...streamOptimizeAliases,\n ...polyfillShimAliasObj,\n },\n }),\n }\n\n return {\n // Apply global → globalThis for Rollup production builds too.\n // optimizeDeps.rolldownOptions.transform.define only covers the dev pre-bundle step;\n // this top-level define is picked up by @rollup/plugin-replace during build\n // and covers all chunks, including code-split migrator/commonjs-helper chunks.\n define: {\n ...(userConfig.define ?? {}),\n global: 'globalThis',\n // process is referenced by path-browserify and other CJS modules.\n // Point at globalThis.process which is set by the synchronous inline\n // shim script injected into index.html before any modules load.\n // Do not define process.env.NODE_ENV — Vite already sets it from mode,\n // and forcing \"production\" during `vite serve` compiles out React Refresh.\n 'process.browser': 'true',\n 'process.platform': '\"browser\"',\n },\n resolve: {\n ...existingResolve,\n alias: mergedAlias,\n // Prevent duplicate React/thirdweb instances when @seedprotocol/publish is workspace-linked.\n // Multiple copies break context (e.g. useActiveAccount must be used within ThirdwebProvider).\n // Also dedupe XState and Seed packages: two xstate copies cause Object.assign _version errors;\n // two @seedprotocol/sdk copies leave BaseDb facade / Db.appDb on different module instances\n // (\"App DB not found\", undefined.$with on PostsPage).\n // Two @zenfs copies leave configureSingle / WebAccess on different module instances\n // and can remount OPFS against a stale handle.\n dedupe: Array.from(\n new Set([\n ...(existingResolve.dedupe ?? []),\n 'react',\n 'react-dom',\n 'thirdweb',\n 'xstate',\n '@xstate/react',\n '@seedprotocol/sdk',\n '@seedprotocol/react',\n '@seedprotocol/publish',\n '@seedprotocol/feed',\n '@zenfs/core',\n '@zenfs/dom',\n ])\n ),\n },\n optimizeDeps,\n ...(isolationHeaders\n ? {\n server: {\n ...(userConfig.server ?? {}),\n headers: {\n ...(userConfig.server?.headers ?? {}),\n ...isolationHeaders,\n },\n },\n preview: {\n ...(userConfig.preview ?? {}),\n headers: {\n ...(userConfig.preview?.headers ?? {}),\n ...isolationHeaders,\n },\n },\n }\n : {}),\n }\n },\n }\n\n /**\n * Runs after vite-plugin-node-polyfills so absolute shim aliases win over its bare\n * package-id aliases in both resolve.alias and the Rolldown optimizeDeps graph.\n */\n const polyfillResolvePlugin: Plugin = {\n name: 'seed-protocol:polyfill-resolve',\n enforce: 'post',\n\n config(userConfig) {\n if (Object.keys(polyfillShimAliasObj).length === 0) return\n\n const existingResolve = userConfig.resolve ?? {}\n const mergedAlias = withPreferredPolyfillAliases(\n normalizeAliasEntries(existingResolve.alias),\n polyfillShimPaths,\n )\n\n return {\n resolve: {\n alias: mergedAlias,\n },\n optimizeDeps: {\n rolldownOptions: optimizeDepsRolldownPatch(undefined, {\n // Later merges overwrite vite-plugin-node-polyfills' serve-time\n // `global: 'global'` define and its bare shim-id aliases.\n define: { global: 'globalThis' },\n alias: polyfillShimAliasObj,\n }),\n },\n }\n },\n\n resolveId: {\n order: 'pre',\n handler(id) {\n // Always rewrite injected shim package ids (safe even if nested under the SDK).\n if (id === 'vite-plugin-node-polyfills/shims/buffer') {\n return polyfillShimPaths.buffer ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/global') {\n return polyfillShimPaths.global ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/process') {\n return polyfillShimPaths.process ?? null\n }\n // Only remap node globals when we own the polyfills plugin config.\n if (!includeNodePolyfills) return null\n if (id === 'buffer' || id === 'node:buffer') return polyfillShimPaths.buffer ?? null\n if (id === 'global') return polyfillShimPaths.global ?? null\n if (id === 'process' || id === 'node:process') return polyfillShimPaths.process ?? null\n return null\n },\n },\n\n transform: {\n // Must emit absolute shim paths: order \"post\" runs after import-analysis.\n order: 'post',\n handler(code) {\n const rewritten = rewriteBarePolyfillShimImports(code, polyfillShimPaths)\n return rewritten ? { code: rewritten, map: null } : null\n },\n },\n }\n\n /**\n * Post-plugin: build configuration + optional ZenFS init.\n */\n const mainPlugin: Plugin = {\n name: 'seed-protocol:main',\n enforce: 'post',\n\n configureServer(server) {\n if (isolationHeaders) applyIsolationHeaderMiddleware(server, isolationHeaders)\n },\n\n configurePreviewServer(server) {\n if (isolationHeaders) applyIsolationHeaderMiddleware(server, isolationHeaders)\n },\n\n config(userConfig) {\n const existingBuild = userConfig.build ?? {}\n const existingCommonjs = existingBuild.commonjsOptions ?? {}\n const existingRollupOptions = existingBuild.rollupOptions ?? {}\n const existingRolldownOptions = (existingBuild as Record<string, unknown>).rolldownOptions as\n | Record<string, unknown>\n | undefined\n const existingExternal = existingRollupOptions.external ?? []\n\n const include = [\n // Anything the user already had\n ...(Array.isArray(existingCommonjs.include)\n ? existingCommonjs.include\n : existingCommonjs.include\n ? [existingCommonjs.include]\n : []),\n // Always process node_modules and the SDK dist so require() is transformed\n /node_modules/,\n /seed-protocol-sdk[\\\\/]+dist[\\\\/]/,\n ]\n\n // Exclude packages that are already ESM or have special worker handling\n const exclude = [\n ...(Array.isArray(existingCommonjs.exclude)\n ? existingCommonjs.exclude\n : existingCommonjs.exclude\n ? [existingCommonjs.exclude]\n : []),\n // sqlocal is ESM and uses workers - don't transform it\n /node_modules[\\\\/]+sqlocal[\\\\/]/,\n ]\n\n const commonjsOptions = {\n ...existingCommonjs,\n include,\n exclude,\n transformMixedEsModules: true,\n }\n\n // Externalize Node.js-only packages that should never be bundled for the browser\n const nodeOnlyPackages = [\n 'better-sqlite3', // Native SQLite binding (Node.js only)\n ]\n\n const isNodeOnlyExternal = (id: string) =>\n nodeOnlyPackages.some(\n (pkg) =>\n id === pkg ||\n id.startsWith(`${pkg}/`) ||\n id.includes(`/${pkg}/`) ||\n id.endsWith(`/${pkg}`)\n )\n\n const externalList = (id: string, importer?: string, isResolved?: boolean) => {\n if (isNodeOnlyExternal(id)) return true\n if (typeof existingExternal === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (existingExternal as any)(id, importer, isResolved ?? false)\n }\n if (Array.isArray(existingExternal)) {\n return existingExternal.some((ext) => ext === id || id.startsWith(`${ext}/`))\n }\n return false\n }\n\n const rollupOptions = {\n ...existingRollupOptions,\n external: externalList,\n }\n\n const build: Record<string, unknown> = {\n ...existingBuild,\n commonjsOptions,\n }\n if (existingRolldownOptions) {\n build.rolldownOptions = {\n ...existingRolldownOptions,\n external: externalList,\n }\n } else {\n build.rollupOptions = rollupOptions\n }\n\n // Worker options are TOP-LEVEL in Vite config, not under build.\n // Default 'iife' breaks when workers use code-splitting (e.g. sqlocal).\n const existingWorker = userConfig.worker ?? {}\n const worker = {\n ...existingWorker,\n format: existingWorker.format ?? 'es',\n }\n\n return {\n build,\n worker,\n }\n },\n\n generateBundle(_options, bundle) {\n const allHits: Array<{ chunk: string } & GlobalHit> = []\n\n for (const [chunkName, asset] of Object.entries(bundle)) {\n if (asset.type !== 'chunk') continue\n const hits = findDangerousGlobals(asset.code)\n for (const hit of hits) {\n allHits.push({ chunk: chunkName, ...hit })\n }\n }\n\n if (allHits.length === 0) return\n\n console.warn(\n '\\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +\n ' These will throw ReferenceError at runtime unless shimmed.\\n'\n )\n const byChunk = new Map<string, typeof allHits>()\n for (const hit of allHits) {\n const list = byChunk.get(hit.chunk) ?? []\n list.push(hit)\n byChunk.set(hit.chunk, list)\n }\n for (const [chunk, hits] of byChunk) {\n console.warn(` ${chunk}`)\n for (const h of hits) {\n console.warn(` line ${h.line}: \\`${h.global}\\` — ${h.context}`)\n }\n }\n console.warn('')\n },\n\n transformIndexHtml(html) {\n // Synchronous inline script runs before any <script type=\"module\">, so\n // global and process are guaranteed to exist when CJS wrappers evaluate.\n // vite-plugin-node-polyfills injects polyfills via module imports, which\n // resolve too late for @rollup/plugin-commonjs-generated wrapper code.\n const nodeEnvLiteral = JSON.stringify(htmlNodeEnv)\n const shimScript = `<script>\n(function(){\n if(typeof globalThis.global==='undefined')globalThis.global=globalThis;\n if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${nodeEnvLiteral}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};\n})();\n</script>`\n\n let result = html\n if (result.includes('<head>')) {\n result = result.replace('<head>', `<head>\\n${shimScript}`)\n } else {\n result = shimScript + result\n }\n\n if (!autoInit) return result\n\n const initScript = `\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n</script>`\n\n if (result.includes('</head>')) {\n return result.replace('</head>', `${initScript}\\n</head>`)\n }\n\n return result + initScript\n },\n }\n\n const sdkImportFixPlugin: Plugin = {\n name: 'seed-protocol:sdk-import-fix',\n enforce: 'post',\n transform(code, id) {\n if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {\n return null\n }\n const hasDefaultPathBrowserifyImport =\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"]/.test(code)\n if (!hasDefaultPathBrowserifyImport) {\n return null\n }\n const transformed = code.replace(\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"];/g,\n \"import * as path from 'path';\",\n )\n if (transformed === code) {\n return null\n }\n return { code: transformed, map: null }\n },\n }\n\n const plugins: Plugin[] = [configPlugin, mainPlugin, sdkImportFixPlugin]\n\n if (includeNodePolyfills) {\n log('Including vite-plugin-node-polyfills with default settings')\n // vite-plugin-node-polyfills ≥0.27 returns Plugin[]; older versions returned a single Plugin.\n const polyfillPlugins = nodePolyfills({\n // Let fs be handled by @zenfs/core instead of polyfills\n exclude: ['readline',],\n // Common set of browser-friendly polyfills used by many deps\n include: ['path', 'buffer', 'events', 'string_decoder', 'util'],\n globals: {\n Buffer: true,\n global: true,\n process: true,\n },\n protocolImports: true,\n }) as unknown as Plugin | Plugin[]\n if (Array.isArray(polyfillPlugins)) {\n plugins.push(...polyfillPlugins)\n } else {\n plugins.push(polyfillPlugins)\n }\n }\n\n // After nodePolyfills so config() can overwrite its bare shim aliases.\n if (Object.keys(polyfillShimAliasObj).length > 0) {\n plugins.push(polyfillResolvePlugin)\n }\n\n return plugins\n}\n"],"mappings":";;;;;;AAOA,IAAME,IAAOC,EAAc,YAAY,GAAG,GAsDpCC,IAAoD;CACxD,QAAY;CACZ,SAAY;CACZ,QAAY;CACZ,WAAY;CACZ,YAAY;AACd;AAOA,SAASC,EAAwB,GAAsB;CACrD,OAAOC,EACJ,QAAQ,sBAAsB,MAAM,IAAI,OAAOC,EAAE,MAAM,CAAC,CAAC,CACzD,QAAQ,gBAAgB,MAAM,IAAI,OAAOA,EAAE,MAAM,CAAC,CAAC,CACnD,QAAQ,wBAAwB,MAAM,MAAM,IAAI,OAAOA,EAAE,SAAS,CAAC,IAAI,GAAG,CAAC,CAC3E,QAAQ,uBAAuB,MAAM,OAAM,IAAI,OAAOA,EAAE,SAAS,CAAC,IAAI,IAAG,CAAC,CAC1E,QAAQ,uBAAuB,MAAM,MAAM,IAAI,OAAOA,EAAE,SAAS,CAAC,IAAI,GAAG;AAC9E;AAYA,SAASC,EAAqB,GAA8B;CAC1D,IAAMC,IAAWJ,EAAwBK,CAAO,GAC1CC,IAAoB,CAAC;CAE3B,KAAK,IAAM,CAACC,GAAMC,MAAgB,OAAO,QAAQT,CAAyB,GAAG;EAE3E,IAA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,OAHIuL,MAAgBvL,IACX,OAEF;KAAE,MAAMuL;KAAa,KAAK;IAAK;GACxC;EAGmD;CAAkB;CAEvE,IAAIxD,GAAsB;EACxB,EAAI,4DAA4D;EAEhE,IAAMyD,IAAkBC,EAAc;GAEpC,SAAS,CAAC,UAAW;GAErB,SAAS;IAAC;IAAQ;IAAU;IAAU;IAAkB;GAAM;GAC9D,SAAS;IACP,QAAQ;IACR,QAAQ;IACR,SAAS;GACX;GACA,iBAAiB;EACnB,CAAC;EACD,AAAI,MAAM,QAAQD,CAAe,IAC/BlC,EAAQ,KAAK,GAAGkC,CAAe,IAE/BlC,EAAQ,KAAKkC,CAAe;CAEhC;CAOA,OAJI,OAAO,KAAK1D,CAAoB,CAAC,CAAC,SAAS,KAC7CwB,EAAQ,KAAKF,CAAqB,GAG7BE;AACT"}
1
+ {"version":3,"file":"index.js","names":["fs","path","_req","createRequire","BROWSER_DANGEROUS_GLOBALS","isAstNode","value","isVariableReference","parent","key","containsTypeofOf","node","name","child","c","isGuarded","ancestor","viaKey","findDangerousGlobals","program","rootScope","parseAst","code","attachScopes","hits","lineStarts","i","lineIndexOf","lo","hi","mid","offset","stack","outerScope","scope","lineIndex","lineStart","lineEnd","context","children","item","DEFAULT_FS_MODULES","SDK_DIST_DIR","fileURLToPath","ARWEAVE_SHIM_FILE","DEBUG_SHIM_FILE","STREAM_SHIM_FILE","FRAGILE_RENDERER_OPTIMIZE_INCLUDES","EAS_OPTIMIZE_INCLUDES","APP_OPTIONAL_OPTIMIZE_INCLUDES","SEED_SHARED_STATE_PACKAGES","seedSharedStateDeps","include","dedupe","sdkAtRoot","isResolvableFromRoot","appRoot","pkg","CJS_OPTIMIZE_INCLUDES","DEFAULT_ISOLATION_HEADERS","resolveIsolationHeaders","option","overrides","isolationHeadersNotSetBy","userKeys","headers","isolationHeaders","effectiveIsolationHeaders","userValues","userValue","applyIsolationHeaderMiddleware","apply","res","originalWriteHead","args","next","pushBunPackageCandidates","bunDir","bunPrefix","packageName","entry","candidates","relativePath","root","dir","resolvePackageFile","sdkRoot","pkgJson","pkgJsonPath","cwdNodeModules","bunInstallRoot","findNodeModulesBunRoot","candidate","startDir","isFsAllowCovering","filePath","allow","uri","realpathOrResolve","p","collectDevServerFsAllowPaths","paths","add","sdkPkgDir","ensureDevServerFsAllow","added","normalizeAliasEntries","alias","find","replacement","mergeAliasEntries","merged","existing","keyOf","seen","additions","NODE_POLYFILL_SHIM_IDS","resolvePolyfillShimFile","resolved","shimId","esm","resolveNodePolyfillShimPaths","unresolved","id","abs","rewriteBarePolyfillShimImports","changed","replacements","bare","absLiteral","quote","from","addNodePolyfillShimAliases","aliasEntries","nodePolyfillShimAliasObject","POLYFILL_ALIAS_FINDS_TO_REPLACE","withPreferredPolyfillAliases","preferred","filtered","addRendererCompatibilityAliases","nanoidDictionaryEsm","zenfsCoreIndex","zenfsCorePath","zenfsDomIndex","debugBrowserEntry","debugShimOptimizeAliasObject","streamShimOptimizeAliasObject","optimizeDepsRolldownPatch","define","patch","seedVitePlugin","isolationHeadersOption","options","serverIsolationHeaders","previewIsolationHeaders","htmlNodeEnv","log","debug","polyfillShimPaths","unresolvedPolyfillShims","polyfillShimAliasObj","includeNodePolyfills","configPlugin","resolvedConfig","addedAllowPaths","env","mod","fsModules","target","eventEmitterEsm","arweaveBundle","userConfig","userDedupe","desiredOptimizeIncludes","resolvableOptimizeIncludes","dep","sharedStateDeps","existingOptimize","debugOptimizeAliases","streamOptimizeAliases","optimizeDeps","polyfillResolvePlugin","rewritten","plugins","server","commonjsOptions","nodeOnlyExternal","userExternal","re","importer","isResolved","allHits","chunkName","asset","bundle","hit","byChunk","list","chunk","h","shimScript","result","html","autoInit","initScript","transformed","polyfillPlugins","nodePolyfills"],"sources":["../src/index.ts"],"sourcesContent":["import type { ConfigEnv, Plugin, PreviewServer, UserConfig, ViteDevServer } from 'vite'\nimport { parseAst } from 'vite'\nimport { attachScopes, type AttachedScope } from '@rollup/pluginutils'\nimport fs from 'node:fs'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { nodePolyfills } from 'vite-plugin-node-polyfills'\n\nconst _req = createRequire(import.meta.url)\n\nexport interface SeedVitePluginOptions {\n /**\n * Modules to alias to ZenFS (`@zenfs/core`, or `@zenfs/core/promises` for ids\n * containing \"promises\"). The list replaces the default; to add a module, pass\n * the defaults plus yours.\n * @default ['fs', 'fs/promises', 'node:fs', 'node:fs/promises']\n */\n fsModules?: string[]\n\n /**\n * Whether to inject a ZenFS initialization script into index.html that mounts\n * IndexedDB at `/`. Leave this false with the SDK: `client.init()` mounts OPFS\n * at `/` itself, so apps do not configure ZenFS, and this mount would only be\n * replaced. The script also imports the bare specifiers '@zenfs/core' and\n * '@zenfs/dom', which browsers cannot resolve without an import map.\n * @default false\n */\n autoInit?: boolean\n\n /**\n * Enable debug logging.\n * @default false\n */\n debug?: boolean\n\n /**\n * Whether to automatically include vite-plugin-node-polyfills with sensible defaults.\n * The SDK depends on that package and aliases its injected shim imports to absolute\n * paths, so consuming apps do not need to install vite-plugin-node-polyfills themselves.\n * Default include list omits full `stream`/`crypto` polyfills (those pull\n * stream-browserify and break Vite SSR / React Router prerender). A minimal\n * `stream` stub is still aliased so sax/rss-parser do not warn. Use `false`\n * for Framework Mode / prerender.\n * @default true\n */\n includeNodePolyfills?: boolean\n\n /**\n * Cross-origin isolation headers for sqlocal / SharedArrayBuffer / OPFS.\n * Applied in configureServer and configurePreviewServer, including writeHead,\n * because Vite `server.headers` is not copied onto Framework-Mode HTML responses.\n * Set `false` to disable. Pass `{ coop, coep, corp }` to override values.\n * A COOP/COEP/CORP value you set yourself in `server.headers` or `preview.headers`\n * (any letter case) wins over both this option and the defaults, for that server.\n * @default true (`COOP: same-origin`, `COEP: credentialless`, `CORP: same-origin`)\n */\n isolationHeaders?: boolean | {\n coop?: string\n coep?: string\n corp?: string\n }\n}\n\n// Node.js globals that are undefined in browsers and will throw at runtime.\nconst BROWSER_DANGEROUS_GLOBALS = new Set(['global', 'process', 'Buffer', '__dirname', '__filename'])\n\ninterface GlobalHit {\n global: string\n /** zero-based character offset in the chunk */\n offset: number\n /** 1-based line number */\n line: number\n /** surrounding raw source for context */\n context: string\n}\n\n// Loose ESTree node: we only read type, positions and child nodes.\ntype AstNode = { type: string; start: number; end: number; [key: string]: unknown }\ntype AstPath = { node: AstNode; key: string; parent: AstPath | null }\n\nfunction isAstNode(value: unknown): value is AstNode {\n return !!value && typeof value === 'object' && typeof (value as AstNode).type === 'string'\n}\n\n/** Whether an Identifier at `key` of `parent` reads a variable (not a property name or label). */\nfunction isVariableReference(parent: AstNode, key: string): boolean {\n switch (parent.type) {\n case 'MemberExpression':\n return key !== 'property' || !!parent.computed\n case 'Property':\n case 'MethodDefinition':\n case 'PropertyDefinition':\n case 'AccessorProperty':\n return key !== 'key' || !!parent.computed\n case 'LabeledStatement':\n case 'BreakStatement':\n case 'ContinueStatement':\n case 'MetaProperty':\n return false\n case 'ImportSpecifier':\n return key !== 'imported'\n case 'ExportSpecifier':\n return key !== 'exported'\n default:\n return true\n }\n}\n\nfunction containsTypeofOf(node: AstNode, name: string): boolean {\n if (\n node.type === 'UnaryExpression' &&\n node.operator === 'typeof' &&\n isAstNode(node.argument) &&\n node.argument.type === 'Identifier' &&\n node.argument.name === name\n ) {\n return true\n }\n for (const key of Object.keys(node)) {\n const child = node[key]\n if (Array.isArray(child)) {\n if (child.some((c) => isAstNode(c) && containsTypeofOf(c, name))) return true\n } else if (isAstNode(child) && containsTypeofOf(child, name)) {\n return true\n }\n }\n return false\n}\n\n/**\n * Whether the reference only runs behind a guard: the consequent of a\n * `typeof name` test (`if`, `?:`, `&&`/`||`), or a try block.\n */\nfunction isGuarded(path: AstPath, name: string): boolean {\n for (let child = path; child.parent; child = child.parent) {\n const ancestor = child.parent.node\n const viaKey = child.key\n if (\n (ancestor.type === 'IfStatement' || ancestor.type === 'ConditionalExpression') &&\n viaKey !== 'test' &&\n containsTypeofOf(ancestor.test as AstNode, name)\n ) {\n return true\n }\n if (\n ancestor.type === 'LogicalExpression' &&\n viaKey === 'right' &&\n containsTypeofOf(ancestor.left as AstNode, name)\n ) {\n return true\n }\n if (ancestor.type === 'TryStatement' && viaKey === 'block') return true\n }\n return false\n}\n\n/**\n * Find free references to Node-only globals in a bundled chunk. Skips names\n * the chunk declares itself (e.g. the process polyfill's own `var process`),\n * `typeof` checks, property names, and uses behind a `typeof` guard or `try`.\n * Best-effort: a chunk that fails to parse reports nothing.\n */\nfunction findDangerousGlobals(code: string): GlobalHit[] {\n let program: AstNode\n let rootScope: AttachedScope\n try {\n program = parseAst(code) as unknown as AstNode\n rootScope = attachScopes(program as never, 'scope')\n } catch {\n return []\n }\n\n const hits: GlobalHit[] = []\n const lineStarts = [0]\n for (let i = code.indexOf('\\n'); i !== -1; i = code.indexOf('\\n', i + 1)) lineStarts.push(i + 1)\n const lineIndexOf = (offset: number) => {\n let lo = 0\n let hi = lineStarts.length - 1\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1\n if (lineStarts[mid]! <= offset) lo = mid\n else hi = mid - 1\n }\n return lo\n }\n // Iterative walk: bundled chunks can nest deeper than the call stack allows.\n const stack: Array<{ path: AstPath; scope: AttachedScope }> = [\n { path: { node: program, key: '', parent: null }, scope: rootScope },\n ]\n while (stack.length > 0) {\n const { path, scope: outerScope } = stack.pop()!\n const { node } = path\n const scope = (node.scope as AttachedScope | undefined) ?? outerScope\n\n if (\n node.type === 'Identifier' &&\n BROWSER_DANGEROUS_GLOBALS.has(node.name as string) &&\n path.parent\n ) {\n const name = node.name as string\n const parent = path.parent.node\n const isTypeofOperand = parent.type === 'UnaryExpression' && parent.operator === 'typeof'\n if (\n !isTypeofOperand &&\n isVariableReference(parent, path.key) &&\n !scope.contains(name) &&\n !isGuarded(path, name)\n ) {\n const lineIndex = lineIndexOf(node.start)\n const lineStart = lineStarts[lineIndex]!\n const lineEnd = lineStarts[lineIndex + 1] ?? code.length\n const context = code\n .slice(Math.max(lineStart, node.start - 40), Math.min(lineEnd, node.end + 40))\n .trim()\n hits.push({ global: name, offset: node.start, line: lineIndex + 1, context })\n }\n continue\n }\n\n const children: AstPath[] = []\n for (const key of Object.keys(node)) {\n if (key === 'scope') continue\n const value = node[key]\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isAstNode(item)) children.push({ node: item, key, parent: path })\n }\n } else if (isAstNode(value)) {\n children.push({ node: value, key, parent: path })\n }\n }\n // Reverse so hits come out in source order.\n for (let i = children.length - 1; i >= 0; i--) stack.push({ path: children[i]!, scope })\n }\n\n return hits\n}\n\nconst DEFAULT_FS_MODULES = [\n 'fs',\n 'fs/promises',\n 'node:fs',\n 'node:fs/promises',\n]\nconst SDK_DIST_DIR = path.dirname(fileURLToPath(import.meta.url))\nconst ARWEAVE_SHIM_FILE = path.join(SDK_DIST_DIR, 'arweave-default-shim.js')\nconst DEBUG_SHIM_FILE = path.join(SDK_DIST_DIR, 'debug-default-shim.js')\nconst STREAM_SHIM_FILE = path.join(SDK_DIST_DIR, 'stream-default-shim.js')\n\n/** Fragile renderer deps pre-bundled for stable CJS/ESM interop (aligned with permapress). */\nconst FRAGILE_RENDERER_OPTIMIZE_INCLUDES = [\n 'debug',\n 'random',\n 'seedrandom',\n '@georgedoescode/generative-utils',\n 'nanoid-dictionary',\n] as const\n\n/**\n * Always force-include (do not gate on resolvePackageFile): under bun these live nested\n * under @seedprotocol/sdk, and eas-sdk's ESM named-imports CJS eas-contracts. Without\n * prebundling, Vite serves raw /@fs CJS and the browser throws\n * \"does not provide an export named 'EAS__factory'\" during SchemaEncoder encode.\n */\nconst EAS_OPTIMIZE_INCLUDES = [\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk',\n '@seedprotocol/sdk > @ethereum-attestation-service/eas-sdk > @ethereum-attestation-service/eas-contracts',\n] as const\n\n/**\n * Prebundled only when the app itself can resolve them. Vite resolves `include`\n * entries from the app root, so finding them under a linked SDK is not enough\n * (Vite would skip them with \"Failed to resolve dependency\"). The zenfs helpers\n * are bundled into the @zenfs chunks anyway; viem/isows come from\n * @seedprotocol/publish, not the SDK.\n */\nconst APP_OPTIONAL_OPTIMIZE_INCLUDES = [\n 'kerium',\n 'utilium',\n 'memium',\n 'readable-stream',\n 'viem',\n 'isows',\n] as const\n\n/**\n * Seed packages whose module-level state (registered EAS / query / Arweave clients, EAS chain,\n * Arweave gateway) must be one copy per page. With the SDK excluded from prebundling, Vite can\n * find these one at a time; a package prebundled in a later optimizer pass can load as its own\n * module instance, and query then throws DuplicateEasModuleError. Prebundling them together in\n * the first pass, and deduping the ones the app resolves, keeps one copy.\n */\nconst SEED_SHARED_STATE_PACKAGES = [\n '@seedprotocol/eas',\n '@seedprotocol/arweave',\n '@seedprotocol/query',\n] as const\n\n/**\n * `include` entries: the bare name when the app resolves the package itself, else the nested\n * form through the SDK (bun installs it under @seedprotocol/sdk). `dedupe` only gets packages\n * the app root resolves: Vite resolves deduped packages from the root, so a nested-only one\n * would fail to resolve.\n */\nfunction seedSharedStateDeps(appRoot: string): { include: string[]; dedupe: string[] } {\n const include: string[] = []\n const dedupe: string[] = []\n const sdkAtRoot = isResolvableFromRoot('@seedprotocol/sdk', appRoot)\n for (const pkg of SEED_SHARED_STATE_PACKAGES) {\n if (isResolvableFromRoot(pkg, appRoot)) {\n include.push(pkg)\n dedupe.push(pkg)\n } else if (sdkAtRoot) {\n include.push(`@seedprotocol/sdk > ${pkg}`)\n }\n }\n return { include, dedupe }\n}\n\n/** CJS packages Seed ESM default-imports. Always include (do not gate on resolve). */\nconst CJS_OPTIMIZE_INCLUDES = ['pluralize'] as const\n\nconst DEFAULT_ISOLATION_HEADERS = {\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'credentialless',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n} as const\n\nfunction resolveIsolationHeaders(\n option: SeedVitePluginOptions['isolationHeaders'],\n): Record<string, string> | null {\n if (option === false) return null\n const overrides = typeof option === 'object' && option ? option : {}\n return {\n 'Cross-Origin-Opener-Policy': overrides.coop ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Opener-Policy'],\n 'Cross-Origin-Embedder-Policy': overrides.coep ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Embedder-Policy'],\n 'Cross-Origin-Resource-Policy': overrides.corp ?? DEFAULT_ISOLATION_HEADERS['Cross-Origin-Resource-Policy'],\n }\n}\n\n/**\n * Isolation headers the user has not set in `headers` (case-insensitive), so a\n * config() hook can add them without replacing the user's values.\n */\nfunction isolationHeadersNotSetBy(\n isolationHeaders: Record<string, string>,\n headers: Record<string, unknown> | undefined,\n): Record<string, string> {\n const userKeys = new Set(Object.keys(headers ?? {}).map((key) => key.toLowerCase()))\n return Object.fromEntries(\n Object.entries(isolationHeaders).filter(([key]) => !userKeys.has(key.toLowerCase())),\n )\n}\n\n/**\n * The isolation headers the middleware sends: the user's `headers` value where\n * they set one, else ours.\n */\nfunction effectiveIsolationHeaders(\n isolationHeaders: Record<string, string>,\n headers: Record<string, unknown> | undefined,\n): Record<string, string> {\n const userValues = new Map(\n Object.entries(headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]),\n )\n return Object.fromEntries(\n Object.entries(isolationHeaders).map(([key, value]) => {\n const userValue = userValues.get(key.toLowerCase())\n return [key, userValue == null ? value : String(userValue)]\n }),\n )\n}\n\nfunction applyIsolationHeaderMiddleware(\n server: ViteDevServer | PreviewServer,\n headers: Record<string, string>,\n): void {\n server.middlewares.use((_req, res, next) => {\n const apply = () => {\n for (const [key, value] of Object.entries(headers)) {\n if (!res.getHeader(key)) {\n res.setHeader(key, value)\n }\n }\n }\n const originalWriteHead = res.writeHead.bind(res)\n res.writeHead = ((...args: Parameters<typeof res.writeHead>) => {\n apply()\n return originalWriteHead(...args)\n }) as typeof res.writeHead\n apply()\n next()\n })\n}\n\ntype AliasEntry = { find: string | RegExp; replacement: string }\n\nfunction pushBunPackageCandidates(\n bunDir: string,\n packageName: string,\n relativePath: string,\n candidates: string[],\n): void {\n if (!fs.existsSync(bunDir)) return\n // Nested scopes (@scope/name) live under .bun as @scope+name@version/...\n const bunPrefix = packageName.startsWith('@')\n ? packageName.replace('/', '+')\n : packageName\n for (const entry of fs.readdirSync(bunDir)) {\n if (!entry.startsWith(`${bunPrefix}@`) && !entry.startsWith(`${packageName}@`)) continue\n candidates.push(path.join(bunDir, entry, `node_modules/${packageName}`, relativePath))\n }\n}\n\n/** Whether a package is installed where Vite's optimizer looks for it (the app root upward). */\nfunction isResolvableFromRoot(packageName: string, root: string): boolean {\n const lookupDirs = createRequire(path.join(root, 'package.json')).resolve.paths(packageName) ?? []\n return lookupDirs.some((dir) => fs.existsSync(path.join(dir, packageName, 'package.json')))\n}\n\nfunction resolvePackageFile(packageName: string, relativePath: string): string | undefined {\n const candidates: string[] = []\n const sdkRoot = path.resolve(SDK_DIST_DIR, '..')\n\n try {\n const pkgJson = _req.resolve(`${packageName}/package.json`)\n candidates.push(path.join(path.dirname(pkgJson), relativePath))\n } catch {\n // Many packages (e.g. sqlocal) omit package.json from \"exports\". Resolve an\n // entry file and walk up to the package root instead.\n try {\n const entry = _req.resolve(packageName)\n let dir = path.dirname(entry)\n for (let i = 0; i < 8; i++) {\n const pkgJsonPath = path.join(dir, 'package.json')\n if (fs.existsSync(pkgJsonPath)) {\n try {\n const pkgName = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')).name\n if (pkgName === packageName) {\n candidates.push(path.join(dir, relativePath))\n break\n }\n } catch {\n // ignore invalid package.json\n }\n }\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n } catch {\n // package may be hoisted/unavailable in this graph\n }\n }\n\n // Linked/file installs: deps often live under the SDK package, not the app cwd.\n candidates.push(path.join(sdkRoot, 'node_modules', packageName, relativePath))\n\n const cwdNodeModules = path.join(process.cwd(), 'node_modules')\n candidates.push(path.join(cwdNodeModules, packageName, relativePath))\n\n pushBunPackageCandidates(\n path.join(cwdNodeModules, '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n pushBunPackageCandidates(\n path.join(sdkRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n const bunInstallRoot = findNodeModulesBunRoot(sdkRoot)\n if (bunInstallRoot) {\n pushBunPackageCandidates(\n path.join(bunInstallRoot, 'node_modules', '.bun'),\n packageName,\n relativePath,\n candidates,\n )\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) return candidate\n }\n return undefined\n}\n\n/** Walk up from startDir looking for a directory that contains node_modules/.bun. */\nfunction findNodeModulesBunRoot(startDir: string): string | undefined {\n let dir = path.resolve(startDir)\n for (let i = 0; i < 8; i++) {\n if (fs.existsSync(path.join(dir, 'node_modules', '.bun'))) return dir\n const parent = path.dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n return undefined\n}\n\nfunction isFsAllowCovering(allow: readonly string[], filePath: string): boolean {\n const child = path.resolve(filePath)\n return allow.some((uri) => {\n const parent = path.resolve(String(uri))\n return (\n child === parent ||\n child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep)\n )\n })\n}\n\nfunction realpathOrResolve(p: string): string {\n try {\n return fs.realpathSync(p)\n } catch {\n return path.resolve(p)\n }\n}\n\n/**\n * When the SDK is linked (file:/symlink) into an external app, sqlocal's worker\n * and sqlite-wasm assets resolve into the SDK install tree (often bun's .bun\n * store). Vite's default server.fs.allow only covers the consumer workspace, so\n * those absolute /@fs requests 403 unless we allowlist the install roots.\n */\nfunction collectDevServerFsAllowPaths(): string[] {\n const paths = new Set<string>()\n const add = (p?: string) => {\n if (!p) return\n paths.add(realpathOrResolve(p))\n }\n\n let sdkPkgDir: string\n try {\n sdkPkgDir = path.dirname(_req.resolve('@seedprotocol/sdk/package.json'))\n } catch {\n sdkPkgDir = path.resolve(SDK_DIST_DIR, '..')\n }\n add(sdkPkgDir)\n\n const bunInstallRoot = findNodeModulesBunRoot(sdkPkgDir)\n if (bunInstallRoot) add(bunInstallRoot)\n\n for (const pkg of ['sqlocal', '@sqlite.org/sqlite-wasm'] as const) {\n const pkgJson = resolvePackageFile(pkg, 'package.json')\n if (pkgJson) add(path.dirname(pkgJson))\n }\n\n return [...paths]\n}\n\nfunction ensureDevServerFsAllow(allow: string[]): string[] {\n const added: string[] = []\n for (const dir of collectDevServerFsAllowPaths()) {\n if (isFsAllowCovering(allow, dir)) continue\n allow.push(dir)\n added.push(dir)\n }\n return added\n}\n\nfunction normalizeAliasEntries(\n alias: NonNullable<UserConfig['resolve']>['alias'] | undefined\n): AliasEntry[] {\n if (!alias) return []\n if (Array.isArray(alias)) {\n return alias\n .filter((entry): entry is AliasEntry => !!entry && !!(entry as AliasEntry).replacement)\n .map((entry) => ({ find: entry.find, replacement: entry.replacement }))\n }\n\n return Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement: String(replacement),\n }))\n}\n\nfunction mergeAliasEntries(existing: AliasEntry[], additions: AliasEntry[]): AliasEntry[] {\n const merged = [...existing]\n const keyOf = (find: string | RegExp) =>\n typeof find === 'string' ? `s:${find}` : `r:${find.toString()}`\n const seen = new Set(merged.map((entry) => keyOf(entry.find)))\n\n for (const entry of additions) {\n const key = keyOf(entry.find)\n if (seen.has(key)) continue\n seen.add(key)\n merged.push(entry)\n }\n\n return merged\n}\n\n/** Bare IDs that vite-plugin-node-polyfills injects into every transformed module. */\nconst NODE_POLYFILL_SHIM_IDS = [\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n] as const\n\ntype NodePolyfillShimPaths = {\n buffer?: string\n global?: string\n process?: string\n}\n\n/**\n * Prefer the package \"import\" ESM build (index.js). createRequire resolves the\n * \"require\" condition (index.cjs); Vite then serves `/@fs/...cjs?import` and\n * default-import fails in the browser.\n */\nfunction resolvePolyfillShimFile(shimId: string): string {\n const resolved = _req.resolve(shimId)\n if (resolved.endsWith('.cjs')) {\n const esm = resolved.slice(0, -4) + '.js'\n if (fs.existsSync(esm)) return esm\n }\n return resolved\n}\n\nfunction resolveNodePolyfillShimPaths(): {\n paths: NodePolyfillShimPaths\n unresolved: string[]\n} {\n const paths: NodePolyfillShimPaths = {}\n const unresolved: string[] = []\n for (const id of NODE_POLYFILL_SHIM_IDS) {\n try {\n const abs = resolvePolyfillShimFile(id)\n if (id.endsWith('/buffer')) paths.buffer = abs\n else if (id.endsWith('/global')) paths.global = abs\n else if (id.endsWith('/process')) paths.process = abs\n } catch {\n unresolved.push(id)\n }\n }\n return { paths, unresolved }\n}\n\n/** Rewrite leftover bare shim package ids to absolute ESM files (post import-analysis). */\nfunction rewriteBarePolyfillShimImports(\n code: string,\n paths: NodePolyfillShimPaths,\n): string | null {\n let next = code\n let changed = false\n const replacements: Array<[string, string]> = []\n if (paths.buffer) {\n replacements.push(['vite-plugin-node-polyfills/shims/buffer', paths.buffer])\n }\n if (paths.global) {\n replacements.push(['vite-plugin-node-polyfills/shims/global', paths.global])\n }\n if (paths.process) {\n replacements.push(['vite-plugin-node-polyfills/shims/process', paths.process])\n }\n for (const [bare, abs] of replacements) {\n const absLiteral = JSON.stringify(abs)\n for (const quote of ['\"', \"'\"] as const) {\n const from = `${quote}${bare}${quote}`\n if (!next.includes(from)) continue\n next = next.split(from).join(absLiteral)\n changed = true\n }\n }\n return changed ? next : null\n}\n\n/**\n * Alias polyfill shim bare imports + buffer/process/global module ids to absolute\n * paths resolved from this package. Nested installs under @seedprotocol/sdk are\n * invisible to consumer-project resolution (and to Vite 8's Rolldown optimizer)\n * unless we rewrite to absolute files.\n */\nfunction addNodePolyfillShimAliases(\n aliasEntries: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): void {\n if (paths.buffer) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/buffer', replacement: paths.buffer },\n { find: /^buffer$/, replacement: paths.buffer },\n { find: /^node:buffer$/, replacement: paths.buffer },\n )\n }\n if (paths.global) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/global', replacement: paths.global },\n { find: /^global$/, replacement: paths.global },\n )\n }\n if (paths.process) {\n aliasEntries.push(\n { find: 'vite-plugin-node-polyfills/shims/process', replacement: paths.process },\n { find: /^process$/, replacement: paths.process },\n { find: /^node:process$/, replacement: paths.process },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps.rolldown/rollup resolve (string keys). */\nfunction nodePolyfillShimAliasObject(paths: NodePolyfillShimPaths): Record<string, string> {\n const alias: Record<string, string> = {}\n if (paths.buffer) {\n alias['vite-plugin-node-polyfills/shims/buffer'] = paths.buffer\n alias.buffer = paths.buffer\n alias['node:buffer'] = paths.buffer\n }\n if (paths.global) {\n alias['vite-plugin-node-polyfills/shims/global'] = paths.global\n alias.global = paths.global\n }\n if (paths.process) {\n alias['vite-plugin-node-polyfills/shims/process'] = paths.process\n alias.process = paths.process\n alias['node:process'] = paths.process\n }\n return alias\n}\n\nconst POLYFILL_ALIAS_FINDS_TO_REPLACE = new Set([\n 'vite-plugin-node-polyfills/shims/buffer',\n 'vite-plugin-node-polyfills/shims/global',\n 'vite-plugin-node-polyfills/shims/process',\n 'buffer',\n 'node:buffer',\n 'process',\n 'node:process',\n 'global',\n])\n\n/**\n * Put absolute polyfill aliases first and drop bare/package-id entries that\n * vite-plugin-node-polyfills may have added for the same modules (first match wins).\n */\nfunction withPreferredPolyfillAliases(\n existing: AliasEntry[],\n paths: NodePolyfillShimPaths,\n): AliasEntry[] {\n const preferred: AliasEntry[] = []\n addNodePolyfillShimAliases(preferred, paths)\n if (preferred.length === 0) return existing\n\n const filtered = existing.filter((entry) => {\n if (typeof entry.find !== 'string') return true\n return !POLYFILL_ALIAS_FINDS_TO_REPLACE.has(entry.find)\n })\n return [...preferred, ...filtered]\n}\n\nfunction addRendererCompatibilityAliases(aliasEntries: AliasEntry[]): void {\n const nanoidDictionaryEsm = resolvePackageFile(\n 'nanoid-dictionary',\n 'dist/dictionary.esm.js',\n )\n if (nanoidDictionaryEsm) {\n aliasEntries.push({\n find: /^nanoid-dictionary$/,\n replacement: nanoidDictionaryEsm,\n })\n }\n\n const zenfsCoreIndex = resolvePackageFile('@zenfs/core', 'dist/index.js')\n const zenfsCorePath = resolvePackageFile('@zenfs/core', 'dist/path.js')\n if (zenfsCoreIndex) {\n aliasEntries.push({ find: /^@zenfs\\/core$/, replacement: zenfsCoreIndex })\n }\n if (zenfsCorePath) {\n aliasEntries.push({ find: /^@zenfs\\/core\\/path$/, replacement: zenfsCorePath })\n }\n\n const zenfsDomIndex = resolvePackageFile('@zenfs/dom', 'dist/index.js')\n if (zenfsDomIndex) {\n aliasEntries.push({ find: /^@zenfs\\/dom$/, replacement: zenfsDomIndex })\n }\n\n if (fs.existsSync(DEBUG_SHIM_FILE)) {\n // Only alias the package root. Do not alias debug/src/browser.js to this shim:\n // the shim imports that path and aliasing it back creates a circular module.\n aliasEntries.push({ find: /^debug$/, replacement: DEBUG_SHIM_FILE })\n }\n\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n if (debugBrowserEntry) {\n aliasEntries.push({\n find: /^debug\\/src\\/browser\\.js$/,\n replacement: debugBrowserEntry,\n })\n }\n\n // Minimal stream stub (not stream-browserify) so sax/rss-parser init is quiet.\n if (fs.existsSync(STREAM_SHIM_FILE)) {\n aliasEntries.push(\n { find: /^stream$/, replacement: STREAM_SHIM_FILE },\n { find: /^node:stream$/, replacement: STREAM_SHIM_FILE },\n )\n }\n}\n\n/** Object-form aliases for optimizeDeps pre-bundle (debug shim subpath). */\nfunction debugShimOptimizeAliasObject(): Record<string, string> {\n const debugBrowserEntry = resolvePackageFile('debug', 'src/browser.js')\n return debugBrowserEntry ? { 'debug/src/browser.js': debugBrowserEntry } : {}\n}\n\n/** Object-form aliases so optimizeDeps prebundles (rss-parser → sax) use our stream stub. */\nfunction streamShimOptimizeAliasObject(): Record<string, string> {\n if (!fs.existsSync(STREAM_SHIM_FILE)) return {}\n return {\n stream: STREAM_SHIM_FILE,\n 'node:stream': STREAM_SHIM_FILE,\n }\n}\n\ntype OptimizeDepsConfig = NonNullable<UserConfig['optimizeDeps']>\n\n/**\n * Build a Vite 8 `optimizeDeps.rolldownOptions` patch for a plugin `config()` hook.\n *\n * Returns only what this plugin adds. Vite deep-merges hook results into the\n * user config and concatenates arrays, so echoing existing options back would\n * duplicate them — e.g. vite-plugin-node-polyfills' optimizer banner plugin,\n * which then declares `__buffer_polyfill` twice in every prebundled chunk.\n * Legacy `esbuildOptions.define` is carried into `transform.define` so\n * definitions survive the move off the deprecated key.\n */\nfunction optimizeDepsRolldownPatch(\n existing: OptimizeDepsConfig | undefined,\n patch: {\n define?: Record<string, string>\n alias?: Record<string, string>\n },\n): OptimizeDepsConfig['rolldownOptions'] {\n const define = {\n ...existing?.esbuildOptions?.define,\n ...patch.define,\n }\n const alias = patch.alias ?? {}\n\n return {\n ...(Object.keys(define).length > 0 ? { transform: { define } } : {}),\n ...(Object.keys(alias).length > 0 ? { resolve: { alias } } : {}),\n }\n}\n\n/**\n * Minimal Vite plugin to make the SDK work in browser/Electron renderer:\n * - Aliases fs → @zenfs/core (and promises variant)\n * - Aliases path → path-browserify\n * - Ensures CommonJS in SDK dist is transformed by Vite's CommonJS plugin\n * - Allowlists linked SDK / sqlocal worker paths on server.fs.allow for Vite dev\n * - Optionally wires up vite-plugin-node-polyfills with safe defaults\n *\n * This plugin assumes the SDK does not bundle Node-only code in the browser entry.\n * For Electron, Node-only work (e.g. better-sqlite3) should run in the\n * main process; the renderer should only use browser-safe SDK usage.\n *\n * For the renderer build:\n * - Use the SDK's ESM entry: import from '@seedprotocol/sdk' (resolves to dist/main.js).\n * - Do not configure ZenFS yourself: `client.init()` mounts OPFS at `/`.\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = DEFAULT_FS_MODULES,\n autoInit = false,\n debug = false,\n includeNodePolyfills = true,\n isolationHeaders: isolationHeadersOption,\n } = options\n\n const isolationHeaders = resolveIsolationHeaders(isolationHeadersOption)\n // Replaced in configResolved by the values the user's server/preview headers leave us.\n let serverIsolationHeaders = isolationHeaders\n let previewIsolationHeaders = isolationHeaders\n let htmlNodeEnv = 'production'\n\n const log = (...args: unknown[]) => {\n if (debug) console.log('[seed-vite-plugin]', ...args)\n }\n\n const { paths: polyfillShimPaths, unresolved: unresolvedPolyfillShims } =\n resolveNodePolyfillShimPaths()\n const polyfillShimAliasObj = nodePolyfillShimAliasObject(polyfillShimPaths)\n\n if (includeNodePolyfills && unresolvedPolyfillShims.length > 0) {\n console.warn(\n '[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims from the SDK package:\\n' +\n unresolvedPolyfillShims.map((id) => ` - ${id}`).join('\\n') +\n '\\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/sdk, or set includeNodePolyfills: false and configure polyfills yourself.',\n )\n } else if (unresolvedPolyfillShims.length === 0) {\n log('Resolved vite-plugin-node-polyfills shims to absolute paths')\n }\n\n /**\n * Pre-plugin: configure aliases and optimizeDeps.\n */\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n if (isolationHeaders) {\n serverIsolationHeaders = effectiveIsolationHeaders(\n isolationHeaders,\n resolvedConfig.server.headers,\n )\n previewIsolationHeaders = effectiveIsolationHeaders(\n isolationHeaders,\n resolvedConfig.preview.headers,\n )\n }\n const addedAllowPaths = ensureDevServerFsAllow(resolvedConfig.server.fs.allow)\n if (addedAllowPaths.length > 0) {\n log(\n 'Extended server.fs.allow for linked SDK / sqlocal worker paths:',\n addedAllowPaths,\n )\n }\n },\n\n config(userConfig, env) {\n if (env?.mode) {\n htmlNodeEnv = env.mode\n }\n const aliasEntries: AliasEntry[] = []\n for (const mod of fsModules) {\n const isPromises = mod.includes('promises')\n const target = isPromises ? '@zenfs/core/promises' : '@zenfs/core'\n aliasEntries.push({ find: mod, replacement: target })\n }\n\n const eventEmitterEsm = resolvePackageFile('eventemitter3', 'dist/eventemitter3.esm.js')\n if (eventEmitterEsm) {\n aliasEntries.push(\n { find: 'eventemitter3', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.mjs', replacement: eventEmitterEsm },\n { find: 'eventemitter3/index.js', replacement: eventEmitterEsm },\n )\n }\n\n const arweaveBundle = resolvePackageFile('arweave', 'bundles/web.bundle.js')\n if (arweaveBundle) {\n aliasEntries.push(\n { find: /^arweave$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/web\\/index\\.js$/, replacement: ARWEAVE_SHIM_FILE },\n { find: /^arweave\\/bundles\\/web\\.bundle\\.js$/, replacement: arweaveBundle },\n )\n }\n\n addRendererCompatibilityAliases(aliasEntries)\n // Node polyfill shim aliases come from seed-protocol:polyfill-resolve, ahead of all others.\n\n // Vite merges a returned alias list *before* the existing one, so returning ours\n // would let it shadow the user's. Append to the config in place instead (Vite's\n // documented escape hatch when merging can't express the order), skipping finds\n // the user already set, so user aliases still match first.\n userConfig.resolve = {\n ...userConfig.resolve,\n alias: mergeAliasEntries(normalizeAliasEntries(userConfig.resolve?.alias), aliasEntries),\n }\n const userDedupe = new Set(userConfig.resolve.dedupe ?? [])\n\n const desiredOptimizeIncludes = [\n '@zenfs/core',\n '@zenfs/dom',\n ...FRAGILE_RENDERER_OPTIMIZE_INCLUDES,\n ]\n const appRoot = path.resolve(userConfig.root ?? process.cwd())\n const resolvableOptimizeIncludes = [\n ...desiredOptimizeIncludes.filter((dep) => !!resolvePackageFile(dep, 'package.json')),\n ...APP_OPTIONAL_OPTIMIZE_INCLUDES.filter((dep) => isResolvableFromRoot(dep, appRoot)),\n ]\n\n const sharedStateDeps = seedSharedStateDeps(appRoot)\n\n const existingOptimize = userConfig.optimizeDeps\n const debugOptimizeAliases = debugShimOptimizeAliasObject()\n const streamOptimizeAliases = streamShimOptimizeAliasObject()\n\n // Only this plugin's additions: Vite concatenates them onto the user's arrays.\n const optimizeDeps: UserConfig['optimizeDeps'] = {\n exclude: [\n // Do not prebundle the SDK itself or clearly node-only tools\n '@seedprotocol/sdk',\n 'drizzle-orm',\n 'better-sqlite3',\n // sqlocal uses workers and should not be prebundled\n 'sqlocal',\n ],\n include: [\n ...resolvableOptimizeIncludes,\n ...sharedStateDeps.include,\n ...EAS_OPTIMIZE_INCLUDES,\n ...CJS_OPTIMIZE_INCLUDES,\n ],\n // Keep `global` shim in optimizer Rolldown options; top-level Vite `define`\n // can be rejected by Rolldown in some consumer setups.\n rolldownOptions: optimizeDepsRolldownPatch(existingOptimize, {\n define: { global: 'globalThis' },\n alias: {\n ...debugOptimizeAliases,\n ...streamOptimizeAliases,\n ...polyfillShimAliasObj,\n },\n }),\n }\n\n return {\n // Apply global → globalThis for Rollup production builds too.\n // optimizeDeps.rolldownOptions.transform.define only covers the dev pre-bundle step;\n // this top-level define is picked up by @rollup/plugin-replace during build\n // and covers all chunks, including code-split migrator/commonjs-helper chunks.\n define: {\n ...(userConfig.define ?? {}),\n global: 'globalThis',\n // process is referenced by path-browserify and other CJS modules.\n // Point at globalThis.process which is set by the synchronous inline\n // shim script injected into index.html before any modules load.\n // Do not define process.env.NODE_ENV — Vite already sets it from mode,\n // and forcing \"production\" during `vite serve` compiles out React Refresh.\n 'process.browser': 'true',\n 'process.platform': '\"browser\"',\n },\n // Only this plugin's dedupe entries: Vite concatenates them onto the user's.\n resolve: {\n // Prevent duplicate React/thirdweb instances when @seedprotocol/publish is workspace-linked.\n // Multiple copies break context (e.g. useActiveAccount must be used within ThirdwebProvider).\n // Also dedupe XState and Seed packages: two xstate copies cause Object.assign _version errors;\n // two @seedprotocol/sdk copies leave BaseDb facade / Db.appDb on different module instances\n // (\"App DB not found\", undefined.$with on PostsPage).\n // Two eas / arweave / query copies split registered clients and chain (see SEED_SHARED_STATE_PACKAGES).\n // Two @zenfs copies leave configureSingle / WebAccess on different module instances\n // and can remount OPFS against a stale handle.\n dedupe: Array.from(\n new Set([\n 'react',\n 'react-dom',\n 'thirdweb',\n 'xstate',\n '@xstate/react',\n '@seedprotocol/sdk',\n '@seedprotocol/react',\n '@seedprotocol/publish',\n '@seedprotocol/feed',\n ...sharedStateDeps.dedupe,\n '@zenfs/core',\n '@zenfs/dom',\n ]),\n ).filter((dep) => !userDedupe.has(dep)),\n },\n optimizeDeps,\n // Only the headers the user has not set: Vite deep-merges these into theirs.\n // Preview falls back to server.headers when preview.headers is unset, so\n // only touch preview.headers when the user set it.\n ...(isolationHeaders\n ? {\n server: {\n headers: isolationHeadersNotSetBy(isolationHeaders, userConfig.server?.headers),\n },\n ...(userConfig.preview?.headers\n ? {\n preview: {\n headers: isolationHeadersNotSetBy(isolationHeaders, userConfig.preview.headers),\n },\n }\n : {}),\n }\n : {}),\n }\n },\n }\n\n /**\n * Runs after vite-plugin-node-polyfills so absolute shim aliases win over its bare\n * package-id aliases in both resolve.alias and the Rolldown optimizeDeps graph.\n */\n const polyfillResolvePlugin: Plugin = {\n name: 'seed-protocol:polyfill-resolve',\n enforce: 'post',\n\n config(userConfig) {\n if (Object.keys(polyfillShimAliasObj).length === 0) return\n\n // Rewrite resolve.alias in place rather than returning it: this drops entries\n // (a returned list can only add), and Vite would concatenate a returned copy\n // onto the existing list, duplicating every alias.\n userConfig.resolve = {\n ...userConfig.resolve,\n alias: withPreferredPolyfillAliases(\n normalizeAliasEntries(userConfig.resolve?.alias),\n polyfillShimPaths,\n ),\n }\n\n return {\n optimizeDeps: {\n rolldownOptions: optimizeDepsRolldownPatch(undefined, {\n // Later merges overwrite vite-plugin-node-polyfills' serve-time\n // `global: 'global'` define and its bare shim-id aliases.\n define: { global: 'globalThis' },\n alias: polyfillShimAliasObj,\n }),\n },\n }\n },\n\n resolveId: {\n order: 'pre',\n handler(id) {\n // Always rewrite injected shim package ids (safe even if nested under the SDK).\n if (id === 'vite-plugin-node-polyfills/shims/buffer') {\n return polyfillShimPaths.buffer ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/global') {\n return polyfillShimPaths.global ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/process') {\n return polyfillShimPaths.process ?? null\n }\n // Only remap node globals when we own the polyfills plugin config.\n if (!includeNodePolyfills) return null\n if (id === 'buffer' || id === 'node:buffer') return polyfillShimPaths.buffer ?? null\n if (id === 'global') return polyfillShimPaths.global ?? null\n if (id === 'process' || id === 'node:process') return polyfillShimPaths.process ?? null\n return null\n },\n },\n\n transform: {\n // Must emit absolute shim paths: order \"post\" runs after import-analysis.\n order: 'post',\n handler(code) {\n const rewritten = rewriteBarePolyfillShimImports(code, polyfillShimPaths)\n return rewritten ? { code: rewritten, map: null } : null\n },\n },\n }\n\n /**\n * Post-plugin: build configuration + optional ZenFS init.\n */\n const mainPlugin: Plugin = {\n name: 'seed-protocol:main',\n enforce: 'post',\n\n configureServer(server) {\n if (serverIsolationHeaders) applyIsolationHeaderMiddleware(server, serverIsolationHeaders)\n },\n\n configurePreviewServer(server) {\n if (previewIsolationHeaders) applyIsolationHeaderMiddleware(server, previewIsolationHeaders)\n },\n\n config(userConfig) {\n // Only this plugin's additions: Vite deep-merges them into the user's build\n // config and concatenates arrays. Echoing `...userConfig.build` back also\n // returned both `rollupOptions` and `rolldownOptions` (Vite 8 aliases one\n // to the other), which made Vite warn on every run.\n const commonjsOptions = {\n // Always process node_modules and the SDK dist so require() is transformed\n include: [/node_modules/, /seed-protocol-sdk[\\\\/]+dist[\\\\/]/],\n // sqlocal is ESM and uses workers - don't transform it\n exclude: [/node_modules[\\\\/]+sqlocal[\\\\/]/],\n transformMixedEsModules: true,\n }\n\n // Externalize Node.js-only packages that should never be bundled for the browser\n // (better-sqlite3: native SQLite binding, Node.js only), by bare id or resolved path.\n const nodeOnlyExternal = [/^better-sqlite3(?:\\/|$)/, /[\\\\/]better-sqlite3(?:[\\\\/]|$)/]\n const userExternal = (userConfig.build?.rolldownOptions ?? userConfig.build?.rollupOptions)\n ?.external\n // A user external function can't be concatenated with patterns, so wrap it.\n // Otherwise return patterns, which Vite appends to the user's list.\n const external =\n typeof userExternal === 'function'\n ? (id: string, importer: string | undefined, isResolved: boolean) =>\n nodeOnlyExternal.some((re) => re.test(id)) || userExternal(id, importer, isResolved)\n : nodeOnlyExternal\n\n // Worker options are TOP-LEVEL in Vite config, not under build.\n // Default 'iife' breaks when workers use code-splitting (e.g. sqlocal).\n return {\n build: {\n commonjsOptions,\n rolldownOptions: { external },\n },\n ...(userConfig.worker?.format ? {} : { worker: { format: 'es' as const } }),\n }\n },\n\n generateBundle(_options, bundle) {\n const allHits: Array<{ chunk: string } & GlobalHit> = []\n\n for (const [chunkName, asset] of Object.entries(bundle)) {\n if (asset.type !== 'chunk') continue\n const hits = findDangerousGlobals(asset.code)\n for (const hit of hits) {\n allHits.push({ chunk: chunkName, ...hit })\n }\n }\n\n if (allHits.length === 0) return\n\n console.warn(\n '\\n[seed-vite-plugin] ⚠️ Bare Node.js globals detected in browser bundle chunks.' +\n ' These will throw ReferenceError at runtime unless shimmed.\\n'\n )\n const byChunk = new Map<string, typeof allHits>()\n for (const hit of allHits) {\n const list = byChunk.get(hit.chunk) ?? []\n list.push(hit)\n byChunk.set(hit.chunk, list)\n }\n for (const [chunk, hits] of byChunk) {\n console.warn(` ${chunk}`)\n for (const h of hits) {\n console.warn(` line ${h.line}: \\`${h.global}\\` — ${h.context}`)\n }\n }\n console.warn('')\n },\n\n transformIndexHtml(html) {\n // Synchronous inline script runs before any <script type=\"module\">, so\n // global and process are guaranteed to exist when CJS wrappers evaluate.\n // vite-plugin-node-polyfills injects polyfills via module imports, which\n // resolve too late for @rollup/plugin-commonjs-generated wrapper code.\n const nodeEnvLiteral = JSON.stringify(htmlNodeEnv)\n const shimScript = `<script>\n(function(){\n if(typeof globalThis.global==='undefined')globalThis.global=globalThis;\n if(typeof globalThis.process==='undefined')globalThis.process={env:{NODE_ENV:${nodeEnvLiteral}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};\n})();\n</script>`\n\n let result = html\n if (result.includes('<head>')) {\n result = result.replace('<head>', `<head>\\n${shimScript}`)\n } else {\n result = shimScript + result\n }\n\n if (!autoInit) return result\n\n const initScript = `\n<script type=\"module\">\nimport { configure } from '@zenfs/core';\nimport { IndexedDB } from '@zenfs/dom';\n\nif (!window.__seedFsReady) {\n window.__seedFsReady = configure({\n mounts: { '/': IndexedDB },\n }).catch((err) => {\n console.error('[seed-vite-plugin] ZenFS initialization failed', err);\n });\n}\n</script>`\n\n if (result.includes('</head>')) {\n return result.replace('</head>', `${initScript}\\n</head>`)\n }\n\n return result + initScript\n },\n }\n\n const sdkImportFixPlugin: Plugin = {\n name: 'seed-protocol:sdk-import-fix',\n enforce: 'post',\n transform(code, id) {\n if (!id.includes('@seedprotocol/sdk') || !id.includes('FileManager')) {\n return null\n }\n const hasDefaultPathBrowserifyImport =\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"]/.test(code)\n if (!hasDefaultPathBrowserifyImport) {\n return null\n }\n const transformed = code.replace(\n /import\\s+path\\s+from\\s+['\"]path-browserify['\"];/g,\n \"import * as path from 'path';\",\n )\n if (transformed === code) {\n return null\n }\n return { code: transformed, map: null }\n },\n }\n\n const plugins: Plugin[] = [configPlugin, mainPlugin, sdkImportFixPlugin]\n\n if (includeNodePolyfills) {\n log('Including vite-plugin-node-polyfills with default settings')\n // vite-plugin-node-polyfills ≥0.27 returns Plugin[]; older versions returned a single Plugin.\n const polyfillPlugins = nodePolyfills({\n // Let fs be handled by @zenfs/core instead of polyfills\n exclude: ['readline',],\n // Common set of browser-friendly polyfills used by many deps\n include: ['path', 'buffer', 'events', 'string_decoder', 'util'],\n globals: {\n Buffer: true,\n global: true,\n process: true,\n },\n protocolImports: true,\n }) as unknown as Plugin | Plugin[]\n if (Array.isArray(polyfillPlugins)) {\n plugins.push(...polyfillPlugins)\n } else {\n plugins.push(polyfillPlugins)\n }\n }\n\n // After nodePolyfills so config() can overwrite its bare shim aliases.\n if (Object.keys(polyfillShimAliasObj).length > 0) {\n plugins.push(polyfillResolvePlugin)\n }\n\n return plugins\n}\n"],"mappings":";;;;;;;;AASA,IAAME,IAAOC,EAAc,YAAY,GAAG,GAwDpCC,oBAA4B,IA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CuB,EAAQ,KAAKF,CAAqB,GAG7BE;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seedprotocol/vite",
3
- "version": "0.7.4-next.711.gce2b766",
3
+ "version": "0.7.4-next.793.g6dd83dd",
4
4
  "description": "Vite plugin for Seed Protocol browser/renderer apps",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,6 +26,7 @@
26
26
  "prepublishOnly": "bun run build && node ../../scripts/sync-versions.js"
27
27
  },
28
28
  "dependencies": {
29
+ "@rollup/pluginutils": "^5.1.0",
29
30
  "debug": "^4.4.1",
30
31
  "vite-plugin-node-polyfills": "^0.27.0"
31
32
  },
package/dist/easFix.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=easFix.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"easFix.d.ts","sourceRoot":"","sources":["../src/easFix.ts"],"names":[],"mappings":""}