Skip to content

Commit 9d3a30c

Browse files
author
Younes Khoubza
authored
Merge pull request #7 from php-flasher/fix/execute-js-callback-from-string
Execute js callback function from string
2 parents 68a697b + 9c87fe0 commit 9d3a30c

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/flasher.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ import {
44
Envelope,
55
FlasherResponseOptions,
66
QueueableInterface,
7-
ResponseContext,
7+
ResponseContext, FlasherOptions,
88
} from './interfaces';
99
import TemplateFactory from './template';
10+
import { parseFunction } from './functions';
1011

1112
export default class Flasher {
1213
private static instance: Flasher;
@@ -26,6 +27,7 @@ export default class Flasher {
2627
}
2728

2829
public render(response: FlasherResponse): void {
30+
response = this.parseResponse(response);
2931
this.addStyles(response.styles, () => {
3032
this.addScripts(response.scripts, () => {
3133
this.renderOptions(response.options);
@@ -127,4 +129,24 @@ export default class Flasher {
127129
return typeof object.addEnvelope === 'function'
128130
&& typeof object.renderQueue === 'function';
129131
}
132+
133+
private parseResponse(response: FlasherResponse): FlasherResponse {
134+
Object.entries(response.options).forEach(([handler, options]) => {
135+
response.options[handler] = this.parseOptions(options);
136+
});
137+
138+
response.envelopes.forEach(envelope => {
139+
envelope.notification.options = this.parseOptions(envelope.notification.options);
140+
});
141+
142+
return response;
143+
}
144+
145+
private parseOptions(options: FlasherOptions): FlasherOptions {
146+
Object.entries(options).forEach(([key, value]) => {
147+
options[key] = parseFunction(value);
148+
});
149+
150+
return options;
151+
}
130152
}

src/functions.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export function parseFunction(func: any): any {
2+
if (typeof func !== 'string') {
3+
return func;
4+
}
5+
6+
const match = func.match(/^function(?:.+)?(?:\s+)?\((.+)?\)(?:\s+|\n+)?\{(?:\s+|\n+)?((?:.|\n)+)\}$/m);
7+
8+
if (!match) {
9+
return func;
10+
}
11+
12+
const args = match[1]?.split(',').map(arg => arg.trim()) ?? [];
13+
const body = match[2];
14+
15+
// @ts-ignore
16+
// eslint-disable-next-line @typescript-eslint/no-implied-eval
17+
return new Function(...args, body);
18+
}

0 commit comments

Comments
 (0)