🎥 Make videos programmatically with React
pretty print browser logs in --log=verbose
Jonny Burgerf9b6369afa99
diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsxindex 8666ac8767..4ccdf2a726 100644--- a/packages/example/src/Video.tsx+++ b/packages/example/src/Video.tsx@@ -52,6 +52,7 @@ import {WarpDemoOuter} from './WarpText';import {WarpDemo2} from './WarpText/demo2';import {Tailwind} from './Tailwind';import {DynamicDuration, dynamicDurationSchema} from './DynamicDuration';+import {should} from 'vitest';if (alias !== 'alias') {throw new Error('should support TS aliases');@@ -66,9 +67,69 @@ export const Index: React.FC = () => {const calculateMetadata: CalculateMetadataFunction<z.infer<typeof dynamicDurationSchema>> = useCallback(async ({props}) => {+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const shouldLog = (..._data: unknown[]) => undefined;+ // To test logging+ // const shouldLog = console.log;++ const foo = function* () {+ yield 'a';+ yield 'b';+ yield 'c';+ };+ shouldLog('');+ shouldLog('');+ shouldLog('');+ shouldLog('');++ shouldLog('objects', {a: 'string'});+ shouldLog('boolean:', false);+ shouldLog('number:', 1);+ shouldLog('symbol', Symbol('hi'));+ shouldLog('Date:', new Date());+ shouldLog('bigint:', BigInt(123));+ shouldLog('function:', () => 'hi');+ shouldLog('array:', [1, 2, 3]);+ shouldLog('regex:', /abc/);+ shouldLog('');+ shouldLog('');+ shouldLog('');+ shouldLog('');+ shouldLog('Hello World ArrayBuffer', new ArrayBuffer(1));+ shouldLog('Hello World DataView', new DataView(new ArrayBuffer(1)));+ shouldLog('Hello World Error', new Error('hithere'));+ shouldLog('Hello World Generator', foo());+ shouldLog('Hello World Iterator', [1, 2, 3].values());+ const map = new Map();+ map.set('a', 1);+ shouldLog('Hello World Map', map);+ shouldLog('Hello World Node', document.createElement('div'));+ shouldLog('Hello World null', null);+ shouldLog(+ 'Hello World Promise',+ new Promise((resolve) => {+ resolve();+ })+ );+ shouldLog('Hello World Proxy', new Proxy(document, {}));+ shouldLog('Hello World RegExp', /abc/);+ shouldLog('Hello World Set', {a: [1, 2, 3]});+ shouldLog('Hello World TypedArray', new Uint8Array([1, 2, 3]));+ const wm3 = new WeakMap();+ const o1 = {};+ wm3.set(o1, 'azerty');+ const ws = new WeakSet();+ const foo2 = {};++ ws.add(foo2);++ console.log('Hello World WeakMap', wm3);+ console.log('Hello World WeakSet', ws);+await new Promise((r) => {setTimeout(r, 1000);});+return {durationInFrames: props.duration,fps: 30,diff --git a/packages/renderer/src/browser/BrowserPage.ts b/packages/renderer/src/browser/BrowserPage.tsindex 1be89e13a6..187129668e 100644--- a/packages/renderer/src/browser/BrowserPage.ts+++ b/packages/renderer/src/browser/BrowserPage.ts@@ -57,6 +57,7 @@ import {valueFromRemoteObject,} from './util';import type {LogLevel} from '../log-level';+import {formatRemoteObject} from '../format-logs';interface WaitForOptions {timeout?: number;@@ -202,7 +203,7 @@ export class Page extends EventEmitter {tag: [origPosition.name, file].filter(truthy).join('@'),indent,},- log.text+ log.previewString);} else {Log.verboseAdvanced(@@ -278,10 +279,24 @@ export class Page extends EventEmitter {});}+ const previewString = args+ ? args+ .map((arg) => {+ return formatRemoteObject(arg);+ })+ .join(', ')+ : '';+if (source !== 'worker') {this.emit(PageEmittedEvents.Console,- new ConsoleMessage(level, text, [], [{url, lineNumber}])+ new ConsoleMessage({+ type: level,+ text,+ args: [],+ stackTraceLocations: [{url, lineNumber}],+ previewString,+ }));}}@@ -412,12 +427,18 @@ export class Page extends EventEmitter {}}- const message = new ConsoleMessage(- eventType,- textTokens.join(' '),+ const previewString = args+ .map((a) => formatRemoteObject(a._remoteObject))+ .filter(Boolean)+ .join(' ');++ const message = new ConsoleMessage({+ type: eventType,+ text: textTokens.join(' '),args,- stackTraceLocations- );+ stackTraceLocations,+ previewString,+ });this.emit(PageEmittedEvents.Console, message);}diff --git a/packages/renderer/src/browser/ConsoleMessage.ts b/packages/renderer/src/browser/ConsoleMessage.tsindex 3c43cb0471..b216d40101 100644--- a/packages/renderer/src/browser/ConsoleMessage.ts+++ b/packages/renderer/src/browser/ConsoleMessage.ts@@ -47,17 +47,26 @@ export class ConsoleMessage {type: ConsoleMessageType;text: string;args: JSHandle[];+ previewString: string;#stackTraceLocations: ConsoleMessageLocation[];- constructor(- type: ConsoleMessageType,- text: string,- args: JSHandle[],- stackTraceLocations: ConsoleMessageLocation[]- ) {+ constructor({+ type,+ text,+ args,+ stackTraceLocations,+ previewString,+ }: {+ type: ConsoleMessageType;+ text: string;+ args: JSHandle[];+ stackTraceLocations: ConsoleMessageLocation[];+ previewString: string;+ }) {this.type = type;this.text = text;this.args = args;+ this.previewString = previewString;this.#stackTraceLocations = stackTraceLocations;}diff --git a/packages/renderer/src/browser/devtools-types.ts b/packages/renderer/src/browser/devtools-types.tsindex 726a084f73..06837d5056 100644--- a/packages/renderer/src/browser/devtools-types.ts+++ b/packages/renderer/src/browser/devtools-types.ts@@ -97,6 +97,123 @@ export interface DevtoolsRemoteObject {* Unique object identifier (for non-primitive values).*/objectId?: RemoteObjectId;+ preview?: ObjectPreview;+}++export interface ObjectPreview {+ /**+ * Object type. (ObjectPreviewType enum)+ */+ type:+ | 'object'+ | 'function'+ | 'undefined'+ | 'string'+ | 'number'+ | 'boolean'+ | 'symbol'+ | 'bigint';+ /**+ * Object subtype hint. Specified for `object` type values only. (ObjectPreviewSubtype enum)+ */+ subtype?:+ | 'array'+ | 'null'+ | 'node'+ | 'regexp'+ | 'date'+ | 'map'+ | 'set'+ | 'weakmap'+ | 'weakset'+ | 'iterator'+ | 'generator'+ | 'error'+ | 'proxy'+ | 'promise'+ | 'typedarray'+ | 'arraybuffer'+ | 'dataview'+ | 'webassemblymemory'+ | 'wasmvalue';+ /**+ * String representation of the object.+ */+ description?: string;+ /**+ * True iff some of the properties or entries of the original object did not fit.+ */+ overflow: boolean;+ /**+ * List of the properties.+ */+ properties: PropertyPreview[];+ /**+ * List of the entries. Specified for `map` and `set` subtype values only.+ */+ entries?: EntryPreview[];+}++export interface EntryPreview {+ /**+ * Preview of the key. Specified for map-like collection entries.+ */+ key?: ObjectPreview;+ /**+ * Preview of the value.+ */+ value: ObjectPreview;+}++export interface PropertyPreview {+ /**+ * Property name.+ */+ name: string;+ /**+ * Object type. Accessor means that the property itself is an accessor property. (PropertyPreviewType enum)+ */+ type:+ | 'object'+ | 'function'+ | 'undefined'+ | 'string'+ | 'number'+ | 'boolean'+ | 'symbol'+ | 'accessor'+ | 'bigint';+ /**+ * User-friendly property value string.+ */+ value?: string;+ /**+ * Nested value preview.+ */+ valuePreview?: ObjectPreview;+ /**+ * Object subtype hint. Specified for `object` type values only. (PropertyPreviewSubtype enum)+ */+ subtype?:+ | 'array'+ | 'null'+ | 'node'+ | 'regexp'+ | 'date'+ | 'map'+ | 'set'+ | 'weakmap'+ | 'weakset'+ | 'iterator'+ | 'generator'+ | 'error'+ | 'proxy'+ | 'promise'+ | 'typedarray'+ | 'arraybuffer'+ | 'dataview'+ | 'webassemblymemory'+ | 'wasmvalue';}type TargetID = string;diff --git a/packages/renderer/src/chalk/index.ts b/packages/renderer/src/chalk/index.tsindex adc969c1be..fce05ed81b 100644--- a/packages/renderer/src/chalk/index.ts+++ b/packages/renderer/src/chalk/index.ts@@ -39,6 +39,7 @@ type ColorsWithMethods = Colors & {yellow: Method;blue: Method;magenta: Method;+ cyan: Method;white: Method;gray: Method;bgBlack: Method;@@ -139,6 +140,7 @@ export const chalk = (() => {define('yellow', [33, 39], 'color');define('blue', [34, 39], 'color');define('magenta', [35, 39], 'color');+ define('cyan', [36, 39], 'color');define('white', [37, 39], 'color');define('gray', [90, 39], 'color');define('grey', [90, 39], 'color');diff --git a/packages/renderer/src/format-logs.ts b/packages/renderer/src/format-logs.tsnew file mode 100644index 0000000000..c150f94d01--- /dev/null+++ b/packages/renderer/src/format-logs.ts@@ -0,0 +1,270 @@+import type {+ DevtoolsRemoteObject,+ ObjectPreview,+ PropertyPreview,+} from './browser/devtools-types';+import {chalk} from './chalk';++export const formatRemoteObject = (remoteObject: DevtoolsRemoteObject) => {+ if (remoteObject.preview) {+ return formatObjectPreview(remoteObject.preview);+ }++ if (remoteObject.type === 'string') {+ return chalk.reset(`${remoteObject.value}`);+ }++ if (remoteObject.type === 'number') {+ return chalk.yellow(`${remoteObject.value}`);+ }++ if (remoteObject.type === 'bigint') {+ return chalk.yellow(`${remoteObject.description}`);+ }++ if (remoteObject.type === 'boolean') {+ return chalk.yellow(`${remoteObject.value}`);+ }++ if (remoteObject.type === 'function') {+ return chalk.cyan(String(remoteObject.description));+ }++ if (remoteObject.type === 'object') {+ if (remoteObject.subtype === 'null') {+ return chalk.white(`null`);+ }++ return chalk.reset(`Object`);+ }++ if (remoteObject.type === 'symbol') {+ return chalk.green(`${remoteObject.description}`);+ }++ if (remoteObject.type === 'undefined') {+ return chalk.gray(`undefined`);+ }++ throw new Error('unhandled remote object');+};++export const formatObjectPreview = (preview: ObjectPreview) => {+ if (typeof preview === 'undefined') {+ return '';+ }++ if (preview.type === 'object') {+ if (preview.subtype === 'date') {+ return chalk.reset(+ `Date { ${chalk.magenta(String(preview.description))} }`+ );+ }++ const properties = preview.properties.map((property) => {+ return `${property.name}: ${formatProperty(property)}`;+ });++ if (preview.subtype === 'array') {+ return chalk.reset(+ `[ ${preview.properties.map((p) => formatProperty(p)).join(', ')} ]`+ );+ }++ if (preview.subtype === 'arraybuffer') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'dataview') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'generator') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'iterator') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'map') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'node') {+ return chalk.magenta(`<${preview.description}>`);+ }++ if (preview.subtype === 'null') {+ return chalk.white(String(preview.description));+ }++ if (preview.subtype === 'promise') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'proxy') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'regexp') {+ return chalk.red(String(preview.description));+ }++ if (preview.subtype === 'set') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'typedarray') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'error') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'wasmvalue') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'weakmap') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'weakset') {+ return chalk.reset(String(preview.description));+ }++ if (preview.subtype === 'webassemblymemory') {+ return chalk.reset(String(preview.description));+ }++ if (properties.length === 0) {+ return chalk.reset('{}');+ }++ return chalk.reset(`{ ${properties.join(', ')} }`);+ }++ return '';+};++const formatProperty = (property: PropertyPreview | DevtoolsRemoteObject) => {+ if (property.type === 'string') {+ return chalk.green(`"${property.value}"`);+ }++ if (property.type === 'object') {+ if (!property.subtype && property.value === 'Object') {+ return chalk.reset(`{…}`);+ }++ if (property.subtype === 'date') {+ return chalk.reset(`Date { ${chalk.magenta(String(property.value))} }`);+ }++ if (property.subtype === 'arraybuffer') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'array') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'dataview') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'error') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'generator') {+ return chalk.reset(`[generator ${property.value}]`);+ }++ if (property.subtype === 'iterator') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'map') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'node') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'null') {+ return chalk.white(`${property.value}`);+ }++ if (property.subtype === 'promise') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'proxy') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'regexp') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'set') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'typedarray') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'wasmvalue') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'webassemblymemory') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'weakmap') {+ return chalk.reset(`${property.value}`);+ }++ if (property.subtype === 'weakset') {+ return chalk.reset(`${property.value}`);+ }++ return chalk.reset(`${property.value}`);+ }++ if (property.type === 'accessor') {+ return chalk.gray(`get()`);+ }++ if (property.type === 'bigint') {+ return chalk.yellow(`${property.value}`);+ }++ if (property.type === 'boolean') {+ return chalk.yellow(`${property.value}`);+ }++ if (property.type === 'function') {+ return chalk.cyan(`Function`);+ }++ if (property.type === 'number') {+ return chalk.yellow(`${property.value}`);+ }++ if (property.type === 'symbol') {+ return chalk.green(`${property.value}`);+ }++ if (property.type === 'undefined') {+ return chalk.gray(`undefined`);+ }++ throw new Error('unexpected property type ' + JSON.stringify(property));+};diff --git a/packages/renderer/src/test/format-logs.test.ts b/packages/renderer/src/test/format-logs.test.tsnew file mode 100644index 0000000000..6825e0eda7--- /dev/null+++ b/packages/renderer/src/test/format-logs.test.ts@@ -0,0 +1,50 @@+import {expect, test} from 'vitest';+import {formatObjectPreview} from '../format-logs';++test('Format logs with big object', () => {+ const result = formatObjectPreview({+ type: 'object',+ description: 'Object',+ overflow: false,+ properties: [{name: 'inputProps', type: 'object', value: 'Object'}],+ });++ expect(result).toBe('{ inputProps: {…} }');+});++test('Format logs with string', () => {+ const result = formatObjectPreview({+ type: 'object',+ description: 'Object',+ overflow: false,+ properties: [{name: 'a', type: 'string', value: 'b'}],+ });++ expect(result).toBe('{ a: "b" }');+});++test('Format accessor', () => {+ const result = formatObjectPreview({+ type: 'object',+ description: 'Object',+ overflow: false,+ properties: [{name: 'a', type: 'accessor'}],+ });++ expect(result).toBe('{ a: get() }');+});++test('Format date', () => {+ const result = formatObjectPreview({+ type: 'object',+ subtype: 'date',+ description:+ 'Fri Jun 23 2023 10:19:49 GMT+0200 (Central European Summer Time)',+ overflow: false,+ properties: [],+ });++ expect(result).toBe(+ 'Date { Fri Jun 23 2023 10:19:49 GMT+0200 (Central European Summer Time) }'+ );+});