/
utils.ts
67 lines (60 loc) · 1.54 KB
/
utils.ts
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
import { BLOCKED_PAGES } from '../shared/lib/constants'
export function isBlockedPage(pathname: string): boolean {
return BLOCKED_PAGES.includes(pathname)
}
export function cleanAmpPath(pathname: string): string {
if (pathname.match(/\?amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/\?amp=(y|yes|true|1)&?/, '?')
}
if (pathname.match(/&=(y|yes|true|1)/)) {
pathname = pathname.replace(/&=(y|yes|true|1)/, '')
}
pathname = pathname.replace(/\?$/, '')
return pathname
}
export type Disposable = () => void
export type Observer<T> = {
next(chunk: T): void
error(error: Error): void
complete(): void
}
export type RenderResult = (observer: Observer<string>) => Disposable
export function resultFromChunks(chunks: string[]): RenderResult {
return ({ next, complete, error }) => {
let canceled = false
process.nextTick(() => {
try {
for (const chunk of chunks) {
if (canceled) {
return
}
next(chunk)
}
} catch (err) {
if (!canceled) {
canceled = true
error(err)
}
}
if (!canceled) {
canceled = true
complete()
}
})
return () => {
canceled = true
}
}
}
export function resultToChunks(result: RenderResult): Promise<string[]> {
return new Promise((resolve, reject) => {
const chunks: string[] = []
result({
next: (chunk) => {
chunks.push(chunk)
},
error: (error) => reject(error),
complete: () => resolve(chunks),
})
})
}