zastro-websockets-cloudflare 0.0.0-729d313

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.
@@ -0,0 +1,175 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import * as url from "node:url";
4
+ function cloudflareModuleLoader(enabled) {
5
+ const adaptersByExtension = enabled ? { ...defaultAdapters } : {};
6
+ const extensions = Object.keys(adaptersByExtension);
7
+ let isDev = false;
8
+ const MAGIC_STRING = "__CLOUDFLARE_ASSET__";
9
+ const replacements = [];
10
+ return {
11
+ name: "vite:cf-module-loader",
12
+ enforce: "pre",
13
+ configResolved(config) {
14
+ isDev = config.command === "serve";
15
+ },
16
+ config(_, __) {
17
+ return {
18
+ assetsInclude: extensions.map((x) => `**/*${x}`),
19
+ build: {
20
+ rollupOptions: {
21
+ // mark the wasm files as external so that they are not bundled and instead are loaded from the files
22
+ external: extensions.map(
23
+ (x) => new RegExp(`^${MAGIC_STRING}.+${escapeRegExp(x)}.mjs$`, "i")
24
+ )
25
+ }
26
+ }
27
+ };
28
+ },
29
+ async load(id, _) {
30
+ const maybeExtension = extensions.find((x) => id.endsWith(x));
31
+ const moduleType = maybeExtension && adaptersByExtension[maybeExtension] || void 0;
32
+ if (!moduleType || !maybeExtension) {
33
+ return;
34
+ }
35
+ if (!enabled) {
36
+ throw new Error(
37
+ `Cloudflare module loading is experimental. The ${maybeExtension} module cannot be loaded unless you add \`cloudflareModules: true\` to your astro config.`
38
+ );
39
+ }
40
+ const moduleLoader = renderers[moduleType];
41
+ const filePath = id.replace(/\?\w+$/, "");
42
+ const extension = maybeExtension.replace(/\?\w+$/, "");
43
+ const data = await fs.readFile(filePath);
44
+ const base64 = data.toString("base64");
45
+ const inlineModule = moduleLoader(data);
46
+ if (isDev) {
47
+ return inlineModule;
48
+ }
49
+ const hash = hashString(base64);
50
+ const assetName = `${path.basename(filePath).split(".")[0]}.${hash}${extension}`;
51
+ this.emitFile({
52
+ type: "asset",
53
+ // emit the data explicitly as an esset with `fileName` rather than `name` so that
54
+ // vite doesn't give it a random hash-id in its name--We need to be able to easily rewrite from
55
+ // the .mjs loader and the actual wasm asset later in the ESbuild for the worker
56
+ fileName: assetName,
57
+ source: data
58
+ });
59
+ const chunkId = this.emitFile({
60
+ type: "prebuilt-chunk",
61
+ fileName: `${assetName}.mjs`,
62
+ code: inlineModule
63
+ });
64
+ return `import module from "${MAGIC_STRING}${chunkId}${extension}.mjs";export default module;`;
65
+ },
66
+ // output original wasm file relative to the chunk now that chunking has been achieved
67
+ renderChunk(code, chunk, _) {
68
+ if (isDev) return;
69
+ if (!code.includes(MAGIC_STRING)) return;
70
+ let replaced = code;
71
+ for (const ext of extensions) {
72
+ const extension = ext.replace(/\?\w+$/, "");
73
+ replaced = replaced.replaceAll(
74
+ new RegExp(`${MAGIC_STRING}([^\\s]+?)${escapeRegExp(extension)}\\.mjs`, "g"),
75
+ (_s, assetId) => {
76
+ const fileName = this.getFileName(assetId);
77
+ const relativePath = path.relative(path.dirname(chunk.fileName), fileName).replaceAll("\\", "/");
78
+ replacements.push({
79
+ chunkName: chunk.name,
80
+ cloudflareImport: relativePath.replace(/\.mjs$/, ""),
81
+ nodejsImport: relativePath
82
+ });
83
+ return `./${relativePath}`;
84
+ }
85
+ );
86
+ }
87
+ return { code: replaced };
88
+ },
89
+ generateBundle(_, bundle) {
90
+ const replacementsByChunkName = /* @__PURE__ */ new Map();
91
+ for (const replacement of replacements) {
92
+ const repls = replacementsByChunkName.get(replacement.chunkName) || [];
93
+ if (!repls.length) {
94
+ replacementsByChunkName.set(replacement.chunkName, repls);
95
+ }
96
+ repls.push(replacement);
97
+ }
98
+ for (const chunk of Object.values(bundle)) {
99
+ const repls = chunk.name && replacementsByChunkName.get(chunk.name);
100
+ for (const replacement of repls || []) {
101
+ if (!replacement.fileName) {
102
+ replacement.fileName = [];
103
+ }
104
+ replacement.fileName.push(chunk.fileName);
105
+ }
106
+ }
107
+ },
108
+ /**
109
+ * Once prerendering is complete, restore the imports in the _worker.js to cloudflare compatible ones, removing the .mjs suffix.
110
+ */
111
+ async afterBuildCompleted(config) {
112
+ const baseDir = url.fileURLToPath(config.outDir);
113
+ const replacementsByFileName = /* @__PURE__ */ new Map();
114
+ for (const replacement of replacements) {
115
+ if (!replacement.fileName) {
116
+ continue;
117
+ }
118
+ for (const fileName of replacement.fileName) {
119
+ const repls = replacementsByFileName.get(fileName) || [];
120
+ if (!repls.length) {
121
+ replacementsByFileName.set(fileName, repls);
122
+ }
123
+ repls.push(replacement);
124
+ }
125
+ }
126
+ for (const [fileName, repls] of replacementsByFileName.entries()) {
127
+ const filepath = path.join(baseDir, "_worker.js", fileName);
128
+ const contents = await fs.readFile(filepath, "utf-8");
129
+ let updated = contents;
130
+ for (const replacement of repls) {
131
+ updated = updated.replaceAll(replacement.nodejsImport, replacement.cloudflareImport);
132
+ }
133
+ await fs.writeFile(filepath, updated, "utf-8");
134
+ }
135
+ }
136
+ };
137
+ }
138
+ const renderers = {
139
+ CompiledWasm(fileContents) {
140
+ const base64 = fileContents.toString("base64");
141
+ return `const wasmModule = new WebAssembly.Module(Uint8Array.from(atob("${base64}"), c => c.charCodeAt(0)));export default wasmModule;`;
142
+ },
143
+ Data(fileContents) {
144
+ const base64 = fileContents.toString("base64");
145
+ return `const binModule = Uint8Array.from(atob("${base64}"), c => c.charCodeAt(0)).buffer;export default binModule;`;
146
+ },
147
+ Text(fileContents) {
148
+ const escaped = JSON.stringify(fileContents.toString("utf-8"));
149
+ return `const stringModule = ${escaped};export default stringModule;`;
150
+ }
151
+ };
152
+ const defaultAdapters = {
153
+ // Loads '*.wasm?module' imports as WebAssembly modules, which is the only way to load WASM in cloudflare workers.
154
+ // Current proposal for WASM modules: https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration
155
+ ".wasm?module": "CompiledWasm",
156
+ // treats the module as a WASM module
157
+ ".wasm": "CompiledWasm",
158
+ ".bin": "Data",
159
+ ".txt": "Text"
160
+ };
161
+ function hashString(str) {
162
+ let hash = 0;
163
+ for (let i = 0; i < str.length; i++) {
164
+ const char = str.charCodeAt(i);
165
+ hash = (hash << 5) - hash + char;
166
+ hash &= hash;
167
+ }
168
+ return new Uint32Array([hash])[0].toString(36);
169
+ }
170
+ function escapeRegExp(string) {
171
+ return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
172
+ }
173
+ export {
174
+ cloudflareModuleLoader
175
+ };
@@ -0,0 +1,2 @@
1
+ import type { GetEnv } from 'astro/env/setup';
2
+ export declare const createGetEnv: (env: Record<string, unknown>) => GetEnv;
@@ -0,0 +1,13 @@
1
+ const createGetEnv = (env) => (key) => {
2
+ const v = env[key];
3
+ if (typeof v === "undefined" || typeof v === "string") {
4
+ return v;
5
+ }
6
+ if (typeof v === "boolean" || typeof v === "number") {
7
+ return v.toString();
8
+ }
9
+ return void 0;
10
+ };
11
+ export {
12
+ createGetEnv
13
+ };
@@ -0,0 +1,9 @@
1
+ import type { AstroConfig, AstroIntegrationLogger, IntegrationResolvedRoute, RoutePart } from 'astro';
2
+ export declare function getParts(part: string): RoutePart[];
3
+ export declare function createRoutesFile(_config: AstroConfig, logger: AstroIntegrationLogger, routes: IntegrationResolvedRoute[], pages: {
4
+ pathname: string;
5
+ }[], redirects: IntegrationResolvedRoute['segments'][], includeExtends: {
6
+ pattern: string;
7
+ }[] | undefined, excludeExtends: {
8
+ pattern: string;
9
+ }[] | undefined): Promise<void>;
@@ -0,0 +1,225 @@
1
+ import { existsSync } from "node:fs";
2
+ import { writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ prependForwardSlash,
7
+ removeLeadingForwardSlash,
8
+ removeTrailingForwardSlash
9
+ } from "@astrojs/internal-helpers/path";
10
+ import { glob } from "tinyglobby";
11
+ const ROUTE_DYNAMIC_SPLIT = /\[(.+?\(.+?\)|.+?)\]/;
12
+ const ROUTE_SPREAD = /^\.{3}.+$/;
13
+ function getParts(part) {
14
+ const result = [];
15
+ part.split(ROUTE_DYNAMIC_SPLIT).map((str, i) => {
16
+ if (!str) return;
17
+ const dynamic = i % 2 === 1;
18
+ const [, content] = dynamic ? /([^(]+)$/.exec(str) || [null, null] : [null, str];
19
+ if (!content || dynamic && !/^(?:\.\.\.)?[\w$]+$/.test(content)) {
20
+ throw new Error("Parameter name must match /^[a-zA-Z0-9_$]+$/");
21
+ }
22
+ result.push({
23
+ content,
24
+ dynamic,
25
+ spread: dynamic && ROUTE_SPREAD.test(content)
26
+ });
27
+ });
28
+ return result;
29
+ }
30
+ async function writeRoutesFileToOutDir(_config, logger, include, exclude) {
31
+ try {
32
+ await writeFile(
33
+ new URL("./_routes.json", _config.outDir),
34
+ JSON.stringify(
35
+ {
36
+ version: 1,
37
+ include,
38
+ exclude
39
+ },
40
+ null,
41
+ 2
42
+ ),
43
+ "utf-8"
44
+ );
45
+ } catch (_error) {
46
+ logger.error("There was an error writing the '_routes.json' file to the output directory.");
47
+ }
48
+ }
49
+ function segmentsToCfSyntax(segments, _config) {
50
+ const pathSegments = [];
51
+ if (removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)).length > 0) {
52
+ pathSegments.push(removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)));
53
+ }
54
+ for (const segment of segments.flat()) {
55
+ if (segment.dynamic) pathSegments.push("*");
56
+ else pathSegments.push(segment.content);
57
+ }
58
+ return pathSegments;
59
+ }
60
+ class TrieNode {
61
+ children = /* @__PURE__ */ new Map();
62
+ isEndOfPath = false;
63
+ hasWildcardChild = false;
64
+ }
65
+ class PathTrie {
66
+ root;
67
+ returnHasWildcard = false;
68
+ constructor() {
69
+ this.root = new TrieNode();
70
+ }
71
+ insert(thisPath) {
72
+ let node = this.root;
73
+ for (const segment of thisPath) {
74
+ if (segment === "*") {
75
+ node.hasWildcardChild = true;
76
+ break;
77
+ }
78
+ if (!node.children.has(segment)) {
79
+ node.children.set(segment, new TrieNode());
80
+ }
81
+ node = node.children.get(segment);
82
+ }
83
+ node.isEndOfPath = true;
84
+ }
85
+ /**
86
+ * Depth-first search (dfs), traverses the "graph" segment by segment until the end or wildcard (*).
87
+ * It makes sure that all necessary paths are returned, but not paths with an existing wildcard prefix.
88
+ * e.g. if we have a path like /foo/* and /foo/bar, we only want to return /foo/*
89
+ */
90
+ dfs(node, thisPath, allPaths) {
91
+ if (node.hasWildcardChild) {
92
+ this.returnHasWildcard = true;
93
+ allPaths.push([...thisPath, "*"]);
94
+ return;
95
+ }
96
+ if (node.isEndOfPath) {
97
+ allPaths.push([...thisPath]);
98
+ }
99
+ for (const [segment, childNode] of node.children) {
100
+ this.dfs(childNode, [...thisPath, segment], allPaths);
101
+ }
102
+ }
103
+ /**
104
+ * The reduce function is used to remove unnecessary paths from the trie.
105
+ * It receives a trie node to compare with the current node.
106
+ */
107
+ reduce(compNode, node) {
108
+ if (node.hasWildcardChild || compNode.hasWildcardChild) return;
109
+ for (const [segment, childNode] of node.children) {
110
+ if (childNode.children.size === 0) continue;
111
+ const compChildNode = compNode.children.get(segment);
112
+ if (compChildNode === void 0) {
113
+ childNode.hasWildcardChild = true;
114
+ continue;
115
+ }
116
+ this.reduce(compChildNode, childNode);
117
+ }
118
+ }
119
+ reduceAllPaths(compTrie) {
120
+ this.reduce(compTrie.root, this.root);
121
+ return this;
122
+ }
123
+ getAllPaths() {
124
+ const allPaths = [];
125
+ this.dfs(this.root, [], allPaths);
126
+ return [allPaths, this.returnHasWildcard];
127
+ }
128
+ }
129
+ async function createRoutesFile(_config, logger, routes, pages, redirects, includeExtends, excludeExtends) {
130
+ const includePaths = [];
131
+ const excludePaths = [];
132
+ const assetsPath = segmentsToCfSyntax(
133
+ [
134
+ [{ content: _config.build.assets, dynamic: false, spread: false }],
135
+ [{ content: "", dynamic: true, spread: false }]
136
+ ],
137
+ _config
138
+ );
139
+ excludePaths.push(assetsPath);
140
+ for (const redirect of redirects) {
141
+ excludePaths.push(segmentsToCfSyntax(redirect, _config));
142
+ }
143
+ if (existsSync(fileURLToPath(_config.publicDir))) {
144
+ const staticFiles = await glob(`**/*`, {
145
+ cwd: fileURLToPath(_config.publicDir),
146
+ dot: true
147
+ });
148
+ for (const staticFile of staticFiles) {
149
+ if (["_headers", "_redirects", "_routes.json"].includes(staticFile)) continue;
150
+ const staticPath = staticFile;
151
+ const segments = removeLeadingForwardSlash(staticPath).split(path.sep).filter(Boolean).map((s) => {
152
+ return getParts(s);
153
+ });
154
+ excludePaths.push(segmentsToCfSyntax(segments, _config));
155
+ }
156
+ }
157
+ let hasPrerendered404 = false;
158
+ for (const route of routes) {
159
+ const convertedPath = segmentsToCfSyntax(route.segments, _config);
160
+ if (route.pathname === "/404" && route.isPrerendered === true) hasPrerendered404 = true;
161
+ switch (route.type) {
162
+ case "page":
163
+ if (route.isPrerendered === false) includePaths.push(convertedPath);
164
+ break;
165
+ case "endpoint":
166
+ if (route.isPrerendered === false) includePaths.push(convertedPath);
167
+ else excludePaths.push(convertedPath);
168
+ break;
169
+ case "redirect":
170
+ excludePaths.push(convertedPath);
171
+ break;
172
+ default:
173
+ includePaths.push(convertedPath);
174
+ break;
175
+ }
176
+ }
177
+ for (const page of pages) {
178
+ if (page.pathname === "404") hasPrerendered404 = true;
179
+ const pageSegments = removeLeadingForwardSlash(page.pathname).split(path.posix.sep).filter(Boolean).map((s) => {
180
+ return getParts(s);
181
+ });
182
+ excludePaths.push(segmentsToCfSyntax(pageSegments, _config));
183
+ }
184
+ const includeTrie = new PathTrie();
185
+ for (const includePath of includePaths) {
186
+ includeTrie.insert(includePath);
187
+ }
188
+ const excludeTrie = new PathTrie();
189
+ for (const excludePath of excludePaths) {
190
+ if (excludePath[0] === "*") continue;
191
+ excludeTrie.insert(excludePath);
192
+ }
193
+ const [deduplicatedIncludePaths, includedPathsHaveWildcard] = includeTrie.reduceAllPaths(excludeTrie).getAllPaths();
194
+ const [deduplicatedExcludePaths, _excludedPathsHaveWildcard] = excludeTrie.reduceAllPaths(includeTrie).getAllPaths();
195
+ const CLOUDFLARE_COMBINED_LIMIT = 100;
196
+ const AUTOMATIC_INCLUDE_RULES_COUNT = deduplicatedIncludePaths.length;
197
+ const EXTENDED_INCLUDE_RULES_COUNT = includeExtends?.length ?? 0;
198
+ const INCLUDE_RULES_COUNT = AUTOMATIC_INCLUDE_RULES_COUNT + EXTENDED_INCLUDE_RULES_COUNT;
199
+ const AUTOMATIC_EXCLUDE_RULES_COUNT = deduplicatedExcludePaths.length;
200
+ const EXTENDED_EXCLUDE_RULES_COUNT = excludeExtends?.length ?? 0;
201
+ const EXCLUDE_RULES_COUNT = AUTOMATIC_EXCLUDE_RULES_COUNT + EXTENDED_EXCLUDE_RULES_COUNT;
202
+ const OPTION2_TOTAL_COUNT = INCLUDE_RULES_COUNT + (includedPathsHaveWildcard ? EXCLUDE_RULES_COUNT : 0);
203
+ if (!hasPrerendered404 || OPTION2_TOTAL_COUNT > CLOUDFLARE_COMBINED_LIMIT) {
204
+ await writeRoutesFileToOutDir(
205
+ _config,
206
+ logger,
207
+ ["/*"].concat(includeExtends?.map((entry) => entry.pattern) ?? []),
208
+ deduplicatedExcludePaths.map((thisPath) => `${prependForwardSlash(thisPath.join("/"))}`).slice(
209
+ 0,
210
+ CLOUDFLARE_COMBINED_LIMIT - EXTENDED_INCLUDE_RULES_COUNT - EXTENDED_EXCLUDE_RULES_COUNT - 1
211
+ ).concat(excludeExtends?.map((entry) => entry.pattern) ?? [])
212
+ );
213
+ } else {
214
+ await writeRoutesFileToOutDir(
215
+ _config,
216
+ logger,
217
+ deduplicatedIncludePaths.map((thisPath) => `${prependForwardSlash(thisPath.join("/"))}`).concat(includeExtends?.map((entry) => entry.pattern) ?? []),
218
+ includedPathsHaveWildcard ? deduplicatedExcludePaths.map((thisPath) => `${prependForwardSlash(thisPath.join("/"))}`).concat(excludeExtends?.map((entry) => entry.pattern) ?? []) : []
219
+ );
220
+ }
221
+ }
222
+ export {
223
+ createRoutesFile,
224
+ getParts
225
+ };
@@ -0,0 +1,24 @@
1
+ import type { CacheStorage as CloudflareCacheStorage, ExecutionContext, ExportedHandlerFetchHandler } from '@cloudflare/workers-types';
2
+ import type { SSRManifest } from 'astro';
3
+ import type { App } from 'astro/app';
4
+ type Env = {
5
+ [key: string]: unknown;
6
+ ASSETS: {
7
+ fetch: (req: Request | string) => Promise<Response>;
8
+ };
9
+ ASTRO_STUDIO_APP_TOKEN?: string;
10
+ };
11
+ export interface Runtime<T extends object = object> {
12
+ runtime: {
13
+ env: Env & T;
14
+ cf: Parameters<ExportedHandlerFetchHandler>[0]['cf'];
15
+ caches: CloudflareCacheStorage;
16
+ ctx: ExecutionContext;
17
+ };
18
+ }
19
+ declare global {
20
+ var __ASTRO_SESSION_BINDING_NAME: string;
21
+ var __env__: Partial<Env>;
22
+ }
23
+ export declare function handle(manifest: SSRManifest, app: App, request: Parameters<ExportedHandlerFetchHandler>[0], env: Env, context: ExecutionContext): Promise<Response>;
24
+ export {};
@@ -0,0 +1,64 @@
1
+ import { env as globalEnv } from "cloudflare:workers";
2
+ import { setGetEnv } from "astro/env/setup";
3
+ import { createGetEnv } from "../utils/env.js";
4
+ setGetEnv(createGetEnv(globalEnv));
5
+ async function handle(manifest, app, request, env, context) {
6
+ const { pathname } = new URL(request.url);
7
+ const bindingName = globalThis.__ASTRO_SESSION_BINDING_NAME;
8
+ globalThis.__env__ ??= {};
9
+ globalThis.__env__[bindingName] = env[bindingName];
10
+ if (manifest.assets.has(pathname)) {
11
+ return env.ASSETS.fetch(request.url.replace(/\.html$/, ""));
12
+ }
13
+ const routeData = app.match(request);
14
+ if (!routeData) {
15
+ const asset = await env.ASSETS.fetch(
16
+ request.url.replace(/index.html$/, "").replace(/\.html$/, "")
17
+ );
18
+ if (asset.status !== 404) {
19
+ return asset;
20
+ }
21
+ }
22
+ Reflect.set(request, Symbol.for("astro.clientAddress"), request.headers.get("cf-connecting-ip"));
23
+ process.env.ASTRO_STUDIO_APP_TOKEN ??= (() => {
24
+ if (typeof env.ASTRO_STUDIO_APP_TOKEN === "string") {
25
+ return env.ASTRO_STUDIO_APP_TOKEN;
26
+ }
27
+ })();
28
+ const locals = {
29
+ runtime: {
30
+ env,
31
+ cf: request.cf,
32
+ caches,
33
+ ctx: {
34
+ waitUntil: (promise) => context.waitUntil(promise),
35
+ // Currently not available: https://developers.cloudflare.com/pages/platform/known-issues/#pages-functions
36
+ passThroughOnException: () => {
37
+ throw new Error(
38
+ "`passThroughOnException` is currently not available in Cloudflare Pages. See https://developers.cloudflare.com/pages/platform/known-issues/#pages-functions."
39
+ );
40
+ },
41
+ props: {}
42
+ }
43
+ }
44
+ };
45
+ const response = await app.render(
46
+ request,
47
+ {
48
+ routeData,
49
+ locals,
50
+ prerenderedErrorPageFetch: async (url) => {
51
+ return env.ASSETS.fetch(url.replace(/\.html$/, ""));
52
+ }
53
+ }
54
+ );
55
+ if (app.setCookieHeaders) {
56
+ for (const setCookieHeader of app.setCookieHeaders(response)) {
57
+ response.headers.append("Set-Cookie", setCookieHeader);
58
+ }
59
+ }
60
+ return response;
61
+ }
62
+ export {
63
+ handle
64
+ };
@@ -0,0 +1,38 @@
1
+ import type { AstroConfig, AstroIntegrationLogger, HookParameters } from 'astro';
2
+ export type ImageService = 'passthrough' | 'cloudflare' | 'compile' | 'custom';
3
+ export declare function setImageConfig(service: ImageService, config: AstroConfig['image'], command: HookParameters<'astro:config:setup'>['command'], logger: AstroIntegrationLogger): {
4
+ service: import("astro").ImageServiceConfig<Record<string, any>>;
5
+ responsiveStyles: boolean;
6
+ endpoint: {
7
+ route: string;
8
+ entrypoint?: string | undefined;
9
+ };
10
+ domains: string[];
11
+ remotePatterns: {
12
+ port?: string | undefined;
13
+ protocol?: string | undefined;
14
+ hostname?: string | undefined;
15
+ pathname?: string | undefined;
16
+ }[];
17
+ layout?: "fixed" | "constrained" | "full-width" | "none" | undefined;
18
+ objectFit?: string | undefined;
19
+ objectPosition?: string | undefined;
20
+ breakpoints?: number[] | undefined;
21
+ } | {
22
+ service: import("astro").ImageServiceConfig<Record<string, any>>;
23
+ endpoint: {
24
+ entrypoint: string | undefined;
25
+ };
26
+ responsiveStyles: boolean;
27
+ domains: string[];
28
+ remotePatterns: {
29
+ port?: string | undefined;
30
+ protocol?: string | undefined;
31
+ hostname?: string | undefined;
32
+ pathname?: string | undefined;
33
+ }[];
34
+ layout?: "fixed" | "constrained" | "full-width" | "none" | undefined;
35
+ objectFit?: string | undefined;
36
+ objectPosition?: string | undefined;
37
+ breakpoints?: number[] | undefined;
38
+ };
@@ -0,0 +1,33 @@
1
+ import { passthroughImageService, sharpImageService } from "astro/config";
2
+ function setImageConfig(service, config, command, logger) {
3
+ switch (service) {
4
+ case "passthrough":
5
+ return { ...config, service: passthroughImageService() };
6
+ case "cloudflare":
7
+ return {
8
+ ...config,
9
+ service: command === "dev" ? sharpImageService() : { entrypoint: "zastro-websockets-cloudflare/image-service" }
10
+ };
11
+ case "compile":
12
+ return {
13
+ ...config,
14
+ service: sharpImageService(),
15
+ endpoint: {
16
+ entrypoint: command === "dev" ? void 0 : "zastro-websockets-cloudflare/image-endpoint"
17
+ }
18
+ };
19
+ case "custom":
20
+ return { ...config };
21
+ default:
22
+ if (config.service.entrypoint === "astro/assets/services/sharp") {
23
+ logger.warn(
24
+ `The current configuration does not support image optimization. To allow your project to build with the original, unoptimized images, the image service has been automatically switched to the 'passthrough' option. See https://docs.astro.build/en/reference/configuration-reference/#imageservice`
25
+ );
26
+ return { ...config, service: passthroughImageService() };
27
+ }
28
+ return { ...config };
29
+ }
30
+ }
31
+ export {
32
+ setImageConfig
33
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Cloudflare WebSocket exports
3
+ */
4
+ export { WebSocket, attach, ErrorEvent, CloseEvent } from './websocket.js';
5
+ export { onRequest } from './middleware.js';
6
+ export { createWebSocketHandler } from './server.js';
@@ -0,0 +1,11 @@
1
+ import { WebSocket, attach, ErrorEvent, CloseEvent } from "./websocket.js";
2
+ import { onRequest } from "./middleware.js";
3
+ import { createWebSocketHandler } from "./server.js";
4
+ export {
5
+ CloseEvent,
6
+ ErrorEvent,
7
+ WebSocket,
8
+ attach,
9
+ createWebSocketHandler,
10
+ onRequest
11
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Cloudflare WebSocket middleware
3
+ */
4
+ import { WebSocket } from './websocket.js';
5
+ declare global {
6
+ var WebSocketPair: {
7
+ new (): {
8
+ 0: CloudflareWebSocket;
9
+ 1: CloudflareWebSocket;
10
+ };
11
+ };
12
+ interface CloudflareWebSocket {
13
+ send(data: string | ArrayBufferLike | ArrayBufferView): void;
14
+ close(code?: number, reason?: string): void;
15
+ accept(): void;
16
+ addEventListener(type: 'message', listener: (event: {
17
+ data: any;
18
+ }) => void): void;
19
+ addEventListener(type: 'close', listener: (event: {
20
+ code: number;
21
+ reason: string;
22
+ wasClean: boolean;
23
+ }) => void): void;
24
+ addEventListener(type: 'error', listener: (event: any) => void): void;
25
+ addEventListener(type: 'open', listener: (event: any) => void): void;
26
+ removeEventListener(type: string, listener: any): void;
27
+ readonly readyState: number;
28
+ readonly url: string;
29
+ }
30
+ }
31
+ export interface CloudflareLocals {
32
+ isUpgradeRequest: boolean;
33
+ upgradeWebSocket(): {
34
+ socket: WebSocket;
35
+ response: Response;
36
+ };
37
+ runtime?: {
38
+ env: any;
39
+ cf: any;
40
+ ctx: any;
41
+ caches: any;
42
+ waitUntil: (promise: Promise<any>) => void;
43
+ };
44
+ }
45
+ export declare const onRequest: (context: any, next: () => Promise<Response>) => Promise<Response>;
@@ -0,0 +1,29 @@
1
+ import { WebSocket, attach } from "./websocket.js";
2
+ const onRequest = async function cloudflareWebSocketMiddleware(context, next) {
3
+ const { request, locals } = context;
4
+ const isUpgradeRequest = request.headers.get("upgrade") === "websocket" && request.headers.get("connection")?.toLowerCase().includes("upgrade");
5
+ locals.isUpgradeRequest = isUpgradeRequest;
6
+ locals.upgradeWebSocket = () => {
7
+ if (!isUpgradeRequest) {
8
+ throw new Error("The request must be an upgrade request to upgrade the connection to a WebSocket.");
9
+ }
10
+ const webSocketPair = new WebSocketPair();
11
+ const [client, server] = [webSocketPair[0], webSocketPair[1]];
12
+ const socket = new WebSocket(request.url);
13
+ attach(socket, server);
14
+ const response = new Response(null, {
15
+ status: 101,
16
+ statusText: "Switching Protocols",
17
+ headers: {
18
+ "Upgrade": "websocket",
19
+ "Connection": "Upgrade"
20
+ },
21
+ webSocket: client
22
+ });
23
+ return { socket, response };
24
+ };
25
+ return next();
26
+ };
27
+ export {
28
+ onRequest
29
+ };