-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.ts
218 lines (192 loc) Β· 7.31 KB
/
server.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
import { type JSXNode, type JSXOutput, jsx } from "@qwik.dev/core";
import { isDev } from "@qwik.dev/core/build";
import type { QwikManifest } from "@qwik.dev/core/optimizer";
import {
type RenderToStreamOptions,
getQwikLoaderScript,
renderToStream
} from "@qwik.dev/core/server";
import type { SSRResult } from "astro";
const isQwikLoaderAddedMap = new WeakMap<SSRResult, boolean>();
const modulePreloadScript = `window.addEventListener("load",()=>{(async()=>{window.requestIdleCallback||(window.requestIdleCallback=(e,t)=>{const n=t||{},o=1,i=n.timeout||o,a=performance.now();return setTimeout(()=>{e({get didTimeout(){return!n.timeout&&performance.now()-a-o>i},timeRemaining:()=>Math.max(0,o+(performance.now()-a))})},o)});const e=async()=>{const e=new Set,t=document.querySelectorAll('script[q\\\\:type="prefetch-bundles"]');t.forEach(t=>{if(!t.textContent)return;const n=t.textContent,o=n.match(/\\["prefetch","[/]build[/]","(.*?)"\\]/);o&&o[1]&&o[1].split('","').forEach(t=>{t.startsWith("q-")&&e.add(t)})}),document.querySelectorAll('script[type="qwik/json"]').forEach(t=>{if(!t.textContent)return;const n=t.textContent.match(/q-[A-Za-z0-9_-]+\\.js/g);n&&n.forEach(t=>e.add(t))}),e.forEach(e=>{const t=document.createElement("link");t.rel="modulepreload",t.href="/build/"+e,t.fetchPriority="low",document.head.appendChild(t)})};await requestIdleCallback(await e)})()});`;
type RendererContext = {
result: SSRResult;
};
/**
* Because inline components are very much like normal functions, it's hard to distinguish them from normal functions.
*
* We currently identify them through the jsx transform function call.
*
* In Qwik v1, the identifiers are _jsxQ - _jsxC - _jsxS
*
* In Qwik v2, it is jsxsplit and I believe jsxSorted
*
*/
function isInlineComponent(component: unknown): boolean {
if (typeof component !== "function") {
return false;
}
const codeStr = component?.toString().toLowerCase();
const qwikJsxIdentifiers = ["_jsxq", "_jsxc", "_jsxs", "jsxsplit"];
return (
qwikJsxIdentifiers.some((id) => codeStr.includes(id)) &&
component.name !== "QwikComponent"
);
}
function isQwikComponent(component: unknown) {
if (typeof component !== "function") {
return false;
}
if (isInlineComponent(component)) {
return true;
}
if (component.name !== "QwikComponent") {
return false;
}
return true;
}
async function check(this: RendererContext, component: unknown) {
try {
return isQwikComponent(component);
} catch (error) {
console.error("Error in check function of @qwikdev/astro: ", error);
return false;
}
}
export async function renderToStaticMarkup(
this: RendererContext,
component: any,
props: Record<string, unknown>,
slotted: any
) {
try {
if (!isQwikComponent(component)) {
return;
}
let html = "";
const devUrls = new Set<string>();
const renderToStreamOpts: RenderToStreamOptions = {
containerAttributes: {
style: "display: contents",
...(isDev && { "q-astro-marker": "" })
},
containerTagName: "div",
...(isDev
? {
manifest: {} as QwikManifest,
symbolMapper: (symbolName, mapper, parent) => {
const requestUrl = new URL(this.result.request.url);
const origin = requestUrl.origin;
const devUrl = origin + parent + "_" + symbolName + ".js";
devUrls.add(devUrl);
// this determines if the container is the last one
renderToStreamOpts.containerAttributes!["q-astro-marker"] = "last";
return globalThis.symbolMapperFn(symbolName, mapper, parent);
}
}
: {
manifest: globalThis.qManifest
}),
serverData: props,
qwikPrefetchServiceWorker: {
include: false
},
stream: {
write: (chunk: string) => {
html += chunk;
}
}
};
// https://qwik.dev/docs/components/overview/#inline-components
const isInline = isInlineComponent(component);
if (isInline) {
const inlineComponentJSX = component(props);
// we don't want to process slots for inline components
await renderToStream(inlineComponentJSX, renderToStreamOpts);
return {
html
};
}
// https://qwik.dev/docs/advanced/qwikloader/#qwikloader
const isQwikLoaderNeeded = !isQwikLoaderAddedMap.has(this.result);
const qwikLoader =
isQwikLoaderNeeded &&
jsx("script", {
"qwik-loader": "",
dangerouslySetInnerHTML: getQwikLoaderScript()
});
const modulePreload =
isQwikLoaderNeeded &&
jsx("script", {
"qwik-astro-preloader": "",
dangerouslySetInnerHTML: modulePreloadScript
});
/**
* service worker script is only added to the page once, and in prod.
* https://github.com/QwikDev/qwik/pull/5618
*/
const qwikScripts = jsx("span", {
"q:slot": "qwik-scripts",
"qwik-scripts": "",
children: [qwikLoader, modulePreload]
});
const slots: { [key: string]: unknown } = {};
let defaultSlot: JSXNode<"span"> | undefined = undefined;
/** slot handling
* https://qwik.dev/docs/components/slots/#slots
* https://docs.astro.build/en/basics/astro-components/#slots
*/
for (const [key, value] of Object.entries(slotted)) {
const namedSlot = key !== "default" && { "q:slot": key };
const jsxElement = jsx("span", {
dangerouslySetInnerHTML: String(value),
style: "display: contents",
...namedSlot,
"q:key": Math.random().toString(26).split(".").pop()
});
if (key === "default") {
defaultSlot = jsxElement;
} else {
slots[key] = jsxElement;
}
}
const slotValues = Object.values(slots);
const qwikComponentJSX = jsx(component, {
...props,
children: [qwikScripts, defaultSlot, ...slotValues]
});
if (isQwikLoaderNeeded) {
isQwikLoaderAddedMap.set(this.result, true);
renderToStreamOpts.containerAttributes!["q-astro-marker"] = "first";
}
await renderToStream(qwikComponentJSX as JSXOutput, renderToStreamOpts);
const isClientRouter = Array.from(this.result._metadata.renderedScripts).some(
(path) => path.includes("ClientRouter.astro")
);
/** With View Transitions, rerun so that signals work
* https://docs.astro.build/en/guides/view-transitions/#data-astro-rerun
*/
const htmlWithRerun = html.replace(
'<script q:func="qwik/json">',
'<script q:func="qwik/json" data-astro-rerun>'
);
/** Adds support for visible tasks with Astro's client router */
const htmlWithObservers =
isClientRouter &&
htmlWithRerun +
`
${isQwikLoaderNeeded ? `<script data-qwik-astro-client-router>document.addEventListener('astro:after-swap',()=>{const e=document.querySelectorAll('[on\\\\:qvisible]');if(e.length){const o=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&(e.target.dispatchEvent(new CustomEvent('qvisible')),o.unobserve(e.target))})});e.forEach(e=>o.observe(e))}});</script>` : ""}
`;
return {
html: isClientRouter ? htmlWithObservers : html
};
} catch (error) {
console.error("Error in renderToStaticMarkup function of @qwikdev/astro: ", error);
throw error;
}
}
export default {
renderToStaticMarkup,
supportsAstroStaticSlot: true,
check
};