0.2.2 • Published 2 years ago

@tbbjs/localhost v0.2.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

@tbbjs/localhost

GitHub license PRs Welcome Downloads npm version Discord

Simple web request interception using ServiceWorker, mainly used in online preview scenarios, where all web requests for the preview page are provided by the 'Main' page.

Installation

$ npm install @tbbjs/localhost

Usage

Prepare HTML

1. Preview Page(./index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<div class="container">
    「Here is a copywriting tip waiting for hosting」
</div>
<script src="./site.js"></script>
</body>
</html>

2. Relay Page(./__relay__.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<script src="./site.js"></script>
</body>
</html>

Prepare Resource

├── index.html
├── __relay__.html
├── site.js
└── sw.js

site.js and sw.js are in dist folder.

Create a Server

make sure http://localhost:3000 and http://localhost:3000/__relay__.html can access successfully.

Use

Execute this code anywhere in your project.

import { Localhost } from '@tbbjs/localhost';

const localhost = new Localhost({
    getTemplate: (port) => {
        return `http://localhost:${port}`
    },
    getPort: (segment) => {
        return Number(new URL(segment).port)
    },
    reload: true
});

// will server port at 3000. 
localhost.create(3000, async (url, options) => {
    console.log('[main] ------------')
    console.log('[main] url:', url)
    console.log('[main] options:', options)
    console.log('[main] ------------')
    return {
        headers: {
            'Content-Type': 'text/html; charset=utf-8'
        },
        status: 200,
        statusText: 'OK',
        body: new TextEncoder().encode(`Hello World, port: ${port}, date:` + new Date().getTime())
    }
}).then(() => {
    console.log('[main] server started, port request will be handled by localhost.')
})
  • open/refresh http://localhost:3000

API

type LocalhostTemplateFn = (port: number | string) => Promise<string>;
type LocalhostPortFn = (segment: string) => Promise<number>;
type PreviewRequestFn = (url: string, options: RequestInit) => Promise<PreviewResponse>;

interface PreviewResponse {
    status: number;
    statusText: string;
    headers: Record<string, string>;
    body: Uint8Array | ArrayBuffer;
}

declare class Localhost {
    constructor(options?: {
        getTemplate?: LocalhostTemplateFn; // eg: https://xx-xx--3000.xx.xx.com;
        getPort?: LocalhostPortFn;
        reload?: boolean; // autoreload when port ready.
    });
    ports(): Promise<number[]>;
    create(port: number, fn: PreviewRequestFn): Promise<Comlink.Remote<RemoteRelay>>;
    dispose(port?: number): Promise<void>;
}

declare class RemoteRelay {
    getUrls(): Promise<string[]>; 
    reload(): Promise<void>;
    dispose(): Promise<void>;
}

NOTICE: Usually the preview address is an online address, for example: https://xx-xx--3000.xx.xx.com; here it is recommended to follow the /-(\w+)--(\d+)\. / pattern.

License

MIT

0.2.2

2 years ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago

0.0.1

2 years ago