-
Notifications
You must be signed in to change notification settings - Fork 2
feat: add browser routing cache #99
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 4 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
94228be
feat: add browser-scoped session client
rgarcia ae9a739
fix: require base_url for browser-scoped routing
rgarcia d835f69
fix: enforce browser base_url routing
rgarcia e730af8
feat: generate browser-scoped session bindings
rgarcia 2f12277
refactor: replace browser-scoped client with browser routing cache
rgarcia 2082705
refactor: simplify browser routing cache
rgarcia 7030d96
refactor: rename browser routing subresources config
rgarcia 0d9ddce
docs: restore raw http example in browser routing demo
rgarcia b09434e
feat: restore node browser fetch helper
rgarcia 2f16386
fix: drop node browser routing branch churn
rgarcia 7a56ab6
fix: clean up node browser routing lint drift
rgarcia fdd3adf
fix: simplify node browser routing helpers
rgarcia 00c91ef
refactor: move node browser routing rollout to env
rgarcia 9b24280
fix: preserve browser routing fetch options
rgarcia 0e0e88f
fix: limit browser route cache sniffing
rgarcia 2d0056e
fix: evict deleted browser routes
rgarcia a76f7ae
fix: keep browser routing helpers out of generated code
rgarcia a7ff9bc
fix: restore generated types formatting
rgarcia 81e47ca
fix: handle browser pool route cache updates
rgarcia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| /** | ||
| * Browser-scoped client: call browser VM-routed browser APIs without repeating the | ||
| * session id, and run `fetch`-style HTTP through the browser network stack. | ||
| * | ||
| * Run after `yarn build` so `dist/` matches sources, or import from `src/` via | ||
| * ts-node with path aliases. | ||
| */ | ||
| import Kernel from '@onkernel/sdk'; | ||
|
|
||
| async function main() { | ||
| const kernel = new Kernel(); | ||
|
|
||
| const created = await kernel.browsers.create({}); | ||
| const browser = kernel.forBrowser(created); | ||
|
|
||
| await browser.computer.clickMouse({ x: 10, y: 10 }); | ||
|
|
||
| const page = await browser.fetch('https://example.com', { method: 'GET' }); | ||
| console.log('status', page.status); | ||
|
|
||
| await kernel.browsers.deleteByID(created.session_id); | ||
| } | ||
|
|
||
| void main(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,332 @@ | ||
| #!/usr/bin/env -S node | ||
|
|
||
| import fs from 'fs'; | ||
| import path from 'path'; | ||
| import { | ||
| Node, | ||
| Project, | ||
| SyntaxKind, | ||
| type MethodDeclaration, | ||
| type ParameterDeclaration, | ||
| type PropertyDeclaration, | ||
| } from 'ts-morph'; | ||
|
|
||
| type ChildMeta = { | ||
| propName: string; | ||
| targetClass: string; | ||
| }; | ||
|
|
||
| type MethodMeta = { | ||
| name: string; | ||
| signature: string; | ||
| returnType: string; | ||
| implArgs: string; | ||
| }; | ||
|
|
||
| type ResourceMeta = { | ||
| className: string; | ||
| filePath: string; | ||
| importPath: string; | ||
| alias: string; | ||
| exportedTypeNames: Set<string>; | ||
| children: ChildMeta[]; | ||
| methods: MethodMeta[]; | ||
| }; | ||
|
|
||
| const repoRoot = path.resolve(__dirname, '..'); | ||
| const resourcesDir = path.join(repoRoot, 'src', 'resources', 'browsers'); | ||
| const outputFile = path.join(repoRoot, 'src', 'lib', 'generated', 'browser-session-bindings.ts'); | ||
|
|
||
| const project = new Project({ | ||
| skipAddingFilesFromTsConfig: true, | ||
| }); | ||
|
|
||
| project.addSourceFilesAtPaths(path.join(resourcesDir, '**/*.ts')); | ||
|
|
||
| const sourceFiles = project | ||
| .getSourceFiles() | ||
| .filter((sf) => !sf.getBaseName().endsWith('.test.ts') && sf.getBaseName() !== 'index.ts'); | ||
|
|
||
| const resourceByClass = new Map<string, ResourceMeta>(); | ||
|
|
||
| for (const sf of sourceFiles) { | ||
| for (const classDecl of sf.getClasses()) { | ||
| if (classDecl.getName() == null) continue; | ||
| if (!extendsAPIResource(classDecl)) continue; | ||
|
|
||
| const className = classDecl.getNameOrThrow(); | ||
| const importPath = toImportPath(path.relative(path.dirname(outputFile), sf.getFilePath())); | ||
| const alias = `${className}API`; | ||
| const exportedTypeNames = new Set<string>( | ||
| sf | ||
| .getStatements() | ||
| .filter( | ||
| (stmt) => | ||
| Node.isInterfaceDeclaration(stmt) || | ||
| Node.isTypeAliasDeclaration(stmt) || | ||
| Node.isEnumDeclaration(stmt), | ||
| ) | ||
| .map((stmt) => { | ||
| if ( | ||
| Node.isInterfaceDeclaration(stmt) || | ||
| Node.isTypeAliasDeclaration(stmt) || | ||
| Node.isEnumDeclaration(stmt) | ||
| ) { | ||
| return stmt.getName(); | ||
| } | ||
| return ''; | ||
| }) | ||
| .filter(Boolean), | ||
| ); | ||
|
|
||
| const meta: ResourceMeta = { | ||
| className, | ||
| filePath: sf.getFilePath(), | ||
| importPath, | ||
| alias, | ||
| exportedTypeNames, | ||
| children: extractChildren(classDecl), | ||
| methods: [], | ||
| }; | ||
| resourceByClass.set(className, meta); | ||
| } | ||
| } | ||
|
|
||
| for (const sf of sourceFiles) { | ||
| for (const classDecl of sf.getClasses()) { | ||
| const className = classDecl.getName(); | ||
| if (!className) continue; | ||
| const meta = resourceByClass.get(className); | ||
| if (!meta) continue; | ||
|
|
||
| for (const method of classDecl.getMethods()) { | ||
| const parsed = parseMethod(meta, method); | ||
| if (parsed) meta.methods.push(parsed); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const browserMeta = resourceByClass.get('Browsers'); | ||
| if (!browserMeta) { | ||
| throw new Error('Could not find Browsers resource'); | ||
| } | ||
|
|
||
| const ordered = orderResources(browserMeta, resourceByClass); | ||
| const importLines = ordered | ||
| .map((meta) => `import type * as ${meta.alias} from '${meta.importPath}';`) | ||
| .join('\n'); | ||
|
|
||
| const interfaces = ordered.map((meta) => emitInterface(meta, resourceByClass)).join('\n\n'); | ||
|
|
||
| const constructorAssignments = browserMeta.children | ||
| .map((child) => emitAssignment(child, resourceByClass)) | ||
| .join('\n '); | ||
|
|
||
| const rootMethods = browserMeta.methods.map((method) => emitMethod(method, 'browsers')).join('\n\n'); | ||
|
|
||
| const output = `// This file is generated by scripts/generate-browser-session.ts.\n// Do not edit by hand.\n\nimport type { Kernel } from '../../client';\nimport type { APIPromise } from '../../core/api-promise';\nimport type { RequestOptions } from '../../internal/request-options';\nimport type { Stream } from '../../core/streaming';\nimport type * as Shared from '../../resources/shared';\n${importLines}\n\n${interfaces}\n\nexport class GeneratedBrowserSessionBindings {\n protected readonly sessionClient: Kernel;\n readonly sessionId: string;\n\n readonly ${browserMeta.children | ||
| .map((child) => `${child.propName}: ${bindingName(child.targetClass)}`) | ||
| .join( | ||
| '\n readonly ', | ||
| )};\n\n constructor(sessionClient: Kernel, sessionId: string) {\n this.sessionClient = sessionClient;\n this.sessionId = sessionId;\n ${constructorAssignments}\n }\n\n protected opt(options?: RequestOptions): RequestOptions | undefined {\n return options;\n }\n\n${indent( | ||
| rootMethods, | ||
| 2, | ||
| )}\n}\n`; | ||
|
|
||
| fs.mkdirSync(path.dirname(outputFile), { recursive: true }); | ||
| fs.writeFileSync(outputFile, output); | ||
|
|
||
| function extendsAPIResource(classDecl: import('ts-morph').ClassDeclaration): boolean { | ||
| const ext = classDecl.getExtends(); | ||
| if (!ext) return false; | ||
| const text = ext.getExpression().getText(); | ||
| return text === 'APIResource'; | ||
| } | ||
|
|
||
| function extractChildren(classDecl: import('ts-morph').ClassDeclaration): ChildMeta[] { | ||
| return classDecl | ||
| .getProperties() | ||
| .filter((prop) => !prop.getName().startsWith('with_')) | ||
| .map((prop) => { | ||
| const targetClass = childClassName(prop); | ||
| if (!targetClass) return null; | ||
| return { propName: prop.getName(), targetClass }; | ||
| }) | ||
| .filter((v): v is ChildMeta => v !== null); | ||
| } | ||
|
|
||
| function childClassName(prop: PropertyDeclaration): string | null { | ||
| const init = prop.getInitializer(); | ||
| if (!init || !Node.isNewExpression(init)) return null; | ||
| const expr = init.getExpression().getText(); | ||
| const last = expr.split('.').pop() || expr; | ||
| return last; | ||
| } | ||
|
|
||
| function parseMethod(meta: ResourceMeta, method: MethodDeclaration): MethodMeta | null { | ||
| if (!isPublicMethod(method)) return null; | ||
| const pathText = getPathTemplate(method); | ||
| if (!pathText) return null; | ||
| if (meta.className === 'Browsers' && !pathText.includes('/browsers/${id}/')) return null; | ||
|
|
||
| const params = method.getParameters(); | ||
| const idParam = params[0]?.getName() === 'id' ? params[0] : undefined; | ||
| const paramsIdName = detectParamsIdParam(method); | ||
| if (!idParam && !paramsIdName) return null; | ||
|
|
||
| const publicParams = params | ||
| .filter((param) => param !== idParam) | ||
| .map((param) => formatParam(meta, param, paramsIdName, true)) | ||
| .join(', '); | ||
|
|
||
| const implArgs = params | ||
| .map((param) => { | ||
| const name = param.getName(); | ||
| if (param === idParam) return 'this.sessionId'; | ||
| if (paramsIdName && name === paramsIdName) return `{ ...${name}, id: this.sessionId }`; | ||
| if (name === 'options') return 'this.opt(options)'; | ||
| return name; | ||
| }) | ||
| .join(', '); | ||
|
|
||
| return { | ||
| name: method.getName(), | ||
| signature: publicParams, | ||
| returnType: rewriteType(meta, method.getReturnTypeNodeOrThrow().getText()), | ||
| implArgs, | ||
| }; | ||
| } | ||
|
|
||
| function isPublicMethod(method: MethodDeclaration): boolean { | ||
| const name = method.getName(); | ||
| if (name.startsWith('_')) return false; | ||
| if (method.isStatic()) return false; | ||
| return true; | ||
| } | ||
|
|
||
| function getPathTemplate(method: MethodDeclaration): string | null { | ||
| const tag = method | ||
| .getDescendantsOfKind(SyntaxKind.TaggedTemplateExpression) | ||
| .find((node) => node.getTag().getText() === 'path'); | ||
| return tag?.getTemplate().getText() ?? null; | ||
| } | ||
|
|
||
| function detectParamsIdParam(method: MethodDeclaration): string | null { | ||
| const body = method.getBodyText() ?? ''; | ||
| const match = body.match(/const\s+\{\s*id(?:\s*,\s*\.\.\.\w+)?\s*\}\s*=\s*(\w+)/); | ||
| return match?.[1] ?? null; | ||
| } | ||
|
|
||
| function formatParam( | ||
| meta: ResourceMeta, | ||
| param: ParameterDeclaration, | ||
| paramsIdName: string | null, | ||
| includeInitializer: boolean, | ||
| ): string { | ||
| const name = param.getName(); | ||
| let typeText = param.getTypeNodeOrThrow().getText(); | ||
| typeText = rewriteType(meta, typeText); | ||
| if (paramsIdName && name === paramsIdName) { | ||
| typeText = `Omit<${typeText}, 'id'>`; | ||
| } | ||
| const initializer = includeInitializer ? param.getInitializer()?.getText() : undefined; | ||
| const question = param.hasQuestionToken() ? '?' : ''; | ||
| return `${name}${question}: ${typeText}${initializer ? ` = ${initializer}` : ''}`; | ||
| } | ||
|
|
||
| function rewriteType(meta: ResourceMeta, text: string): string { | ||
| let out = text; | ||
| const typeNames = Array.from(meta.exportedTypeNames).sort((a, b) => b.length - a.length); | ||
| for (const name of typeNames) { | ||
| out = out.replace(new RegExp(`\\b${name}\\b`, 'g'), `${meta.alias}.${name}`); | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| function orderResources(root: ResourceMeta, all: Map<string, ResourceMeta>): ResourceMeta[] { | ||
| const out: ResourceMeta[] = []; | ||
| const seen = new Set<string>(); | ||
| const visit = (meta: ResourceMeta) => { | ||
| if (seen.has(meta.className)) return; | ||
| seen.add(meta.className); | ||
| for (const child of meta.children) { | ||
| const childMeta = all.get(child.targetClass); | ||
| if (childMeta) visit(childMeta); | ||
| } | ||
| out.push(meta); | ||
| }; | ||
| visit(root); | ||
| return out.filter((meta) => meta.className !== 'Browsers').concat(root); | ||
| } | ||
|
|
||
| function emitInterface(meta: ResourceMeta, all: Map<string, ResourceMeta>): string { | ||
| const lines: string[] = []; | ||
| for (const method of meta.methods) { | ||
| const noInitSignature = method.signature.replace(/\s*=\s*[^,)+]+/g, ''); | ||
| lines.push(` ${method.name}(${noInitSignature}): ${method.returnType};`); | ||
| } | ||
| for (const child of meta.children) { | ||
| if (all.has(child.targetClass)) { | ||
| lines.push(` ${child.propName}: ${bindingName(child.targetClass)};`); | ||
| } | ||
| } | ||
| return `export interface ${bindingName(meta.className)} {\n${lines.join('\n')}\n}`; | ||
| } | ||
|
|
||
| function bindingName(className: string): string { | ||
| return `BrowserSession${className}Bindings`; | ||
| } | ||
|
|
||
| function emitAssignment(child: ChildMeta, all: Map<string, ResourceMeta>): string { | ||
| const meta = all.get(child.targetClass)!; | ||
| const methodLines = meta.methods.map((method) => { | ||
| return `${method.name}: (${method.signature}) => this.sessionClient.browsers.${resourceCallPath( | ||
| meta.filePath, | ||
| )}.${method.name}(${method.implArgs}),`; | ||
| }); | ||
| const childLines = meta.children.map((nested) => emitNestedObject(nested, all)); | ||
| return `this.${child.propName} = {\n ${[...methodLines, ...childLines].join('\n ')}\n };`; | ||
| } | ||
|
|
||
| function emitNestedObject(child: ChildMeta, all: Map<string, ResourceMeta>): string { | ||
| const meta = all.get(child.targetClass)!; | ||
| const methodLines = meta.methods.map((method) => { | ||
| return `${method.name}: (${method.signature}) => this.sessionClient.browsers.${resourceCallPath( | ||
| meta.filePath, | ||
| )}.${method.name}(${method.implArgs}),`; | ||
| }); | ||
| const nestedLines = meta.children.map((nested) => emitNestedObject(nested, all)); | ||
| return `${child.propName}: {\n ${[...methodLines, ...nestedLines].join('\n ')}\n },`; | ||
| } | ||
|
|
||
| function resourceCallPath(filePath: string): string { | ||
| const rel = path.relative(resourcesDir, filePath).replace(/\\/g, '/').replace(/\.ts$/, ''); | ||
| const segments = rel.split('/'); | ||
| if (segments[segments.length - 1] === 'fs') { | ||
| return 'fs'; | ||
| } | ||
| if (segments[0] === 'fs') { | ||
| return ['fs', ...segments.slice(1)].join('.'); | ||
| } | ||
| if (segments[0] === 'browsers') { | ||
| return segments.slice(1).join('.'); | ||
| } | ||
| return segments.join('.'); | ||
| } | ||
|
|
||
| function emitMethod(method: MethodMeta, resourcePrefix: string): string { | ||
| return `${method.name}(${method.signature}): ${method.returnType} {\n return this.sessionClient.${resourcePrefix}.${method.name}(${method.implArgs});\n }`; | ||
| } | ||
|
|
||
| function toImportPath(relPath: string): string { | ||
| const normalized = relPath.replace(/\\/g, '/').replace(/\.ts$/, ''); | ||
| return normalized.startsWith('.') ? normalized : `./${normalized}`; | ||
| } | ||
|
|
||
| function indent(value: string, depth: number): string { | ||
| const prefix = ' '.repeat(depth); | ||
| return value | ||
| .split('\n') | ||
| .map((line) => (line.length ? `${prefix}${line}` : line)) | ||
| .join('\n'); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.