Skip to content

Commit

Permalink
allow to pass in functions
Browse files Browse the repository at this point in the history
  • Loading branch information
christian-bromann committed Feb 26, 2024
1 parent b9e0e36 commit e71f854
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 49 deletions.
55 changes: 29 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ It even allows you to run `.html` files, e.g. given this file:

```html
<script type="module">
console.log(document.querySelector('b').textContent);
console.log(document.querySelector("b").textContent);
</script>
<b>Hello World!</b>
```
Expand All @@ -48,34 +48,37 @@ Hello World!
You can also run `bx` programmatically, e.g. to hydrate components within the browser. For example, to hydrate a [Lit](https://lit.dev/) component through a [Koa](https://koajs.com/) server, you can run this script:

```ts
import path from 'node:path'
import Koa from 'koa'
import path from "node:path";
import Koa from "koa";

import { run } from '../../dist/index.js'
import { run } from "../../dist/index.js";

const __dirname = path.dirname(new URL(import.meta.url).pathname)
const app = new Koa()
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const app = new Koa();

app.use(async (ctx) => {
if (ctx.path === '/favicon.ico') {
return
}

ctx.body = await run(/*js*/`
import {render} from '@lit-labs/ssr';
import {html} from 'lit';
import './component.ts';
const dom = await render(html\`<simple-greeting></simple-greeting>\`);
export default Array.from(dom).join('\\n')
`, {
browserName: 'chrome',
rootDir: __dirname
})
})

app.listen(3000)
console.log('Server running at http://localhost:3000/');
if (ctx.path === "/favicon.ico") {
return;
}

ctx.body = await run(async () => {
/**
* runs in the browser
*/
const { render } = await import("@lit-labs/ssr");
const { html } = await import("lit");
await import("./component.ts");

const dom = await render(html`<simple-greeting></simple-greeting>`);
return Array.from(dom).join("\n");
}, {
browserName: "chrome",
rootDir: __dirname,
});
});

app.listen(3000);
console.log("Server running at http://localhost:3000/");
```

# Session Management
Expand Down Expand Up @@ -106,4 +109,4 @@ Kill specific or all sessions via:
```sh
npx bx session --kill chrome
npx bx session --killAll
```
```
18 changes: 8 additions & 10 deletions examples/lit-hydrate/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import Koa from 'koa'

import { run } from '../../dist/index.js'

import {render} from '@lit-labs/ssr'

const __dirname = path.dirname(new URL(import.meta.url).pathname)
const app = new Koa()

Expand All @@ -13,15 +11,15 @@ app.use(async (ctx) => {
return
}

ctx.body = await run(/*js*/`
import {render} from '@lit-labs/ssr';
import {html} from 'lit';
import './component.ts';
ctx.body = await run(async () => {
const { render } = await import('@lit-labs/ssr');
const { html } = await import('lit');
await import('./component.ts');

const dom = await render(html\`<simple-greeting></simple-greeting>\`);
export default Array.from(dom).join('\\n')
`, {
browserName: 'chrome',
const dom = await render(html`<simple-greeting></simple-greeting>`);
return Array.from(dom).join('\n')
}, {
sessionName: 'haha',
rootDir: __dirname
})
})
Expand Down
6 changes: 3 additions & 3 deletions src/cli/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { Argv } from 'yargs'
import { ViteServer } from '../server.js'
import { run as runCall } from '../runner.js'
import { CLI_EPILOGUE } from '../constants.js'
import type { RunnerArgs } from '../types.js'
import type { RunnerArgs, Target } from '../types.js'

export const command = '<target> [options]'
export const desc = 'Run script, html file or URL.'
Expand Down Expand Up @@ -51,13 +51,13 @@ export const handler = async () => {
process.exit(0)
}

export async function run (target?: string, params?: RunnerArgs) {
export async function run (target?: Target, params?: RunnerArgs) {
if (!target) {
console.error('Error: No target provided')
process.exit(1)
}

if (target.startsWith('http')) {
if (typeof target === 'string' && target.startsWith('http')) {
console.error('Error: Running URLs is not supported yet')
process.exit(1)
}
Expand Down
18 changes: 12 additions & 6 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'node:fs/promises'
import path from 'node:path'
import { createServer, type InlineConfig, type ViteDevServer, type Plugin } from 'vite'

import type { ExecutionEnvironment, ConsoleEvent } from './types.js'
import type { ExecutionEnvironment, ConsoleEvent, Target } from './types.js'

const __dirname = path.dirname(new URL(import.meta.url).pathname)
const virtualModuleId = 'virtual:inline'
Expand All @@ -24,7 +24,7 @@ export class ViteServer {
}
}

async start(target: string): Promise<ExecutionEnvironment> {
async start(target: Target): Promise<ExecutionEnvironment> {
let onConnectHandler: (value: ViteDevServer) => void = () => { }
const connectPromise = new Promise<ViteDevServer>((resolve) => {
onConnectHandler = resolve
Expand All @@ -47,7 +47,7 @@ export class ViteServer {
}
}

async function instrument(target: string, onConnect: (value: ViteDevServer) => void): Promise<Plugin> {
async function instrument(target: Target, onConnect: (value: ViteDevServer) => void): Promise<Plugin> {
const instrumentation = await fs.readFile(path.resolve(__dirname, 'browser', 'index.js'), 'utf-8')
const sendFinishEvent = `requestAnimationFrame(() => import.meta.hot?.send('bx:event', { name: 'doneEvent' }))`
return {
Expand All @@ -60,9 +60,12 @@ async function instrument(target: string, onConnect: (value: ViteDevServer) => v
return null
},
load(id) {
if (id === resolvedVirtualModuleId) {
if (typeof target === 'string' && id === resolvedVirtualModuleId) {
return target
}
if (typeof target === 'function' && id === resolvedVirtualModuleId) {
return `export default await (${target.toString()})()`
}
return null
},
transform: (code, id) => {
Expand All @@ -82,7 +85,7 @@ async function instrument(target: string, onConnect: (value: ViteDevServer) => v
return next()
}

const code = target.startsWith('./') || target.startsWith('/')
const code = typeof target === 'string' && (target.startsWith('./') || target.startsWith('/'))
? path.extname(target) === '.html'
? await fs.readFile(target, 'utf-8')
: `<script type="module" src="/@fs${path.resolve(process.cwd(), target)}"></script>`
Expand All @@ -98,7 +101,10 @@ async function instrument(target: string, onConnect: (value: ViteDevServer) => v
<html>
<script type="module">${instrumentation}</script>
${code}
${path.extname(target) === '.html' ? `<script type="module">${sendFinishEvent}</script>` : ''}
${typeof target === 'string' && path.extname(target) === '.html'
? `<script type="module">${sendFinishEvent}</script>`
: ''
}
`
res.end(await server.transformIndexHtml(`${req.originalUrl}`, template))
})
Expand Down
12 changes: 9 additions & 3 deletions src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ export async function deleteSession(sessionName?: string) {
throw new Error(`Session "${sessionName}" not found`)
}

await fs.unlink(sessionFilePath)
const session = await loadSession(sessionName)
return Promise.all([
fs.unlink(sessionFilePath),
session.deleteSession()
])
}

export async function deleteAllSessions() {
Expand All @@ -79,7 +83,9 @@ export async function deleteAllSessions() {
}
const sessionName = path.basename(file, path.extname(file)).replace(SESSION_FILE_PREFIX, '')
const session = await loadSession(sessionName)
await fs.unlink(path.join(SESSION_DIR, file))
await session.deleteSession()
return Promise.all([
fs.unlink(path.join(SESSION_DIR, file)),
session.deleteSession()
])
}))
}
4 changes: 3 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,6 @@ export interface ErrorEvent {
filename: string
message: string
error: string
}
}

export type Target = string | (() => any | Promise<any>)

0 comments on commit e71f854

Please sign in to comment.