-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
util.ts
242 lines (213 loc) · 8.34 KB
/
util.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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import type { SSRElement } from '../../../@types/astro.js';
import type { RenderDestination, RenderDestinationChunk, RenderFunction } from './common.js';
import { clsx } from 'clsx';
import { HTMLString, markHTMLString } from '../escape.js';
export const voidElementNames =
/^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i;
const htmlBooleanAttributes =
/^(?:allowfullscreen|async|autofocus|autoplay|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|itemscope)$/i;
const htmlEnumAttributes = /^(?:contenteditable|draggable|spellcheck|value)$/i;
// Note: SVG is case-sensitive!
const svgEnumAttributes = /^(?:autoReverse|externalResourcesRequired|focusable|preserveAlpha)$/i;
const STATIC_DIRECTIVES = new Set(['set:html', 'set:text']);
// converts (most) arbitrary strings to valid JS identifiers
const toIdent = (k: string) =>
k.trim().replace(/(?!^)\b\w|\s+|\W+/g, (match, index) => {
if (/\W/.test(match)) return '';
return index === 0 ? match : match.toUpperCase();
});
export const toAttributeString = (value: any, shouldEscape = true) =>
shouldEscape ? String(value).replace(/&/g, '&').replace(/"/g, '"') : value;
const kebab = (k: string) =>
k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
const toStyleString = (obj: Record<string, any>) =>
Object.entries(obj)
.filter(([_, v]) => (typeof v === 'string' && v.trim()) || typeof v === 'number')
.map(([k, v]) => {
if (k[0] !== '-' && k[1] !== '-') return `${kebab(k)}:${v}`;
return `${k}:${v}`;
})
.join(';');
// Adds variables to an inline script.
export function defineScriptVars(vars: Record<any, any>) {
let output = '';
for (const [key, value] of Object.entries(vars)) {
// Use const instead of let as let global unsupported with Safari
// https://stackoverflow.com/questions/29194024/cant-use-let-keyword-in-safari-javascript
output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace(
/<\/script>/g,
'\\x3C/script>'
)};\n`;
}
return markHTMLString(output);
}
export function formatList(values: string[]): string {
if (values.length === 1) {
return values[0];
}
return `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;
}
// A helper used to turn expressions into attribute key/value
export function addAttribute(value: any, key: string, shouldEscape = true) {
if (value == null) {
return '';
}
if (value === false) {
if (htmlEnumAttributes.test(key) || svgEnumAttributes.test(key)) {
return markHTMLString(` ${key}="false"`);
}
return '';
}
// compiler directives cannot be applied dynamically, log a warning and ignore.
if (STATIC_DIRECTIVES.has(key)) {
// eslint-disable-next-line no-console
console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute.
Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`);
return '';
}
// support "class" from an expression passed into an element (#782)
if (key === 'class:list') {
const listValue = toAttributeString(clsx(value), shouldEscape);
if (listValue === '') {
return '';
}
return markHTMLString(` ${key.slice(0, -5)}="${listValue}"`);
}
// support object styles for better JSX compat
if (key === 'style' && !(value instanceof HTMLString)) {
if (Array.isArray(value) && value.length === 2) {
return markHTMLString(
` ${key}="${toAttributeString(`${toStyleString(value[0])};${value[1]}`, shouldEscape)}"`
);
}
if (typeof value === 'object') {
return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`);
}
}
// support `className` for better JSX compat
if (key === 'className') {
return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`);
}
// Prevents URLs in attributes from being escaped in static builds
if (typeof value === 'string' && value.includes('&') && urlCanParse(value)) {
return markHTMLString(` ${key}="${toAttributeString(value, false)}"`);
}
// Boolean values only need the key
if (value === true && (key.startsWith('data-') || htmlBooleanAttributes.test(key))) {
return markHTMLString(` ${key}`);
} else {
return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`);
}
}
// Adds support for `<Component {...value} />
export function internalSpreadAttributes(values: Record<any, any>, shouldEscape = true) {
let output = '';
for (const [key, value] of Object.entries(values)) {
output += addAttribute(value, key, shouldEscape);
}
return markHTMLString(output);
}
export function renderElement(
name: string,
{ props: _props, children = '' }: SSRElement,
shouldEscape = true
) {
// Do not print `hoist`, `lang`, `is:global`
const { lang: _, 'data-astro-id': astroId, 'define:vars': defineVars, ...props } = _props;
if (defineVars) {
if (name === 'style') {
delete props['is:global'];
delete props['is:scoped'];
}
if (name === 'script') {
delete props.hoist;
children = defineScriptVars(defineVars) + '\n' + children;
}
}
if ((children == null || children == '') && voidElementNames.test(name)) {
return `<${name}${internalSpreadAttributes(props, shouldEscape)}>`;
}
return `<${name}${internalSpreadAttributes(props, shouldEscape)}>${children}</${name}>`;
}
/**
* Executes the `bufferRenderFunction` to prerender it into a buffer destination, and return a promise
* with an object containing the `renderToFinalDestination` function to flush the buffer to the final
* destination.
*
* @example
* ```ts
* // Render components in parallel ahead of time
* const finalRenders = [ComponentA, ComponentB].map((comp) => {
* return renderToBufferDestination(async (bufferDestination) => {
* await renderComponentToDestination(bufferDestination);
* });
* });
* // Render array of components serially
* for (const finalRender of finalRenders) {
* await finalRender.renderToFinalDestination(finalDestination);
* }
* ```
*/
export function renderToBufferDestination(bufferRenderFunction: RenderFunction): {
renderToFinalDestination: RenderFunction;
} {
// Keep chunks in memory
const bufferChunks: RenderDestinationChunk[] = [];
const bufferDestination: RenderDestination = {
write: (chunk) => bufferChunks.push(chunk),
};
// Don't await for the render to finish to not block streaming
const renderPromise = bufferRenderFunction(bufferDestination);
// Catch here in case it throws before `renderToFinalDestination` is called,
// to prevent an unhandled rejection.
Promise.resolve(renderPromise).catch(() => {});
// Return a closure that writes the buffered chunk
return {
async renderToFinalDestination(destination) {
// Write the buffered chunks to the real destination
for (const chunk of bufferChunks) {
destination.write(chunk);
}
// NOTE: We don't empty `bufferChunks` after it's written as benchmarks show
// that it causes poorer performance, likely due to forced memory re-allocation,
// instead of letting the garbage collector handle it automatically.
// (Unsure how this affects on limited memory machines)
// Re-assign the real destination so `instance.render` will continue and write to the new destination
bufferDestination.write = (chunk) => destination.write(chunk);
// Wait for render to finish entirely
await renderPromise;
},
};
}
export const isNode =
typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]';
// @ts-expect-error: Deno is not part of the types.
export const isDeno = typeof Deno !== 'undefined';
// We can get rid of this when Promise.withResolvers() is ready
export type PromiseWithResolvers<T> = {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (reason?: any) => void;
};
// This is an implementation of Promise.withResolvers(), which we can't yet rely on.
// We can remove this once the native function is available in Node.js
export function promiseWithResolvers<T = any>(): PromiseWithResolvers<T> {
let resolve: any, reject: any;
const promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return {
promise,
resolve,
reject,
};
}
function urlCanParse(url: string) {
try {
new URL(url);
return true;
} catch {
return false;
}
}