@seedprotocol/vite 0.7.5 → 0.7.6-next.920.gdd0b533
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/README.md +33 -32
- package/dist/aliases.d.ts +15 -0
- package/dist/aliases.d.ts.map +1 -0
- package/dist/index.d.ts +29 -51
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +280 -457
- package/dist/index.js.map +1 -1
- package/dist/nodeGlobals.d.ts +22 -0
- package/dist/nodeGlobals.d.ts.map +1 -0
- package/dist/nodePolyfills.d.ts +24 -0
- package/dist/nodePolyfills.d.ts.map +1 -0
- package/package.json +3 -4
- package/dist/arweave-default-shim.d.ts +0 -4
- package/dist/arweave-default-shim.d.ts.map +0 -1
- package/dist/arweave-default-shim.js +0 -6
- package/dist/debug-default-shim.d.ts +0 -3
- package/dist/debug-default-shim.d.ts.map +0 -1
- package/dist/debug-default-shim.js +0 -19
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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) {\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,KAAK,GAAGuB,CAAe,IAE/BvB,EAAQ,KAAKuB,CAAe;CAEhC;CAOA,OAJI,OAAO,KAAK9C,CAAoB,CAAC,CAAC,SAAS,KAC7CuB,EAAQ,KAAKF,CAAqB,GAG7BE;AACT"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["fs","path","zenfsModuleFor","fsModule","DEFAULT_ISOLATION_HEADERS","resolveIsolationHeaders","option","overrides","isolationHeadersNotSetBy","userKeys","headers","key","isolationHeaders","effectiveIsolationHeaders","userValues","value","userValue","normalizeAliasEntries","alias","entry","find","replacement","mergeAliasEntries","merged","existing","keyOf","seen","additions","appendAliases","userConfig","BROWSER_DANGEROUS_GLOBALS","isAstNode","isVariableReference","parent","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","warnAboutNodeGlobals","allHits","chunkName","asset","bundle","hit","byChunk","list","chunk","h","_req","createRequire","STREAM_SHIM_FILE","fileURLToPath","NODE_POLYFILL_SHIM_IDS","resolvePolyfillShimFile","resolved","shimId","esm","resolveNodePolyfillShimPaths","paths","unresolved","id","abs","rewriteBarePolyfillShimImports","next","changed","replacements","bare","absLiteral","quote","from","addNodePolyfillShimAliases","aliasEntries","nodePolyfillShimAliasObject","POLYFILL_ALIAS_FINDS_TO_REPLACE","withPreferredPolyfillAliases","preferred","filtered","optimizeDepsRolldownPatch","define","patch","nodePolyfillPlugins","shimPaths","shimAliasObj","log","streamAliases","htmlNodeEnv","globalsPlugin","env","userDefine","shimScript","html","polyfillResolvePlugin","rewritten","polyfills","nodePolyfills","DEDUPE_CANDIDATES","findPackageDir","dir","fromDir","candidate","packageName","sdkServePaths","installed","appRoot","dirs","pkg","isCoveredBy","allow","applyIsolationHeaderMiddleware","apply","res","originalWriteHead","args","seedVitePlugin","isolationHeadersOption","options","serverIsolationHeaders","previewIsolationHeaders","debug","fsModules","mod","userDedupe","dedupe","resolvedConfig","added","server","includeNodePolyfills"],"sources":["../../bundler-core/dist/index.js","../src/aliases.ts","../src/nodeGlobals.ts","../src/nodePolyfills.ts","../src/index.ts"],"sourcesContent":["/**\n * Settings shared by the Seed bundler integrations (@seedprotocol/vite, @seedprotocol/next).\n * Each package inlines this module at build time, so keep it dependency-free.\n */\n/** The ZenFS module an aliased `fs` specifier resolves to. */\nexport function zenfsModuleFor(fsModule) {\n return fsModule.includes('promises') ? '@zenfs/core/promises' : '@zenfs/core';\n}\n/** Cross-origin isolation headers SQLite WASM, SharedArrayBuffer and OPFS need. */\nexport const DEFAULT_ISOLATION_HEADERS = {\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Embedder-Policy': 'credentialless',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n};\n/** Header name to value, or `null` when the option disables the headers. */\nexport function resolveIsolationHeaders(option) {\n if (option === false)\n 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 * Isolation headers the user has not set in `headers` (case-insensitive), so an\n * integration can add them without replacing the user's values.\n */\nexport function isolationHeadersNotSetBy(isolationHeaders, headers) {\n const userKeys = new Set(Object.keys(headers ?? {}).map((key) => key.toLowerCase()));\n return Object.fromEntries(Object.entries(isolationHeaders).filter(([key]) => !userKeys.has(key.toLowerCase())));\n}\n/**\n * The isolation headers to send: the user's `headers` value where they set one, else ours.\n */\nexport function effectiveIsolationHeaders(isolationHeaders, headers) {\n const userValues = new Map(Object.entries(headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));\n return Object.fromEntries(Object.entries(isolationHeaders).map(([key, value]) => {\n const userValue = userValues.get(key.toLowerCase());\n return [key, userValue == null ? value : String(userValue)];\n }));\n}\n//# sourceMappingURL=index.js.map","import type { UserConfig } from 'vite'\n\nexport type AliasEntry = { find: string | RegExp; replacement: string }\n\nexport function 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 return Object.entries(alias).map(([find, replacement]) => ({\n find,\n replacement: String(replacement),\n }))\n}\n\n/** `existing` plus the `additions` whose find it doesn't already have, after it. */\nexport function 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 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 return merged\n}\n\n/**\n * Append aliases to the user's config in place. Vite merges a returned alias list *before*\n * the existing one, so returning ours would let it shadow the user's; appending (Vite's\n * documented escape hatch when merging can't express the order) keeps user aliases first.\n */\nexport function appendAliases(userConfig: UserConfig, additions: AliasEntry[]): void {\n if (additions.length === 0) return\n userConfig.resolve = {\n ...userConfig.resolve,\n alias: mergeAliasEntries(normalizeAliasEntries(userConfig.resolve?.alias), additions),\n }\n}\n","import { parseAst } from 'vite'\nimport { attachScopes, type AttachedScope } from '@rollup/pluginutils'\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\nexport interface 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 */\nexport function 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\n/** Warn about free references to Node-only globals in the bundle's chunks (`debug: true`). */\nexport function warnAboutNodeGlobals(\n bundle: Record<string, { type: string; code?: string }>,\n): void {\n const allHits: Array<{ chunk: string } & GlobalHit> = []\n for (const [chunkName, asset] of Object.entries(bundle)) {\n if (asset.type !== 'chunk' || asset.code === undefined) continue\n for (const hit of findDangerousGlobals(asset.code)) allHits.push({ chunk: chunkName, ...hit })\n }\n if (allHits.length === 0) return\n\n console.warn(\n '\\n[seed-vite-plugin] Bare Node.js globals in browser chunks. They throw ReferenceError at ' +\n 'runtime if that code runs; set includeNodePolyfills: true if it does.\\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) console.warn(` line ${h.line}: \\`${h.global}\\` — ${h.context}`)\n }\n console.warn('')\n}\n","import type { Plugin, UserConfig } 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'\nimport { appendAliases, normalizeAliasEntries, type AliasEntry } from './aliases'\n\n// `includeNodePolyfills: true`. The SDK doesn't need any of this; it is for apps whose other\n// dependencies use Node built-ins or the `Buffer` / `process` / `global` globals.\n\nconst _req = createRequire(import.meta.url)\nconst STREAM_SHIM_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'stream-default-shim.js')\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\ntype OptimizeDepsConfig = NonNullable<UserConfig['optimizeDeps']>\n\n/**\n * 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 */\nexport function 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 * vite-plugin-node-polyfills (path, buffer, events, string_decoder, util and the Buffer /\n * process / global globals), with its shim imports resolved from this package so apps don't\n * install it, a minimal `stream` stub, and inline `global` / `process` shims in index.html.\n */\nexport function nodePolyfillPlugins(log: (...args: unknown[]) => void): Plugin[] {\n const { paths: shimPaths, unresolved } = resolveNodePolyfillShimPaths()\n const shimAliasObj = nodePolyfillShimAliasObject(shimPaths)\n if (unresolved.length > 0) {\n console.warn(\n '[seed-vite-plugin] Could not resolve vite-plugin-node-polyfills shims:\\n' +\n unresolved.map((id) => ` - ${id}`).join('\\n') +\n '\\nNode polyfill globals may fail to resolve. Reinstall @seedprotocol/vite.',\n )\n } else {\n log('Resolved vite-plugin-node-polyfills shims to absolute paths')\n }\n\n // Minimal stream stub (not stream-browserify, which breaks Vite SSR / React Router prerender)\n // so sax / rss-parser init is quiet.\n const streamAliases: Record<string, string> = fs.existsSync(STREAM_SHIM_FILE)\n ? { stream: STREAM_SHIM_FILE, 'node:stream': STREAM_SHIM_FILE }\n : {}\n let htmlNodeEnv = 'production'\n\n const globalsPlugin: Plugin = {\n name: 'seed-protocol:node-globals',\n enforce: 'pre',\n\n config(userConfig, env) {\n if (env?.mode) htmlNodeEnv = env.mode\n appendAliases(\n userConfig,\n Object.entries(streamAliases).map(([find, replacement]): AliasEntry => ({\n find: new RegExp(`^${find}$`),\n replacement,\n })),\n )\n const userDefine = userConfig.define ?? {}\n // Not process.env.NODE_ENV: Vite sets it from the mode, and forcing \"production\" during\n // `vite serve` compiles out React Refresh.\n const define = Object.fromEntries(\n Object.entries({\n global: 'globalThis',\n 'process.browser': 'true',\n 'process.platform': '\"browser\"',\n }).filter(([key]) => !(key in userDefine)),\n )\n return {\n define,\n optimizeDeps: {\n // Keep the `global` shim in the optimizer's Rolldown options too; top-level `define`\n // only covers app code and build chunks.\n rolldownOptions: optimizeDepsRolldownPatch(userConfig.optimizeDeps, {\n define: { global: 'globalThis' },\n alias: { ...streamAliases, ...shimAliasObj },\n }),\n },\n }\n },\n\n transformIndexHtml(html) {\n // A classic script runs before any module, so `global` and `process` exist when CJS\n // wrappers evaluate; the polyfills plugin injects module imports, which load too late.\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:${JSON.stringify(htmlNodeEnv)}},browser:true,version:'v18.0.0',versions:{},platform:'browser',cwd:function(){return'/'},nextTick:function(fn){setTimeout(fn,0)}};\n})();\n</script>`\n return html.includes('<head>') ? html.replace('<head>', `<head>\\n${shimScript}`) : shimScript + html\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(shimAliasObj).length === 0) return\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(normalizeAliasEntries(userConfig.resolve?.alias), shimPaths),\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: shimAliasObj,\n }),\n },\n }\n },\n\n resolveId: {\n order: 'pre',\n handler(id) {\n if (id === 'vite-plugin-node-polyfills/shims/buffer' || id === 'buffer' || id === 'node:buffer') {\n return shimPaths.buffer ?? null\n }\n if (id === 'vite-plugin-node-polyfills/shims/global' || id === 'global') return shimPaths.global ?? null\n if (id === 'vite-plugin-node-polyfills/shims/process' || id === 'process' || id === 'node:process') {\n return shimPaths.process ?? null\n }\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, shimPaths)\n return rewritten ? { code: rewritten, map: null } : null\n },\n },\n }\n\n // vite-plugin-node-polyfills ≥0.27 returns Plugin[]; older versions returned a single Plugin.\n const polyfills = nodePolyfills({\n exclude: ['readline'],\n // Not stream or crypto: those pull stream-browserify and break Vite SSR / React Router prerender.\n include: ['path', 'buffer', 'events', 'string_decoder', 'util'],\n globals: { Buffer: true, global: true, process: true },\n protocolImports: true,\n }) as unknown as Plugin | Plugin[]\n\n return [\n globalsPlugin,\n ...(Array.isArray(polyfills) ? polyfills : [polyfills]),\n // After nodePolyfills so its config() can overwrite the bare shim aliases.\n ...(Object.keys(shimAliasObj).length > 0 ? [polyfillResolvePlugin] : []),\n ]\n}\n","import type { Plugin, PreviewServer, ViteDevServer } from 'vite'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport {\n effectiveIsolationHeaders,\n isolationHeadersNotSetBy,\n resolveIsolationHeaders,\n zenfsModuleFor,\n} from '@seedprotocol/bundler-core'\nimport { appendAliases } from './aliases'\nimport { warnAboutNodeGlobals } from './nodeGlobals'\nimport { nodePolyfillPlugins } from './nodePolyfills'\n\nexport interface SeedVitePluginOptions {\n /**\n * Cross-origin isolation headers for SQLite WASM, SharedArrayBuffer and OPFS on the dev and\n * preview servers, also applied in `writeHead` because Vite's `server.headers` is not copied\n * onto React Router Framework Mode HTML responses. Without them the SDK can't keep its\n * database in OPFS. Set `false` to disable, or pass `{ coop, coep, corp }` to override values.\n * A COOP/COEP/CORP value you set in `server.headers` or `preview.headers` (any letter case)\n * wins 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 * Add vite-plugin-node-polyfills (`path`, `buffer`, `events`, `string_decoder`, `util`, and\n * the `Buffer` / `process` / `global` globals), a `stream` stub and inline `global` /\n * `process` shims in index.html. The SDK doesn't need them; turn this on when another\n * dependency of your app uses Node built-ins in the browser.\n * @default false\n */\n includeNodePolyfills?: boolean\n\n /**\n * Modules to alias to ZenFS (`@zenfs/core`, or `@zenfs/core/promises` for ids containing\n * \"promises\"), for app code or dependencies that import Node's `fs` in the browser. The SDK's\n * browser build doesn't.\n * @default []\n */\n fsModules?: string[]\n\n /**\n * Log what the plugin adds, and warn about Node-only globals left in production chunks.\n * @default false\n */\n debug?: boolean\n}\n\n/**\n * Packages deduplicated when the app root resolves them, so a linked or workspace Seed package\n * shares the app's copies instead of loading its own: two Reacts break hooks, two thirdweb\n * copies break its provider context, and two copies of a Seed package split its module state\n * (registered clients, the app DB). A package only nested under another one is left alone:\n * Vite resolves deduplicated packages from the root.\n */\nconst DEDUPE_CANDIDATES = [\n 'react',\n 'react-dom',\n 'thirdweb',\n 'xstate',\n '@xstate/react',\n '@zenfs/core',\n '@zenfs/dom',\n '@seedprotocol/sdk',\n '@seedprotocol/react',\n '@seedprotocol/publish',\n '@seedprotocol/feed',\n '@seedprotocol/eas',\n '@seedprotocol/arweave',\n '@seedprotocol/query',\n] as const\n\n/**\n * The directory of `packageName` in the nearest node_modules folder from `fromDir` upward, the\n * way Vite and Node look packages up. Found on disk rather than with `require.resolve`, which\n * adds NODE_PATH (pnpm's bin shims point it at node_modules/.pnpm/node_modules, which Vite\n * doesn't search) and can't resolve ESM-only packages such as sqlocal.\n */\nfunction findPackageDir(packageName: string, fromDir: string): string | undefined {\n let dir = path.resolve(fromDir)\n for (;;) {\n const candidate = path.join(dir, 'node_modules', packageName)\n if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate\n const parent = path.dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\n/**\n * Directories the dev server serves SDK files from: the SDK package, and sqlocal and SQLite\n * WASM (its database worker and WASM file). They are outside Vite's default `server.fs.allow`\n * when the SDK is linked into the app (`file:`, `link:`, a workspace) or lives in a package\n * manager store, and the worker request then fails with 403.\n */\nfunction sdkServePaths(appRoot: string): string[] {\n const installed = findPackageDir('@seedprotocol/sdk', appRoot)\n if (!installed) return []\n // Real paths: a linked or store-installed package is a symlink, and Vite checks real paths.\n const dirs = [fs.realpathSync(installed)]\n // Each from the package that imports it: the SDK imports sqlocal, which imports SQLite WASM.\n for (const pkg of ['sqlocal', '@sqlite.org/sqlite-wasm']) {\n const dir = findPackageDir(pkg, dirs[dirs.length - 1]!)\n if (dir) dirs.push(fs.realpathSync(dir))\n }\n return dirs\n}\n\nfunction isCoveredBy(allow: readonly string[], dir: string): boolean {\n return allow.some((entry) => {\n const parent = path.resolve(String(entry))\n return dir === parent || dir.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep)\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)) res.setHeader(key, value)\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\n/**\n * The Vite settings a browser app using @seedprotocol/sdk needs: cross-origin isolation headers\n * on the dev and preview servers, ES module workers, in-order dev pre-bundles, and, for SDK\n * packages installed outside the app root, deduplication and dev-server file access. Node polyfills and `fs` aliases are\n * opt-in.\n */\nexport function seedVitePlugin(options: SeedVitePluginOptions = {}): Plugin[] {\n const {\n fsModules = [],\n debug = false,\n includeNodePolyfills = false,\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\n const log = (...args: unknown[]) => {\n if (debug) console.log('[seed-vite-plugin]', ...args)\n }\n\n const configPlugin: Plugin = {\n name: 'seed-protocol:config',\n enforce: 'pre',\n\n config(userConfig) {\n appendAliases(\n userConfig,\n fsModules.map((mod) => ({ find: mod, replacement: zenfsModuleFor(mod) })),\n )\n\n const appRoot = path.resolve(userConfig.root ?? process.cwd())\n const userDedupe = new Set(userConfig.resolve?.dedupe ?? [])\n const dedupe = DEDUPE_CANDIDATES.filter(\n (pkg) => !userDedupe.has(pkg) && findPackageDir(pkg, appRoot) !== undefined,\n )\n log('resolve.dedupe:', dedupe)\n\n // Only this plugin's additions: Vite deep-merges them into the user's config and\n // concatenates arrays.\n return {\n resolve: { dedupe },\n // drizzle-orm's modules import each other in a cycle. When the app imports both\n // @seedprotocol/sdk and @seedprotocol/sdk/drizzle, the dev pre-bundle splits them across\n // chunks that can run out of order, and drizzle throws \"Cannot read properties of\n // undefined (reading 'Symbol')\" at startup. Production builds aren't affected.\n ...(userConfig.optimizeDeps?.rolldownOptions?.output &&\n 'strictExecutionOrder' in userConfig.optimizeDeps.rolldownOptions.output\n ? {}\n : { optimizeDeps: { rolldownOptions: { output: { strictExecutionOrder: true } } } }),\n // SQLite's worker code-splits, which the default 'iife' worker format can't do: the\n // database never opens in a production build.\n ...(userConfig.worker?.format ? {} : { worker: { format: 'es' as const } }),\n // Only the headers the user has not set. Preview falls back to server.headers when\n // preview.headers is unset, so 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 configResolved(resolvedConfig) {\n if (isolationHeaders) {\n serverIsolationHeaders = effectiveIsolationHeaders(isolationHeaders, resolvedConfig.server.headers)\n previewIsolationHeaders = effectiveIsolationHeaders(isolationHeaders, resolvedConfig.preview.headers)\n }\n if (resolvedConfig.command !== 'serve') return\n const allow = resolvedConfig.server.fs.allow\n const added = sdkServePaths(resolvedConfig.root).filter((dir) => !isCoveredBy(allow, dir))\n allow.push(...added)\n if (added.length > 0) log('server.fs.allow += ', added)\n },\n\n configureServer(server) {\n if (serverIsolationHeaders) applyIsolationHeaderMiddleware(server, serverIsolationHeaders)\n },\n\n configurePreviewServer(server) {\n if (previewIsolationHeaders) applyIsolationHeaderMiddleware(server, previewIsolationHeaders)\n },\n\n generateBundle(_options, bundle) {\n if (debug) warnAboutNodeGlobals(bundle as Record<string, { type: string; code?: string }>)\n },\n }\n\n return [configPlugin, ...(includeNodePolyfills ? nodePolyfillPlugins(log) : [])]\n}\n"],"mappings":";;;;;;;;AAKA,SAAgBE,EAAe,GAAU;CACrC,OAAOC,EAAS,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SAAS,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,KAAc,EAAE;IAGzE,GAAIjB,IACA;KACE,QAAQ,EACN,SAASJ,EAAyBI,GAAkBiB,EAAW,QAAQ,OAAO,EAChF;KACA,GAAIA,EAAW,SAAS,UACpB,EACE,SAAS,EACP,SAASrB,EAAyBI,GAAkBiB,EAAW,QAAQ,OAAO,EAChF,EACF,IACA,CAAC;IACP,IACA,CAAC;GACP;EACF;EAEA,eAAe,GAAgB;GAK7B,IAJIjB,MACF,IAAyBC,EAA0BD,GAAkB0I,EAAe,OAAO,OAAO,GAClG,IAA0BzI,EAA0BD,GAAkB0I,EAAe,QAAQ,OAAO,IAElGA,EAAe,YAAY,SAAS;GACxC,IAAMhB,IAAQgB,EAAe,OAAO,GAAG,OACjCC,IAAQvB,EAAcsB,EAAe,IAAI,CAAC,CAAC,QAAQ,MAAQ,CAACjB,EAAYC,GAAOV,CAAG,CAAC;GAEzF,AADAU,EAAM,KAAK,GAAGiB,CAAK,GACfA,EAAM,SAAS,KAAGzC,EAAI,uBAAuByC,CAAK;EACxD;EAEA,gBAAgB,GAAQ;GACtB,AAAIR,KAAwBR,EAA+BiB,GAAQT,CAAsB;EAC3F;EAEA,uBAAuB,GAAQ;GAC7B,AAAIC,KAAyBT,EAA+BiB,GAAQR,CAAuB;EAC7F;EAEA,eAAe,GAAU,GAAQ;GAC/B,AAAIC,KAAOhF,EAAqBI,CAAyD;EAC3F;CAGM,GAAc,GAAIoF,IAAuB9C,EAAoBG,CAAG,IAAI,CAAC,CAAE;AACjF"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface GlobalHit {
|
|
2
|
+
global: string;
|
|
3
|
+
/** zero-based character offset in the chunk */
|
|
4
|
+
offset: number;
|
|
5
|
+
/** 1-based line number */
|
|
6
|
+
line: number;
|
|
7
|
+
/** surrounding raw source for context */
|
|
8
|
+
context: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Find free references to Node-only globals in a bundled chunk. Skips names
|
|
12
|
+
* the chunk declares itself (e.g. the process polyfill's own `var process`),
|
|
13
|
+
* `typeof` checks, property names, and uses behind a `typeof` guard or `try`.
|
|
14
|
+
* Best-effort: a chunk that fails to parse reports nothing.
|
|
15
|
+
*/
|
|
16
|
+
export declare function findDangerousGlobals(code: string): GlobalHit[];
|
|
17
|
+
/** Warn about free references to Node-only globals in the bundle's chunks (`debug: true`). */
|
|
18
|
+
export declare function warnAboutNodeGlobals(bundle: Record<string, {
|
|
19
|
+
type: string;
|
|
20
|
+
code?: string;
|
|
21
|
+
}>): void;
|
|
22
|
+
//# sourceMappingURL=nodeGlobals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodeGlobals.d.ts","sourceRoot":"","sources":["../src/nodeGlobals.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAA;IACd,+CAA+C;IAC/C,MAAM,EAAE,MAAM,CAAA;IACd,0BAA0B;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,yCAAyC;IACzC,OAAO,EAAE,MAAM,CAAA;CAChB;AAkFD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,CA0E9D;AAED,8FAA8F;AAC9F,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACtD,IAAI,CAuBN"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Plugin, UserConfig } from 'vite';
|
|
2
|
+
type OptimizeDepsConfig = NonNullable<UserConfig['optimizeDeps']>;
|
|
3
|
+
/**
|
|
4
|
+
* A Vite 8 `optimizeDeps.rolldownOptions` patch for a plugin `config()` hook.
|
|
5
|
+
*
|
|
6
|
+
* Returns only what this plugin adds. Vite deep-merges hook results into the
|
|
7
|
+
* user config and concatenates arrays, so echoing existing options back would
|
|
8
|
+
* duplicate them — e.g. vite-plugin-node-polyfills' optimizer banner plugin,
|
|
9
|
+
* which then declares `__buffer_polyfill` twice in every prebundled chunk.
|
|
10
|
+
* Legacy `esbuildOptions.define` is carried into `transform.define` so
|
|
11
|
+
* definitions survive the move off the deprecated key.
|
|
12
|
+
*/
|
|
13
|
+
export declare function optimizeDepsRolldownPatch(existing: OptimizeDepsConfig | undefined, patch: {
|
|
14
|
+
define?: Record<string, string>;
|
|
15
|
+
alias?: Record<string, string>;
|
|
16
|
+
}): OptimizeDepsConfig['rolldownOptions'];
|
|
17
|
+
/**
|
|
18
|
+
* vite-plugin-node-polyfills (path, buffer, events, string_decoder, util and the Buffer /
|
|
19
|
+
* process / global globals), with its shim imports resolved from this package so apps don't
|
|
20
|
+
* install it, a minimal `stream` stub, and inline `global` / `process` shims in index.html.
|
|
21
|
+
*/
|
|
22
|
+
export declare function nodePolyfillPlugins(log: (...args: unknown[]) => void): Plugin[];
|
|
23
|
+
export {};
|
|
24
|
+
//# sourceMappingURL=nodePolyfills.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodePolyfills.d.ts","sourceRoot":"","sources":["../src/nodePolyfills.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,MAAM,CAAA;AA2K9C,KAAK,kBAAkB,GAAG,WAAW,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC,CAAA;AAEjE;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,kBAAkB,GAAG,SAAS,EACxC,KAAK,EAAE;IACL,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,GACA,kBAAkB,CAAC,iBAAiB,CAAC,CAWvC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,GAAG,MAAM,EAAE,CAyI/E"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seedprotocol/vite",
|
|
3
|
-
"version": "0.7.
|
|
4
|
-
"description": "Vite plugin for browser apps using @seedprotocol/sdk:
|
|
3
|
+
"version": "0.7.6-next.920.gdd0b533",
|
|
4
|
+
"description": "Vite plugin for browser apps using @seedprotocol/sdk: cross-origin isolation headers, ES module workers, linked-install support, and opt-in Node polyfills",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"seed-protocol",
|
|
7
7
|
"vite",
|
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
"zenfs",
|
|
10
10
|
"opfs",
|
|
11
11
|
"sqlite-wasm",
|
|
12
|
-
"polyfills",
|
|
13
12
|
"cross-origin-isolation"
|
|
14
13
|
],
|
|
15
14
|
"type": "module",
|
|
@@ -38,7 +37,6 @@
|
|
|
38
37
|
},
|
|
39
38
|
"dependencies": {
|
|
40
39
|
"@rollup/pluginutils": "^5.1.0",
|
|
41
|
-
"debug": "^4.4.1",
|
|
42
40
|
"vite-plugin-node-polyfills": "^0.27.0"
|
|
43
41
|
},
|
|
44
42
|
"peerDependencies": {
|
|
@@ -53,6 +51,7 @@
|
|
|
53
51
|
}
|
|
54
52
|
},
|
|
55
53
|
"devDependencies": {
|
|
54
|
+
"@seedprotocol/bundler-core": "0.7.6-next.920.gdd0b533",
|
|
56
55
|
"@types/bun": "latest",
|
|
57
56
|
"@types/node": "^24.10.1",
|
|
58
57
|
"@vitejs/plugin-react": "^6.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"arweave-default-shim.d.ts","sourceRoot":"","sources":["../src/arweave-default-shim.js"],"names":[],"mappings":";AAKO,0CAA4D;AAHnE,qCAA4C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"debug-default-shim.d.ts","sourceRoot":"","sources":["../src/debug-default-shim.js"],"names":[],"mappings":";AAgBA,2BAA+C"}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ESM interop shim for the `debug` package browser entry.
|
|
3
|
-
* `debug/src/browser.js` is CJS and may not expose a default export when served
|
|
4
|
-
* directly by Vite; default-import consumers expect `import debug from 'debug'`.
|
|
5
|
-
*/
|
|
6
|
-
import * as debugModule from 'debug/src/browser.js'
|
|
7
|
-
|
|
8
|
-
function resolveDebugExport(mod) {
|
|
9
|
-
if (typeof mod === 'function') return mod
|
|
10
|
-
if (mod && typeof mod.default === 'function') return mod.default
|
|
11
|
-
const candidate = mod?.default ?? mod
|
|
12
|
-
if (typeof candidate === 'function') return candidate
|
|
13
|
-
if (candidate && typeof candidate.default === 'function') return candidate.default
|
|
14
|
-
return candidate
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
const debugFn = resolveDebugExport(debugModule)
|
|
18
|
-
|
|
19
|
-
export default debugFn
|