Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updates and upgrades and adds support for esm, jsx, and typescript #253

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ example/
screenshots/
.npmignore
.tmp
LICENSE.md
LICENSE.md
yarn.lock
package-lock.json
16 changes: 12 additions & 4 deletions bin/bundle-livereload-client.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
var browserify = require('browserify')
var path = require('path')
var fs = require('fs')
var UglifyJS = require('uglify-js')
//var UglifyJS = require('uglify-js')

var buildFolder = path.resolve(__dirname, '..', 'build')
var buildFile = path.resolve(buildFolder, 'bundled-livereload-client.js')
var clientFile = path.resolve(__dirname, '..', 'lib', 'reload', 'client.js')

mkdir(buildFolder, function (err) {
if (err) return error(err)
browserify().add(clientFile).bundle(function (err, src) {
browserify()
.add(clientFile)
.plugin("tinyify")
.bundle()
.pipe(fs.createWriteStream("build/bundled-livereload-client.js"))

/* .bundle(function (err, src) {
if (err) return error(err)
var result
try {
result = UglifyJS.minify(src.toString(), { fromString: true }).code
} catch (err) {
}
catch (err) {
return error(err)
}
fs.writeFile(buildFile, result, function (err) {
if (err) error(err)
})
})
}) */

})

function mkdir (path, cb) {
Expand Down
2 changes: 2 additions & 0 deletions example/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import createLoop from 'canvas-loop'
import createContext from '2d-context'


const context = createContext()
const canvas = context.canvas


const app = createLoop(canvas, {
scale: window.devicePixelRatio
})
Expand Down
37 changes: 37 additions & 0 deletions example/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* globals Image */
import createLoop from 'canvas-loop'
import createContext from '2d-context'


const context = createContext() as CanvasRenderingContext2D
const canvas = context.canvas as HTMLCanvasElement

type IApp = ReturnType<typeof createLoop> & Partial<NodeJS.EventEmitter> & {
shape?: [ width: number, height: number ],
scale?: any
}

const app: IApp = createLoop(canvas, {
scale: window.devicePixelRatio
})
document.body.appendChild(canvas)

const img = new Image()
img.onload = () => app.start()
img.src = 'baboon.png'

let time = 0

app.on('tick', (dt) => {
const [ width, height ] = app.shape
context.clearRect(0, 0, width, height)

time += dt / 1000

context.save()
context.scale(app.scale, app.scale)
context.fillRect(Math.sin(time) * 50 + 300, 50, 20, 40)
context.fillText('from browserify with typescript!', 40, 40)
context.drawImage(img, 50, 50)
context.restore()
})
2 changes: 1 addition & 1 deletion example/main.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
body {
background: #e1e1e1;
background: #9a8b9e;
}
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var parseArgs = require('./lib/parse-args')
var budo = require('./lib/budo')
var color = require('term-color')
var color = require('kolorist')
var stdoutStream = require('stdout-stream')
var exec = require('child_process').exec

Expand All @@ -24,7 +24,7 @@ function budoCLI (args, opts) {
if (argv.version) {
console.log('budo v' + require('./package.json').version)
console.log('browserify v' + require('browserify/package.json').version)
console.log('watchify v' + require('watchify-middleware').getWatchifyVersion())
console.log('watchify v' + require('watchify/package.json').version)
return null
}

Expand Down
4 changes: 2 additions & 2 deletions lib/budo.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var bole = require('bole')
var xtend = require('xtend')
var once = require('once')
var path = require('path')
var EventEmitter = require('events').EventEmitter
var {EventEmitter} = require('events')
var isMatch = require('micromatch')
var openUrl = require('opn')
var internalIp = require('internal-ip')
Expand Down Expand Up @@ -112,7 +112,7 @@ function createBudo (entries, opts) {
})
}

var defaultInternalIp = internalIp.v4.sync()
var defaultInternalIp = opts.useLocalNetworkIp ? internalIp.v4.sync() : "localhost";
var defaultWatchGlob = opts.watchGlob || '**/*.{html,css}'
var server = null
var closed = false
Expand Down
7 changes: 6 additions & 1 deletion lib/bundler.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
var xtend = require('xtend')
var createMiddleware = require('watchify-middleware').emitter
var {createMiddleware} = require('./watchify-middleware')
var fromArgs = require('browserify/bin/args')
var browserify = require('browserify')
var path = require('path')
var defaultErrorHandler = require('./error-handler')
var sucrasify = require("./sucrasify")

module.exports = createBundler
function createBundler (files, opts) {
var bOpts = xtend({
extensions: [".js", ".jsx", ".ts", ".tsx"],
cache: {},
packageCache: {},
debug: opts.debug
Expand All @@ -27,6 +29,8 @@ function createBundler (files, opts) {
bundler.add(path.resolve(file))
})

bundler.transform([sucrasify, {global: true}])

var errorHandler = opts.errorHandler
if (typeof errorHandler !== 'function' && errorHandler !== false) {
errorHandler = defaultErrorHandler
Expand All @@ -39,6 +43,7 @@ function createBundler (files, opts) {
rootDirName = path.basename(cwd) + path.sep
}
return createMiddleware(bundler, {
output: opts.output || null,
delay: opts.delay || 0,
initialBundle: false,
errorHandler: typeof errorHandler === 'function'
Expand Down
6 changes: 3 additions & 3 deletions lib/file-watch.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// a thin wrapper around chokidar file watching HTML / CSS
var watch = require('chokidar').watch
var {watch} = require('chokidar')
var xtend = require('xtend')
var Emitter = require('events/')
var {EventEmitter} = require('events')

var ignores = [
'node_modules/**', 'bower_components/**',
Expand All @@ -16,7 +16,7 @@ module.exports = function (glob, opt) {
ignoreInitial: true
}, opt)

var emitter = new Emitter()
var emitter = new EventEmitter()
var closed = false

var watcher = watch(glob, opt)
Expand Down
92 changes: 85 additions & 7 deletions lib/get-ports.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
var xtend = require('xtend')
var getPorts = require('get-ports')
var net = require("net")
var os = require("os");

module.exports = getServerPorts

function getServerPorts (opt, cb) {
opt = xtend({ port: 9966 }, opt)

Expand All @@ -14,11 +16,87 @@ function getServerPorts (opt, cb) {
})
}

getFreePort(opt.port)
.then(portNumber => cb(null, {port: portNumber}))

// find available ports
getPorts([ opt.port ], function (err, ports) {
if (err) return cb(err)
cb(null, {
port: ports[0]
})
})
// getPorts([ opt.port ], function (err, ports) {
// if (err) return cb(err)
// cb(null, {
// port: ports[0]
// })
// })

}



//thanks https://github.com/preactjs/wmr/blob/main/src/lib/net-utils.js
/**
* Check if the requested port is free and increase port number
* sequentially until we find a free port.
* @param {number|string} port The suggested port to listen on
* @returns {Promise<number>} The next free port
*/
async function getFreePort(port) {
let found = false;
let attempts = 0;
let maxAttempts = 20

if (typeof port === 'string') port = parseInt(port, 10);

// Limit to 20 attempts for now
while (!found && attempts <= maxAttempts) {
try {
await new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen({ port }, () => {
port = server.address().port;
found = true;
server.close(resolve);
});
});
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
port++;
attempts++;
}
}
if(attempts == maxAttempts) console.log(`[BUDO]:exceeded max portfinding attemps, using ${port}`)
return port;
}

/**
* Display local and network origins for a server's address.
* @param {net.AddressInfo|string} addr
*/
function getServerAddresses(addr, { https = false } = {}) {
if (typeof addr === 'string') {
return addr;
}

const protocol = https ? 'https:' : 'http:';
const host = addr.address.replace('::', 'localhost');
const port = addr.port;

// Get network address
const ifaces = os.networkInterfaces();
const addresses = [];
for (const name in ifaces) {
for (const iface of ifaces[name]) {
const { family, address, internal } = iface;
if (family === 'IPv4' && address !== host && !internal) {
addresses.push(`${protocol}//${address}:${port}`);
}
}
}

let out = `${protocol}//${host}:${port}`;
if (addresses.length) {
out += `\n ⌙ ${addresses.join(', ')}`;
}

return out;
}
11 changes: 8 additions & 3 deletions lib/map-entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ var path = require('path')
var url = require('url')
var resolve = require('resolve')

module.exports = mapEntry
module.exports = mapEntry;

function mapEntry (file) {
file = file.toString()
if (file === '.') {
Expand All @@ -17,7 +18,8 @@ function mapEntry (file) {
parts = file.split(':')
}

var pathFrom, pathUrl
var pathFrom
var pathUrl

if (parts.length > 1 && parts[1].length > 0) {
pathFrom = parts[0]
Expand All @@ -26,9 +28,12 @@ function mapEntry (file) {
if (pathFrom === '.') {
pathFrom = entry()
}
} else {
}
else {
pathFrom = file
pathUrl = url.parse(path.basename(pathFrom)).pathname
//this passes tests, but idk
//pathUrl = path.parse(pathFrom).base.replace(" ", "%20")
}

return {
Expand Down
21 changes: 11 additions & 10 deletions lib/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,16 +168,17 @@ function budoMiddleware (entryMiddleware, opts) {
} else {
fs.readFile(bundledReloadClientFile, function (err, src) {
if (err) {
if (shouldUseBundledLiveReload) {
console.error([
'NOTE: The bundled LiveReload client could not be found, so budo will',
'generate this on the fly.',
'This is most likely because you are using a git cloned version of budo',
'instead of installing it from npm.',
'You can run this from your cloned budo folder to create a build:',
' npm run bundle-live-client'
].join('\n'))
}
//if (shouldUseBundledLiveReload) {
// console.error([
// 'NOTE: The bundled LiveReload client could not be found, so budo will',
// 'generate this on the fly.',
// 'This is most likely because you are using a git cloned version of budo',
// 'instead of installing it from npm.',
// 'You can run this from your cloned budo folder to create a build:',
// ' npm run bundle-live-client'
// ].join('\n'))
//}

shouldUseBundledLiveReload = false
successCallback(false)
} else {
Expand Down
5 changes: 3 additions & 2 deletions lib/reload/client.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var reloadCSS = require('reload-css')
var reloadCSS = require('./reload-css')
var errorPopup = require('./error-popup')

module.exports = connect()
Expand Down Expand Up @@ -151,5 +151,6 @@ function connect () {
}

function reloadPage () {
window.location.reload(true)
//window.location.reload(true)
window.location.reload()
}
3 changes: 2 additions & 1 deletion lib/reload/error-popup.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var popupContainer, popupText
var popupContainer
var popupText

function clearLegacy () {
var legacyPopup = document.querySelector('.budo-error-handler-legacy-popup-element')
Expand Down