@astrojs/cloudflare 0.0.0-404-fix-20231115224256

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.
package/dist/index.js ADDED
@@ -0,0 +1,511 @@
1
+ import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
2
+ import { AstroError } from 'astro/errors';
3
+ import esbuild from 'esbuild';
4
+ import { Miniflare } from 'miniflare';
5
+ import * as fs from 'node:fs';
6
+ import * as os from 'node:os';
7
+ import { dirname, relative, sep } from 'node:path';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+ import glob from 'tiny-glob';
10
+ import { getAdapter } from './getAdapter.js';
11
+ import { deduplicatePatterns } from './utils/deduplicatePatterns.js';
12
+ import { getCFObject } from './utils/getCFObject.js';
13
+ import { prepareImageConfig } from './utils/image-config.js';
14
+ import { getD1Bindings, getDOBindings, getEnvVars, getKVBindings, getR2Bindings, } from './utils/parser.js';
15
+ import { prependForwardSlash } from './utils/prependForwardSlash.js';
16
+ import { rewriteWasmImportPath } from './utils/rewriteWasmImportPath.js';
17
+ import { wasmModuleLoader } from './utils/wasm-module-loader.js';
18
+ const RUNTIME_WARNING = `You are using a deprecated string format for the \`runtime\` API. Please update to the current format for better support.
19
+
20
+ Example:
21
+ Old Format: 'local'
22
+ Current Format: { mode: 'local', persistTo: '.wrangler/state/v3' }
23
+
24
+ Please refer to our runtime documentation for more details on the format. https://docs.astro.build/en/guides/integrations-guide/cloudflare/#runtime`;
25
+ export default function createIntegration(args) {
26
+ let _config;
27
+ let _buildConfig;
28
+ let _mf;
29
+ let _entryPoints = new Map();
30
+ const SERVER_BUILD_FOLDER = '/$server_build/';
31
+ const isModeDirectory = args?.mode === 'directory';
32
+ const functionPerRoute = args?.functionPerRoute ?? false;
33
+ let runtimeMode = { mode: 'off' };
34
+ if (args?.runtime === 'remote') {
35
+ runtimeMode = { mode: 'remote' };
36
+ }
37
+ else if (args?.runtime === 'local') {
38
+ runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
39
+ }
40
+ else if (typeof args?.runtime === 'object' &&
41
+ args?.runtime.mode === 'local' &&
42
+ args.runtime.persistTo === undefined) {
43
+ runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
44
+ }
45
+ else if (args?.runtime) {
46
+ runtimeMode = args?.runtime;
47
+ }
48
+ return {
49
+ name: '@astrojs/cloudflare',
50
+ hooks: {
51
+ 'astro:config:setup': ({ command, config, updateConfig, logger }) => {
52
+ updateConfig({
53
+ build: {
54
+ client: new URL(`.${config.base}`, config.outDir),
55
+ server: new URL(`.${SERVER_BUILD_FOLDER}`, config.outDir),
56
+ serverEntry: '_worker.mjs',
57
+ redirects: false,
58
+ },
59
+ vite: {
60
+ // load .wasm files as WebAssembly modules
61
+ plugins: [
62
+ wasmModuleLoader({
63
+ disabled: !args?.wasmModuleImports,
64
+ assetsDirectory: config.build.assets,
65
+ }),
66
+ ],
67
+ },
68
+ image: prepareImageConfig(args?.imageService ?? 'DEFAULT', config.image, command, logger),
69
+ });
70
+ },
71
+ 'astro:config:done': ({ setAdapter, config, logger }) => {
72
+ setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
73
+ _config = config;
74
+ _buildConfig = config.build;
75
+ if (_config.output === 'static') {
76
+ throw new AstroError('[@astrojs/cloudflare] `output: "server"` or `output: "hybrid"` is required to use this adapter. Otherwise, this adapter is not necessary to deploy a static site to Cloudflare.');
77
+ }
78
+ if (_config.base === SERVER_BUILD_FOLDER) {
79
+ throw new AstroError('[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.');
80
+ }
81
+ if (typeof args?.runtime === 'string') {
82
+ logger.warn(RUNTIME_WARNING);
83
+ }
84
+ },
85
+ 'astro:server:setup': ({ server }) => {
86
+ if (runtimeMode.mode === 'local') {
87
+ const typedRuntimeMode = runtimeMode;
88
+ server.middlewares.use(async function middleware(req, res, next) {
89
+ try {
90
+ const cf = await getCFObject(typedRuntimeMode.mode);
91
+ const vars = await getEnvVars();
92
+ const D1Bindings = await getD1Bindings();
93
+ const R2Bindings = await getR2Bindings();
94
+ const KVBindings = await getKVBindings();
95
+ const DOBindings = await getDOBindings();
96
+ let bindingsEnv = new Object({});
97
+ // fix for the error "kj/filesystem-disk-unix.c++:1709: warning: PWD environment variable doesn't match current directory."
98
+ // note: This mismatch might be primarily due to the test runner.
99
+ const originalPWD = process.env.PWD;
100
+ process.env.PWD = process.cwd();
101
+ _mf = new Miniflare({
102
+ modules: true,
103
+ script: '',
104
+ cache: true,
105
+ cachePersist: `${typedRuntimeMode.persistTo}/cache`,
106
+ cacheWarnUsage: true,
107
+ d1Databases: D1Bindings,
108
+ d1Persist: `${typedRuntimeMode.persistTo}/d1`,
109
+ r2Buckets: R2Bindings,
110
+ r2Persist: `${typedRuntimeMode.persistTo}/r2`,
111
+ kvNamespaces: KVBindings,
112
+ kvPersist: `${typedRuntimeMode.persistTo}/kv`,
113
+ durableObjects: DOBindings,
114
+ durableObjectsPersist: `${typedRuntimeMode.persistTo}/do`,
115
+ });
116
+ await _mf.ready;
117
+ for (const D1Binding of D1Bindings) {
118
+ const db = await _mf.getD1Database(D1Binding);
119
+ Reflect.set(bindingsEnv, D1Binding, db);
120
+ }
121
+ for (const R2Binding of R2Bindings) {
122
+ const bucket = await _mf.getR2Bucket(R2Binding);
123
+ Reflect.set(bindingsEnv, R2Binding, bucket);
124
+ }
125
+ for (const KVBinding of KVBindings) {
126
+ const namespace = await _mf.getKVNamespace(KVBinding);
127
+ Reflect.set(bindingsEnv, KVBinding, namespace);
128
+ }
129
+ for (const key in DOBindings) {
130
+ if (Object.prototype.hasOwnProperty.call(DOBindings, key)) {
131
+ const DO = await _mf.getDurableObjectNamespace(key);
132
+ Reflect.set(bindingsEnv, key, DO);
133
+ }
134
+ }
135
+ const mfCache = await _mf.getCaches();
136
+ process.env.PWD = originalPWD;
137
+ const clientLocalsSymbol = Symbol.for('astro.locals');
138
+ Reflect.set(req, clientLocalsSymbol, {
139
+ runtime: {
140
+ env: {
141
+ // default binding for static assets will be dynamic once we support mocking of bindings
142
+ ASSETS: {},
143
+ // this is just a VAR for CF to change build behavior, on dev it should be 0
144
+ CF_PAGES: '0',
145
+ // will be fetched from git dynamically once we support mocking of bindings
146
+ CF_PAGES_BRANCH: 'TBA',
147
+ // will be fetched from git dynamically once we support mocking of bindings
148
+ CF_PAGES_COMMIT_SHA: 'TBA',
149
+ CF_PAGES_URL: `http://${req.headers.host}`,
150
+ ...bindingsEnv,
151
+ ...vars,
152
+ },
153
+ cf: cf,
154
+ waitUntil: (_promise) => {
155
+ return;
156
+ },
157
+ caches: mfCache,
158
+ },
159
+ });
160
+ next();
161
+ }
162
+ catch {
163
+ next();
164
+ }
165
+ });
166
+ }
167
+ },
168
+ 'astro:server:done': async ({ logger }) => {
169
+ if (_mf) {
170
+ logger.info('Cleaning up the Miniflare instance, and shutting down the workerd server.');
171
+ await _mf.dispose();
172
+ }
173
+ },
174
+ 'astro:build:setup': ({ vite, target }) => {
175
+ if (target === 'server') {
176
+ vite.resolve ||= {};
177
+ vite.resolve.alias ||= {};
178
+ const aliases = [
179
+ {
180
+ find: 'react-dom/server',
181
+ replacement: 'react-dom/server.browser',
182
+ },
183
+ ];
184
+ if (Array.isArray(vite.resolve.alias)) {
185
+ vite.resolve.alias = [...vite.resolve.alias, ...aliases];
186
+ }
187
+ else {
188
+ for (const alias of aliases) {
189
+ vite.resolve.alias[alias.find] = alias.replacement;
190
+ }
191
+ }
192
+ vite.ssr ||= {};
193
+ vite.ssr.target = 'webworker';
194
+ // Cloudflare env is only available per request. This isn't feasible for code that access env vars
195
+ // in a global way, so we shim their access as `process.env.*`. We will populate `process.env` later
196
+ // in its fetch handler.
197
+ vite.define = {
198
+ 'process.env': 'process.env',
199
+ ...vite.define,
200
+ };
201
+ }
202
+ },
203
+ 'astro:build:ssr': ({ entryPoints }) => {
204
+ _entryPoints = entryPoints;
205
+ },
206
+ 'astro:build:done': async ({ pages, routes, dir }) => {
207
+ const functionsUrl = new URL('functions/', _config.root);
208
+ const assetsUrl = new URL(_buildConfig.assets, _buildConfig.client);
209
+ if (isModeDirectory) {
210
+ await fs.promises.mkdir(functionsUrl, { recursive: true });
211
+ }
212
+ // TODO: remove _buildConfig.split in Astro 4.0
213
+ if (isModeDirectory && (_buildConfig.split || functionPerRoute)) {
214
+ const entryPointsURL = [..._entryPoints.values()];
215
+ const entryPaths = entryPointsURL.map((entry) => fileURLToPath(entry));
216
+ const outputUrl = new URL('$astro', _buildConfig.server);
217
+ const outputDir = fileURLToPath(outputUrl);
218
+ //
219
+ // Sadly, when wasmModuleImports is enabled, this needs to build esbuild for each depth of routes/entrypoints
220
+ // independently so that relative import paths to the assets are the correct depth of '../' traversals
221
+ // This is inefficient, so wasmModuleImports is opt-in. This could potentially be improved in the future by
222
+ // taking advantage of the esbuild "onEnd" hook to rewrite import code per entry point relative to where the final
223
+ // destination of the entrypoint is
224
+ const entryPathsGroupedByDepth = !args.wasmModuleImports
225
+ ? [entryPaths]
226
+ : entryPaths
227
+ .reduce((sum, thisPath) => {
228
+ const depthFromRoot = thisPath.split(sep).length;
229
+ sum.set(depthFromRoot, (sum.get(depthFromRoot) || []).concat(thisPath));
230
+ return sum;
231
+ }, new Map())
232
+ .values();
233
+ for (const pathsGroup of entryPathsGroupedByDepth) {
234
+ // for some reason this exports to "entry.pages" on windows instead of "pages" on unix environments.
235
+ // This deduces the name of the "pages" build directory
236
+ const pagesDirname = relative(fileURLToPath(_buildConfig.server), pathsGroup[0]).split(sep)[0];
237
+ const absolutePagesDirname = fileURLToPath(new URL(pagesDirname, _buildConfig.server));
238
+ const urlWithinFunctions = new URL(relative(absolutePagesDirname, pathsGroup[0]), functionsUrl);
239
+ const relativePathToAssets = relative(dirname(fileURLToPath(urlWithinFunctions)), fileURLToPath(assetsUrl));
240
+ await esbuild.build({
241
+ target: 'es2022',
242
+ platform: 'browser',
243
+ conditions: ['workerd', 'worker', 'browser'],
244
+ external: [
245
+ 'node:assert',
246
+ 'node:async_hooks',
247
+ 'node:buffer',
248
+ 'node:crypto',
249
+ 'node:diagnostics_channel',
250
+ 'node:events',
251
+ 'node:path',
252
+ 'node:process',
253
+ 'node:stream',
254
+ 'node:string_decoder',
255
+ 'node:util',
256
+ 'cloudflare:*',
257
+ ],
258
+ entryPoints: pathsGroup,
259
+ outbase: absolutePagesDirname,
260
+ outdir: outputDir,
261
+ allowOverwrite: true,
262
+ format: 'esm',
263
+ bundle: true,
264
+ minify: _config.vite?.build?.minify !== false,
265
+ banner: {
266
+ js: `globalThis.process = {
267
+ argv: [],
268
+ env: {},
269
+ };`,
270
+ },
271
+ logOverride: {
272
+ 'ignored-bare-import': 'silent',
273
+ },
274
+ plugins: !args?.wasmModuleImports
275
+ ? []
276
+ : [rewriteWasmImportPath({ relativePathToAssets })],
277
+ });
278
+ }
279
+ const outputFiles = await glob(`**/*`, {
280
+ cwd: outputDir,
281
+ filesOnly: true,
282
+ });
283
+ // move the files into the functions folder
284
+ // & make sure the file names match Cloudflare syntax for routing
285
+ for (const outputFile of outputFiles) {
286
+ const path = outputFile.split(sep);
287
+ const finalSegments = path.map((segment) => segment
288
+ .replace(/(\_)(\w+)(\_)/g, (_, __, prop) => {
289
+ return `[${prop}]`;
290
+ })
291
+ .replace(/(\_\-\-\-)(\w+)(\_)/g, (_, __, prop) => {
292
+ return `[[${prop}]]`;
293
+ }));
294
+ finalSegments[finalSegments.length - 1] = finalSegments[finalSegments.length - 1]
295
+ .replace('entry.', '')
296
+ .replace(/(.*)\.(\w+)\.(\w+)$/g, (_, fileName, __, newExt) => {
297
+ return `${fileName}.${newExt}`;
298
+ });
299
+ const finalDirPath = finalSegments.slice(0, -1).join(sep);
300
+ const finalPath = finalSegments.join(sep);
301
+ const newDirUrl = new URL(finalDirPath, functionsUrl);
302
+ await fs.promises.mkdir(newDirUrl, { recursive: true });
303
+ const oldFileUrl = new URL(`$astro/${outputFile}`, outputUrl);
304
+ const newFileUrl = new URL(finalPath, functionsUrl);
305
+ await fs.promises.rename(oldFileUrl, newFileUrl);
306
+ }
307
+ }
308
+ else {
309
+ const entryPath = fileURLToPath(new URL(_buildConfig.serverEntry, _buildConfig.server));
310
+ const entryUrl = new URL(_buildConfig.serverEntry, _config.outDir);
311
+ const buildPath = fileURLToPath(entryUrl);
312
+ // A URL for the final build path after renaming
313
+ const finalBuildUrl = pathToFileURL(buildPath.replace(/\.mjs$/, '.js'));
314
+ await esbuild.build({
315
+ target: 'es2022',
316
+ platform: 'browser',
317
+ conditions: ['workerd', 'worker', 'browser'],
318
+ external: [
319
+ 'node:assert',
320
+ 'node:async_hooks',
321
+ 'node:buffer',
322
+ 'node:crypto',
323
+ 'node:diagnostics_channel',
324
+ 'node:events',
325
+ 'node:path',
326
+ 'node:process',
327
+ 'node:stream',
328
+ 'node:string_decoder',
329
+ 'node:util',
330
+ 'cloudflare:*',
331
+ ],
332
+ entryPoints: [entryPath],
333
+ outfile: buildPath,
334
+ allowOverwrite: true,
335
+ format: 'esm',
336
+ bundle: true,
337
+ minify: _config.vite?.build?.minify !== false,
338
+ banner: {
339
+ js: `globalThis.process = {
340
+ argv: [],
341
+ env: {},
342
+ };`,
343
+ },
344
+ logOverride: {
345
+ 'ignored-bare-import': 'silent',
346
+ },
347
+ plugins: !args?.wasmModuleImports
348
+ ? []
349
+ : [
350
+ rewriteWasmImportPath({
351
+ relativePathToAssets: isModeDirectory
352
+ ? relative(fileURLToPath(functionsUrl), fileURLToPath(assetsUrl))
353
+ : relative(fileURLToPath(_buildConfig.client), fileURLToPath(assetsUrl)),
354
+ }),
355
+ ],
356
+ });
357
+ // Rename to worker.js
358
+ await fs.promises.rename(buildPath, finalBuildUrl);
359
+ if (isModeDirectory) {
360
+ const directoryUrl = new URL('[[path]].js', functionsUrl);
361
+ await fs.promises.rename(finalBuildUrl, directoryUrl);
362
+ }
363
+ }
364
+ // throw the server folder in the bin
365
+ const serverUrl = new URL(_buildConfig.server);
366
+ await fs.promises.rm(serverUrl, { recursive: true, force: true });
367
+ // move cloudflare specific files to the root
368
+ const cloudflareSpecialFiles = ['_headers', '_redirects', '_routes.json'];
369
+ if (_config.base !== '/') {
370
+ for (const file of cloudflareSpecialFiles) {
371
+ try {
372
+ await fs.promises.rename(new URL(file, _buildConfig.client), new URL(file, _config.outDir));
373
+ }
374
+ catch (e) {
375
+ // ignore
376
+ }
377
+ }
378
+ }
379
+ // Add also the worker file so it's excluded from the _routes.json generation
380
+ if (!isModeDirectory) {
381
+ cloudflareSpecialFiles.push('_worker.js');
382
+ }
383
+ const routesExists = await fs.promises
384
+ .stat(new URL('./_routes.json', _config.outDir))
385
+ .then((stat) => stat.isFile())
386
+ .catch(() => false);
387
+ // this creates a _routes.json, in case there is none present to enable
388
+ // cloudflare to handle static files and support _redirects configuration
389
+ if (!routesExists) {
390
+ /**
391
+ * These route types are candiates for being part of the `_routes.json` `include` array.
392
+ */
393
+ const potentialFunctionRouteTypes = ['endpoint', 'page'];
394
+ const functionEndpoints = routes
395
+ // Certain route types, when their prerender option is set to false, run on the server as function invocations
396
+ .filter((route) => potentialFunctionRouteTypes.includes(route.type) && !route.prerender)
397
+ .map((route) => {
398
+ const includePattern = '/' +
399
+ route.segments
400
+ .flat()
401
+ .map((segment) => (segment.dynamic ? '*' : segment.content))
402
+ .join('/');
403
+ const regexp = new RegExp('^\\/' +
404
+ route.segments
405
+ .flat()
406
+ .map((segment) => (segment.dynamic ? '(.*)' : segment.content))
407
+ .join('\\/') +
408
+ '$');
409
+ return {
410
+ includePattern,
411
+ regexp,
412
+ };
413
+ });
414
+ const staticPathList = (await glob(`${fileURLToPath(_buildConfig.client)}/**/*`, {
415
+ cwd: fileURLToPath(_config.outDir),
416
+ filesOnly: true,
417
+ dot: true,
418
+ }))
419
+ .filter((file) => cloudflareSpecialFiles.indexOf(file) < 0)
420
+ .map((file) => `/${file.replace(/\\/g, '/')}`);
421
+ for (let page of pages) {
422
+ let pagePath = prependForwardSlash(page.pathname);
423
+ if (_config.base !== '/') {
424
+ const base = _config.base.endsWith('/') ? _config.base.slice(0, -1) : _config.base;
425
+ pagePath = `${base}${pagePath}`;
426
+ }
427
+ staticPathList.push(pagePath);
428
+ }
429
+ const redirectsExists = await fs.promises
430
+ .stat(new URL('./_redirects', _config.outDir))
431
+ .then((stat) => stat.isFile())
432
+ .catch(() => false);
433
+ // convert all redirect source paths into a list of routes
434
+ // and add them to the static path
435
+ if (redirectsExists) {
436
+ const redirects = (await fs.promises.readFile(new URL('./_redirects', _config.outDir), 'utf-8'))
437
+ .split(os.EOL)
438
+ .map((line) => {
439
+ const parts = line.split(' ');
440
+ if (parts.length < 2) {
441
+ return null;
442
+ }
443
+ else {
444
+ // convert /products/:id to /products/*
445
+ return (parts[0]
446
+ .replace(/\/:.*?(?=\/|$)/g, '/*')
447
+ // remove query params as they are not supported by cloudflare
448
+ .replace(/\?.*$/, ''));
449
+ }
450
+ })
451
+ .filter((line, index, arr) => line !== null && arr.indexOf(line) === index);
452
+ if (redirects.length > 0) {
453
+ staticPathList.push(...redirects);
454
+ }
455
+ }
456
+ const redirectRoutes = routes
457
+ .filter((r) => r.type === 'redirect')
458
+ .map((r) => {
459
+ return [r, ''];
460
+ });
461
+ const trueRedirects = createRedirectsFromAstroRoutes({
462
+ config: _config,
463
+ routeToDynamicTargetMap: new Map(Array.from(redirectRoutes)),
464
+ dir,
465
+ });
466
+ if (!trueRedirects.empty()) {
467
+ await fs.promises.appendFile(new URL('./_redirects', _config.outDir), trueRedirects.print());
468
+ }
469
+ staticPathList.push(...routes.filter((r) => r.type === 'redirect').map((r) => r.route));
470
+ const strategy = args?.routes?.strategy ?? 'auto';
471
+ // Strategy `include`: include all function endpoints, and then exclude static paths that would be matched by an include pattern
472
+ const includeStrategy = strategy === 'exclude'
473
+ ? undefined
474
+ : {
475
+ include: deduplicatePatterns(functionEndpoints
476
+ .map((endpoint) => endpoint.includePattern)
477
+ .concat(args?.routes?.include ?? [])),
478
+ exclude: deduplicatePatterns(staticPathList
479
+ .filter((file) => functionEndpoints.some((endpoint) => endpoint.regexp.test(file)))
480
+ .concat(args?.routes?.exclude ?? [])),
481
+ };
482
+ // Cloudflare requires at least one include pattern:
483
+ // https://developers.cloudflare.com/pages/platform/functions/routing/#limits
484
+ // So we add a pattern that we immediately exclude again
485
+ if (includeStrategy?.include.length === 0) {
486
+ includeStrategy.include = ['/'];
487
+ includeStrategy.exclude = ['/'];
488
+ }
489
+ // Strategy `exclude`: include everything, and then exclude all static paths
490
+ const excludeStrategy = strategy === 'include'
491
+ ? undefined
492
+ : {
493
+ include: ['/*'],
494
+ exclude: deduplicatePatterns(staticPathList.concat(args?.routes?.exclude ?? [])),
495
+ };
496
+ const includeStrategyLength = includeStrategy
497
+ ? includeStrategy.include.length + includeStrategy.exclude.length
498
+ : Infinity;
499
+ const excludeStrategyLength = excludeStrategy
500
+ ? excludeStrategy.include.length + excludeStrategy.exclude.length
501
+ : Infinity;
502
+ const winningStrategy = includeStrategyLength <= excludeStrategyLength ? includeStrategy : excludeStrategy;
503
+ await fs.promises.writeFile(new URL('./_routes.json', _config.outDir), JSON.stringify({
504
+ version: 1,
505
+ ...winningStrategy,
506
+ }, null, 2));
507
+ }
508
+ },
509
+ },
510
+ };
511
+ }
package/dist/util.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare const isNode: boolean;
2
+ export declare function getProcessEnvProxy(): {};
package/dist/util.js ADDED
@@ -0,0 +1,13 @@
1
+ export const isNode = typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]';
2
+ export function getProcessEnvProxy() {
3
+ return new Proxy({}, {
4
+ get: (target, prop) => {
5
+ console.warn(
6
+ // NOTE: \0 prevents Vite replacement
7
+ `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization ` +
8
+ `as the Cloudflare platform only provides the environment variables per request. ` +
9
+ `Please move the environment variable access inside a function ` +
10
+ `that's only called after a request has been received.`);
11
+ },
12
+ });
13
+ }
@@ -0,0 +1,14 @@
1
+ import type { AstroConfig, ImageMetadata, RemotePattern } from 'astro';
2
+ export declare function isESMImportedImage(src: ImageMetadata | string): src is ImageMetadata;
3
+ export declare function isRemotePath(src: string): boolean;
4
+ export declare function matchHostname(url: URL, hostname?: string, allowWildcard?: boolean): boolean;
5
+ export declare function matchPort(url: URL, port?: string): boolean;
6
+ export declare function matchProtocol(url: URL, protocol?: string): boolean;
7
+ export declare function matchPathname(url: URL, pathname?: string, allowWildcard?: boolean): boolean;
8
+ export declare function matchPattern(url: URL, remotePattern: RemotePattern): boolean;
9
+ export declare function isRemoteAllowed(src: string, { domains, remotePatterns, }: Partial<Pick<AstroConfig['image'], 'domains' | 'remotePatterns'>>): boolean;
10
+ export declare function isString(path: unknown): path is string;
11
+ export declare function removeTrailingForwardSlash(path: string): string;
12
+ export declare function removeLeadingForwardSlash(path: string): string;
13
+ export declare function trimSlashes(path: string): string;
14
+ export declare function joinPaths(...paths: (string | undefined)[]): string;
@@ -0,0 +1,95 @@
1
+ export function isESMImportedImage(src) {
2
+ return typeof src === 'object';
3
+ }
4
+ export function isRemotePath(src) {
5
+ return /^(http|ftp|https|ws):?\/\//.test(src) || src.startsWith('data:');
6
+ }
7
+ export function matchHostname(url, hostname, allowWildcard) {
8
+ if (!hostname) {
9
+ return true;
10
+ }
11
+ else if (!allowWildcard || !hostname.startsWith('*')) {
12
+ return hostname === url.hostname;
13
+ }
14
+ else if (hostname.startsWith('**.')) {
15
+ const slicedHostname = hostname.slice(2); // ** length
16
+ return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname);
17
+ }
18
+ else if (hostname.startsWith('*.')) {
19
+ const slicedHostname = hostname.slice(1); // * length
20
+ const additionalSubdomains = url.hostname
21
+ .replace(slicedHostname, '')
22
+ .split('.')
23
+ .filter(Boolean);
24
+ return additionalSubdomains.length === 1;
25
+ }
26
+ return false;
27
+ }
28
+ export function matchPort(url, port) {
29
+ return !port || port === url.port;
30
+ }
31
+ export function matchProtocol(url, protocol) {
32
+ return !protocol || protocol === url.protocol.slice(0, -1);
33
+ }
34
+ export function matchPathname(url, pathname, allowWildcard) {
35
+ if (!pathname) {
36
+ return true;
37
+ }
38
+ else if (!allowWildcard || !pathname.endsWith('*')) {
39
+ return pathname === url.pathname;
40
+ }
41
+ else if (pathname.endsWith('/**')) {
42
+ const slicedPathname = pathname.slice(0, -2); // ** length
43
+ return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname);
44
+ }
45
+ else if (pathname.endsWith('/*')) {
46
+ const slicedPathname = pathname.slice(0, -1); // * length
47
+ const additionalPathChunks = url.pathname
48
+ .replace(slicedPathname, '')
49
+ .split('/')
50
+ .filter(Boolean);
51
+ return additionalPathChunks.length === 1;
52
+ }
53
+ return false;
54
+ }
55
+ export function matchPattern(url, remotePattern) {
56
+ return (matchProtocol(url, remotePattern.protocol) &&
57
+ matchHostname(url, remotePattern.hostname, true) &&
58
+ matchPort(url, remotePattern.port) &&
59
+ matchPathname(url, remotePattern.pathname, true));
60
+ }
61
+ export function isRemoteAllowed(src, { domains = [], remotePatterns = [], }) {
62
+ if (!isRemotePath(src))
63
+ return false;
64
+ const url = new URL(src);
65
+ return (domains.some((domain) => matchHostname(url, domain)) ||
66
+ remotePatterns.some((remotePattern) => matchPattern(url, remotePattern)));
67
+ }
68
+ export function isString(path) {
69
+ return typeof path === 'string' || path instanceof String;
70
+ }
71
+ export function removeTrailingForwardSlash(path) {
72
+ return path.endsWith('/') ? path.slice(0, path.length - 1) : path;
73
+ }
74
+ export function removeLeadingForwardSlash(path) {
75
+ return path.startsWith('/') ? path.substring(1) : path;
76
+ }
77
+ export function trimSlashes(path) {
78
+ return path.replace(/^\/|\/$/g, '');
79
+ }
80
+ export function joinPaths(...paths) {
81
+ return paths
82
+ .filter(isString)
83
+ .map((path, i) => {
84
+ if (i === 0) {
85
+ return removeTrailingForwardSlash(path);
86
+ }
87
+ else if (i === paths.length - 1) {
88
+ return removeLeadingForwardSlash(path);
89
+ }
90
+ else {
91
+ return trimSlashes(path);
92
+ }
93
+ })
94
+ .join('/');
95
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Remove duplicates and redundant patterns from an `include` or `exclude` list.
3
+ * Otherwise Cloudflare will throw an error on deployment. Plus, it saves more entries.
4
+ * E.g. `['/foo/*', '/foo/*', '/foo/bar'] => ['/foo/*']`
5
+ * @param patterns a list of `include` or `exclude` patterns
6
+ * @returns a deduplicated list of patterns
7
+ */
8
+ export declare function deduplicatePatterns(patterns: string[]): string[];