Skip to content

Commit de44d64

Browse files
committed
Fix for using compatibility_flags = [ "nodejs_compat" ] instead
1 parent ef96f38 commit de44d64

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

cf/polyfills.js

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { EventEmitter } from 'events'
2-
import { connect as Connect } from 'cloudflare:sockets'
1+
import { EventEmitter } from 'node:events'
2+
import { Buffer } from 'node:buffer'
33

44
const Crypto = globalThis.crypto
55

@@ -64,6 +64,22 @@ export const crypto = {
6464
})
6565
}
6666

67+
export const process = {
68+
env: {}
69+
}
70+
71+
export const os = {
72+
userInfo() {
73+
return { username: 'postgres' }
74+
}
75+
}
76+
77+
export const fs = {
78+
readFile() {
79+
throw new Error('Reading files not supported on CloudFlare')
80+
}
81+
}
82+
6783
export const net = {
6884
isIP: x => RegExp.prototype.test.call(IPv4Reg, x) ? 4 : RegExp.prototype.test.call(IPv6Reg, x) ? 6 : 0,
6985
Socket
@@ -108,10 +124,11 @@ function Socket() {
108124

109125
return tcp
110126

111-
function connect(port, host) {
127+
async function connect(port, host) {
112128
try {
113129
tcp.readyState = 'opening'
114-
tcp.raw = Connect(host + ':' + port, tcp.ssl ? { secureTransport: 'starttls' } : {})
130+
const { connect } = await import('cloudflare:sockets')
131+
tcp.raw = connect(host + ':' + port, tcp.ssl ? { secureTransport: 'starttls' } : {})
115132
tcp.raw.closed.then(
116133
() => {
117134
tcp.readyState !== 'upgrade'

transpile.cf.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,19 @@ function transpile(x) {
2020
? 'import { setImmediate, clearImmediate } from \'../polyfills.js\'\n'
2121
: ''
2222

23-
return timers + x
23+
const process = x.includes('process.')
24+
? 'import { process } from \'../polyfills.js\'\n'
25+
: ''
26+
27+
const buffer = x.includes('Buffer')
28+
? 'import { Buffer } from \'node:buffer\'\n'
29+
: ''
30+
31+
return process + buffer + timers + x
2432
.replace('import net from \'net\'', 'import { net } from \'../polyfills.js\'')
2533
.replace('import tls from \'tls\'', 'import { tls } from \'../polyfills.js\'')
2634
.replace('import crypto from \'crypto\'', 'import { crypto } from \'../polyfills.js\'')
35+
.replace('import os from \'os\'', 'import { os } from \'../polyfills.js\'')
36+
.replace('import fs from \'fs\'', 'import { fs } from \'../polyfills.js\'')
37+
.replace(/ from '([a-z_]+)'/g, ' from \'node:$1\'')
2738
}

0 commit comments

Comments
 (0)