Skip to content

Commit 514e7f0

Browse files
committed
Convert to esm with backwards cjs compat
1 parent 605a917 commit 514e7f0

15 files changed

+127
-81
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
node_modules
2+
cjs

lib/backend.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
const { errors } = require('./errors.js')
2-
, { entries, errorFields } = require('./types.js')
1+
import { errors } from './errors.js'
2+
import { entries, errorFields } from './types.js'
33

44
const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc)
55
, N = '\u0000'
66

7-
module.exports = Backend
7+
export default Backend
88

99
function Backend({
1010
onparse,

lib/bytes.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ const b = Object.assign(messages, {
5959
}
6060
})
6161

62-
module.exports = b
62+
export default b
6363

6464
function fit(x) {
6565
if (buffer.length - b.i < x) {

lib/connection.js

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
const net = require('net')
2-
const tls = require('tls')
3-
const frontend = require('./frontend.js')
4-
const Backend = require('./backend.js')
5-
const Queue = require('./queue.js')
6-
const { END, retryRoutines } = require('./types.js')
7-
const { errors } = require('./errors.js')
8-
9-
module.exports = Connection
1+
import net from 'net'
2+
import tls from 'tls'
3+
import frontend from './frontend.js'
4+
import Backend from './backend.js'
5+
import Queue from './queue.js'
6+
import { END, retryRoutines } from './types.js'
7+
import { errors } from './errors.js'
8+
9+
export default Connection
1010

1111
let count = 1
1212

lib/errors.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
class PostgresError extends Error {
1+
export class PostgresError extends Error {
22
constructor(x) {
33
super(x.message)
44
this.name = this.constructor.name
55
Object.assign(this, x)
66
}
77
}
88

9-
module.exports.PostgresError = PostgresError
10-
11-
module.exports.errors = {
9+
export const errors = {
1210
connection,
1311
postgres,
1412
generic,

lib/frontend.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
const crypto = require('crypto')
2-
const bytes = require('./bytes.js')
3-
const { entries } = require('./types.js')
4-
const { errors } = require('./errors.js')
1+
import crypto from 'crypto'
2+
import bytes from './bytes.js'
3+
import { entries } from './types.js'
4+
import { errors } from './errors.js'
55

66
const N = String.fromCharCode(0)
77
const empty = Buffer.alloc(0)
@@ -36,7 +36,7 @@ const auths = {
3636
12: SASLFinal
3737
}
3838

39-
module.exports = {
39+
export default {
4040
StartupMessage,
4141
SSLRequest,
4242
auth,

lib/index.js

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
const fs = require('fs')
2-
const Url = require('url')
3-
const Stream = require('stream')
4-
const Connection = require('./connection.js')
5-
const Queue = require('./queue.js')
6-
const Subscribe = require('./subscribe.js')
7-
const { errors, PostgresError } = require('./errors.js')
8-
const {
1+
import fs from 'fs'
2+
import os from 'os'
3+
import Url from 'url'
4+
import Stream from 'stream'
5+
import Connection from './connection.js'
6+
import Queue from './queue.js'
7+
import Subscribe from './subscribe.js'
8+
import { errors, PostgresError } from './errors.js'
9+
import {
910
mergeUserTypes,
1011
arraySerializer,
1112
arrayParser,
@@ -20,7 +21,7 @@ const {
2021
escape,
2122
types,
2223
END
23-
} = require('./types.js')
24+
} from './types.js'
2425

2526
const notPromise = {
2627
P: {},
@@ -51,7 +52,7 @@ Object.assign(Postgres, {
5152

5253
const originCache = new Map()
5354

54-
module.exports = Postgres
55+
export default Postgres
5556

5657
function Postgres(a, b) {
5758
if (arguments.length && !a)
@@ -704,7 +705,7 @@ function warn(x) {
704705

705706
function osUsername() {
706707
try {
707-
return require('os').userInfo().username // eslint-disable-line
708+
return os.userInfo().username // eslint-disable-line
708709
} catch (_) {
709710
return
710711
}

lib/queue.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
module.exports = Queue
1+
export default Queue
22

33
function Queue() {
44
let xs = []

lib/subscribe.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
module.exports = function(postgres, a, b) {
1+
export default function Subscribe(postgres, a, b) {
22
const listeners = new Map()
33

44
let connection

lib/types.js

+19-21
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
const char = module.exports.char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc)
2-
const entries = o => Object.keys(o).map(x => [x, o[x]])
1+
export const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc)
2+
export const entries = o => Object.keys(o).map(x => [x, o[x]])
33

44
// These were the fastest ways to do it in Node.js v12.11.1 (add tests to revise if this changes)
5-
const types = module.exports.types = {
5+
export const types = {
66
string: {
77
to: 25,
88
from: null, // defaults to string
@@ -42,14 +42,12 @@ const types = module.exports.types = {
4242

4343
const defaultHandlers = typeHandlers(types)
4444

45-
const serializers = module.exports.serializers = defaultHandlers.serializers
46-
const parsers = module.exports.parsers = defaultHandlers.parsers
45+
export const serializers = defaultHandlers.serializers
46+
export const parsers = defaultHandlers.parsers
4747

48-
module.exports.entries = entries
48+
export const END = {}
4949

50-
module.exports.END = {}
51-
52-
module.exports.mergeUserTypes = function(types) {
50+
export const mergeUserTypes = function(types) {
5351
const user = typeHandlers(types || {})
5452
return {
5553
serializers: Object.assign({}, serializers, user.serializers),
@@ -65,7 +63,7 @@ function typeHandlers(types) {
6563
}, { parsers: {}, serializers: {} })
6664
}
6765

68-
module.exports.escape = function escape(str) {
66+
export const escape = function escape(str) {
6967
return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"'
7068
}
7169

@@ -75,7 +73,7 @@ const type = {
7573
boolean: 16
7674
}
7775

78-
module.exports.inferType = function inferType(x) {
76+
export const inferType = function inferType(x) {
7977
return (x && x.type) || (x instanceof Date
8078
? 1184
8179
: Array.isArray(x)
@@ -94,7 +92,7 @@ function arrayEscape(x) {
9492
.replace(escapeQuote, '\\"')
9593
}
9694

97-
module.exports.arraySerializer = function arraySerializer(xs, serializer) {
95+
export const arraySerializer = function arraySerializer(xs, serializer) {
9896
if (!xs.length)
9997
return '{}'
10098

@@ -116,7 +114,7 @@ const arrayParserState = {
116114
last: 0
117115
}
118116

119-
module.exports.arrayParser = function arrayParser(x, parser) {
117+
export const arrayParser = function arrayParser(x, parser) {
120118
arrayParserState.i = arrayParserState.last = 0
121119
return arrayParserLoop(arrayParserState, x, parser)
122120
}
@@ -156,27 +154,27 @@ function arrayParserLoop(s, x, parser) {
156154
return xs
157155
}
158156

159-
module.exports.toCamel = x => {
157+
export const toCamel = x => {
160158
let str = x[0]
161159
for (let i = 1; i < x.length; i++)
162160
str += x[i] === '_' ? x[++i].toUpperCase() : x[i]
163161
return str
164162
}
165163

166-
module.exports.toPascal = x => {
164+
export const toPascal = x => {
167165
let str = x[0].toUpperCase()
168166
for (let i = 1; i < x.length; i++)
169167
str += x[i] === '_' ? x[++i].toUpperCase() : x[i]
170168
return str
171169
}
172170

173-
module.exports.toKebab = x => x.replace(/_/g, '-')
171+
export const toKebab = x => x.replace(/_/g, '-')
174172

175-
module.exports.fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase()
176-
module.exports.fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase()
177-
module.exports.fromKebab = x => x.replace(/-/g, '_')
173+
export const fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase()
174+
export const fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase()
175+
export const fromKebab = x => x.replace(/-/g, '_')
178176

179-
module.exports.errorFields = entries({
177+
export const errorFields = entries({
180178
S: 'severity_local',
181179
V: 'severity',
182180
C: 'code',
@@ -197,7 +195,7 @@ module.exports.errorFields = entries({
197195
R: 'routine'
198196
}).reduce(char, {})
199197

200-
module.exports.retryRoutines = {
198+
export const retryRoutines = {
201199
FetchPreparedStatement: true,
202200
RevalidateCachedQuery: true,
203201
transformAssignedExpr: true

package.json

+10-3
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,23 @@
22
"name": "postgres",
33
"version": "2.0.0-beta.9",
44
"description": "Fastest full featured PostgreSQL client for Node.js",
5-
"main": "lib/index.js",
5+
"type": "module",
6+
"module": "lib/index.js",
7+
"main": "cjs/index.js",
8+
"exports": {
9+
"import": "./lib/index.js",
10+
"default": "./cjs/index.js"
11+
},
612
"types": "types/index.d.ts",
713
"typings": "types/index.d.ts",
8-
"type": "commonjs",
914
"scripts": {
10-
"test": "node tests/index.js",
15+
"build": "node transpile.cjs",
16+
"test": "pushd tests && node index.js && popd && npm run build && pushd cjs/tests && node index.js",
1117
"lint": "eslint lib && eslint tests",
1218
"prepublishOnly": "npm run lint && npm test"
1319
},
1420
"files": [
21+
"/cjs",
1522
"/lib",
1623
"/types"
1724
],

tests/bootstrap.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const cp = require('child_process')
1+
import cp from 'child_process'
22

33
exec('psql -c "create user postgres_js_test"')
44
exec('psql -c "alter system set password_encryption=md5"')

tests/index.js

+16-16
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
/* eslint no-console: 0 */
22

3-
require('./bootstrap.js')
3+
import './bootstrap.js'
44

5-
const { t, not, ot } = require('./test.js') // eslint-disable-line
6-
const cp = require('child_process')
7-
const path = require('path')
8-
const net = require('net')
9-
const fs = require('fs')
5+
import { t, not, ot } from './test.js' // eslint-disable-line
6+
import cp from 'child_process'
7+
import path from 'path'
8+
import net from 'net'
9+
import fs from 'fs'
1010

1111
/** @type {import('../types')} */
12-
const postgres = require('../lib')
12+
import postgres from '../lib/index.js'
1313
const delay = ms => new Promise(r => setTimeout(r, ms))
1414

1515
const login = {
@@ -397,13 +397,13 @@ t('Point type array', async() => {
397397
})
398398

399399
t('sql file', async() =>
400-
[1, (await sql.file(path.join(__dirname, 'select.sql')))[0].x]
400+
[1, (await sql.file(path.join('select.sql')))[0].x]
401401
)
402402

403403
t('sql file can stream', async() => {
404404
let result
405405
await sql
406-
.file(path.join(__dirname, 'select.sql'), { cache: false })
406+
.file(path.join('select.sql'), { cache: false })
407407
.stream(({ x }) => result = x)
408408

409409
return [1, result]
@@ -414,15 +414,15 @@ t('sql file throws', async() =>
414414
)
415415

416416
t('sql file cached', async() => {
417-
await sql.file(path.join(__dirname, 'select.sql'))
417+
await sql.file(path.join('select.sql'))
418418
await delay(20)
419419

420-
return [1, (await sql.file(path.join(__dirname, 'select.sql')))[0].x]
420+
return [1, (await sql.file(path.join('select.sql')))[0].x]
421421
})
422422

423423
t('Parameters in file', async() => {
424424
const result = await sql.file(
425-
path.join(__dirname, 'select-param.sql'),
425+
path.join('select-param.sql'),
426426
['hello']
427427
)
428428
return ['hello', result[0].x]
@@ -1091,8 +1091,8 @@ t('numeric is returned as string', async() => [
10911091
t('Async stack trace', async() => {
10921092
const sql = postgres({ ...options, debug: false })
10931093
return [
1094-
parseInt(new Error().stack.split('\n')[1].split(':')[1]) + 1,
1095-
parseInt(await sql`select.sql`.catch(x => x.stack.split('\n').pop().split(':')[1]))
1094+
parseInt(new Error().stack.split('\n')[1].match(':([0-9]+):')[1]) + 1,
1095+
parseInt(await sql`select.sql`.catch(x => x.stack.split('\n').pop().match(':([0-9]+):')[1]))
10961096
]
10971097
})
10981098

@@ -1404,7 +1404,7 @@ t('Copy write as first works', async() => {
14041404
t('Copy from file works', async() => {
14051405
await sql`create table test (x int, y int, z int)`
14061406
await new Promise(r => fs
1407-
.createReadStream(path.join(__dirname, 'copy.csv'))
1407+
.createReadStream(path.join('copy.csv'))
14081408
.pipe(sql`copy test from stdin`.writable())
14091409
.on('finish', r)
14101410
)
@@ -1432,7 +1432,7 @@ t('Copy from works in transaction', async() => {
14321432

14331433
t('Copy from abort works', async() => {
14341434
const sql = postgres(options)
1435-
const readable = fs.createReadStream(path.join(__dirname, 'copy.csv'))
1435+
const readable = fs.createReadStream(path.join('copy.csv'))
14361436

14371437
await sql`create table test (x int, y int, z int)`
14381438
await sql`TRUNCATE TABLE test`

0 commit comments

Comments
 (0)