aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> 2023-09-19 04:33:58 -0700
committerGravatar Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> 2023-09-19 04:33:58 -0700
commited9e64805feab8e84b2debf09534c7eaa23574c4 (patch)
tree8ab0d6a5b841a8e6e033edafc90c6c8ea7aec6f1
parent8ca691693f9972096196b2b15b49b2ca2dfbb639 (diff)
downloadbun-ed9e64805feab8e84b2debf09534c7eaa23574c4.tar.gz
bun-ed9e64805feab8e84b2debf09534c7eaa23574c4.tar.zst
bun-ed9e64805feab8e84b2debf09534c7eaa23574c4.zip
Delete long-broken package which is causing confusion
-rw-r--r--.github/workflows/bun-framework-next.yml41
-rw-r--r--packages/bun-framework-next/.npmignore5
-rw-r--r--packages/bun-framework-next/README.md25
-rw-r--r--packages/bun-framework-next/appInjector.js15
-rwxr-xr-xpackages/bun-framework-next/bun.lockbbin13004 -> 0 bytes
-rw-r--r--packages/bun-framework-next/client.development.tsx463
-rw-r--r--packages/bun-framework-next/empty.js1
-rw-r--r--packages/bun-framework-next/fallback.development.tsx102
-rw-r--r--packages/bun-framework-next/next-image-polyfill.tsx36
-rw-r--r--packages/bun-framework-next/next_document.tsx0
-rw-r--r--packages/bun-framework-next/package.json101
-rw-r--r--packages/bun-framework-next/packageVersion.ts44
-rw-r--r--packages/bun-framework-next/page-loader.ts138
-rw-r--r--packages/bun-framework-next/renderDocument.tsx835
-rw-r--r--packages/bun-framework-next/server.development.tsx91
-rw-r--r--packages/bun-framework-next/tsconfig.json28
16 files changed, 0 insertions, 1925 deletions
diff --git a/.github/workflows/bun-framework-next.yml b/.github/workflows/bun-framework-next.yml
deleted file mode 100644
index e871c2c31..000000000
--- a/.github/workflows/bun-framework-next.yml
+++ /dev/null
@@ -1,41 +0,0 @@
-name: bun-framework-next
-on:
- push:
- paths:
- - packages/bun-framework-next/**/*
- branches: [main, bun-framework-next-actions]
- pull_request:
- paths:
- - packages/bun-framework-next/**/*
- branches: [main]
-
-jobs:
- build:
- name: lint, test and build on Node ${{ matrix.node }} and ${{ matrix.os }}
-
- runs-on: ${{ matrix.os }}
-
- strategy:
- matrix:
- node: ["14.x"]
- os: [macOS-latest]
-
- steps:
- - name: Checkout repo
- uses: actions/checkout@v2
-
- - name: Use Node ${{ matrix.node }}
- uses: actions/setup-node@v2
- with:
- node-version: ${{ matrix.node }}
-
- - name: Install PNPM
- uses: pnpm/action-setup@v2.0.1
- with:
- version: 6.21.0
-
- - name: Install dependencies
- run: cd packages/bun-framework-next && pnpm install
-
- - name: Type check bun-framework-next
- run: cd packages/bun-framework-next && pnpm check
diff --git a/packages/bun-framework-next/.npmignore b/packages/bun-framework-next/.npmignore
deleted file mode 100644
index cdb7baa1d..000000000
--- a/packages/bun-framework-next/.npmignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*.bun
-node_modules
-pnpm-log.yaml
-yarn-error.log
-yarn.lock \ No newline at end of file
diff --git a/packages/bun-framework-next/README.md b/packages/bun-framework-next/README.md
deleted file mode 100644
index 4df8999d1..000000000
--- a/packages/bun-framework-next/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# bun-framework-next
-
-This package lets you use Next.js 12.2 with bun. This readme assumes you already installed bun.
-
-To start a new project:
-
-```bash
-bun create next --open
-```
-
-To use Next.js 12 with an existing project:
-
-```bash
-bun add bun-framework-next
-echo "framework = 'next'" > bunfig.toml
-bun bun
-```
-
-Launch the development server:
-
-```bash
-bun dev
-```
-
-Open http://localhost:3000 with your browser to see the result.
diff --git a/packages/bun-framework-next/appInjector.js b/packages/bun-framework-next/appInjector.js
deleted file mode 100644
index e8bf22d21..000000000
--- a/packages/bun-framework-next/appInjector.js
+++ /dev/null
@@ -1,15 +0,0 @@
-export function maybeInjectApp(expr) {
- var app;
- try {
- const path = Bun.routesDir + "/_app";
- app = Bun.resolveSync(path, Bun.cwd + "/");
- } catch (exception) {
- return undefined;
- }
-
- return (
- <>
- <import path={app} />
- </>
- );
-}
diff --git a/packages/bun-framework-next/bun.lockb b/packages/bun-framework-next/bun.lockb
deleted file mode 100755
index 7cb21bc37..000000000
--- a/packages/bun-framework-next/bun.lockb
+++ /dev/null
Binary files differ
diff --git a/packages/bun-framework-next/client.development.tsx b/packages/bun-framework-next/client.development.tsx
deleted file mode 100644
index 470dd2085..000000000
--- a/packages/bun-framework-next/client.development.tsx
+++ /dev/null
@@ -1,463 +0,0 @@
-globalThis.global = globalThis;
-globalThis.Bun_disableCSSImports = true;
-
-import * as React from "react";
-
-var ReactDOM;
-try {
- ReactDOM = require("react-dom/client");
-} catch (exception) {}
-
-if (!ReactDOM) {
- try {
- ReactDOM = require("react-dom");
- } catch (exception) {}
-}
-
-import NextApp from "next/app";
-import mitt, { MittEmitter } from "next/dist/shared/lib/mitt";
-import { RouterContext } from "next/dist/shared/lib/router-context";
-import Router, {
- AppComponent,
- AppProps,
- PrivateRouteInfo,
-} from "next/dist/shared/lib/router/router";
-
-import NextRouteLoader from "next/dist/client/route-loader";
-import { isDynamicRoute } from "next/dist/shared/lib/router/utils/is-dynamic";
-import {
- urlQueryToSearchParams,
- assign,
-} from "next/dist/shared/lib/router/utils/querystring";
-import { setConfig } from "next/dist/shared/lib/runtime-config";
-import { getURL, NEXT_DATA } from "next/dist/shared/lib/utils";
-
-import initHeadManager from "next/dist/client/head-manager";
-import { HeadManagerContext } from "next/dist/shared/lib/head-manager-context";
-import PageLoader from "./page-loader";
-import {
- createRouter,
- makePublicRouterInstance,
-} from "next/dist/client/router";
-
-export const emitter: MittEmitter<string> = mitt();
-
-declare global {
- interface Window {
- /* test fns */
- __NEXT_HYDRATED?: boolean;
- __NEXT_HYDRATED_CB?: () => void;
-
- /* prod */
- __NEXT_PRELOADREADY?: (ids?: (string | number)[]) => void;
- __NEXT_DATA__: NEXT_DATA;
- __NEXT_P: any[];
- }
-}
-
-function nextDataFromBunData() {
- const {
- router: { routes, route, params: paramsList },
- } = globalThis.__BUN_DATA__;
-
- const paramsMap = new Map();
- for (let i = 0; i < paramsList.keys.length; i++) {
- paramsMap.set(
- decodeURIComponent(paramsList.keys[i]),
- decodeURIComponent(paramsList.values[i]),
- );
- }
-
- const params = {};
- var url = new URL(location.href);
- Object.assign(params, Object.fromEntries(url.searchParams.entries()));
- Object.assign(params, Object.fromEntries(paramsMap.entries()));
-
- const pages = routes.keys.reduce((acc, routeName, i) => {
- const routePath = routes.values[i];
- acc[routeName] = [routePath];
- return acc;
- }, {});
-
- return {
- page: routes.keys[route],
- buildId: "1234",
- assetPrefix: "",
- isPreview: false,
- locale: null,
- locales: [],
- isFallback: false,
- err: null,
- props: {},
- query: params,
- pages,
- };
-}
-
-type RenderRouteInfo = PrivateRouteInfo & {
- App: AppComponent;
- scroll?: { x: number; y: number } | null;
-};
-
-const nextDataTag = document.getElementById("__NEXT_DATA__");
-
-// pages is added at runtime and doesn't exist in Next types
-const data: NEXT_DATA & { pages: Record<string, string[]> } = nextDataTag
- ? JSON.parse(document.getElementById("__NEXT_DATA__")!.textContent!)
- : nextDataFromBunData();
-
-window.__NEXT_DATA__ = data;
-
-const {
- props: hydrateProps,
- err: hydrateErr,
- page,
- query,
- buildId,
- assetPrefix,
- runtimeConfig,
- // Todo, revist this constant when supporting dynamic()
- dynamicIds,
- isFallback,
- locale,
- locales,
- domainLocales,
- isPreview,
- pages,
-} = data;
-
-const prefix: string = assetPrefix || "";
-
-setConfig({
- serverRuntimeConfig: {},
- publicRuntimeConfig: runtimeConfig || {},
-});
-
-let asPath: string = getURL();
-const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || "";
-
-function pathNoQueryHash(path: string) {
- const queryIndex = path.indexOf("?");
- const hashIndex = path.indexOf("#");
-
- if (queryIndex > -1 || hashIndex > -1) {
- path = path.substring(0, queryIndex > -1 ? queryIndex : hashIndex);
- }
- return path;
-}
-
-function hasBasePath(path: string): boolean {
- path = pathNoQueryHash(path);
- return path === prefix || path.startsWith(prefix + "/");
-}
-
-function delBasePath(path: string): string {
- path = path.slice(basePath.length);
- if (!path.startsWith("/")) path = `/${path}`;
- return path;
-}
-
-// make sure not to attempt stripping basePath for 404s
-if (hasBasePath(asPath)) {
- asPath = delBasePath(asPath);
-}
-
-export const pageLoader: PageLoader = new PageLoader(buildId, prefix, pages);
-
-const headManager: {
- mountedInstances: Set<unknown>;
- updateHead: (head: JSX.Element[]) => void;
-} = initHeadManager();
-
-export let router: Router;
-
-let CachedApp: AppComponent = null;
-
-export default function boot(EntryPointNamespace) {
- _boot(EntryPointNamespace, false);
-}
-
-class Container extends React.Component<{
- fn: (err: Error, info?: any) => void;
-}> {
- componentDidCatch(componentErr: Error, info: any) {
- this.props.fn(componentErr, info);
- }
-
- componentDidMount() {
- this.scrollToHash();
-
- // We need to replace the router state if:
- // - the page was (auto) exported and has a query string or search (hash)
- // - it was auto exported and is a dynamic route (to provide params)
- // - if it is a client-side skeleton (fallback render)
- if (
- router.isSsr &&
- // We don't update for 404 requests as this can modify
- // the asPath unexpectedly e.g. adding basePath when
- // it wasn't originally present
- page !== "/404" &&
- page !== "/_error" &&
- (isFallback ||
- (data.nextExport &&
- (isDynamicRoute(router.pathname) ||
- location.search ||
- process.env.__NEXT_HAS_REWRITES)) ||
- (hydrateProps &&
- hydrateProps.__N_SSG &&
- (location.search || process.env.__NEXT_HAS_REWRITES)))
- ) {
- // update query on mount for exported pages
- router.replace(
- router.pathname +
- "?" +
- String(
- assign(
- urlQueryToSearchParams(router.query),
- new URLSearchParams(location.search),
- ),
- ),
- asPath,
- {
- // @ts-ignore
- // WARNING: `_h` is an internal option for handing Next.js
- // client-side hydration. Your app should _never_ use this property.
- // It may change at any time without notice.
- _h: 1,
- // Fallback pages must trigger the data fetch, so the transition is
- // not shallow.
- // Other pages (strictly updating query) happens shallowly, as data
- // requirements would already be present.
- shallow: !isFallback,
- },
- );
- }
- }
-
- componentDidUpdate() {
- this.scrollToHash();
- }
-
- scrollToHash() {
- let { hash } = location;
- hash = hash && hash.substring(1);
- if (!hash) return;
-
- const el: HTMLElement | null = document.getElementById(hash);
- if (!el) return;
-
- // If we call scrollIntoView() in here without a setTimeout
- // it won't scroll properly.
- setTimeout(() => el.scrollIntoView(), 0);
- }
-
- render() {
- return this.props.children;
- }
-}
-
-let CachedComponent: React.ComponentType;
-
-const wrapApp =
- (App: AppComponent) =>
- (wrappedAppProps: Record<string, any>): JSX.Element => {
- const appProps: AppProps = {
- ...wrappedAppProps,
- Component: CachedComponent,
- err: hydrateErr,
- router,
- };
- return (
- <AppContainer>
- <App {...appProps} />
- </AppContainer>
- );
- };
-
-function AppContainer({
- children,
-}: React.PropsWithChildren<{}>): React.ReactElement {
- return (
- <Container fn={(error) => <div>{JSON.stringify(error)}</div>}>
- <RouterContext.Provider value={makePublicRouterInstance(router)}>
- <HeadManagerContext.Provider value={headManager}>
- {children}
- </HeadManagerContext.Provider>
- </RouterContext.Provider>
- </Container>
- );
-}
-
-let reactRoot: any = null;
-
-const USE_REACT_18 = "hydrateRoot" in ReactDOM;
-
-class BootError extends Error {
- constructor(message) {
- super(message);
- this.name = "BootError";
- }
-}
-
-export async function _boot(EntryPointNamespace, isError) {
- NextRouteLoader.getClientBuildManifest = () => Promise.resolve({});
-
- const PageComponent = EntryPointNamespace.default;
-
- const appScripts = globalThis.__NEXT_DATA__.pages["/_app"];
-
- // Type 'typeof App' is not assignable to type 'ComponentClass<AppProps, any>'.
- // Construct signature return types 'App<any, any, any>' and 'Component<AppProps, any, any>' are incompatible.
- // @ts-expect-error
- CachedApp = NextApp;
- CachedComponent = PageComponent;
-
- if (appScripts && appScripts.length > 0) {
- let appSrc;
- for (let asset of appScripts) {
- if (!asset.endsWith(".css")) {
- appSrc = asset;
- break;
- }
- }
-
- if (appSrc) {
- const AppModule = await import(appSrc);
-
- console.assert(
- AppModule.default,
- appSrc + " must have a default export'd React component",
- );
-
- if ("default" in AppModule) {
- CachedApp = AppModule.default;
- }
- }
- }
-
- router = createRouter(page, query, asPath, {
- initialProps: hydrateProps,
- pageLoader,
- App: CachedApp,
- Component: CachedComponent,
- wrapApp,
- err: null,
- isFallback: Boolean(isFallback),
- subscription: async (info, App, scroll) => {
- return render(
- Object.assign<
- {},
- Omit<RenderRouteInfo, "App" | "scroll" | "Component">,
- Pick<RenderRouteInfo, "App" | "scroll" | "Component">
- >({}, info, {
- // If we don't have an info.Component, we may be shallow routing,
- // fallback to current entry point
- Component: info.Component || CachedComponent,
- App,
- scroll,
- }),
- );
- },
- locale,
- locales,
- defaultLocale: "",
- domainLocales,
- isPreview,
- });
-
- globalThis.next.router = router;
-
- var domEl = document.querySelector("#__next");
-
- if (!domEl) {
- const nextEl = document.createElement("div");
- nextEl.id = "__next";
- document.body.appendChild(nextEl);
- domEl = nextEl;
- }
-
- const reactEl = (
- <TopLevelRender
- App={CachedApp}
- Component={PageComponent}
- props={hydrateProps}
- />
- );
-
- if (USE_REACT_18) {
- if (!isError && domEl.hasChildNodes() && !reactRoot) {
- try {
- // Unlike with createRoot, you don't need a separate root.render() call here
- reactRoot = ReactDOM.hydrateRoot(domEl, reactEl);
- } catch (exception) {
- try {
- reactRoot = ReactDOM.createRoot(domEl);
- reactRoot.render(reactEl);
- } catch {
- throw exception;
- }
- }
- } else {
- if (!reactRoot) {
- reactRoot = ReactDOM.createRoot(domEl);
- }
-
- reactRoot.render(reactEl);
- }
- } else {
- if (isError || !domEl.hasChildNodes() || !("hydrate" in ReactDOM)) {
- ReactDOM.render(reactEl, domEl);
- } else {
- try {
- ReactDOM.hydrate(reactEl, domEl);
- } catch (e) {
- ReactDOM.render(reactEl, domEl);
- }
- }
- }
-}
-
-function TopLevelRender({ App, Component, props }) {
- return (
- <AppContainer>
- <App Component={Component} {...props}></App>
- </AppContainer>
- );
-}
-
-export function render(props) {
- if (USE_REACT_18) {
- reactRoot.render(<TopLevelRender {...props} />);
- } else {
- ReactDOM.render(
- <TopLevelRender {...props} />,
- document.getElementById("__next"),
- );
- }
-}
-
-export function renderError(e) {
- const reactEl = <AppContainer>{null}</AppContainer>;
-
- if (USE_REACT_18) {
- if (!reactRoot) {
- const domEl = document.querySelector("#__next");
-
- // Unlike with createRoot, you don't need a separate root.render() call here
- reactRoot = ReactDOM.hydrateRoot(domEl, reactEl);
- } else {
- reactRoot.render(reactEl);
- }
- } else {
- const domEl = document.querySelector("#__next");
-
- ReactDOM.render(reactEl, domEl);
- }
-}
-
-globalThis.next = {
- version: "12.0.4",
- emitter,
- render,
- renderError,
-};
diff --git a/packages/bun-framework-next/empty.js b/packages/bun-framework-next/empty.js
deleted file mode 100644
index bbf5800ce..000000000
--- a/packages/bun-framework-next/empty.js
+++ /dev/null
@@ -1 +0,0 @@
-// Keep this file here so that main resolves correctly
diff --git a/packages/bun-framework-next/fallback.development.tsx b/packages/bun-framework-next/fallback.development.tsx
deleted file mode 100644
index 6e3ff00ff..000000000
--- a/packages/bun-framework-next/fallback.development.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import type { FallbackMessageContainer } from "../../src/api/schema";
-import { maybeInjectApp } from "macro:./appInjector";
-
-var globalStyles = [];
-function insertGlobalStyleSheet({ detail: url }) {
- globalStyles.push(
- new Promise((resolve, reject) => {
- const link: HTMLLinkElement = document.createElement("link");
- link.rel = "stylesheet";
- link.href = url;
- link.onload = resolve;
- link.onabort = reject;
- link.onerror = reject;
- document.head.appendChild(link);
- }),
- );
-}
-
-const nCSS = document.createElement("noscript");
-nCSS.setAttribute("data-n-css", "");
-document.head.appendChild(nCSS);
-
-document.addEventListener("onimportcss", insertGlobalStyleSheet);
-
-var once = false;
-function insertNextHeadCount() {
- if (!once) {
- document.head.insertAdjacentHTML(
- "beforeend",
- `<meta name="next-head-count" content="0">`,
- );
- once = true;
- }
-}
-
-maybeInjectApp();
-
-globalThis.__BUN_APP_STYLES = [...globalThis["__BUN"].allImportedStyles].map(
- (style) => {
- const url = new URL(style, location.origin);
- if (url.origin === location.origin && url.href === style) {
- return url.pathname;
- }
-
- return style;
- },
-);
-
-import { _boot, pageLoader } from "./client.development";
-
-function renderFallback({ router }: FallbackMessageContainer) {
- const route = router.routes.values[router.route];
-
- if (!document.getElementById("__next")) {
- const next = document.createElement("div");
- next.id = "__next";
- document.body.prepend(next);
- }
-
- document.removeEventListener("onimportcss", insertGlobalStyleSheet);
- document.addEventListener("onimportcss", pageLoader.onImportCSS);
-
- var cssQueue;
- return import(route)
- .then((Namespace) => {
- nCSS.remove();
- document.head.appendChild(nCSS);
- cssQueue = [...globalStyles, ...pageLoader.cssQueue];
- pageLoader.cssQueue = [];
- insertNextHeadCount();
- return _boot(Namespace, true);
- })
- .then(() => {
- cssQueue = [...cssQueue, ...pageLoader.cssQueue.slice()];
- pageLoader.cssQueue = [];
- return Promise.allSettled(cssQueue);
- })
- .finally(() => {
- document.body.style.visibility = "visible";
- document.removeEventListener("onimportcss", pageLoader.onImportCSS);
- });
-}
-
-export default function render(props: FallbackMessageContainer) {
- // @ts-expect-error bun:error.js is real
- return import("/bun:error.js").then(({ renderFallbackError }) => {
- return renderFallback(props).then(
- () => {
- Promise.all(pageLoader.cssQueue).finally(() => {
- renderFallbackError(props);
- document.body.style.visibility = "visible";
- });
- },
- (err) => {
- console.error(err);
- Promise.all(pageLoader.cssQueue).finally(() => {
- renderFallbackError(props);
- });
- },
- );
- });
-}
diff --git a/packages/bun-framework-next/next-image-polyfill.tsx b/packages/bun-framework-next/next-image-polyfill.tsx
deleted file mode 100644
index edc3775d7..000000000
--- a/packages/bun-framework-next/next-image-polyfill.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-function NextImagePolyfill({
- src,
- width,
- height,
- objectFit,
- style,
- layout,
- ...otherProps
-}) {
- var _style = style;
- if (layout === "fit") {
- objectFit = "contain";
- } else if (layout === "fill") {
- objectFit = "cover";
- }
-
- if (objectFit) {
- if (!_style) {
- _style = { objectFit: objectFit };
- } else {
- _style.objectFit = objectFit;
- }
- }
-
- return (
- <img
- src={src}
- width={width}
- height={height}
- style={_style}
- {...otherProps}
- />
- );
-}
-
-export default NextImagePolyfill;
diff --git a/packages/bun-framework-next/next_document.tsx b/packages/bun-framework-next/next_document.tsx
deleted file mode 100644
index e69de29bb..000000000
--- a/packages/bun-framework-next/next_document.tsx
+++ /dev/null
diff --git a/packages/bun-framework-next/package.json b/packages/bun-framework-next/package.json
deleted file mode 100644
index a06294ba5..000000000
--- a/packages/bun-framework-next/package.json
+++ /dev/null
@@ -1,101 +0,0 @@
-{
- "name": "bun-framework-next",
- "version": "12.2.5",
- "main": "empty.js",
- "repository": "https://github.com/oven-sh/bun",
- "module": "empty.js",
- "description": "bun compatibility layer for Next.js >= v12.2.3",
- "homepage": "https://bun.sh",
- "bugs": {
- "url": "https://github.com/oven-sh/bun/issues"
- },
- "scripts": {
- "check": "tsc --noEmit"
- },
- "license": "MIT",
- "dependencies": {
- "react-is": "*"
- },
- "peerDependencies": {
- "next": "~12.2.3"
- },
- "devDependencies": {
- "@types/react": "^18",
- "@types/react-dom": "^18",
- "next": "^12.2.3",
- "react": "^18",
- "react-dom": "^18",
- "typescript": "^4"
- },
- "framework": {
- "displayName": "Next.js",
- "static": "public",
- "assetPrefix": "_next/",
- "router": {
- "dir": [
- "pages",
- "src/pages"
- ],
- "extensions": [
- ".js",
- ".ts",
- ".tsx",
- ".jsx"
- ]
- },
- "css": "onimportcss",
- "development": {
- "client": "client.development.tsx",
- "fallback": "fallback.development.tsx",
- "server": "server.development.tsx",
- "css": "onimportcss",
- "override": {
- "next/dist/client/image.js": "next-image-polyfill.tsx"
- },
- "define": {
- "client": {
- ".env": "NEXT_PUBLIC_",
- "defaults": {
- "process.env.__NEXT_TRAILING_SLASH": "false",
- "process.env.NODE_ENV": "'development'",
- "process.env.__NEXT_ROUTER_BASEPATH": "''",
- "process.env.__NEXT_SCROLL_RESTORATION": "false",
- "process.env.__NEXT_I18N_SUPPORT": "false",
- "process.env.__NEXT_HAS_REWRITES": "false",
- "process.env.__NEXT_ANALYTICS_ID": "null",
- "process.env.__NEXT_OPTIMIZE_CSS": "false",
- "process.env.__NEXT_CROSS_ORIGIN": "''",
- "process.env.__NEXT_STRICT_MODE": "false",
- "process.env.__NEXT_IMAGE_OPTS": "null"
- }
- },
- "server": {
- ".env": "NEXT_",
- "defaults": {
- "process.env.__NEXT_TRAILING_SLASH": "false",
- "process.env.__NEXT_OPTIMIZE_FONTS": "false",
- "process.env.NODE_ENV": "\"development\"",
- "process.env.__NEXT_OPTIMIZE_IMAGES": "false",
- "process.env.__NEXT_OPTIMIZE_CSS": "false",
- "process.env.__NEXT_ROUTER_BASEPATH": "''",
- "process.env.__NEXT_SCROLL_RESTORATION": "false",
- "process.env.__NEXT_I18N_SUPPORT": "false",
- "process.env.__NEXT_HAS_REWRITES": "false",
- "process.env.__NEXT_ANALYTICS_ID": "null",
- "process.env.__NEXT_CROSS_ORIGIN": "''",
- "process.env.__NEXT_STRICT_MODE": "false",
- "process.env.__NEXT_IMAGE_OPTS": "null",
- "global": "globalThis",
- "window": "undefined"
- }
- }
- }
- },
- "production": {
- "client": "empty.js",
- "server": "empty.js",
- "fallback": "empty.js",
- "css": "onimportcss"
- }
- }
-}
diff --git a/packages/bun-framework-next/packageVersion.ts b/packages/bun-framework-next/packageVersion.ts
deleted file mode 100644
index d6ff0b21d..000000000
--- a/packages/bun-framework-next/packageVersion.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { readFileSync } from "fs";
-
-var memoizeMap;
-
-// This gives us a package version inline into the build without pulling in the whole package.json
-// it only parses the package.json for a given package name once (relative to the directory of this file)
-export function packageVersion(call) {
- var name = call.arguments[0].toString();
-
- // in the general case, this would break when using multiple versions of the same package
- // but people don't use multiple versions of next in the same bundle
- // so we don't need to worry about it here
- // and it skips resolveSync which is a bit faster
- if (memoizeMap) {
- const value = memoizeMap.get(name);
- if (value) return value;
- }
- var nextPath;
- try {
- nextPath = Bun.resolveSync(`${name}/package.json`, import.meta.dir);
- } catch (exception) {
- throw new Error(`${name} is not a valid package name`);
- }
-
- var json;
- try {
- // TODO: Add sync methods to FileBlob?
- json = JSON.parse(readFileSync(nextPath, "utf8"));
- } catch (exc) {
- throw new AggregateError([exc], `Error parsing ${name}/package.json`);
- }
-
- if (!json.version) {
- throw new Error(`${name}/package.json is missing a version`);
- }
-
- if (!memoizeMap) {
- memoizeMap = new Map();
- }
-
- memoizeMap.set(name, json.version);
-
- return json.version;
-}
diff --git a/packages/bun-framework-next/page-loader.ts b/packages/bun-framework-next/page-loader.ts
deleted file mode 100644
index c74b22fbf..000000000
--- a/packages/bun-framework-next/page-loader.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import NextPageLoader, {
- GoodPageCache as NextGoodPageCache,
-} from "next/dist/client/page-loader";
-import getAssetPathFromRoute from "next/dist/shared/lib/router/utils/get-asset-path-from-route";
-
-export function insertStyleSheet(url: string, isFallback: boolean = false) {
- if (document.querySelector(`link[href="${url}"]`)) {
- return Promise.resolve();
- }
-
- return new Promise((resolve, reject) => {
- const link: HTMLLinkElement = document.createElement("link");
- link.rel = "stylesheet";
-
- // marking this resolve as void seems to break other things
- link.onload = resolve;
- link.onerror = reject;
-
- link.href = url;
-
- if (isFallback) {
- link.setAttribute("data-href", url);
- }
-
- document.head.appendChild(link);
- });
-}
-
-interface GoodPageCache extends NextGoodPageCache {
- __N_SSG: boolean;
- __N_SSP: boolean;
-}
-
-export default class PageLoader extends NextPageLoader {
- constructor(_, __, pages) {
- super(_, __);
-
- // TODO: assetPrefix?
-
- // Rewrite the pages object to omit the entry script
- // At this point, the entry point has been loaded so we don't want to do that again.
- for (let name in pages) {
- for (let i = 0; i < pages[name].length; i += 1) {
- const lastDot = pages[name][i].lastIndexOf(".");
- if (lastDot == -1) continue;
- if (
- pages[name][i].substring(lastDot - ".entry".length, lastDot) !==
- ".entry"
- )
- continue;
-
- pages[name][i] =
- pages[name][i].substring(0, lastDot - ".entry".length) +
- pages[name][i].substring(lastDot);
- }
- }
-
- this.pages = pages;
- this.pageList = Object.keys(this.pages);
- }
-
- pageList: string[];
- pages: Record<string, string[]>;
-
- getPageList() {
- return this.pageList;
- }
-
- async getMiddlewareList() {
- return [];
- }
-
- cssQueue = [];
-
- onImportCSS = (event) => {
- this.cssQueue.push(
- insertStyleSheet(event.detail).then(
- () => {},
- () => {},
- ),
- );
- };
-
- prefetch() {
- return Promise.resolve();
- }
-
- async loadPage(route: string): Promise<GoodPageCache> {
- const assets =
- this.pages[route] || this.pages[getAssetPathFromRoute(route)];
-
- var src;
- for (let asset of assets) {
- if (!asset.endsWith(".css")) {
- src = asset;
- break;
- }
- }
- console.assert(src, "Invalid or unknown route passed to loadPage");
-
- if ("__BunClearBuildFailure" in globalThis) {
- globalThis.__BunClearBuildFailure();
- }
-
- document.removeEventListener("onimportcss", this.onImportCSS);
- this.cssQueue.length = 0;
- document.addEventListener("onimportcss", this.onImportCSS, {
- passive: true,
- });
-
- try {
- const res = await import(src);
-
- if (this.cssQueue.length > 0) {
- await Promise.all(this.cssQueue);
- this.cssQueue.length = 0;
- }
-
- document.removeEventListener("onimportcss", this.onImportCSS);
-
- if (this.cssQueue.length > 0) {
- await Promise.all(this.cssQueue);
-
- this.cssQueue.length = 0;
- }
-
- return {
- page: res.default,
- mod: res,
- styleSheets: [],
- __N_SSG: false,
- __N_SSP: false,
- };
- } catch (exception) {
- console.error({ exception });
- }
- }
-}
diff --git a/packages/bun-framework-next/renderDocument.tsx b/packages/bun-framework-next/renderDocument.tsx
deleted file mode 100644
index 5eae9ebf1..000000000
--- a/packages/bun-framework-next/renderDocument.tsx
+++ /dev/null
@@ -1,835 +0,0 @@
-import App from "next/app";
-import { AmpStateContext } from "next/dist/shared/lib/amp-context";
-import { HeadManagerContext } from "next/dist/shared/lib/head-manager-context";
-import Loadable from "next/dist/shared/lib/loadable";
-import { LoadableContext } from "next/dist/shared/lib/loadable-context";
-import { RouterContext } from "next/dist/shared/lib/router-context";
-import type { NextRouter } from "next/dist/shared/lib/router/router";
-import {
- getDisplayName,
- loadGetInitialProps,
- type AppType,
- type ComponentsEnhancer,
- type DocumentInitialProps,
- type DocumentProps,
- type DocumentType,
- type NextComponentType,
- type RenderPage,
- type RenderPageResult,
-} from "next/dist/shared/lib/utils";
-import { HtmlContext } from "next/dist/shared/lib/html-context";
-import type { RenderOpts } from "next/dist/server/render";
-import * as NextDocument from "next/document";
-import * as ReactDOMServer from "react-dom/server.browser";
-import * as React from "react";
-import * as ReactIs from "react-is";
-import packageJson from "next/package.json";
-
-const nextVersion = packageJson.version;
-
-function appendNextBody(documentHTML: string, pageContent: string) {
- if (nextVersion.startsWith("12.0")) {
- const NEXT_12_0_BODY_RENDER_TARGET = "__NEXT_BODY_RENDER_TARGET__";
-
- const bodyRenderIdx = documentHTML.indexOf(NEXT_12_0_BODY_RENDER_TARGET);
-
- if (!documentHTML.startsWith("<!DOCTYPE html>")) {
- documentHTML = "<!DOCTYPE html>" + documentHTML;
- }
-
- return (
- documentHTML.substring(0, bodyRenderIdx) +
- pageContent +
- documentHTML.substring(
- bodyRenderIdx + NEXT_12_0_BODY_RENDER_TARGET.length,
- )
- );
- } else {
- var [renderTargetPrefix, renderTargetSuffix] = documentHTML.split(
- "<next-js-internal-body-render-target></next-js-internal-body-render-target>",
- );
-
- if (!renderTargetPrefix || !renderTargetSuffix) {
- throw new Error(
- "Can't find where your <App /> starts or where the <Document /> ends. \nThis is probably a version incompatibility. Please mention this error in Bun's discord\n\n" +
- documentHTML,
- );
- }
-
- if (!renderTargetPrefix.startsWith("<!DOCTYPE html>")) {
- renderTargetPrefix = "<!DOCTYPE html>" + renderTargetPrefix;
- }
-
- return (
- renderTargetPrefix +
- `<div id="__next">${pageContent || ""}</div>` +
- renderTargetSuffix
- );
- }
-}
-
-const dev = process.env.NODE_ENV === "development";
-
-type ParsedUrlQuery = Record<string, string | string[]>;
-
-const isJSFile = (file: string) =>
- file.endsWith(".js") ||
- file.endsWith(".jsx") ||
- file.endsWith(".mjs") ||
- file.endsWith(".ts") ||
- file.endsWith(".tsx");
-
-type DocumentFiles = {
- sharedFiles: readonly string[];
- pageFiles: readonly string[];
- allFiles: readonly string[];
-};
-
-function getScripts(files: DocumentFiles) {
- const { context, props } = this;
- const {
- assetPrefix,
- buildManifest,
- isDevelopment,
- devOnlyCacheBusterQueryString,
- } = context;
-
- const normalScripts = files?.allFiles?.filter(isJSFile) ?? [];
- const lowPriorityScripts =
- buildManifest?.lowPriorityFiles?.filter(isJSFile) ?? [];
- var entryPointIndex = -1;
- const scripts = [...normalScripts, ...lowPriorityScripts].map(
- (file, index) => {
- // if (file.includes(".entry.")) {
- // entryPointIndex = index;
- // }
-
- return (
- <script
- key={file}
- src={`${encodeURI(file)}${devOnlyCacheBusterQueryString}`}
- nonce={props.nonce}
- async
- crossOrigin={props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN}
- type="module"
- />
- );
- },
- );
- // if (entryPointIndex > 0) {
- // const entry = scripts.splice(entryPointIndex, 1);
- // scripts.unshift(...entry);
- // }
-
- return scripts;
-}
-
-interface DomainLocale {
- defaultLocale: string;
- domain: string;
- http?: true;
- locales?: string[];
-}
-
-function renderDocument(
- Document: DocumentType,
- {
- buildManifest,
- docComponentsRendered,
- props,
- docProps,
- pathname,
- query,
- buildId,
- page,
- canonicalBase,
- assetPrefix,
- runtimeConfig,
- nextExport,
- autoExport,
- isFallback,
- dynamicImportsIds,
- dangerousAsPath,
- err,
- dev,
- ampPath,
- ampState,
- inAmpMode,
- hybridAmp,
- dynamicImports,
- headTags,
- gsp,
- gssp,
- customServer,
- gip,
- appGip,
- unstable_runtimeJS,
- unstable_JsPreload,
- devOnlyCacheBusterQueryString,
- scriptLoader,
- locale,
- locales,
- defaultLocale,
- domainLocales,
- isPreview,
- disableOptimizedLoading,
- }: RenderOpts & {
- props: any;
- //
- page: string;
- //
- docComponentsRendered: DocumentProps["docComponentsRendered"];
- docProps: DocumentInitialProps;
- pathname: string;
- query: ParsedUrlQuery;
- dangerousAsPath: string;
- ampState: any;
- ampPath: string;
- inAmpMode: boolean;
- hybridAmp: boolean;
- dynamicImportsIds: (string | number)[];
- dynamicImports: string[];
- headTags: any;
- isFallback?: boolean;
- gsp?: boolean;
- gssp?: boolean;
- customServer?: boolean;
- gip?: boolean;
- appGip?: boolean;
- devOnlyCacheBusterQueryString: string;
- scriptLoader: any;
- isPreview?: boolean;
- autoExport?: boolean;
- },
-): string {
- const htmlProps = {
- __NEXT_DATA__: {
- props, // The result of getInitialProps
- page: page, // The rendered page
- query, // querystring parsed / passed by the user
- buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles
- assetPrefix: assetPrefix === "" ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
- runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
- nextExport, // If this is a page exported by `next export`
- autoExport, // If this is an auto exported page
- isFallback,
- dynamicIds:
- dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
- err: err || undefined, // err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
- gsp, // whether the page is getStaticProps
- gssp, // whether the page is getServerSideProps
- customServer, // whether the user is using a custom server
- gip, // whether the page has getInitialProps
- appGip, // whether the _app has getInitialProps
- locale,
- locales,
- defaultLocale,
- domainLocales,
- isPreview,
-
- pages: buildManifest.pages,
- },
- buildManifest,
- docComponentsRendered,
- dangerousAsPath,
- canonicalBase,
- ampPath,
- inAmpMode,
- isDevelopment: !!dev,
- hybridAmp,
- dynamicImports,
- assetPrefix,
- headTags,
- unstable_runtimeJS,
- unstable_JsPreload,
- devOnlyCacheBusterQueryString,
- scriptLoader,
- locale,
- disableOptimizedLoading,
- useMaybeDeferContent,
- ...docProps,
- };
-
- return ReactDOMServer.renderToStaticMarkup(
- <AmpStateContext.Provider value={ampState}>
- {/* HTMLContextProvider expects useMainContent */}
- {/* @ts-expect-error */}
- <HtmlContext.Provider value={htmlProps}>
- {/* Document doesn't expect useMaybeDeferContent */}
- {/* @ts-expect-error */}
- <Document {...htmlProps} {...docProps}></Document>
- </HtmlContext.Provider>
- </AmpStateContext.Provider>,
- );
-}
-
-class ServerRouter implements NextRouter {
- route: string;
- pathname: string;
- query: ParsedUrlQuery;
- asPath: string;
- basePath: string;
- events: any;
- isFallback: boolean;
- locale?: string;
- isReady: boolean;
- locales?: string[];
- defaultLocale?: string;
- domainLocales?: DomainLocale[];
- isPreview: boolean;
- isLocaleDomain: boolean;
-
- constructor(
- pathname: string,
- query: ParsedUrlQuery,
- as: string,
- { isFallback }: { isFallback: boolean },
- isReady: boolean,
- basePath: string,
- locale?: string,
- locales?: string[],
- defaultLocale?: string,
- domainLocales?: DomainLocale[],
- isPreview?: boolean,
- isLocaleDomain?: boolean,
- ) {
- this.route = pathname.replace(/\/$/, "") || "/";
- this.pathname = new URL(
- pathname || "/",
- Bun.origin || "http://localhost:3000",
- ).href;
-
- this.query = query;
- this.asPath = new URL(
- as || "/",
- Bun.origin || "http://localhost:3000",
- ).href;
- this.isFallback = isFallback;
- this.basePath = basePath;
- this.locale = locale;
- this.locales = locales;
- this.defaultLocale = defaultLocale;
- this.isReady = isReady;
- this.domainLocales = domainLocales;
- this.isPreview = !!isPreview;
- this.isLocaleDomain = !!isLocaleDomain;
- }
-
- push(): any {
- noRouter();
- }
- replace(): any {
- noRouter();
- }
- reload() {
- noRouter();
- }
- back() {
- noRouter();
- }
- prefetch(): any {
- noRouter();
- }
- beforePopState() {
- noRouter();
- }
-}
-
-function noRouter() {
- const message =
- 'No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance';
- throw new Error(message);
-}
-
-function enhanceComponents(
- options: ComponentsEnhancer,
- App: AppType,
- Component: NextComponentType,
-): {
- App: AppType;
- Component: NextComponentType;
-} {
- // For backwards compatibility
- if (typeof options === "function") {
- return {
- App,
- Component: options(Component),
- };
- }
-
- return {
- App: options.enhanceApp ? options.enhanceApp(App) : App,
- Component: options.enhanceComponent
- ? options.enhanceComponent(Component)
- : Component,
- };
-}
-const scriptsGetter = {
- get() {
- return getScripts;
- },
-};
-
-Object.defineProperty(NextDocument.Head.prototype, "getScripts", scriptsGetter);
-Object.defineProperty(
- NextDocument.NextScript.prototype,
- "getScripts",
- scriptsGetter,
-);
-try {
- Object.defineProperty(
- NextDocument.default.prototype,
- "getScripts",
- scriptsGetter,
- );
-} catch {}
-try {
- Object.defineProperty(NextDocument.default, "getScripts", scriptsGetter);
-} catch {}
-
-export async function render({
- route,
- request,
- PageNamespace,
- AppNamespace,
- appStylesheets = [],
- pageStylesheets = [],
- DocumentNamespace = null,
- buildId,
- routePaths = [],
- routeNames = [],
-}: {
- buildId: number;
- route: any;
- PageNamespace: { default: NextComponentType<any> };
- AppNamespace: { default: NextComponentType<any> } | null;
- DocumentNamespace: Object | null;
- appStylesheets: string[];
- pageStylesheets: string[];
- routePaths: string[];
- routeNames: string[];
- request: Request;
-}): Promise<Response> {
- const { default: Component } = PageNamespace || {};
- const getStaticProps = (PageNamespace as any)?.getStaticProps || null;
- const { default: AppComponent_ } = AppNamespace || {};
- var query = Object.assign({}, route.query);
- const origin = Bun.origin;
-
- // These are reversed in our Router versus Next.js...mostly due to personal preference.
- const pathname = route.name;
- var asPath = route.pathname;
- const pages = {};
-
- for (let i = 0; i < routeNames.length; i++) {
- const filePath = routePaths[i];
- const name = routeNames[i];
- pages[name] = [filePath];
- }
-
- if (appStylesheets.length > 0) {
- if (pages["/_app"]) {
- pages["/_app"].push(...appStylesheets);
- } else {
- pages["/_app"] = appStylesheets;
- }
- }
- pages[pathname] = [route.scriptSrc, ...pageStylesheets];
-
- if (!("/_app" in pages)) {
- pages["/_app"] = [];
- }
-
- const AppComponent = AppComponent_ || App;
- const Document = (DocumentNamespace as any)?.default || NextDocument.default;
-
- const callMiddleware = async (method: string, args: any[], props = false) => {
- let results: any = props ? {} : [];
-
- if ((Document as any)[`${method}Middleware`]) {
- let middlewareFunc = await (Document as any)[`${method}Middleware`];
- middlewareFunc = middlewareFunc.default || middlewareFunc;
-
- const curResults = await middlewareFunc(...args);
- if (props) {
- for (const result of curResults) {
- results = {
- ...results,
- ...result,
- };
- }
- } else {
- results = curResults;
- }
- }
- return results;
- };
-
- const headTags = (...args: any) => callMiddleware("headTags", args);
-
- if (!ReactIs.isValidElementType(Component)) {
- const exportNames = Object.keys(PageNamespace || {});
-
- const reactComponents = exportNames.filter(ReactIs.isValidElementType);
- if (reactComponents.length > 2) {
- throw new Error(
- `\"export default\" missing in ${
- route.filePath
- }.\nTry exporting one of ${reactComponents.join(", ")}\n`,
- );
- } else if (reactComponents.length === 2) {
- throw new Error(
- `\"export default\" missing in ${route.filePath}.\n\nTry exporting <${reactComponents[0]} /> or <${reactComponents[1]} />\n`,
- );
- } else if (reactComponents.length == 1) {
- throw new Error(
- `\"export default\" missing in ${route.filePath}. Try adding this to the bottom of the file:\n\n export default ${reactComponents[0]};\n`,
- );
- } else if (reactComponents.length == 0) {
- throw new Error(
- `\"export default\" missing in ${route.filePath}. Try exporting a React component.\n`,
- );
- }
- }
-
- const isFallback = !!query.__nextFallback;
- delete query.__nextFallback;
- delete query.__nextLocale;
- delete query.__nextDefaultLocale;
-
- // const isSSG = !!getStaticProps;
-
- const defaultAppGetInitialProps =
- App.getInitialProps === (App as any).origGetInitialProps;
-
- const hasPageGetInitialProps = !!(Component as any).getInitialProps;
- const pageIsDynamic = route.kind === "dynamic";
- const isPreview = false;
- const isAutoExport = false;
- const nextExport = isAutoExport || isFallback;
-
- if (isAutoExport || isFallback) {
- // // remove query values except ones that will be set during export
- // query = {
- // ...(query.amp
- // ? {
- // amp: query.amp,
- // }
- // : {}),
- // };
- asPath = `${asPath}${
- // ensure trailing slash is present for non-dynamic auto-export pages
- asPath.endsWith("/") && asPath !== "/" && !pageIsDynamic ? "/" : ""
- }`;
- }
-
- let head: JSX.Element[] = [
- <meta charSet="utf-8" />,
- <meta name="viewport" content="width=device-width" />,
- ];
-
- const reactLoadableModules: string[] = [];
- var scriptLoader = {};
- const AppContainer = ({ children }: any) => (
- <RouterContext.Provider value={router}>
- {/* <AmpStateContext.Provider value={ampState}> */}
- <HeadManagerContext.Provider
- value={{
- updateHead: (state) => {
- head = state;
- },
- updateScripts: (scripts) => {
- scriptLoader = scripts;
- },
- scripts: {},
- mountedInstances: new Set(),
- }}
- >
- <LoadableContext.Provider
- value={(moduleName) => reactLoadableModules.push(moduleName)}
- >
- {children}
- </LoadableContext.Provider>
- </HeadManagerContext.Provider>
- {/* </AmpStateContext.Provider> */}
- </RouterContext.Provider>
- );
-
- // Todo: Double check this when adding support for dynamic()
- await Loadable.preloadAll(); // Make sure all dynamic imports are loaded
-
- const router = new ServerRouter(
- pathname,
- query,
- asPath,
- {
- isFallback: isFallback,
- },
- true,
- origin,
- null,
- [], // renderOpts.locales,
- null, //renderOpts.defaultLocale,
- [], // renderOpts.domainLocales,
- false,
- false,
- );
-
- const ctx = {
- err: null,
- req: undefined,
- res: undefined,
- pathname,
- query,
- asPath,
- locale: null,
- locales: [],
- defaultLocale: null,
- AppTree: (props: any) => {
- return (
- <AppContainer>
- <App {...props} Component={Component} router={router} />
- </AppContainer>
- );
- },
- defaultGetInitialProps: async (
- docCtx: NextDocument.DocumentContext,
- ): Promise<DocumentInitialProps> => {
- const enhanceApp = (AppComp: any) => {
- return (props: any) => <AppComp {...props} />;
- };
-
- const { html, head } = await docCtx.renderPage({ enhanceApp });
- // const styles = jsxStyleRegistry.styles();
- return { html, head };
- },
- };
-
- var props: any = await loadGetInitialProps(AppComponent, {
- AppTree: ctx.AppTree,
- Component,
- router,
- ctx,
- });
-
- const pageProps = Object.assign({}, props.pageProps || {});
- // We don't call getServerSideProps on clients.
- // @ts-expect-error
- const getServerSideProps = PageNamespace.getServerSideProps;
-
- var responseHeaders: Headers;
-
- if (typeof getServerSideProps === "function") {
- const result = await getServerSideProps({
- params: route.params,
- query: route.query,
- req: {
- destroy() {},
- method: request.method,
- httpVersion: "1.1",
- rawHeaders: [],
- rawTrailers: [],
- socket: null,
- statusCode: 200,
- statusMessage: "OK",
- trailers: {},
- url: request.url,
- headers: new Proxy(
- {},
- {
- get(target, name) {
- return request.headers.get(name as string);
- },
- has(target, name) {
- return request.headers.has(name as string);
- },
- },
- ),
- },
- res: {
- getHeaders() {
- return {};
- },
- getHeaderNames() {
- return {};
- },
- flushHeaders() {},
- getHeader(name) {
- if (!responseHeaders) return undefined;
- return responseHeaders.get(name);
- },
- hasHeader(name) {
- if (!responseHeaders) return undefined;
- return responseHeaders.has(name);
- },
- headersSent: false,
- setHeader(name, value) {
- responseHeaders = responseHeaders || new Headers();
- responseHeaders.set(name, String(value));
- },
- cork() {},
- end() {},
- finished: false,
- },
- resolvedUrl: route.pathname,
- preview: false,
- previewData: null,
- locale: null,
- locales: [],
- defaultLocale: null,
- });
-
- if (result) {
- if ("props" in result) {
- if (typeof result.props === "object") {
- Object.assign(pageProps, result.props);
- }
- }
- }
- } else if (typeof getStaticProps === "function") {
- const result = await getStaticProps({
- params: route.params,
- query: route.query,
- req: null,
- res: null,
- resolvedUrl: route.pathname,
- preview: false,
- previewData: null,
- locale: null,
- locales: [],
- defaultLocale: null,
- });
-
- if (result) {
- if ("props" in result) {
- if (typeof result.props === "object") {
- Object.assign(pageProps, result.props);
- }
- }
- }
- }
-
- const renderToString = ReactDOMServer.renderToString;
- const ErrorDebug = null;
-
- props.pageProps = pageProps;
-
- const renderPage: RenderPage = (
- options: ComponentsEnhancer = {},
- ): RenderPageResult | Promise<RenderPageResult> => {
- if (ctx.err && ErrorDebug) {
- const htmlOrPromise = renderToString(<ErrorDebug error={ctx.err} />);
- return { html: htmlOrPromise, head };
- }
-
- if (dev && (props.router || props.Component)) {
- throw new Error(
- `'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`,
- );
- }
-
- const { App: EnhancedApp, Component: EnhancedComponent } =
- // Argument of type 'NextComponentType<any, {}, {}> | typeof App' is not assignable to parameter of type 'AppType'.
- // @ts-expect-error
- enhanceComponents(options, AppComponent, Component);
-
- const htmlOrPromise = renderToString(
- <AppContainer>
- <EnhancedApp
- Component={EnhancedComponent}
- router={router}
- {...props}
- pageProps={pageProps}
- />
- </AppContainer>,
- );
-
- return { html: htmlOrPromise, head };
- };
-
- const documentCtx = { ...ctx, renderPage };
- const docProps: DocumentInitialProps = await loadGetInitialProps(
- Document,
- documentCtx,
- );
-
- if (!docProps || typeof docProps.html !== "string") {
- const message = `"${getDisplayName(
- Document,
- )}.getInitialProps()" should resolve to an object with a "html" prop set with a valid html string`;
- throw new Error(message);
- }
-
- const renderOpts = {
- params: route.params,
- };
-
- const docComponentsRendered: DocumentProps["docComponentsRendered"] = {};
-
- let html = renderDocument(Document, {
- docComponentsRendered,
- ...renderOpts,
- disableOptimizedLoading: false,
- canonicalBase: origin,
- buildManifest: {
- devFiles: [],
- allFiles: [],
- polyfillFiles: [],
- lowPriorityFiles: [],
- // buildManifest doesn't expect pages, even though its used
- // @ts-expect-error
- pages,
- },
- // Only enabled in production as development mode has features relying on HMR (style injection for example)
- // @ts-expect-error
- unstable_runtimeJS: true,
- // process.env.NODE_ENV === "production"
- // ? pageConfig.unstable_runtimeJS
- // : undefined,
- // unstable_JsPreload: pageConfig.unstable_JsPreload,
- // @ts-expect-error
- unstable_JsPreload: true,
- dangerousAsPath: router.asPath,
- ampState: undefined,
- props,
- assetPrefix: "",
- headTags: await headTags(documentCtx),
- isFallback,
- docProps,
- page: pathname,
- pathname,
- ampPath: undefined,
- query,
- inAmpMode: false,
- hybridAmp: undefined,
- dynamicImportsIds: [], // Array.from(dynamicImportsIds),
- dynamicImports: [], //Array.from(dynamicImports),
- gsp: !!getStaticProps ? true : undefined,
- gssp: !!getServerSideProps ? true : undefined,
- gip: hasPageGetInitialProps ? true : undefined,
- appGip: !defaultAppGetInitialProps ? true : undefined,
- devOnlyCacheBusterQueryString: "",
- scriptLoader,
- isPreview: isPreview,
- autoExport: nextExport === true ? true : undefined,
- nextExport: nextExport,
- useMaybeDeferContent,
- });
- // __NEXT_BODY_RENDER_TARGET__
- html = appendNextBody(html, docProps.html);
- html = html
- .replaceAll('"/_next/http://', '"http://')
- .replaceAll('"/_next/https://', '"https://');
- if (responseHeaders) {
- return new Response(html, { headers: responseHeaders });
- } else {
- return new Response(html);
- }
-}
-
-export function useMaybeDeferContent(
- _name: string,
- contentFn: () => JSX.Element,
-): [boolean, JSX.Element] {
- return [false, contentFn()];
-}
diff --git a/packages/bun-framework-next/server.development.tsx b/packages/bun-framework-next/server.development.tsx
deleted file mode 100644
index a19ffd149..000000000
--- a/packages/bun-framework-next/server.development.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { render } from "./renderDocument";
-import packagejson from "next/package.json";
-
-const version = packagejson.version;
-
-if (!version.startsWith("12.2")) {
- console.warn(
- "Possibly incompatible Next.js version: ",
- version,
- ". Please upgrade to Next.js 12.2.0+.\n",
- );
-}
-
-let buildId = 0;
-
-let DocumentLoaded = false;
-let DocumentNamespace;
-
-import(Bun.routesDir + "_document").then(
- (doc) => {
- DocumentNamespace = doc;
- DocumentLoaded = true;
- },
- (err) => {
- // ResolveError is defined outside of bun-framework-next in ../../src/runtime/errors
- // @ts-expect-error
- if (err instanceof ResolveError) {
- DocumentLoaded = true;
- } else {
- console.error(err);
- }
- },
-);
-
-addEventListener("fetch", async (event: FetchEvent) => {
- const route = Bun.match(event);
-
- // This imports the currently matched route.
- let PageNamespace: any;
-
- try {
- PageNamespace = await import(route.filePath);
- } catch (exception) {
- console.error("Error loading page:", route.filePath);
- throw exception;
- }
-
- // This returns all .css files that were imported in the line above.
- // It's recursive, so any file that imports a CSS file will be included.
- const pageStylesheets = (Bun.getImportedStyles() as string[]).slice();
-
- let appRoute: any;
-
- try {
- appRoute = await import(Bun.routesDir + "_app");
- } catch (exception) {
- // ResolveError is defined outside of bun-framework-next in ../../src/runtime/errors
- // @ts-expect-error
- if (exception && !(exception instanceof ResolveError)) {
- console.error("Error loading app:", Bun.routesDir + "_app");
- throw exception;
- }
- }
-
- const appStylesheets = (Bun.getImportedStyles() as string[]).slice();
- let response: Response;
- try {
- response = await render({
- route,
- PageNamespace,
- appStylesheets,
- pageStylesheets,
- DocumentNamespace,
- AppNamespace: appRoute,
- buildId,
- routePaths: Bun.getRouteFiles(),
- routeNames: Bun.getRouteNames(),
- request: event.request,
- });
- } catch (exception) {
- console.error("Error rendering route", route.filePath);
- throw exception;
- }
-
- event.respondWith(response);
-
- buildId++;
-});
-
-declare let Bun: any;
-export {};
diff --git a/packages/bun-framework-next/tsconfig.json b/packages/bun-framework-next/tsconfig.json
deleted file mode 100644
index 96e13d1eb..000000000
--- a/packages/bun-framework-next/tsconfig.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "target": "esnext",
- "lib": [
- "dom",
- "dom.iterable",
- "esnext",
- "WebWorker"
- ],
- "strict": false,
- "forceConsistentCasingInFileNames": true,
- "noEmit": true,
- "esModuleInterop": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "jsx": "preserve",
- },
- "include": [
- "next-env.d.ts",
- "**/*.ts",
- "**/*.tsx",
- "empty.js"
- ],
- "exclude": [
- "node_modules"
- ],
-} \ No newline at end of file