@velocity-astro/cms-astro 0.0.0-stage → 0.1.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/bin/velocity-cms.mjs +6 -0
  4. package/dist/admin-files.d.ts +21 -0
  5. package/dist/admin-files.d.ts.map +1 -0
  6. package/dist/admin-files.js +83 -0
  7. package/dist/admin-files.js.map +1 -0
  8. package/dist/challenge.d.ts +35 -0
  9. package/dist/challenge.d.ts.map +1 -0
  10. package/dist/challenge.js +84 -0
  11. package/dist/challenge.js.map +1 -0
  12. package/dist/cli.d.ts +9 -0
  13. package/dist/cli.d.ts.map +1 -0
  14. package/dist/cli.js +76 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/connection.d.ts +26 -0
  17. package/dist/connection.d.ts.map +1 -0
  18. package/dist/connection.js +87 -0
  19. package/dist/connection.js.map +1 -0
  20. package/dist/editor.d.ts +67 -0
  21. package/dist/editor.d.ts.map +1 -0
  22. package/dist/editor.js +194 -0
  23. package/dist/editor.js.map +1 -0
  24. package/dist/entry-page.d.ts +37 -0
  25. package/dist/entry-page.d.ts.map +1 -0
  26. package/dist/entry-page.js +56 -0
  27. package/dist/entry-page.js.map +1 -0
  28. package/dist/form-post.d.ts +114 -0
  29. package/dist/form-post.d.ts.map +1 -0
  30. package/dist/form-post.js +298 -0
  31. package/dist/form-post.js.map +1 -0
  32. package/dist/hosted.d.ts +76 -0
  33. package/dist/hosted.d.ts.map +1 -0
  34. package/dist/hosted.js +104 -0
  35. package/dist/hosted.js.map +1 -0
  36. package/dist/image-optimizer.d.ts +35 -0
  37. package/dist/image-optimizer.d.ts.map +1 -0
  38. package/dist/image-optimizer.js +76 -0
  39. package/dist/image-optimizer.js.map +1 -0
  40. package/dist/index.d.ts +34 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +34 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/init.d.ts +35 -0
  45. package/dist/init.d.ts.map +1 -0
  46. package/dist/init.js +140 -0
  47. package/dist/init.js.map +1 -0
  48. package/dist/integration.d.ts +72 -0
  49. package/dist/integration.d.ts.map +1 -0
  50. package/dist/integration.js +143 -0
  51. package/dist/integration.js.map +1 -0
  52. package/dist/link.d.ts +32 -0
  53. package/dist/link.d.ts.map +1 -0
  54. package/dist/link.js +80 -0
  55. package/dist/link.js.map +1 -0
  56. package/dist/live-loader.d.ts +44 -0
  57. package/dist/live-loader.d.ts.map +1 -0
  58. package/dist/live-loader.js +98 -0
  59. package/dist/live-loader.js.map +1 -0
  60. package/dist/live-pages.d.ts +69 -0
  61. package/dist/live-pages.d.ts.map +1 -0
  62. package/dist/live-pages.js +94 -0
  63. package/dist/live-pages.js.map +1 -0
  64. package/dist/loader.d.ts +22 -0
  65. package/dist/loader.d.ts.map +1 -0
  66. package/dist/loader.js +62 -0
  67. package/dist/loader.js.map +1 -0
  68. package/dist/media-store.d.ts +61 -0
  69. package/dist/media-store.d.ts.map +1 -0
  70. package/dist/media-store.js +178 -0
  71. package/dist/media-store.js.map +1 -0
  72. package/dist/menu.d.ts +51 -0
  73. package/dist/menu.d.ts.map +1 -0
  74. package/dist/menu.js +81 -0
  75. package/dist/menu.js.map +1 -0
  76. package/dist/page-head.d.ts +23 -0
  77. package/dist/page-head.d.ts.map +1 -0
  78. package/dist/page-head.js +66 -0
  79. package/dist/page-head.js.map +1 -0
  80. package/dist/page-marks.d.ts +50 -0
  81. package/dist/page-marks.d.ts.map +1 -0
  82. package/dist/page-marks.js +90 -0
  83. package/dist/page-marks.js.map +1 -0
  84. package/dist/preview.d.ts +92 -0
  85. package/dist/preview.d.ts.map +1 -0
  86. package/dist/preview.js +192 -0
  87. package/dist/preview.js.map +1 -0
  88. package/dist/resend-mailer.d.ts +63 -0
  89. package/dist/resend-mailer.d.ts.map +1 -0
  90. package/dist/resend-mailer.js +116 -0
  91. package/dist/resend-mailer.js.map +1 -0
  92. package/dist/secret.d.ts +8 -0
  93. package/dist/secret.d.ts.map +1 -0
  94. package/dist/secret.js +17 -0
  95. package/dist/secret.js.map +1 -0
  96. package/dist/single.d.ts +18 -0
  97. package/dist/single.d.ts.map +1 -0
  98. package/dist/single.js +37 -0
  99. package/dist/single.js.map +1 -0
  100. package/dist/site-editor.d.ts +41 -0
  101. package/dist/site-editor.d.ts.map +1 -0
  102. package/dist/site-editor.js +140 -0
  103. package/dist/site-editor.js.map +1 -0
  104. package/dist/site-forms.d.ts +54 -0
  105. package/dist/site-forms.d.ts.map +1 -0
  106. package/dist/site-forms.js +100 -0
  107. package/dist/site-forms.js.map +1 -0
  108. package/dist/site-images.d.ts +17 -0
  109. package/dist/site-images.d.ts.map +1 -0
  110. package/dist/site-images.js +22 -0
  111. package/dist/site-images.js.map +1 -0
  112. package/dist/site-mail.d.ts +45 -0
  113. package/dist/site-mail.d.ts.map +1 -0
  114. package/dist/site-mail.js +84 -0
  115. package/dist/site-mail.js.map +1 -0
  116. package/dist/site-media.d.ts +22 -0
  117. package/dist/site-media.d.ts.map +1 -0
  118. package/dist/site-media.js +52 -0
  119. package/dist/site-media.js.map +1 -0
  120. package/dist/site-name.d.ts +9 -0
  121. package/dist/site-name.d.ts.map +1 -0
  122. package/dist/site-name.js +21 -0
  123. package/dist/site-name.js.map +1 -0
  124. package/dist/site-plugins.d.ts +10 -0
  125. package/dist/site-plugins.d.ts.map +1 -0
  126. package/dist/site-plugins.js +23 -0
  127. package/dist/site-plugins.js.map +1 -0
  128. package/dist/site-search.d.ts +12 -0
  129. package/dist/site-search.d.ts.map +1 -0
  130. package/dist/site-search.js +79 -0
  131. package/dist/site-search.js.map +1 -0
  132. package/dist/site-storage.d.ts +34 -0
  133. package/dist/site-storage.d.ts.map +1 -0
  134. package/dist/site-storage.js +118 -0
  135. package/dist/site-storage.js.map +1 -0
  136. package/package.json +56 -3
  137. package/routes/admin.ts +10 -0
  138. package/routes/api.ts +15 -0
  139. package/routes/auth.ts +10 -0
  140. package/routes/due.ts +12 -0
  141. package/routes/editor.ts +49 -0
  142. package/routes/form-client.js.ts +173 -0
  143. package/routes/media.ts +10 -0
  144. package/routes/pages.ts +13 -0
  145. package/routes/plugins.ts +10 -0
  146. package/routes/preview-client.js.ts +18 -0
  147. package/routes/published.ts +29 -0
  148. package/routes/schedule.ts +20 -0
  149. package/routes/search-client.js.ts +33 -0
  150. package/routes/search.json.ts +10 -0
  151. package/routes/share-image.png.ts +33 -0
  152. package/routes/sitemap-live.xml.ts +16 -0
  153. package/routes/sites.ts +11 -0
  154. package/routes/submit.ts +22 -0
@@ -0,0 +1,298 @@
1
+ import { FORM_CHALLENGE_FIELD } from './challenge.js';
2
+ import { NotFoundError, ValidationError, liveFields } from '@velocity-astro/cms-core';
3
+ /** The names a form's page sends beside its own fields. A field's key never starts with `_`. */
4
+ export const FORM_TRAP_FIELD = '_hp';
5
+ export const FORM_TOKEN_FIELD = '_t';
6
+ export const FORM_PAGE_FIELD = '_page';
7
+ export const FORM_LOCALE_FIELD = '_locale';
8
+ export const FORM_ABOUT_FIELD = '_about';
9
+ /** Holds the challenge's site key, so the form's script draws the challenge in a template that knows nothing of it. */
10
+ export const FORM_CHALLENGE_KEY_FIELD = '_challenge';
11
+ /** The largest post a form may send: plenty for words, far too little to fill a disk. */
12
+ export const MAX_FORM_POST_BYTES = 64 * 1024;
13
+ /** A person takes at least this long to fill in a form. What arrives sooner is suspected. */
14
+ const TOO_FAST_MS = 1500;
15
+ /** Counts posts per address in this server's memory: `limit` in any stretch of `windowMs`. */
16
+ export class MemoryRateLimiter {
17
+ limit;
18
+ windowMs;
19
+ now;
20
+ #taken = new Map();
21
+ constructor(limit = 8, windowMs = 10 * 60_000, now = Date.now) {
22
+ this.limit = limit;
23
+ this.windowMs = windowMs;
24
+ this.now = now;
25
+ }
26
+ /** `limit` is the most to take from one address just now, when it is not the one this was made with. */
27
+ take(address, limit = this.limit) {
28
+ const since = this.now() - this.windowMs;
29
+ // Forgets addresses that have gone quiet, so the list cannot grow without end.
30
+ if (this.#taken.size > 5000) {
31
+ for (const [known, times] of this.#taken)
32
+ if ((times.at(-1) ?? 0) <= since)
33
+ this.#taken.delete(known);
34
+ }
35
+ const times = (this.#taken.get(address) ?? []).filter((time) => time > since);
36
+ if (times.length >= limit) {
37
+ this.#taken.set(address, times);
38
+ return false;
39
+ }
40
+ this.#taken.set(address, [...times, this.now()]);
41
+ return true;
42
+ }
43
+ }
44
+ export const englishFormPostWords = {
45
+ sentTitle: 'Thank you',
46
+ sentMessage: 'Your message was sent.',
47
+ problemsTitle: 'A few answers need another look',
48
+ problemsHelp: 'Use your browser\'s Back button to return to the form. What you typed is still there.',
49
+ back: 'Back to the page',
50
+ tooMany: 'Too many messages were sent from here in a short time. Wait a few minutes and try again.',
51
+ tooLarge: 'That is more than this form can take. Shorten your message and try again.',
52
+ notAForm: 'This form is not taking messages.',
53
+ elsewhere: 'This form can only be sent from the site it is on.',
54
+ };
55
+ const encoder = new TextEncoder();
56
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
57
+ const escaped = (text) => text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
58
+ const isOwnPath = (page) => typeof page === 'string' && page.length <= 300 && /^\/(?!\/)[^\s\\]*$/.test(page);
59
+ const inLanguage = (text, locale) => text === undefined ? undefined : ((locale !== undefined ? text[locale] : undefined) ?? text['en'] ?? Object.values(text)[0]);
60
+ /**
61
+ * Takes what visitors send through the site's forms. It is the one address of the CMS that
62
+ * anyone may post to, so it is narrow: a small body, only from the site's own pages, only so
63
+ * many from one address, and nothing that was sent is ever written back into a page.
64
+ */
65
+ export class FormPosts {
66
+ #options;
67
+ #limiter;
68
+ #words;
69
+ #now;
70
+ constructor(options) {
71
+ this.#options = options;
72
+ this.#limiter = options.limiter ?? new MemoryRateLimiter();
73
+ this.#words = options.words ?? englishFormPostWords;
74
+ this.#now = options.now ?? Date.now;
75
+ }
76
+ /**
77
+ * The mark a form's page sends back with a post: when the form was drawn, signed. A post
78
+ * without a true one, or one that follows it too closely, did not come from a person filling
79
+ * in the page. `undefined` when the site has no secret to sign with.
80
+ */
81
+ token(formKey) {
82
+ return formToken(this.#options.secret, formKey, this.#now());
83
+ }
84
+ /** Answers a post to a form's address. `address` is where it came from, when the server knows. */
85
+ async handle(request, formKey, address) {
86
+ const wantsJson = (request.headers.get('accept') ?? '').includes('application/json') || (request.headers.get('content-type') ?? '').includes('application/json');
87
+ const refuse = (status, code, message, extra = {}) => wantsJson
88
+ ? Response.json({ error: { code, message } }, { status, headers: { 'cache-control': 'no-store', ...extra } })
89
+ : this.#page(status, this.#words.problemsTitle, [message], undefined, extra);
90
+ if (request.method !== 'POST')
91
+ return refuse(405, 'method_not_allowed', this.#words.notAForm, { allow: 'POST' });
92
+ // A browser says where a post comes from. One that names another site is not from a page of this one.
93
+ const origin = typeof this.#options.origin === 'string' ? this.#options.origin : this.#options.origin(request);
94
+ const from = request.headers.get('origin');
95
+ if (from !== null && from !== origin)
96
+ return refuse(403, 'forbidden', this.#words.elsewhere);
97
+ if (address !== undefined && !(await this.#limiter.take(address)))
98
+ return refuse(429, 'too_many', this.#words.tooMany, { 'retry-after': '600' });
99
+ const sent = await readPost(request);
100
+ if (sent === 'too-large')
101
+ return refuse(413, 'too_large', this.#words.tooLarge);
102
+ if (sent === null)
103
+ return refuse(415, 'unsupported', this.#words.notAForm);
104
+ const page = isOwnPath(sent[FORM_PAGE_FIELD]) ? sent[FORM_PAGE_FIELD] : undefined;
105
+ const locale = typeof sent[FORM_LOCALE_FIELD] === 'string' ? sent[FORM_LOCALE_FIELD] : undefined;
106
+ const suspected = (typeof sent[FORM_TRAP_FIELD] === 'string' && sent[FORM_TRAP_FIELD] !== '') ||
107
+ !(await this.#drawnForAPerson(formKey, sent[FORM_TOKEN_FIELD])) ||
108
+ // Asked last: a post already suspected is not worth a question to another service.
109
+ !((await this.#options.challenge?.passed(sent[FORM_CHALLENGE_FIELD])) ?? true);
110
+ // A page that cannot be looked up costs the submission nothing but its subject.
111
+ const about = (await this.#marked(formKey, sent[FORM_ABOUT_FIELD])) ?? (page === undefined ? undefined : await this.#options.entryAt?.(page).catch(() => undefined));
112
+ try {
113
+ const { submission, form } = await this.#options.cms.submissions.receive(formKey, sent, { suspected, ...(page !== undefined && { page }), ...(locale !== undefined && { locale }), ...(about !== undefined && { about }) });
114
+ // Whoever the form names is told. A notice that cannot be sent never loses the submission.
115
+ if (submission.status === 'new')
116
+ await this.#notify(form, submission, origin);
117
+ }
118
+ catch (error) {
119
+ if (error instanceof NotFoundError)
120
+ return refuse(404, 'not_found', this.#words.notAForm);
121
+ if (!(error instanceof ValidationError))
122
+ throw error;
123
+ if (wantsJson) {
124
+ return Response.json({ error: { code: error.code, message: error.message, issues: error.issues } }, { status: 422, headers: { 'cache-control': 'no-store' } });
125
+ }
126
+ // The form's own labels and the checks' own words: nothing the visitor typed.
127
+ const form = await this.#options.cms.forms.forSite(formKey);
128
+ const lines = error.issues.map((issue) => {
129
+ const field = form?.fields.find((candidate) => candidate.key === issue.path[0]);
130
+ return `${inLanguage(field?.label, locale) ?? String(issue.path[0] ?? '')}: ${issue.message}`;
131
+ });
132
+ return this.#page(422, this.#words.problemsTitle, [...lines, this.#words.problemsHelp], page);
133
+ }
134
+ const form = await this.#options.cms.forms.forSite(formKey);
135
+ const message = inLanguage(form?.success, locale) ?? this.#words.sentMessage;
136
+ return wantsJson
137
+ ? Response.json({ ok: true, message }, { headers: { 'cache-control': 'no-store' } })
138
+ : this.#page(200, this.#words.sentTitle, [message], page ?? '/');
139
+ }
140
+ async #notify(form, submission, origin) {
141
+ const { mailer, siteName, onFault } = this.#options;
142
+ if (form.notify.length === 0)
143
+ return;
144
+ if (!mailer) {
145
+ onFault?.(new Error(`The form "${form.key}" was sent, and nobody was emailed: no email provider is set up. The submission is kept in the CMS.`));
146
+ return;
147
+ }
148
+ const answers = liveFields(form.fields).flatMap((field) => {
149
+ const value = submission.data[field.id];
150
+ if (value === undefined)
151
+ return [];
152
+ return [{ label: inLanguage(field.label, submission.locale) ?? field.key, value: value === true ? '✓' : String(value) }];
153
+ });
154
+ const notice = {
155
+ siteName,
156
+ formName: inLanguage(form.label, submission.locale) ?? form.key,
157
+ answers,
158
+ ...(submission.page !== undefined && { page: `${origin}${submission.page}` }),
159
+ ...(submission.email !== undefined && { replyTo: submission.email }),
160
+ };
161
+ for (const to of form.notify) {
162
+ // The fault is told without the notice: a log is not the place for what a visitor wrote.
163
+ await mailer.sendSubmissionNotice({ ...notice, to }).catch((error) => onFault?.(new Error(`A notice for the form "${form.key}" could not be sent. ${error instanceof Error ? error.message : ''}`)));
164
+ }
165
+ }
166
+ /** Whether the post carries a true mark of when its form was drawn, from long enough ago. */
167
+ async #drawnForAPerson(formKey, token) {
168
+ if (this.#options.secret === undefined)
169
+ return true;
170
+ if (typeof token !== 'string')
171
+ return false;
172
+ const [drawn = '', signature = ''] = token.split('.');
173
+ if (!/^\d{1,16}$/.test(drawn) || !/^[0-9a-f]{64}$/.test(signature))
174
+ return false;
175
+ const expected = await this.#sign(formKey, drawn);
176
+ if (expected === undefined || !sameText(expected, signature))
177
+ return false;
178
+ return this.#now() - Number(drawn) >= TOO_FAST_MS;
179
+ }
180
+ async #sign(formKey, drawn) {
181
+ const { secret } = this.#options;
182
+ return secret === undefined ? undefined : sign(secret, `form:${formKey}:${drawn}`);
183
+ }
184
+ /** The entry a form's page said it is about, when the mark is one this site signed for this form. */
185
+ async #marked(formKey, mark) {
186
+ const { secret } = this.#options;
187
+ if (secret === undefined || typeof mark !== 'string' || mark.length > 400)
188
+ return undefined;
189
+ const [typeId = '', entry = '', signature = ''] = mark.split('.');
190
+ if (!ID.test(typeId) || !ID.test(entry) || !/^[0-9a-f]{64}$/.test(signature))
191
+ return undefined;
192
+ return sameText(await sign(secret, aboutText(formKey, typeId, entry)), signature) ? { typeId, entry } : undefined;
193
+ }
194
+ /** A plain page for a visitor whose browser runs no scripts. Every word in it is the site's own, escaped. */
195
+ #page(status, title, lines, back, headers = {}) {
196
+ const html = [
197
+ '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">',
198
+ `<title>${escaped(title)} · ${escaped(this.#options.siteName)}</title>`,
199
+ '<style>body{margin:0;font:1rem/1.6 system-ui,sans-serif;color:#1a1a1a;background:#fafafa}main{max-width:32rem;margin:15vh auto;padding:0 1.5rem}h1{font-size:1.5rem;margin:0 0 1rem}p{margin:0 0 .75rem}a{color:inherit}@media(prefers-color-scheme:dark){body{color:#eee;background:#111}}</style>',
200
+ `</head><body><main><h1>${escaped(title)}</h1>`,
201
+ ...lines.map((line) => `<p>${escaped(line)}</p>`),
202
+ back === undefined ? '' : `<p><a href="${escaped(back)}">${escaped(this.#words.back)}</a></p>`,
203
+ '</main></body></html>',
204
+ ].join('');
205
+ return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'", ...headers } });
206
+ }
207
+ }
208
+ async function sign(secret, text) {
209
+ const key = await globalThis.crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
210
+ return hex(await globalThis.crypto.subtle.sign('HMAC', key, encoder.encode(text)));
211
+ }
212
+ /** What an id may be made of, so a mark splits into its parts one way only. */
213
+ const ID = /^[A-Za-z0-9_-]{1,100}$/;
214
+ const aboutText = (formKey, typeId, entry) => `about:${formKey}:${typeId}:${entry}`;
215
+ /**
216
+ * The mark a form's page sends along to say which entry it is about, signed with the site's
217
+ * secret so that only the site's own pages can say it. `undefined` without a secret, or for ids
218
+ * a mark cannot carry.
219
+ */
220
+ export async function aboutMark(secret, formKey, about) {
221
+ if (secret === undefined || !ID.test(about.typeId) || !ID.test(about.entry))
222
+ return undefined;
223
+ return `${about.typeId}.${about.entry}.${await sign(secret, aboutText(formKey, about.typeId, about.entry))}`;
224
+ }
225
+ /** The mark for a form drawn at `drawn`, signed with the site's secret. `undefined` without a secret. */
226
+ export async function formToken(secret, formKey, drawn = Date.now()) {
227
+ return secret === undefined ? undefined : `${drawn}.${await sign(secret, `form:${formKey}:${drawn}`)}`;
228
+ }
229
+ /** Compares two texts of the same length without stopping at the first difference. */
230
+ function sameText(a, b) {
231
+ if (a.length !== b.length)
232
+ return false;
233
+ let difference = 0;
234
+ for (let index = 0; index < a.length; index += 1)
235
+ difference |= a.charCodeAt(index) ^ b.charCodeAt(index);
236
+ return difference === 0;
237
+ }
238
+ /**
239
+ * What a post holds, by name: a plain form's fields or a script's JSON. `null` for a body that
240
+ * is neither, `too-large` for one over the limit. Files are left out: forms take none yet.
241
+ */
242
+ async function readPost(request) {
243
+ const type = request.headers.get('content-type') ?? '';
244
+ if (Number(request.headers.get('content-length') ?? 0) > MAX_FORM_POST_BYTES)
245
+ return 'too-large';
246
+ const bytes = await readLimited(request);
247
+ if (bytes === null)
248
+ return 'too-large';
249
+ if (type.includes('application/json')) {
250
+ try {
251
+ const body = JSON.parse(new TextDecoder().decode(bytes));
252
+ return typeof body === 'object' && body !== null && !Array.isArray(body) ? { ...body } : null;
253
+ }
254
+ catch {
255
+ return null;
256
+ }
257
+ }
258
+ if (!type.includes('application/x-www-form-urlencoded') && !type.includes('multipart/form-data'))
259
+ return null;
260
+ try {
261
+ const data = await new Response(bytes, { headers: { 'content-type': type } }).formData();
262
+ const sent = {};
263
+ for (const [name, value] of data)
264
+ if (typeof value === 'string')
265
+ sent[name] = value;
266
+ return sent;
267
+ }
268
+ catch {
269
+ return null;
270
+ }
271
+ }
272
+ /** The body, or `null` once it has passed the limit, however long it said it was. */
273
+ async function readLimited(request) {
274
+ if (!request.body)
275
+ return new Uint8Array();
276
+ const reader = request.body.getReader();
277
+ const chunks = [];
278
+ let size = 0;
279
+ for (;;) {
280
+ const { done, value } = await reader.read();
281
+ if (done)
282
+ break;
283
+ size += value.byteLength;
284
+ if (size > MAX_FORM_POST_BYTES) {
285
+ await reader.cancel();
286
+ return null;
287
+ }
288
+ chunks.push(value);
289
+ }
290
+ const bytes = new Uint8Array(size);
291
+ let offset = 0;
292
+ for (const chunk of chunks) {
293
+ bytes.set(chunk, offset);
294
+ offset += chunk.byteLength;
295
+ }
296
+ return bytes;
297
+ }
298
+ //# sourceMappingURL=form-post.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form-post.js","sourceRoot":"","sources":["../src/form-post.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAuB,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,UAAU,EAAiF,MAAM,0BAA0B,CAAC;AAErK,gGAAgG;AAChG,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AACrC,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AACrC,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC;AACvC,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAS,CAAC;AAC3C,MAAM,CAAC,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AACzC,uHAAuH;AACvH,MAAM,CAAC,MAAM,wBAAwB,GAAG,YAAY,CAAC;AAErD,yFAAyF;AACzF,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7C,6FAA6F;AAC7F,MAAM,WAAW,GAAG,IAAI,CAAC;AAWzB,8FAA8F;AAC9F,MAAM,OAAO,iBAAiB;IAIT;IACA;IACA;IALV,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;IAE9C,YACmB,QAAQ,CAAC,EACT,WAAW,EAAE,GAAG,MAAM,EACtB,MAAoB,IAAI,CAAC,GAAG;QAF5B,UAAK,GAAL,KAAK,CAAI;QACT,aAAQ,GAAR,QAAQ,CAAc;QACtB,QAAG,GAAH,GAAG,CAAyB;IAC5C,CAAC;IAEJ,wGAAwG;IACxG,IAAI,CAAC,OAAe,EAAE,QA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B,IAAI,IAAI,GAAG,mBAAmB,EAAE,CAAC;YAC/B,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACrB,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,UAAU,CAAC;IAC7B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,76 @@
1
+ import type { MiddlewareHandler } from 'astro';
2
+ import type { MediaStore } from '@velocity-astro/cms-core';
3
+ /**
4
+ * One site among many that a single running copy of a template serves. Everything that sets one
5
+ * site apart from the next is here: nothing of a hosted site is read from the environment.
6
+ */
7
+ export interface HostedSite {
8
+ /** The site's permanent name with its host: letters, digits and dashes. It is never shown. */
9
+ readonly id: string;
10
+ /** The address links, sign-in and passkeys are made for: `https://example.com`. */
11
+ readonly origin: string;
12
+ /** The site's own database. No two sites share one. */
13
+ readonly database: {
14
+ readonly url: string;
15
+ readonly authToken?: string;
16
+ };
17
+ /** The site's own secret, at least 32 characters. It signs previews and seals plugin secrets. */
18
+ readonly secret: string;
19
+ /** The site's name, shown in the editor and in sign-in emails. */
20
+ readonly name?: string;
21
+ /** Where the site's uploads are kept, apart from every other site's. Without it the site takes none. */
22
+ readonly media?: MediaStore;
23
+ }
24
+ /**
25
+ * How a host that runs many sites tells them apart. The registry, and nothing a visitor sends,
26
+ * decides which site an address belongs to: a host name it does not know has no site.
27
+ */
28
+ export interface SiteRegistry {
29
+ /** The site at this host name (`example.com`, `example.com:8080`), or `null` when there is none. */
30
+ find(host: string): Promise<HostedSite | null> | HostedSite | null;
31
+ }
32
+ /** A request, or other work, reached for a site's content when no site was chosen for it. */
33
+ export declare class NoSiteError extends Error {
34
+ constructor();
35
+ }
36
+ /**
37
+ * Tells the CMS that this server runs many sites. From then on nothing is read for "the" site.
38
+ * `undefined` takes it back, which only a test does.
39
+ */
40
+ export declare function useSiteRegistry(sites: SiteRegistry | undefined): void;
41
+ /** Whether this server runs many sites. */
42
+ export declare const isHosted: () => boolean;
43
+ /**
44
+ * The site this work is for. `undefined` on a server that runs one site, which reads its
45
+ * settings from the environment as ever. On a server that runs many, work begun for no site
46
+ * throws: it must never fall back to some site's content.
47
+ */
48
+ export declare function currentSite(): HostedSite | undefined;
49
+ /** The site at a host name, or `null`. On a server that runs one site there is nothing to find. */
50
+ export declare function siteAt(host: string): Promise<HostedSite | null>;
51
+ /** Runs work for one site: whatever it reads and writes is that site's and no other's. */
52
+ export declare const inSite: <Result>(site: HostedSite, work: () => Result) => Result;
53
+ /**
54
+ * The tag every kept page of the site carries, which a publish clears. One site's publish never
55
+ * clears another's pages.
56
+ */
57
+ export declare const siteCacheTag: () => string;
58
+ /** The key state kept per site in this server's memory is filed under. */
59
+ export declare const siteKey: () => string;
60
+ /**
61
+ * A response whose body is read inside the site's work. Astro draws a page as its response is
62
+ * read, which happens after the middleware has returned: without this the rest of the page
63
+ * would be drawn for no site.
64
+ */
65
+ export declare function readInSite(site: HostedSite, response: Response): Response;
66
+ /**
67
+ * On a server that runs many sites, chooses the site a request is for before anything else runs.
68
+ * A host name the registry does not know is answered as nothing at all: there is no site to
69
+ * fall back to. On a server that runs one site this does nothing.
70
+ *
71
+ * The host name is the request's own, which is what a host that runs many sites routes by: it
72
+ * says which site is asked for, never what that site's links are made for. Those come from the
73
+ * registry (`HostedSite.origin`).
74
+ */
75
+ export declare const hostedRequest: MiddlewareHandler;
76
+ //# sourceMappingURL=hosted.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted.d.ts","sourceRoot":"","sources":["../src/hosted.ts"],"names":[],"mappings":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MAAM,MAAM,MAAM,KAAG,MAA0C,CAAC;AAEjH;;;GAGG;AACH,eAAO,MAAM,YAAY,QAAO,MAG/B,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,OAAO,QAAO,MAAiC,CAAC;AAE7D;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAazE;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa,EAAE,iBAS3B,CAAC"}
package/dist/hosted.js ADDED
@@ -0,0 +1,104 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ /** A request, or other work, reached for a site's content when no site was chosen for it. */
3
+ export class NoSiteError extends Error {
4
+ constructor() {
5
+ super('This server runs many sites, and this work was not begun for any one of them. Content is read only inside a request for a known site.');
6
+ }
7
+ }
8
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
9
+ const current = new AsyncLocalStorage();
10
+ let registry;
11
+ /**
12
+ * Tells the CMS that this server runs many sites. From then on nothing is read for "the" site.
13
+ * `undefined` takes it back, which only a test does.
14
+ */
15
+ export function useSiteRegistry(sites) {
16
+ registry = sites;
17
+ }
18
+ /** Whether this server runs many sites. */
19
+ export const isHosted = () => registry !== undefined;
20
+ /**
21
+ * The site this work is for. `undefined` on a server that runs one site, which reads its
22
+ * settings from the environment as ever. On a server that runs many, work begun for no site
23
+ * throws: it must never fall back to some site's content.
24
+ */
25
+ export function currentSite() {
26
+ if (!registry)
27
+ return undefined;
28
+ const site = current.getStore();
29
+ if (!site)
30
+ throw new NoSiteError();
31
+ return site;
32
+ }
33
+ /** A site as the registry gave it, checked before anything is opened for it. */
34
+ function checked(site) {
35
+ if (!ID.test(site.id))
36
+ throw new Error(`"${site.id}" cannot be a site's id. Use lower-case letters, digits and dashes.`);
37
+ if (!URL.canParse(site.origin))
38
+ throw new Error(`The site "${site.id}" has no address the CMS can make links for.`);
39
+ if (site.secret.length < 32)
40
+ throw new Error(`The secret of the site "${site.id}" is shorter than 32 characters.`);
41
+ return site;
42
+ }
43
+ /** The site at a host name, or `null`. On a server that runs one site there is nothing to find. */
44
+ export async function siteAt(host) {
45
+ if (!registry)
46
+ return null;
47
+ const site = await registry.find(host.toLowerCase());
48
+ return site ? checked(site) : null;
49
+ }
50
+ /** Runs work for one site: whatever it reads and writes is that site's and no other's. */
51
+ export const inSite = (site, work) => current.run(checked(site), work);
52
+ /**
53
+ * The tag every kept page of the site carries, which a publish clears. One site's publish never
54
+ * clears another's pages.
55
+ */
56
+ export const siteCacheTag = () => {
57
+ const site = currentSite();
58
+ return site ? `cms-site:${site.id}` : 'cms';
59
+ };
60
+ /** The key state kept per site in this server's memory is filed under. */
61
+ export const siteKey = () => currentSite()?.id ?? '';
62
+ /**
63
+ * A response whose body is read inside the site's work. Astro draws a page as its response is
64
+ * read, which happens after the middleware has returned: without this the rest of the page
65
+ * would be drawn for no site.
66
+ */
67
+ export function readInSite(site, response) {
68
+ if (!response.body)
69
+ return response;
70
+ const reader = response.body.getReader();
71
+ const body = new ReadableStream({
72
+ pull: (controller) => inSite(site, async () => {
73
+ const { done, value } = await reader.read();
74
+ if (done)
75
+ controller.close();
76
+ else
77
+ controller.enqueue(value);
78
+ }),
79
+ cancel: (reason) => inSite(site, () => reader.cancel(reason)),
80
+ });
81
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
82
+ }
83
+ /**
84
+ * On a server that runs many sites, chooses the site a request is for before anything else runs.
85
+ * A host name the registry does not know is answered as nothing at all: there is no site to
86
+ * fall back to. On a server that runs one site this does nothing.
87
+ *
88
+ * The host name is the request's own, which is what a host that runs many sites routes by: it
89
+ * says which site is asked for, never what that site's links are made for. Those come from the
90
+ * registry (`HostedSite.origin`).
91
+ */
92
+ export const hostedRequest = async (context, next) => {
93
+ if (!isHosted() || context.isPrerendered)
94
+ return next();
95
+ const site = await siteAt(context.url.host);
96
+ if (!site)
97
+ return new Response('There is no site at this address.', { status: 404, headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8' } });
98
+ return inSite(site, async () => {
99
+ // A page kept for this site is cleared by this site's publish and by no other's.
100
+ context.cache.set({ tags: [siteCacheTag()] });
101
+ return readInSite(site, await next());
102
+ });
103
+ };
104
+ //# sourceMappingURL=hosted.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted.js","sourceRoot":"","sources":["../src/hosted.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAgCrD,6FAA6F;AAC7F,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC;QACE,KAAK,CAAC,uIAAuI,CAAC,CAAC;IACjJ,CAAC;CACF;AAED,MAAM,EAAE,GAAG,4BAA4B,CAAC;AAExC,MAAM,OAAO,GAAG,IAAI,iBAAiB,EAAc,CAAC;AACpD,IAAI,QAAkC,CAAC;AAEvC;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,KAA+B;IAC7D,QAAQ,GAAG,KAAK,CAAC;AACnB,CAAC;AAED,2CAA2C;AAC3C,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAY,EAAE,CAAC,QAAQ,KAAK,SAAS,CAAC;AAE9D;;;;GAIG;AACH,MAAM,UAAU,WAAW;IACzB,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChC,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAChC,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,WAAW,EAAE,CAAC;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAED,gFAAgF;AAChF,SAAS,OAAO,CAAC,IAAgB;IAC/B,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,IAAI,IAAI,CAAC,EAAE,qEAAqE,CAAC,CAAC;IACzH,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,C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;QACjF,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,YAAY,EAAE,CAAC,EAAE,CAAC,CAAC;QAC9C,OAAO,UAAU,CAAC,IAAI,EAAE,MAAM,IAAI,EAAE,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC"}
@@ -0,0 +1,35 @@
1
+ import type sharp from 'sharp';
2
+ import { type ImageOptimizer } from '@velocity-astro/cms-core';
3
+ /** Only its type is named here: the library itself is loaded when the first image arrives. */
4
+ type Sharp = typeof sharp;
5
+ export interface SharpImageOptimizerOptions {
6
+ /** Loads the library. Defaults to the `sharp` package, which comes with Astro. */
7
+ readonly load?: () => Promise<Sharp>;
8
+ /** Hears, once, that the library could not be loaded. Defaults to a line in the server's log. */
9
+ readonly onUnavailable?: (error: unknown) => void;
10
+ }
11
+ /**
12
+ * Makes uploads lighter with sharp, the library Astro itself resizes images with. It runs
13
+ * wherever Node does: a server of your own, and the functions of hosts such as Vercel.
14
+ *
15
+ * Where it cannot be loaded (a runtime that is not Node, or a machine it has no build for),
16
+ * nothing is optimized and nothing breaks: every method answers `null`, which the media
17
+ * service reads as "keep the image as it is".
18
+ */
19
+ export declare class SharpImageOptimizer implements ImageOptimizer {
20
+ #private;
21
+ constructor(options?: SharpImageOptimizerOptions);
22
+ /**
23
+ * A photo becomes a WebP at a quality nobody tells from the original. A PNG is tried both
24
+ * ways, exact and nearly exact, and the lighter is kept: a logo or a screenshot packs best
25
+ * exactly and stays crisp, a photo saved as a PNG packs best the other way. See-through
26
+ * parts stay see-through.
27
+ *
28
+ * A WebP that already fits is left alone, since packing it again would only wear it, and so
29
+ * is one that moves, which would stop.
30
+ */
31
+ optimize(bytes: Uint8Array): Promise<Uint8Array | null>;
32
+ resize(bytes: Uint8Array, width: number): Promise<Uint8Array | null>;
33
+ }
34
+ export {};
35
+ //# sourceMappingURL=image-optimizer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-optimizer.d.ts","sourceRoot":"","sources":["../src/image-optimizer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAEnF,8FAA8F;AAC9F,KAAK,KAAK,GAAG,OAAO,KAAK,CAAC;AAW1B,MAAM,WAAW,0BAA0B;IACzC,kFAAkF;IAClF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IACrC,iGAAiG;IACjG,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;CACnD;AAED;;;;;;;GAOG;AACH,qBAAa,mBAAoB,YAAW,cAAc;;gBAI5C,OAAO,GAAE,0BAA+B;IAIpD;;;;;;;;OAQG;IACG,QAAQ,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;IAoBvD,MAAM,CAAC,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;CAgB3E"}
@@ -0,0 +1,76 @@
1
+ import { IMAGE_LONGEST_SIDE } from '@velocity-astro/cms-core';
2
+ /** How closely a photo is kept: past this nobody sees the difference, and the file only grows. */
3
+ const PHOTO_QUALITY = 80;
4
+ /** A PNG is often a drawing with sharp edges, which show a loss sooner than a photo does. */
5
+ const DRAWING_QUALITY = 90;
6
+ /** How hard the encoder works, from 0 to 6. Four is where more time stops buying much. */
7
+ const EFFORT = 4;
8
+ /** The most pixels an image is opened with: the service refuses a longer side than 12,000 itself. */
9
+ const MAX_PIXELS = 12_000 * 12_000;
10
+ /**
11
+ * Makes uploads lighter with sharp, the library Astro itself resizes images with. It runs
12
+ * wherever Node does: a server of your own, and the functions of hosts such as Vercel.
13
+ *
14
+ * Where it cannot be loaded (a runtime that is not Node, or a machine it has no build for),
15
+ * nothing is optimized and nothing breaks: every method answers `null`, which the media
16
+ * service reads as "keep the image as it is".
17
+ */
18
+ export class SharpImageOptimizer {
19
+ #options;
20
+ #sharp;
21
+ constructor(options = {}) {
22
+ this.#options = options;
23
+ }
24
+ /**
25
+ * A photo becomes a WebP at a quality nobody tells from the original. A PNG is tried both
26
+ * ways, exact and nearly exact, and the lighter is kept: a logo or a screenshot packs best
27
+ * exactly and stays crisp, a photo saved as a PNG packs best the other way. See-through
28
+ * parts stay see-through.
29
+ *
30
+ * A WebP that already fits is left alone, since packing it again would only wear it, and so
31
+ * is one that moves, which would stop.
32
+ */
33
+ async optimize(bytes) {
34
+ const library = await this.#library();
35
+ if (!library)
36
+ return null;
37
+ const open = () => library(bytes, { limitInputPixels: MAX_PIXELS });
38
+ const facts = await open().metadata();
39
+ if ((facts.pages ?? 1) > 1)
40
+ return null;
41
+ const turned = (facts.orientation ?? 1) > 1;
42
+ const fits = Math.max(facts.width, facts.height) <= IMAGE_LONGEST_SIDE;
43
+ if (facts.format === 'webp' && fits && !turned)
44
+ return null;
45
+ // Turned the way it was taken first, since what the camera noted about that is not kept.
46
+ const ready = () => open().rotate().resize({ width: IMAGE_LONGEST_SIDE, height: IMAGE_LONGEST_SIDE, fit: 'inside', withoutEnlargement: true });
47
+ if (facts.format !== 'png')
48
+ return ready().webp({ quality: PHOTO_QUALITY, effort: EFFORT }).toBuffer();
49
+ const [exact, close] = await Promise.all([
50
+ ready().webp({ lossless: true, effort: EFFORT }).toBuffer(),
51
+ ready().webp({ quality: DRAWING_QUALITY, effort: EFFORT }).toBuffer(),
52
+ ]);
53
+ return exact.length <= close.length ? exact : close;
54
+ }
55
+ async resize(bytes, width) {
56
+ const library = await this.#library();
57
+ if (!library)
58
+ return null;
59
+ const open = () => library(bytes, { limitInputPixels: MAX_PIXELS });
60
+ if (((await open().metadata()).pages ?? 1) > 1)
61
+ return null;
62
+ return open().rotate().resize({ width, withoutEnlargement: true }).webp({ quality: PHOTO_QUALITY, effort: EFFORT }).toBuffer();
63
+ }
64
+ /** The library, loaded the first time an image arrives, or `null` on a machine that has none. */
65
+ #library() {
66
+ const load = this.#options.load ?? (async () => (await import('sharp')).default);
67
+ return (this.#sharp ??= load().catch((error) => {
68
+ (this.#options.onUnavailable ?? unavailable)(error);
69
+ return null;
70
+ }));
71
+ }
72
+ }
73
+ function unavailable(error) {
74
+ console.warn('[velocity-cms] Uploads are kept as they arrive, since the image library "sharp" could not be loaded. Install it (`npm install sharp`) to have them made lighter.', error);
75
+ }
76
+ //# sourceMappingURL=image-optimizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-optimizer.js","sourceRoot":"","sources":["../src/image-optimizer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,0BAA0B,CAAC;AAKnF,kGAAkG;AAClG,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,6FAA6F;AAC7F,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,0FAA0F;AAC1F,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,qGAAqG;AACrG,MAAM,UAAU,GAAG,MAAM,GAAG,MAAM,CAAC;AASnC;;;;;;;GAOG;AACH,MAAM,OAAO,mBAAmB;IACrB,QAAQ,CAA6B;IAC9C,MAAM,CAAoC;IAE1C,YAAY,UAAsC,EAAE;QAClD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,QAAQ,CAAC,KAAiB;QAC9B,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;QACtC,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,CAAC;QAC1B,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,gBAAgB,EAAE,UAAU,EAAE,CAAC,CAAC;QACpE,MAAM,KAAK,GAAG,MAAM,IAAI,EAAE,CAAC,QAAQ,EAAE,CAAC;QACtC,IAAI,CA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