-
Notifications
You must be signed in to change notification settings - Fork 177
Feat: Generic Code Patching #781
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 13 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
a65c92b
poc for code patching
conico974 6e43665
review fix
conico974 b2e94bd
fix build
conico974 b6f2a11
use ContentUpdater plugin
conico974 d0fda25
added ast-grep code patcher
conico974 c9b8917
added some manifests
conico974 3542789
fix and add logs
conico974 0beaee9
fix to apply patch one after the other
conico974 7da13fe
review fix
conico974 c53d36e
improve typing
conico974 0917c34
simplified CodePatcher types
conico974 ea7f2b5
fix linting
conico974 4bf7f95
changed versions to be more user friendly
conico974 cb7cbd9
review
conico974 dcdb184
review fix
conico974 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
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
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 |
|---|---|---|
|
|
@@ -3,8 +3,10 @@ import path from "node:path"; | |
|
|
||
| import type { FunctionOptions, SplittedFunctionOptions } from "types/open-next"; | ||
|
|
||
| import type { Plugin } from "esbuild"; | ||
| import logger from "../logger.js"; | ||
| import { minifyAll } from "../minimize-js.js"; | ||
| import { ContentUpdater } from "../plugins/content-updater.js"; | ||
| import { openNextReplacementPlugin } from "../plugins/replacement.js"; | ||
| import { openNextResolvePlugin } from "../plugins/resolve.js"; | ||
| import { getCrossPlatformPathRegex } from "../utils/regex.js"; | ||
|
|
@@ -14,8 +16,20 @@ import { copyTracedFiles } from "./copyTracedFiles.js"; | |
| import { generateEdgeBundle } from "./edge/createEdgeBundle.js"; | ||
| import * as buildHelper from "./helper.js"; | ||
| import { installDependencies } from "./installDeps.js"; | ||
| import { type CodePatcher, applyCodePatches } from "./patch/codePatcher.js"; | ||
|
|
||
| interface CodeCustomization { | ||
conico974 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // These patches are meant to apply on user and next generated code | ||
| additionalCodePatches?: CodePatcher[]; | ||
| // These plugins are meant to apply during the esbuild bundling process. | ||
| // This will only apply to OpenNext code. | ||
| additionalPlugins?: (contentUpdater: ContentUpdater) => Plugin[]; | ||
| } | ||
|
|
||
| export async function createServerBundle(options: buildHelper.BuildOptions) { | ||
| export async function createServerBundle( | ||
| options: buildHelper.BuildOptions, | ||
| codeCustomization?: CodeCustomization, | ||
| ) { | ||
| const { config } = options; | ||
| const foundRoutes = new Set<string>(); | ||
| // Get all functions to build | ||
|
|
@@ -36,7 +50,7 @@ export async function createServerBundle(options: buildHelper.BuildOptions) { | |
| if (fnOptions.runtime === "edge") { | ||
| await generateEdgeBundle(name, options, fnOptions); | ||
| } else { | ||
| await generateBundle(name, options, fnOptions); | ||
| await generateBundle(name, options, fnOptions, codeCustomization); | ||
| } | ||
| }); | ||
|
|
||
|
|
@@ -101,6 +115,7 @@ async function generateBundle( | |
| name: string, | ||
| options: buildHelper.BuildOptions, | ||
| fnOptions: SplittedFunctionOptions, | ||
| codeCustomization?: CodeCustomization, | ||
| ) { | ||
| const { appPath, appBuildOutputPath, config, outputDir, monorepoRoot } = | ||
| options; | ||
|
|
@@ -153,14 +168,20 @@ async function generateBundle( | |
| buildHelper.copyEnvFile(appBuildOutputPath, packagePath, outputPath); | ||
|
|
||
| // Copy all necessary traced files | ||
| await copyTracedFiles({ | ||
| const { tracedFiles, manifests } = await copyTracedFiles({ | ||
| buildOutputPath: appBuildOutputPath, | ||
| packagePath, | ||
| outputDir: outputPath, | ||
| routes: fnOptions.routes ?? ["app/page.tsx"], | ||
| bundledNextServer: isBundled, | ||
| }); | ||
|
|
||
| const additionalCodePatches = codeCustomization?.additionalCodePatches ?? []; | ||
|
|
||
| await applyCodePatches(options, Array.from(tracedFiles), manifests, [ | ||
|
||
| ...additionalCodePatches, | ||
| ]); | ||
|
|
||
| // Build Lambda code | ||
| // note: bundle in OpenNext package b/c the adapter relies on the | ||
| // "serverless-http" package which is not a dependency in user's | ||
|
|
@@ -179,6 +200,12 @@ async function generateBundle( | |
|
|
||
| const disableRouting = isBefore13413 || config.middleware?.external; | ||
|
|
||
| const updater = new ContentUpdater(options); | ||
|
|
||
| const additionalPlugins = codeCustomization?.additionalPlugins | ||
| ? codeCustomization.additionalPlugins(updater) | ||
| : []; | ||
|
|
||
| const plugins = [ | ||
| openNextReplacementPlugin({ | ||
| name: `requestHandlerOverride ${name}`, | ||
|
|
@@ -204,6 +231,9 @@ async function generateBundle( | |
| fnName: name, | ||
| overrides, | ||
| }), | ||
| ...additionalPlugins, | ||
| // The content updater plugin must be the last plugin | ||
| updater.plugin, | ||
| ]; | ||
|
|
||
| const outfileExt = fnOptions.runtime === "deno" ? "ts" : "mjs"; | ||
|
|
||
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,114 @@ | ||
| // Mostly copied from the cloudflare adapter | ||
| import { readFileSync } from "node:fs"; | ||
|
|
||
| import { | ||
| type Edit, | ||
| Lang, | ||
| type NapiConfig, | ||
| type SgNode, | ||
| parse, | ||
| } from "@ast-grep/napi"; | ||
| import yaml from "yaml"; | ||
| import type { PatchCodeFn } from "./codePatcher"; | ||
|
|
||
| /** | ||
| * fix has the same meaning as in yaml rules | ||
| * see https://ast-grep.github.io/guide/rewrite-code.html#using-fix-in-yaml-rule | ||
| */ | ||
| export type RuleConfig = NapiConfig & { fix?: string }; | ||
|
|
||
| /** | ||
| * Returns the `Edit`s and `Match`es for an ast-grep rule in yaml format | ||
| * | ||
| * The rule must have a `fix` to rewrite the matched node. | ||
| * | ||
| * Tip: use https://ast-grep.github.io/playground.html to create rules. | ||
| * | ||
| * @param rule The rule. Either a yaml string or an instance of `RuleConfig` | ||
| * @param root The root node | ||
| * @param once only apply once | ||
| * @returns A list of edits and a list of matches. | ||
| */ | ||
| export function applyRule( | ||
| rule: string | RuleConfig, | ||
| root: SgNode, | ||
| { once = false } = {}, | ||
| ) { | ||
| const ruleConfig: RuleConfig = | ||
| typeof rule === "string" ? yaml.parse(rule) : rule; | ||
| if (ruleConfig.transform) { | ||
| throw new Error("transform is not supported"); | ||
| } | ||
| if (!ruleConfig.fix) { | ||
| throw new Error("no fix to apply"); | ||
| } | ||
|
|
||
| const fix = ruleConfig.fix; | ||
|
|
||
| const matches = once | ||
| ? [root.find(ruleConfig)].filter((m) => m !== null) | ||
| : root.findAll(ruleConfig); | ||
|
|
||
| const edits: Edit[] = []; | ||
|
|
||
| matches.forEach((match) => { | ||
| edits.push( | ||
| match.replace( | ||
| // Replace known placeholders by their value | ||
| fix | ||
| .replace(/\$\$\$([A-Z0-9_]+)/g, (_m, name) => | ||
| match | ||
| .getMultipleMatches(name) | ||
| .map((n) => n.text()) | ||
| .join(""), | ||
| ) | ||
| .replace( | ||
| /\$([A-Z0-9_]+)/g, | ||
| (m, name) => match.getMatch(name)?.text() ?? m, | ||
| ), | ||
| ), | ||
| ); | ||
| }); | ||
|
|
||
| return { edits, matches }; | ||
| } | ||
|
|
||
| /** | ||
| * Parse a file and obtain its root. | ||
| * | ||
| * @param path The file path | ||
| * @param lang The language to parse. Defaults to TypeScript. | ||
| * @returns The root for the file. | ||
| */ | ||
| export function parseFile(path: string, lang = Lang.TypeScript) { | ||
| return parse(lang, readFileSync(path, { encoding: "utf-8" })).root(); | ||
| } | ||
|
|
||
| /** | ||
| * Patches the code from by applying the rule. | ||
| * | ||
| * This function is mainly for on off edits and tests, | ||
| * use `getRuleEdits` to apply multiple rules. | ||
| * | ||
| * @param code The source code | ||
| * @param rule The astgrep rule (yaml or NapiConfig) | ||
| * @param lang The language used by the source code | ||
| * @param lang Whether to apply the rule only once | ||
| * @returns The patched code | ||
| */ | ||
| export function patchCode( | ||
| code: string, | ||
| rule: string | RuleConfig, | ||
| { lang = Lang.TypeScript, once = false } = {}, | ||
| ): string { | ||
| const node = parse(lang, code).root(); | ||
| const { edits } = applyRule(rule, node, { once }); | ||
| return node.commitEdits(edits); | ||
| } | ||
|
|
||
| export function createPatchCode( | ||
| rule: string | RuleConfig, | ||
| lang = Lang.TypeScript, | ||
| ): PatchCodeFn { | ||
| return async ({ code }) => patchCode(code, rule, { lang }); | ||
conico974 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could this be optional?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah it could, i'll change that