Skip to content

Commit

Permalink
refactor: support env and improve structure
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Nov 18, 2020
1 parent 265ac16 commit d910aa2
Show file tree
Hide file tree
Showing 37 changed files with 705 additions and 77 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
dist
lib
runtime
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
node_modules
*.log*
dist
lib
runtime
24 changes: 22 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Yet expected to run code that had to work both of them :}

## What is un?

un is a framework of modules, shims and presets that work perfectly with any Javascript environemnt
un is a collection of modules, shims and presets that work perfectly with any Javascript environemnt
including Browsers, Workers, NodeJS or pure JavaScript.

You still need a bundler like [rollup.js](https://rollupjs.org) and un will disapear as soon as is bundled.
Expand All @@ -35,10 +35,29 @@ yarn add --dev @nuxt/un
npm i -D @nuxt/un
```

You can import modules from `@nuxt/un/lib/`
You can import modules from `@nuxt/un/runtime/`

## Env

```js
import { env, nodeless } from '@nuxt/un'

const { alias, inject } = env(nodeless, {
alias: {
// custom aliases
}
})
```

### Presets

- [nodeless](./src/env/presets/nodeless.ts)
- [vue2](./src/env/presets/vue2.ts)
- [vue3](./src/env/presets/vue3.ts)

## Shims

- [fetch](./src/shims/fetch.ts)
- [process](./src/shims/process.ts)

## NodeJS
Expand Down Expand Up @@ -67,6 +86,7 @@ You can import modules from `@nuxt/un/lib/`

## Packages

- [consola](./src/npm/consola.ts)
- [depd](./src/npm/depd.ts)
- [mime-db](./src/npm/mime-db.ts)
- [mime](./src/npm/mime.ts)
Expand Down
21 changes: 16 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,34 @@
"repository": "nuxt-contrib/un",
"license": "MIT",
"sideEffects": false,
"types": "lib/*.d.ts",
"main": "./dist/index.js",
"files": [
"dist"
],
"scripts": {
"build": "tsc src",
"build": "yarn clean && siroc build && yarn build:runtime",
"build:runtime": "tsc --build tsconfig.runtime.json",
"clean": "rm -rf dist lib",
"lint": "eslint --ext ts .",
"release": "yarn build && standard-version && npm publish && git push --follow-tags"
},
"dependencies": {
"buffer": "^6.0.2",
"defu": "^3.2.2",
"events": "^3.2.0",
"inherits": "^2.0.4",
"mime": "^2.4.6",
"process": "^0.11.10",
"upath": "^2.0.1",
"util": "^0.12.3"
},
"devDependencies": {
"@nuxtjs/eslint-config-typescript": "latest",
"@types/node": "latest",
"consola": "^2.15.0",
"eslint": "latest",
"siroc": "^0.4.1",
"standard-version": "latest",
"typescript": "latest"
},
"dependencies": {
"mime": "^2.4.6"
}
}
File renamed without changes.
File renamed without changes.
12 changes: 6 additions & 6 deletions src/mock/proxy.ts → src.runtime/mock/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
function getProxy (name: string, overrides: any = {}): any {
function createMock (name: string, overrides: any = {}): any {
const fn = function () { }
fn.prototype.name = name
const props: any = {}
return new Proxy(fn, {
get (_target, prop) {
if (prop === 'caller') { return null }
if (prop === '__createMock__') { return getProxy }
if (prop === '__createMock__') { return createMock }
if (prop in overrides) { return overrides[prop] }
// @ts-ignore
return (props[prop] = props[prop] || getProxy(`${name}.${prop.toString()}`))
return (props[prop] = props[prop] || createMock(`${name}.${prop.toString()}`))
},
apply (_target, _this, _args) {
return getProxy(`${name}()`)
return createMock(`${name}()`)
},
construct (_target, _args, _newT) {
return getProxy(`[${name}]`) as Object
return createMock(`[${name}]`) as Object
},
enumerate (_target) {
return []
}
})
}

export default getProxy('mock')
export default createMock('mock')
File renamed without changes.
File renamed without changes.
6 changes: 3 additions & 3 deletions src/node/http/request.ts → src.runtime/node/http/request.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type http from 'http'
import { Socket } from 'src/node/net/socket'
import { Readable } from 'src/node/stream/readable'
import { rawHeaders } from 'src/utils'
import { Socket } from '../net/socket'
import { Readable } from '../stream/readable'
import { rawHeaders } from '../../utils'

// Docs: https://nodejs.org/api/http.html#http_class_http_incomingmessage
// Implementation: https://github.com/nodejs/node/blob/master/lib/_http_incoming.js
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type http from 'http'
import type { Socket } from 'net'
import { Callback, HeadersObject } from 'src/types'
import { Writable } from 'src/node/stream/writable'
import { Callback, HeadersObject } from '../../types'
import { Writable } from '../stream/writable'

// Docs: https://nodejs.org/api/http.html#http_class_http_serverresponse
// Implementation: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js
Expand Down
File renamed without changes.
File renamed without changes.
8 changes: 4 additions & 4 deletions src/node/net/socket.ts → src.runtime/node/net/socket.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type * as net from 'net'
import { Callback, BufferEncoding } from 'src/types'
import { Readable } from 'src/node/stream/readable'
import { Writable } from 'src/node/stream/writable'
import { mergeFns } from 'src/utils'
import { Callback, BufferEncoding } from '../../types'
import { Readable } from '../stream/readable'
import { Writable } from '../stream/writable'
import { mergeFns } from '../../utils'

type ReadableAndWritableT = Readable & Writable
type ReadableAndWritableC = new () => ReadableAndWritableT
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EventEmitter } from 'events'
import type * as stream from 'stream'
import type { BufferEncoding, Callback } from 'src/types'
import type { BufferEncoding, Callback } from '../../types'

// Docs: https://nodejs.org/api/stream.html#stream_readable_streams
// Implementation: https://github.com/nodejs/node/blob/master/lib/internal/streams/readable.js
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EventEmitter } from 'events'
import type * as stream from 'stream'
import type { BufferEncoding, Callback } from 'src/types'
import type { BufferEncoding, Callback } from '../../types'

// Docs: https://nodejs.org/api/stream.html#stream_writable_streams
// Implementation: https://github.com/nodejs/node/blob/master/lib/internal/streams/writable.js
Expand Down
5 changes: 5 additions & 0 deletions src.runtime/npm/consola.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import mock from '../mock/proxy'

export default mock.__createMock__('consola', {
...console
})
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/npm/mime.ts → src.runtime/npm/mime.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// https://www.npmjs.com/package/mime

// @ts-ignore
import mimeLite from 'mime/lite'
import mimeLite from 'mime/lite.js'

const mime = { ...mimeLite }

Expand Down
1 change: 1 addition & 0 deletions src.runtime/shims/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// TODO
6 changes: 5 additions & 1 deletion src/shims/process.ts → src.runtime/shims/process.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
// https://github.com/defunctzombie/node-process/

global.process = global.process || {}
Object.assign(global.process, require('node-process'))

// TODO: apply only non-existing keys
Object.assign(global.process, require('node-process/browser.js'))

export default global.process
3 changes: 3 additions & 0 deletions src.runtime/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type Callback<E = Error | null | undefined> = (error?: E) => void
export type HeadersObject = { [key: string]: string | string[] | undefined }
export type BufferEncoding = any // TODO
23 changes: 23 additions & 0 deletions src.runtime/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { HeadersObject } from './types'

export function rawHeaders (headers: HeadersObject) {
const rawHeaders = []
for (const key in headers) {
if (Array.isArray(headers[key])) {
for (const h of headers[key] as any) {
rawHeaders.push(key, h)
}
} else {
rawHeaders.push(key, headers[key])
}
}
return rawHeaders
}

export function mergeFns (...functions: Function[]) {
return function (...args: any[]) {
for (const fn of functions) {
fn(...args)
}
}
}
19 changes: 19 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { Preset, Environment } from './types'

export function env (...presets: Preset[]) {
const options: Environment = {
alias: {},
inject: {}
}

for (const preset of presets) {
if (preset.alias) {
Object.assign(options.alias, preset.alias)
}
if (preset.inject) {
Object.assign(options.alias, preset.inject)
}
}

return options
}
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './utils'
export * from './presets'
export * from './env'
export * from './types'
3 changes: 3 additions & 0 deletions src/presets/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { default as nodeless } from './nodeless'
export { default as vue2 } from './vue2'
export { default as vue3 } from './vue3'
28 changes: 28 additions & 0 deletions src/presets/nodeless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { r, NodeBuiltinModules, mockAll } from '../utils'
import type { Preset } from '../types'

export default {
alias: {
...mockAll(NodeBuiltinModules),

// Custom
http: r('node/http'),
process: r('shims/process'),

// Browserify
buffer: require.resolve('buffer/index.js'),
util: require.resolve('util/util.js'),
events: require.resolve('events/events.js'),
inherits: require.resolve('inherits/inherits_browser.js'),

// npm
etag: r('mock/noop'),
'mime-db': r('npm/mime-db'),
mime: r('npm/mime')
},

inject: {
process: r('shims/process'),
Buffer: ['buffer', 'Buffer']
}
} as Preset
15 changes: 15 additions & 0 deletions src/presets/vue2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { mockAll } from '../utils'
import type { Preset } from '../types'

export default {
alias: {
...mockAll([
'encoding',
'he',
'resolve',
'source-map',
'lodash.template',
'serialize-javascript'
])
}
} as Preset
13 changes: 13 additions & 0 deletions src/presets/vue3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { mockAll } from '../utils'
import type { Preset } from '../types'

export default {
alias: {
...mockAll([
'@babel/parser',
'@vue/compiler-core',
'@vue/compiler-dom',
'@vue/compiler-ssr'
])
}
} as Preset
Empty file removed src/shims/fetch.ts
Empty file.
12 changes: 9 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
export type Callback<E = Error | null | undefined> = (error?: E) => void
export type HeadersObject = { [key: string]: string | string[] | undefined }
export type BufferEncoding = any // TODO
export interface Environment {
alias: { [key: string]: string }
inject: { [key: string]: string | string[] }
}

export interface Preset {
alias?: { [key: string]: string }
inject?: { [key: string]: string | string[] }
}
33 changes: 14 additions & 19 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
import type { HeadersObject } from 'src/types'
import { Module } from 'module'
import { resolve, join } from 'upath'

export function rawHeaders (headers: HeadersObject) {
const rawHeaders = []
for (const key in headers) {
if (Array.isArray(headers[key])) {
for (const h of headers[key] as any) {
rawHeaders.push(key, h)
}
} else {
rawHeaders.push(key, headers[key])
}
}
return rawHeaders
export const RUNTIME_DIR = resolve(__dirname, '../runtime')

export const NodeBuiltinModules = Module.builtinModules

export function mapArrToVal (val: any, arr: any[]) {
return arr.reduce((p, c) => ({ ...p, [c]: val }), {})
}

export function r (id: string) {
return require.resolve(join(RUNTIME_DIR, id))
}

export function mergeFns (...functions: Function[]) {
return function (...args: any[]) {
for (const fn of functions) {
fn(...args)
}
}
export function mockAll (packages: string[]) {
return mapArrToVal(r('mock/proxy'), packages)
}
9 changes: 3 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@
"compilerOptions": {
"baseUrl": ".",
"target": "ESNext",
"module": "ESNext",
"module": "ES6",
"moduleResolution": "Node",
"esModuleInterop": true,
"strict": true,
"declaration": true,
"outDir": "lib",
"types": [
"node",
"node"
]
},
"include": [
"src"
]
}
}
Loading

0 comments on commit d910aa2

Please sign in to comment.