deictic 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/API.md +71 -17
- package/README.md +1 -1
- package/dist/annotations/client.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client/index.d.ts +13 -13
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +11 -7
- package/dist/client/index.js.map +1 -1
- package/dist/react/client.d.ts +19 -0
- package/dist/react/client.d.ts.map +1 -0
- package/dist/react/client.js +504 -0
- package/dist/react/client.js.map +1 -0
- package/dist/react/index.d.ts +2 -0
- package/dist/react/index.js +1 -0
- package/dist/recommended/index.d.ts +15 -7
- package/dist/recommended/index.d.ts.map +1 -1
- package/dist/recommended/index.js +1 -1
- package/dist/recordings/client.d.ts.map +1 -1
- package/dist/recordings/client.js +48 -5
- package/dist/recordings/client.js.map +1 -1
- package/dist/screenshots/client.d.ts +9 -1
- package/dist/screenshots/client.d.ts.map +1 -1
- package/dist/screenshots/rrweb.d.ts +0 -6
- package/dist/screenshots/rrweb.d.ts.map +1 -1
- package/dist/screenshots/rrweb.js +46 -12
- package/dist/screenshots/rrweb.js.map +1 -1
- package/dist/shared/board.js +1 -1
- package/dist/shared/client.js +44 -2
- package/dist/shared/client.js.map +1 -1
- package/dist/shared/dom.js +7 -1
- package/dist/shared/dom.js.map +1 -1
- package/dist/shared/drawer.js +1 -1
- package/dist/shared/endpoints.js +1 -1
- package/dist/shared/index.d.ts +6 -0
- package/dist/shared/index.d.ts.map +1 -1
- package/dist/shared/index10.d.ts +70 -0
- package/dist/shared/index10.d.ts.map +1 -0
- package/dist/shared/index3.d.ts +11 -0
- package/dist/shared/index3.d.ts.map +1 -1
- package/dist/shared/index7.d.ts +92 -312
- package/dist/shared/index7.d.ts.map +1 -1
- package/dist/shared/index8.d.ts +324 -47
- package/dist/shared/index8.d.ts.map +1 -1
- package/dist/shared/index9.d.ts +45 -63
- package/dist/shared/index9.d.ts.map +1 -1
- package/dist/shared/init.js +15 -11
- package/dist/shared/init.js.map +1 -1
- package/dist/shared/marks.js +7 -1
- package/dist/shared/marks.js.map +1 -1
- package/dist/shared/package.js +3 -1
- package/dist/shared/packages.js +1 -1
- package/dist/shared/playwright.js +39 -1
- package/dist/shared/playwright.js.map +1 -1
- package/dist/shared/react.js +25 -0
- package/dist/shared/react.js.map +1 -0
- package/dist/shared/recommended.js +6 -3
- package/dist/shared/recommended.js.map +1 -1
- package/dist/shared/recording.js +80 -3
- package/dist/shared/recording.js.map +1 -1
- package/dist/shared/recordings.js +30 -2
- package/dist/shared/recordings.js.map +1 -1
- package/dist/shared/screenshots.js.map +1 -1
- package/dist/shared/src.js.map +1 -1
- package/dist/shared/task.js +1 -0
- package/dist/shared/task.js.map +1 -1
- package/dist/shared/tasks.js +11 -0
- package/dist/shared/tasks.js.map +1 -1
- package/dist/tailwind/client.d.ts +1 -1
- package/dist/tailwind/index.d.ts +1 -1
- package/dist/tasks/client.d.ts +1 -1
- package/dist/tasks/client.js +45 -19
- package/dist/tasks/client.js.map +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/voice/client.d.ts +1 -1
- package/dist/voice/client.js +1 -1
- package/dist/voice/index.d.ts +1 -1
- package/package.json +25 -1
- package/src/cli/bun.ts +2 -2
- package/src/cli/init.ts +14 -9
- package/src/cli/recording.ts +90 -4
- package/src/cli/task.ts +4 -0
- package/src/cli.ts +13 -6
- package/src/client/dom.ts +14 -0
- package/src/client/index.ts +21 -14
- package/src/index.ts +6 -0
- package/src/plugins/react/client.ts +162 -0
- package/src/plugins/react/index.ts +130 -0
- package/src/plugins/react/renders.ts +219 -0
- package/src/plugins/react/serialize.ts +139 -0
- package/src/plugins/react/timeline.ts +143 -0
- package/src/plugins/recommended/index.ts +17 -5
- package/src/plugins/recordings/client.ts +64 -4
- package/src/plugins/recordings/marks.ts +7 -0
- package/src/plugins/recordings/replay.ts +30 -2
- package/src/plugins/screenshots/client.ts +42 -2
- package/src/plugins/screenshots/index.ts +11 -0
- package/src/plugins/screenshots/playwright.ts +65 -1
- package/src/plugins/screenshots/rrweb.ts +55 -28
- package/src/plugins/screenshots/states.ts +26 -0
- package/src/plugins/tasks/client.ts +41 -6
- package/src/plugins/tasks/composer.ts +24 -7
- package/src/plugins/tasks/index.ts +16 -2
package/dist/shared/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","names":[],"sources":["../../src/cli/edit.ts","../../src/cli/bun.ts","../../src/cli/init.ts"],"sourcesContent":["/**\n * Editing a project's own source the way it's written: its quotes, semicolons, line endings and indentation. What\n * `init` adds to a bundler's config and to a Bun server goes through here.\n */\nimport type MagicString from 'magic-string';\nimport type { Program } from 'oxc-parser';\n\n/** The file's line ending. */\nexport const eolOf = (code: string) => (code.includes('\\r\\n') ? '\\r\\n' : '\\n');\n\n/** The whitespace a line starts with, for the line `offset` is on. */\nexport function indentAt(code: string, offset: number): string {\n const start = code.lastIndexOf('\\n', offset - 1) + 1;\n return /^[ \\t]*/.exec(code.slice(start))![0];\n}\n\n/**\n * Adds import lines after the module's last import (or `require`, in CommonJS), or at its top: written in the quotes\n * and semicolons of its first import. Each line is `[what, from]`: `import ${what} from '${from}'`, or as a `require`.\n */\nexport function addImports(out: MagicString, program: Program, code: string, lines: [string, string][], commonjs = false): void {\n const eol = eolOf(code);\n const imports = program.body.filter((s) => s.type === 'ImportDeclaration');\n const first = imports[0];\n const quote = first === undefined ? \"'\" : code[first.source.start]!;\n const semi = first === undefined || code.slice(first.start, first.end).trimEnd().endsWith(';') ? ';' : '';\n const q = (s: string) => `${quote}${s}${quote}`;\n const text = lines\n .map(([what, from]) => (commonjs ? `const ${what} = require(${q(from)})${semi}` : `import ${what} from ${q(from)}${semi}`))\n .join(eol);\n const after = imports.at(-1) ?? requiresOf(program).at(-1);\n if (after === undefined) out.prepend(`${text}${eol}${eol}`);\n else out.appendLeft(after.end, `${eol}${text}`);\n}\n\n/** The top-level `const … = require(…)` statements of a CommonJS module, to put new ones after. */\nfunction requiresOf(program: Program) {\n return program.body.filter(\n (s) =>\n s.type === 'VariableDeclaration' &&\n s.declarations.some(\n (d) => d.init?.type === 'CallExpression' && d.init.callee.type === 'Identifier' && d.init.callee.name === 'require',\n ),\n );\n}\n\n/** Inserts `text` as the first property of the object literal that starts at `open` (its `{`), as the object is laid out. */\nexport function addFirst(out: MagicString, code: string, open: number, first: { start: number } | undefined, text: string): void {\n const eol = eolOf(code);\n if (first === undefined) {\n out.appendLeft(open + 1, ` ${text} `);\n return;\n }\n const multiline = code.slice(open, first.start).includes('\\n');\n out.appendLeft(first.start, multiline ? `${text},${eol}${indentAt(code, first.start)}` : `${text}, `);\n}\n","/**\n * `init` for Bun's own dev server: `Bun.serve` with HTML imports, which bundles the page with the plugins bunfig.toml\n * names. Only that: a Bun project that runs Vite, Next.js or another bundler is that bundler's, and one with no HTML\n * imports has no page of Bun's for deictic to be in. Three steps, as the API has them: the plugin's module, bunfig's\n * `[serve.static] plugins`, and its routes spread into `Bun.serve`'s.\n */\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\n\nimport MagicString from 'magic-string';\nimport { type CallExpression, parseSync, Visitor } from 'oxc-parser';\n\nimport { addFirst, addImports, eolOf } from './edit.ts';\n\n/** The plugin's module, from the root, which bunfig names and the server imports. */\nexport const MODULE = 'deictic.plugin.ts';\n\nexport const PLUGIN = `import { deictic } from 'deictic/bun';\nimport { recommended } from 'deictic/recommended';\n\n// One module for both: bunfig.toml names it as the dev server's bundler plugin, and the server spreads its routes,\n// deictic's endpoints, into its own.\nexport default deictic({ plugins: recommended() });\n`;\n\nconst SOURCE = /\\.[cm]?[jt]sx?$/;\nconst SKIP = new Set(['node_modules', 'dist', 'build', 'out']);\nconst SERVE = /\\bBun\\.serve\\s*\\(/;\nconst HTML = /\\bfrom\\s*['\"][^'\"]+\\.html['\"]/;\n\n/**\n * The module that serves the page with Bun's bundler: it calls `Bun.serve` and imports an HTML file. Looked for under\n * the root, not in dependencies, builds or dot folders, a few folders deep.\n */\nexport function serverOf(root: string): string | undefined {\n const walk = (dir: string, depth: number): string | undefined => {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return undefined;\n }\n for (const e of entries) {\n if (!e.isFile() || !SOURCE.test(e.name)) continue;\n const path = join(dir, e.name);\n const code = readFileSync(path, 'utf8');\n if (SERVE.test(code) && HTML.test(code)) return path;\n }\n if (depth === 0) return undefined;\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;\n const found = walk(join(dir, e.name), depth - 1);\n if (found !== undefined) return found;\n }\n return undefined;\n };\n return walk(root, 3);\n}\n\n/**\n * bunfig.toml with the plugin's module first in `[serve.static] plugins` (first, so it sees the source as written),\n * made where there's none; unchanged where it's there already, and nothing where bunfig says it another way (a dotted\n * key, an inline table) and it can't tell where.\n */\nexport function addToBunfig(text: string | undefined, entry = `./${MODULE}`): string | undefined {\n const quoted = JSON.stringify(entry);\n if (text === undefined) return `[serve.static]\\nplugins = [${quoted}]\\n`;\n if (text.includes(entry)) return text;\n if (/serve\\.static\\.|static\\s*=\\s*\\{/.test(text)) return undefined;\n const eol = eolOf(text);\n const header = /^[ \\t]*\\[serve\\.static\\][ \\t]*(#.*)?$/m.exec(text);\n if (header === null)\n return `${text}${text === '' || text.endsWith('\\n') ? '' : eol}${eol}[serve.static]${eol}plugins = [${quoted}]${eol}`;\n const bodyStart = header.index + header[0].length;\n const next = /^[ \\t]*\\[/m.exec(text.slice(bodyStart));\n const body = text.slice(bodyStart, next === null ? text.length : bodyStart + next.index);\n const list = /^[ \\t]*plugins[ \\t]*=[ \\t]*\\[/m.exec(body);\n if (list === null) return `${text.slice(0, bodyStart)}${eol}plugins = [${quoted}]${text.slice(bodyStart)}`;\n const open = bodyStart + list.index + list[0].length;\n const rest = text.slice(open);\n const empty = /^\\s*\\]/.test(rest);\n const lineBreak = /^[ \\t]*\\r?\\n([ \\t]*)/.exec(rest);\n if (empty) return `${text.slice(0, open)}${quoted}${rest.trimStart()}`;\n if (lineBreak !== null) return `${text.slice(0, open)}${eol}${lineBreak[1]}${quoted},${rest}`;\n return `${text.slice(0, open)}${quoted}, ${rest.trimStart()}`;\n}\n\n/**\n * The server with the plugin's routes first in `Bun.serve`'s `routes`, or `routes` with them where it has none, and\n * the module imported: nothing where `Bun.serve` isn't given an object it can see, or its routes aren't one.\n */\nexport function addToServer(file: string, code: string, root: string): string | undefined {\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const calls: CallExpression[] = [];\n new Visitor({\n CallExpression(node) {\n const { callee } = node;\n if (\n callee.type === 'MemberExpression' &&\n callee.object.type === 'Identifier' &&\n callee.object.name === 'Bun' &&\n callee.property.type === 'Identifier' &&\n callee.property.name === 'serve'\n )\n calls.push(node);\n },\n }).visit(program);\n const options = calls.length === 1 ? calls[0]!.arguments[0] : undefined;\n if (options?.type !== 'ObjectExpression') return undefined;\n\n // `tools`, as the API names it, unless the module has a `tools` of its own.\n const name = /\\btools\\b/.test(code) ? 'deicticTools' : 'tools';\n const out = new MagicString(code);\n const routes = options.properties.find(\n (p) => p.type === 'Property' && !p.computed && p.key.type === 'Identifier' && p.key.name === 'routes',\n );\n if (routes === undefined) {\n addFirst(out, code, options.start, options.properties[0], `routes: { ...${name}.routes }`);\n } else {\n if (routes.type !== 'Property' || routes.value.type !== 'ObjectExpression') return undefined;\n addFirst(out, code, routes.value.start, routes.value.properties[0], `...${name}.routes`);\n }\n const from = relative(dirname(file), join(root, MODULE)).replaceAll('\\\\', '/');\n addImports(out, program, code, [[name, from.startsWith('.') ? from : `./${from}`]]);\n return out.toString();\n}\n\n/** What to add by hand, for a server or a bunfig it can't edit. */\nexport const BY_HAND = {\n bunfig: `[serve.static]\\nplugins = [\"./${MODULE}\"]`,\n server: `import tools from './${MODULE}';\\nBun.serve({ routes: { ...tools.routes, '/*': index } });`,\n};\n","/**\n * `deictic init`: the recommended setup in a project, in one step. It installs deictic and what the recommended\n * plugins import, with the project's package manager and as the project's own dev dependencies (deictic, the\n * page's bundle and the skill all find them from the project, so they can't come in through another package), adds\n * deictic to the bundler's config where it can find the place, and offers the agent skill.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\n\nimport MagicString from 'magic-string';\nimport { type Expression, type ObjectExpression, parseSync, type Program } from 'oxc-parser';\n\nimport { recommended } from '#src/plugins/recommended/index.ts';\n\nimport { installCommand, packageManager, readJson, runnerOf } from '#src/tools/packages.ts';\n\nimport { fail } from './board.ts';\nimport { addToBunfig, addToServer, BY_HAND, MODULE, PLUGIN, serverOf } from './bun.ts';\nimport { addFirst, addImports } from './edit.ts';\n\nexport type Bundler = 'next' | 'astro' | 'vite' | 'rspack' | 'webpack' | 'bun';\n\ninterface Setup {\n /** The config files it looks for, in order. */\n files: string[];\n /** The module deictic's integration comes from, and its name there. */\n from: string;\n name: string;\n /** What goes in the config: in its `list`, or wrapped around the whole of it with `wrap`. */\n list?: string;\n value: string;\n wrap?: boolean;\n /** The snippet for a config it can't edit. */\n snippet: string;\n}\n\nconst extensions = (base: string) => ['ts', 'mts', 'js', 'mjs', 'cts', 'cjs'].map((e) => `${base}.${e}`);\nconst PLUGINS = '{ plugins: recommended() }';\n\nconst SETUPS: Record<Exclude<Bundler, 'bun'>, Setup> = {\n next: {\n files: extensions('next.config'),\n from: 'deictic/next',\n name: 'withDeictic',\n value: PLUGINS,\n wrap: true,\n snippet: `export default withDeictic(nextConfig, ${PLUGINS});`,\n },\n astro: {\n files: extensions('astro.config'),\n from: 'deictic/astro',\n name: 'deictic',\n list: 'integrations',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ integrations: [deictic(${PLUGINS})] });`,\n },\n vite: {\n files: extensions('vite.config'),\n from: 'deictic/vite',\n name: 'deictic',\n list: 'plugins',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ plugins: [deictic(${PLUGINS}), react()] });`,\n },\n rspack: {\n files: extensions('rspack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n webpack: {\n files: extensions('webpack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n};\n\n/** The project's root: the nearest folder with a package.json, from `dir` up. */\nexport function rootOf(dir: string): string | undefined {\n for (let at = dir; ; at = dirname(at)) {\n if (existsSync(join(at, 'package.json'))) return at;\n if (dirname(at) === at) return undefined;\n }\n}\n\n/** The project's dependencies and dev dependencies, by name. */\nfunction dependenciesOf(root: string): Set<string> {\n const manifest = readJson(join(root, 'package.json')) ?? {};\n return new Set([manifest.dependencies, manifest.devDependencies].flatMap((d) => Object.keys((d as object | undefined) ?? {})));\n}\n\n/** The bundler the project runs its dev server with, from its dependencies, or none deictic knows. */\nexport function bundlerOf(root: string): Bundler | undefined {\n const has = dependenciesOf(root);\n if (has.has('next')) return 'next';\n if (has.has('astro')) return 'astro';\n if (has.has('vite') || SETUPS.vite.files.some((f) => existsSync(join(root, f)))) return 'vite';\n if (has.has('@rspack/core') || has.has('@rspack/cli')) return 'rspack';\n if (has.has('webpack')) return 'webpack';\n // Bun's own bundler only where a server of the project's has it bundle a page: not every project Bun runs.\n if (serverOf(root) !== undefined) return 'bun';\n return undefined;\n}\n\n/** What the recommended setup imports, for the bundler: launch-editor opens files under webpack, which has no launcher. */\nexport function packagesFor(bundler: Bundler | undefined): string[] {\n const plugins = recommended().flatMap((p) => p.packages ?? []);\n return ['deictic', ...plugins, ...(bundler === 'webpack' || bundler === 'rspack' ? ['launch-editor'] : [])];\n}\n\ntype Node = Expression | ObjectExpression;\n\n/**\n * The object an expression comes to: through `defineConfig(…)`, `(…)`, `satisfies`, a function's return and a top-level\n * `const`. Not through another call: in `mergeConfig(base, {…})` or webpack-merge's `merge(common, {…})` the first\n * argument is a base the project may build with too, and the plugin isn't the base's.\n */\nfunction objectOf(node: Node | null | undefined, program: Program, depth = 0): ObjectExpression | undefined {\n if (node == null || depth > 8) return undefined;\n const next = (n: Node | null | undefined) => objectOf(n, program, depth + 1);\n if (node.type === 'ObjectExpression') return node;\n if (node.type === 'ParenthesizedExpression' || node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')\n return next(node.expression);\n if (node.type === 'CallExpression') {\n const { callee } = node;\n const named = (callee.type === 'Identifier' ? callee : callee.type === 'MemberExpression' ? callee.property : undefined) as\n { type: string; name?: string } | undefined;\n const [first] = node.arguments;\n if (named?.name !== 'defineConfig' || first === undefined || first.type === 'SpreadElement') return undefined;\n return next(first);\n }\n if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {\n const body = node.body;\n if (body === null) return undefined;\n if (body.type !== 'BlockStatement') return next(body);\n const returned = body.body.findLast((s) => s.type === 'ReturnStatement');\n return returned?.type === 'ReturnStatement' ? next(returned.argument) : undefined;\n }\n if (node.type !== 'Identifier') return undefined;\n for (const statement of program.body) {\n const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n const found = declaration.declarations.find((d) => d.id.type === 'Identifier' && d.id.name === node.name);\n if (found !== undefined) return next(found.init);\n }\n return undefined;\n}\n\n/** The config's exported value: `export default …` or `module.exports = …`, and whether it's CommonJS. */\nfunction exportedOf(program: Program): { value: Expression; commonjs: boolean } | undefined {\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n return value.type.endsWith('Declaration') && value.type !== 'FunctionDeclaration'\n ? undefined\n : { value: value as Expression, commonjs: false };\n }\n if (statement.type !== 'ExpressionStatement' || statement.expression.type !== 'AssignmentExpression') continue;\n const { left, right } = statement.expression;\n const exports =\n left.type === 'MemberExpression' &&\n left.object.type === 'Identifier' &&\n left.object.name === 'module' &&\n left.property.type === 'Identifier' &&\n left.property.name === 'exports';\n if (exports) return { value: right, commonjs: true };\n }\n return undefined;\n}\n\n/**\n * The config with deictic added, or nothing where it can't tell where: deictic's import beside the config's, and its\n * plugin first in the list (`plugins`, `integrations`), as its marks count lines and columns in the code it's given, or the config wrapped (Next's). Written in the config's quotes,\n * semicolons and line endings.\n */\nexport function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {\n const setup = SETUPS[bundler];\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const exported = exportedOf(program);\n if (exported === undefined) return undefined;\n const out = new MagicString(code);\n\n if (setup.wrap) {\n out.appendLeft(exported.value.start, `${setup.name}(`);\n out.appendRight(exported.value.end, `, ${setup.value})`);\n } else {\n const object = objectOf(exported.value, program);\n if (object === undefined || !addTo(out, code, object, setup.list!, setup.value)) return undefined;\n }\n\n const lines: [string, string][] = [\n ['{ recommended }', 'deictic/recommended'],\n [`{ ${setup.name} }`, setup.from],\n ];\n addImports(out, program, code, lines, exported.commonjs);\n return out.toString();\n}\n\n/**\n * Adds `value` first in the object's array `list`, or the list with it, as the object is laid out. False where `list`\n * isn't an array. First, since a plugin before deictic's that changes a module (both `pre` under Vite) leaves the\n * page's marks pointing at its code, not the file.\n */\nfunction addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string): boolean {\n const property = object.properties.find(\n (p) =>\n p.type === 'Property' &&\n !p.computed &&\n ((p.key.type === 'Identifier' && p.key.name === list) || (p.key.type === 'Literal' && p.key.value === list)),\n );\n if (property !== undefined) {\n if (property.type !== 'Property') return false;\n let array = property.value;\n while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;\n if (array.type !== 'ArrayExpression') return false;\n const first = array.elements.find((e) => e !== null);\n if (first == null) {\n out.appendLeft(array.start + 1, value);\n return true;\n }\n addFirst(out, code, array.start, first, value);\n return true;\n }\n addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);\n return true;\n}\n\nexport interface InitOptions {\n /** Where it runs: the project is the nearest folder with a package.json. */\n cwd: string;\n /** Installs the packages; false only says the command. */\n install?: boolean;\n /** Adds the skill (true), says how (false), or asks (undefined, on a terminal; says how elsewhere). */\n skill?: boolean;\n /** Says what it would do, and does none of it. */\n dryRun?: boolean;\n log?: (line: string) => void;\n /** Runs a command in the project, and answers whether it succeeded. */\n run?: (command: string, cwd: string) => boolean;\n ask?: (question: string) => Promise<boolean>;\n}\n\nconst runIn = (command: string, cwd: string) => spawnSync(command, { cwd, stdio: 'inherit', shell: true }).status === 0;\n\n/** Sets the project up; throws what to do where it can't. */\nexport async function init(options: InitOptions): Promise<void> {\n const { install = true, dryRun = false, log = console.log, run = runIn } = options;\n const root = rootOf(options.cwd);\n if (root === undefined) throw new Error('deictic: no package.json here or above: run it in your project');\n const manager = packageManager(root);\n const bundler = bundlerOf(root);\n const has = dependenciesOf(root);\n\n const wanted = packagesFor(bundler).filter((p) => !has.has(p));\n const command = installCommand(manager, wanted, root);\n if (wanted.length === 0) {\n log('deictic: its packages are installed');\n } else if (!install || dryRun) {\n log(`deictic: install them with ${command}`);\n } else {\n log(`deictic: ${command}`);\n if (!run(command, root)) throw new Error(`deictic: the install failed: run ${command} yourself, then this again`);\n }\n\n configure(root, bundler, dryRun, log);\n\n const skill = `${runnerOf(manager)} skills add ${existsSync(join(root, 'node_modules', 'deictic')) ? './node_modules/deictic' : 'gkurt/deictic'}`;\n const add =\n options.skill ?? (options.ask === undefined ? false : await options.ask('deictic: add the skill, so your agent works the tasks?'));\n if (!add || dryRun) {\n log(`deictic: to have your agent work the tasks, add the skill: ${skill}`);\n } else {\n log(`deictic: ${skill}`);\n if (!run(skill, root)) log(`deictic: adding the skill failed: run ${skill} yourself`);\n }\n\n log(`deictic: screenshots render in Playwright's Chromium (${runnerOf(manager)} playwright install chromium), else Chrome or Edge`);\n log('deictic: start your dev server and Alt-click an element');\n}\n\n/** Adds deictic to the bundler's config, or says what to add where it can't. */\nfunction configure(root: string, bundler: Bundler | undefined, dryRun: boolean, log: (line: string) => void): void {\n if (bundler === undefined) {\n log('deictic: no bundler it knows in package.json (Vite, Next.js, Astro, webpack, Rspack, Bun): see API.md#bundlers to add it');\n return;\n }\n if (bundler === 'bun') {\n configureBun(root, dryRun, log);\n return;\n }\n const setup = SETUPS[bundler];\n const file = setup.files.map((f) => join(root, f)).find((f) => existsSync(f));\n const imports = `import { recommended } from 'deictic/recommended';\\nimport { ${setup.name} } from '${setup.from}';`;\n if (file === undefined) {\n log(`deictic: no ${setup.files[0]} here: add deictic to your ${bundler} config:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n const name = relative(root, file).replaceAll('\\\\', '/');\n const code = readFileSync(file, 'utf8');\n if (/['\"]deictic\\//.test(code)) {\n log(`deictic: ${name} has it already`);\n return;\n }\n const added = addToConfig(bundler, file, code);\n if (added === undefined) {\n log(`deictic: couldn't tell where it goes in ${name}: add it yourself:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n if (!dryRun) writeFileSync(file, added);\n log(`deictic: ${dryRun ? 'would add' : 'added'} it to ${name}`);\n}\n\n/** Bun's three steps: the plugin's module, bunfig.toml, and its routes in the server. Each says what to add where it can't. */\nfunction configureBun(root: string, dryRun: boolean, log: (line: string) => void): void {\n const write = (file: string, text: string) => !dryRun && writeFileSync(file, text);\n const did = dryRun ? 'would add' : 'added';\n const plugin = join(root, MODULE);\n if (!existsSync(plugin)) {\n write(plugin, PLUGIN);\n log(`deictic: ${dryRun ? 'would write' : 'wrote'} ${MODULE}`);\n } else if (!readFileSync(plugin, 'utf8').includes('deictic/bun')) {\n log(`deictic: ${MODULE} is a module of yours: add deictic by hand, as API.md#bundlers says for Bun`);\n return;\n }\n\n const bunfig = join(root, 'bunfig.toml');\n const before = existsSync(bunfig) ? readFileSync(bunfig, 'utf8') : undefined;\n const after = addToBunfig(before);\n if (after === undefined) {\n log(`deictic: couldn't tell where it goes in bunfig.toml: add it yourself:\\n\\n${BY_HAND.bunfig}\\n`);\n } else if (after === before) {\n log('deictic: bunfig.toml has it already');\n } else {\n write(bunfig, after);\n log(`deictic: ${did} it to bunfig.toml`);\n }\n\n const server = serverOf(root)!;\n const name = relative(root, server).replaceAll('\\\\', '/');\n const code = readFileSync(server, 'utf8');\n if (code.includes(MODULE.replace(/\\.ts$/, ''))) {\n log(`deictic: ${name} has its routes already`);\n return;\n }\n const added = addToServer(server, code, root);\n if (added === undefined) {\n log(`deictic: couldn't tell where its routes go in ${name}: add them yourself:\\n\\n${BY_HAND.server}\\n`);\n return;\n }\n write(server, added);\n log(`deictic: ${did} its routes to ${name}`);\n}\n\n/** Asks a yes-or-no question on the terminal, yes by default. */\nasync function ask(question: string): Promise<boolean> {\n const lines = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return !/^n/i.test((await lines.question(`${question} (Y/n) `)).trim());\n } finally {\n lines.close();\n }\n}\n\nexport async function run(values: { dryRun?: boolean; install: boolean; skill?: boolean }): Promise<void> {\n try {\n await init({\n cwd: process.cwd(),\n install: values.install,\n skill: values.skill,\n dryRun: values.dryRun,\n ask: process.stdin.isTTY && process.stdout.isTTY ? ask : undefined,\n });\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e));\n }\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,SAAS,SAAkB,KAAK,SAAS,MAAM,IAAI,SAAS;;AAGzE,SAAgB,SAAS,MAAc,QAAwB;CAC7D,MAAM,QAAQ,KAAK,YAAY,MAAM,SAAS,CAAC,IAAI;CACnD,OAAO,UAAU,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,CAAE;AAC5C;;;;;AAMA,SAAgB,WAAW,KAAkB,SAAkB,MAAc,OAA2B,WAAW,OAAa;CAC9H,MAAM,MAAM,MAAM,IAAI;CACtB,MAAM,UAA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"version":3,"file":"init.js","names":[],"sources":["../../src/cli/edit.ts","../../src/cli/bun.ts","../../src/cli/init.ts"],"sourcesContent":["/**\n * Editing a project's own source the way it's written: its quotes, semicolons, line endings and indentation. What\n * `init` adds to a bundler's config and to a Bun server goes through here.\n */\nimport type MagicString from 'magic-string';\nimport type { Program } from 'oxc-parser';\n\n/** The file's line ending. */\nexport const eolOf = (code: string) => (code.includes('\\r\\n') ? '\\r\\n' : '\\n');\n\n/** The whitespace a line starts with, for the line `offset` is on. */\nexport function indentAt(code: string, offset: number): string {\n const start = code.lastIndexOf('\\n', offset - 1) + 1;\n return /^[ \\t]*/.exec(code.slice(start))![0];\n}\n\n/**\n * Adds import lines after the module's last import (or `require`, in CommonJS), or at its top: written in the quotes\n * and semicolons of its first import. Each line is `[what, from]`: `import ${what} from '${from}'`, or as a `require`.\n */\nexport function addImports(out: MagicString, program: Program, code: string, lines: [string, string][], commonjs = false): void {\n const eol = eolOf(code);\n const imports = program.body.filter((s) => s.type === 'ImportDeclaration');\n const first = imports[0];\n const quote = first === undefined ? \"'\" : code[first.source.start]!;\n const semi = first === undefined || code.slice(first.start, first.end).trimEnd().endsWith(';') ? ';' : '';\n const q = (s: string) => `${quote}${s}${quote}`;\n const text = lines\n .map(([what, from]) => (commonjs ? `const ${what} = require(${q(from)})${semi}` : `import ${what} from ${q(from)}${semi}`))\n .join(eol);\n const after = imports.at(-1) ?? requiresOf(program).at(-1);\n if (after === undefined) out.prepend(`${text}${eol}${eol}`);\n else out.appendLeft(after.end, `${eol}${text}`);\n}\n\n/** The top-level `const … = require(…)` statements of a CommonJS module, to put new ones after. */\nfunction requiresOf(program: Program) {\n return program.body.filter(\n (s) =>\n s.type === 'VariableDeclaration' &&\n s.declarations.some(\n (d) => d.init?.type === 'CallExpression' && d.init.callee.type === 'Identifier' && d.init.callee.name === 'require',\n ),\n );\n}\n\n/** Inserts `text` as the first property of the object literal that starts at `open` (its `{`), as the object is laid out. */\nexport function addFirst(out: MagicString, code: string, open: number, first: { start: number } | undefined, text: string): void {\n const eol = eolOf(code);\n if (first === undefined) {\n out.appendLeft(open + 1, ` ${text} `);\n return;\n }\n const multiline = code.slice(open, first.start).includes('\\n');\n out.appendLeft(first.start, multiline ? `${text},${eol}${indentAt(code, first.start)}` : `${text}, `);\n}\n","/**\n * `init` for Bun's own dev server: `Bun.serve` with HTML imports, which bundles the page with the plugins bunfig.toml\n * names. Only that: a Bun project that runs Vite, Next.js or another bundler is that bundler's, and one with no HTML\n * imports has no page of Bun's for deictic to be in. Three steps, as the API has them: the plugin's module, bunfig's\n * `[serve.static] plugins`, and its routes spread into `Bun.serve`'s.\n */\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\n\nimport MagicString from 'magic-string';\nimport { type CallExpression, parseSync, Visitor } from 'oxc-parser';\n\nimport { addFirst, addImports, eolOf } from './edit.ts';\n\n/** The plugin's module, from the root, which bunfig names and the server imports. */\nexport const MODULE = 'deictic.plugin.ts';\n\nexport const PLUGIN = `import { deictic } from 'deictic/bun';\nimport { deicticRecommended } from 'deictic/recommended';\n\n// One module for both: bunfig.toml names it as the dev server's bundler plugin, and the server spreads its routes,\n// deictic's endpoints, into its own.\nexport default deictic({ plugins: deicticRecommended() });\n`;\n\nconst SOURCE = /\\.[cm]?[jt]sx?$/;\nconst SKIP = new Set(['node_modules', 'dist', 'build', 'out']);\nconst SERVE = /\\bBun\\.serve\\s*\\(/;\nconst HTML = /\\bfrom\\s*['\"][^'\"]+\\.html['\"]/;\n\n/**\n * The module that serves the page with Bun's bundler: it calls `Bun.serve` and imports an HTML file. Looked for under\n * the root, not in dependencies, builds or dot folders, a few folders deep.\n */\nexport function serverOf(root: string): string | undefined {\n const walk = (dir: string, depth: number): string | undefined => {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return undefined;\n }\n for (const e of entries) {\n if (!e.isFile() || !SOURCE.test(e.name)) continue;\n const path = join(dir, e.name);\n const code = readFileSync(path, 'utf8');\n if (SERVE.test(code) && HTML.test(code)) return path;\n }\n if (depth === 0) return undefined;\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;\n const found = walk(join(dir, e.name), depth - 1);\n if (found !== undefined) return found;\n }\n return undefined;\n };\n return walk(root, 3);\n}\n\n/**\n * bunfig.toml with the plugin's module first in `[serve.static] plugins` (first, so it sees the source as written),\n * made where there's none; unchanged where it's there already, and nothing where bunfig says it another way (a dotted\n * key, an inline table) and it can't tell where.\n */\nexport function addToBunfig(text: string | undefined, entry = `./${MODULE}`): string | undefined {\n const quoted = JSON.stringify(entry);\n if (text === undefined) return `[serve.static]\\nplugins = [${quoted}]\\n`;\n if (text.includes(entry)) return text;\n if (/serve\\.static\\.|static\\s*=\\s*\\{/.test(text)) return undefined;\n const eol = eolOf(text);\n const header = /^[ \\t]*\\[serve\\.static\\][ \\t]*(#.*)?$/m.exec(text);\n if (header === null)\n return `${text}${text === '' || text.endsWith('\\n') ? '' : eol}${eol}[serve.static]${eol}plugins = [${quoted}]${eol}`;\n const bodyStart = header.index + header[0].length;\n const next = /^[ \\t]*\\[/m.exec(text.slice(bodyStart));\n const body = text.slice(bodyStart, next === null ? text.length : bodyStart + next.index);\n const list = /^[ \\t]*plugins[ \\t]*=[ \\t]*\\[/m.exec(body);\n if (list === null) return `${text.slice(0, bodyStart)}${eol}plugins = [${quoted}]${text.slice(bodyStart)}`;\n const open = bodyStart + list.index + list[0].length;\n const rest = text.slice(open);\n const empty = /^\\s*\\]/.test(rest);\n const lineBreak = /^[ \\t]*\\r?\\n([ \\t]*)/.exec(rest);\n if (empty) return `${text.slice(0, open)}${quoted}${rest.trimStart()}`;\n if (lineBreak !== null) return `${text.slice(0, open)}${eol}${lineBreak[1]}${quoted},${rest}`;\n return `${text.slice(0, open)}${quoted}, ${rest.trimStart()}`;\n}\n\n/**\n * The server with the plugin's routes first in `Bun.serve`'s `routes`, or `routes` with them where it has none, and\n * the module imported: nothing where `Bun.serve` isn't given an object it can see, or its routes aren't one.\n */\nexport function addToServer(file: string, code: string, root: string): string | undefined {\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const calls: CallExpression[] = [];\n new Visitor({\n CallExpression(node) {\n const { callee } = node;\n if (\n callee.type === 'MemberExpression' &&\n callee.object.type === 'Identifier' &&\n callee.object.name === 'Bun' &&\n callee.property.type === 'Identifier' &&\n callee.property.name === 'serve'\n )\n calls.push(node);\n },\n }).visit(program);\n const options = calls.length === 1 ? calls[0]!.arguments[0] : undefined;\n if (options?.type !== 'ObjectExpression') return undefined;\n\n // `tools`, as the API names it, unless the module has a `tools` of its own.\n const name = /\\btools\\b/.test(code) ? 'deicticTools' : 'tools';\n const out = new MagicString(code);\n const routes = options.properties.find(\n (p) => p.type === 'Property' && !p.computed && p.key.type === 'Identifier' && p.key.name === 'routes',\n );\n if (routes === undefined) {\n addFirst(out, code, options.start, options.properties[0], `routes: { ...${name}.routes }`);\n } else {\n if (routes.type !== 'Property' || routes.value.type !== 'ObjectExpression') return undefined;\n addFirst(out, code, routes.value.start, routes.value.properties[0], `...${name}.routes`);\n }\n const from = relative(dirname(file), join(root, MODULE)).replaceAll('\\\\', '/');\n addImports(out, program, code, [[name, from.startsWith('.') ? from : `./${from}`]]);\n return out.toString();\n}\n\n/** What to add by hand, for a server or a bunfig it can't edit. */\nexport const BY_HAND = {\n bunfig: `[serve.static]\\nplugins = [\"./${MODULE}\"]`,\n server: `import tools from './${MODULE}';\\nBun.serve({ routes: { ...tools.routes, '/*': index } });`,\n};\n","/**\n * `deictic init`: the recommended setup in a project, in one step. It installs deictic and what the recommended\n * plugins import, with the project's package manager and as the project's own dev dependencies (deictic, the\n * page's bundle and the skill all find them from the project, so they can't come in through another package), adds\n * deictic to the bundler's config where it can find the place, and offers the agent skill.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\n\nimport MagicString from 'magic-string';\nimport { type Expression, type ObjectExpression, parseSync, type Program } from 'oxc-parser';\n\nimport { deicticRecommended } from '#src/plugins/recommended/index.ts';\n\nimport { installCommand, installed, packageManager, readJson, runnerOf } from '#src/tools/packages.ts';\n\nimport { fail } from './board.ts';\nimport { addToBunfig, addToServer, BY_HAND, MODULE, PLUGIN, serverOf } from './bun.ts';\nimport { addFirst, addImports } from './edit.ts';\n\nexport type Bundler = 'next' | 'astro' | 'vite' | 'rspack' | 'webpack' | 'bun';\n\ninterface Setup {\n /** The config files it looks for, in order. */\n files: string[];\n /** The module deictic's integration comes from, and its name there. */\n from: string;\n name: string;\n /** What goes in the config: in its `list`, or wrapped around the whole of it with `wrap`. */\n list?: string;\n value: string;\n wrap?: boolean;\n /** The snippet for a config it can't edit. */\n snippet: string;\n}\n\nconst extensions = (base: string) => ['ts', 'mts', 'js', 'mjs', 'cts', 'cjs'].map((e) => `${base}.${e}`);\nconst PLUGINS = '{ plugins: deicticRecommended() }';\n\nconst SETUPS: Record<Exclude<Bundler, 'bun'>, Setup> = {\n next: {\n files: extensions('next.config'),\n from: 'deictic/next',\n name: 'withDeictic',\n value: PLUGINS,\n wrap: true,\n snippet: `export default withDeictic(nextConfig, ${PLUGINS});`,\n },\n astro: {\n files: extensions('astro.config'),\n from: 'deictic/astro',\n name: 'deictic',\n list: 'integrations',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ integrations: [deictic(${PLUGINS})] });`,\n },\n vite: {\n files: extensions('vite.config'),\n from: 'deictic/vite',\n name: 'deictic',\n list: 'plugins',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ plugins: [deictic(${PLUGINS}), react()] });`,\n },\n rspack: {\n files: extensions('rspack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n webpack: {\n files: extensions('webpack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n};\n\n/** The project's root: the nearest folder with a package.json, from `dir` up. */\nexport function rootOf(dir: string): string | undefined {\n for (let at = dir; ; at = dirname(at)) {\n if (existsSync(join(at, 'package.json'))) return at;\n if (dirname(at) === at) return undefined;\n }\n}\n\n/** The project's dependencies and dev dependencies, by name. */\nfunction dependenciesOf(root: string): Set<string> {\n const manifest = readJson(join(root, 'package.json')) ?? {};\n return new Set([manifest.dependencies, manifest.devDependencies].flatMap((d) => Object.keys((d as object | undefined) ?? {})));\n}\n\n/** The bundler the project runs its dev server with, from its dependencies, or none deictic knows. */\nexport function bundlerOf(root: string): Bundler | undefined {\n const has = dependenciesOf(root);\n if (has.has('next')) return 'next';\n if (has.has('astro')) return 'astro';\n if (has.has('vite') || SETUPS.vite.files.some((f) => existsSync(join(root, f)))) return 'vite';\n if (has.has('@rspack/core') || has.has('@rspack/cli')) return 'rspack';\n if (has.has('webpack')) return 'webpack';\n // Bun's own bundler only where a server of the project's has it bundle a page: not every project Bun runs.\n if (serverOf(root) !== undefined) return 'bun';\n return undefined;\n}\n\n/**\n * What the recommended setup imports, for the bundler and the project: launch-editor opens files under webpack, which\n * has no launcher, and React's state is read only where it has React.\n */\nexport function packagesFor(bundler: Bundler | undefined, root: string): string[] {\n // Named in package.json and not installed yet, in a fresh checkout, or installed from a workspace's.\n const react = dependenciesOf(root).has('react') || installed(root, 'react');\n const plugins = deicticRecommended({ react: react ? {} : false }).flatMap((p) => p.packages ?? []);\n return ['deictic', ...plugins, ...(bundler === 'webpack' || bundler === 'rspack' ? ['launch-editor'] : [])];\n}\n\ntype Node = Expression | ObjectExpression;\n\n/**\n * The object an expression comes to: through `defineConfig(…)`, `(…)`, `satisfies`, a function's return and a top-level\n * `const`. Not through another call: in `mergeConfig(base, {…})` or webpack-merge's `merge(common, {…})` the first\n * argument is a base the project may build with too, and the plugin isn't the base's.\n */\nfunction objectOf(node: Node | null | undefined, program: Program, depth = 0): ObjectExpression | undefined {\n if (node == null || depth > 8) return undefined;\n const next = (n: Node | null | undefined) => objectOf(n, program, depth + 1);\n if (node.type === 'ObjectExpression') return node;\n if (node.type === 'ParenthesizedExpression' || node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')\n return next(node.expression);\n if (node.type === 'CallExpression') {\n const { callee } = node;\n const named = (callee.type === 'Identifier' ? callee : callee.type === 'MemberExpression' ? callee.property : undefined) as\n { type: string; name?: string } | undefined;\n const [first] = node.arguments;\n if (named?.name !== 'defineConfig' || first === undefined || first.type === 'SpreadElement') return undefined;\n return next(first);\n }\n if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {\n const body = node.body;\n if (body === null) return undefined;\n if (body.type !== 'BlockStatement') return next(body);\n const returned = body.body.findLast((s) => s.type === 'ReturnStatement');\n return returned?.type === 'ReturnStatement' ? next(returned.argument) : undefined;\n }\n if (node.type !== 'Identifier') return undefined;\n for (const statement of program.body) {\n const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n const found = declaration.declarations.find((d) => d.id.type === 'Identifier' && d.id.name === node.name);\n if (found !== undefined) return next(found.init);\n }\n return undefined;\n}\n\n/** The config's exported value: `export default …` or `module.exports = …`, and whether it's CommonJS. */\nfunction exportedOf(program: Program): { value: Expression; commonjs: boolean } | undefined {\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n return value.type.endsWith('Declaration') && value.type !== 'FunctionDeclaration'\n ? undefined\n : { value: value as Expression, commonjs: false };\n }\n if (statement.type !== 'ExpressionStatement' || statement.expression.type !== 'AssignmentExpression') continue;\n const { left, right } = statement.expression;\n const exports =\n left.type === 'MemberExpression' &&\n left.object.type === 'Identifier' &&\n left.object.name === 'module' &&\n left.property.type === 'Identifier' &&\n left.property.name === 'exports';\n if (exports) return { value: right, commonjs: true };\n }\n return undefined;\n}\n\n/**\n * The config with deictic added, or nothing where it can't tell where: deictic's import beside the config's, and its\n * plugin first in the list (`plugins`, `integrations`), as its marks count lines and columns in the code it's given, or the config wrapped (Next's). Written in the config's quotes,\n * semicolons and line endings.\n */\nexport function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {\n const setup = SETUPS[bundler];\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const exported = exportedOf(program);\n if (exported === undefined) return undefined;\n const out = new MagicString(code);\n\n if (setup.wrap) {\n out.appendLeft(exported.value.start, `${setup.name}(`);\n out.appendRight(exported.value.end, `, ${setup.value})`);\n } else {\n const object = objectOf(exported.value, program);\n if (object === undefined || !addTo(out, code, object, setup.list!, setup.value)) return undefined;\n }\n\n const lines: [string, string][] = [\n ['{ deicticRecommended }', 'deictic/recommended'],\n [`{ ${setup.name} }`, setup.from],\n ];\n addImports(out, program, code, lines, exported.commonjs);\n return out.toString();\n}\n\n/**\n * Adds `value` first in the object's array `list`, or the list with it, as the object is laid out. False where `list`\n * isn't an array. First, since a plugin before deictic's that changes a module (both `pre` under Vite) leaves the\n * page's marks pointing at its code, not the file.\n */\nfunction addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string): boolean {\n const property = object.properties.find(\n (p) =>\n p.type === 'Property' &&\n !p.computed &&\n ((p.key.type === 'Identifier' && p.key.name === list) || (p.key.type === 'Literal' && p.key.value === list)),\n );\n if (property !== undefined) {\n if (property.type !== 'Property') return false;\n let array = property.value;\n while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;\n if (array.type !== 'ArrayExpression') return false;\n const first = array.elements.find((e) => e !== null);\n if (first == null) {\n out.appendLeft(array.start + 1, value);\n return true;\n }\n addFirst(out, code, array.start, first, value);\n return true;\n }\n addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);\n return true;\n}\n\nexport interface InitOptions {\n /** Where it runs: the project is the nearest folder with a package.json. */\n cwd: string;\n /** Installs the packages; false only says the command. */\n install?: boolean;\n /** Adds the skill (true), says how (false), or asks (undefined, on a terminal; says how elsewhere). */\n skill?: boolean;\n /** Says what it would do, and does none of it. */\n dryRun?: boolean;\n log?: (line: string) => void;\n /** Runs a command in the project, and answers whether it succeeded. */\n run?: (command: string, cwd: string) => boolean;\n ask?: (question: string) => Promise<boolean>;\n}\n\nconst runIn = (command: string, cwd: string) => spawnSync(command, { cwd, stdio: 'inherit', shell: true }).status === 0;\n\n/** Sets the project up; throws what to do where it can't. */\nexport async function init(options: InitOptions): Promise<void> {\n const { install = true, dryRun = false, log = console.log, run = runIn } = options;\n const root = rootOf(options.cwd);\n if (root === undefined) throw new Error('deictic: no package.json here or above: run it in your project');\n const manager = packageManager(root);\n const bundler = bundlerOf(root);\n const has = dependenciesOf(root);\n\n const wanted = packagesFor(bundler, root).filter((p) => !has.has(p));\n const command = installCommand(manager, wanted, root);\n if (wanted.length === 0) {\n log('deictic: its packages are installed');\n } else if (!install || dryRun) {\n log(`deictic: install them with ${command}`);\n } else {\n log(`deictic: ${command}`);\n if (!run(command, root)) throw new Error(`deictic: the install failed: run ${command} yourself, then this again`);\n }\n\n configure(root, bundler, dryRun, log);\n\n const skill = `${runnerOf(manager)} skills add ${existsSync(join(root, 'node_modules', 'deictic')) ? './node_modules/deictic' : 'gkurt/deictic'}`;\n const add =\n options.skill ?? (options.ask === undefined ? false : await options.ask('deictic: add the skill, so your agent works the tasks?'));\n if (!add || dryRun) {\n log(`deictic: to have your agent work the tasks, add the skill: ${skill}`);\n } else {\n log(`deictic: ${skill}`);\n if (!run(skill, root)) log(`deictic: adding the skill failed: run ${skill} yourself`);\n }\n\n log(`deictic: screenshots render in Playwright's Chromium (${runnerOf(manager)} playwright install chromium), else Chrome or Edge`);\n log('deictic: start your dev server and Alt-click an element');\n}\n\n/** Adds deictic to the bundler's config, or says what to add where it can't. */\nfunction configure(root: string, bundler: Bundler | undefined, dryRun: boolean, log: (line: string) => void): void {\n if (bundler === undefined) {\n log('deictic: no bundler it knows in package.json (Vite, Next.js, Astro, webpack, Rspack, Bun): see API.md#bundlers to add it');\n return;\n }\n if (bundler === 'bun') {\n configureBun(root, dryRun, log);\n return;\n }\n const setup = SETUPS[bundler];\n const file = setup.files.map((f) => join(root, f)).find((f) => existsSync(f));\n const imports = `import { deicticRecommended } from 'deictic/recommended';\\nimport { ${setup.name} } from '${setup.from}';`;\n if (file === undefined) {\n log(`deictic: no ${setup.files[0]} here: add deictic to your ${bundler} config:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n const name = relative(root, file).replaceAll('\\\\', '/');\n const code = readFileSync(file, 'utf8');\n if (/['\"]deictic\\//.test(code)) {\n log(`deictic: ${name} has it already`);\n return;\n }\n const added = addToConfig(bundler, file, code);\n if (added === undefined) {\n log(`deictic: couldn't tell where it goes in ${name}: add it yourself:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n if (!dryRun) writeFileSync(file, added);\n log(`deictic: ${dryRun ? 'would add' : 'added'} it to ${name}`);\n}\n\n/** Bun's three steps: the plugin's module, bunfig.toml, and its routes in the server. Each says what to add where it can't. */\nfunction configureBun(root: string, dryRun: boolean, log: (line: string) => void): void {\n const write = (file: string, text: string) => !dryRun && writeFileSync(file, text);\n const did = dryRun ? 'would add' : 'added';\n const plugin = join(root, MODULE);\n if (!existsSync(plugin)) {\n write(plugin, PLUGIN);\n log(`deictic: ${dryRun ? 'would write' : 'wrote'} ${MODULE}`);\n } else if (!readFileSync(plugin, 'utf8').includes('deictic/bun')) {\n log(`deictic: ${MODULE} is a module of yours: add deictic by hand, as API.md#bundlers says for Bun`);\n return;\n }\n\n const bunfig = join(root, 'bunfig.toml');\n const before = existsSync(bunfig) ? readFileSync(bunfig, 'utf8') : undefined;\n const after = addToBunfig(before);\n if (after === undefined) {\n log(`deictic: couldn't tell where it goes in bunfig.toml: add it yourself:\\n\\n${BY_HAND.bunfig}\\n`);\n } else if (after === before) {\n log('deictic: bunfig.toml has it already');\n } else {\n write(bunfig, after);\n log(`deictic: ${did} it to bunfig.toml`);\n }\n\n const server = serverOf(root)!;\n const name = relative(root, server).replaceAll('\\\\', '/');\n const code = readFileSync(server, 'utf8');\n if (code.includes(MODULE.replace(/\\.ts$/, ''))) {\n log(`deictic: ${name} has its routes already`);\n return;\n }\n const added = addToServer(server, code, root);\n if (added === undefined) {\n log(`deictic: couldn't tell where its routes go in ${name}: add them yourself:\\n\\n${BY_HAND.server}\\n`);\n return;\n }\n write(server, added);\n log(`deictic: ${did} its routes to ${name}`);\n}\n\n/** Asks a yes-or-no question on the terminal, yes by default. */\nasync function ask(question: string): Promise<boolean> {\n const lines = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return !/^n/i.test((await lines.question(`${question} (Y/n) `)).trim());\n } finally {\n lines.close();\n }\n}\n\nexport async function run(values: { dryRun?: boolean; install: boolean; skill?: boolean }): Promise<void> {\n try {\n await init({\n cwd: process.cwd(),\n install: values.install,\n skill: values.skill,\n dryRun: values.dryRun,\n ask: process.stdin.isTTY && process.stdout.isTTY ? ask : undefined,\n });\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e));\n }\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,SAAS,SAAkB,KAAK,SAAS,MAAM,IAAI,SAAS;;AAGzE,SAAgB,SAAS,MAAc,QAAwB;CAC7D,MAAM,QAAQ,KAAK,YAAY,MAAM,SAAS,CAAC,IAAI;CACnD,OAAO,UAAU,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,CAAE;AAC5C;;;;;AAMA,SAAgB,WAAW,KAAkB,SAAkB,MAAc,OAA2B,WAAW,OAAa;CAC9H,MAAM,MAAM,MAAM,IAAI;CACtB,MAAM,UAAU,QAAQ,KAAK,QAAQ,MAAM,EAAE,SAAS,mBAAmB;CACzE,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,UAAU,KAAA,IAAY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AAC;CACjD;AACF"}
|
package/dist/shared/marks.js
CHANGED
|
@@ -14,6 +14,12 @@ const PAGE = "deictic.page";
|
|
|
14
14
|
* recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.
|
|
15
15
|
*/
|
|
16
16
|
const END = "deictic.end";
|
|
17
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The custom event for React's commits, where the react plugin is loaded and they're asked for (the recording's React
|
|
19
|
+
* button): a `Commit` each (`deictic/react`'s), and `{ on }` where the recording starts and stops having them, so a
|
|
20
|
+
* stretch without them isn't read as one where nothing rendered.
|
|
21
|
+
*/
|
|
22
|
+
const REACT = "deictic.react";
|
|
23
|
+
export { REACT as i, MARKS as n, PAGE as r, END as t };
|
|
18
24
|
|
|
19
25
|
//# sourceMappingURL=marks.js.map
|
package/dist/shared/marks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marks.js","names":[],"sources":["../../src/plugins/recordings/marks.ts"],"sourcesContent":["/**\n * The custom event's tag the marks go in: the page's annotations, as an SVG in page coordinates (`svg`),\n * and as the annotations themselves (`annotations`, absent from recordings made before it was added).\n */\nexport const MARKS = 'deictic.annotations';\n\n/**\n * The custom event for the page's address changing with no load, as a router does it (`href`, the new one): rrweb\n * records what the route drew, not that the address changed. A page that loads has rrweb's own `Meta` instead.\n */\nexport const PAGE = 'deictic.page';\n\n/**\n * The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a\n * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.\n */\nexport const END = 'deictic.end';\n"],"mappings":";;;;;AAIA,MAAa,QAAQ;;;;;AAMrB,MAAa,OAAO;;;;;AAMpB,MAAa,MAAM"}
|
|
1
|
+
{"version":3,"file":"marks.js","names":[],"sources":["../../src/plugins/recordings/marks.ts"],"sourcesContent":["/**\n * The custom event's tag the marks go in: the page's annotations, as an SVG in page coordinates (`svg`),\n * and as the annotations themselves (`annotations`, absent from recordings made before it was added).\n */\nexport const MARKS = 'deictic.annotations';\n\n/**\n * The custom event for the page's address changing with no load, as a router does it (`href`, the new one): rrweb\n * records what the route drew, not that the address changed. A page that loads has rrweb's own `Meta` instead.\n */\nexport const PAGE = 'deictic.page';\n\n/**\n * The custom event a recording ends with: rrweb's timeline lasts as long as its events, so without it a\n * recording of a still page (a voice-over, say) would replay as a moment, and its voice never play.\n */\nexport const END = 'deictic.end';\n\n/**\n * The custom event for React's commits, where the react plugin is loaded and they're asked for (the recording's React\n * button): a `Commit` each (`deictic/react`'s), and `{ on }` where the recording starts and stops having them, so a\n * stretch without them isn't read as one where nothing rendered.\n */\nexport const REACT = 'deictic.react';\n"],"mappings":";;;;;AAIA,MAAa,QAAQ;;;;;AAMrB,MAAa,OAAO;;;;;AAMpB,MAAa,MAAM;;;;;;AAOnB,MAAa,QAAQ"}
|
package/dist/shared/package.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// package.json
|
|
2
2
|
var name = "deictic";
|
|
3
|
-
var version = "0.
|
|
3
|
+
var version = "0.9.0";
|
|
4
4
|
var bugs = { "url": "https://github.com/gkurt/deictic/issues" };
|
|
5
5
|
var peerDependencies = {
|
|
6
6
|
"@rrweb/rrweb-plugin-console-record": "^2.2.2",
|
|
@@ -8,10 +8,12 @@ var peerDependencies = {
|
|
|
8
8
|
"@rspack/core": ">=1",
|
|
9
9
|
"@vercel/board": ">=0.53.0",
|
|
10
10
|
"astro": ">=5",
|
|
11
|
+
"bippy": "^0.7.3",
|
|
11
12
|
"launch-editor": "^2.9.0",
|
|
12
13
|
"modern-screenshot": "^4.7.0",
|
|
13
14
|
"next": ">=16",
|
|
14
15
|
"playwright-core": "^1.50.0",
|
|
16
|
+
"react": ">=18",
|
|
15
17
|
"rrweb": "^2.2.2",
|
|
16
18
|
"rrweb-player": "^2.2.2",
|
|
17
19
|
"rrweb-snapshot": "^2.2.2",
|
package/dist/shared/packages.js
CHANGED
|
@@ -118,6 +118,6 @@ function missingProblem(root, plugins) {
|
|
|
118
118
|
message: `install what ${who} ${need}, then restart the dev server: ${installCommand(packageManager(root), names, root)}`
|
|
119
119
|
};
|
|
120
120
|
}
|
|
121
|
-
export {
|
|
121
|
+
export { packageManager as a, missingProblem as i, installCommand as n, readJson as o, installed as r, runnerOf as s, execOf as t };
|
|
122
122
|
|
|
123
123
|
//# sourceMappingURL=packages.js.map
|
|
@@ -80,7 +80,7 @@ async function render(input, options) {
|
|
|
80
80
|
...shot,
|
|
81
81
|
size: CANVAS_SIZE
|
|
82
82
|
};
|
|
83
|
-
const found = await page.evaluate(async ({ snapshot, scroll, overlay, element, size }) => {
|
|
83
|
+
const found = await page.evaluate(async ({ snapshot, scroll, overlay, element, size, states }) => {
|
|
84
84
|
const { rebuildIntoSandboxedIframe, createCache, createMirror } = globalThis.rrwebSnapshot;
|
|
85
85
|
const mirror = createMirror();
|
|
86
86
|
const { iframe } = rebuildIntoSandboxedIframe(snapshot, {
|
|
@@ -95,6 +95,44 @@ async function render(input, options) {
|
|
|
95
95
|
const hidden = doc.createElement("style");
|
|
96
96
|
hidden.textContent = "noscript { display: none !important; }";
|
|
97
97
|
doc.head.append(hidden);
|
|
98
|
+
if (states !== void 0) {
|
|
99
|
+
const pseudo = [
|
|
100
|
+
[":focus-visible", "deictic-focus-visible"],
|
|
101
|
+
[":focus-within", "deictic-focus-within"],
|
|
102
|
+
[":focus", "deictic-focus"],
|
|
103
|
+
[":hover", "deictic-hover"]
|
|
104
|
+
];
|
|
105
|
+
const copy = (into) => {
|
|
106
|
+
const list = into.cssRules;
|
|
107
|
+
for (let i = 0; i < list.length; i++) {
|
|
108
|
+
const rule = list[i];
|
|
109
|
+
if (rule.cssRules !== void 0 && rule.insertRule !== void 0) copy(rule);
|
|
110
|
+
const selector = rule.selectorText;
|
|
111
|
+
if (selector === void 0 || !rule.cssText.startsWith(selector)) continue;
|
|
112
|
+
let stated = selector;
|
|
113
|
+
for (const [name, className] of pseudo) stated = stated.split(name).join(`.${className}`);
|
|
114
|
+
if (stated === selector) continue;
|
|
115
|
+
try {
|
|
116
|
+
into.insertRule(stated + rule.cssText.slice(selector.length), i + 1);
|
|
117
|
+
i++;
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const roots = [doc];
|
|
122
|
+
for (let i = 0; i < roots.length; i++) for (const el of roots[i].querySelectorAll("*")) if (el.shadowRoot !== null) roots.push(el.shadowRoot);
|
|
123
|
+
for (const root of roots) for (const sheet of [...root.styleSheets, ...root.adoptedStyleSheets]) try {
|
|
124
|
+
copy(sheet);
|
|
125
|
+
} catch {}
|
|
126
|
+
for (const [name, className] of Object.entries({
|
|
127
|
+
hover: "deictic-hover",
|
|
128
|
+
focus: "deictic-focus",
|
|
129
|
+
focusVisible: "deictic-focus-visible",
|
|
130
|
+
focusWithin: "deictic-focus-within"
|
|
131
|
+
})) for (const id of states[name] ?? []) {
|
|
132
|
+
const node = mirror.getNode(id);
|
|
133
|
+
if (isElement(node)) node.classList.add(className);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
98
136
|
for (const canvas of doc.querySelectorAll(`canvas[${size}]`)) {
|
|
99
137
|
const meta = mirror.getMeta(canvas);
|
|
100
138
|
const [box, inline] = (canvas.getAttribute(size) ?? "").split(" ");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"playwright.js","names":[],"sources":["../../src/plugins/screenshots/playwright.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and\n * screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The\n * browser is launched on the first shot and kept for the next; Playwright closes it with the process.\n *\n * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which\n * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs\n * whole, and its stylesheets' fonts and images load from the dev server as the page's did.\n *\n * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the\n * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window\n * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then\n * cut to the part the page is in.\n */\nimport { createRequire } from 'node:module';\n\nimport type { Browser } from 'playwright-core';\nimport type * as Rrweb from 'rrweb-snapshot';\n\nimport { CANVAS_SIZE } from './canvas.ts';\nimport type { Box, BrowserOptions } from './index.ts';\n\n/** What the page sends: its snapshot and what's needed to show it as the page does. */\n/** A node of an rrweb snapshot, as `snapshot()` answers it. */\nexport type SnapshotNode = NonNullable<ReturnType<typeof Rrweb.snapshot>>;\n\nexport interface Snapshot {\n snapshot: SnapshotNode;\n url: string;\n viewport: { width: number; height: number };\n /** The window's size, scrollbars included, where it has any: what the page's media queries ask. */\n window?: { width: number; height: number };\n scroll: { x: number; y: number };\n scale: number;\n /** The element the shot is of, as the snapshot numbers its nodes: found again in the rebuilt page, for where it is there. */\n element?: number;\n /** The part of the viewport to keep, for a shot of an element alone: where the element was in the page. */\n clip?: Box;\n /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */\n overlay?: string;\n}\n\nconst HOST = '<!doctype html><html><body style=\"margin:0\"></body></html>';\n\nconst browsers = new Map<string, Promise<Browser>>();\n\n/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */\nexport function browserOf(options: BrowserOptions): Promise<Browser> {\n const key = JSON.stringify(options);\n const known = browsers.get(key);\n if (known !== undefined) return known;\n const launched = launch(options);\n browsers.set(key, launched);\n // A launch that failed is tried again on the next shot, after the user installs what it said to.\n launched.catch(() => browsers.delete(key));\n return launched;\n}\n\n/** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */\nconst SCROLLBARS = { ignoreDefaultArgs: ['--hide-scrollbars'] };\n\nasync function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {\n const { chromium } = await import('playwright-core').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });\n });\n if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel, ...SCROLLBARS });\n const tried: string[] = [];\n for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {\n try {\n return await chromium.launch({ ...attempt, ...SCROLLBARS });\n } catch (e) {\n tried.push(\n `${'channel' in attempt ? attempt.channel : \"Playwright's Chromium\"}: ${(e instanceof Error ? e.message : String(e)).split('\\n', 1)[0]}`,\n );\n }\n }\n throw new Error(\n `the rrweb() renderer found no browser to render in (${tried.join('; ')}): run \\`npx playwright install chromium\\`, or pass rrweb({ executablePath })`,\n );\n}\n\n/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */\nconst bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');\n\n/**\n * The PNG, and where the element is in it. That's measured in the rebuilt page, not taken from the live one: the\n * two can lay out a few pixels apart (a font that loaded differently, a panel's own scroll), and an outline drawn\n * at the live page's box would then cross the element.\n */\nexport async function render(input: unknown, options: BrowserOptions): Promise<{ png: Uint8Array; box?: Box }> {\n const shot = input as Snapshot;\n if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')\n throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');\n const browser = await browserOf(options);\n const context = await browser.newContext({ viewport: shot.window ?? shot.viewport, deviceScaleFactor: shot.scale });\n try {\n const page = await context.newPage();\n const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;\n await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));\n await page.goto(host);\n await page.addScriptTag({ path: bundle() });\n // The shot, and the attribute that sizes each canvas's picture, which the page's code can't import.\n const given = { ...shot, size: CANVAS_SIZE };\n const found = await page.evaluate(async ({ snapshot, scroll, overlay, element, size }) => {\n const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })\n .rrwebSnapshot;\n const mirror = createMirror();\n const { iframe } = rebuildIntoSandboxedIframe(snapshot, {\n root: document.body,\n cache: createCache(),\n mirror,\n iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },\n });\n const doc = iframe.contentDocument;\n if (doc === null) throw new Error('screenshots: the snapshot was rebuilt where it cannot be read');\n // By its kind: the iframe's elements aren't instances of this page's `Element`.\n const isElement = (node: Node | null): node is Element => node?.nodeType === 1;\n // rrweb rebuilds a script as a `noscript` holding SCRIPT_PLACEHOLDER, which the sandbox, running no scripts,\n // shows: hidden, as rrweb's own replayer hides it.\n const hidden = doc.createElement('style');\n hidden.textContent = 'noscript { display: none !important; }';\n doc.head.append(hidden);\n // The sandbox runs no scripts, and where scripts don't run, a canvas shows what's inside the canvas instead of\n // what was drawn on the canvas: so each canvas's picture goes inside the canvas, at the size the page laid the\n // canvas out at. rrweb's own drawing of the picture on the canvas never shows.\n for (const canvas of doc.querySelectorAll(`canvas[${size}]`)) {\n const meta = mirror.getMeta(canvas);\n const [box, inline] = (canvas.getAttribute(size) ?? '').split(' ');\n const [width, height] = (box ?? '').split('x');\n if (meta === null || !('attributes' in meta) || typeof meta.attributes.rr_dataURL !== 'string') continue;\n const picture = doc.createElement('img');\n picture.src = meta.attributes.rr_dataURL;\n // In a line as the canvas was, else the whole of the canvas's box.\n picture.style.cssText = `display:${inline === undefined ? 'block' : 'inline'};width:${width}px;height:${height}px`;\n canvas.replaceChildren(picture);\n }\n await doc.fonts.ready;\n await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));\n // At once: a page with `scroll-behavior: smooth` would glide there, and be shot on its way.\n iframe.contentWindow?.scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });\n // rrweb scrolled each element as it built it, before the fonts and images gave its content its height:\n // one that couldn't scroll that far yet is scrolled again now.\n for (const id of mirror.getIds()) {\n const node = mirror.getNode(id);\n const meta = node === null ? null : mirror.getMeta(node);\n if (!isElement(node) || meta === null || !('attributes' in meta)) continue;\n const { rr_scrollTop: top, rr_scrollLeft: left } = meta.attributes;\n if (typeof top !== 'number' && typeof left !== 'number') continue;\n node.scrollTo({\n top: typeof top === 'number' ? top : node.scrollTop,\n left: typeof left === 'number' ? left : node.scrollLeft,\n behavior: 'instant',\n });\n }\n const node = element === undefined ? null : mirror.getNode(element);\n // The iframe fills the page from its top left, so a box in it is one in the shot.\n const rect = isElement(node) ? node.getBoundingClientRect() : undefined;\n const box = rect === undefined ? undefined : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };\n if (overlay === undefined) return box;\n // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.\n const marks = document.createElement('div');\n marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';\n marks.innerHTML = overlay;\n document.body.append(marks);\n return box;\n }, given);\n // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.\n // A shot of the element alone is cut where the element is here.\n const clip = clamp(shot.clip === undefined ? { x: 0, y: 0, ...shot.viewport } : (found ?? shot.clip), shot.viewport);\n const png = new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));\n return { png, ...(found === undefined || shot.clip !== undefined ? {} : { box: found }) };\n } finally {\n await context.close();\n }\n}\n\n/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */\nfunction clamp(box: Box, viewport: { width: number; height: number }): Box | undefined {\n const x = Math.max(0, box.x);\n const y = Math.max(0, box.y);\n const width = Math.min(viewport.width, box.x + box.width) - x;\n const height = Math.min(viewport.height, box.y + box.height) - y;\n return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0CA,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAA8B;;AAGnD,SAAgB,UAAU,SAA2C;CACnE,MAAM,MAAM,KAAK,UAAU,OAAO;CAClC,MAAM,QAAQ,SAAS,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,WAAW,OAAO,OAAO;CAC/B,SAAS,IAAI,KAAK,QAAQ;CAE1B,SAAS,YAAY,SAAS,OAAO,GAAG,CAAC;CACzC,OAAO;AACT;;AAGA,MAAM,a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A,IADO,WAAW,MAAM,KAAK,WAAW;IAAE,MAAM;IAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;GAAG,CAAC,CAC9F;GAAG,GAAI,UAAU,KAAA,KAAa,KAAK,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK,MAAM;EAAG;CAC1F,UAAU;EACR,MAAM,QAAQ,MAAM;CACtB;AACF;;AAGA,SAAS,MAAM,KAAU,UAA8D;CACrF,MAAM,IAAI,KAAK,IAAI,GAAG,IAAI,CAAC;CAC3B,MAAM,IAAI,KAAK,IAAI,GAAG,IAAI,CAAC;CAC3B,MAAM,QAAQ,KAAK,IAAI,SAAS,OAAO,IAAI,IAAI,IAAI,KAAK,IAAI;CAC5D,MAAM,SAAS,KAAK,IAAI,SAAS,QAAQ,IAAI,IAAI,IAAI,MAAM,IAAI;CAC/D,OAAO,QAAQ,KAAK,SAAS,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO,IAAI,KAAA;AAC7D"}
|
|
1
|
+
{"version":3,"file":"playwright.js","names":[],"sources":["../../src/plugins/screenshots/playwright.ts"],"sourcesContent":["/**\n * The `rrweb()` renderer's server half: rebuilds a page's snapshot in a browser beside the dev server and\n * screenshots it at the page's viewport, scroll and pixel density, so text lays out as the page's does. The\n * browser is launched on the first shot and kept for the next; Playwright closes it with the process.\n *\n * The snapshot is rebuilt into a sandboxed iframe filling a blank page on the page's own origin, which\n * Playwright answers itself, so nothing asks the dev server for it: rrweb has made the snapshot's URLs\n * whole, and its stylesheets' fonts and images load from the dev server as the page's did.\n *\n * The browser is as big as the page's window, scrollbars and all, and shows its own: a media query asks the\n * window's width, and the page is laid out in what the scrollbar leaves. At the width without it, a window\n * right on a breakpoint (1024 wide, 1009 to lay out in) would render as the narrower layout. The shot is then\n * cut to the part the page is in.\n */\nimport { createRequire } from 'node:module';\n\nimport type { Browser } from 'playwright-core';\nimport type * as Rrweb from 'rrweb-snapshot';\n\nimport { CANVAS_SIZE } from './canvas.ts';\nimport type { Box, BrowserOptions } from './index.ts';\n\n/** What the page sends: its snapshot and what's needed to show it as the page does. */\n/** A node of an rrweb snapshot, as `snapshot()` answers it. */\nexport type SnapshotNode = NonNullable<ReturnType<typeof Rrweb.snapshot>>;\n\nexport interface Snapshot {\n snapshot: SnapshotNode;\n url: string;\n viewport: { width: number; height: number };\n /** The window's size, scrollbars included, where it has any: what the page's media queries ask. */\n window?: { width: number; height: number };\n scroll: { x: number; y: number };\n scale: number;\n /** The element the shot is of, as the snapshot numbers its nodes: found again in the rebuilt page, for where it is there. */\n element?: number;\n /** The part of the viewport to keep, for a shot of an element alone: where the element was in the page. */\n clip?: Box;\n /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */\n overlay?: string;\n /** The nodes in each interactive state as the shot was taken, which a copy of the DOM can't be in itself. */\n states?: States;\n}\n\n/** The snapshot's nodes that matched each pseudo-class: what was hovered, focused, and around the focus. */\nexport interface States {\n hover?: number[];\n focus?: number[];\n focusVisible?: number[];\n focusWithin?: number[];\n}\n\nconst HOST = '<!doctype html><html><body style=\"margin:0\"></body></html>';\n\nconst browsers = new Map<string, Promise<Browser>>();\n\n/** A browser by the options, launched once: the one named, or Playwright's own Chromium, then Chrome, then Edge. */\nexport function browserOf(options: BrowserOptions): Promise<Browser> {\n const key = JSON.stringify(options);\n const known = browsers.get(key);\n if (known !== undefined) return known;\n const launched = launch(options);\n browsers.set(key, launched);\n // A launch that failed is tried again on the next shot, after the user installs what it said to.\n launched.catch(() => browsers.delete(key));\n return launched;\n}\n\n/** Playwright hides a headless browser's scrollbars, and with them the room they take in the page. */\nconst SCROLLBARS = { ignoreDefaultArgs: ['--hide-scrollbars'] };\n\nasync function launch({ executablePath, channel }: BrowserOptions): Promise<Browser> {\n const { chromium } = await import('playwright-core').catch((e: unknown) => {\n throw new Error('the rrweb() renderer needs playwright-core: add it to your devDependencies', { cause: e });\n });\n if (executablePath !== undefined || channel !== undefined) return chromium.launch({ executablePath, channel, ...SCROLLBARS });\n const tried: string[] = [];\n for (const attempt of [{}, { channel: 'chrome' }, { channel: 'msedge' }]) {\n try {\n return await chromium.launch({ ...attempt, ...SCROLLBARS });\n } catch (e) {\n tried.push(\n `${'channel' in attempt ? attempt.channel : \"Playwright's Chromium\"}: ${(e instanceof Error ? e.message : String(e)).split('\\n', 1)[0]}`,\n );\n }\n }\n throw new Error(\n `the rrweb() renderer found no browser to render in (${tried.join('; ')}): run \\`npx playwright install chromium\\`, or pass rrweb({ executablePath })`,\n );\n}\n\n/** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */\nconst bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');\n\n/**\n * The PNG, and where the element is in it. That's measured in the rebuilt page, not taken from the live one: the\n * two can lay out a few pixels apart (a font that loaded differently, a panel's own scroll), and an outline drawn\n * at the live page's box would then cross the element.\n */\nexport async function render(input: unknown, options: BrowserOptions): Promise<{ png: Uint8Array; box?: Box }> {\n const shot = input as Snapshot;\n if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')\n throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');\n const browser = await browserOf(options);\n const context = await browser.newContext({ viewport: shot.window ?? shot.viewport, deviceScaleFactor: shot.scale });\n try {\n const page = await context.newPage();\n const host = new URL('/__deictic/plugins/screenshots/host', shot.url).href;\n await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));\n await page.goto(host);\n await page.addScriptTag({ path: bundle() });\n // The shot, and the attribute that sizes each canvas's picture, which the page's code can't import.\n const given = { ...shot, size: CANVAS_SIZE };\n const found = await page.evaluate(async ({ snapshot, scroll, overlay, element, size, states }) => {\n const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })\n .rrwebSnapshot;\n const mirror = createMirror();\n const { iframe } = rebuildIntoSandboxedIframe(snapshot, {\n root: document.body,\n cache: createCache(),\n mirror,\n iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },\n });\n const doc = iframe.contentDocument;\n if (doc === null) throw new Error('screenshots: the snapshot was rebuilt where it cannot be read');\n // By its kind: the iframe's elements aren't instances of this page's `Element`.\n const isElement = (node: Node | null): node is Element => node?.nodeType === 1;\n // rrweb rebuilds a script as a `noscript` holding SCRIPT_PLACEHOLDER, which the sandbox, running no scripts,\n // shows: hidden, as rrweb's own replayer hides it.\n const hidden = doc.createElement('style');\n hidden.textContent = 'noscript { display: none !important; }';\n doc.head.append(hidden);\n // What was hovered and focused: a copy of the DOM is in no state, so each rule of those pseudo-classes is\n // copied under a class of its own, and the nodes that were in it get the class. Nested rules and grouping ones\n // (a Tailwind `hover:` class is `&:hover { @media (hover: hover) { … } }`) are copied whole.\n if (states !== undefined) {\n const pseudo: [string, string][] = [\n [':focus-visible', 'deictic-focus-visible'],\n [':focus-within', 'deictic-focus-within'],\n [':focus', 'deictic-focus'],\n [':hover', 'deictic-hover'],\n ];\n type Rules = { cssRules: CSSRuleList; insertRule: (rule: string, index: number) => number };\n const copy = (into: Rules) => {\n const list = into.cssRules;\n for (let i = 0; i < list.length; i++) {\n const rule = list[i] as CSSRule & Partial<Rules> & { selectorText?: string };\n if (rule.cssRules !== undefined && rule.insertRule !== undefined) copy(rule as Rules);\n const selector = rule.selectorText;\n if (selector === undefined || !rule.cssText.startsWith(selector)) continue;\n let stated = selector;\n for (const [name, className] of pseudo) stated = stated.split(name).join(`.${className}`);\n if (stated === selector) continue;\n try {\n into.insertRule(stated + rule.cssText.slice(selector.length), i + 1);\n i++;\n } catch {\n // A selector this browser won't take back: that state goes unshown.\n }\n }\n };\n const roots: (Document | ShadowRoot)[] = [doc];\n for (let i = 0; i < roots.length; i++)\n for (const el of roots[i]!.querySelectorAll('*')) if (el.shadowRoot !== null) roots.push(el.shadowRoot);\n for (const root of roots) {\n for (const sheet of [...root.styleSheets, ...root.adoptedStyleSheets]) {\n try {\n copy(sheet);\n } catch {\n // Another origin's, which can't be read: rrweb inlines what it can.\n }\n }\n }\n const classes = {\n hover: 'deictic-hover',\n focus: 'deictic-focus',\n focusVisible: 'deictic-focus-visible',\n focusWithin: 'deictic-focus-within',\n };\n for (const [name, className] of Object.entries(classes)) {\n for (const id of states[name as keyof typeof classes] ?? []) {\n const node = mirror.getNode(id);\n if (isElement(node)) node.classList.add(className);\n }\n }\n }\n // The sandbox runs no scripts, and where scripts don't run, a canvas shows what's inside the canvas instead of\n // what was drawn on the canvas: so each canvas's picture goes inside the canvas, at the size the page laid the\n // canvas out at. rrweb's own drawing of the picture on the canvas never shows.\n for (const canvas of doc.querySelectorAll(`canvas[${size}]`)) {\n const meta = mirror.getMeta(canvas);\n const [box, inline] = (canvas.getAttribute(size) ?? '').split(' ');\n const [width, height] = (box ?? '').split('x');\n if (meta === null || !('attributes' in meta) || typeof meta.attributes.rr_dataURL !== 'string') continue;\n const picture = doc.createElement('img');\n picture.src = meta.attributes.rr_dataURL;\n // In a line as the canvas was, else the whole of the canvas's box.\n picture.style.cssText = `display:${inline === undefined ? 'block' : 'inline'};width:${width}px;height:${height}px`;\n canvas.replaceChildren(picture);\n }\n await doc.fonts.ready;\n await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));\n // At once: a page with `scroll-behavior: smooth` would glide there, and be shot on its way.\n iframe.contentWindow?.scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });\n // rrweb scrolled each element as it built it, before the fonts and images gave its content its height:\n // one that couldn't scroll that far yet is scrolled again now.\n for (const id of mirror.getIds()) {\n const node = mirror.getNode(id);\n const meta = node === null ? null : mirror.getMeta(node);\n if (!isElement(node) || meta === null || !('attributes' in meta)) continue;\n const { rr_scrollTop: top, rr_scrollLeft: left } = meta.attributes;\n if (typeof top !== 'number' && typeof left !== 'number') continue;\n node.scrollTo({\n top: typeof top === 'number' ? top : node.scrollTop,\n left: typeof left === 'number' ? left : node.scrollLeft,\n behavior: 'instant',\n });\n }\n const node = element === undefined ? null : mirror.getNode(element);\n // The iframe fills the page from its top left, so a box in it is one in the shot.\n const rect = isElement(node) ? node.getBoundingClientRect() : undefined;\n const box = rect === undefined ? undefined : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };\n if (overlay === undefined) return box;\n // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.\n const marks = document.createElement('div');\n marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';\n marks.innerHTML = overlay;\n document.body.append(marks);\n return box;\n }, given);\n // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.\n // A shot of the element alone is cut where the element is here.\n const clip = clamp(shot.clip === undefined ? { x: 0, y: 0, ...shot.viewport } : (found ?? shot.clip), shot.viewport);\n const png = new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));\n return { png, ...(found === undefined || shot.clip !== undefined ? {} : { box: found }) };\n } finally {\n await context.close();\n }\n}\n\n/** A box kept within the viewport: an element partly scrolled out of it shows only the part that's in. */\nfunction clamp(box: Box, viewport: { width: number; height: number }): Box | undefined {\n const x = Math.max(0, box.x);\n const y = Math.max(0, box.y);\n const width = Math.min(viewport.width, box.x + box.width) - x;\n const height = Math.min(viewport.height, box.y + box.height) - y;\n return width > 0 && height > 0 ? { x, y, width, height } : undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoDA,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAA8B;;AAGnD,SAAgB,UAAU,SAA2C;CACnE,MAAM,MAAM,KAAK,UAAU,OAAO;CAClC,MAAM,QAAQ,SAAS,IAAI,GAAG;CAC9B,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,MAAM,WAAW,OAAO,OAAO;CAC/B,SAAS,IAAI,KAAK,QAAQ;CAE1B,SAAS,YAAY,SAAS,OAAO,GAAG,CAAC;CACzC,OAAO;AACT;;AAGA,MAAM,aAAa,EAAE,mBAAmB,CAAC,mBAAmB,EAAE;AAE9D,eAAe,OAAO,EAAE,gBAAgB,WAA6C;CACnF,MA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IADO,WAAW,MAAM,KAAK,WAAW;IAAE,MAAM;IAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;GAAG,CAAC,CAC9F;GAAG,GAAI,UAAU,KAAA,KAAa,KAAK,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK,MAAM;EAAG;CAC1F,UAAU;EACR,MAAM,QAAQ,MAAM;CACtB;AACF;;AAGA,SAAS,MAAM,KAAU,UAA8D;CACrF,MAAM,IAAI,KAAK,IAAI,GAAG,IAAI,CAAC;CAC3B,MAAM,IAAI,KAAK,IAAI,GAAG,IAAI,CAAC;CAC3B,MAAM,QAAQ,KAAK,IAAI,SAAS,OAAO,IAAI,IAAI,IAAI,KAAK,IAAI;CAC5D,MAAM,SAAS,KAAK,IAAI,SAAS,QAAQ,IAAI,IAAI,IAAI,MAAM,IAAI;CAC/D,OAAO,QAAQ,KAAK,SAAS,IAAI;EAAE;EAAG;EAAG;EAAO;CAAO,IAAI,KAAA;AAC7D"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { r as definePlugin } from "./src.js";
|
|
2
|
+
// src/plugins/react/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* `deictic/react`: what React's DevTools would show of the element a task is about, attached to the task as
|
|
5
|
+
* `react.json`. The component that wrote the element and the ones that wrote it in turn, each with its props, and
|
|
6
|
+
* its state: a class's, or a function's hooks, named as the code names them where the source says (`count`, not
|
|
7
|
+
* `State`). Read with bippy (an optional peer, imported as a task first asks for it) in development only, as React
|
|
8
|
+
* keeps who wrote an element only there. Each says how often it rendered, how long that took and why, as DevTools'
|
|
9
|
+
* profiler would, counted from React's commits. No tab, and nothing in the page of its own: the tasks plugin asks it, and
|
|
10
|
+
* sends what it answers beside the element's HTML, while the panel's HTML snapshot box is ticked.
|
|
11
|
+
*
|
|
12
|
+
* Values are what the page holds, so they're masked as the network plugin's are, by their names (`token`,
|
|
13
|
+
* `password`, `auth`…, and `mask`'s), and cut where they're deep or long.
|
|
14
|
+
*/
|
|
15
|
+
function reactState(options = {}) {
|
|
16
|
+
return definePlugin({
|
|
17
|
+
name: "react",
|
|
18
|
+
client: "deictic/react/client",
|
|
19
|
+
packages: ["bippy"],
|
|
20
|
+
clientOptions: { ...options }
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
export { reactState as t };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=react.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react.js","names":[],"sources":["../../src/plugins/react/index.ts"],"sourcesContent":["/**\n * `deictic/react`: what React's DevTools would show of the element a task is about, attached to the task as\n * `react.json`. The component that wrote the element and the ones that wrote it in turn, each with its props, and\n * its state: a class's, or a function's hooks, named as the code names them where the source says (`count`, not\n * `State`). Read with bippy (an optional peer, imported as a task first asks for it) in development only, as React\n * keeps who wrote an element only there. Each says how often it rendered, how long that took and why, as DevTools'\n * profiler would, counted from React's commits. No tab, and nothing in the page of its own: the tasks plugin asks it, and\n * sends what it answers beside the element's HTML, while the panel's HTML snapshot box is ticked.\n *\n * Values are what the page holds, so they're masked as the network plugin's are, by their names (`token`,\n * `password`, `auth`…, and `mask`'s), and cut where they're deep or long.\n */\nimport { definePlugin } from '#src/index.ts';\n\nexport interface ReactOptions {\n /** How many components, out from the one that wrote the element: 4 by default. */\n components?: number;\n /** More names whose values are blanked: a part of the name, in any case. */\n mask?: string[];\n /**\n * Whether hooks are named as the code names them, read off the source and its map (fetched from the dev server, as\n * DevTools does): true by default. Without, each is its kind alone, `State` or `Memo`, in the order they're called.\n */\n names?: boolean;\n /**\n * Whether each component's renders are counted, timed and explained, from React's commits as DevTools' hook hears\n * them: true by default. That hook is React Refresh's, in development; without one there's nothing to count.\n */\n renders?: boolean;\n}\n\n/** What JSON holds of a value: anything it can't hold says what it was, in brackets (`[function onClick]`). */\nexport type Value = null | boolean | number | string | Value[] | { [key: string]: Value };\n\n/** A hook as DevTools lists it. */\nexport interface Hook {\n /** Its kind: `State`, `Memo`, `Context`, or a custom hook's name less `use` (`Auth`), whose `hooks` it called. */\n hook: string;\n /** What the code calls it: `const [count, setCount] = useState(0)` is `count`. */\n as?: string;\n value?: Value;\n hooks?: Hook[];\n}\n\n/** A component's renders, counted from when the page started deictic, not from its first. */\nexport interface Renders {\n count: number;\n /** In the 10 seconds before the task: a loop, or a burst on each keystroke. */\n recent: number;\n /** How long ago it last rendered, in milliseconds. */\n lastAgo: number;\n /** How long its last render took, with what it rendered, in milliseconds: where React times them. */\n lastMs?: number;\n /** Its own part of it. */\n selfMs?: number;\n /** Why it last rendered: `mounted`, `props changed: chosen`, `state changed`, `context changed`, `its parent rendered`. */\n why: string;\n}\n\n/** A component that rendered in a recording's commit, once for each time it did in the entry. */\nexport interface Rendered {\n name: string;\n /** Where its JSX has the first element it wrote, `src/Plan.tsx:12`, where it wrote one. */\n at?: string;\n /** How many times it rendered in the entry, where that's more than once. */\n count?: number;\n /** How long it took, with what it rendered, in milliseconds, all its renders in the entry together. */\n ms?: number;\n /** Its own part of it. */\n selfMs?: number;\n /** Why it last rendered, as `Renders.why`. */\n why: string;\n}\n\n/**\n * A recording's entry of React's commits, `deictic.react` events: commits a frame apart, as one, with the components\n * they rendered, the slowest first. `{ on: boolean }` events say where the recording starts and stops having them.\n */\nexport interface Commit {\n /** How many commits it is. */\n commits: number;\n /** How long rendering them took, in milliseconds, where React times it. */\n ms?: number;\n /** Of several, the slowest one's, in milliseconds: one past a frame is what makes a page stutter. */\n slowest?: number;\n /**\n * The rest of a busy second, past ten entries in it: how long it spans, in milliseconds, up to this entry's\n * moment. A page that renders without stop is ten entries and this one a second.\n */\n over?: number;\n /** React's scheduler priority for the last: `immediate` (a click, a key), `user-blocking`, `normal`, `low`, `idle`. */\n priority?: string;\n /** Twenty at most. */\n components: Rendered[];\n /** How many more components rendered than it names. */\n more?: number;\n}\n\n/** A component that wrote the element, or wrote one that did. */\nexport interface Component {\n name: string;\n /** Where its JSX has the nearest element around this one, `src/Plan.tsx:12`: none for one that only passed it on. */\n at?: string;\n /** A server component: React kept its name, and nothing of it is in the page. */\n server?: true;\n props?: Value;\n /** A class component's state. */\n state?: Value;\n /** A function component's hooks, in the order it calls them, effects left out. */\n hooks?: Hook[];\n renders?: Renders;\n /** Why what's missing is. */\n problem?: string;\n}\n\n/** `react.json`: the component that wrote the element first, then the one that wrote it, and on out. */\nexport interface Snapshot {\n components: Component[];\n}\n\nexport function reactState(options: ReactOptions = {}) {\n return definePlugin<never, never>({\n name: 'react',\n client: 'deictic/react/client',\n packages: ['bippy'],\n clientOptions: { ...options },\n });\n}\n\nexport default reactState;\n"],"mappings":";;;;;;;;;;;;;;AAwHA,SAAgB,WAAW,UAAwB,CAAC,GAAG;CACrD,OAAO,aAA2B;EAChC,MAAM;EACN,QAAQ;EACR,UAAU,CAAC,OAAO;EAClB,eAAe,EAAE,GAAG,QAAQ;CAC9B,CAAC;AACH"}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { t as annotations } from "./annotations.js";
|
|
2
2
|
import { t as logs } from "./logs.js";
|
|
3
3
|
import { t as network } from "./network.js";
|
|
4
|
+
import { t as reactState } from "./react.js";
|
|
4
5
|
import { t as recordings } from "./recordings.js";
|
|
5
6
|
import { r as screenshots } from "./screenshots.js";
|
|
6
7
|
import { t as tasks } from "./tasks.js";
|
|
7
8
|
import { t as voice } from "./voice.js";
|
|
9
|
+
import { r as installed } from "./packages.js";
|
|
8
10
|
// src/plugins/recommended/index.ts
|
|
9
11
|
/**
|
|
10
12
|
* Tasks, screenshots, annotations, recordings and voice, in that order, the order of their tabs, then what a
|
|
11
|
-
* recording has besides the page: logs and network.
|
|
13
|
+
* recording has besides the page: logs and network, and React's state where the project has React.
|
|
12
14
|
*/
|
|
13
|
-
function
|
|
15
|
+
function deicticRecommended(options = {}) {
|
|
14
16
|
const plugins = [];
|
|
15
17
|
if (options.tasks !== false) plugins.push(tasks(options.tasks));
|
|
16
18
|
if (options.screenshots !== false) plugins.push(screenshots(options.screenshots));
|
|
@@ -19,8 +21,9 @@ function recommended(options = {}) {
|
|
|
19
21
|
if (options.voice !== false) plugins.push(voice(options.voice));
|
|
20
22
|
if (options.recordings !== false && options.logs !== false) plugins.push(logs(options.logs));
|
|
21
23
|
if (options.recordings !== false && options.network !== false) plugins.push(network(options.network));
|
|
24
|
+
if (options.react !== false && (options.react !== void 0 || installed(process.cwd(), "react"))) plugins.push(reactState(options.react));
|
|
22
25
|
return plugins;
|
|
23
26
|
}
|
|
24
|
-
export {
|
|
27
|
+
export { deicticRecommended as t };
|
|
25
28
|
|
|
26
29
|
//# sourceMappingURL=recommended.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recommended.js","names":[],"sources":["../../src/plugins/recommended/index.ts"],"sourcesContent":["/**\n * `deictic/recommended`: the plugins for describing a change rather than making it. Alt-click an element, say what\n * should change, attach a screenshot to draw on, a screen recording or your voice, and it goes to a Vercel Board.\n * A recording has the page's console and its requests in it too.\n *\n * Only the server halves, as every factory is: each names its page half, which the integration imports. A plugin\n * outside the preset (Tailwind, your own) goes beside it: `plugins: [...
|
|
1
|
+
{"version":3,"file":"recommended.js","names":[],"sources":["../../src/plugins/recommended/index.ts"],"sourcesContent":["/**\n * `deictic/recommended`: the plugins for describing a change rather than making it. Alt-click an element, say what\n * should change, attach a screenshot to draw on, a screen recording or your voice, and it goes to a Vercel Board.\n * A recording has the page's console and its requests in it too, and in a React project a task has the props and\n * state of the components that wrote its element.\n *\n * Only the server halves, as every factory is: each names its page half, which the integration imports. A plugin\n * outside the preset (Tailwind, your own) goes beside it: `plugins: [...deicticRecommended(), tailwind()]`. Named for\n * deictic, as a config imports other presets called `recommended`.\n */\nimport type { ServerPlugin } from '#src/index.ts';\nimport { annotations, type AnnotationsOptions } from '#src/plugins/annotations/index.ts';\nimport { logs, type LogsOptions } from '#src/plugins/logs/index.ts';\nimport { network, type NetworkOptions } from '#src/plugins/network/index.ts';\nimport { type ReactOptions, reactState } from '#src/plugins/react/index.ts';\nimport { recordings, type RecordingsOptions } from '#src/plugins/recordings/index.ts';\nimport { screenshots, type ScreenshotsOptions } from '#src/plugins/screenshots/index.ts';\nimport { tasks, type TasksOptions } from '#src/plugins/tasks/index.ts';\nimport { voice, type VoiceOptions } from '#src/plugins/voice/index.ts';\nimport { installed } from '#src/tools/packages.ts';\n\n/** Each plugin's options, by its name, or `false` to leave it out. */\nexport interface RecommendedOptions {\n tasks?: TasksOptions | false;\n screenshots?: ScreenshotsOptions | false;\n annotations?: AnnotationsOptions | false;\n recordings?: RecordingsOptions | false;\n voice?: VoiceOptions | false;\n /** The console's lines in a recording. */\n logs?: LogsOptions | false;\n /** The page's requests in a recording, masked. */\n network?: NetworkOptions | false;\n /**\n * The props, state and hooks of the components that wrote a task's element: where the project has React (found from\n * the working directory, where the dev server starts), unless it's `false`.\n */\n react?: ReactOptions | false;\n}\n\n/**\n * Tasks, screenshots, annotations, recordings and voice, in that order, the order of their tabs, then what a\n * recording has besides the page: logs and network, and React's state where the project has React.\n */\nexport function deicticRecommended(options: RecommendedOptions = {}): ServerPlugin[] {\n const plugins: ServerPlugin[] = [];\n if (options.tasks !== false) plugins.push(tasks(options.tasks));\n if (options.screenshots !== false) plugins.push(screenshots(options.screenshots));\n if (options.annotations !== false) plugins.push(annotations(options.annotations));\n if (options.recordings !== false) plugins.push(recordings(options.recordings));\n if (options.voice !== false) plugins.push(voice(options.voice));\n // Nothing without recordings to be in.\n if (options.recordings !== false && options.logs !== false) plugins.push(logs(options.logs));\n if (options.recordings !== false && options.network !== false) plugins.push(network(options.network));\n // Its page half reads React's fibers: nothing to read without React, and bippy to install for nothing.\n if (options.react !== false && (options.react !== undefined || installed(process.cwd(), 'react')))\n plugins.push(reactState(options.react));\n return plugins;\n}\n\nexport default deicticRecommended;\n"],"mappings":";;;;;;;;;;;;;;AA2CA,SAAgB,mBAAmB,UAA8B,CAAC,GAAmB;CACnF,MAAM,UAA0B,CAAC;CACjC,IAAI,QAAQ,UAAU,OAAO,QAAQ,KAAK,MAAM,QAAQ,KAAK,CAAC;CAC9D,IAAI,QAAQ,gBAAgB,OAAO,QAAQ,KAAK,YAAY,QAAQ,WAAW,CAAC;CAChF,IAAI,QAAQ,gBAAgB,OAAO,QAAQ,KAAK,YAAY,QAAQ,WAAW,CAAC;CAChF,IAAI,QAAQ,eAAe,OAAO,QAAQ,KAAK,WAAW,QAAQ,UAAU,CAAC;CAC7E,IAAI,QAAQ,UAAU,OAAO,QAAQ,KAAK,MAAM,QAAQ,KAAK,CAAC;CAE9D,IAAI,QAAQ,eAAe,SAAS,QAAQ,SAAS,OAAO,QAAQ,KAAK,KAAK,QAAQ,IAAI,CAAC;CAC3F,IAAI,QAAQ,eAAe,SAAS,QAAQ,YAAY,OAAO,QAAQ,KAAK,QAAQ,QAAQ,OAAO,CAAC;CAEpG,IAAI,QAAQ,UAAU,UAAU,QAAQ,UAAU,KAAA,KAAa,UAAU,QAAQ,IAAI,GAAG,OAAO,IAC7F,QAAQ,KAAK,WAAW,QAAQ,KAAK,CAAC;CACxC,OAAO;AACT"}
|
package/dist/shared/recording.js
CHANGED
|
@@ -1,13 +1,64 @@
|
|
|
1
1
|
import { relative } from "node:path";
|
|
2
|
+
import "./marks.js";
|
|
2
3
|
import { a as clock, l as fail, t as ME } from "./board.js";
|
|
3
4
|
import { r as loadRecording } from "./find.js";
|
|
4
5
|
// src/cli/recording.ts
|
|
5
6
|
/**
|
|
6
7
|
* `deictic recording`: a recording as a timeline: the page, each click and field typed in (with the element's place
|
|
7
8
|
* in the source), scrolls, resizes, each change to the marks (what was drawn, where, and the notes' text), the voice
|
|
8
|
-
* clips, the page's console and its requests where the project records them,
|
|
9
|
-
*
|
|
9
|
+
* clips, the page's console and its requests where the project records them, React's commits where the recording had
|
|
10
|
+
* them on, and the end. Or the part of it asked
|
|
11
|
+
* for: `--only`, `--problems`, `--from`, `--to`, `--around`, `--grep`, `--all`, and `--full` for all of each line.
|
|
12
|
+
*
|
|
13
|
+
* Asked for nothing, it's what the person did and what went wrong: the page's requests, its console's lines and
|
|
14
|
+
* React's commits, which a dev server makes hundreds of, are left out where they're not a problem, and counted at
|
|
15
|
+
* the end with what lists them. An agent asks for them where the task needs them. `--json` has every line.
|
|
10
16
|
*/
|
|
17
|
+
/**
|
|
18
|
+
* The kinds left out of a timeline asked for nothing in particular, where a line of them isn't a problem: a dev
|
|
19
|
+
* server's page makes hundreds of requests (its modules, its hot updates), logs what its tools do, and commits
|
|
20
|
+
* React each frame it animates. Counted, with what lists them.
|
|
21
|
+
*/
|
|
22
|
+
const QUIET = [
|
|
23
|
+
{
|
|
24
|
+
kind: "request",
|
|
25
|
+
noun: "request"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
kind: "console",
|
|
29
|
+
noun: "console line"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
kind: "react",
|
|
33
|
+
noun: "React line"
|
|
34
|
+
}
|
|
35
|
+
];
|
|
36
|
+
/** A commit past this took longer than a frame: a problem, as it's what makes a page stutter. */
|
|
37
|
+
const FRAME = 16;
|
|
38
|
+
const ms = (n) => `${n < 10 ? n.toFixed(1) : round(n)}ms`;
|
|
39
|
+
/** A React commit entry, as a line: how long, why it ran, and what rendered, the slowest first. */
|
|
40
|
+
function commitLine(c) {
|
|
41
|
+
const components = c.components ?? [];
|
|
42
|
+
const many = (c.commits ?? 1) > 1;
|
|
43
|
+
const head = [
|
|
44
|
+
c.priority,
|
|
45
|
+
many ? `${c.commits} commits${c.over === void 0 ? "" : ` over ${(c.over / 1e3).toFixed(1)}s`}` : void 0,
|
|
46
|
+
c.slowest === void 0 ? void 0 : `slowest ${ms(c.slowest)}`
|
|
47
|
+
].filter(Boolean).join(", ");
|
|
48
|
+
const slow = c.slowest ?? c.ms;
|
|
49
|
+
const named = components.map((r) => `${r.name}${(r.count ?? 1) > 1 ? ` ×${r.count}` : ""}${r.selfMs === void 0 ? "" : ` ${ms(r.selfMs)}`} (${r.why})`);
|
|
50
|
+
const rest = c.more === void 0 ? "" : named.length === 0 ? `${c.more} components` : `, and ${c.more} more`;
|
|
51
|
+
return {
|
|
52
|
+
text: `${c.ms === void 0 ? "commit" : ms(c.ms)}${head === "" ? "" : ` (${head})`}: ${named.join(", ")}${rest}`,
|
|
53
|
+
details: components.map((r) => [
|
|
54
|
+
`${r.name}${(r.count ?? 1) > 1 ? ` ×${r.count}` : ""}`,
|
|
55
|
+
r.at,
|
|
56
|
+
r.ms === void 0 ? void 0 : `${ms(r.ms)} with what it rendered`,
|
|
57
|
+
r.why
|
|
58
|
+
].filter(Boolean).join(" · ")),
|
|
59
|
+
...slow !== void 0 && slow > FRAME ? { problem: true } : {}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
11
62
|
const round = Math.round;
|
|
12
63
|
/** The marks, as data where the recording has it. */
|
|
13
64
|
function shapeOf({ shape }) {
|
|
@@ -185,6 +236,10 @@ function timelineOf(events, voice) {
|
|
|
185
236
|
...payload.isInitial === true ? { before: "made as the page loaded, before this moment" } : {}
|
|
186
237
|
});
|
|
187
238
|
}
|
|
239
|
+
if (e.type === 5 && d.tag === "deictic.react") {
|
|
240
|
+
if (payload.on !== void 0) push(t, "react", payload.on ? "commits recorded from here" : "commits no longer recorded");
|
|
241
|
+
else push(t, "react", "", commitLine(payload));
|
|
242
|
+
}
|
|
188
243
|
if (e.type === 5 && d.tag === "deictic.end") push(t, "end", "recording stopped");
|
|
189
244
|
if (e.type !== 3) continue;
|
|
190
245
|
if (d.source === 0) {
|
|
@@ -272,7 +327,22 @@ async function run(named, values) {
|
|
|
272
327
|
const only = (values.only ?? []).flatMap((list) => list.split(",")).filter(Boolean);
|
|
273
328
|
const grep = values.grep?.toLowerCase();
|
|
274
329
|
const isKind = (kind, asked) => kind === asked || kind.startsWith(`${asked}.`) || kind.endsWith(`-${asked}`);
|
|
330
|
+
const whole = values.all === true || only.length > 0 || from !== void 0 || to !== void 0 || grep !== void 0;
|
|
331
|
+
const left = /* @__PURE__ */ new Map();
|
|
332
|
+
const listed = (e) => {
|
|
333
|
+
if (whole || e.problem === true) return true;
|
|
334
|
+
const quiet = QUIET.find((q) => isKind(e.kind, q.kind));
|
|
335
|
+
if (quiet === void 0) return true;
|
|
336
|
+
const held = left.get(quiet.kind) ?? {
|
|
337
|
+
count: 0,
|
|
338
|
+
noun: quiet.noun
|
|
339
|
+
};
|
|
340
|
+
held.count++;
|
|
341
|
+
left.set(quiet.kind, held);
|
|
342
|
+
return false;
|
|
343
|
+
};
|
|
275
344
|
const shown = timeline.filter((e) => (only.length === 0 || only.some((asked) => isKind(e.kind, asked))) && (values.problems !== true || e.problem === true) && (from === void 0 || e.t >= from) && (to === void 0 || e.t <= to) && (grep === void 0 || `${e.kind} ${e.text}`.toLowerCase().includes(grep)));
|
|
345
|
+
const listing = values.json === true ? shown : shown.filter(listed);
|
|
276
346
|
const colorScheme = kept.colorScheme ?? "light";
|
|
277
347
|
const startedAt = new Date(kept.startedAt ?? events[0].timestamp).toISOString();
|
|
278
348
|
if (values.json) {
|
|
@@ -297,12 +367,14 @@ async function run(named, values) {
|
|
|
297
367
|
console.log(`viewport ${kept.viewport.width}×${kept.viewport.height}, ${colorScheme}, started ${startedAt}`);
|
|
298
368
|
if (replay !== void 0) console.log(`replays at ${replay} (add ?t=<seconds> to open it paused there)`);
|
|
299
369
|
if (shown.length < timeline.length) console.log(`${shown.length} of its ${timeline.length} lines, as asked`);
|
|
370
|
+
else if (listing.length < shown.length) console.log(`${listing.length} of its ${timeline.length} lines: what the person did, and what went wrong`);
|
|
300
371
|
console.log();
|
|
301
372
|
const short = shortener(kept.page);
|
|
302
373
|
const under = (line) => console.log(`${" ".repeat(22)}${short(line)}`);
|
|
303
|
-
for (const e of
|
|
374
|
+
for (const e of listing) {
|
|
304
375
|
console.log(`${e.at.padStart(6)} ${e.kind.padEnd(13)} ${short(e.text)}`);
|
|
305
376
|
if (e.trace && (values.full === true || e.problem === true)) for (const line of values.full ? e.trace : e.trace.slice(0, 5)) under(`at ${line}`);
|
|
377
|
+
if (values.full === true) for (const line of e.details ?? []) under(line);
|
|
306
378
|
if (values.full !== true || e.request === void 0) continue;
|
|
307
379
|
const r = e.request;
|
|
308
380
|
if (e.before !== void 0) under(e.before);
|
|
@@ -311,6 +383,11 @@ async function run(named, values) {
|
|
|
311
383
|
if (r.responseBody !== void 0) under(`response body ${r.responseBody}`);
|
|
312
384
|
}
|
|
313
385
|
if (shown.length === 0) console.log(timeline.length === 0 ? "Nothing in it." : "No line of it is what was asked for.");
|
|
386
|
+
if (left.size > 0) {
|
|
387
|
+
const counted = [...left.entries()].map(([kind, { count, noun }]) => `${count} ${noun}${count === 1 ? "" : "s"} (--only ${kind})`);
|
|
388
|
+
console.log(`
|
|
389
|
+
Not listed: ${counted.join(", ")}; --all lists every line, --around <seconds> every line of a moment.`);
|
|
390
|
+
}
|
|
314
391
|
const problems = timeline.filter((e) => e.problem === true).length;
|
|
315
392
|
if (problems === 0 || shown.length < timeline.length) return;
|
|
316
393
|
const ref = task?.id ?? id;
|