forked from microsoft/BotFramework-WebChat
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtemplatePolymiddleware.tsx
More file actions
175 lines (145 loc) · 5.91 KB
/
Copy pathtemplatePolymiddleware.tsx
File metadata and controls
175 lines (145 loc) · 5.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { warnOnce } from '@msinternal/botframework-webchat-base/utils';
import { type Enhancer } from 'handler-chain';
import React, { memo, type ReactNode } from 'react';
import {
createChainOfResponsibility,
type ComponentEnhancer,
type ComponentHandler,
type ComponentHandlerResult,
type ComponentRenderer,
type InferMiddleware as InferOrganicMiddleware,
type ProviderProps,
type ProxyProps
} from 'react-chain-of-responsibility/preview';
import { array, check, function_, literal, parse, pipe, safeParse, union, type InferOutput } from 'valibot';
const arrayOfFunctionSchema = array(function_());
const isArrayOfFunction = (middleware: unknown): middleware is InferOutput<typeof arrayOfFunctionSchema> =>
safeParse(arrayOfFunctionSchema, middleware).success;
const BYPASS_ENHANCER: Enhancer<any, any> = next => request => next(request);
const EMPTY_ARRAY = Object.freeze([]);
// Following @types/react to use {} for props.
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
function templatePolymiddleware<Request, Props extends {}>(name: string) {
const {
Provider,
Proxy,
reactComponent,
useBuildRenderCallback: useBuildRenderCallbackRaw
} = createChainOfResponsibility<Request, Props, string>();
type TemplatedEnhancer = ReturnType<InferOrganicMiddleware<typeof Provider>>;
type TemplatedMiddleware = (init: string) => TemplatedEnhancer;
const middlewareFactoryTag = Symbol();
const middlewareSchema = union([
pipe(
function_(),
check(value => value === BYPASS_ENHANCER || middlewareFactoryTag in value)
),
literal(false)
]);
const createMiddleware = (enhancer: TemplatedEnhancer): TemplatedMiddleware => {
parse(function_(`botframework-webchat: ${name} enhancer must be of type function.`), enhancer);
// Clone the enhancer function and tag it, so we leave the original enhancer as-is.
const taggedEnhancer = enhancer.bind(undefined);
// This is for checking if the middleware is created via factory function or not.
// We enforce middleware to be created using factory function.
Object.defineProperty(taggedEnhancer, middlewareFactoryTag, { enumerable: false });
return init => (init === name ? taggedEnhancer : BYPASS_ENHANCER);
};
const warnInvalidExtraction = warnOnce(`Middleware passed for extraction of "${name}" must be an array of function`);
const extractEnhancer = (
middleware: readonly ((init: string) => ComponentEnhancer<any, any>)[] | undefined
): readonly TemplatedEnhancer[] => {
if (middleware) {
if (isArrayOfFunction(middleware)) {
return Object.freeze(
middleware
.map(middleware => {
const result = middleware(name);
if (typeof result !== 'function' && result !== false) {
console.warn(`botframework-webchat: ${name}.middleware must return enhancer function or false`);
return false;
} else if (!safeParse(middlewareSchema, result).success) {
console.warn(`botframework-webchat: ${name}.middleware must be created using factory function`);
return false;
}
return result;
})
.filter((enhancer): enhancer is ReturnType<TemplatedMiddleware> => !!enhancer)
);
}
warnInvalidExtraction();
}
return EMPTY_ARRAY;
};
// Bind "init" props.
const TemplatedProvider = memo(function TemplatedProvider({
children,
middleware
}: {
readonly children?: ReactNode | undefined;
readonly middleware: readonly TemplatedMiddleware[];
}) {
return (
<Provider init={name} middleware={middleware}>
{children}
</Provider>
);
});
TemplatedProvider.displayName = `${name}Provider`;
Proxy.displayName = `${name}Proxy`;
const useBuildRenderCallback = () => {
try {
return useBuildRenderCallbackRaw();
} catch (error) {
if (error && typeof error === 'object' && 'message' in error && typeof error.message === 'string') {
if (error.message.includes('middleware must return value constructed by reactComponent()')) {
const customError = new Error(
`botframework-webchat: middleware must return value constructed by ${name}Component()`
);
customError.cause = error;
throw customError;
}
}
throw error;
}
};
return {
createMiddleware,
extractEnhancer,
Provider: TemplatedProvider as typeof TemplatedProvider & InferenceHelper<Request, Props>,
Proxy,
reactComponent,
useBuildRenderCallback
};
}
type InferenceHelper<Request, Props extends object> = {
'~types': {
handler: ComponentHandler<Request, Props>;
handlerResult: ComponentHandlerResult<Props>;
middleware: (init: string) => ComponentEnhancer<Request, Props>;
props: Props;
providerProps: Pick<ProviderProps<Request, Props, string>, 'children' | 'middleware'>;
proxyProps: ProxyProps<Request, Props>;
renderer: ComponentRenderer<Props>;
request: Request;
};
};
type InferHandler<T extends InferenceHelper<any, any>> = T['~types']['handler'];
type InferHandlerResult<T extends InferenceHelper<any, any>> = T['~types']['handlerResult'];
type InferMiddleware<T extends InferenceHelper<any, any>> = T['~types']['middleware'];
type InferProps<T extends InferenceHelper<any, any>> = T['~types']['props'];
type InferProviderProps<T extends InferenceHelper<any, any>> = T['~types']['providerProps'];
type InferProxyProps<T extends InferenceHelper<any, any>> = T['~types']['proxyProps'];
type InferRenderer<T extends InferenceHelper<any, any>> = T['~types']['renderer'];
type InferRequest<T extends InferenceHelper<any, any>> = T['~types']['request'];
export default templatePolymiddleware;
export {
type InferHandler,
type InferHandlerResult,
type InferMiddleware,
type InferProps,
type InferProviderProps,
type InferProxyProps,
type InferRenderer,
type InferRequest
};