UNPKG

one

Version:

One is a new React Framework that makes Vite serve both native and web.

78 lines (77 loc) 2.77 kB
import { prefixRegex } from "rolldown/filter"; const VIRTUAL_PREFIX = "\0one-env-guard:"; const GUARD_SPECIFIERS = ["server-only", "client-only", "native-only", "web-only"]; const GUARD_SPECIFIERS_RE = new RegExp(`^(?:${GUARD_SPECIFIERS.join("|")})$`); const ALLOWED_BY_NAME = { "native-only": ["ios", "android"], "web-only": ["client", "ssr"] }; const ALLOWED_BY_CONSUMER = { "server-only": "server", "client-only": "client" }; function resolveEnvironmentGuard(specifier, envName, consumer, options) { if (!GUARD_SPECIFIERS.includes(specifier)) { return null; } if (options?.disabled || options?.disableGuards?.includes(specifier)) { return `${VIRTUAL_PREFIX}${specifier}:disabled`; } return `${VIRTUAL_PREFIX}${specifier}:${envName}:${consumer ?? "unknown"}`; } function loadEnvironmentGuard(id) { if (!id.startsWith(VIRTUAL_PREFIX)) { return null; } const rest = id.slice(VIRTUAL_PREFIX.length); const parts = rest.split(":"); if (parts.length === 2 && parts[1] === "disabled") { return "export {}"; } const specifier = parts[0]; const envName = parts[1]; const consumer = parts[2]; const requiredConsumer = ALLOWED_BY_CONSUMER[specifier]; if (requiredConsumer) { if (consumer === requiredConsumer) return "export {}"; if (!consumer || consumer === "unknown") { const legacyAllowed = requiredConsumer === "server" ? ["ssr"] : ["client"]; if (legacyAllowed.includes(envName)) return "export {}"; } return `throw new Error("${specifier} cannot be imported in the \\"${envName}\\" environment")`; } const allowedNames = ALLOWED_BY_NAME[specifier]; if (!allowedNames) return null; if (allowedNames.includes(envName)) return "export {}"; return `throw new Error("${specifier} cannot be imported in the \\"${envName}\\" environment")`; } function environmentGuardPlugin(options) { return { name: "one:environment-guard", enforce: "pre", // filters are evaluated in rust, so non-guard ids never cross into js. // without them every import in the graph paid a napi round trip to be told // it wasn't one of these four specifiers. resolveId: { filter: { id: GUARD_SPECIFIERS_RE }, handler(source) { const envName = this.environment?.name; if (!envName) return null; const consumer = this.environment?.config?.consumer; return resolveEnvironmentGuard(source, envName, consumer, options); } }, load: { filter: { id: prefixRegex(VIRTUAL_PREFIX) }, handler(id) { return loadEnvironmentGuard(id); } } }; } export { environmentGuardPlugin, loadEnvironmentGuard, resolveEnvironmentGuard }; //# sourceMappingURL=environmentGuardPlugin.mjs.map