Files
SWebStatic/node_modules/@cloudflare/kv-asset-handler/dist/index.js
T

369 lines
50 KiB
JavaScript
Raw Normal View History

2026-07-08 18:29:36 +08:00
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
__defProp(target, "default", { value: mod, enumerable: true }) ,
mod
));
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js
var require_Mime = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js"(exports, module) {
function Mime() {
this._types = /* @__PURE__ */ Object.create(null);
this._extensions = /* @__PURE__ */ Object.create(null);
for (let i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
__name(Mime, "Mime");
Mime.prototype.define = function(typeMap, force) {
for (let type in typeMap) {
let extensions = typeMap[type].map(function(t) {
return t.toLowerCase();
});
type = type.toLowerCase();
for (let i = 0; i < extensions.length; i++) {
const ext = extensions[i];
if (ext[0] === "*") {
continue;
}
if (!force && ext in this._types) {
throw new Error(
'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".'
);
}
this._types[ext] = type;
}
if (force || !this._extensions[type]) {
const ext = extensions[0];
this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1);
}
}
};
Mime.prototype.getType = function(path) {
path = String(path);
let last = path.replace(/^.*[/\\]/, "").toLowerCase();
let ext = last.replace(/^.*\./, "").toLowerCase();
let hasPath = last.length < path.length;
let hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module.exports = Mime;
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js
var require_standard = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js"(exports, module) {
module.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "applicat
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js
var require_other = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js"(exports, module) {
module.exports = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flogr
}
});
// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js
var require_mime = __commonJS({
"../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js"(exports, module) {
var Mime = require_Mime();
module.exports = new Mime(require_standard(), require_other());
}
});
// src/index.ts
var mime = __toESM(require_mime());
// src/types.ts
var KVError = class _KVError extends Error {
static {
__name(this, "KVError");
}
constructor(message, status = 500) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = _KVError.name;
this.status = status;
}
status;
};
var MethodNotAllowedError = class extends KVError {
static {
__name(this, "MethodNotAllowedError");
}
constructor(message = `Not a valid request method`, status = 405) {
super(message, status);
}
};
var NotFoundError = class extends KVError {
static {
__name(this, "NotFoundError");
}
constructor(message = `Not Found`, status = 404) {
super(message, status);
}
};
var InternalError = class extends KVError {
static {
__name(this, "InternalError");
}
constructor(message = `Internal Error in KV Asset Handler`, status = 500) {
super(message, status);
}
};
// src/index.ts
var defaultCacheControl = {
browserTTL: null,
edgeTTL: 2 * 60 * 60 * 24,
// 2 days
bypassCache: false
// do not bypass Cloudflare's cache
};
var parseStringAsObject = /* @__PURE__ */ __name((maybeString) => typeof maybeString === "string" ? JSON.parse(maybeString) : maybeString, "parseStringAsObject");
function getAssetFromKVDefaultOptions() {
return {
ASSET_NAMESPACE: typeof __STATIC_CONTENT !== "undefined" ? __STATIC_CONTENT : void 0,
ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== "undefined" ? parseStringAsObject(__STATIC_CONTENT_MANIFEST) : {},
cacheControl: defaultCacheControl,
defaultMimeType: "text/plain",
defaultDocument: "index.html",
pathIsEncoded: false,
defaultETag: "strong"
};
}
__name(getAssetFromKVDefaultOptions, "getAssetFromKVDefaultOptions");
function assignOptions(options) {
return Object.assign({}, getAssetFromKVDefaultOptions(), options);
}
__name(assignOptions, "assignOptions");
var mapRequestToAsset = /* @__PURE__ */ __name((request, options) => {
options = assignOptions(options);
const parsedUrl = new URL(request.url);
let pathname = parsedUrl.pathname;
if (pathname.endsWith("/")) {
pathname = pathname.concat(options.defaultDocument);
} else if (!mime.getType(pathname)) {
pathname = pathname.concat("/" + options.defaultDocument);
}
parsedUrl.pathname = pathname;
return new Request(parsedUrl.toString(), request);
}, "mapRequestToAsset");
function serveSinglePageApp(request, options) {
options = assignOptions(options);
request = mapRequestToAsset(request, options);
const parsedUrl = new URL(request.url);
if (parsedUrl.pathname.endsWith(".html")) {
return new Request(
`${parsedUrl.origin}/${options.defaultDocument}`,
request
);
} else {
return request;
}
}
__name(serveSinglePageApp, "serveSinglePageApp");
var getAssetFromKV = /* @__PURE__ */ __name(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 InternalError(`there is no KV namespace bound to the script`);
}
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, "");
let pathIsEncoded = options.pathIsEncoded;
let requestKey;
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 {
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;
let pathKey = pathname.replace(/^\/+/, "");
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;
if (typeof ASSET_MANIFEST !== "undefined") {
if (ASSET_MANIFEST[pathKey]) {
pathKey = ASSET_MANIFEST[pathKey];
shouldEdgeCache = true;
}
}
const cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
const evalCacheOpts = (() => {
switch (typeof options.cacheControl) {
case "function":
return options.cacheControl(request);
case "object":
return options.cacheControl;
default:
return defaultCacheControl;
}
})();
const formatETag = /* @__PURE__ */ __name((entityId = pathKey, validatorType = options.defaultETag) => {
if (!entityId) {
return "";
}
switch (validatorType) {
case "weak":
if (!entityId.startsWith("W/")) {
if (entityId.startsWith(`"`) && entityId.endsWith(`"`)) {
return `W/${entityId}`;
}
return `W/"${entityId}"`;
}
return entityId;
case "strong":
if (entityId.startsWith(`W/"`)) {
entityId = entityId.replace("W/", "");
}
if (!entityId.endsWith(`"`)) {
entityId = `"${entityId}"`;
}
return entityId;
default:
return "";
}
}, "formatETag");
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts);
if (options.cacheControl.bypassCache || options.cacheControl.edgeTTL === null || request.method == "HEAD") {
shouldEdgeCache = false;
}
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)) {
response.body.cancel();
}
response = new Response(null, response);
} else {
const 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", String(body.byteLength));
if (!response.headers.has("etag")) {
response.headers.set("etag", formatETag(pathKey));
}
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) {
const etag = formatETag(response.headers.get("etag"));
const ifNoneMatch = cacheKey.headers.get("if-none-match");
const 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;
}, "getAssetFromKV");
export { InternalError, MethodNotAllowedError, NotFoundError, getAssetFromKV, mapRequestToAsset, serveSinglePageApp };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map