enforced .gitignore

This commit is contained in:
J-onasJones 2023-09-14 19:04:01 +02:00
parent a29aac8fa7
commit ffdb1c0b69
1739 changed files with 0 additions and 740138 deletions

1
node_modules/.bin/acorn generated vendored
View file

@ -1 +0,0 @@
../acorn/bin/acorn

1
node_modules/.bin/esbuild generated vendored
View file

@ -1 +0,0 @@
../esbuild/bin/esbuild

1
node_modules/.bin/mime generated vendored
View file

@ -1 +0,0 @@
../mime/cli.js

1
node_modules/.bin/mustache generated vendored
View file

@ -1 +0,0 @@
../mustache/bin/mustache

1
node_modules/.bin/nanoid generated vendored
View file

@ -1 +0,0 @@
../nanoid/bin/nanoid.cjs

1
node_modules/.bin/prebuild-install generated vendored
View file

@ -1 +0,0 @@
../prebuild-install/bin.js

1
node_modules/.bin/rc generated vendored
View file

@ -1 +0,0 @@
../rc/cli.js

1
node_modules/.bin/semver generated vendored
View file

@ -1 +0,0 @@
../semver/bin/semver.js

1
node_modules/.bin/workerd generated vendored
View file

@ -1 +0,0 @@
../workerd/bin/workerd

1
node_modules/.bin/wrangler generated vendored
View file

@ -1 +0,0 @@
../wrangler/bin/wrangler.js

1
node_modules/.bin/wrangler2 generated vendored
View file

@ -1 +0,0 @@
../wrangler/bin/wrangler.js

1237
node_modules/.package-lock.json generated vendored

File diff suppressed because it is too large Load diff

View file

@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View file

@ -1,25 +0,0 @@
Copyright (c) 2018 Ashley Williams <ashley666ashley@gmail.com>
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -1,329 +0,0 @@
# @cloudflare/kv-asset-handler
[![npm](https://img.shields.io/npm/v/@cloudflare/kv-asset-handler.svg)](https://www.npmjs.com/package/@cloudflare/kv-asset-handler) &nbsp;
[![Run npm tests](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml) &nbsp;
[![Lint Markdown](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml) &nbsp;
`kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects.
`kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client.
Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations!
For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV.
The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers-sites` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.gg/cloudflaredev)!
- [Installation](#installation)
- [Usage](#usage)
- [`getAssetFromKV`](#-getassetfromkv)
- [Example](#example)
* [Return](#return)
* [Optional Arguments](#optional-arguments)
- [`mapRequestToAsset`](#-maprequesttoasset)
- [Example](#example-1)
- [`cacheControl`](#-cachecontrol)
- [`browserTTL`](#browserttl)
- [`edgeTTL`](#edgettl)
- [`bypassCache`](#bypasscache)
- [`ASSET_NAMESPACE` (required for ES Modules)](#asset_namespace-required-for-es-modules)
- [`ASSET_MANIFEST` (required for ES Modules)](#asset_manifest-required-for-es-modules)
* [Helper functions](#helper-functions)
- [`mapRequestToAsset`](#maprequesttoasset-1)
- [`serveSinglePageApp`](#servesinglepageapp)
* [Cache revalidation and etags](#cache-revalidation-and-etags)
## Installation
Add this package to your `package.json` by running this in the root of your
project's directory:
```
npm i @cloudflare/kv-asset-handler
```
## Usage
This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites).
## `getAssetFromKV`
getAssetFromKV(Evt) => Promise<Response>
`getAssetFromKV` is an async function that takes an `Evt` object (containing a `Request` and a [`waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#waituntil)) and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`.
#### Example
This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`.
### Return
`getAssetFromKV` returns a `Promise<Response>` with `Response` being the body of the asset requested.
Known errors to be thrown are:
- MethodNotAllowedError
- NotFoundError
- InternalError
#### ES Modules
```js
import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler'
import manifestJSON from '__STATIC_CONTENT_MANIFEST'
const assetManifest = JSON.parse(manifestJSON)
export default {
async fetch(request, env, ctx) {
if (request.url.includes('/docs')) {
try {
return await getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise)
},
},
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
},
)
} catch (e) {
if (e instanceof NotFoundError) {
// ...
} else if (e instanceof MethodNotAllowedError) {
// ...
} else {
return new Response('An unexpected error occurred', { status: 500 })
}
}
} else return fetch(request)
},
}
```
#### Service Worker
```js
import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler'
addEventListener('fetch', (event) => {
event.respondWith(handleEvent(event))
})
async function handleEvent(event) {
if (event.request.url.includes('/docs')) {
try {
return await getAssetFromKV(event)
} catch (e) {
if (e instanceof NotFoundError) {
// ...
} else if (e instanceof MethodNotAllowedError) {
// ...
} else {
return new Response('An unexpected error occurred', { status: 500 })
}
}
} else return fetch(event.request)
}
```
### Optional Arguments
You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument.
```
getAssetFromKV(event, { mapRequestToAsset: ... })
```
#### `mapRequestToAsset`
mapRequestToAsset(Request) => Request
Maps the incoming request to the value that will be looked up in Cloudflare's KV
By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV.
For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function
#### Example
Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV.
```js
import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
...
const customKeyModifier = request => {
let url = request.url
//custom key mapping optional
url = url.replace('/docs', '').replace(/^\/+/, '')
return mapRequestToAsset(new Request(url, request))
}
let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier })
```
#### `cacheControl`
type: object
`cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows:
```javascript
let cacheControl = {
browserTTL: null, // do not set cache control ttl on responses
edgeTTL: 2 * 60 * 60 * 24, // 2 days
bypassCache: false, // do not bypass Cloudflare's cache
}
```
##### `browserTTL`
type: number | null
nullable: true
Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all.
##### `edgeTTL`
type: number | null
nullable: true
Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all.
##### `bypassCache`
type: boolean
Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing.
#### `ASSET_NAMESPACE` (required for ES Modules)
type: KV Namespace Binding
The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`.
It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request.
In ES Modules format, this argument is required, and can be gotten from `env`.
##### ES Module
```js
return getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise)
},
},
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
},
)
```
##### Service Worker
```
return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE })
```
#### `ASSET_MANIFEST` (required for ES Modules)
type: text blob (JSON formatted) or object
The mapping of requested file path to the key stored on Cloudflare.
Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace.
In ES Modules format, this argument is required, and can be imported.
##### ES Module
```js
import manifestJSON from '__STATIC_CONTENT_MANIFEST'
let manifest = JSON.parse(manifestJSON)
manifest['index.html'] = 'index.special.html'
return getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise)
},
},
{
ASSET_MANIFEST: manifest,
// ...
},
)
```
##### Service Worker
```
let assetManifest = { "index.html": "index.special.html" }
return getAssetFromKV(event, { ASSET_MANIFEST: assetManifest })
```
#### `defaultMimeType` (optional)
type: string
This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`.
If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`.
#### `defaultDocument` (optional)
type: string
This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`.
# Helper functions
## `mapRequestToAsset`
mapRequestToAsset(Request) => Request
The default function for mapping incoming requests to keys in Cloudflare's KV.
Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace.
## `serveSinglePageApp`
serveSinglePageApp(Request) => Request
A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments.
```js
import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler'
...
let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })
```
# Cache revalidation and etags
All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: <filename>.<hash of file contents>.<extension>` (ex. `etag: index.54321.html`).
Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits:
- When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth.
- Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired.
#### Disable the `etag`
To turn `etags` **off**, you must bypass cache:
```js
/* Turn etags off */
let cacheControl = {
bypassCache: true,
}
```
#### Syntax and comparison context
`kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client.

View file

@ -1,36 +0,0 @@
import { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } from './types';
declare global {
var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string;
}
/**
* maps the path of incoming request to the request pathKey to look up
* in bucket and in cache
* e.g. for a path '/' returns '/index.html' which serves
* the content of bucket/index.html
* @param {Request} request incoming request
*/
declare const mapRequestToAsset: (request: Request, options?: Partial<Options>) => Request;
/**
* maps the path of incoming request to /index.html if it evaluates to
* any HTML file.
* @param {Request} request incoming request
*/
declare function serveSinglePageApp(request: Request, options?: Partial<Options>): Request;
/**
* takes the path of the incoming request, gathers the appropriate content from KV, and returns
* the response
*
* @param {FetchEvent} event the fetch event of the triggered request
* @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
* @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
* @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
* @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
* @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
* */
declare type Evt = {
request: Request;
waitUntil: (promise: Promise<any>) => void;
};
declare const getAssetFromKV: (event: Evt, options?: Partial<Options>) => Promise<Response>;
export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp };
export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError };

View file

@ -1,267 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.serveSinglePageApp = exports.mapRequestToAsset = exports.getAssetFromKV = void 0;
const mime = require("mime");
const types_1 = require("./types");
Object.defineProperty(exports, "MethodNotAllowedError", { enumerable: true, get: function () { return types_1.MethodNotAllowedError; } });
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return types_1.NotFoundError; } });
Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return types_1.InternalError; } });
const defaultCacheControl = {
browserTTL: null,
edgeTTL: 2 * 60 * 60 * 24,
bypassCache: false, // do not bypass Cloudflare's cache
};
const parseStringAsObject = (maybeString) => typeof maybeString === 'string' ? JSON.parse(maybeString) : maybeString;
const getAssetFromKVDefaultOptions = {
ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined,
ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== 'undefined'
? parseStringAsObject(__STATIC_CONTENT_MANIFEST)
: {},
cacheControl: defaultCacheControl,
defaultMimeType: 'text/plain',
defaultDocument: 'index.html',
pathIsEncoded: false,
};
function assignOptions(options) {
// Assign any missing options passed in to the default
// options.mapRequestToAsset is handled manually later
return Object.assign({}, getAssetFromKVDefaultOptions, options);
}
/**
* maps the path of incoming request to the request pathKey to look up
* in bucket and in cache
* e.g. for a path '/' returns '/index.html' which serves
* the content of bucket/index.html
* @param {Request} request incoming request
*/
const mapRequestToAsset = (request, options) => {
options = assignOptions(options);
const parsedUrl = new URL(request.url);
let pathname = parsedUrl.pathname;
if (pathname.endsWith('/')) {
// If path looks like a directory append options.defaultDocument
// e.g. If path is /about/ -> /about/index.html
pathname = pathname.concat(options.defaultDocument);
}
else if (!mime.getType(pathname)) {
// If path doesn't look like valid content
// e.g. /about.me -> /about.me/index.html
pathname = pathname.concat('/' + options.defaultDocument);
}
parsedUrl.pathname = pathname;
return new Request(parsedUrl.toString(), request);
};
exports.mapRequestToAsset = mapRequestToAsset;
/**
* maps the path of incoming request to /index.html if it evaluates to
* any HTML file.
* @param {Request} request incoming request
*/
function serveSinglePageApp(request, options) {
options = assignOptions(options);
// First apply the default handler, which already has logic to detect
// paths that should map to HTML files.
request = mapRequestToAsset(request, options);
const parsedUrl = new URL(request.url);
// Detect if the default handler decided to map to
// a HTML file in some specific directory.
if (parsedUrl.pathname.endsWith('.html')) {
// If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request);
}
else {
// The default handler decided this is not an HTML page. It's probably
// an image, CSS, or JS file. Leave it as-is.
return request;
}
}
exports.serveSinglePageApp = serveSinglePageApp;
const getAssetFromKV = async (event, options) => {
options = assignOptions(options);
const request = event.request;
const ASSET_NAMESPACE = options.ASSET_NAMESPACE;
const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST);
if (typeof ASSET_NAMESPACE === 'undefined') {
throw new types_1.InternalError(`there is no KV namespace bound to the script`);
}
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ''); // strip any preceding /'s
let pathIsEncoded = options.pathIsEncoded;
let requestKey;
// if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
// otherwise handle request as normal, with default mapRequestToAsset below
if (options.mapRequestToAsset) {
requestKey = options.mapRequestToAsset(request);
}
else if (ASSET_MANIFEST[rawPathKey]) {
requestKey = request;
}
else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
pathIsEncoded = true;
requestKey = request;
}
else {
const mappedRequest = mapRequestToAsset(request);
const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '');
if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
pathIsEncoded = true;
requestKey = mappedRequest;
}
else {
// use default mapRequestToAsset
requestKey = mapRequestToAsset(request, options);
}
}
const SUPPORTED_METHODS = ['GET', 'HEAD'];
if (!SUPPORTED_METHODS.includes(requestKey.method)) {
throw new types_1.MethodNotAllowedError(`${requestKey.method} is not a valid request method`);
}
const parsedUrl = new URL(requestKey.url);
const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname; // decode percentage encoded path only when necessary
// pathKey is the file path to look up in the manifest
let pathKey = pathname.replace(/^\/+/, ''); // remove prepended /
// @ts-ignore
const cache = caches.default;
let mimeType = mime.getType(pathKey) || options.defaultMimeType;
if (mimeType.startsWith('text') || mimeType === 'application/javascript') {
mimeType += '; charset=utf-8';
}
let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash
// check manifest for map from file path to hash
if (typeof ASSET_MANIFEST !== 'undefined') {
if (ASSET_MANIFEST[pathKey]) {
pathKey = ASSET_MANIFEST[pathKey];
// if path key is in asset manifest, we can assume it contains a content hash and can be cached
shouldEdgeCache = true;
}
}
// TODO this excludes search params from cache, investigate ideal behavior
let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
// if argument passed in for cacheControl is a function then
// evaluate that function. otherwise return the Object passed in
// or default Object
const evalCacheOpts = (() => {
switch (typeof options.cacheControl) {
case 'function':
return options.cacheControl(request);
case 'object':
return options.cacheControl;
default:
return defaultCacheControl;
}
})();
// formats the etag depending on the response context. if the entityId
// is invalid, returns an empty string (instead of null) to prevent the
// the potentially disastrous scenario where the value of the Etag resp
// header is "null". Could be modified in future to base64 encode etc
const formatETag = (entityId = pathKey, validatorType = 'strong') => {
if (!entityId) {
return '';
}
switch (validatorType) {
case 'weak':
if (!entityId.startsWith('W/')) {
return `W/${entityId}`;
}
return entityId;
case 'strong':
if (entityId.startsWith(`W/"`)) {
entityId = entityId.replace('W/', '');
}
if (!entityId.endsWith(`"`)) {
entityId = `"${entityId}"`;
}
return entityId;
default:
return '';
}
};
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts);
// override shouldEdgeCache if options say to bypassCache
if (options.cacheControl.bypassCache ||
options.cacheControl.edgeTTL === null ||
request.method == 'HEAD') {
shouldEdgeCache = false;
}
// only set max-age if explicitly passed in a number as an arg
const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number';
let response = null;
if (shouldEdgeCache) {
response = await cache.match(cacheKey);
}
if (response) {
if (response.status > 300 && response.status < 400) {
if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) {
// Body exists and environment supports readable streams
response.body.cancel();
}
else {
// Environment doesnt support readable streams, or null repsonse body. Nothing to do
}
response = new Response(null, response);
}
else {
// fixes #165
let opts = {
headers: new Headers(response.headers),
status: 0,
statusText: '',
};
opts.headers.set('cf-cache-status', 'HIT');
if (response.status) {
opts.status = response.status;
opts.statusText = response.statusText;
}
else if (opts.headers.has('Content-Range')) {
opts.status = 206;
opts.statusText = 'Partial Content';
}
else {
opts.status = 200;
opts.statusText = 'OK';
}
response = new Response(response.body, opts);
}
}
else {
const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer');
if (body === null) {
throw new types_1.NotFoundError(`could not find ${pathKey} in your content namespace`);
}
response = new Response(body);
if (shouldEdgeCache) {
response.headers.set('Accept-Ranges', 'bytes');
response.headers.set('Content-Length', body.length);
// set etag before cache insertion
if (!response.headers.has('etag')) {
response.headers.set('etag', formatETag(pathKey, 'strong'));
}
// determine Cloudflare cache behavior
response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`);
event.waitUntil(cache.put(cacheKey, response.clone()));
response.headers.set('CF-Cache-Status', 'MISS');
}
}
response.headers.set('Content-Type', mimeType);
if (response.status === 304) {
let etag = formatETag(response.headers.get('etag'), 'strong');
let ifNoneMatch = cacheKey.headers.get('if-none-match');
let proxyCacheStatus = response.headers.get('CF-Cache-Status');
if (etag) {
if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') {
response.headers.set('CF-Cache-Status', 'EXPIRED');
}
else {
response.headers.set('CF-Cache-Status', 'REVALIDATED');
}
response.headers.set('etag', formatETag(etag, 'weak'));
}
}
if (shouldSetBrowserCache) {
response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`);
}
else {
response.headers.delete('Cache-Control');
}
return response;
};
exports.getAssetFromKV = getAssetFromKV;

View file

@ -1,14 +0,0 @@
export declare const getEvent: (request: Request) => any;
export declare const mockKV: (store: any) => {
get: (path: string) => any;
};
export declare const mockManifest: () => string;
export declare const mockCaches: () => {
default: {
match(key: any): Promise<any>;
put(key: any, val: Response): Promise<void>;
};
};
export declare function mockRequestScope(): void;
export declare function mockGlobalScope(): void;
export declare const sleep: (milliseconds: number) => Promise<unknown>;

View file

@ -1,146 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sleep = exports.mockGlobalScope = exports.mockRequestScope = exports.mockCaches = exports.mockManifest = exports.mockKV = exports.getEvent = void 0;
const makeServiceWorkerEnv = require('service-worker-mock');
const HASH = '123HASHBROWN';
const getEvent = (request) => {
const waitUntil = async (callback) => {
await callback;
};
return {
request,
waitUntil,
};
};
exports.getEvent = getEvent;
const store = {
'key1.123HASHBROWN.txt': 'val1',
'key1.123HASHBROWN.png': 'val1',
'index.123HASHBROWN.html': 'index.html',
'cache.123HASHBROWN.html': 'cache me if you can',
'测试.123HASHBROWN.html': 'My filename is non-ascii',
'%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded',
'%2F.123HASHBROWN.html': 'user percent encoded',
'你好.123HASHBROWN.html': 'I shouldnt be served',
'%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important',
'nohash.txt': 'no hash but still got some result',
'sub/blah.123HASHBROWN.png': 'picturedis',
'sub/index.123HASHBROWN.html': 'picturedis',
'client.123HASHBROWN': 'important file',
'client.123HASHBROWN/index.html': 'Im here but serve my big bro above',
'image.123HASHBROWN.png': 'imagepng',
'image.123HASHBROWN.webp': 'imagewebp',
'你好/index.123HASHBROWN.html': 'My path is non-ascii',
};
const mockKV = (store) => {
return {
get: (path) => store[path] || null,
};
};
exports.mockKV = mockKV;
const mockManifest = () => {
return JSON.stringify({
'key1.txt': `key1.${HASH}.txt`,
'key1.png': `key1.${HASH}.png`,
'cache.html': `cache.${HASH}.html`,
'测试.html': `测试.${HASH}.html`,
'你好.html': `你好.${HASH}.html`,
'%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`,
'%2F.html': `%2F.${HASH}.html`,
'%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`,
'index.html': `index.${HASH}.html`,
'sub/blah.png': `sub/blah.${HASH}.png`,
'sub/index.html': `sub/index.${HASH}.html`,
client: `client.${HASH}`,
'client/index.html': `client.${HASH}`,
'image.png': `image.${HASH}.png`,
'image.webp': `image.${HASH}.webp`,
'你好/index.html': `你好/index.${HASH}.html`,
});
};
exports.mockManifest = mockManifest;
let cacheStore = new Map();
const mockCaches = () => {
return {
default: {
async match(key) {
let cacheKey = {
url: key.url,
headers: {},
};
let response;
if (key.headers.has('if-none-match')) {
let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '');
Reflect.set(cacheKey.headers, 'etag', makeStrongEtag);
response = cacheStore.get(JSON.stringify(cacheKey));
}
else {
// if client doesn't send if-none-match, we need to iterate through these keys
// and just test the URL
const activeCacheKeys = Array.from(cacheStore.keys());
for (const cacheStoreKey of activeCacheKeys) {
if (JSON.parse(cacheStoreKey).url === key.url) {
response = cacheStore.get(cacheStoreKey);
}
}
}
// TODO: write test to accomodate for rare scenarios with where range requests accomodate etags
if (response && !key.headers.has('if-none-match')) {
// this appears overly verbose, but is necessary to document edge cache behavior
// The Range request header triggers the response header Content-Range ...
const range = key.headers.get('range');
if (range) {
response.headers.set('content-range', `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`);
}
// ... which we are using in this repository to set status 206
if (response.headers.has('content-range')) {
response.status = 206;
}
else {
response.status = 200;
}
let etag = response.headers.get('etag');
if (etag && !etag.includes('W/')) {
response.headers.set('etag', `W/${etag}`);
}
}
return response;
},
async put(key, val) {
let headers = new Headers(val.headers);
let url = new URL(key.url);
let resWithBody = new Response(val.body, { headers, status: 200 });
let resNoBody = new Response(null, { headers, status: 304 });
let cacheKey = {
url: key.url,
headers: {
etag: `"${url.pathname.replace('/', '')}"`,
},
};
cacheStore.set(JSON.stringify(cacheKey), resNoBody);
cacheKey.headers = {};
cacheStore.set(JSON.stringify(cacheKey), resWithBody);
return;
},
},
};
};
exports.mockCaches = mockCaches;
// mocks functionality used inside worker request
function mockRequestScope() {
Object.assign(global, makeServiceWorkerEnv());
Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() });
Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) });
Object.assign(global, { caches: (0, exports.mockCaches)() });
}
exports.mockRequestScope = mockRequestScope;
// mocks functionality used on global isolate scope. such as the KV namespace bind
function mockGlobalScope() {
Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() });
Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) });
}
exports.mockGlobalScope = mockGlobalScope;
const sleep = (milliseconds) => {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
};
exports.sleep = sleep;

View file

@ -1 +0,0 @@
export {};

View file

@ -1,22 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const mocks_1 = require("../mocks");
(0, mocks_1.mockGlobalScope)();
// manually reset manifest global, to test optional behaviour
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined });
const index_1 = require("../index");
(0, ava_1.default)('getAssetFromKV return correct val from KV without manifest', async (t) => {
(0, mocks_1.mockRequestScope)();
// manually reset manifest global, to test optional behaviour
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined });
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.123HASHBROWN.txt'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'val1');
t.true(res.headers.get('content-type').includes('text'));
}
else {
t.fail('Response was undefined');
}
});

View file

@ -1 +0,0 @@
export {};

View file

@ -1,446 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const mocks_1 = require("../mocks");
(0, mocks_1.mockGlobalScope)();
const index_1 = require("../index");
(0, ava_1.default)('getAssetFromKV return correct val from KV and default caching', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.txt'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(res.headers.get('cache-control'), null);
t.is(res.headers.get('cf-cache-status'), 'MISS');
t.is(await res.text(), 'val1');
t.true(res.headers.get('content-type').includes('text'));
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client/`));
const res = await (0, index_1.getAssetFromKV)(event);
t.is(await res.text(), 'important file');
t.true(res.headers.get('content-type').includes('text'));
});
(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`));
const res = await (0, index_1.getAssetFromKV)(event);
t.is(await res.text(), 'important file');
t.true(res.headers.get('content-type').includes('text'));
});
(0, ava_1.default)('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/nohash.txt'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'no hash but still got some result');
t.true(res.headers.get('content-type').includes('text'));
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV if no asset manifest /client -> client fails', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`));
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_MANIFEST: {} }));
t.is(error.status, 404);
});
(0, ava_1.default)('getAssetFromKV if sub/ -> sub/index.html served', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/sub`));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'picturedis');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV gets index.html by default for / requests', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'index.html');
t.true(res.headers.get('content-type').includes('html'));
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV non ASCII path support', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/测试.html'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'My filename is non-ascii');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV supports browser percent encoded URLs', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://example.com/%not-really-percent-encoded.html'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'browser percent encoded');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV supports user percent encoded URLs', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/%2F.html'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'user percent encoded');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV only decode URL when necessary', async (t) => {
(0, mocks_1.mockRequestScope)();
const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html'));
const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好.html'));
const res1 = await (0, index_1.getAssetFromKV)(event1);
const res2 = await (0, index_1.getAssetFromKV)(event2);
if (res1 && res2) {
t.is(await res1.text(), 'Im important');
t.is(await res2.text(), 'Im important');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV Support for user decode url path', async (t) => {
(0, mocks_1.mockRequestScope)();
const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/'));
const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好/'));
const res1 = await (0, index_1.getAssetFromKV)(event1);
const res2 = await (0, index_1.getAssetFromKV)(event2);
if (res1 && res2) {
t.is(await res1.text(), 'My path is non-ascii');
t.is(await res2.text(), 'My path is non-ascii');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV custom key modifier', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/docs/sub/blah.png'));
const customRequestMapper = (request) => {
let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request);
let url = new URL(defaultModifiedRequest.url);
url.pathname = url.pathname.replace('/docs', '');
return new Request(url.toString(), request);
};
const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper });
if (res) {
t.is(await res.text(), 'picturedis');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV request override with existing manifest file', async (t) => {
// see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/image.png')); // real file in manifest
const customRequestMapper = (request) => {
let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request);
let url = new URL(defaultModifiedRequest.url);
url.pathname = '/image.webp'; // other different file in manifest
return new Request(url.toString(), request);
};
const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper });
if (res) {
t.is(await res.text(), 'imagewebp');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV when setting browser caching', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: 22 } });
if (res) {
t.is(res.headers.get('cache-control'), 'max-age=22');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV when setting custom cache setting', async (t) => {
(0, mocks_1.mockRequestScope)();
const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.png?blah=34'));
const cacheOnlyPngs = (req) => {
if (new URL(req.url).pathname.endsWith('.png'))
return {
browserTTL: 720,
edgeTTL: 720,
};
else
return {
bypassCache: true,
};
};
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: cacheOnlyPngs });
const res2 = await (0, index_1.getAssetFromKV)(event2, { cacheControl: cacheOnlyPngs });
if (res1 && res2) {
t.is(res1.headers.get('cache-control'), null);
t.true(res2.headers.get('content-type').includes('png'));
t.is(res2.headers.get('cache-control'), 'max-age=720');
t.is(res2.headers.get('cf-cache-status'), 'MISS');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV caches on two sequential requests', async (t) => {
(0, mocks_1.mockRequestScope)();
const resourceKey = 'cache.html';
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
}));
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } });
await (0, mocks_1.sleep)(1);
const res2 = await (0, index_1.getAssetFromKV)(event2);
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS');
t.is(res1.headers.get('cache-control'), 'max-age=720');
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV does not store max-age on two sequential requests', async (t) => {
(0, mocks_1.mockRequestScope)();
const resourceKey = 'cache.html';
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
}));
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } });
await (0, mocks_1.sleep)(100);
const res2 = await (0, index_1.getAssetFromKV)(event2);
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS');
t.is(res1.headers.get('cache-control'), null);
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
t.is(res2.headers.get('cache-control'), null);
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { bypassCache: true } });
if (res) {
t.is(res.headers.get('cache-control'), null);
t.is(res.headers.get('cf-cache-status'), null);
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV with no trailing slash on root', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'index.html');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV with no trailing slash on a subdirectory', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/sub/blah.png'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'picturedis');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV no result throws an error', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/random'));
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event));
t.is(error.status, 404);
});
(0, ava_1.default)('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => {
(0, mocks_1.mockRequestScope)();
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } });
await (0, mocks_1.sleep)(100);
const res2 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } });
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), null);
t.is(res1.headers.get('cache-control'), null);
t.is(res2.headers.get('cf-cache-status'), null);
t.is(res2.headers.get('cache-control'), null);
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => {
(0, mocks_1.mockRequestScope)();
let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({
'key1.123HASHBROWN.txt': 'val1',
});
Object.assign(global, { CUSTOM_NAMESPACE });
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const res = await (0, index_1.getAssetFromKV)(event);
if (res) {
t.is(await res.text(), 'index.html');
t.true(res.headers.get('content-type').includes('html'));
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV when custom namespace without the asset should fail', async (t) => {
(0, mocks_1.mockRequestScope)();
let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({
'key5.123HASHBROWN.txt': 'customvalu',
});
const event = (0, mocks_1.getEvent)(new Request('https://blah.com'));
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE }));
t.is(error.status, 404);
});
(0, ava_1.default)('getAssetFromKV when namespace not bound fails', async (t) => {
(0, mocks_1.mockRequestScope)();
var MY_CUSTOM_NAMESPACE = undefined;
Object.assign(global, { MY_CUSTOM_NAMESPACE });
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE }));
t.is(error.status, 500);
});
(0, ava_1.default)('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => {
(0, mocks_1.mockRequestScope)();
const resourceKey = 'key1.png';
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `W/"${resourceVersion}"`,
},
}));
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } });
await (0, mocks_1.sleep)(100);
const res2 = await (0, index_1.getAssetFromKV)(event2);
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS');
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => {
(0, mocks_1.mockRequestScope)();
const resourceKey = 'key1.png';
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
const req1 = new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
});
const req2 = new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}-another-version"`,
},
});
const event = (0, mocks_1.getEvent)(req1);
const event2 = (0, mocks_1.getEvent)(req2);
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } });
const res2 = await (0, index_1.getAssetFromKV)(event);
const res3 = await (0, index_1.getAssetFromKV)(event2);
if (res1 && res2 && res3) {
t.is(res1.headers.get('cf-cache-status'), 'MISS');
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`);
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
t.not(res3.headers.get('etag'), req2.headers.get('if-none-match'));
t.is(res3.headers.get('cf-cache-status'), 'MISS');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => {
(0, mocks_1.mockRequestScope)();
const resourceKey = 'key1.png';
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
const req1 = new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
});
const event = (0, mocks_1.getEvent)(req1);
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } });
const res2 = await (0, index_1.getAssetFromKV)(event);
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS');
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`);
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => {
const resourceKey = 'cache.html';
const event = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } });
await (0, mocks_1.sleep)(1);
const res2 = await (0, index_1.getAssetFromKV)(event);
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS');
t.is(res1.headers.get('cache-control'), null);
t.is(res2.status, 200);
t.is(res2.headers.get('cf-cache-status'), 'HIT');
}
else {
t.fail('Response was undefined');
}
});
(0, ava_1.default)('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => {
const resourceKey = 'cache.html';
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } }));
const res1 = (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } });
await res1;
await (0, mocks_1.sleep)(2);
const res2 = await (0, index_1.getAssetFromKV)(event2);
if (res2.headers.has('content-range')) {
t.is(res2.status, 206);
}
else {
t.fail('Response was undefined');
}
});
ava_1.default.todo('getAssetFromKV when body not empty, should invoke .cancel()');

View file

@ -1 +0,0 @@
export {};

View file

@ -1,34 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const mocks_1 = require("../mocks");
(0, mocks_1.mockGlobalScope)();
const index_1 = require("../index");
(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => {
(0, mocks_1.mockRequestScope)();
let path = '/about';
let request = new Request(`https://foo.com${path}`);
let newRequest = (0, index_1.mapRequestToAsset)(request);
t.is(newRequest.url, request.url + '/index.html');
});
(0, ava_1.default)('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => {
(0, mocks_1.mockRequestScope)();
let path = '/about/';
let request = new Request(`https://foo.com${path}`);
let newRequest = (0, index_1.mapRequestToAsset)(request);
t.is(newRequest.url, request.url + 'index.html');
});
(0, ava_1.default)('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => {
(0, mocks_1.mockRequestScope)();
let path = '/about.me/';
let request = new Request(`https://foo.com${path}`);
let newRequest = (0, index_1.mapRequestToAsset)(request);
t.is(newRequest.url, request.url + 'index.html');
});
(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => {
(0, mocks_1.mockRequestScope)();
let path = '/about';
let request = new Request(`https://foo.com${path}`);
let newRequest = (0, index_1.mapRequestToAsset)(request, { defaultDocument: 'default.html' });
t.is(newRequest.url, request.url + '/default.html');
});

View file

@ -1 +0,0 @@
export {};

View file

@ -1,34 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = require("ava");
const mocks_1 = require("../mocks");
(0, mocks_1.mockGlobalScope)();
const index_1 = require("../index");
function testRequest(path) {
(0, mocks_1.mockRequestScope)();
let url = new URL('https://example.com');
url.pathname = path;
let request = new Request(url.toString());
return request;
}
(0, ava_1.default)('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => {
let path = '/foo/thing.html';
let request = testRequest(path);
let expected_request = testRequest('/index.html');
let actual_request = (0, index_1.serveSinglePageApp)(request);
t.deepEqual(expected_request, actual_request);
});
(0, ava_1.default)('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => {
let path = '/foo/thing';
let request = testRequest(path);
let expected_request = testRequest('/index.html');
let actual_request = (0, index_1.serveSinglePageApp)(request);
t.deepEqual(expected_request, actual_request);
});
(0, ava_1.default)('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => {
let path = '/foo/thing.js';
let request = testRequest(path);
let expected_request = request;
let actual_request = (0, index_1.serveSinglePageApp)(request);
t.deepEqual(expected_request, actual_request);
});

View file

@ -1,28 +0,0 @@
export declare type CacheControl = {
browserTTL: number;
edgeTTL: number;
bypassCache: boolean;
};
export declare type AssetManifestType = Record<string, string>;
export declare type Options = {
cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl>;
ASSET_NAMESPACE: any;
ASSET_MANIFEST: AssetManifestType | string;
mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request;
defaultMimeType: string;
defaultDocument: string;
pathIsEncoded: boolean;
};
export declare class KVError extends Error {
constructor(message?: string, status?: number);
status: number;
}
export declare class MethodNotAllowedError extends KVError {
constructor(message?: string, status?: number);
}
export declare class NotFoundError extends KVError {
constructor(message?: string, status?: number);
}
export declare class InternalError extends KVError {
constructor(message?: string, status?: number);
}

View file

@ -1,31 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.KVError = void 0;
class KVError extends Error {
constructor(message, status = 500) {
super(message);
// see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
this.name = KVError.name; // stack traces display correctly now
this.status = status;
}
}
exports.KVError = KVError;
class MethodNotAllowedError extends KVError {
constructor(message = `Not a valid request method`, status = 405) {
super(message, status);
}
}
exports.MethodNotAllowedError = MethodNotAllowedError;
class NotFoundError extends KVError {
constructor(message = `Not Found`, status = 404) {
super(message, status);
}
}
exports.NotFoundError = NotFoundError;
class InternalError extends KVError {
constructor(message = `Internal Error in KV Asset Handler`, status = 500) {
super(message, status);
}
}
exports.InternalError = InternalError;

View file

@ -1,52 +0,0 @@
{
"name": "@cloudflare/kv-asset-handler",
"version": "0.2.0",
"description": "Routes requests to KV assets",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"prepack": "npm run build",
"build": "tsc -d",
"format": "prettier --write \"**/*.{js,ts,json,md}\"",
"pretest": "npm run build",
"lint:code": "prettier --check \"**/*.{js,ts,json,md}\"",
"lint:markdown": "markdownlint \"**/*.md\" --ignore node_modules",
"test": "ava dist/test/*.js --verbose"
},
"repository": {
"type": "git",
"url": "git+https://github.com/cloudflare/kv-asset-handler.git"
},
"keywords": [
"kv",
"cloudflare",
"workers",
"wrangler",
"assets"
],
"files": [
"src",
"dist",
"LICENSE_APACHE",
"LICENSE_MIT"
],
"author": "wrangler@cloudflare.com",
"license": "MIT OR Apache-2.0",
"bugs": {
"url": "https://github.com/cloudflare/kv-asset-handler/issues"
},
"homepage": "https://github.com/cloudflare/kv-asset-handler#readme",
"dependencies": {
"mime": "^3.0.0"
},
"devDependencies": {
"@ava/typescript": "^3.0.0",
"@cloudflare/workers-types": "^3.0.0",
"@types/mime": "^2.0.3",
"@types/node": "^15.14.9",
"ava": "^3.15.0",
"prettier": "^2.4.1",
"service-worker-mock": "^2.0.5",
"typescript": "^4.4.4"
}
}

View file

@ -1,312 +0,0 @@
import * as mime from 'mime'
import {
Options,
CacheControl,
MethodNotAllowedError,
NotFoundError,
InternalError,
AssetManifestType,
} from './types'
declare global {
var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string
}
const defaultCacheControl: CacheControl = {
browserTTL: null,
edgeTTL: 2 * 60 * 60 * 24, // 2 days
bypassCache: false, // do not bypass Cloudflare's cache
}
const parseStringAsObject = <T>(maybeString: string | T): T =>
typeof maybeString === 'string' ? (JSON.parse(maybeString) as T) : maybeString
const getAssetFromKVDefaultOptions: Partial<Options> = {
ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined,
ASSET_MANIFEST:
typeof __STATIC_CONTENT_MANIFEST !== 'undefined'
? parseStringAsObject<AssetManifestType>(__STATIC_CONTENT_MANIFEST)
: {},
cacheControl: defaultCacheControl,
defaultMimeType: 'text/plain',
defaultDocument: 'index.html',
pathIsEncoded: false,
}
function assignOptions(options?: Partial<Options>): Options {
// Assign any missing options passed in to the default
// options.mapRequestToAsset is handled manually later
return <Options>Object.assign({}, getAssetFromKVDefaultOptions, options)
}
/**
* maps the path of incoming request to the request pathKey to look up
* in bucket and in cache
* e.g. for a path '/' returns '/index.html' which serves
* the content of bucket/index.html
* @param {Request} request incoming request
*/
const mapRequestToAsset = (request: Request, options?: Partial<Options>) => {
options = assignOptions(options)
const parsedUrl = new URL(request.url)
let pathname = parsedUrl.pathname
if (pathname.endsWith('/')) {
// If path looks like a directory append options.defaultDocument
// e.g. If path is /about/ -> /about/index.html
pathname = pathname.concat(options.defaultDocument)
} else if (!mime.getType(pathname)) {
// If path doesn't look like valid content
// e.g. /about.me -> /about.me/index.html
pathname = pathname.concat('/' + options.defaultDocument)
}
parsedUrl.pathname = pathname
return new Request(parsedUrl.toString(), request)
}
/**
* maps the path of incoming request to /index.html if it evaluates to
* any HTML file.
* @param {Request} request incoming request
*/
function serveSinglePageApp(request: Request, options?: Partial<Options>): Request {
options = assignOptions(options)
// First apply the default handler, which already has logic to detect
// paths that should map to HTML files.
request = mapRequestToAsset(request, options)
const parsedUrl = new URL(request.url)
// Detect if the default handler decided to map to
// a HTML file in some specific directory.
if (parsedUrl.pathname.endsWith('.html')) {
// If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request)
} else {
// The default handler decided this is not an HTML page. It's probably
// an image, CSS, or JS file. Leave it as-is.
return request
}
}
/**
* takes the path of the incoming request, gathers the appropriate content from KV, and returns
* the response
*
* @param {FetchEvent} event the fetch event of the triggered request
* @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
* @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
* @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
* @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
* @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
* */
type Evt = {
request: Request
waitUntil: (promise: Promise<any>) => void
}
const getAssetFromKV = async (event: Evt, options?: Partial<Options>): Promise<Response> => {
options = assignOptions(options)
const request = event.request
const ASSET_NAMESPACE = options.ASSET_NAMESPACE
const ASSET_MANIFEST = parseStringAsObject<AssetManifestType>(options.ASSET_MANIFEST)
if (typeof ASSET_NAMESPACE === 'undefined') {
throw new InternalError(`there is no KV namespace bound to the script`)
}
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, '') // strip any preceding /'s
let pathIsEncoded = options.pathIsEncoded
let requestKey
// if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
// otherwise handle request as normal, with default mapRequestToAsset below
if (options.mapRequestToAsset) {
requestKey = options.mapRequestToAsset(request)
} else if (ASSET_MANIFEST[rawPathKey]) {
requestKey = request
} else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
pathIsEncoded = true
requestKey = request
} else {
const mappedRequest = mapRequestToAsset(request)
const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '')
if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
pathIsEncoded = true
requestKey = mappedRequest
} else {
// use default mapRequestToAsset
requestKey = mapRequestToAsset(request, options)
}
}
const SUPPORTED_METHODS = ['GET', 'HEAD']
if (!SUPPORTED_METHODS.includes(requestKey.method)) {
throw new MethodNotAllowedError(`${requestKey.method} is not a valid request method`)
}
const parsedUrl = new URL(requestKey.url)
const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname // decode percentage encoded path only when necessary
// pathKey is the file path to look up in the manifest
let pathKey = pathname.replace(/^\/+/, '') // remove prepended /
// @ts-ignore
const cache = caches.default
let mimeType = mime.getType(pathKey) || options.defaultMimeType
if (mimeType.startsWith('text') || mimeType === 'application/javascript') {
mimeType += '; charset=utf-8'
}
let shouldEdgeCache = false // false if storing in KV by raw file path i.e. no hash
// check manifest for map from file path to hash
if (typeof ASSET_MANIFEST !== 'undefined') {
if (ASSET_MANIFEST[pathKey]) {
pathKey = ASSET_MANIFEST[pathKey]
// if path key is in asset manifest, we can assume it contains a content hash and can be cached
shouldEdgeCache = true
}
}
// TODO this excludes search params from cache, investigate ideal behavior
let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request)
// if argument passed in for cacheControl is a function then
// evaluate that function. otherwise return the Object passed in
// or default Object
const evalCacheOpts = (() => {
switch (typeof options.cacheControl) {
case 'function':
return options.cacheControl(request)
case 'object':
return options.cacheControl
default:
return defaultCacheControl
}
})()
// formats the etag depending on the response context. if the entityId
// is invalid, returns an empty string (instead of null) to prevent the
// the potentially disastrous scenario where the value of the Etag resp
// header is "null". Could be modified in future to base64 encode etc
const formatETag = (entityId: any = pathKey, validatorType: string = 'strong') => {
if (!entityId) {
return ''
}
switch (validatorType) {
case 'weak':
if (!entityId.startsWith('W/')) {
return `W/${entityId}`
}
return entityId
case 'strong':
if (entityId.startsWith(`W/"`)) {
entityId = entityId.replace('W/', '')
}
if (!entityId.endsWith(`"`)) {
entityId = `"${entityId}"`
}
return entityId
default:
return ''
}
}
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts)
// override shouldEdgeCache if options say to bypassCache
if (
options.cacheControl.bypassCache ||
options.cacheControl.edgeTTL === null ||
request.method == 'HEAD'
) {
shouldEdgeCache = false
}
// only set max-age if explicitly passed in a number as an arg
const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number'
let response = null
if (shouldEdgeCache) {
response = await cache.match(cacheKey)
}
if (response) {
if (response.status > 300 && response.status < 400) {
if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) {
// Body exists and environment supports readable streams
response.body.cancel()
} else {
// Environment doesnt support readable streams, or null repsonse body. Nothing to do
}
response = new Response(null, response)
} else {
// fixes #165
let opts = {
headers: new Headers(response.headers),
status: 0,
statusText: '',
}
opts.headers.set('cf-cache-status', 'HIT')
if (response.status) {
opts.status = response.status
opts.statusText = response.statusText
} else if (opts.headers.has('Content-Range')) {
opts.status = 206
opts.statusText = 'Partial Content'
} else {
opts.status = 200
opts.statusText = 'OK'
}
response = new Response(response.body, opts)
}
} else {
const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer')
if (body === null) {
throw new NotFoundError(`could not find ${pathKey} in your content namespace`)
}
response = new Response(body)
if (shouldEdgeCache) {
response.headers.set('Accept-Ranges', 'bytes')
response.headers.set('Content-Length', body.length)
// set etag before cache insertion
if (!response.headers.has('etag')) {
response.headers.set('etag', formatETag(pathKey, 'strong'))
}
// determine Cloudflare cache behavior
response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`)
event.waitUntil(cache.put(cacheKey, response.clone()))
response.headers.set('CF-Cache-Status', 'MISS')
}
}
response.headers.set('Content-Type', mimeType)
if (response.status === 304) {
let etag = formatETag(response.headers.get('etag'), 'strong')
let ifNoneMatch = cacheKey.headers.get('if-none-match')
let proxyCacheStatus = response.headers.get('CF-Cache-Status')
if (etag) {
if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') {
response.headers.set('CF-Cache-Status', 'EXPIRED')
} else {
response.headers.set('CF-Cache-Status', 'REVALIDATED')
}
response.headers.set('etag', formatETag(etag, 'weak'))
}
}
if (shouldSetBrowserCache) {
response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`)
} else {
response.headers.delete('Cache-Control')
}
return response
}
export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp }
export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError }

View file

@ -1,148 +0,0 @@
const makeServiceWorkerEnv = require('service-worker-mock')
const HASH = '123HASHBROWN'
export const getEvent = (request: Request): any => {
const waitUntil = async (callback: any) => {
await callback
}
return {
request,
waitUntil,
}
}
const store: any = {
'key1.123HASHBROWN.txt': 'val1',
'key1.123HASHBROWN.png': 'val1',
'index.123HASHBROWN.html': 'index.html',
'cache.123HASHBROWN.html': 'cache me if you can',
'测试.123HASHBROWN.html': 'My filename is non-ascii',
'%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded',
'%2F.123HASHBROWN.html': 'user percent encoded',
'你好.123HASHBROWN.html': 'I shouldnt be served',
'%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important',
'nohash.txt': 'no hash but still got some result',
'sub/blah.123HASHBROWN.png': 'picturedis',
'sub/index.123HASHBROWN.html': 'picturedis',
'client.123HASHBROWN': 'important file',
'client.123HASHBROWN/index.html': 'Im here but serve my big bro above',
'image.123HASHBROWN.png': 'imagepng',
'image.123HASHBROWN.webp': 'imagewebp',
'你好/index.123HASHBROWN.html': 'My path is non-ascii',
}
export const mockKV = (store: any) => {
return {
get: (path: string) => store[path] || null,
}
}
export const mockManifest = () => {
return JSON.stringify({
'key1.txt': `key1.${HASH}.txt`,
'key1.png': `key1.${HASH}.png`,
'cache.html': `cache.${HASH}.html`,
'测试.html': `测试.${HASH}.html`,
'你好.html': `你好.${HASH}.html`,
'%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`,
'%2F.html': `%2F.${HASH}.html`,
'%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`,
'index.html': `index.${HASH}.html`,
'sub/blah.png': `sub/blah.${HASH}.png`,
'sub/index.html': `sub/index.${HASH}.html`,
client: `client.${HASH}`,
'client/index.html': `client.${HASH}`,
'image.png': `image.${HASH}.png`,
'image.webp': `image.${HASH}.webp`,
'你好/index.html': `你好/index.${HASH}.html`,
})
}
let cacheStore: any = new Map()
interface CacheKey {
url: object
headers: object
}
export const mockCaches = () => {
return {
default: {
async match(key: any) {
let cacheKey: CacheKey = {
url: key.url,
headers: {},
}
let response
if (key.headers.has('if-none-match')) {
let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '')
Reflect.set(cacheKey.headers, 'etag', makeStrongEtag)
response = cacheStore.get(JSON.stringify(cacheKey))
} else {
// if client doesn't send if-none-match, we need to iterate through these keys
// and just test the URL
const activeCacheKeys: Array<string> = Array.from(cacheStore.keys())
for (const cacheStoreKey of activeCacheKeys) {
if (JSON.parse(cacheStoreKey).url === key.url) {
response = cacheStore.get(cacheStoreKey)
}
}
}
// TODO: write test to accomodate for rare scenarios with where range requests accomodate etags
if (response && !key.headers.has('if-none-match')) {
// this appears overly verbose, but is necessary to document edge cache behavior
// The Range request header triggers the response header Content-Range ...
const range = key.headers.get('range')
if (range) {
response.headers.set(
'content-range',
`bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`,
)
}
// ... which we are using in this repository to set status 206
if (response.headers.has('content-range')) {
response.status = 206
} else {
response.status = 200
}
let etag = response.headers.get('etag')
if (etag && !etag.includes('W/')) {
response.headers.set('etag', `W/${etag}`)
}
}
return response
},
async put(key: any, val: Response) {
let headers = new Headers(val.headers)
let url = new URL(key.url)
let resWithBody = new Response(val.body, { headers, status: 200 })
let resNoBody = new Response(null, { headers, status: 304 })
let cacheKey: CacheKey = {
url: key.url,
headers: {
etag: `"${url.pathname.replace('/', '')}"`,
},
}
cacheStore.set(JSON.stringify(cacheKey), resNoBody)
cacheKey.headers = {}
cacheStore.set(JSON.stringify(cacheKey), resWithBody)
return
},
},
}
}
// mocks functionality used inside worker request
export function mockRequestScope() {
Object.assign(global, makeServiceWorkerEnv())
Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() })
Object.assign(global, { __STATIC_CONTENT: mockKV(store) })
Object.assign(global, { caches: mockCaches() })
}
// mocks functionality used on global isolate scope. such as the KV namespace bind
export function mockGlobalScope() {
Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() })
Object.assign(global, { __STATIC_CONTENT: mockKV(store) })
}
export const sleep = (milliseconds: number) => {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}

View file

@ -1,24 +0,0 @@
import test from 'ava'
import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks'
mockGlobalScope()
// manually reset manifest global, to test optional behaviour
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined })
import { getAssetFromKV, mapRequestToAsset } from '../index'
test('getAssetFromKV return correct val from KV without manifest', async (t) => {
mockRequestScope()
// manually reset manifest global, to test optional behaviour
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined })
const event = getEvent(new Request('https://blah.com/key1.123HASHBROWN.txt'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'val1')
t.true(res.headers.get('content-type').includes('text'))
} else {
t.fail('Response was undefined')
}
})

View file

@ -1,488 +0,0 @@
import test from 'ava'
import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks'
mockGlobalScope()
import { getAssetFromKV, mapRequestToAsset } from '../index'
import { KVError } from '../types'
test('getAssetFromKV return correct val from KV and default caching', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/key1.txt'))
const res = await getAssetFromKV(event)
if (res) {
t.is(res.headers.get('cache-control'), null)
t.is(res.headers.get('cf-cache-status'), 'MISS')
t.is(await res.text(), 'val1')
t.true(res.headers.get('content-type').includes('text'))
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => {
mockRequestScope()
const event = getEvent(new Request(`https://foo.com/client/`))
const res = await getAssetFromKV(event)
t.is(await res.text(), 'important file')
t.true(res.headers.get('content-type').includes('text'))
})
test('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => {
mockRequestScope()
const event = getEvent(new Request(`https://foo.com/client`))
const res = await getAssetFromKV(event)
t.is(await res.text(), 'important file')
t.true(res.headers.get('content-type').includes('text'))
})
test('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/nohash.txt'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'no hash but still got some result')
t.true(res.headers.get('content-type').includes('text'))
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV if no asset manifest /client -> client fails', async (t) => {
mockRequestScope()
const event = getEvent(new Request(`https://foo.com/client`))
const error: KVError = await t.throwsAsync(getAssetFromKV(event, { ASSET_MANIFEST: {} }))
t.is(error.status, 404)
})
test('getAssetFromKV if sub/ -> sub/index.html served', async (t) => {
mockRequestScope()
const event = getEvent(new Request(`https://foo.com/sub`))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'picturedis')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV gets index.html by default for / requests', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'index.html')
t.true(res.headers.get('content-type').includes('html'))
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV non ASCII path support', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/测试.html'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'My filename is non-ascii')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV supports browser percent encoded URLs', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://example.com/%not-really-percent-encoded.html'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'browser percent encoded')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV supports user percent encoded URLs', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/%2F.html'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'user percent encoded')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV only decode URL when necessary', async (t) => {
mockRequestScope()
const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html'))
const event2 = getEvent(new Request('https://blah.com/你好.html'))
const res1 = await getAssetFromKV(event1)
const res2 = await getAssetFromKV(event2)
if (res1 && res2) {
t.is(await res1.text(), 'Im important')
t.is(await res2.text(), 'Im important')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV Support for user decode url path', async (t) => {
mockRequestScope()
const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/'))
const event2 = getEvent(new Request('https://blah.com/你好/'))
const res1 = await getAssetFromKV(event1)
const res2 = await getAssetFromKV(event2)
if (res1 && res2) {
t.is(await res1.text(), 'My path is non-ascii')
t.is(await res2.text(), 'My path is non-ascii')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV custom key modifier', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/docs/sub/blah.png'))
const customRequestMapper = (request: Request) => {
let defaultModifiedRequest = mapRequestToAsset(request)
let url = new URL(defaultModifiedRequest.url)
url.pathname = url.pathname.replace('/docs', '')
return new Request(url.toString(), request)
}
const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper })
if (res) {
t.is(await res.text(), 'picturedis')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV request override with existing manifest file', async (t) => {
// see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info
mockRequestScope()
const event = getEvent(new Request('https://blah.com/image.png')) // real file in manifest
const customRequestMapper = (request: Request) => {
let defaultModifiedRequest = mapRequestToAsset(request)
let url = new URL(defaultModifiedRequest.url)
url.pathname = '/image.webp' // other different file in manifest
return new Request(url.toString(), request)
}
const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper })
if (res) {
t.is(await res.text(), 'imagewebp')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV when setting browser caching', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/'))
const res = await getAssetFromKV(event, { cacheControl: { browserTTL: 22 } })
if (res) {
t.is(res.headers.get('cache-control'), 'max-age=22')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV when setting custom cache setting', async (t) => {
mockRequestScope()
const event1 = getEvent(new Request('https://blah.com/'))
const event2 = getEvent(new Request('https://blah.com/key1.png?blah=34'))
const cacheOnlyPngs = (req: Request) => {
if (new URL(req.url).pathname.endsWith('.png'))
return {
browserTTL: 720,
edgeTTL: 720,
}
else
return {
bypassCache: true,
}
}
const res1 = await getAssetFromKV(event1, { cacheControl: cacheOnlyPngs })
const res2 = await getAssetFromKV(event2, { cacheControl: cacheOnlyPngs })
if (res1 && res2) {
t.is(res1.headers.get('cache-control'), null)
t.true(res2.headers.get('content-type').includes('png'))
t.is(res2.headers.get('cache-control'), 'max-age=720')
t.is(res2.headers.get('cf-cache-status'), 'MISS')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV caches on two sequential requests', async (t) => {
mockRequestScope()
const resourceKey = 'cache.html'
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
const event2 = getEvent(
new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
}),
)
const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } })
await sleep(1)
const res2 = await getAssetFromKV(event2)
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS')
t.is(res1.headers.get('cache-control'), 'max-age=720')
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV does not store max-age on two sequential requests', async (t) => {
mockRequestScope()
const resourceKey = 'cache.html'
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
const event2 = getEvent(
new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
}),
)
const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } })
await sleep(100)
const res2 = await getAssetFromKV(event2)
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS')
t.is(res1.headers.get('cache-control'), null)
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
t.is(res2.headers.get('cache-control'), null)
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/'))
const res = await getAssetFromKV(event, { cacheControl: { bypassCache: true } })
if (res) {
t.is(res.headers.get('cache-control'), null)
t.is(res.headers.get('cf-cache-status'), null)
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV with no trailing slash on root', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'index.html')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV with no trailing slash on a subdirectory', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/sub/blah.png'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'picturedis')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV no result throws an error', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/random'))
const error: KVError = await t.throwsAsync(getAssetFromKV(event))
t.is(error.status, 404)
})
test('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => {
mockRequestScope()
const event = getEvent(new Request('https://blah.com/'))
const res1 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } })
await sleep(100)
const res2 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } })
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), null)
t.is(res1.headers.get('cache-control'), null)
t.is(res2.headers.get('cf-cache-status'), null)
t.is(res2.headers.get('cache-control'), null)
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => {
mockRequestScope()
let CUSTOM_NAMESPACE = mockKV({
'key1.123HASHBROWN.txt': 'val1',
})
Object.assign(global, { CUSTOM_NAMESPACE })
const event = getEvent(new Request('https://blah.com/'))
const res = await getAssetFromKV(event)
if (res) {
t.is(await res.text(), 'index.html')
t.true(res.headers.get('content-type').includes('html'))
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV when custom namespace without the asset should fail', async (t) => {
mockRequestScope()
let CUSTOM_NAMESPACE = mockKV({
'key5.123HASHBROWN.txt': 'customvalu',
})
const event = getEvent(new Request('https://blah.com'))
const error: KVError = await t.throwsAsync(
getAssetFromKV(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE }),
)
t.is(error.status, 404)
})
test('getAssetFromKV when namespace not bound fails', async (t) => {
mockRequestScope()
var MY_CUSTOM_NAMESPACE = undefined
Object.assign(global, { MY_CUSTOM_NAMESPACE })
const event = getEvent(new Request('https://blah.com/'))
const error: KVError = await t.throwsAsync(
getAssetFromKV(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE }),
)
t.is(error.status, 500)
})
test('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => {
mockRequestScope()
const resourceKey = 'key1.png'
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
const event2 = getEvent(
new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `W/"${resourceVersion}"`,
},
}),
)
const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } })
await sleep(100)
const res2 = await getAssetFromKV(event2)
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS')
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => {
mockRequestScope()
const resourceKey = 'key1.png'
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
const req1 = new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
})
const req2 = new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}-another-version"`,
},
})
const event = getEvent(req1)
const event2 = getEvent(req2)
const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } })
const res2 = await getAssetFromKV(event)
const res3 = await getAssetFromKV(event2)
if (res1 && res2 && res3) {
t.is(res1.headers.get('cf-cache-status'), 'MISS')
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`)
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
t.not(res3.headers.get('etag'), req2.headers.get('if-none-match'))
t.is(res3.headers.get('cf-cache-status'), 'MISS')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => {
mockRequestScope()
const resourceKey = 'key1.png'
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
const req1 = new Request(`https://blah.com/${resourceKey}`, {
headers: {
'if-none-match': `"${resourceVersion}"`,
},
})
const event = getEvent(req1)
const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } })
const res2 = await getAssetFromKV(event)
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS')
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`)
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => {
const resourceKey = 'cache.html'
const event = getEvent(new Request(`https://blah.com/${resourceKey}`))
const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } })
await sleep(1)
const res2 = await getAssetFromKV(event)
if (res1 && res2) {
t.is(res1.headers.get('cf-cache-status'), 'MISS')
t.is(res1.headers.get('cache-control'), null)
t.is(res2.status, 200)
t.is(res2.headers.get('cf-cache-status'), 'HIT')
} else {
t.fail('Response was undefined')
}
})
test('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => {
const resourceKey = 'cache.html'
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
const event2 = getEvent(
new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } }),
)
const res1 = getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } })
await res1
await sleep(2)
const res2 = await getAssetFromKV(event2)
if (res2.headers.has('content-range')) {
t.is(res2.status, 206)
} else {
t.fail('Response was undefined')
}
})
test.todo('getAssetFromKV when body not empty, should invoke .cancel()')

View file

@ -1,37 +0,0 @@
import test from 'ava'
import { mockRequestScope, mockGlobalScope } from '../mocks'
mockGlobalScope()
import { mapRequestToAsset } from '../index'
test('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => {
mockRequestScope()
let path = '/about'
let request = new Request(`https://foo.com${path}`)
let newRequest = mapRequestToAsset(request)
t.is(newRequest.url, request.url + '/index.html')
})
test('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => {
mockRequestScope()
let path = '/about/'
let request = new Request(`https://foo.com${path}`)
let newRequest = mapRequestToAsset(request)
t.is(newRequest.url, request.url + 'index.html')
})
test('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => {
mockRequestScope()
let path = '/about.me/'
let request = new Request(`https://foo.com${path}`)
let newRequest = mapRequestToAsset(request)
t.is(newRequest.url, request.url + 'index.html')
})
test('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => {
mockRequestScope()
let path = '/about'
let request = new Request(`https://foo.com${path}`)
let newRequest = mapRequestToAsset(request, { defaultDocument: 'default.html' })
t.is(newRequest.url, request.url + '/default.html')
})

View file

@ -1,44 +0,0 @@
import test from 'ava'
import { mockRequestScope, mockGlobalScope } from '../mocks'
mockGlobalScope()
import { serveSinglePageApp } from '../index'
function testRequest(path: string) {
mockRequestScope()
let url = new URL('https://example.com')
url.pathname = path
let request = new Request(url.toString())
return request
}
test('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => {
let path = '/foo/thing.html'
let request = testRequest(path)
let expected_request = testRequest('/index.html')
let actual_request = serveSinglePageApp(request)
t.deepEqual(expected_request, actual_request)
})
test('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => {
let path = '/foo/thing'
let request = testRequest(path)
let expected_request = testRequest('/index.html')
let actual_request = serveSinglePageApp(request)
t.deepEqual(expected_request, actual_request)
})
test('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => {
let path = '/foo/thing.js'
let request = testRequest(path)
let expected_request = request
let actual_request = serveSinglePageApp(request)
t.deepEqual(expected_request, actual_request)
})

View file

@ -1,43 +0,0 @@
export type CacheControl = {
browserTTL: number
edgeTTL: number
bypassCache: boolean
}
export type AssetManifestType = Record<string, string>
export type Options = {
cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl>
ASSET_NAMESPACE: any
ASSET_MANIFEST: AssetManifestType | string
mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request
defaultMimeType: string
defaultDocument: string
pathIsEncoded: boolean
}
export class KVError extends Error {
constructor(message?: string, status: number = 500) {
super(message)
// see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
this.name = KVError.name // stack traces display correctly now
this.status = status
}
status: number
}
export class MethodNotAllowedError extends KVError {
constructor(message: string = `Not a valid request method`, status: number = 405) {
super(message, status)
}
}
export class NotFoundError extends KVError {
constructor(message: string = `Not Found`, status: number = 404) {
super(message, status)
}
}
export class InternalError extends KVError {
constructor(message: string = `Internal Error in KV Asset Handler`, status: number = 500) {
super(message, status)
}
}

View file

@ -1,6 +0,0 @@
# 👷 `workerd` for Linux 64-bit, Cloudflare's JavaScript/Wasm Runtime
`workerd` is a JavaScript / Wasm server runtime based on the same code that powers
[Cloudflare Workers](https://workers.dev).
See https://github.com/cloudflare/workerd for details.

Binary file not shown.

View file

@ -1,17 +0,0 @@
{
"name": "@cloudflare/workerd-linux-64",
"description": "👷 workerd for Linux 64-bit, Cloudflare's JavaScript/Wasm Runtime",
"repository": "https://github.com/cloudflare/workerd",
"license": "Apache-2.0",
"preferUnplugged": false,
"engines": {
"node": ">=16"
},
"os": [
"linux"
],
"cpu": [
"x64"
],
"version": "1.20230904.0"
}

File diff suppressed because it is too large Load diff

View file

@ -1 +0,0 @@
export { Buffer } from '_node-buffer-polyfill_.js'

View file

@ -1 +0,0 @@
export { process } from '_node-process-polyfill_.js'

View file

@ -1,7 +0,0 @@
import * as esbuild from 'esbuild';
export declare function NodeGlobalsPolyfillPlugin({ buffer, process, }?: {
buffer?: boolean | undefined;
process?: boolean | undefined;
}): esbuild.Plugin;
export default NodeGlobalsPolyfillPlugin;
//# sourceMappingURL=index.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAElC,wBAAgB,yBAAyB,CAAC,EACtC,MAAc,EAEd,OAAc,GACjB;;;CAAK,GAAG,OAAO,CAAC,MAAM,CAyEtB;AAED,eAAe,yBAAyB,CAAA"}

View file

@ -1,80 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeGlobalsPolyfillPlugin = void 0;
const path_1 = __importDefault(require("path"));
function NodeGlobalsPolyfillPlugin({ buffer = false,
// define = {},
process = true, } = {}) {
return {
name: 'node-globals-polyfill',
setup({ initialOptions, onResolve, onLoad }) {
onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => {
return {
path: path_1.default.resolve(__dirname, '../Buffer.js'),
};
});
onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => {
return {
path: path_1.default.resolve(__dirname, '../process.js'),
};
});
// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762
// onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => {
// const data = fs
// .readFileSync(path.resolve(__dirname, '../process.js'))
// .toString()
// const keys = Object.keys(define)
// return {
// loader: 'js',
// contents: data.replace(
// `const defines = {}`,
// 'const defines = {\n' +
// keys
// .filter((x) => x.startsWith('process.'))
// .sort((a, b) => a.length - b.length)
// .map(
// (k) =>
// ` ${JSON.stringify(k).replace(
// 'process.',
// '',
// )}: ${define[k]},`,
// )
// .join('\n') +
// '\n}',
// ),
// }
// })
onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => {
return {
path: path_1.default.resolve(__dirname, '../process.js'),
};
});
onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => {
return {
path: path_1.default.resolve(__dirname, '../_buffer.js'),
};
});
const polyfills = [];
if (process) {
polyfills.push(path_1.default.resolve(__dirname, '../_virtual-process-polyfill_.js'));
}
if (buffer) {
polyfills.push(path_1.default.resolve(__dirname, '../_virtual-buffer-polyfill_.js'));
}
if (initialOptions.inject) {
initialOptions.inject.push(...polyfills);
// handle duplicate plugin
initialOptions.inject = [...new Set(initialOptions.inject)];
}
else {
initialOptions.inject = [...polyfills];
}
},
};
}
exports.NodeGlobalsPolyfillPlugin = NodeGlobalsPolyfillPlugin;
exports.default = NodeGlobalsPolyfillPlugin;
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AAIvB,SAAgB,yBAAyB,CAAC,EACtC,MAAM,GAAG,KAAK;AACd,eAAe;AACf,OAAO,GAAG,IAAI,GACjB,GAAG,EAAE;IACF,OAAO;QACH,IAAI,EAAE,uBAAuB;QAC7B,KAAK,CAAC,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,EAAE;YACvC,SAAS,CAAC,EAAE,MAAM,EAAE,4BAA4B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACxD,OAAO;oBACH,IAAI,EAAE,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,cAAc,CAAC;iBAChD,CAAA;YACL,CAAC,CAAC,CAAA;YACF,SAAS,CAAC,EAAE,MAAM,EAAE,6BAA6B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACzD,OAAO;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AA0B;gBAC1B,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAA;aAC9D;iBAAM;gBACH,cAAc,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA;aACzC;QACL,CAAC;KACJ,CAAA;AACL,CAAC;AA7ED,8DA6EC;AAED,kBAAe,yBAAyB,CAAA"}

View file

@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=index.test.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}

View file

@ -1,139 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const esbuild_1 = require("esbuild");
const test_support_1 = require("test-support");
const _1 = require(".");
require('debug').enable(require('../package.json').name);
test('process works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `process.version`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../process')],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
test('process is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `console.log('hei')`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../process')],
});
const output = res.outputFiles[0].text;
expect(output).not.toContain('process');
unlink();
}));
// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762
test('process env vars are replaced with ones from define', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
define: {
'process.env.VAR': '"hello"',
},
plugins: [_1.NodeGlobalsPolyfillPlugin({})],
});
const output = res.outputFiles[0].text;
eval(output);
unlink();
}));
test('Buffer works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `console.log(Buffer.from('xxx').toString())`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../Buffer')],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
test('Buffer is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `console.log('hei')`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../Buffer')],
});
const output = res.outputFiles[0].text;
expect(output).not.toContain('Buffer');
unlink();
}));
test('Buffer works using plugin', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `
let buf = new Buffer(256);
let len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.NodeGlobalsPolyfillPlugin({ buffer: true })],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
test('process works using plugin', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `console.log(process.cwd())`,
});
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.NodeGlobalsPolyfillPlugin({ process: true })],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
//# sourceMappingURL=index.test.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,qCAA+B;AAC/B,+CAAyC;AACzC,wBAA6C;AAE7C,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,eAAe,EAAE,GAAS,EAAE;IAC7B,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,yBAAU,CAAC;QACjB,UAAU,EAAE,iBAAiB;KAChC,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,eAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;KAC1C,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA;AAEF,IAAI,CAAC,wBAAwB,EAAE,GAAS,EAAE;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BAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"}

View file

@ -1,7 +0,0 @@
import * as esbuild from 'esbuild';
export declare function NodeGlobalsPolyfillPlugin({ buffer, process, }?: {
buffer?: boolean | undefined;
process?: boolean | undefined;
}): esbuild.Plugin;
export default NodeGlobalsPolyfillPlugin;
//# sourceMappingURL=index.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAElC,wBAAgB,yBAAyB,CAAC,EACtC,MAAc,EAEd,OAAc,GACjB;;;CAAK,GAAG,OAAO,CAAC,MAAM,CAyEtB;AAED,eAAe,yBAAyB,CAAA"}

View file

@ -1,73 +0,0 @@
import path from 'path';
export function NodeGlobalsPolyfillPlugin({ buffer = false,
// define = {},
process = true, } = {}) {
return {
name: 'node-globals-polyfill',
setup({ initialOptions, onResolve, onLoad }) {
onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => {
return {
path: path.resolve(__dirname, '../Buffer.js'),
};
});
onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => {
return {
path: path.resolve(__dirname, '../process.js'),
};
});
// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762
// onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => {
// const data = fs
// .readFileSync(path.resolve(__dirname, '../process.js'))
// .toString()
// const keys = Object.keys(define)
// return {
// loader: 'js',
// contents: data.replace(
// `const defines = {}`,
// 'const defines = {\n' +
// keys
// .filter((x) => x.startsWith('process.'))
// .sort((a, b) => a.length - b.length)
// .map(
// (k) =>
// ` ${JSON.stringify(k).replace(
// 'process.',
// '',
// )}: ${define[k]},`,
// )
// .join('\n') +
// '\n}',
// ),
// }
// })
onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => {
return {
path: path.resolve(__dirname, '../process.js'),
};
});
onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => {
return {
path: path.resolve(__dirname, '../_buffer.js'),
};
});
const polyfills = [];
if (process) {
polyfills.push(path.resolve(__dirname, '../_virtual-process-polyfill_.js'));
}
if (buffer) {
polyfills.push(path.resolve(__dirname, '../_virtual-buffer-polyfill_.js'));
}
if (initialOptions.inject) {
initialOptions.inject.push(...polyfills);
// handle duplicate plugin
initialOptions.inject = [...new Set(initialOptions.inject)];
}
else {
initialOptions.inject = [...polyfills];
}
},
};
}
export default NodeGlobalsPolyfillPlugin;
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAA;AAIvB,MAAM,UAAU,yBAAyB,CAAC,EACtC,MAAM,GAAG,KAAK;AACd,eAAe;AACf,OAAO,GAAG,IAAI,GACjB,GAAG,EAAE;IACF,OAAO;QACH,IAAI,EAAE,uBAAuB;QAC7B,KAAK,CAAC,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,EAAE;YACvC,SAAS,CAAC,EAAE,MAAM,EAAE,4BAA4B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACxD,OAAO;oBACH,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,cAAc,CAAC;iBAChD,CAAA;YACL,CAAC,CAAC,CAAA;YACF,SAAS,CAAC,EAAE,MAAM,EAAE,6BAA6B,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE;gBACzD,OAAO;oBACH,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,CAAC;iBACjD,CAAA;YACL,CAAC,CAAC,CAAA;YAEF,mGAAmG;YACnG,kEAAkE;YAClE,sBAAsB;YACtB,kEAAkE;YAClE,sBAAsB;YAEtB,uCAAuC;YACvC,eAAe;YACf,wBAAwB;YACxB,kCAAkC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,yBAAyB,CAAA"}

View file

@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=index.test.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}

View file

@ -1,137 +0,0 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { build } from 'esbuild';
import { writeFiles } from 'test-support';
import { NodeGlobalsPolyfillPlugin } from '.';
require('debug').enable(require('../package.json').name);
test('process works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `process.version`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../process')],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
test('process is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `console.log('hei')`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../process')],
});
const output = res.outputFiles[0].text;
expect(output).not.toContain('process');
unlink();
}));
// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762
test('process env vars are replaced with ones from define', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
define: {
'process.env.VAR': '"hello"',
},
plugins: [NodeGlobalsPolyfillPlugin({})],
});
const output = res.outputFiles[0].text;
eval(output);
unlink();
}));
test('Buffer works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `console.log(Buffer.from('xxx').toString())`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../Buffer')],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
test('Buffer is tree shaken', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `console.log('hei')`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../Buffer')],
});
const output = res.outputFiles[0].text;
expect(output).not.toContain('Buffer');
unlink();
}));
test('Buffer works using plugin', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `
let buf = new Buffer(256);
let len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
test('process works using plugin', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `console.log(process.cwd())`,
});
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeGlobalsPolyfillPlugin({ process: true })],
});
const output = res.outputFiles[0].text;
// console.log(output)
eval(output);
unlink();
}));
//# sourceMappingURL=index.test.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.js","sourceRoot":"","sources":["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,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,yBAAyB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;KACzD,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA;AACF,IAAI,CAAC,4BAA4B,EAAE,GAAS,EAAE;IAC1C,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,UAAU,CAAC;QACjB,UAAU,EAAE,4BAA4B;KAC3C,CAAC,CAAA;IACF,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC;QACpB,KAAK,EAAE,KAAK;QACZ,MAAM,EAAE,KAAK;QACb,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,IAAI;QACZ,OAAO,EAAE,CAAC,yBAAyB,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;KAC1D,CAAC,CAAA;IACF,MAAM,MAAM,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;IACtC,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,CAAA;IACZ,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"}

View file

@ -1,34 +0,0 @@
{
"name": "@esbuild-plugins/node-globals-polyfill",
"version": "0.2.3",
"description": "",
"preferUnplugged": true,
"sideEffects": false,
"main": "dist/index.js",
"module": "esm/index.js",
"types": "dist/index.d.ts",
"repository": "https://github.com/remorses/esbuild-plugins.git",
"scripts": {
"build": "tsc && tsc -m es6 --outDir esm",
"watch": "tsc -w"
},
"files": [
"dist",
"src",
"esm",
"Buffer.js",
"process.js",
"_buffer.js",
"_process.js"
],
"keywords": [],
"author": "Tommaso De Rossi, morse <beats.by.morse@gmail.com>",
"license": "ISC",
"devDependencies": {
"test-support": "*"
},
"dependencies": {},
"peerDependencies": {
"esbuild": "*"
}
}

View file

@ -1,245 +0,0 @@
// shim for using process in browser
// based off https://github.com/defunctzombie/node-process/blob/master/browser.js
function defaultSetTimout() {
throw new Error('setTimeout has not been defined')
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined')
}
var cachedSetTimeout = defaultSetTimout
var cachedClearTimeout = defaultClearTimeout
if (typeof global.setTimeout === 'function') {
cachedSetTimeout = setTimeout
}
if (typeof global.clearTimeout === 'function') {
cachedClearTimeout = clearTimeout
}
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0)
}
// if setTimeout wasn't available but was latter defined
if (
(cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) &&
setTimeout
) {
cachedSetTimeout = setTimeout
return setTimeout(fun, 0)
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0)
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0)
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0)
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker)
}
// if clearTimeout wasn't available but was latter defined
if (
(cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) &&
clearTimeout
) {
cachedClearTimeout = clearTimeout
return clearTimeout(marker)
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker)
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker)
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker)
}
}
}
var queue = []
var draining = false
var currentQueue
var queueIndex = -1
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return
}
draining = false
if (currentQueue.length) {
queue = currentQueue.concat(queue)
} else {
queueIndex = -1
}
if (queue.length) {
drainQueue()
}
}
function drainQueue() {
if (draining) {
return
}
var timeout = runTimeout(cleanUpNextTick)
draining = true
var len = queue.length
while (len) {
currentQueue = queue
queue = []
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run()
}
}
queueIndex = -1
len = queue.length
}
currentQueue = null
draining = false
runClearTimeout(timeout)
}
function nextTick(fun) {
var args = new Array(arguments.length - 1)
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i]
}
}
queue.push(new Item(fun, args))
if (queue.length === 1 && !draining) {
runTimeout(drainQueue)
}
}
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun
this.array = array
}
Item.prototype.run = function() {
this.fun.apply(null, this.array)
}
var title = 'browser'
var platform = 'browser'
var browser = true
var env = {}
var argv = []
var version = '' // empty string to avoid regexp issues
var versions = {}
var release = {}
var config = {}
function noop() {}
var on = noop
var addListener = noop
var once = noop
var off = noop
var removeListener = noop
var removeAllListeners = noop
var emit = noop
function binding(name) {
throw new Error('process.binding is not supported')
}
function cwd() {
return '/'
}
function chdir(dir) {
throw new Error('process.chdir is not supported')
}
function umask() {
return 0
}
// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = global.performance || {}
var performanceNow =
performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
function() {
return new Date().getTime()
}
// generate timestamp or delta
// see http://nodejs.org/api/process.html#process_process_hrtime
function hrtime(previousTimestamp) {
var clocktime = performanceNow.call(performance) * 1e-3
var seconds = Math.floor(clocktime)
var nanoseconds = Math.floor((clocktime % 1) * 1e9)
if (previousTimestamp) {
seconds = seconds - previousTimestamp[0]
nanoseconds = nanoseconds - previousTimestamp[1]
if (nanoseconds < 0) {
seconds--
nanoseconds += 1e9
}
}
return [seconds, nanoseconds]
}
var startTime = new Date()
function uptime() {
var currentTime = new Date()
var dif = currentTime - startTime
return dif / 1000
}
export var process = {
nextTick: nextTick,
title: title,
browser: browser,
env: env,
argv: argv,
version: version,
versions: versions,
on: on,
addListener: addListener,
once: once,
off: off,
removeListener: removeListener,
removeAllListeners: removeAllListeners,
emit: emit,
binding: binding,
cwd: cwd,
chdir: chdir,
umask: umask,
hrtime: hrtime,
platform: platform,
release: release,
config: config,
uptime: uptime,
}
// replace process.env.VAR with define
const defines = {}
Object.keys(defines).forEach((key) => {
const segs = key.split('.')
let target = process
for (let i = 0; i < segs.length; i++) {
const seg = segs[i]
if (i === segs.length - 1) {
target[seg] = defines[key]
} else {
target = target[seg] || (target[seg] = {})
}
}
})

View file

@ -1,155 +0,0 @@
import { build } from 'esbuild'
import { writeFiles } from 'test-support'
import { NodeGlobalsPolyfillPlugin } from '.'
require('debug').enable(require('../package.json').name)
test('process works', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `process.version`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../process')],
})
const output = res.outputFiles[0].text
// console.log(output)
eval(output)
unlink()
})
test('process is tree shaken', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `console.log('hei')`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../process')],
})
const output = res.outputFiles[0].text
expect(output).not.toContain('process')
unlink()
})
// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762
test('process env vars are replaced with ones from define', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `if (process.env.VAR !== 'hello') { throw new Error('process.env.VAR not right: ' + process.env.VAR) }`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
define: {
'process.env.VAR': '"hello"',
},
plugins: [NodeGlobalsPolyfillPlugin({})],
})
const output = res.outputFiles[0].text
eval(output)
unlink()
})
test('Buffer works', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `console.log(Buffer.from('xxx').toString())`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../Buffer')],
})
const output = res.outputFiles[0].text
// console.log(output)
eval(output)
unlink()
})
test('Buffer is tree shaken', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `console.log('hei')`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
inject: [require.resolve('../Buffer')],
})
const output = res.outputFiles[0].text
expect(output).not.toContain('Buffer')
unlink()
})
test('Buffer works using plugin', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `
let buf = new Buffer(256);
let len = buf.write("Simply Easy Learning");
console.log("Octets written : "+ len);`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeGlobalsPolyfillPlugin({ buffer: true })],
})
const output = res.outputFiles[0].text
// console.log(output)
eval(output)
unlink()
})
test('process works using plugin', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `console.log(process.cwd())`,
})
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeGlobalsPolyfillPlugin({ process: true })],
})
const output = res.outputFiles[0].text
// console.log(output)
eval(output)
unlink()
})

View file

@ -1,84 +0,0 @@
import path from 'path'
import fs from 'fs'
import * as esbuild from 'esbuild'
export function NodeGlobalsPolyfillPlugin({
buffer = false,
// define = {},
process = true,
} = {}): esbuild.Plugin {
return {
name: 'node-globals-polyfill',
setup({ initialOptions, onResolve, onLoad }) {
onResolve({ filter: /_node-buffer-polyfill_\.js/ }, (arg) => {
return {
path: path.resolve(__dirname, '../Buffer.js'),
}
})
onResolve({ filter: /_node-process-polyfill_\.js/ }, (arg) => {
return {
path: path.resolve(__dirname, '../process.js'),
}
})
// TODO esbuild cannot use virtual modules for inject: https://github.com/evanw/esbuild/issues/2762
// onLoad({ filter: /_virtual-process-polyfill_\.js/ }, (arg) => {
// const data = fs
// .readFileSync(path.resolve(__dirname, '../process.js'))
// .toString()
// const keys = Object.keys(define)
// return {
// loader: 'js',
// contents: data.replace(
// `const defines = {}`,
// 'const defines = {\n' +
// keys
// .filter((x) => x.startsWith('process.'))
// .sort((a, b) => a.length - b.length)
// .map(
// (k) =>
// ` ${JSON.stringify(k).replace(
// 'process.',
// '',
// )}: ${define[k]},`,
// )
// .join('\n') +
// '\n}',
// ),
// }
// })
onResolve({ filter: /_virtual-process-polyfill_\.js/ }, () => {
return {
path: path.resolve(__dirname, '../process.js'),
}
})
onResolve({ filter: /_virtual-buffer-polyfill_\.js/ }, () => {
return {
path: path.resolve(__dirname, '../_buffer.js'),
}
})
const polyfills: string[] = []
if (process) {
polyfills.push(
path.resolve(__dirname, '../_virtual-process-polyfill_.js'),
)
}
if (buffer) {
polyfills.push(
path.resolve(__dirname, '../_virtual-buffer-polyfill_.js'),
)
}
if (initialOptions.inject) {
initialOptions.inject.push(...polyfills)
// handle duplicate plugin
initialOptions.inject = [...new Set(initialOptions.inject)]
} else {
initialOptions.inject = [...polyfills]
}
},
}
}
export default NodeGlobalsPolyfillPlugin

View file

@ -1,8 +0,0 @@
import { Plugin } from 'esbuild';
export interface NodePolyfillsOptions {
name?: string;
namespace?: string;
}
export declare function NodeModulesPolyfillPlugin(options?: NodePolyfillsOptions): Plugin;
export default NodeModulesPolyfillPlugin;
//# sourceMappingURL=index.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,MAAM,EAAE,MAAM,SAAS,CAAA;AAkB/C,MAAM,WAAW,oBAAoB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,yBAAyB,CACrC,OAAO,GAAE,oBAAyB,GACnC,MAAM,CAwFR;AAmBD,eAAe,yBAAyB,CAAA"}

View file

@ -1,127 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeModulesPolyfillPlugin = void 0;
const escape_string_regexp_1 = __importDefault(require("escape-string-regexp"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const polyfills_1 = require("./polyfills");
// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve'
const NAME = 'node-modules-polyfills';
const NAMESPACE = NAME;
function removeEndingSlash(importee) {
if (importee && importee.slice(-1) === '/') {
importee = importee.slice(0, -1);
}
return importee;
}
function NodeModulesPolyfillPlugin(options = {}) {
const { namespace = NAMESPACE, name = NAME } = options;
if (namespace.endsWith('commonjs')) {
throw new Error(`namespace ${namespace} must not end with commonjs`);
}
// this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default
const commonjsNamespace = namespace + '-commonjs';
const polyfilledBuiltins = polyfills_1.builtinsPolyfills();
const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()];
return {
name,
setup: function setup({ onLoad, onResolve, initialOptions }) {
var _a;
// polyfills contain global keyword, it must be defined
if ((initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define) && !((_a = initialOptions.define) === null || _a === void 0 ? void 0 : _a.global)) {
initialOptions.define['global'] = 'globalThis';
}
else if (!(initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define)) {
initialOptions.define = { global: 'globalThis' };
}
// TODO these polyfill module cannot import anything, is that ok?
function loader(args) {
return __awaiter(this, void 0, void 0, function* () {
try {
const argsPath = args.path.replace(/^node:/, '');
const isCommonjs = args.namespace.endsWith('commonjs');
const resolved = polyfilledBuiltins.get(removeEndingSlash(argsPath));
const contents = yield (yield fs_1.default.promises.readFile(resolved)).toString();
let resolveDir = path_1.default.dirname(resolved);
if (isCommonjs) {
return {
loader: 'js',
contents: commonJsTemplate({
importPath: argsPath,
}),
resolveDir,
};
}
return {
loader: 'js',
contents,
resolveDir,
};
}
catch (e) {
console.error('node-modules-polyfill', e);
return {
contents: `export {}`,
loader: 'js',
};
}
});
}
onLoad({ filter: /.*/, namespace }, loader);
onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader);
const filter = new RegExp([
...polyfilledBuiltinsNames,
...polyfilledBuiltinsNames.map((n) => `node:${n}`),
]
.map(escape_string_regexp_1.default)
.join('|'));
function resolver(args) {
return __awaiter(this, void 0, void 0, function* () {
const argsPath = args.path.replace(/^node:/, '');
const ignoreRequire = args.namespace === commonjsNamespace;
if (!polyfilledBuiltins.has(argsPath)) {
return;
}
const isCommonjs = !ignoreRequire && args.kind === 'require-call';
return {
namespace: isCommonjs ? commonjsNamespace : namespace,
path: argsPath,
};
});
}
onResolve({ filter }, resolver);
// onResolve({ filter: /.*/, namespace }, resolver)
},
};
}
exports.NodeModulesPolyfillPlugin = NodeModulesPolyfillPlugin;
function commonJsTemplate({ importPath }) {
return `
const polyfill = require('${importPath}')
if (polyfill && polyfill.default) {
module.exports = polyfill.default
for (let k in polyfill) {
module.exports[k] = polyfill[k]
}
} else if (polyfill) {
module.exports = polyfill
}
`;
}
exports.default = NodeModulesPolyfillPlugin;
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,gFAAqD;AACrD,4CAAmB;AACnB,gDAAuB;AAEvB,2CAA+C;AAE/C,oEAAoE;AACpE,MAAM,IAAI,GAAG,wBAAwB,CAAA;AACrC,MAAM,SAAS,GAAG,IAAI,CAAA;AAEtB,SAAS,iBAAiB,CAAC,QAAQ;IAC/B,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACxC,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;KACnC;IACD,OAAO,QAAQ,CAAA;AACnB,CAAC;AAOD,SAAgB,yBAAyB,CACrC,UAAgC,EAAE;IAElC,MAAM,EAAE,SAAS,GAAG,SAAS,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,OAAO,CAAA;IACtD,IAAI,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QAChC,MAAM,IAAI,KAAK,CAAC,aAAa,SAAS,6BAA6B,CAAC,CAAA;KACvE;IACD,+IAA+I;IAC/I,MAAM,iBAAiB,GAAG,SAAS,GAAG,WAAW,CAAA;IACjD,MAAM,kBAAkB,GAAG,6BAAiB,EAAE,CAAA;IAC9C,MAAM,uBAAuB,GAAG,CAAC,GAAG,kBAAkB,CAAC,IAAI,EAAE,CAAC,CAAA;IAE9D,OAAO;QACH,IAAI;QACJ,KAAK,EAAE,SAAS,KAAK,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE;;YACvD,uDAAuD;YACvD,IA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,CAAA"}

View file

@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=index.test.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}

View file

@ -1,183 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const esbuild_1 = require("esbuild");
const test_support_1 = require("test-support");
const fs_1 = __importDefault(require("fs"));
const _1 = __importDefault(require("."));
const node_globals_polyfill_1 = __importDefault(require("@esbuild-plugins/node-globals-polyfill"));
require('debug').enable(require('../package.json').name);
test('works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
eval(res.outputFiles[0].text);
// console.log(res.outputFiles[0].text)
unlink();
}));
test('works with SafeBuffer and other package consumers', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`,
'safe-buffer.ts': fs_1.default
.readFileSync(require.resolve('safe-buffer'))
.toString(),
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
// console.log(
// res.outputFiles[0].text
// .split('\n')
// .map((x, i) => i + ' ' + x)
// .join('\n'),
// )
eval(res.outputFiles[0].text);
unlink();
}));
test('events works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `
import EventEmitter from 'events';
class Test extends EventEmitter {
constructor() { };
}
console.log(Test)
`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
// console.log(res.outputFiles[0].text)
eval(res.outputFiles[0].text);
unlink();
}));
test('require can use default export', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `
const assert = require('assert')
// console.log(assert)
assert('ok')
`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
// console.log(res.outputFiles[0].text)
eval(res.outputFiles[0].text);
unlink();
}));
test.skip('crypto', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
eval(res.outputFiles[0].text);
// console.log(res.outputFiles[0].text)
unlink();
}));
test.skip('fs', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
eval(res.outputFiles[0].text);
// console.log(res.outputFiles[0].text)
unlink();
}));
test('does not include global keyword', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default()],
});
const text = res.outputFiles[0].text;
eval(text);
expect(text).not.toContain(/\bglobal\b/);
// console.log(res.outputFiles[0].text)
unlink();
}));
test('works with globals polyfills', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield test_support_1.writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
});
// const outfile = randomOutputFile()
const res = yield esbuild_1.build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [_1.default(), node_globals_polyfill_1.default()],
});
const text = res.outputFiles[0].text;
eval(text);
console.log(text);
// console.log(res.outputFiles[0].text)
unlink();
}));
//# sourceMappingURL=index.test.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,qCAA+B;AAC/B,+CAAyC;AACzC,4CAAmB;AACnB,yCAA0C;AAC1C,mGAA+E;AAE/E,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,OAAO,EAAE,GA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IAAI,CAAC,CAAA;IACV,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IACjB,uCAAuC;IACvC,MAAM,EAAE,CAAA;AACZ,CAAC,CAAA,CAAC,CAAA"}

View file

@ -1,2 +0,0 @@
export declare function builtinsPolyfills(): Map<any, any>;
//# sourceMappingURL=polyfills.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAQA,wBAAgB,iBAAiB,kBA8IhC"}

View file

@ -1,61 +0,0 @@
"use strict";
// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts
Object.defineProperty(exports, "__esModule", { value: true });
exports.builtinsPolyfills = void 0;
const EMPTY_PATH = require.resolve('rollup-plugin-node-polyfills/polyfills/empty.js');
function builtinsPolyfills() {
const libs = new Map();
libs.set('process', require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6'));
libs.set('buffer', require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6'));
libs.set('util', require.resolve('rollup-plugin-node-polyfills/polyfills/util'));
libs.set('sys', libs.get('util'));
libs.set('events', require.resolve('rollup-plugin-node-polyfills/polyfills/events'));
libs.set('stream', require.resolve('rollup-plugin-node-polyfills/polyfills/stream'));
libs.set('path', require.resolve('rollup-plugin-node-polyfills/polyfills/path'));
libs.set('querystring', require.resolve('rollup-plugin-node-polyfills/polyfills/qs'));
libs.set('punycode', require.resolve('rollup-plugin-node-polyfills/polyfills/punycode'));
libs.set('url', require.resolve('rollup-plugin-node-polyfills/polyfills/url'));
libs.set('string_decoder', require.resolve('rollup-plugin-node-polyfills/polyfills/string-decoder'));
libs.set('http', require.resolve('rollup-plugin-node-polyfills/polyfills/http'));
libs.set('https', require.resolve('rollup-plugin-node-polyfills/polyfills/http'));
libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os'));
libs.set('assert', require.resolve('rollup-plugin-node-polyfills/polyfills/assert'));
libs.set('constants', require.resolve('rollup-plugin-node-polyfills/polyfills/constants'));
libs.set('_stream_duplex', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/duplex'));
libs.set('_stream_passthrough', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough'));
libs.set('_stream_readable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/readable'));
libs.set('_stream_writable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/writable'));
libs.set('_stream_transform', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/transform'));
libs.set('timers', require.resolve('rollup-plugin-node-polyfills/polyfills/timers'));
libs.set('console', require.resolve('rollup-plugin-node-polyfills/polyfills/console'));
libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm'));
libs.set('zlib', require.resolve('rollup-plugin-node-polyfills/polyfills/zlib'));
libs.set('tty', require.resolve('rollup-plugin-node-polyfills/polyfills/tty'));
libs.set('domain', require.resolve('rollup-plugin-node-polyfills/polyfills/domain'));
// not shimmed
libs.set('dns', EMPTY_PATH);
libs.set('dgram', EMPTY_PATH);
libs.set('child_process', EMPTY_PATH);
libs.set('cluster', EMPTY_PATH);
libs.set('module', EMPTY_PATH);
libs.set('net', EMPTY_PATH);
libs.set('readline', EMPTY_PATH);
libs.set('repl', EMPTY_PATH);
libs.set('tls', EMPTY_PATH);
libs.set('fs', EMPTY_PATH);
libs.set('crypto', EMPTY_PATH);
// libs.set(
// 'fs',
// require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'),
// )
// TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20
// libs.set(
// 'crypto',
// require.resolve(
// 'rollup-plugin-node-polyfills/polyfills/crypto-browserify',
// ),
// )
return libs;
}
exports.builtinsPolyfills = builtinsPolyfills;
//# sourceMappingURL=polyfills.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":";AAAA,mGA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KAAK,EACL,OAAO,CAAC,OAAO,CAAC,4CAA4C,CAAC,CAChE,CAAA;IACD,IAAI,CAAC,GAAG,CACJ,QAAQ,EACR,OAAO,CAAC,OAAO,CAAC,+CAA+C,CAAC,CACnE,CAAA;IAED,cAAc;IACd,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;IAC7B,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,CAAC,CAAA;IACrC,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;IAChC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAC5B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;IAC1B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAE9B,YAAY;IACZ,YAAY;IACZ,+EAA+E;IAC/E,IAAI;IAEJ,iGAAiG;IACjG,YAAY;IACZ,gBAAgB;IAChB,uBAAuB;IACvB,sEAAsE;IACtE,SAAS;IACT,IAAI;IAEJ,OAAO,IAAI,CAAA;AACf,CAAC;AA9ID,8CA8IC"}

View file

@ -1,8 +0,0 @@
import { Plugin } from 'esbuild';
export interface NodePolyfillsOptions {
name?: string;
namespace?: string;
}
export declare function NodeModulesPolyfillPlugin(options?: NodePolyfillsOptions): Plugin;
export default NodeModulesPolyfillPlugin;
//# sourceMappingURL=index.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,MAAM,EAAE,MAAM,SAAS,CAAA;AAkB/C,MAAM,WAAW,oBAAoB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,wBAAgB,yBAAyB,CACrC,OAAO,GAAE,oBAAyB,GACnC,MAAM,CAwFR;AAmBD,eAAe,yBAAyB,CAAA"}

View file

@ -1,120 +0,0 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import escapeStringRegexp from 'escape-string-regexp';
import fs from 'fs';
import path from 'path';
import { builtinsPolyfills } from './polyfills';
// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve'
const NAME = 'node-modules-polyfills';
const NAMESPACE = NAME;
function removeEndingSlash(importee) {
if (importee && importee.slice(-1) === '/') {
importee = importee.slice(0, -1);
}
return importee;
}
export function NodeModulesPolyfillPlugin(options = {}) {
const { namespace = NAMESPACE, name = NAME } = options;
if (namespace.endsWith('commonjs')) {
throw new Error(`namespace ${namespace} must not end with commonjs`);
}
// this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default
const commonjsNamespace = namespace + '-commonjs';
const polyfilledBuiltins = builtinsPolyfills();
const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()];
return {
name,
setup: function setup({ onLoad, onResolve, initialOptions }) {
var _a;
// polyfills contain global keyword, it must be defined
if ((initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define) && !((_a = initialOptions.define) === null || _a === void 0 ? void 0 : _a.global)) {
initialOptions.define['global'] = 'globalThis';
}
else if (!(initialOptions === null || initialOptions === void 0 ? void 0 : initialOptions.define)) {
initialOptions.define = { global: 'globalThis' };
}
// TODO these polyfill module cannot import anything, is that ok?
function loader(args) {
return __awaiter(this, void 0, void 0, function* () {
try {
const argsPath = args.path.replace(/^node:/, '');
const isCommonjs = args.namespace.endsWith('commonjs');
const resolved = polyfilledBuiltins.get(removeEndingSlash(argsPath));
const contents = yield (yield fs.promises.readFile(resolved)).toString();
let resolveDir = path.dirname(resolved);
if (isCommonjs) {
return {
loader: 'js',
contents: commonJsTemplate({
importPath: argsPath,
}),
resolveDir,
};
}
return {
loader: 'js',
contents,
resolveDir,
};
}
catch (e) {
console.error('node-modules-polyfill', e);
return {
contents: `export {}`,
loader: 'js',
};
}
});
}
onLoad({ filter: /.*/, namespace }, loader);
onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader);
const filter = new RegExp([
...polyfilledBuiltinsNames,
...polyfilledBuiltinsNames.map((n) => `node:${n}`),
]
.map(escapeStringRegexp)
.join('|'));
function resolver(args) {
return __awaiter(this, void 0, void 0, function* () {
const argsPath = args.path.replace(/^node:/, '');
const ignoreRequire = args.namespace === commonjsNamespace;
if (!polyfilledBuiltins.has(argsPath)) {
return;
}
const isCommonjs = !ignoreRequire && args.kind === 'require-call';
return {
namespace: isCommonjs ? commonjsNamespace : namespace,
path: argsPath,
};
});
}
onResolve({ filter }, resolver);
// onResolve({ filter: /.*/, namespace }, resolver)
},
};
}
function commonJsTemplate({ importPath }) {
return `
const polyfill = require('${importPath}')
if (polyfill && polyfill.default) {
module.exports = polyfill.default
for (let k in polyfill) {
module.exports[k] = polyfill[k]
}
} else if (polyfill) {
module.exports = polyfill
}
`;
}
export default NodeModulesPolyfillPlugin;
//# sourceMappingURL=index.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;A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,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,iBAAiB,EAAE,EAAE,MAAM,CAAC,CAAA;YAC9D,MAAM,MAAM,GAAG,IAAI,MAAM,CACrB;gBACI,GAAG,uBAAuB;gBAC1B,GAAG,uBAAuB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC;aACrD;iBACI,GAAG,CAAC,kBAAkB,CAAC;iBACvB,IAAI,CAAC,GAAG,CAAC,CACjB,CAAA;YACD,SAAe,QAAQ,CAAC,IAAmB;;oBACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;oBAChD,MAAM,aAAa,GAAG,IAAI,CAAC,SAAS,KAAK,iBAAiB,CAAA;oBAE1D,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;wBACnC,OAAM;qBACT;oBAED,MAAM,UAAU,GACZ,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc,CAAA;oBAElD,OAAO;wBACH,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS;wBACrD,IAAI,EAAE,QAAQ;qBACjB,CAAA;gBACL,CAAC;aAAA;YACD,SAAS,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,CAAA;YAC/B,mDAAmD;QACvD,CAAC;KACJ,CAAA;AACL,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAE,UAAU,EAAE;IACpC,OAAO;4BACiB,UAAU;;;;;;;;;;;;CAYrC,CAAA;AACD,CAAC;AAED,eAAe,yBAAyB,CAAA"}

View file

@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=index.test.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":""}

View file

@ -1,178 +0,0 @@
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { build } from 'esbuild';
import { writeFiles } from 'test-support';
import fs from 'fs';
import NodeModulesPolyfillsPlugin from '.';
import NodeGlobalsPolyfillsPlugin from '@esbuild-plugins/node-globals-polyfill';
require('debug').enable(require('../package.json').name);
test('works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
eval(res.outputFiles[0].text);
// console.log(res.outputFiles[0].text)
unlink();
}));
test('works with SafeBuffer and other package consumers', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`,
'safe-buffer.ts': fs
.readFileSync(require.resolve('safe-buffer'))
.toString(),
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
// console.log(
// res.outputFiles[0].text
// .split('\n')
// .map((x, i) => i + ' ' + x)
// .join('\n'),
// )
eval(res.outputFiles[0].text);
unlink();
}));
test('events works', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `
import EventEmitter from 'events';
class Test extends EventEmitter {
constructor() { };
}
console.log(Test)
`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
// console.log(res.outputFiles[0].text)
eval(res.outputFiles[0].text);
unlink();
}));
test('require can use default export', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `
const assert = require('assert')
// console.log(assert)
assert('ok')
`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
// console.log(res.outputFiles[0].text)
eval(res.outputFiles[0].text);
unlink();
}));
test.skip('crypto', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
eval(res.outputFiles[0].text);
// console.log(res.outputFiles[0].text)
unlink();
}));
test.skip('fs', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
eval(res.outputFiles[0].text);
// console.log(res.outputFiles[0].text)
unlink();
}));
test('does not include global keyword', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
});
const text = res.outputFiles[0].text;
eval(text);
expect(text).not.toContain(/\bglobal\b/);
// console.log(res.outputFiles[0].text)
unlink();
}));
test('works with globals polyfills', () => __awaiter(void 0, void 0, void 0, function* () {
const { unlink, paths: [ENTRY], } = yield writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
});
// const outfile = randomOutputFile()
const res = yield build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin(), NodeGlobalsPolyfillsPlugin()],
});
const text = res.outputFiles[0].text;
eval(text);
console.log(text);
// console.log(res.outputFiles[0].text)
unlink();
}));
//# sourceMappingURL=index.test.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,0BAA0B,MAAM,GAAG,CAAA;AAC1C,OAAO,0BAA0B,MAAM,wCAAwC,CAAA;AAE/E,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,IAAI,CAAC,CAAA;AAExD,IAAI,CAAC,OAAO,EAAE,GAAS,EAAE;IACrB,MAAM,EACF,MAAM,EACN,KAAK,EAAE,CAAC,KAAK,CAAC,GACjB,GAAG,MAAM,UAAU,CAAC;QACjB,UAAU,EAAE,4CAA4C;QACxD,UAAU,EAAE,uHAAuH;KACtI,CAAC,CAAA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Polyfills(): Map<any, any>;
//# sourceMappingURL=polyfills.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"polyfills.d.ts","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAQA,wBAAgB,iBAAiB,kBA8IhC"}

View file

@ -1,57 +0,0 @@
// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts
const EMPTY_PATH = require.resolve('rollup-plugin-node-polyfills/polyfills/empty.js');
export function builtinsPolyfills() {
const libs = new Map();
libs.set('process', require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6'));
libs.set('buffer', require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6'));
libs.set('util', require.resolve('rollup-plugin-node-polyfills/polyfills/util'));
libs.set('sys', libs.get('util'));
libs.set('events', require.resolve('rollup-plugin-node-polyfills/polyfills/events'));
libs.set('stream', require.resolve('rollup-plugin-node-polyfills/polyfills/stream'));
libs.set('path', require.resolve('rollup-plugin-node-polyfills/polyfills/path'));
libs.set('querystring', require.resolve('rollup-plugin-node-polyfills/polyfills/qs'));
libs.set('punycode', require.resolve('rollup-plugin-node-polyfills/polyfills/punycode'));
libs.set('url', require.resolve('rollup-plugin-node-polyfills/polyfills/url'));
libs.set('string_decoder', require.resolve('rollup-plugin-node-polyfills/polyfills/string-decoder'));
libs.set('http', require.resolve('rollup-plugin-node-polyfills/polyfills/http'));
libs.set('https', require.resolve('rollup-plugin-node-polyfills/polyfills/http'));
libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os'));
libs.set('assert', require.resolve('rollup-plugin-node-polyfills/polyfills/assert'));
libs.set('constants', require.resolve('rollup-plugin-node-polyfills/polyfills/constants'));
libs.set('_stream_duplex', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/duplex'));
libs.set('_stream_passthrough', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough'));
libs.set('_stream_readable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/readable'));
libs.set('_stream_writable', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/writable'));
libs.set('_stream_transform', require.resolve('rollup-plugin-node-polyfills/polyfills/readable-stream/transform'));
libs.set('timers', require.resolve('rollup-plugin-node-polyfills/polyfills/timers'));
libs.set('console', require.resolve('rollup-plugin-node-polyfills/polyfills/console'));
libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm'));
libs.set('zlib', require.resolve('rollup-plugin-node-polyfills/polyfills/zlib'));
libs.set('tty', require.resolve('rollup-plugin-node-polyfills/polyfills/tty'));
libs.set('domain', require.resolve('rollup-plugin-node-polyfills/polyfills/domain'));
// not shimmed
libs.set('dns', EMPTY_PATH);
libs.set('dgram', EMPTY_PATH);
libs.set('child_process', EMPTY_PATH);
libs.set('cluster', EMPTY_PATH);
libs.set('module', EMPTY_PATH);
libs.set('net', EMPTY_PATH);
libs.set('readline', EMPTY_PATH);
libs.set('repl', EMPTY_PATH);
libs.set('tls', EMPTY_PATH);
libs.set('fs', EMPTY_PATH);
libs.set('crypto', EMPTY_PATH);
// libs.set(
// 'fs',
// require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'),
// )
// TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20
// libs.set(
// 'crypto',
// require.resolve(
// 'rollup-plugin-node-polyfills/polyfills/crypto-browserify',
// ),
// )
return libs;
}
//# sourceMappingURL=polyfills.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"polyfills.js","sourceRoot":"","sources":["../src/polyfills.ts"],"names":[],"mappings":"AAAA,mGAAmG;AAInG,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAC9B,iDAAiD,CACpD,CAAA;AAED,MAAM,UAAU,iBAAiB;IAC7B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAE,CAAA;IAEtB,IAAI,CAAC,GAAG,CACJ,SAAS,EACT,OAAO,CAAC,OAAO,CAAC,oDAAoD,CAAC,CACxE,CAAA;IACD,IAAI,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AC,OAAO,EAAE,UAAU,CAAC,CAAA;IAC7B,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,CAAC,CAAA;IACrC,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,UAAU,CAAC,CAAA;IAC/B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAC9B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;IAChC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAA;IAC5B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAA;IAC3B,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;IAC1B,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;IAE9B,YAAY;IACZ,YAAY;IACZ,+EAA+E;IAC/E,IAAI;IAEJ,iGAAiG;IACjG,YAAY;IACZ,gBAAgB;IAChB,uBAAuB;IACvB,sEAAsE;IACtE,SAAS;IACT,IAAI;IAEJ,OAAO,IAAI,CAAA;AACf,CAAC"}

View file

@ -1,33 +0,0 @@
{
"name": "@esbuild-plugins/node-modules-polyfill",
"version": "0.2.2",
"description": "",
"main": "dist/index.js",
"module": "esm/index.js",
"types": "dist/index.d.ts",
"repository": "https://github.com/remorses/esbuild-plugins.git",
"scripts": {
"build": "tsc && tsc -m es6 --outDir esm",
"watch": "tsc -w"
},
"files": [
"dist",
"src",
"esm"
],
"keywords": [],
"author": "Tommaso De Rossi, morse <beats.by.morse@gmail.com>",
"license": "ISC",
"devDependencies": {
"safe-buffer": "^5.2.1",
"test-support": "*",
"@esbuild-plugins/node-globals-polyfill": "*"
},
"dependencies": {
"escape-string-regexp": "^4.0.0",
"rollup-plugin-node-polyfills": "^0.2.1"
},
"peerDependencies": {
"esbuild": "*"
}
}

View file

@ -1,200 +0,0 @@
import { build } from 'esbuild'
import { writeFiles } from 'test-support'
import fs from 'fs'
import NodeModulesPolyfillsPlugin from '.'
import NodeGlobalsPolyfillsPlugin from '@esbuild-plugins/node-globals-polyfill'
require('debug').enable(require('../package.json').name)
test('works', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
eval(res.outputFiles[0].text)
// console.log(res.outputFiles[0].text)
unlink()
})
test('works with SafeBuffer and other package consumers', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `import {Buffer as SafeBuffer} from './safe-buffer'; console.log(SafeBuffer);`,
'safe-buffer.ts': fs
.readFileSync(require.resolve('safe-buffer'))
.toString(),
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
// console.log(
// res.outputFiles[0].text
// .split('\n')
// .map((x, i) => i + ' ' + x)
// .join('\n'),
// )
eval(res.outputFiles[0].text)
unlink()
})
test('events works', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `
import EventEmitter from 'events';
class Test extends EventEmitter {
constructor() { };
}
console.log(Test)
`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
// console.log(res.outputFiles[0].text)
eval(res.outputFiles[0].text)
unlink()
})
test('require can use default export', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `
const assert = require('assert')
// console.log(assert)
assert('ok')
`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
// console.log(res.outputFiles[0].text)
eval(res.outputFiles[0].text)
unlink()
})
test.skip('crypto', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `import { randomBytes } from 'crypto'; console.log(randomBytes(20).toString('hex'))`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
eval(res.outputFiles[0].text)
// console.log(res.outputFiles[0].text)
unlink()
})
test.skip('fs', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `import { readFile } from 'fs'; console.log(readFile(''))`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
eval(res.outputFiles[0].text)
// console.log(res.outputFiles[0].text)
unlink()
})
test('does not include global keyword', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin()],
})
const text = res.outputFiles[0].text
eval(text)
expect(text).not.toContain(/\bglobal\b/)
// console.log(res.outputFiles[0].text)
unlink()
})
test('works with globals polyfills', async () => {
const {
unlink,
paths: [ENTRY],
} = await writeFiles({
'entry.ts': `import {x} from './utils'; console.log(x);`,
'utils.ts': `import path from 'path'; import { Buffer } from 'buffer'; export const x = path.resolve(Buffer.from('x').toString());`,
})
// const outfile = randomOutputFile()
const res = await build({
entryPoints: [ENTRY],
write: false,
format: 'esm',
target: 'es2017',
bundle: true,
plugins: [NodeModulesPolyfillsPlugin(), NodeGlobalsPolyfillsPlugin()],
})
const text = res.outputFiles[0].text
eval(text)
console.log(text)
// console.log(res.outputFiles[0].text)
unlink()
})

View file

@ -1,133 +0,0 @@
import { OnResolveArgs, Plugin } from 'esbuild'
import escapeStringRegexp from 'escape-string-regexp'
import fs from 'fs'
import path from 'path'
import esbuild from 'esbuild'
import { builtinsPolyfills } from './polyfills'
// import { NodeResolvePlugin } from '@esbuild-plugins/node-resolve'
const NAME = 'node-modules-polyfills'
const NAMESPACE = NAME
function removeEndingSlash(importee) {
if (importee && importee.slice(-1) === '/') {
importee = importee.slice(0, -1)
}
return importee
}
export interface NodePolyfillsOptions {
name?: string
namespace?: string
}
export function NodeModulesPolyfillPlugin(
options: NodePolyfillsOptions = {},
): Plugin {
const { namespace = NAMESPACE, name = NAME } = options
if (namespace.endsWith('commonjs')) {
throw new Error(`namespace ${namespace} must not end with commonjs`)
}
// this namespace is needed to make ES modules expose their default export to require: require('assert') will give you import('assert').default
const commonjsNamespace = namespace + '-commonjs'
const polyfilledBuiltins = builtinsPolyfills()
const polyfilledBuiltinsNames = [...polyfilledBuiltins.keys()]
return {
name,
setup: function setup({ onLoad, onResolve, initialOptions }) {
// polyfills contain global keyword, it must be defined
if (initialOptions?.define && !initialOptions.define?.global) {
initialOptions.define['global'] = 'globalThis'
} else if (!initialOptions?.define) {
initialOptions.define = { global: 'globalThis' }
}
// TODO these polyfill module cannot import anything, is that ok?
async function loader(
args: esbuild.OnLoadArgs,
): Promise<esbuild.OnLoadResult> {
try {
const argsPath = args.path.replace(/^node:/, '')
const isCommonjs = args.namespace.endsWith('commonjs')
const resolved = polyfilledBuiltins.get(
removeEndingSlash(argsPath),
)
const contents = await (
await fs.promises.readFile(resolved)
).toString()
let resolveDir = path.dirname(resolved)
if (isCommonjs) {
return {
loader: 'js',
contents: commonJsTemplate({
importPath: argsPath,
}),
resolveDir,
}
}
return {
loader: 'js',
contents,
resolveDir,
}
} catch (e) {
console.error('node-modules-polyfill', e)
return {
contents: `export {}`,
loader: 'js',
}
}
}
onLoad({ filter: /.*/, namespace }, loader)
onLoad({ filter: /.*/, namespace: commonjsNamespace }, loader)
const filter = new RegExp(
[
...polyfilledBuiltinsNames,
...polyfilledBuiltinsNames.map((n) => `node:${n}`),
]
.map(escapeStringRegexp)
.join('|'), // TODO builtins could end with slash, keep in mind in regex
)
async function resolver(args: OnResolveArgs) {
const argsPath = args.path.replace(/^node:/, '')
const ignoreRequire = args.namespace === commonjsNamespace
if (!polyfilledBuiltins.has(argsPath)) {
return
}
const isCommonjs =
!ignoreRequire && args.kind === 'require-call'
return {
namespace: isCommonjs ? commonjsNamespace : namespace,
path: argsPath,
}
}
onResolve({ filter }, resolver)
// onResolve({ filter: /.*/, namespace }, resolver)
},
}
}
function commonJsTemplate({ importPath }) {
return `
const polyfill = require('${importPath}')
if (polyfill && polyfill.default) {
module.exports = polyfill.default
for (let k in polyfill) {
module.exports[k] = polyfill[k]
}
} else if (polyfill) {
module.exports = polyfill
}
`
}
export default NodeModulesPolyfillPlugin

View file

@ -1,151 +0,0 @@
// Taken from https://github.com/ionic-team/rollup-plugin-node-polyfills/blob/master/src/modules.ts
import { NodePolyfillsOptions } from '.'
const EMPTY_PATH = require.resolve(
'rollup-plugin-node-polyfills/polyfills/empty.js',
)
export function builtinsPolyfills() {
const libs = new Map()
libs.set(
'process',
require.resolve('rollup-plugin-node-polyfills/polyfills/process-es6'),
)
libs.set(
'buffer',
require.resolve('rollup-plugin-node-polyfills/polyfills/buffer-es6'),
)
libs.set(
'util',
require.resolve('rollup-plugin-node-polyfills/polyfills/util'),
)
libs.set('sys', libs.get('util'))
libs.set(
'events',
require.resolve('rollup-plugin-node-polyfills/polyfills/events'),
)
libs.set(
'stream',
require.resolve('rollup-plugin-node-polyfills/polyfills/stream'),
)
libs.set(
'path',
require.resolve('rollup-plugin-node-polyfills/polyfills/path'),
)
libs.set(
'querystring',
require.resolve('rollup-plugin-node-polyfills/polyfills/qs'),
)
libs.set(
'punycode',
require.resolve('rollup-plugin-node-polyfills/polyfills/punycode'),
)
libs.set(
'url',
require.resolve('rollup-plugin-node-polyfills/polyfills/url'),
)
libs.set(
'string_decoder',
require.resolve(
'rollup-plugin-node-polyfills/polyfills/string-decoder',
),
)
libs.set(
'http',
require.resolve('rollup-plugin-node-polyfills/polyfills/http'),
)
libs.set(
'https',
require.resolve('rollup-plugin-node-polyfills/polyfills/http'),
)
libs.set('os', require.resolve('rollup-plugin-node-polyfills/polyfills/os'))
libs.set(
'assert',
require.resolve('rollup-plugin-node-polyfills/polyfills/assert'),
)
libs.set(
'constants',
require.resolve('rollup-plugin-node-polyfills/polyfills/constants'),
)
libs.set(
'_stream_duplex',
require.resolve(
'rollup-plugin-node-polyfills/polyfills/readable-stream/duplex',
),
)
libs.set(
'_stream_passthrough',
require.resolve(
'rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough',
),
)
libs.set(
'_stream_readable',
require.resolve(
'rollup-plugin-node-polyfills/polyfills/readable-stream/readable',
),
)
libs.set(
'_stream_writable',
require.resolve(
'rollup-plugin-node-polyfills/polyfills/readable-stream/writable',
),
)
libs.set(
'_stream_transform',
require.resolve(
'rollup-plugin-node-polyfills/polyfills/readable-stream/transform',
),
)
libs.set(
'timers',
require.resolve('rollup-plugin-node-polyfills/polyfills/timers'),
)
libs.set(
'console',
require.resolve('rollup-plugin-node-polyfills/polyfills/console'),
)
libs.set('vm', require.resolve('rollup-plugin-node-polyfills/polyfills/vm'))
libs.set(
'zlib',
require.resolve('rollup-plugin-node-polyfills/polyfills/zlib'),
)
libs.set(
'tty',
require.resolve('rollup-plugin-node-polyfills/polyfills/tty'),
)
libs.set(
'domain',
require.resolve('rollup-plugin-node-polyfills/polyfills/domain'),
)
// not shimmed
libs.set('dns', EMPTY_PATH)
libs.set('dgram', EMPTY_PATH)
libs.set('child_process', EMPTY_PATH)
libs.set('cluster', EMPTY_PATH)
libs.set('module', EMPTY_PATH)
libs.set('net', EMPTY_PATH)
libs.set('readline', EMPTY_PATH)
libs.set('repl', EMPTY_PATH)
libs.set('tls', EMPTY_PATH)
libs.set('fs', EMPTY_PATH)
libs.set('crypto', EMPTY_PATH)
// libs.set(
// 'fs',
// require.resolve('rollup-plugin-node-polyfills/polyfills/browserify-fs'),
// )
// TODO enable crypto and fs https://github.com/ionic-team/rollup-plugin-node-polyfills/issues/20
// libs.set(
// 'crypto',
// require.resolve(
// 'rollup-plugin-node-polyfills/polyfills/crypto-browserify',
// ),
// )
return libs
}

View file

@ -1,3 +0,0 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

Binary file not shown.

View file

@ -1,17 +0,0 @@
{
"name": "@esbuild/linux-x64",
"version": "0.17.19",
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
"repository": "https://github.com/evanw/esbuild",
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=12"
},
"os": [
"linux"
],
"cpu": [
"x64"
]
}

167
node_modules/acorn-walk/CHANGELOG.md generated vendored
View file

@ -1,167 +0,0 @@
## 8.2.0 (2021-09-06)
### New features
Add support for walking ES2022 class static blocks.
## 8.1.1 (2021-06-29)
### Bug fixes
Include `base` in the type declarations.
## 8.1.0 (2021-04-24)
### New features
Support node types for class fields and private methods.
## 8.0.2 (2021-01-25)
### Bug fixes
Adjust package.json to work with Node 12.16.0 and 13.0-13.6.
## 8.0.0 (2021-01-05)
### Bug fixes
Fix a bug where `full` and `fullAncestor` would skip nodes with overridden types.
## 8.0.0 (2020-08-12)
### New features
The package can now be loaded directly as an ECMAScript module in node 13+.
## 7.2.0 (2020-06-17)
### New features
Support optional chaining and nullish coalescing.
Support `import.meta`.
Add support for `export * as ns from "source"`.
## 7.1.1 (2020-02-13)
### Bug fixes
Clean up the type definitions to actually work well with the main parser.
## 7.1.0 (2020-02-11)
### New features
Add a TypeScript definition file for the library.
## 7.0.0 (2017-08-12)
### New features
Support walking `ImportExpression` nodes.
## 6.2.0 (2017-07-04)
### New features
Add support for `Import` nodes.
## 6.1.0 (2018-09-28)
### New features
The walker now walks `TemplateElement` nodes.
## 6.0.1 (2018-09-14)
### Bug fixes
Fix bad "main" field in package.json.
## 6.0.0 (2018-09-14)
### Breaking changes
This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package.
The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported.
## 5.7.1 (2018-06-15)
### Bug fixes
Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions).
## 5.7.0 (2018-06-15)
### Bug fixes
Fix crash in walker when walking a binding-less catch node.
## 5.6.2 (2018-06-05)
### Bug fixes
In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere.
## 5.6.1 (2018-06-01)
### Bug fixes
Fix regression when passing `null` as fourth argument to `walk.recursive`.
## 5.6.0 (2018-05-31)
### Bug fixes
Fix a bug in the walker that caused a crash when walking an object pattern spread.
## 5.5.1 (2018-03-06)
### Bug fixes
Fix regression in walker causing property values in object patterns to be walked as expressions.
## 5.5.0 (2018-02-27)
### Bug fixes
Support object spread in the AST walker.
## 5.4.1 (2018-02-02)
### Bug fixes
5.4.0 somehow accidentally included an old version of walk.js.
## 5.2.0 (2017-10-30)
### Bug fixes
The `full` and `fullAncestor` walkers no longer visit nodes multiple times.
## 5.1.0 (2017-07-05)
### New features
New walker functions `full` and `fullAncestor`.
## 3.2.0 (2016-06-07)
### New features
Make it possible to use `visit.ancestor` with a walk state.
## 3.1.0 (2016-04-18)
### New features
The walker now allows defining handlers for `CatchClause` nodes.
## 2.5.2 (2015-10-27)
### Fixes
Fix bug where the walker walked an exported `let` statement as an expression.

21
node_modules/acorn-walk/LICENSE generated vendored
View file

@ -1,21 +0,0 @@
MIT License
Copyright (C) 2012-2020 by various contributors (see AUTHORS)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

126
node_modules/acorn-walk/README.md generated vendored
View file

@ -1,126 +0,0 @@
# Acorn AST walker
An abstract syntax tree walker for the
[ESTree](https://github.com/estree/estree) format.
## Community
Acorn is open source software released under an
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE).
You are welcome to
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
requests on [github](https://github.com/acornjs/acorn). For questions
and discussion, please use the
[Tern discussion forum](https://discuss.ternjs.net).
## Installation
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
```sh
npm install acorn-walk
```
Alternately, you can download the source and build acorn yourself:
```sh
git clone https://github.com/acornjs/acorn.git
cd acorn
npm install
```
## Interface
An algorithm for recursing through a syntax tree is stored as an
object, with a property for each tree node type holding a function
that will recurse through such a node. There are several ways to run
such a walker.
**simple**`(node, visitors, base, state)` does a 'simple' walk over a
tree. `node` should be the AST node to walk, and `visitors` an object
with properties whose names correspond to node types in the [ESTree
spec](https://github.com/estree/estree). The properties should contain
functions that will be called with the node object and, if applicable
the state at that point. The last two arguments are optional. `base`
is a walker algorithm, and `state` is a start state. The default
walker will simply visit all statements and expressions and not
produce a meaningful state. (An example of a use of state is to track
scope at each point in the tree.)
```js
const acorn = require("acorn")
const walk = require("acorn-walk")
walk.simple(acorn.parse("let x = 10"), {
Literal(node) {
console.log(`Found a literal: ${node.value}`)
}
})
```
**ancestor**`(node, visitors, base, state)` does a 'simple' walk over
a tree, building up an array of ancestor nodes (including the current node)
and passing the array to the callbacks as a third parameter.
```js
const acorn = require("acorn")
const walk = require("acorn-walk")
walk.ancestor(acorn.parse("foo('hi')"), {
Literal(_, ancestors) {
console.log("This literal's ancestors are:", ancestors.map(n => n.type))
}
})
```
**recursive**`(node, state, functions, base)` does a 'recursive'
walk, where the walker functions are responsible for continuing the
walk on the child nodes of their target node. `state` is the start
state, and `functions` should contain an object that maps node types
to walker functions. Such functions are called with `(node, state, c)`
arguments, and can cause the walk to continue on a sub-node by calling
the `c` argument on it with `(node, state)` arguments. The optional
`base` argument provides the fallback walker functions for node types
that aren't handled in the `functions` object. If not given, the
default walkers will be used.
**make**`(functions, base)` builds a new walker object by using the
walker functions in `functions` and filling in the missing ones by
taking defaults from `base`.
**full**`(node, callback, base, state)` does a 'full' walk over a
tree, calling the callback with the arguments (node, state, type) for
each node
**fullAncestor**`(node, callback, base, state)` does a 'full' walk
over a tree, building up an array of ancestor nodes (including the
current node) and passing the array to the callbacks as a third
parameter.
```js
const acorn = require("acorn")
const walk = require("acorn-walk")
walk.full(acorn.parse("1 + 1"), node => {
console.log(`There's a ${node.type} node at ${node.ch}`)
})
```
**findNodeAt**`(node, start, end, test, base, state)` tries to locate
a node in a tree at the given start and/or end offsets, which
satisfies the predicate `test`. `start` and `end` can be either `null`
(as wildcard) or a number. `test` may be a string (indicating a node
type) or a function that takes `(nodeType, node)` arguments and
returns a boolean indicating whether this node is interesting. `base`
and `state` are optional, and can be used to specify a custom walker.
Nodes are tested from inner to outer, so if two nodes match the
boundaries, the inner one will be preferred.
**findNodeAround**`(node, pos, test, base, state)` is a lot like
`findNodeAt`, but will match any node that exists 'around' (spanning)
the given position.
**findNodeAfter**`(node, pos, test, base, state)` is similar to
`findNodeAround`, but will match all nodes *after* the given position
(testing outer nodes before inner nodes).

View file

@ -1,114 +0,0 @@
import {Node} from 'acorn';
declare module "acorn-walk" {
type FullWalkerCallback<TState> = (
node: Node,
state: TState,
type: string
) => void;
type FullAncestorWalkerCallback<TState> = (
node: Node,
state: TState | Node[],
ancestors: Node[],
type: string
) => void;
type WalkerCallback<TState> = (node: Node, state: TState) => void;
type SimpleWalkerFn<TState> = (
node: Node,
state: TState
) => void;
type AncestorWalkerFn<TState> = (
node: Node,
state: TState| Node[],
ancestors: Node[]
) => void;
type RecursiveWalkerFn<TState> = (
node: Node,
state: TState,
callback: WalkerCallback<TState>
) => void;
type SimpleVisitors<TState> = {
[type: string]: SimpleWalkerFn<TState>
};
type AncestorVisitors<TState> = {
[type: string]: AncestorWalkerFn<TState>
};
type RecursiveVisitors<TState> = {
[type: string]: RecursiveWalkerFn<TState>
};
type FindPredicate = (type: string, node: Node) => boolean;
interface Found<TState> {
node: Node,
state: TState
}
export function simple<TState>(
node: Node,
visitors: SimpleVisitors<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function ancestor<TState>(
node: Node,
visitors: AncestorVisitors<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function recursive<TState>(
node: Node,
state: TState,
functions: RecursiveVisitors<TState>,
base?: RecursiveVisitors<TState>
): void;
export function full<TState>(
node: Node,
callback: FullWalkerCallback<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function fullAncestor<TState>(
node: Node,
callback: FullAncestorWalkerCallback<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function make<TState>(
functions: RecursiveVisitors<TState>,
base?: RecursiveVisitors<TState>
): RecursiveVisitors<TState>;
export function findNodeAt<TState>(
node: Node,
start: number | undefined,
end?: number | undefined,
type?: FindPredicate | string,
base?: RecursiveVisitors<TState>,
state?: TState
): Found<TState> | undefined;
export function findNodeAround<TState>(
node: Node,
start: number | undefined,
type?: FindPredicate | string,
base?: RecursiveVisitors<TState>,
state?: TState
): Found<TState> | undefined;
export const findNodeAfter: typeof findNodeAround;
export const base: RecursiveVisitors<any>;
}

463
node_modules/acorn-walk/dist/walk.js generated vendored
View file

@ -1,463 +0,0 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {})));
}(this, (function (exports) { 'use strict';
// AST walker module for Mozilla Parser API compatible trees
// A simple walk is one where you simply specify callbacks to be
// called on specific nodes. The last two arguments are optional. A
// simple use would be
//
// walk.simple(myTree, {
// Expression: function(node) { ... }
// });
//
// to do something with all expressions. All Parser API node types
// can be used to identify node types, as well as Expression and
// Statement, which denote categories of nodes.
//
// The base argument can be used to pass a custom (recursive)
// walker, and state can be used to give this walked an initial
// state.
function simple(node, visitors, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
baseVisitor[type](node, st, c);
if (found) { found(node, st); }
})(node, state, override);
}
// An ancestor walk keeps an array of ancestor nodes (including the
// current node) and passes them to the callback as third parameter
// (and also as state parameter when no other state is present).
function ancestor(node, visitors, baseVisitor, state, override) {
var ancestors = [];
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (found) { found(node, st || ancestors, ancestors); }
if (isNew) { ancestors.pop(); }
})(node, state, override);
}
// A recursive walk is one where your functions override the default
// walkers. They can modify and replace the state parameter that's
// threaded through the walk, and can opt how and whether to walk
// their child nodes (by calling their third argument on these
// nodes).
function recursive(node, state, funcs, baseVisitor, override) {
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
;(function c(node, st, override) {
visitor[override || node.type](node, st, c);
})(node, state, override);
}
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// A full walk triggers the callback on each node
function full(node, callback, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base; }
var last
;(function c(node, st, override) {
var type = override || node.type;
baseVisitor[type](node, st, c);
if (last !== node) {
callback(node, st, type);
last = node;
}
})(node, state, override);
}
// An fullAncestor walk is like an ancestor walk, but triggers
// the callback on each node
function fullAncestor(node, callback, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
var ancestors = [], last
;(function c(node, st, override) {
var type = override || node.type;
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (last !== node) {
callback(node, st || ancestors, ancestors, type);
last = node;
}
if (isNew) { ancestors.pop(); }
})(node, state);
}
// Find a node with a given start, end, and type (all are optional,
// null can be used as wildcard). Returns a {node, state} object, or
// undefined when it doesn't find a matching node.
function findNodeAt(node, start, end, test, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
test = makeTest(test);
try {
(function c(node, st, override) {
var type = override || node.type;
if ((start == null || node.start <= start) &&
(end == null || node.end >= end))
{ baseVisitor[type](node, st, c); }
if ((start == null || node.start === start) &&
(end == null || node.end === end) &&
test(type, node))
{ throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
baseVisitor[type](node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node after a given position.
function findNodeAfter(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
if (node.end < pos) { return }
var type = override || node.type;
if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
baseVisitor[type](node, st, c);
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node before a given position.
function findNodeBefore(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
var max
;(function c(node, st, override) {
if (node.start > pos) { return }
var type = override || node.type;
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
{ max = new Found(node, st); }
baseVisitor[type](node, st, c);
})(node, state);
return max
}
// Used to create a custom walker. Will fill in all missing node
// type properties with the defaults.
function make(funcs, baseVisitor) {
var visitor = Object.create(baseVisitor || base);
for (var type in funcs) { visitor[type] = funcs[type]; }
return visitor
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
var cs = list$1[i$1];
if (cs.test) { c(cs.test, st, "Expression"); }
for (var i = 0, list = cs.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
};
base.ExportAllDeclaration = function (node, st, c) {
if (node.exported)
{ c(node.exported, st); }
c(node.source, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
if (node.value) { c(node.value, st, "Expression"); }
};
exports.ancestor = ancestor;
exports.base = base;
exports.findNodeAfter = findNodeAfter;
exports.findNodeAround = findNodeAround;
exports.findNodeAt = findNodeAt;
exports.findNodeBefore = findNodeBefore;
exports.full = full;
exports.fullAncestor = fullAncestor;
exports.make = make;
exports.recursive = recursive;
exports.simple = simple;
Object.defineProperty(exports, '__esModule', { value: true });
})));

443
node_modules/acorn-walk/dist/walk.mjs generated vendored
View file

@ -1,443 +0,0 @@
// AST walker module for Mozilla Parser API compatible trees
// A simple walk is one where you simply specify callbacks to be
// called on specific nodes. The last two arguments are optional. A
// simple use would be
//
// walk.simple(myTree, {
// Expression: function(node) { ... }
// });
//
// to do something with all expressions. All Parser API node types
// can be used to identify node types, as well as Expression and
// Statement, which denote categories of nodes.
//
// The base argument can be used to pass a custom (recursive)
// walker, and state can be used to give this walked an initial
// state.
function simple(node, visitors, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
baseVisitor[type](node, st, c);
if (found) { found(node, st); }
})(node, state, override);
}
// An ancestor walk keeps an array of ancestor nodes (including the
// current node) and passes them to the callback as third parameter
// (and also as state parameter when no other state is present).
function ancestor(node, visitors, baseVisitor, state, override) {
var ancestors = [];
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (found) { found(node, st || ancestors, ancestors); }
if (isNew) { ancestors.pop(); }
})(node, state, override);
}
// A recursive walk is one where your functions override the default
// walkers. They can modify and replace the state parameter that's
// threaded through the walk, and can opt how and whether to walk
// their child nodes (by calling their third argument on these
// nodes).
function recursive(node, state, funcs, baseVisitor, override) {
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
;(function c(node, st, override) {
visitor[override || node.type](node, st, c);
})(node, state, override);
}
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// A full walk triggers the callback on each node
function full(node, callback, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base; }
var last
;(function c(node, st, override) {
var type = override || node.type;
baseVisitor[type](node, st, c);
if (last !== node) {
callback(node, st, type);
last = node;
}
})(node, state, override);
}
// An fullAncestor walk is like an ancestor walk, but triggers
// the callback on each node
function fullAncestor(node, callback, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
var ancestors = [], last
;(function c(node, st, override) {
var type = override || node.type;
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (last !== node) {
callback(node, st || ancestors, ancestors, type);
last = node;
}
if (isNew) { ancestors.pop(); }
})(node, state);
}
// Find a node with a given start, end, and type (all are optional,
// null can be used as wildcard). Returns a {node, state} object, or
// undefined when it doesn't find a matching node.
function findNodeAt(node, start, end, test, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
test = makeTest(test);
try {
(function c(node, st, override) {
var type = override || node.type;
if ((start == null || node.start <= start) &&
(end == null || node.end >= end))
{ baseVisitor[type](node, st, c); }
if ((start == null || node.start === start) &&
(end == null || node.end === end) &&
test(type, node))
{ throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
baseVisitor[type](node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node after a given position.
function findNodeAfter(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
if (node.end < pos) { return }
var type = override || node.type;
if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
baseVisitor[type](node, st, c);
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node before a given position.
function findNodeBefore(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
var max
;(function c(node, st, override) {
if (node.start > pos) { return }
var type = override || node.type;
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
{ max = new Found(node, st); }
baseVisitor[type](node, st, c);
})(node, state);
return max
}
// Used to create a custom walker. Will fill in all missing node
// type properties with the defaults.
function make(funcs, baseVisitor) {
var visitor = Object.create(baseVisitor || base);
for (var type in funcs) { visitor[type] = funcs[type]; }
return visitor
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
var cs = list$1[i$1];
if (cs.test) { c(cs.test, st, "Expression"); }
for (var i = 0, list = cs.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
};
base.ExportAllDeclaration = function (node, st, c) {
if (node.exported)
{ c(node.exported, st); }
c(node.source, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
if (node.value) { c(node.value, st, "Expression"); }
};
export { ancestor, base, findNodeAfter, findNodeAround, findNodeAt, findNodeBefore, full, fullAncestor, make, recursive, simple };

Some files were not shown because too many files have changed in this diff Show more