Skip to content

Commit

Permalink
it works
Browse files Browse the repository at this point in the history
  • Loading branch information
remorses committed Jul 28, 2023
1 parent 76209ec commit 23606ba
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 12 deletions.
17 changes: 15 additions & 2 deletions middleflare/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,19 @@ const cli = cac(name)

cli.command('')
.option('--url <url>', 'Your deployed Next.js url, like xxx.fly.dev', {})
.option(
'--use-secrets',
'process.env.VAR is converted to use your Cloudflare secrets',
{ default: false },
)
.option('--middleware <middlewarePath>', 'Your Next.js middleware path', {})
.action(async (opts) => {
console.log(opts)
const { middleware, url } = opts
// console.log(opts)
const { middleware, url, useSecrets } = opts
await buildMiddleware({
middleware,
url,
useSecrets,
})
})

Expand All @@ -35,3 +41,10 @@ async function main() {
}

main()

let finalUrl =
process.env.NEXT_PUBLIC_ENV === 'development'
? `http://localhost:5467`
: process.env.NEXT_PUBLIC_ENV === 'preview'
? 'https://knowledg-website-preview.fly.dev'
: ``
28 changes: 20 additions & 8 deletions middleflare/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import path from 'path'

// console.log(process.env.DIRECT_URL)

export async function buildMiddleware({ middleware, url }) {
export async function buildMiddleware({ useSecrets, middleware, url }) {
console.log(`Bundling middleware to dist/worker.js`)
if (!middleware) {
throw new Error(`--middleware is required`)
}
Expand All @@ -21,11 +22,15 @@ export async function buildMiddleware({ middleware, url }) {
throw new Error(`invalid url ${url}`)
}
// to make docker generate native prisma addons
const define = Object.fromEntries(
Object.keys(process.env).map((k) => {
return [`process.env.${k}`, JSON.stringify(process.env[k])]
}),
)
let envVars = !useSecrets
? Object.fromEntries(
Object.keys(process.env).map((k) => {
return [`process.env.${k}`, JSON.stringify(process.env[k])]
}),
)
: Object.keys(process.env).map((k) => {
return [`process.env.${k}`, 'globalThis.__ENV__.' + k]
})
fs.promises.unlink('dist').catch((e) => null)
const index = path.resolve(
path.dirname(require.resolve('../package.json')),
Expand Down Expand Up @@ -55,7 +60,14 @@ export async function buildMiddleware({ middleware, url }) {
// mainFields: ['module', 'main'],
plugins: [
LooselyIgnoreDeps(),
polyfillNode(), //
polyfillNode({
globals: {
global: true,
buffer: true,
navigator: true,
process: true,
},
}), //
StripWasmModulesQuery(),
// UseNextEsm(),
],
Expand All @@ -64,7 +76,7 @@ export async function buildMiddleware({ middleware, url }) {
logOverride: {
'import-is-undefined': 'silent',
},
define,
define: envVars,
// splitting: false,
// splitting: true,
// outdir: 'dist',
Expand Down
4 changes: 3 additions & 1 deletion middleflare/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ async function processMiddlewareResp(
} else if (!rewriteHeader && !resp.headers.has('location')) {
// We should set the final response body and status to the middleware's if it does not want
// to continue and did not rewrite/redirect the URL.

return new Response(resp.body, {
status: resp.status,
headers: resp.headers,
Expand Down Expand Up @@ -88,6 +88,7 @@ function applyHeaders(
source: Record<string, string> | Headers,
): void {
const entries =

source instanceof Headers ? source.entries() : Object.entries(source)
for (const [key, value] of entries) {
const lowerKey = key.toLowerCase()
Expand All @@ -111,6 +112,7 @@ function safeUrl(url: string) {
export function middlewareAdapter({ middlewareModule, finalUrl }) {
const worker: ExportedHandler = {
async fetch(request, env, context) {
globalThis.__ENV__ = env
try {
// @ts-ignore
context.sourcePage = new URL(request.url).pathname
Expand Down
3 changes: 3 additions & 0 deletions middleflare/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
"extends": "../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",

"types": ["@cloudflare/workers-types"],
"outDir": "dist"
},

"include": ["src"]
}
2 changes: 1 addition & 1 deletion tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"module": "commonjs",
"allowJs": true,
"moduleResolution": "Node",
"lib": ["es2022", "es2017", "es7", "es6", "dom"],
"lib": ["es2022", "es2017", "es7", "es6", "ESNext"],
"declaration": true,
"declarationMap": true,
"strict": true,
Expand Down

0 comments on commit 23606ba

Please sign in to comment.