Skip to content
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

Allow match replacement functions #21

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules\\typescript\\lib"
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "string-replace-middleware",
"version": "1.1.0",
"version": "1.2.0",
"description": "Express middleware to replace strings in response stream on the fly",
"license": "MIT",
"repository": "bfncs/string-replace-middleware",
Expand Down Expand Up @@ -51,4 +51,4 @@
"singleQuote": true,
"trailingComma": "es5"
}
}
}
20 changes: 13 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { NextFunction, Request, Response } from 'express';
import hijackResponse from 'hijackresponse';
import stringReplaceStream from './stringReplaceStream';
import stringReplaceStream, { MatchReplacement } from './stringReplaceStream';

export type Options = Record<'contentTypeFilterRegexp', RegExp>;
export type ReplaceFunction = (req: Request, res: Response) => MatchReplacement;

export type ReplaceFunction = (req: Request, res: Response) => string;

const defaultOptions: Options = {
const defaultOptions = {
contentTypeFilterRegexp: /^text\/|^application\/json$|^application\/xml$/,
useRegExp: false,
};
type Options = typeof defaultOptions;

export const stringReplace = (
replacements: Record<string, string | ReplaceFunction>,
Expand Down Expand Up @@ -39,7 +39,7 @@ export const stringReplace = (
}
res.removeHeader('content-length');

let scopedReplacements: Record<string, string>;
let scopedReplacements: Record<string, MatchReplacement>;
if (hasFunctionReplacements) {
// If we have dynamic replacements, calculate for this request
scopedReplacements = { ...stringReplacements };
Expand All @@ -51,7 +51,13 @@ export const stringReplace = (
scopedReplacements = stringReplacements;
}

res.pipe(stringReplaceStream(scopedReplacements)).pipe(res);
res
.pipe(
stringReplaceStream(scopedReplacements, {
useRegExp: options.useRegExp,
})
)
.pipe(res);
} else {
return res.unhijack();
}
Expand Down
32 changes: 21 additions & 11 deletions src/stringReplaceStream.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,53 @@
import { Transform, TransformCallback } from 'stream';
import escapeStringRegexp from 'escape-string-regexp';

type Options = {
encoding: BufferEncoding;
ignoreCase: boolean;
};
/** The replacer string or function passed to string.replace(text: string, replacer: *MatchReplacement*) */
export type MatchReplacement =
| string
| ((matchedSubstring: string, ...capturedGroups: string[]) => string);

type Replacer = {
matcher: RegExp;
replace: string;
replace: MatchReplacement;
};

type Options = {
encoding: BufferEncoding;
ignoreCase: boolean;
useRegExp: boolean;
};
const defaultOptions: Options = {
encoding: 'utf8',
ignoreCase: true,
useRegExp: false,
};

function buildReplacers(
replacements: Record<string, string>,
replacements: Record<string, MatchReplacement>,
opts: Options
): Replacer[] {
return Object.keys(replacements)
.sort((a, b) => b.length - a.length)
.map(search => ({
matcher: new RegExp(
escapeStringRegexp(search),
opts.useRegExp ? search : escapeStringRegexp(search),
opts.ignoreCase ? 'gmi' : 'gm'
),
replace: replacements[search],
}));
}

function getMaxSearchLength(replacements: Record<string, string>): number {
function getMaxSearchLength(
replacements: Record<string, MatchReplacement>
): number {
return Object.keys(replacements).reduce(
(acc, search) => Math.max(acc, search.length),
0
);
}

export default function StringReplaceStream(
replacements: Record<string, string>,
replacements: Record<string, MatchReplacement>,
options: Partial<Options> = {}
) {
const opts: Options = { ...defaultOptions, ...options };
Expand All @@ -65,7 +74,7 @@ export default function StringReplaceStream(
body =
body
.slice(0, replaceBefore)
.replace(replacer.matcher, replacer.replace) +
.replace(replacer.matcher, replacer.replace as string) +
body.slice(replaceBefore);
});

Expand Down Expand Up @@ -98,7 +107,8 @@ export default function StringReplaceStream(
}

const body = replacers.reduce(
(acc, replacer) => acc.replace(replacer.matcher, replacer.replace),
(acc, replacer) =>
acc.replace(replacer.matcher, replacer.replace as string),
tail
);
cb(null, body);
Expand Down