Skip to content

Commit

Permalink
feat: expose ability to save results of scripts to file. (#48)
Browse files Browse the repository at this point in the history
* feat: add writeFile, appendFile to exposed functions

* fix: await exposed functions

* chore: update Readme

* chore: add changeset
  • Loading branch information
heyMP authored Aug 4, 2024
1 parent 4aa2817 commit ea5b50d
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 44 deletions.
29 changes: 29 additions & 0 deletions .changeset/eleven-kiwis-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
"@heymp/scratchpad": minor
---

Add `writeFile`, `appendFile` exposed functions. (#44)[https://github.com/heyMP/scratchpad/issues/44]

```.js
await writeFile('./log.txt', 'hello');
await appendFile('./log.txt', '\n');
await appendFile('./log.txt', 'world');
```

Include custom exposed functions example.

```.js
import { join } from 'node:path'
import fs from 'node:fs/promises';

function loadFile(path) {
return fs.readFile(join(process.cwd(), path), 'utf8');
}

export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
playwright: async (args) => {
const { context, page } = args;
await context.exposeFunction('loadFile', loadFile)
}
});
```
86 changes: 54 additions & 32 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,48 @@ Commands:
help [command] display help for command
```

## Config

An alternative to using the CLI flags, you can create `scratchpad.config.js`.

```js
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
devtools: true,
url: 'https://internal-rhdc-review-itmktgwsa-hklqgj.apps.int.spoke.preprod.us-west-2.aws.paas.redhat.com/en/test-page-2',
headless: true,
});
```

### Playwright runtime

The `scratchpad.config.js` exposes a method for altering the playwright runtime.
This allows you to interact with the Playwright API to perform actions like blocking
network requests or navigating to different urls.

```js
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
devtools: true,
playwright: async (args) => {
const { context, page } = args;
// block esmodule shims
await context.route(/es-module-shims\.js/, async route => {
await route.abort();
});
await page.goto('https://ux.redhat.com');
}
});
```

## Logging

To send log information from the Chromium browser to node.js we expose two logging helpers, `log()` & `clear()`.
To send log information from the Chromium browser to node.js we expose the following functions.

| Method | Description | Example |
|--------|--------------------------------------------|-----------|
| log | Log data to the stdnout of our terminal and to the Chromium Console it's running. Supports logging advanced types like Arrays, Generators, Iteratiors, Maps, Sets, and Functions. | `log(new Map([[1,2]])` |
| clear | Clear the previous console output results. | `clear()` |
| writeFile | Write data to a local file. | `writeFile('./log.txt', data)` |
| appendFile | Append data to a local file. | `appendFile('./log.txt', data)` |


Example
Expand Down Expand Up @@ -66,6 +99,26 @@ log(new Promise(res => res()));
log(function hello() { return 'world' });
```

## Custom exposed functions

You can provide your own custom exposed functions using the `scratchpad.config.js` file.

```.js
import { join } from 'node:path'
import fs from 'node:fs/promises';

function loadFile(path) {
return fs.readFile(join(process.cwd(), path), 'utf8');
}

export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
playwright: async (args) => {
const { context, page } = args;
await context.exposeFunction('loadFile', loadFile)
}
});
```

## Typescript

Scratchpad also has out of the box support for Typescript. Any file that ends with `.ts` will
Expand Down Expand Up @@ -101,37 +154,6 @@ in your `.ts` files:
/// <reference path="./node_modules/@heymp/scratchpad/types.d.ts" />
```

## Config

An alternative to using the CLI flags, you can create `scratchpad.config.js`.

```js
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
devtools: true,
url: 'https://internal-rhdc-review-itmktgwsa-hklqgj.apps.int.spoke.preprod.us-west-2.aws.paas.redhat.com/en/test-page-2',
headless: true,
});
```

### Playwright runtime

The `scratchpad.config.js` exposes a method for altering the playwright runtime.
This allows you to interact with the Playwright API to perform actions like blocking
network requests or navigating to different urls.

```js
export default /** @type {import('@heymp/scratchpad/src/config').Config} */ ({
devtools: true,
playwright: async (args) => {
const { context, page } = args;
// block esmodule shims
await context.route(/es-module-shims\.js/, async route => {
await route.abort();
});
await page.goto('https://ux.redhat.com');
}
});
```

## Development

Expand Down
37 changes: 25 additions & 12 deletions src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import playwright from 'playwright';
import util from 'node:util';
import { join } from 'node:path'
import fs from 'node:fs/promises';
import type { Processor } from './Processor.js';
util.inspect.defaultOptions.maxArrayLength = null;
util.inspect.defaultOptions.depth = null;

function nodelog(value:any) {
function nodelog(value: any) {
console.log(value);
}

function writeFile(path: string, data: any) {
return fs.writeFile(join(process.cwd(), path), data);
}

function appendFile(path: string, data: any) {
return fs.appendFile(join(process.cwd(), path), data);
}


export async function browser(processor: Processor) {
// Launch the browser
const browser = await playwright['chromium'].launch({
Expand All @@ -18,6 +29,19 @@ export async function browser(processor: Processor) {
const page = await context.newPage();
const playwrightConfig = processor.opts.playwright;

// Exposed functions
await context.exposeFunction('writeFile', writeFile);
await context.exposeFunction('appendFile', appendFile);
await context.exposeFunction('nodelog', (...value: any) => {
console.log(...value);
});
await context.exposeFunction('clear', () => {
console.clear();
page.evaluate(() => {
console.clear()
});
});

// Allow playwright config override
if (playwrightConfig && typeof playwrightConfig === 'function') {
await playwrightConfig({ browser, context, page });
Expand All @@ -28,17 +52,6 @@ export async function browser(processor: Processor) {
await page.goto(processor.opts.url);
}

await page.exposeFunction('clear', () => {
console.clear();
page.evaluate(() => {
console.clear()
});
});

await page.exposeFunction('nodelog', (...value: any) => {
console.log(...value);
});

async function execute() {
page.evaluate(async (func) => {
function log(...value: any[]) {
Expand Down
2 changes: 2 additions & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
declare function log(...args: any[]): void;
declare function clear(): void;
declare function writeFile(string, any): Promise<void>;
declare function appendFile(string, any): Promise<void>;

0 comments on commit ea5b50d

Please sign in to comment.