@crvouga/mockingbird-service-s3 3.10.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -382,7 +382,7 @@ var nameChar = nameStartChar + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
382
382
  var nameRegexp = "[" + nameStartChar + "][" + nameChar + "]*";
383
383
  var regexName = new RegExp("^" + nameRegexp + "$");
384
384
  function getAllMatches(string, regex) {
385
- const matches3 = [];
385
+ const matches2 = [];
386
386
  let match2 = regex.exec(string);
387
387
  while (match2) {
388
388
  const allmatches = [];
@@ -391,10 +391,10 @@ function getAllMatches(string, regex) {
391
391
  for (let index = 0; index < len; index++) {
392
392
  allmatches.push(match2[index]);
393
393
  }
394
- matches3.push(allmatches);
394
+ matches2.push(allmatches);
395
395
  match2 = regex.exec(string);
396
396
  }
397
- return matches3;
397
+ return matches2;
398
398
  }
399
399
  var isName = function(string) {
400
400
  const match2 = regexName.exec(string);
@@ -687,24 +687,24 @@ function scanAttributeTokens(attrStr) {
687
687
  return tokens;
688
688
  }
689
689
  function validateAttributeString(attrStr, options) {
690
- const matches3 = scanAttributeTokens(attrStr);
690
+ const matches2 = scanAttributeTokens(attrStr);
691
691
  const attrNames = {};
692
- for (let i = 0; i < matches3.length; i++) {
693
- if (matches3[i][1].length === 0) {
694
- return getErrorObject("InvalidAttr", "Attribute '" + matches3[i][2] + "' has no space in starting.", getPositionFromMatch(matches3[i]));
695
- } else if (matches3[i][3] !== void 0 && matches3[i][4] === void 0) {
696
- return getErrorObject("InvalidAttr", "Attribute '" + matches3[i][2] + "' is without value.", getPositionFromMatch(matches3[i]));
697
- } else if (matches3[i][3] === void 0 && !options.allowBooleanAttributes) {
698
- return getErrorObject("InvalidAttr", "boolean attribute '" + matches3[i][2] + "' is not allowed.", getPositionFromMatch(matches3[i]));
699
- }
700
- const attrName = matches3[i][2];
692
+ for (let i = 0; i < matches2.length; i++) {
693
+ if (matches2[i][1].length === 0) {
694
+ return getErrorObject("InvalidAttr", "Attribute '" + matches2[i][2] + "' has no space in starting.", getPositionFromMatch(matches2[i]));
695
+ } else if (matches2[i][3] !== void 0 && matches2[i][4] === void 0) {
696
+ return getErrorObject("InvalidAttr", "Attribute '" + matches2[i][2] + "' is without value.", getPositionFromMatch(matches2[i]));
697
+ } else if (matches2[i][3] === void 0 && !options.allowBooleanAttributes) {
698
+ return getErrorObject("InvalidAttr", "boolean attribute '" + matches2[i][2] + "' is not allowed.", getPositionFromMatch(matches2[i]));
699
+ }
700
+ const attrName = matches2[i][2];
701
701
  if (!validateAttrName(attrName)) {
702
- return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches3[i]));
702
+ return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is an invalid name.", getPositionFromMatch(matches2[i]));
703
703
  }
704
704
  if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {
705
705
  attrNames[attrName] = 1;
706
706
  } else {
707
- return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches3[i]));
707
+ return getErrorObject("InvalidAttr", "Attribute '" + attrName + "' is repeated.", getPositionFromMatch(matches2[i]));
708
708
  }
709
709
  }
710
710
  return true;
@@ -3675,8 +3675,8 @@ function assertContext(context) {
3675
3675
  throw new TypeError("is-unsafe: context must not be an empty array");
3676
3676
  }
3677
3677
  if (Array.isArray(context[0])) {
3678
- for (const list2 of context) {
3679
- if (!Array.isArray(list2) || list2.length === 0) {
3678
+ for (const list of context) {
3679
+ if (!Array.isArray(list) || list.length === 0) {
3680
3680
  throw new TypeError(
3681
3681
  "is-unsafe: each context in the array must be a non-empty pattern array (PatternList)"
3682
3682
  );
@@ -3694,9 +3694,9 @@ function normalise(context) {
3694
3694
  if (Array.isArray(context[0])) return { lists: context, regex: null };
3695
3695
  return { lists: [context], regex: null };
3696
3696
  }
3697
- function matchList(value, list2) {
3698
- const label = list2.label ?? "CUSTOM";
3699
- for (const rule of list2) {
3697
+ function matchList(value, list) {
3698
+ const label = list.label ?? "CUSTOM";
3699
+ for (const rule of list) {
3700
3700
  if (rule.pattern.test(value)) {
3701
3701
  return { context: label, id: rule.id, description: rule.description, pattern: rule.pattern };
3702
3702
  }
@@ -3708,8 +3708,8 @@ function isUnsafe(value, context) {
3708
3708
  assertContext(context);
3709
3709
  const { lists, regex } = normalise(context);
3710
3710
  if (regex) return regex.test(value);
3711
- for (const list2 of lists) {
3712
- if (matchList(value, list2) !== null) return true;
3711
+ for (const list of lists) {
3712
+ if (matchList(value, list) !== null) return true;
3713
3713
  }
3714
3714
  return false;
3715
3715
  }
@@ -3843,15 +3843,15 @@ var attrsRegx = new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`, "gm");
3843
3843
  function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3844
3844
  const options = this.options;
3845
3845
  if (force === true || options.ignoreAttributes !== true && typeof attrStr === "string") {
3846
- const matches3 = getAllMatches(attrStr, attrsRegx);
3847
- const len = matches3.length;
3846
+ const matches2 = getAllMatches(attrStr, attrsRegx);
3847
+ const len = matches2.length;
3848
3848
  const attrs = {};
3849
3849
  const processedVals = new Array(len);
3850
3850
  let hasRawAttrs = false;
3851
3851
  const rawAttrsForMatcher = {};
3852
3852
  for (let i = 0; i < len; i++) {
3853
- const attrName = this.resolveNameSpace(matches3[i][1]);
3854
- const oldVal = matches3[i][4];
3853
+ const attrName = this.resolveNameSpace(matches2[i][1]);
3854
+ const oldVal = matches2[i][4];
3855
3855
  if (attrName.length && oldVal !== void 0) {
3856
3856
  let val = oldVal;
3857
3857
  if (options.trimValues) val = val.trim();
@@ -3867,7 +3867,7 @@ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3867
3867
  const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;
3868
3868
  let hasAttrs = false;
3869
3869
  for (let i = 0; i < len; i++) {
3870
- const attrName = this.resolveNameSpace(matches3[i][1]);
3870
+ const attrName = this.resolveNameSpace(matches2[i][1]);
3871
3871
  if (this.ignoreAttributesFn(attrName, jPathStr)) continue;
3872
3872
  let aName = options.attributeNamePrefix + attrName;
3873
3873
  if (attrName.length) {
@@ -3875,7 +3875,7 @@ function buildAttributesMap(attrStr, jPath, tagName, force = false) {
3875
3875
  aName = options.transformAttributeName(aName);
3876
3876
  }
3877
3877
  aName = sanitizeName(aName, options);
3878
- if (matches3[i][4] !== void 0) {
3878
+ if (matches2[i][4] !== void 0) {
3879
3879
  const oldVal = processedVals[i];
3880
3880
  const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);
3881
3881
  if (newVal === null || newVal === void 0) {
@@ -4511,7 +4511,6 @@ var awsParseXml = (source) => {
4511
4511
  processEntities: true
4512
4512
  }).parse(source);
4513
4513
  };
4514
- var awsXmlEscape = (value) => String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4515
4514
 
4516
4515
  // ../core/dist/collection.js
4517
4516
  var Collection = class {
@@ -4671,10 +4670,10 @@ var OpenAPIReferenceError = class extends Error {
4671
4670
  };
4672
4671
  var unescapePointer = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
4673
4672
  var isReference = (value) => typeof value === "object" && value !== null && typeof value.$ref === "string";
4674
- var resolveRef = (document2, ref) => {
4673
+ var resolveRef = (document, ref) => {
4675
4674
  if (!ref.startsWith("#/"))
4676
4675
  throw new OpenAPIReferenceError(ref);
4677
- let cursor = document2;
4676
+ let cursor = document;
4678
4677
  for (const raw of ref.slice(2).split("/")) {
4679
4678
  const segment = unescapePointer(raw);
4680
4679
  if (typeof cursor !== "object" || cursor === null || !(segment in cursor)) {
@@ -4686,14 +4685,14 @@ var resolveRef = (document2, ref) => {
4686
4685
  throw new OpenAPIReferenceError(ref);
4687
4686
  return cursor;
4688
4687
  };
4689
- var deref = (document2, value) => {
4688
+ var deref = (document, value) => {
4690
4689
  let current = value;
4691
4690
  const seen = /* @__PURE__ */ new Set();
4692
4691
  while (isReference(current)) {
4693
4692
  if (seen.has(current.$ref))
4694
4693
  throw new OpenAPIReferenceError(`${current.$ref} (cycle)`);
4695
4694
  seen.add(current.$ref);
4696
- current = resolveRef(document2, current.$ref);
4695
+ current = resolveRef(document, current.$ref);
4697
4696
  }
4698
4697
  return current;
4699
4698
  };
@@ -4711,36 +4710,36 @@ var HTTP_METHODS = [
4711
4710
  ];
4712
4711
 
4713
4712
  // ../../openapi/core/dist/document.js
4714
- var mergeParameters = (document2, item, own) => {
4713
+ var mergeParameters = (document, item, own) => {
4715
4714
  const merged = /* @__PURE__ */ new Map();
4716
4715
  for (const raw of item.parameters ?? []) {
4717
- const parameter = deref(document2, raw);
4716
+ const parameter = deref(document, raw);
4718
4717
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
4719
4718
  }
4720
4719
  for (const raw of own ?? []) {
4721
- const parameter = deref(document2, raw);
4720
+ const parameter = deref(document, raw);
4722
4721
  merged.set(`${parameter.in}:${parameter.name}`, parameter);
4723
4722
  }
4724
4723
  return [...merged.values()];
4725
4724
  };
4726
- var listOperations = (document2) => {
4725
+ var listOperations = (document) => {
4727
4726
  const operations = [];
4728
- for (const [path, item] of Object.entries(document2.paths)) {
4727
+ for (const [path, item] of Object.entries(document.paths)) {
4729
4728
  for (const method of HTTP_METHODS) {
4730
4729
  const operation = item[method];
4731
4730
  if (operation?.operationId === void 0)
4732
4731
  continue;
4733
4732
  const responses = {};
4734
4733
  for (const [status, response] of Object.entries(operation.responses)) {
4735
- responses[status] = deref(document2, response);
4734
+ responses[status] = deref(document, response);
4736
4735
  }
4737
4736
  operations.push({
4738
4737
  operationId: operation.operationId,
4739
4738
  method,
4740
4739
  path,
4741
4740
  operation,
4742
- parameters: mergeParameters(document2, item, operation.parameters),
4743
- requestBody: operation.requestBody === void 0 ? void 0 : deref(document2, operation.requestBody),
4741
+ parameters: mergeParameters(document, item, operation.parameters),
4742
+ requestBody: operation.requestBody === void 0 ? void 0 : deref(document, operation.requestBody),
4744
4743
  responses
4745
4744
  });
4746
4745
  }
@@ -7120,10 +7119,10 @@ var createControlPlane = (context) => {
7120
7119
  return preset !== void 0 ? json(201, { preset, rules: added }) : json(201, added[0]);
7121
7120
  }),
7122
7121
  "PUT /faults": ({ body, namespace }) => guard(() => {
7123
- const list2 = isRecord2(body) ? body.faults : void 0;
7124
- if (!Array.isArray(list2))
7122
+ const list = isRecord2(body) ? body.faults : void 0;
7123
+ if (!Array.isArray(list))
7125
7124
  return adminError(400, 'expected {"faults": [...]}');
7126
- controls.apply(namespace, normalizeControls({ faults: list2 }));
7125
+ controls.apply(namespace, normalizeControls({ faults: list }));
7127
7126
  return json(200, { faults: faults.list(namespace) });
7128
7127
  }),
7129
7128
  "DELETE /faults": ({ url, namespace }) => {
@@ -7569,14 +7568,14 @@ var describeExtension = (extension) => {
7569
7568
  };
7570
7569
  };
7571
7570
  var adminUiRoutes = (service, ui, adminPrefix = ADMIN_PREFIX) => {
7572
- const document2 = (request) => {
7571
+ const document = (request) => {
7573
7572
  const mountPrefix = new URL(requestBaseUrl(request)).pathname.replace(/\/$/, "");
7574
7573
  const shell = () => renderAdminDocument(service, `${mountPrefix}${adminPrefix}`);
7575
7574
  return ui?.render ? ui.render({ service, defaultHtml: shell }) : shell();
7576
7575
  };
7577
7576
  return {
7578
- "GET /ui": ({ request }) => htmlResponse(document2(request)),
7579
- "GET /ui/": ({ request }) => htmlResponse(document2(request)),
7577
+ "GET /ui": ({ request }) => htmlResponse(document(request)),
7578
+ "GET /ui/": ({ request }) => htmlResponse(document(request)),
7580
7579
  "GET /ui/manifest": () => json2({
7581
7580
  service,
7582
7581
  standardRoutes: STANDARD_ADMIN_ROUTES,
@@ -7747,11 +7746,11 @@ var inferFields = (records) => {
7747
7746
  const objects = sample.filter((record) => isRecord3(record.value));
7748
7747
  if (objects.length === 0) {
7749
7748
  const kinds = new Set(sample.map((record) => kindOf(record.value)));
7750
- const list2 = [...kinds];
7749
+ const list = [...kinds];
7751
7750
  return [
7752
7751
  {
7753
7752
  name: "(value)",
7754
- kind: list2.length === 1 ? list2[0] : "unknown",
7753
+ kind: list.length === 1 ? list[0] : "unknown",
7755
7754
  optional: false
7756
7755
  }
7757
7756
  ];
@@ -8048,7 +8047,7 @@ var stateAdminRoutes = (routes) => {
8048
8047
  };
8049
8048
 
8050
8049
  // ../core/dist/version.js
8051
- var PACKAGE_VERSION = true ? "3.10.0" : UNRELEASED_VERSION;
8050
+ var PACKAGE_VERSION = true ? "4.0.0" : UNRELEASED_VERSION;
8052
8051
 
8053
8052
  // ../core/dist/signing.js
8054
8053
  var encoder = new TextEncoder();
@@ -8334,23 +8333,23 @@ var createWebhookHub = (options) => {
8334
8333
  const point = typeof handle === "object" && handle !== null ? snapshots.get(handle) : void 0;
8335
8334
  if (!point)
8336
8335
  throw new Error("invalid webhook snapshot");
8337
- const { namespace: _namespace, ...document2 } = point;
8338
- return structuredClone(document2);
8336
+ const { namespace: _namespace, ...document } = point;
8337
+ return structuredClone(document);
8339
8338
  },
8340
- importSnapshot(namespace, document2) {
8341
- if (!isRecord4(document2) || !Array.isArray(document2.endpoints) || !Array.isArray(document2.messages) || !Array.isArray(document2.deliveries) || !Array.isArray(document2.payloads) || !Array.isArray(document2.faults))
8339
+ importSnapshot(namespace, document) {
8340
+ if (!isRecord4(document) || !Array.isArray(document.endpoints) || !Array.isArray(document.messages) || !Array.isArray(document.deliveries) || !Array.isArray(document.payloads) || !Array.isArray(document.faults))
8342
8341
  throw new Error("invalid portable webhook snapshot");
8343
- for (const endpoint of document2.endpoints)
8342
+ for (const endpoint of document.endpoints)
8344
8343
  if (typeof parseEndpoint(endpoint) === "string")
8345
8344
  throw new Error("invalid portable webhook endpoint");
8346
- for (const message of document2.messages)
8345
+ for (const message of document.messages)
8347
8346
  if (!isRecord4(message) || typeof message.id !== "string" || typeof message.body !== "string")
8348
8347
  throw new Error("invalid portable webhook message");
8349
- for (const pair of [...document2.deliveries, ...document2.payloads])
8348
+ for (const pair of [...document.deliveries, ...document.payloads])
8350
8349
  if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string" || !isRecord4(pair[1]))
8351
8350
  throw new Error("invalid portable webhook entry");
8352
8351
  const handle = {};
8353
- const point = structuredClone(document2);
8352
+ const point = structuredClone(document);
8354
8353
  for (const message of point.messages)
8355
8354
  message.namespace = namespace;
8356
8355
  for (const [, delivery] of point.deliveries)
@@ -8571,11 +8570,11 @@ var webhookAdminRoutes = (hub) => ({
8571
8570
  }))
8572
8571
  }),
8573
8572
  "PUT /webhook-endpoints": ({ body, namespace }) => {
8574
- const list2 = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
8575
- if (!Array.isArray(list2))
8573
+ const list = Array.isArray(body) ? body : isRecord4(body) ? body.endpoints : void 0;
8574
+ if (!Array.isArray(list))
8576
8575
  return adminError3(400, "expected [{url, secret?, events?}]");
8577
8576
  const parsed = [];
8578
- for (const each of list2) {
8577
+ for (const each of list) {
8579
8578
  const endpoint = parseEndpoint(each);
8580
8579
  if (typeof endpoint === "string")
8581
8580
  return adminError3(400, endpoint);
@@ -8693,8 +8692,8 @@ var truncateResponse = (response, bytes) => {
8693
8692
  headers.delete("content-length");
8694
8693
  return new Response(body, { status: response.status, statusText: response.statusText, headers });
8695
8694
  };
8696
- var operationMatcher = (document2) => {
8697
- const matchers = listOperations(document2).map((operation) => ({
8695
+ var operationMatcher = (document) => {
8696
+ const matchers = listOperations(document).map((operation) => ({
8698
8697
  operationId: operation.operationId,
8699
8698
  method: operation.method.toUpperCase(),
8700
8699
  pattern: operationPath(operation).pattern,
@@ -8788,8 +8787,8 @@ var createRuntime = (options) => {
8788
8787
  ...overrides.count !== void 0 ? { count: overrides.count } : {}
8789
8788
  });
8790
8789
  },
8791
- restoreDocument: (namespace, document2, scope) => {
8792
- const { clock: carried, ...point } = fromDocument(namespace, document2);
8790
+ restoreDocument: (namespace, document, scope) => {
8791
+ const { clock: carried, ...point } = fromDocument(namespace, document);
8793
8792
  restoreAll(namespace, bootClockGiven || !carried ? point : { ...point, clock: carried }, scope);
8794
8793
  }
8795
8794
  });
@@ -9087,12 +9086,12 @@ var createRuntime = (options) => {
9087
9086
  throw new ControlError(`${label}: expected an unsigned 32-bit integer`);
9088
9087
  return value;
9089
9088
  };
9090
- const fromDocument = (namespace, document2) => {
9091
- if (document2.service !== void 0 && document2.service !== options.name)
9092
- throw new ControlError(`snapshot was taken from ${document2.service}, not ${options.name}`);
9089
+ const fromDocument = (namespace, document) => {
9090
+ if (document.service !== void 0 && document.service !== options.name)
9091
+ throw new ControlError(`snapshot was taken from ${document.service}, not ${options.name}`);
9093
9092
  const highest = /* @__PURE__ */ new Map();
9094
9093
  const seen = /* @__PURE__ */ new Set();
9095
- const records = document2.records.map((row) => {
9094
+ const records = document.records.map((row) => {
9096
9095
  const key = `${row.collection}\0${row.id}`;
9097
9096
  if (seen.has(key))
9098
9097
  throw new ControlError(`snapshot.records: duplicate ${row.collection}/${row.id}`);
@@ -9108,7 +9107,7 @@ var createRuntime = (options) => {
9108
9107
  });
9109
9108
  records.sort((left, right) => left.collection < right.collection ? -1 : left.collection > right.collection ? 1 : left.seq - right.seq);
9110
9109
  const sequences = /* @__PURE__ */ new Map();
9111
- for (const row of document2.sequences ?? [])
9110
+ for (const row of document.sequences ?? [])
9112
9111
  sequences.set(`${row.name}\0${row.kind}`, { ...row });
9113
9112
  for (const [collection, seq] of highest) {
9114
9113
  const key = `${collection}\0collection`;
@@ -9121,26 +9120,26 @@ var createRuntime = (options) => {
9121
9120
  sequences: Object.freeze([...sequences.values()].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : left.kind < right.kind ? -1 : left.kind > right.kind ? 1 : 0).map((row) => Object.freeze(row)))
9122
9121
  });
9123
9122
  const settings = {};
9124
- if (document2.seed !== void 0)
9125
- settings.seed = normalizeSeed(document2.seed, "snapshot.seed");
9126
- if (document2.virtualTime !== void 0) {
9127
- if (typeof document2.virtualTime !== "boolean")
9123
+ if (document.seed !== void 0)
9124
+ settings.seed = normalizeSeed(document.seed, "snapshot.seed");
9125
+ if (document.virtualTime !== void 0) {
9126
+ if (typeof document.virtualTime !== "boolean")
9128
9127
  throw new ControlError("snapshot.virtualTime: expected a boolean");
9129
- settings.virtualTime = document2.virtualTime;
9128
+ settings.virtualTime = document.virtualTime;
9130
9129
  }
9131
- const stepping2 = document2.clock?.autoAdvanceMs !== void 0 ? normalizeClock({ autoAdvance: document2.clock.autoAdvanceMs }, "snapshot.clock").autoAdvanceMs : void 0;
9130
+ const stepping2 = document.clock?.autoAdvanceMs !== void 0 ? normalizeClock({ autoAdvance: document.clock.autoAdvanceMs }, "snapshot.clock").autoAdvanceMs : void 0;
9132
9131
  if (stepping2 !== void 0)
9133
9132
  settings.autoAdvanceMs = stepping2;
9134
9133
  const held = {};
9135
9134
  if (Object.keys(settings).length > 0)
9136
9135
  held.settings = settings;
9137
- if (document2.rng?.faults !== void 0 || document2.rng?.latency !== void 0)
9136
+ if (document.rng?.faults !== void 0 || document.rng?.latency !== void 0)
9138
9137
  held.streams = {
9139
- ...document2.rng.faults !== void 0 ? { faults: position(document2.rng.faults, "snapshot.rng.faults") } : {},
9140
- ...document2.rng.latency !== void 0 ? { latency: position(document2.rng.latency, "snapshot.rng.latency") } : {}
9138
+ ...document.rng.faults !== void 0 ? { faults: position(document.rng.faults, "snapshot.rng.faults") } : {},
9139
+ ...document.rng.latency !== void 0 ? { latency: position(document.rng.latency, "snapshot.rng.latency") } : {}
9141
9140
  };
9142
- if (document2.faults !== void 0) {
9143
- const given = document2.faults;
9141
+ if (document.faults !== void 0) {
9142
+ const given = document.faults;
9144
9143
  if (!isRecord2(given) || !Array.isArray(given.rules))
9145
9144
  throw new ControlError("snapshot.faults: expected {rules: [...]}");
9146
9145
  held.faults = {
@@ -9158,14 +9157,14 @@ var createRuntime = (options) => {
9158
9157
  nextId: typeof given.nextId === "number" ? given.nextId : 0
9159
9158
  };
9160
9159
  }
9161
- if (document2.latency !== void 0)
9162
- held.latency = normalizeLatency(document2.latency, "snapshot.latency");
9160
+ if (document.latency !== void 0)
9161
+ held.latency = normalizeLatency(document.latency, "snapshot.latency");
9163
9162
  return {
9164
9163
  records: stored,
9165
- ...document2.clock ? { clock: { now: document2.clock.now, frozen: document2.clock.frozen } } : {},
9166
- ...document2.rng?.state !== void 0 ? { rngState: position(document2.rng.state, "snapshot.rng.state") } : {},
9164
+ ...document.clock ? { clock: { now: document.clock.now, frozen: document.clock.frozen } } : {},
9165
+ ...document.rng?.state !== void 0 ? { rngState: position(document.rng.state, "snapshot.rng.state") } : {},
9167
9166
  controls: held,
9168
- ...document2.webhooks !== void 0 ? { webhooks: options.webhooks?.importSnapshot(namespace, document2.webhooks) } : {}
9167
+ ...document.webhooks !== void 0 ? { webhooks: options.webhooks?.importSnapshot(namespace, document.webhooks) } : {}
9169
9168
  };
9170
9169
  };
9171
9170
  const kept = /* @__PURE__ */ new Map();
@@ -9202,7 +9201,7 @@ var createRuntime = (options) => {
9202
9201
  const found = kept.get(namespace)?.get(id);
9203
9202
  return found ? toDocument(found) : void 0;
9204
9203
  },
9205
- import: (namespace, id, document2) => keep(namespace, id, fromDocument(namespace, document2)),
9204
+ import: (namespace, id, document) => keep(namespace, id, fromDocument(namespace, document)),
9206
9205
  restore(namespace, id) {
9207
9206
  const found = kept.get(namespace)?.get(id);
9208
9207
  if (!found)
@@ -9222,9 +9221,9 @@ var createRuntime = (options) => {
9222
9221
  }
9223
9222
  };
9224
9223
  const applyControls = (namespace, plan) => {
9225
- const { snapshot: document2, ...rest } = plan;
9224
+ const { snapshot: document, ...rest } = plan;
9226
9225
  controls.check(rest);
9227
- const point = document2 ? fromDocument(namespace, document2) : void 0;
9226
+ const point = document ? fromDocument(namespace, document) : void 0;
9228
9227
  if (point)
9229
9228
  restoreAll(namespace, point);
9230
9229
  controls.apply(namespace, rest);
@@ -9310,11 +9309,11 @@ var createRuntime = (options) => {
9310
9309
  throw new Error("invalid fleet checkpoint");
9311
9310
  return toDocument(point);
9312
9311
  },
9313
- fleetImport(namespace, document2) {
9312
+ fleetImport(namespace, document) {
9314
9313
  const handle = {};
9315
9314
  fleetPoints.set(handle, {
9316
9315
  namespace,
9317
- ...fromDocument(namespace, assertSnapshotDocument(document2))
9316
+ ...fromDocument(namespace, assertSnapshotDocument(document))
9318
9317
  });
9319
9318
  return handle;
9320
9319
  },
@@ -9324,20 +9323,20 @@ var createRuntime = (options) => {
9324
9323
  reset,
9325
9324
  dropNamespace,
9326
9325
  controls: (namespace = DEFAULT_NAMESPACE) => describeControls(namespace),
9327
- configure(document2, namespace = DEFAULT_NAMESPACE) {
9328
- applyControls(namespace, normalizeControls(document2));
9326
+ configure(document, namespace = DEFAULT_NAMESPACE) {
9327
+ applyControls(namespace, normalizeControls(document));
9329
9328
  return describeControls(namespace);
9330
9329
  },
9331
9330
  snapshots: {
9332
9331
  create: (given = {}) => snapshotStore.create(given.namespace ?? DEFAULT_NAMESPACE, given.name),
9333
9332
  list: (namespace = DEFAULT_NAMESPACE) => snapshotStore.list(namespace),
9334
9333
  export(id, namespace = DEFAULT_NAMESPACE) {
9335
- const document2 = snapshotStore.export(namespace, id);
9336
- if (!document2)
9334
+ const document = snapshotStore.export(namespace, id);
9335
+ if (!document)
9337
9336
  throw new RangeError(`no snapshot ${id} in namespace ${namespace}`);
9338
- return document2;
9337
+ return document;
9339
9338
  },
9340
- import: (document2, given = {}) => snapshotStore.import(given.namespace ?? DEFAULT_NAMESPACE, given.name, document2),
9339
+ import: (document, given = {}) => snapshotStore.import(given.namespace ?? DEFAULT_NAMESPACE, given.name, document),
9341
9340
  restore(id, namespace = DEFAULT_NAMESPACE) {
9342
9341
  if (!snapshotStore.restore(namespace, id))
9343
9342
  throw new RangeError(`no snapshot ${id} in namespace ${namespace}`);
@@ -9737,9 +9736,9 @@ var credentialRoutes = (registry) => ({
9737
9736
  }),
9738
9737
  "PUT /credentials": ({ body, namespace }) => {
9739
9738
  const pairs = [];
9740
- const list2 = Array.isArray(body) ? body : isRecord2(body) ? body.credentials : void 0;
9741
- if (Array.isArray(list2)) {
9742
- for (const each of list2) {
9739
+ const list = Array.isArray(body) ? body : isRecord2(body) ? body.credentials : void 0;
9740
+ if (Array.isArray(list)) {
9741
+ for (const each of list) {
9743
9742
  if (typeof each === "string")
9744
9743
  pairs.push([each, namespace]);
9745
9744
  else if (isRecord2(each) && typeof each.credential === "string") {
@@ -9750,8 +9749,8 @@ var credentialRoutes = (registry) => ({
9750
9749
  } else
9751
9750
  return adminFail(400, "each entry is a credential string or {credential, namespace}");
9752
9751
  }
9753
- } else if (isRecord2(list2)) {
9754
- for (const [credential, target] of Object.entries(list2)) {
9752
+ } else if (isRecord2(list)) {
9753
+ for (const [credential, target] of Object.entries(list)) {
9755
9754
  if (typeof target !== "string")
9756
9755
  return adminFail(400, `namespace for ${credential} must be a string`);
9757
9756
  pairs.push([credential, target]);
@@ -9778,1385 +9777,32 @@ var credentialRoutes = (registry) => ({
9778
9777
  }
9779
9778
  });
9780
9779
 
9781
- // src/checksums.ts
9782
- var table = (polynomial) => Array.from({ length: 256 }, (_, index) => {
9783
- let value = index;
9784
- for (let bit = 0; bit < 8; bit++) value = value & 1 ? value >>> 1 ^ polynomial : value >>> 1;
9785
- return value >>> 0;
9786
- });
9787
- var CRC32_TABLE = table(3988292384);
9788
- var CRC32C_TABLE = table(2197175160);
9789
- var crc32 = (bytes, lookup) => {
9790
- let crc = 4294967295;
9791
- for (const byte of bytes) crc = lookup[(crc ^ byte) & 255] ^ crc >>> 8;
9792
- return (crc ^ 4294967295) >>> 0;
9793
- };
9794
- var POLYNOMIAL_64 = 0x9a6c9329ac4bc9b5n;
9795
- var table64;
9796
- var crc64nvme = (bytes) => {
9797
- table64 ??= Array.from({ length: 256 }, (_, index) => {
9798
- let value = BigInt(index);
9799
- for (let bit = 0; bit < 8; bit++)
9800
- value = value & 1n ? value >> 1n ^ POLYNOMIAL_64 : value >> 1n;
9801
- return value;
9802
- });
9803
- let crc = 0xffffffffffffffffn;
9804
- for (const byte of bytes)
9805
- crc = table64[Number((crc ^ BigInt(byte)) & 0xffn)] ^ crc >> 8n;
9806
- return crc ^ 0xffffffffffffffffn;
9807
- };
9808
- var base64 = (bytes) => btoa(String.fromCharCode(...bytes));
9809
- var big = (value, width) => {
9810
- const out = new Uint8Array(width);
9811
- let rest = BigInt(value);
9812
- for (let index = width - 1; index >= 0; index--) {
9813
- out[index] = Number(rest & 0xffn);
9814
- rest >>= 8n;
9815
- }
9816
- return out;
9817
- };
9818
- var subtle = async (algorithm, bytes) => new Uint8Array(await crypto.subtle.digest(algorithm, bytes));
9819
- var CHECKSUM_ALGORITHMS = ["crc32", "crc32c", "crc64nvme", "sha1", "sha256"];
9820
- var checksum = async (algorithm, bytes) => {
9821
- switch (algorithm) {
9822
- case "crc32":
9823
- return base64(big(crc32(bytes, CRC32_TABLE), 4));
9824
- case "crc32c":
9825
- return base64(big(crc32(bytes, CRC32C_TABLE), 4));
9826
- case "crc64nvme":
9827
- return base64(big(crc64nvme(bytes), 8));
9828
- case "sha1":
9829
- return base64(await subtle("SHA-1", bytes));
9830
- case "sha256":
9831
- return base64(await subtle("SHA-256", bytes));
9832
- }
9833
- };
9834
-
9835
- // src/chunked.ts
9836
- var isAwsChunked = (headers) => (headers.get("x-amz-content-sha256") ?? "").startsWith("STREAMING-") || (headers.get("content-encoding") ?? "").split(",").some((coding) => coding.trim().toLowerCase() === "aws-chunked");
9837
- var CR = 13;
9838
- var LF = 10;
9839
- var HEX_SIZE = /^[0-9a-fA-F]{1,15}$/;
9840
- var decodeAwsChunked = (input) => {
9841
- const line = (from) => {
9842
- for (let index = from; index + 1 < input.length; index++)
9843
- if (input[index] === CR && input[index + 1] === LF)
9844
- return {
9845
- text: new TextDecoder("latin1").decode(input.subarray(from, index)),
9846
- next: index + 2
9847
- };
9848
- return void 0;
9849
- };
9850
- const chunks = [];
9851
- let position = 0;
9852
- for (; ; ) {
9853
- const header = line(position);
9854
- if (!header) return void 0;
9855
- const size = header.text.split(";")[0];
9856
- if (!HEX_SIZE.test(size)) return void 0;
9857
- position = header.next;
9858
- const length = Number.parseInt(size, 16);
9859
- if (length === 0) break;
9860
- if (position + length + 2 > input.length) return void 0;
9861
- if (input[position + length] !== CR || input[position + length + 1] !== LF) return void 0;
9862
- chunks.push(input.subarray(position, position + length));
9863
- position += length + 2;
9864
- }
9865
- const trailers = {};
9866
- for (; ; ) {
9867
- const trailer = line(position);
9868
- if (!trailer) return void 0;
9869
- position = trailer.next;
9870
- if (trailer.text === "") break;
9871
- const colon = trailer.text.indexOf(":");
9872
- if (colon < 1) return void 0;
9873
- trailers[trailer.text.slice(0, colon).trim().toLowerCase()] = trailer.text.slice(colon + 1).trim();
9874
- }
9875
- const payload = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
9876
- let offset = 0;
9877
- for (const chunk of chunks) {
9878
- payload.set(chunk, offset);
9879
- offset += chunk.length;
9880
- }
9881
- return { payload, trailers };
9882
- };
9883
-
9884
- // src/cors.ts
9885
- var CORS_METHODS = ["GET", "PUT", "POST", "DELETE", "HEAD"];
9886
- var PREFLIGHT_VARY = "Origin, Access-Control-Request-Headers, Access-Control-Request-Method";
9887
- var list = (value) => (Array.isArray(value) ? value : value === void 0 || value === "" ? [] : [value]).map(String);
9888
- var parseCors = (body) => {
9889
- const root = awsParseXml(body).CORSConfiguration ?? {};
9890
- const rules = Array.isArray(root.CORSRule) ? root.CORSRule : root.CORSRule ? [root.CORSRule] : [];
9891
- return rules.map((rule) => ({
9892
- origins: list(rule.AllowedOrigin),
9893
- methods: list(rule.AllowedMethod),
9894
- headers: list(rule.AllowedHeader),
9895
- expose: list(rule.ExposeHeader),
9896
- ...rule.MaxAgeSeconds !== void 0 ? { maxAge: String(rule.MaxAgeSeconds).trim() } : {}
9897
- }));
9898
- };
9899
- var invalidCors = (rules) => {
9900
- if (rules.length === 0 || rules.length > 100)
9901
- return [
9902
- "MalformedXML",
9903
- "The XML you provided was not well-formed or did not validate against our published schema"
9904
- ];
9905
- for (const rule of rules) {
9906
- if (rule.origins.length === 0 || rule.methods.length === 0)
9907
- return [
9908
- "MalformedXML",
9909
- "The XML you provided was not well-formed or did not validate against our published schema"
9910
- ];
9911
- for (const method of rule.methods)
9912
- if (!CORS_METHODS.includes(method))
9913
- return [
9914
- "InvalidRequest",
9915
- `Found unsupported HTTP method in CORS config. Unsupported method is ${method}`
9916
- ];
9917
- for (const [name2, values] of [
9918
- ["AllowedOrigin", rule.origins],
9919
- ["AllowedHeader", rule.headers]
9920
- ])
9921
- for (const value of values)
9922
- if (value.split("*").length > 2)
9923
- return ["InvalidRequest", `${name2} "${value}" can not have more than one wildcard.`];
9924
- if (rule.maxAge !== void 0 && !/^\d+$/.test(rule.maxAge))
9925
- return [
9926
- "MalformedXML",
9927
- "The XML you provided was not well-formed or did not validate against our published schema"
9928
- ];
9929
- }
9930
- return void 0;
9931
- };
9932
- var matches2 = (pattern, value) => {
9933
- const star = pattern.indexOf("*");
9934
- return star < 0 ? pattern === value : value.length >= pattern.length - 1 && value.startsWith(pattern.slice(0, star)) && value.endsWith(pattern.slice(star + 1));
9935
- };
9936
- var matchRule = (rules, origin, method, requested = []) => rules.find(
9937
- (rule) => rule.origins.some((pattern) => matches2(pattern, origin)) && rule.methods.includes(method) && requested.every(
9938
- (header) => rule.headers.some((pattern) => matches2(pattern.toLowerCase(), header))
9939
- )
9940
- );
9941
- var corsHeaders = (rule, origin) => {
9942
- const any = rule.origins.includes("*");
9943
- return {
9944
- "access-control-allow-origin": any ? "*" : origin,
9945
- "access-control-allow-methods": rule.methods.join(", "),
9946
- ...any ? {} : { "access-control-allow-credentials": "true" },
9947
- ...rule.expose.length ? { "access-control-expose-headers": rule.expose.join(", ") } : {}
9948
- };
9949
- };
9950
-
9951
- // src/generated/openapi.ts
9952
- var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Amazon S3 (Mockingbird subset)","version":"2006-03-01","description":"Path-style S3 REST contract used by AWS SDK v3."},"servers":[{"url":"https://s3.us-east-1.amazonaws.com"}],"paths":{"/{bucket}":{"parameters":[{"name":"bucket","in":"path","required":true,"schema":{"type":"string"}}],"put":{"operationId":"CreateBucket","x-mockingbird":{"supported":true,"parity":{"safe":false}},"responses":{"200":{"description":"Created"},"400":{"$ref":"#/components/responses/Error"},"403":{"$ref":"#/components/responses/Error"}}},"head":{"operationId":"HeadBucket","responses":{"200":{"description":"Exists"},"404":{"description":"Missing"}}},"get":{"operationId":"ListObjectsV2","responses":{"200":{"description":"XML listing","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"BucketPost","x-mockingbird":{"supported":true,"parity":{"safe":false}},"responses":{"200":{"description":"DeleteObjects result","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"$ref":"#/components/responses/Error"}}}},"/{bucket}/{key}":{"parameters":[{"name":"bucket","in":"path","required":true,"schema":{"type":"string"}},{"name":"key","in":"path","required":true,"schema":{"type":"string"}}],"put":{"operationId":"PutObject","x-mockingbird":{"supported":true,"parity":{"safe":false}},"requestBody":{"content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"responses":{"200":{"description":"Stored"},"400":{"$ref":"#/components/responses/Error"},"403":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"}}},"get":{"operationId":"GetObject","responses":{"200":{"description":"Object bytes","content":{"application/octet-stream":{"schema":{"type":"string","format":"binary"}}}},"206":{"description":"Range bytes"},"403":{"$ref":"#/components/responses/Error"},"404":{"$ref":"#/components/responses/Error"},"416":{"$ref":"#/components/responses/Error"}}},"head":{"operationId":"HeadObject","responses":{"200":{"description":"Object metadata"},"404":{"description":"Missing"}}},"delete":{"operationId":"DeleteObject","x-mockingbird":{"supported":true,"parity":{"safe":false}},"responses":{"204":{"description":"Deleted"},"403":{"$ref":"#/components/responses/Error"}}},"post":{"operationId":"MultipartPost","x-mockingbird":{"supported":true,"parity":{"enabled":false,"reason":"Multipart XML protocol."}},"responses":{"200":{"description":"Multipart response","content":{"application/xml":{"schema":{"type":"string"}}}},"404":{"$ref":"#/components/responses/Error"}}}}},"components":{"responses":{"Error":{"description":"Canonical S3 XML error.","content":{"application/xml":{"schema":{"type":"string"}}}}}}}`);
9953
- var operationIds = ["ListObjectsV2", "CreateBucket", "BucketPost", "HeadBucket", "GetObject", "PutObject", "MultipartPost", "DeleteObject", "HeadObject"];
9954
- var supportedOperationIds = ["ListObjectsV2", "CreateBucket", "BucketPost", "HeadBucket", "GetObject", "PutObject", "MultipartPost", "DeleteObject", "HeadObject"];
9955
-
9956
- // src/hosting.ts
9957
- var DEFAULT_VIRTUAL_HOSTS = ["localhost"];
9958
- var VIRTUAL_BUCKET_HEADER = "x-mockingbird-s3-virtual-bucket";
9959
- var virtualBucket = (host, bases) => {
9960
- if (host.startsWith("[")) return void 0;
9961
- const name2 = host.replace(/:\d+$/, "").toLowerCase();
9962
- const base = [...bases].map((value) => value.toLowerCase().replace(/^\.+|\.+$/g, "")).filter((value) => value && name2.endsWith(`.${value}`) && name2.length > value.length + 1).sort((a, b) => b.length - a.length)[0];
9963
- return base ? name2.slice(0, name2.length - base.length - 1) : void 0;
9964
- };
9965
- var toPathStyle = (request, bases, keep) => {
9966
- const url = new URL(request.url);
9967
- const bucket = virtualBucket(url.host, bases);
9968
- if (!bucket || request.headers.get(VIRTUAL_BUCKET_HEADER) === bucket) return request;
9969
- if (keep && (url.pathname === keep || url.pathname.startsWith(`${keep}/`))) return request;
9970
- url.pathname = url.pathname === "/" ? `/${bucket}` : `/${bucket}${url.pathname}`;
9971
- const headers = new Headers(request.headers);
9972
- headers.set(VIRTUAL_BUCKET_HEADER, bucket);
9973
- const init = {
9974
- method: request.method,
9975
- headers,
9976
- signal: request.signal
9977
- };
9978
- if (request.body) {
9979
- init.body = request.body;
9980
- init.duplex = "half";
9981
- }
9982
- return new Request(url, init);
9983
- };
9984
-
9985
- // src/state.ts
9986
- var CHUNK = 32768;
9987
- var encodeBytes = (bytes) => {
9988
- const pieces = [];
9989
- for (let offset = 0; offset < bytes.length; offset += CHUNK)
9990
- pieces.push(String.fromCharCode(...bytes.subarray(offset, offset + CHUNK)));
9991
- return btoa(pieces.join(""));
9992
- };
9993
- var decodeBytes = (stored) => {
9994
- if (typeof stored !== "string") return Uint8Array.from(stored);
9995
- const binary = atob(stored);
9996
- const bytes = new Uint8Array(binary.length);
9997
- for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
9998
- return bytes;
9999
- };
10000
- var BlobCollection = class {
10001
- inner;
10002
- constructor(sqlite, namespace, name2) {
10003
- this.inner = new Collection(sqlite, namespace, name2);
10004
- }
10005
- decode(value) {
10006
- return { ...value, bytes: decodeBytes(value.bytes) };
10007
- }
10008
- get(id) {
10009
- const value = this.inner.get(id);
10010
- return value && this.decode(value);
10011
- }
10012
- has(id) {
10013
- return this.inner.has(id);
10014
- }
10015
- insert(id, value) {
10016
- this.inner.insert(id, { ...value, bytes: encodeBytes(value.bytes) });
10017
- }
10018
- delete(id) {
10019
- return this.inner.delete(id);
10020
- }
10021
- list(options = {}) {
10022
- return this.inner.list({
10023
- ...options.order ? { order: options.order } : {},
10024
- ...options.where ? { where: options.where } : {}
10025
- }).map((row) => ({ ...row, value: this.decode(row.value) }));
10026
- }
10027
- };
10028
- var S3State = class {
10029
- buckets;
10030
- objects;
10031
- versions;
10032
- configurations;
10033
- uploads;
10034
- parts;
10035
- ids;
10036
- constructor(sqlite, namespace) {
10037
- this.buckets = new Collection(sqlite, namespace, "s3_buckets");
10038
- this.objects = new BlobCollection(sqlite, namespace, "s3_objects");
10039
- this.versions = new BlobCollection(sqlite, namespace, "s3_versions");
10040
- this.configurations = new Collection(sqlite, namespace, "s3_configurations");
10041
- this.uploads = new Collection(sqlite, namespace, "s3_uploads");
10042
- this.parts = new BlobCollection(sqlite, namespace, "s3_parts");
10043
- this.ids = new IdSequence(sqlite, namespace, "s3");
10044
- }
10045
- objectId(bucket, key) {
10046
- return JSON.stringify([bucket, key]);
10047
- }
10048
- object(bucket, key) {
10049
- return this.objects.get(this.objectId(bucket, key));
10050
- }
9780
+ // src/digest.ts
9781
+ var md5Hex = (bytes) => awsMd5(bytes);
9782
+ var md5Base64 = (bytes) => {
9783
+ const hex = awsMd5(bytes);
9784
+ let binary = "";
9785
+ for (let index = 0; index < hex.length; index += 2)
9786
+ binary += String.fromCharCode(Number.parseInt(hex.slice(index, index + 2), 16));
9787
+ return btoa(binary);
10051
9788
  };
10052
-
10053
- // src/runtime.ts
10054
- var S3_PRESETS = {
10055
- slow_down: {
10056
- description: "S3 answers SlowDown for the next matching request",
10057
- rules: [
10058
- {
10059
- status: 503,
10060
- body: "<Error><Code>SlowDown</Code><Message>Please reduce your request rate.</Message></Error>",
10061
- headers: { "content-type": "application/xml" }
10062
- }
10063
- ]
10064
- },
10065
- access_denied: {
10066
- description: "S3 answers AccessDenied",
10067
- rules: [
10068
- {
10069
- status: 403,
10070
- body: "<Error><Code>AccessDenied</Code><Message>Access Denied</Message></Error>",
10071
- headers: { "content-type": "application/xml" }
10072
- }
10073
- ]
10074
- },
10075
- expired_token: {
10076
- description: "S3 answers ExpiredToken",
10077
- rules: [
10078
- {
10079
- status: 400,
10080
- body: "<Error><Code>ExpiredToken</Code><Message>The provided token has expired.</Message></Error>",
10081
- headers: { "content-type": "application/xml" }
10082
- }
10083
- ]
10084
- },
10085
- truncate_stream: {
10086
- description: "The next matching GetObject returns half of the stored bytes",
10087
- rules: [{ operationId: "GetObject", effect: "truncate_stream", count: 1 }]
10088
- }
10089
- };
10090
- var admin = (runtime) => ({
10091
- "GET /objects": ({ namespace, url }) => {
10092
- const bucket = url.searchParams.get("bucket");
10093
- return Response.json({
10094
- objects: runtime.instance(namespace).state.objects.list({ where: (object) => !bucket || object.bucket === bucket }).map(({ value }) => ({
10095
- bucket: value.bucket,
10096
- key: value.key,
10097
- contentLength: value.bytes.length,
10098
- contentType: value.contentType,
10099
- etag: value.etag,
10100
- lastModified: value.lastModified,
10101
- metadata: value.metadata
10102
- }))
10103
- });
10104
- },
10105
- "GET /uploads": ({ namespace }) => Response.json({
10106
- uploads: runtime.instance(namespace).state.uploads.list().map(({ value }) => ({
10107
- ...value,
10108
- parts: runtime.instance(namespace).state.parts.list({ where: (part) => part.uploadId === value.id }).map(({ value: part }) => ({
10109
- partNumber: part.partNumber,
10110
- etag: part.etag,
10111
- contentLength: part.bytes.length
10112
- }))
10113
- }))
10114
- }),
10115
- "POST /objects": async ({ namespace, body }) => {
10116
- const input = body;
10117
- if (!input || typeof input.bucket !== "string" || typeof input.key !== "string" || typeof input.body !== "string")
10118
- return Response.json(
10119
- {
10120
- error: { type: "mockingbird_admin", message: "bucket, key and string body are required" }
10121
- },
10122
- { status: 400 }
10123
- );
10124
- const object = await runtime.instance(namespace).putSeed({
10125
- bucket: input.bucket,
10126
- key: input.key,
10127
- body: input.body,
10128
- metadata: {},
10129
- ...typeof input.contentType === "string" ? { contentType: input.contentType } : {}
10130
- });
10131
- return Response.json(
10132
- { bucket: object.bucket, key: object.key, etag: object.etag },
10133
- { status: 201 }
10134
- );
10135
- },
10136
- "GET /objects/:bucket/:key": ({ namespace, params }) => {
10137
- const object = runtime.instance(namespace).state.object(params.bucket, params.key);
10138
- return object ? new Response(new Uint8Array(object.bytes), {
10139
- headers: { "content-type": object.contentType ?? "application/octet-stream" }
10140
- }) : Response.json(
10141
- { error: { type: "mockingbird_admin", message: "object not found" } },
10142
- { status: 404 }
10143
- );
10144
- }
10145
- });
10146
- var createRuntime2 = (options = {}) => {
10147
- const hub = createWebhookHub({
10148
- signer: signers.none(),
10149
- endpoints: options.webhooks?.endpoints ?? [],
10150
- ...options.webhooks?.retryDelaysMs ? { retryDelaysMs: options.webhooks.retryDelaysMs } : {},
10151
- ...options.webhooks?.fetch ? { fetch: options.webhooks.fetch } : {}
10152
- });
10153
- const runtime = createRuntime({
10154
- name: S3_NAMESPACE,
10155
- document,
10156
- presets: S3_PRESETS,
10157
- ...options.sqlite ? { sqlite: options.sqlite } : {},
10158
- ...options.clock ? { clock: options.clock } : {},
10159
- ...options.seed !== void 0 ? { seed: options.seed } : {},
10160
- ...options.adminPrefix !== void 0 ? { adminPrefix: options.adminPrefix } : {},
10161
- ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
10162
- ...options.adminControls !== void 0 ? { adminControls: options.adminControls } : {},
10163
- ...options.onLog ? { onLog: options.onLog } : {},
10164
- credential: accessKeyCredential,
10165
- create: ({ sqlite, namespace, clock, rng }) => new S3API({
10166
- sqlite,
10167
- namespace,
10168
- now: clock.now,
10169
- random: rng.next,
10170
- ...options.buckets ? { buckets: options.buckets } : {},
10171
- ...options.objects ? { objects: options.objects } : {},
10172
- ...options.credentials ? { credentials: options.credentials } : {},
10173
- ...options.virtualHosts ? { virtualHosts: options.virtualHosts } : {},
10174
- onNotification: (event) => hub.publish({
10175
- namespace,
10176
- type: `s3:${event.eventName}`,
10177
- body: {
10178
- Records: [
10179
- {
10180
- eventName: event.eventName,
10181
- eventTime: event.occurredAt,
10182
- s3: {
10183
- bucket: { name: event.bucket },
10184
- object: {
10185
- key: encodeURIComponent(event.key),
10186
- eTag: event.etag,
10187
- size: event.size
10188
- }
10189
- }
10190
- }
10191
- ]
10192
- }
10193
- })
10194
- }),
10195
- admin
10196
- });
10197
- const bases = options.virtualHosts ?? DEFAULT_VIRTUAL_HOSTS;
10198
- const adminPrefix = (options.adminPrefix ?? "/__admin").replace(/\/+$/, "");
10199
- const fetch2 = runtime.fetch.bind(runtime);
10200
- return Object.assign(runtime, {
10201
- webhooks: hub,
10202
- fetch: (request) => fetch2(toPathStyle(request, bases, adminPrefix))
9789
+ var multipartEtag = (partEtags) => {
9790
+ const bytes = new Uint8Array(partEtags.length * 16);
9791
+ partEtags.forEach((etag, index) => {
9792
+ const clean = etag.replace(/"/g, "");
9793
+ for (let offset = 0; offset < 16; offset++)
9794
+ bytes[index * 16 + offset] = Number.parseInt(clean.slice(offset * 2, offset * 2 + 2), 16);
10203
9795
  });
10204
- };
10205
-
10206
- // src/index.ts
10207
- var S3_NAMESPACE = "s3";
10208
- var S3_MAX_UPLOAD_BYTES = 5 * 1024 ** 3;
10209
- var accessKeyCredential = sigV4AccessKeyId;
10210
- var encoder2 = new TextEncoder();
10211
- var xmlEscape = awsXmlEscape;
10212
- var xml = (body, status = 200, headers = {}) => new Response(body, { status, headers: { "content-type": "application/xml", ...headers } });
10213
- var digest = async (bytes) => `"${awsMd5(bytes)}"`;
10214
- var metadata = (headers) => Object.fromEntries(
10215
- [...headers].filter(([name2]) => name2.startsWith("x-amz-meta-")).map(([name2, value]) => [name2.slice(11), value])
10216
- );
10217
- var HEX = "0123456789ABCDEF";
10218
- var requestId = (random = Math.random) => Array.from({ length: 16 }, () => HEX.charAt(Math.floor(random() * 16))).join("");
10219
- var hex = (bytes) => [...new Uint8Array(bytes instanceof Uint8Array ? bytes : bytes)].map((value) => value.toString(16).padStart(2, "0")).join("");
10220
- var sha256 = async (value) => hex(await crypto.subtle.digest("SHA-256", encoder2.encode(value)));
10221
- var hmac2 = async (key, value) => {
10222
- const imported = await crypto.subtle.importKey(
10223
- "raw",
10224
- key,
10225
- { name: "HMAC", hash: "SHA-256" },
10226
- false,
10227
- ["sign"]
10228
- );
10229
- return new Uint8Array(await crypto.subtle.sign("HMAC", imported, encoder2.encode(value)));
10230
- };
10231
- var RESPONSE_OVERRIDES = [
10232
- ["response-cache-control", "cache-control"],
10233
- ["response-content-disposition", "content-disposition"],
10234
- ["response-content-encoding", "content-encoding"],
10235
- ["response-content-language", "content-language"],
10236
- ["response-content-type", "content-type"],
10237
- ["response-expires", "expires"]
10238
- ];
10239
- var CHECKSUM_HEADER = /^x-amz-checksum-(?!algorithm$|type$)/;
10240
- var hexBytes = (value) => Uint8Array.from([...value.matchAll(/../g)].map((match2) => Number.parseInt(match2[0], 16)));
10241
- var awsEncode = (value) => encodeURIComponent(value).replace(
10242
- /[!'()*]/g,
10243
- (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`
10244
- );
10245
- var S3API = class {
10246
- constructor(options = {}) {
10247
- this.options = options;
10248
- this.sqlite = bootSqlite(options.sqlite);
10249
- this.namespace = options.namespace ?? S3_NAMESPACE;
10250
- this.now = options.now ?? Date.now;
10251
- this.state = new S3State(this.sqlite, this.namespace);
10252
- this.ready = this.seed();
10253
- }
10254
- options;
10255
- state;
10256
- sqlite;
10257
- namespace;
10258
- now;
10259
- ready;
10260
- async seed() {
10261
- for (const bucket of this.options.buckets ?? [])
10262
- if (!this.state.buckets.has(bucket))
10263
- this.state.buckets.insert(bucket, { createdAt: this.now() });
10264
- for (const object of this.options.objects ?? []) await this.putSeed(object);
10265
- }
10266
- async reset() {
10267
- clearNamespace(this.sqlite, this.namespace);
10268
- await this.seed();
10269
- }
10270
- async putSeed(input) {
10271
- if (!this.state.buckets.has(input.bucket))
10272
- this.state.buckets.insert(input.bucket, { createdAt: this.now() });
10273
- const bytes = typeof input.body === "string" ? encoder2.encode(input.body) : input.body;
10274
- const object = {
10275
- bucket: input.bucket,
10276
- key: input.key,
10277
- bytes,
10278
- etag: input.etag ?? await digest(bytes),
10279
- lastModified: input.lastModified ?? this.now(),
10280
- metadata: input.metadata,
10281
- ...input.tags ? { tags: input.tags } : {},
10282
- ...input.checksums ? { checksums: input.checksums } : {},
10283
- ...input.storageClass ? { storageClass: input.storageClass } : {},
10284
- ...input.contentType ? { contentType: input.contentType } : {},
10285
- ...input.cacheControl ? { cacheControl: input.cacheControl } : {},
10286
- ...input.contentDisposition ? { contentDisposition: input.contentDisposition } : {}
10287
- };
10288
- const mode = this.versioning(input.bucket);
10289
- if (mode) {
10290
- const prior = this.state.object(input.bucket, input.key);
10291
- if (prior && !prior.versionId)
10292
- this.state.versions.insert(this.versionKey(input.bucket, input.key, "null"), {
10293
- ...prior,
10294
- versionId: "null"
10295
- });
10296
- object.versionId = mode === "Enabled" ? this.state.ids.next("version-", 24) : "null";
10297
- this.state.versions.insert(this.versionKey(input.bucket, input.key, object.versionId), object);
10298
- }
10299
- this.state.objects.insert(this.state.objectId(input.bucket, input.key), object);
10300
- return object;
10301
- }
10302
- error(code, message, status, resource, extra = {}) {
10303
- const id = requestId(this.options.random);
10304
- const fields = Object.entries(extra).map(([name2, value]) => `<${name2}>${xmlEscape(value)}</${name2}>`).join("");
10305
- return xml(
10306
- `<Error><Code>${code}</Code><Message>${xmlEscape(message)}</Message>${fields}<Resource>${xmlEscape(resource)}</Resource><RequestId>${id}</RequestId><HostId>mockingbird</HostId></Error>`,
10307
- status,
10308
- { "x-amz-request-id": id, "x-amz-id-2": "mockingbird" }
10309
- );
10310
- }
10311
- notify(eventName, object) {
10312
- this.options.onNotification?.({
10313
- eventName,
10314
- bucket: object.bucket,
10315
- key: object.key,
10316
- etag: object.etag,
10317
- size: object.bytes.length,
10318
- occurredAt: new Date(this.now()).toISOString()
10319
- });
10320
- }
10321
- async verifyPresign(request, url, path) {
10322
- if (!url.searchParams.has("X-Amz-Signature")) return;
10323
- const algorithm = url.searchParams.get("X-Amz-Algorithm");
10324
- const credential = url.searchParams.get("X-Amz-Credential") ?? "";
10325
- const signedHeaders = url.searchParams.get("X-Amz-SignedHeaders") ?? "";
10326
- const signature = url.searchParams.get("X-Amz-Signature") ?? "";
10327
- const stamp = url.searchParams.get("X-Amz-Date") ?? "";
10328
- const expires = Number(url.searchParams.get("X-Amz-Expires"));
10329
- const parts = credential.split("/");
10330
- if (algorithm !== "AWS4-HMAC-SHA256" || parts.length !== 5 || parts[3] !== "s3" || parts[4] !== "aws4_request")
10331
- return this.error("AuthorizationQueryParametersError", "Invalid credential scope", 400, path);
10332
- const [accessKey, date, region] = parts;
10333
- const secret = (this.options.credentials ?? { fixture: "fixture" })[accessKey];
10334
- if (!secret) return this.error("AccessDenied", "Invalid access key", 403, path);
10335
- const signedAt = /^\d{8}T\d{6}Z$/.test(stamp) ? Date.UTC(
10336
- Number(stamp.slice(0, 4)),
10337
- Number(stamp.slice(4, 6)) - 1,
10338
- Number(stamp.slice(6, 8)),
10339
- Number(stamp.slice(9, 11)),
10340
- Number(stamp.slice(11, 13)),
10341
- Number(stamp.slice(13, 15))
10342
- ) : Number.NaN;
10343
- if (!Number.isFinite(signedAt) || !Number.isFinite(expires) || expires < 1 || expires > 604800 || !Number.isInteger(expires) || signedAt > this.now() + 9e5 || this.now() > signedAt + expires * 1e3)
10344
- return this.error("AccessDenied", "Request has expired", 403, path);
10345
- const names = signedHeaders.split(";").filter(Boolean);
10346
- if (!names.includes("host"))
10347
- return this.error("SignatureDoesNotMatch", "SignedHeaders must include host", 403, path);
10348
- const canonicalHeaders = names.map(
10349
- (name2) => `${name2}:${name2 === "host" ? url.host : (request.headers.get(name2) ?? "").trim().replace(/\s+/g, " ")}
10350
- `
10351
- ).join("");
10352
- const canonicalQuery = [...url.searchParams].filter(([name2]) => name2 !== "X-Amz-Signature").map(([name2, value]) => `${awsEncode(name2)}=${awsEncode(value)}`).sort().join("&");
10353
- const canonical = [
10354
- request.method,
10355
- path,
10356
- canonicalQuery,
10357
- canonicalHeaders,
10358
- signedHeaders,
10359
- "UNSIGNED-PAYLOAD"
10360
- ].join("\n");
10361
- const scope = `${date}/${region}/s3/aws4_request`;
10362
- const stringToSign = ["AWS4-HMAC-SHA256", stamp, scope, await sha256(canonical)].join("\n");
10363
- let key = await hmac2(encoder2.encode(`AWS4${secret}`), date);
10364
- key = await hmac2(key, region);
10365
- key = await hmac2(key, "s3");
10366
- key = await hmac2(key, "aws4_request");
10367
- if (hex(await hmac2(key, stringToSign)) !== signature.toLowerCase())
10368
- return this.error(
10369
- "SignatureDoesNotMatch",
10370
- "The request signature we calculated does not match the signature you provided",
10371
- 403,
10372
- path
10373
- );
10374
- return void 0;
10375
- }
10376
- objectHeaders(object) {
10377
- const headers = new Headers({
10378
- etag: object.etag,
10379
- "last-modified": new Date(object.lastModified).toUTCString(),
10380
- "content-length": String(object.bytes.length),
10381
- "accept-ranges": "bytes",
10382
- ...object.contentType ? { "content-type": object.contentType } : {},
10383
- ...object.cacheControl ? { "cache-control": object.cacheControl } : {},
10384
- ...object.contentDisposition ? { "content-disposition": object.contentDisposition } : {}
10385
- });
10386
- if (object.versionId) headers.set("x-amz-version-id", object.versionId);
10387
- if (object.storageClass && object.storageClass !== "STANDARD")
10388
- headers.set("x-amz-storage-class", object.storageClass);
10389
- for (const [name2, value] of Object.entries(object.checksums ?? {})) headers.set(name2, value);
10390
- for (const [name2, value] of Object.entries(object.metadata))
10391
- headers.set(`x-amz-meta-${name2}`, value);
10392
- return headers;
10393
- }
10394
- async fetch(input) {
10395
- await this.ready;
10396
- const bases = this.options.virtualHosts ?? DEFAULT_VIRTUAL_HOSTS;
10397
- const request = toPathStyle(input, bases);
10398
- const url = new URL(request.url);
10399
- const slash = url.pathname.indexOf("/", 1);
10400
- const bucket = decodeURIComponent(url.pathname.slice(1, slash < 0 ? void 0 : slash));
10401
- const key = slash < 0 ? "" : decodeURIComponent(url.pathname.slice(slash + 1));
10402
- const signedPath = virtualBucket(url.host, bases) !== void 0 && request.headers.get(VIRTUAL_BUCKET_HEADER) === bucket ? url.pathname.slice(bucket.length + 1) || "/" : url.pathname;
10403
- if (request.method === "OPTIONS" && bucket) return this.preflight(bucket, request, url);
10404
- const response = await this.handle(request, url, bucket, key, signedPath);
10405
- return this.withCors(bucket, request, response);
10406
- }
10407
- async handle(request, url, bucket, key, signedPath) {
10408
- const invalidPresign = await this.verifyPresign(request, url, signedPath);
10409
- if (invalidPresign) return invalidPresign;
10410
- if (!bucket) {
10411
- if (request.method === "GET")
10412
- return xml(
10413
- `<ListAllMyBucketsResult><Owner><ID>000000000000</ID><DisplayName>mockingbird</DisplayName></Owner><Buckets>${this.state.buckets.list().map(
10414
- ({ id, value }) => `<Bucket><Name>${xmlEscape(id)}</Name><CreationDate>${new Date(value.createdAt).toISOString()}</CreationDate></Bucket>`
10415
- ).join("")}</Buckets></ListAllMyBucketsResult>`
10416
- );
10417
- return this.error("InvalidURI", "Could not parse the specified URI", 400, url.pathname);
10418
- }
10419
- const exists = this.state.buckets.has(bucket);
10420
- if (request.method === "PUT" && !key && ![...url.searchParams.keys()].some((name2) => !name2.startsWith("X-Amz-") && name2 !== "x-id")) {
10421
- if (!exists) this.state.buckets.insert(bucket, { createdAt: this.now() });
10422
- return new Response(null, { status: 200, headers: { location: `/${bucket}` } });
10423
- }
10424
- if (!exists)
10425
- return this.error("NoSuchBucket", "The specified bucket does not exist", 404, url.pathname, {
10426
- BucketName: bucket
10427
- });
10428
- if (request.method === "HEAD" && !key)
10429
- return new Response(null, { status: 200, headers: { "x-amz-bucket-region": "us-east-1" } });
10430
- const config = await this.bucketConfiguration(bucket, key, request, url);
10431
- if (config) return config;
10432
- if (request.method === "DELETE" && !key) {
10433
- if (this.state.objects.list({ where: (value) => value.bucket === bucket }).length || this.state.versions.list({ where: (value) => value.bucket === bucket }).length)
10434
- return this.error(
10435
- "BucketNotEmpty",
10436
- "The bucket you tried to delete is not empty",
10437
- 409,
10438
- url.pathname
10439
- );
10440
- this.state.buckets.delete(bucket);
10441
- for (const row of this.state.configurations.list().filter((row2) => row2.id.startsWith(`${bucket}:`)))
10442
- this.state.configurations.delete(row.id);
10443
- return new Response(null, { status: 204 });
10444
- }
10445
- if (request.method === "GET" && !key && url.searchParams.has("versions"))
10446
- return this.listVersions(bucket, url);
10447
- if (request.method === "GET" && !key && url.searchParams.has("uploads"))
10448
- return this.listUploads(bucket, url);
10449
- if (request.method === "GET" && !key) return this.list(bucket, url);
10450
- if (request.method === "POST" && !key && url.searchParams.has("delete"))
10451
- return this.deleteMany(bucket, request);
10452
- if (!key) return this.error("InvalidRequest", "A key is required", 400, url.pathname);
10453
- if (request.method === "POST" && url.searchParams.has("uploads")) {
10454
- const id = this.state.ids.next("upload-", 24);
10455
- this.state.uploads.insert(id, {
10456
- id,
10457
- bucket,
10458
- key,
10459
- initiated: this.now(),
10460
- metadata: metadata(request.headers),
10461
- ...request.headers.get("content-type") ? { contentType: request.headers.get("content-type") } : {},
10462
- ...request.headers.get("cache-control") ? { cacheControl: request.headers.get("cache-control") } : {},
10463
- ...request.headers.get("content-disposition") ? { contentDisposition: request.headers.get("content-disposition") } : {}
10464
- });
10465
- return xml(
10466
- `<InitiateMultipartUploadResult><Bucket>${xmlEscape(bucket)}</Bucket><Key>${xmlEscape(key)}</Key><UploadId>${id}</UploadId></InitiateMultipartUploadResult>`
10467
- );
10468
- }
10469
- if (request.method === "PUT" && url.searchParams.has("uploadId"))
10470
- return this.uploadPart(bucket, key, url, request);
10471
- if (request.method === "POST" && url.searchParams.has("uploadId"))
10472
- return this.complete(bucket, key, url, request);
10473
- if (request.method === "DELETE" && url.searchParams.has("uploadId")) {
10474
- const id = url.searchParams.get("uploadId");
10475
- const upload = this.state.uploads.get(id);
10476
- if (!upload || upload.bucket !== bucket || upload.key !== key)
10477
- return this.error("NoSuchUpload", "The specified upload does not exist", 404, url.pathname);
10478
- this.state.uploads.delete(id);
10479
- for (const part of this.state.parts.list({ where: (value) => value.uploadId === id }))
10480
- this.state.parts.delete(part.id);
10481
- return new Response(null, { status: 204 });
10482
- }
10483
- if (request.method === "GET" && url.searchParams.has("uploadId"))
10484
- return this.listParts(bucket, key, url);
10485
- if (url.searchParams.has("tagging")) return this.objectTagging(bucket, key, request, url);
10486
- if (request.method === "PUT") return this.put(bucket, key, request);
10487
- if (request.method === "DELETE")
10488
- return this.removeObject(bucket, key, url.searchParams.get("versionId"));
10489
- const overrides = RESPONSE_OVERRIDES.filter(([param]) => url.searchParams.has(param));
10490
- if (overrides.length && !request.headers.has("authorization") && !url.searchParams.has("X-Amz-Signature"))
10491
- return this.error(
10492
- "InvalidRequest",
10493
- "Request specific response headers cannot be used for anonymous GET requests.",
10494
- 400,
10495
- url.pathname
10496
- );
10497
- const object = url.searchParams.has("versionId") ? this.state.versions.get(
10498
- this.versionKey(bucket, key, url.searchParams.get("versionId"))
10499
- ) : this.state.object(bucket, key);
10500
- if (!object || object.deleteMarker) {
10501
- const response = this.error(
10502
- url.searchParams.has("versionId") ? "NoSuchVersion" : "NoSuchKey",
10503
- "The specified key does not exist.",
10504
- 404,
10505
- url.pathname
10506
- );
10507
- if (object?.deleteMarker) {
10508
- response.headers.set("x-amz-delete-marker", "true");
10509
- response.headers.set("x-amz-version-id", object.versionId ?? "null");
10510
- }
10511
- return response;
10512
- }
10513
- const condition = this.conditions(object, request);
10514
- if (condition) return condition;
10515
- if (request.method === "HEAD")
10516
- return this.overridden(
10517
- new Response(null, { status: 200, headers: this.objectHeaders(object) }),
10518
- url,
10519
- overrides
10520
- );
10521
- if (request.method === "GET")
10522
- return this.overridden(this.get(object, request, url.pathname), url, overrides);
10523
- return this.error("MethodNotAllowed", "The specified method is not allowed", 405, url.pathname);
10524
- }
10525
- /** `response-*` query parameters replace the stored headers on a 200 or 206. */
10526
- overridden(response, url, overrides) {
10527
- if (response.status === 200 || response.status === 206)
10528
- for (const [param, header] of overrides) {
10529
- const value = url.searchParams.get(param);
10530
- if (value) response.headers.set(header, value);
10531
- }
10532
- return response;
10533
- }
10534
- /**
10535
- * `x-amz-copy-source-if-*`, evaluated as the CopyObject reference describes: a true if-match
10536
- * overrides a false if-unmodified-since, and a failed condition is always 412, never 304.
10537
- */
10538
- copyConditions(source, request) {
10539
- const unquote = (value) => value.trim().replace(/^W\//, "").replace(/^"|"$/g, "");
10540
- const etags = (header) => header === null ? void 0 : header.split(",").map(unquote);
10541
- const have = unquote(source.etag);
10542
- const hit = (list2) => list2?.includes("*") || list2?.includes(have);
10543
- const modified = Math.floor(source.lastModified / 1e3) * 1e3;
10544
- const date = (name2) => Date.parse(request.headers.get(name2) ?? "");
10545
- const ifMatch = etags(request.headers.get("x-amz-copy-source-if-match"));
10546
- const ifNoneMatch = etags(request.headers.get("x-amz-copy-source-if-none-match"));
10547
- const since = date("x-amz-copy-source-if-modified-since");
10548
- const until = date("x-amz-copy-source-if-unmodified-since");
10549
- const failed = (name2) => this.error(
10550
- "PreconditionFailed",
10551
- "At least one of the pre-conditions you specified did not hold",
10552
- 412,
10553
- new URL(request.url).pathname,
10554
- { Condition: name2 }
10555
- );
10556
- if (ifMatch && !hit(ifMatch)) return failed("x-amz-copy-source-If-Match");
10557
- if (!ifMatch && modified > until) return failed("x-amz-copy-source-If-Unmodified-Since");
10558
- if (ifNoneMatch && hit(ifNoneMatch)) return failed("x-amz-copy-source-If-None-Match");
10559
- if (!ifNoneMatch && modified <= since) return failed("x-amz-copy-source-If-Modified-Since");
10560
- return void 0;
10561
- }
10562
- async put(bucket, key, request) {
10563
- const condition = this.conditions(this.state.object(bucket, key), request, true);
10564
- if (condition) return condition;
10565
- const copy2 = request.headers.get("x-amz-copy-source");
10566
- if (copy2) {
10567
- const sourceUrl = new URL(copy2.startsWith("/") ? copy2 : `/${copy2}`, "http://mock");
10568
- const [sourceBucket, ...sourceKey] = sourceUrl.pathname.slice(1).split("/").map(decodeURIComponent);
10569
- const source = sourceBucket ? sourceUrl.searchParams.has("versionId") ? this.state.versions.get(
10570
- this.versionKey(
10571
- sourceBucket,
10572
- sourceKey.join("/"),
10573
- sourceUrl.searchParams.get("versionId")
10574
- )
10575
- ) : this.state.object(sourceBucket, sourceKey.join("/")) : void 0;
10576
- if (!source) return this.error("NoSuchKey", "The specified key does not exist.", 404, copy2);
10577
- const sourceCondition = this.copyConditions(source, request);
10578
- if (sourceCondition) return sourceCondition;
10579
- const stored = await this.putSeed({
10580
- ...source,
10581
- bucket,
10582
- key,
10583
- body: source.bytes,
10584
- metadata: request.headers.get("x-amz-metadata-directive") === "REPLACE" ? metadata(request.headers) : source.metadata,
10585
- lastModified: this.now(),
10586
- ...request.headers.get("x-amz-metadata-directive") === "REPLACE" ? {
10587
- contentType: request.headers.get("content-type") ?? "application/octet-stream",
10588
- cacheControl: request.headers.get("cache-control") ?? "",
10589
- contentDisposition: request.headers.get("content-disposition") ?? ""
10590
- } : {}
10591
- });
10592
- this.notify("ObjectCreated:Copy", stored);
10593
- return xml(
10594
- `<CopyObjectResult><LastModified>${new Date(stored.lastModified).toISOString()}</LastModified><ETag>${stored.etag}</ETag></CopyObjectResult>`
10595
- );
10596
- }
10597
- const received = await this.payload(request);
10598
- if (received instanceof Response) return received;
10599
- const { bytes, checksums } = received;
10600
- const object = await this.putSeed({
10601
- bucket,
10602
- key,
10603
- body: bytes,
10604
- metadata: metadata(request.headers),
10605
- tags: Object.fromEntries(new URLSearchParams(request.headers.get("x-amz-tagging") ?? "")),
10606
- checksums,
10607
- storageClass: request.headers.get("x-amz-storage-class") ?? "STANDARD",
10608
- ...request.headers.get("content-type") ? { contentType: request.headers.get("content-type") } : {},
10609
- ...request.headers.get("cache-control") ? { cacheControl: request.headers.get("cache-control") } : {},
10610
- ...request.headers.get("content-disposition") ? { contentDisposition: request.headers.get("content-disposition") } : {}
10611
- });
10612
- this.notify("ObjectCreated:Put", object);
10613
- return new Response(null, {
10614
- status: 200,
10615
- headers: {
10616
- etag: object.etag,
10617
- ...object.versionId ? { "x-amz-version-id": object.versionId } : {}
10618
- }
10619
- });
10620
- }
10621
- get(object, request, resource) {
10622
- const all = new Uint8Array(object.bytes);
10623
- if (faultEffect(request, "truncate_stream") !== void 0) {
10624
- const bytes2 = all.slice(0, Math.floor(all.length / 2));
10625
- const headers2 = this.objectHeaders(object);
10626
- headers2.set("content-length", String(bytes2.length));
10627
- headers2.set("x-mockingbird-truncated", "true");
10628
- return new Response(bytes2, { status: 200, headers: headers2 });
10629
- }
10630
- const range = request.headers.get("range");
10631
- if (!range) return new Response(all, { status: 200, headers: this.objectHeaders(object) });
10632
- const match2 = /^bytes=(\d*)-(\d*)$/.exec(range);
10633
- if (!match2)
10634
- return this.error("InvalidRange", "The requested range is not satisfiable", 416, resource);
10635
- const start = match2[1] ? Number(match2[1]) : Math.max(0, all.length - Number(match2[2]));
10636
- const end = match2[1] ? Math.min(all.length - 1, match2[2] ? Number(match2[2]) : all.length - 1) : all.length - 1;
10637
- if (start >= all.length || end < start)
10638
- return this.error("InvalidRange", "The requested range is not satisfiable", 416, resource);
10639
- const bytes = all.slice(start, end + 1);
10640
- const headers = this.objectHeaders(object);
10641
- headers.set("content-length", String(bytes.length));
10642
- headers.set("content-range", `bytes ${start}-${end}/${all.length}`);
10643
- for (const name2 of [...headers.keys()])
10644
- if (name2.startsWith("x-amz-checksum-")) headers.delete(name2);
10645
- return new Response(bytes, { status: 206, headers });
10646
- }
10647
- list(bucket, url) {
10648
- const prefix = url.searchParams.get("prefix") ?? "";
10649
- const delimiter = url.searchParams.get("delimiter");
10650
- const max = Number(url.searchParams.get("max-keys") ?? 1e3);
10651
- if (!Number.isInteger(max) || max < 0)
10652
- return this.error("InvalidArgument", "Invalid max-keys", 400, url.pathname);
10653
- const token = url.searchParams.get("continuation-token");
10654
- let after = url.searchParams.get("start-after") ?? url.searchParams.get("marker") ?? "";
10655
- try {
10656
- if (token)
10657
- after = new TextDecoder().decode(Uint8Array.from(atob(token), (char) => char.charCodeAt(0)));
10658
- } catch {
10659
- return this.error("InvalidArgument", "Invalid continuation token", 400, url.pathname);
10660
- }
10661
- const entries = /* @__PURE__ */ new Map();
10662
- for (const { value: object } of this.state.objects.list({
10663
- where: (value) => value.bucket === bucket && !value.deleteMarker && value.key.startsWith(prefix)
10664
- })) {
10665
- const rest = object.key.slice(prefix.length);
10666
- const split = delimiter ? rest.indexOf(delimiter) : -1;
10667
- if (delimiter && split >= 0)
10668
- entries.set(prefix + rest.slice(0, split + delimiter.length), void 0);
10669
- else entries.set(object.key, object);
10670
- }
10671
- const sorted = [...entries].sort(([a], [b]) => this.compareKeys(a, b)).filter(([key]) => this.compareKeys(key, after) > 0);
10672
- const page = sorted.slice(0, Math.min(1e3, max));
10673
- const truncated = max > 0 && sorted.length > page.length;
10674
- const last = page.at(-1)?.[0];
10675
- const encode = (value) => xmlEscape(url.searchParams.get("encoding-type") === "url" ? awsEncode(value) : value);
10676
- const v2 = url.searchParams.get("list-type") === "2";
10677
- return xml(
10678
- `<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>${xmlEscape(bucket)}</Name><Prefix>${encode(prefix)}</Prefix>${delimiter ? `<Delimiter>${encode(delimiter)}</Delimiter>` : ""}${v2 ? `<KeyCount>${page.length}</KeyCount>` : `<Marker>${encode(after)}</Marker>`}<MaxKeys>${Math.min(max, 1e3)}</MaxKeys><IsTruncated>${truncated}</IsTruncated>${url.searchParams.get("encoding-type") === "url" ? "<EncodingType>url</EncodingType>" : ""}${page.map(([key, object]) => object ? `<Contents><Key>${encode(key)}</Key><LastModified>${new Date(object.lastModified).toISOString()}</LastModified><ETag>${xmlEscape(object.etag)}</ETag><Size>${object.bytes.length}</Size><StorageClass>${object.storageClass ?? "STANDARD"}</StorageClass></Contents>` : `<CommonPrefixes><Prefix>${encode(key)}</Prefix></CommonPrefixes>`).join("")}${truncated && last ? v2 ? `<NextContinuationToken>${btoa(String.fromCharCode(...encoder2.encode(last)))}</NextContinuationToken>` : `<NextMarker>${encode(last)}</NextMarker>` : ""}${token ? `<ContinuationToken>${xmlEscape(token)}</ContinuationToken>` : ""}</ListBucketResult>`
10679
- );
10680
- }
10681
- compareKeys(left, right) {
10682
- const a = encoder2.encode(left), b = encoder2.encode(right);
10683
- for (let index = 0; index < Math.min(a.length, b.length); index++) {
10684
- const diff = (a[index] ?? 0) - (b[index] ?? 0);
10685
- if (diff) return diff;
10686
- }
10687
- return a.length - b.length;
10688
- }
10689
- async uploadPart(bucket, key, url, request) {
10690
- const id = url.searchParams.get("uploadId");
10691
- const upload = this.state.uploads.get(id);
10692
- if (!upload || upload.bucket !== bucket || upload.key !== key)
10693
- return this.error("NoSuchUpload", "The specified upload does not exist", 404, url.pathname);
10694
- const partNumber = Number(url.searchParams.get("partNumber"));
10695
- if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 1e4)
10696
- return this.error(
10697
- "InvalidArgument",
10698
- "Part number must be between 1 and 10000",
10699
- 400,
10700
- url.pathname
10701
- );
10702
- const received = await this.payload(request);
10703
- if (received instanceof Response) return received;
10704
- const { bytes } = received;
10705
- const etag = await digest(bytes);
10706
- this.state.parts.insert(`${id}:${partNumber}`, {
10707
- uploadId: id,
10708
- partNumber,
10709
- bytes,
10710
- etag
10711
- });
10712
- return new Response(null, { status: 200, headers: { etag } });
10713
- }
10714
- async complete(bucket, key, url, request) {
10715
- const id = url.searchParams.get("uploadId");
10716
- const upload = this.state.uploads.get(id);
10717
- if (!upload || upload.bucket !== bucket || upload.key !== key)
10718
- return this.error("NoSuchUpload", "The specified upload does not exist", 404, url.pathname);
10719
- let submitted;
10720
- try {
10721
- const parsed = awsParseXml(await request.text()).CompleteMultipartUpload;
10722
- const parts2 = parsed?.Part;
10723
- submitted = Array.isArray(parts2) ? parts2 : parts2 ? [parts2] : [];
10724
- if (!submitted.length) throw new TypeError();
10725
- } catch {
10726
- return this.error(
10727
- "MalformedXML",
10728
- "The XML you provided was not well-formed or did not validate",
10729
- 400,
10730
- url.pathname
10731
- );
10732
- }
10733
- const parts = [];
10734
- let previous = 0;
10735
- for (const entry of submitted) {
10736
- const number = Number(entry.PartNumber);
10737
- if (number <= previous)
10738
- return this.error(
10739
- "InvalidPartOrder",
10740
- "The list of parts was not in ascending order",
10741
- 400,
10742
- url.pathname
10743
- );
10744
- previous = number;
10745
- const part = this.state.parts.get(`${id}:${number}`);
10746
- if (!part || String(entry.ETag).replace(/"/g, "") !== part.etag.replace(/"/g, ""))
10747
- return this.error(
10748
- "InvalidPart",
10749
- "One or more of the specified parts could not be found",
10750
- 400,
10751
- url.pathname
10752
- );
10753
- parts.push(part);
10754
- }
10755
- if (parts.slice(0, -1).some((part) => part.bytes.length < 5 * 1024 * 1024))
10756
- return this.error(
10757
- "EntityTooSmall",
10758
- "Your proposed upload is smaller than the minimum allowed object size",
10759
- 400,
10760
- url.pathname
10761
- );
10762
- const condition = this.conditions(this.state.object(bucket, key), request, true);
10763
- if (condition) return condition;
10764
- const bytes = new Uint8Array(parts.reduce((total, part) => total + part.bytes.length, 0));
10765
- let offset = 0;
10766
- for (const part of parts) {
10767
- bytes.set(part.bytes, offset);
10768
- offset += part.bytes.length;
10769
- }
10770
- const hashes = Uint8Array.from(
10771
- parts.flatMap(
10772
- (part) => [...part.etag.replace(/"/g, "").matchAll(/../g)].map(
10773
- (match2) => Number.parseInt(match2[0], 16)
10774
- )
10775
- )
10776
- );
10777
- const etag = `"${awsMd5(hashes)}-${parts.length}"`;
10778
- const object = await this.putSeed({
10779
- ...upload,
10780
- bucket,
10781
- key,
10782
- body: bytes,
10783
- metadata: upload.metadata ?? {},
10784
- etag
10785
- });
10786
- this.notify("ObjectCreated:CompleteMultipartUpload", object);
10787
- this.state.uploads.delete(id);
10788
- for (const row of this.state.parts.list({ where: (part) => part.uploadId === id }))
10789
- this.state.parts.delete(row.id);
10790
- return xml(
10791
- `<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Location>/${xmlEscape(bucket)}/${xmlEscape(key)}</Location><Bucket>${xmlEscape(bucket)}</Bucket><Key>${xmlEscape(key)}</Key><ETag>${xmlEscape(object.etag)}</ETag></CompleteMultipartUploadResult>`,
10792
- 200,
10793
- object.versionId ? { "x-amz-version-id": object.versionId } : {}
10794
- );
10795
- }
10796
- async deleteMany(bucket, request) {
10797
- let input;
10798
- try {
10799
- input = awsParseXml(await request.text()).Delete;
10800
- if (!input?.Object) throw new TypeError();
10801
- } catch {
10802
- return this.error("MalformedXML", "Malformed XML", 400, `/${bucket}`);
10803
- }
10804
- const entries = Array.isArray(input.Object) ? input.Object : [input.Object];
10805
- if (entries.length > 1e3)
10806
- return this.error("MalformedXML", "Too many objects", 400, `/${bucket}`);
10807
- const quiet = input.Quiet === "true";
10808
- const results = [];
10809
- for (const entry of entries) {
10810
- const key = String(entry.Key ?? "");
10811
- const response = this.removeObject(
10812
- bucket,
10813
- key,
10814
- typeof entry.VersionId === "string" ? entry.VersionId : null
10815
- );
10816
- if (!quiet)
10817
- results.push(
10818
- `<Deleted><Key>${xmlEscape(key)}</Key>${entry.VersionId ? `<VersionId>${xmlEscape(entry.VersionId)}</VersionId>` : ""}${response.headers.get("x-amz-delete-marker") ? `<DeleteMarker>true</DeleteMarker><DeleteMarkerVersionId>${response.headers.get("x-amz-version-id")}</DeleteMarkerVersionId>` : ""}</Deleted>`
10819
- );
10820
- }
10821
- return xml(`<DeleteResult>${results.join("")}</DeleteResult>`);
10822
- }
10823
- versionKey(bucket, key, version) {
10824
- return JSON.stringify([bucket, key, version]);
10825
- }
10826
- versioning(bucket) {
10827
- const body = this.state.configurations.get(`${bucket}:versioning`)?.body ?? "";
10828
- return /<Status>Enabled<\/Status>/.test(body) ? "Enabled" : /<Status>Suspended<\/Status>/.test(body) ? "Suspended" : void 0;
10829
- }
10830
- removeObject(bucket, key, versionId) {
10831
- const headers = {};
10832
- if (versionId !== null) {
10833
- const id = this.versionKey(bucket, key, versionId);
10834
- const prior = this.state.versions.get(id);
10835
- this.state.versions.delete(id);
10836
- headers["x-amz-version-id"] = versionId;
10837
- if (prior?.deleteMarker) headers["x-amz-delete-marker"] = "true";
10838
- if (this.state.object(bucket, key)?.versionId === versionId) {
10839
- const latest = this.state.versions.list({
10840
- where: (value) => value.bucket === bucket && value.key === key,
10841
- order: "newest"
10842
- })[0]?.value;
10843
- if (latest) this.state.objects.insert(this.state.objectId(bucket, key), latest);
10844
- else this.state.objects.delete(this.state.objectId(bucket, key));
10845
- }
10846
- } else if (this.versioning(bucket)) {
10847
- const mode = this.versioning(bucket);
10848
- const id = mode === "Enabled" ? this.state.ids.next("version-", 24) : "null";
10849
- const marker = {
10850
- bucket,
10851
- key,
10852
- bytes: new Uint8Array(),
10853
- etag: "",
10854
- lastModified: this.now(),
10855
- metadata: {},
10856
- versionId: id,
10857
- deleteMarker: true
10858
- };
10859
- this.state.versions.insert(this.versionKey(bucket, key, id), marker);
10860
- this.state.objects.insert(this.state.objectId(bucket, key), marker);
10861
- headers["x-amz-version-id"] = id;
10862
- headers["x-amz-delete-marker"] = "true";
10863
- } else {
10864
- const deleted = this.state.object(bucket, key);
10865
- this.state.objects.delete(this.state.objectId(bucket, key));
10866
- if (deleted) this.notify("ObjectRemoved:Delete", deleted);
10867
- }
10868
- return new Response(null, { status: 204, headers });
10869
- }
10870
- conditions(object, request, write = false) {
10871
- const matches3 = (header) => header !== null && (header === "*" || header.split(",").some((value) => value.trim() === object?.etag));
10872
- const exists = object && !object.deleteMarker;
10873
- if (request.headers.has("if-match") && (!exists || !matches3(request.headers.get("if-match"))))
10874
- return this.error(
10875
- "PreconditionFailed",
10876
- "At least one precondition failed",
10877
- 412,
10878
- new URL(request.url).pathname
10879
- );
10880
- if (exists && matches3(request.headers.get("if-none-match")))
10881
- return write ? this.error(
10882
- "PreconditionFailed",
10883
- "At least one precondition failed",
10884
- 412,
10885
- new URL(request.url).pathname
10886
- ) : new Response(null, { status: 304, headers: this.objectHeaders(object) });
10887
- if (exists && !write) {
10888
- const modified = Math.floor(object.lastModified / 1e3) * 1e3;
10889
- const since = Date.parse(request.headers.get("if-modified-since") ?? "");
10890
- const unmodified = Date.parse(request.headers.get("if-unmodified-since") ?? "");
10891
- if (!request.headers.has("if-none-match") && modified <= since)
10892
- return new Response(null, { status: 304, headers: this.objectHeaders(object) });
10893
- if (!request.headers.has("if-match") && modified > unmodified)
10894
- return this.error(
10895
- "PreconditionFailed",
10896
- "At least one precondition failed",
10897
- 412,
10898
- new URL(request.url).pathname
10899
- );
10900
- }
10901
- return void 0;
10902
- }
10903
- /**
10904
- * The object bytes of a PutObject or UploadPart: an `aws-chunked` stream is decoded (the framing
10905
- * and trailers are not part of the object), the decoded length and every supplied checksum are
10906
- * verified, and the checksums to keep come back as the `x-amz-checksum-*` headers they were.
10907
- */
10908
- async payload(request) {
10909
- const path = new URL(request.url).pathname;
10910
- const chunked = isAwsChunked(request.headers);
10911
- const declared = Number(
10912
- (chunked ? request.headers.get("x-amz-decoded-content-length") : null) ?? request.headers.get("content-length")
10913
- );
10914
- if (declared > S3_MAX_UPLOAD_BYTES)
10915
- return this.error(
10916
- "EntityTooLarge",
10917
- "Your proposed upload exceeds the maximum allowed size",
10918
- 400,
10919
- path,
10920
- { ProposedSize: String(declared), MaxSizeAllowed: String(S3_MAX_UPLOAD_BYTES) }
10921
- );
10922
- let bytes = new Uint8Array(await request.arrayBuffer());
10923
- const checksums = Object.fromEntries(
10924
- [...request.headers].filter(([name2]) => CHECKSUM_HEADER.test(name2))
10925
- );
10926
- if (chunked) {
10927
- const decoded = decodeAwsChunked(bytes);
10928
- if (!decoded)
10929
- return this.error(
10930
- "IncompleteBody",
10931
- "The aws-chunked request body is malformed or ends before its last chunk",
10932
- 400,
10933
- path
10934
- );
10935
- bytes = decoded.payload;
10936
- const length = request.headers.get("x-amz-decoded-content-length");
10937
- if (length !== null && Number(length) !== bytes.length)
10938
- return this.error(
10939
- "IncompleteBody",
10940
- "You did not provide the number of bytes specified by the x-amz-decoded-content-length HTTP header",
10941
- 400,
10942
- path
10943
- );
10944
- for (const [name2, value] of Object.entries(decoded.trailers))
10945
- if (CHECKSUM_HEADER.test(name2)) checksums[name2] = value;
10946
- }
10947
- const md5 = request.headers.get("content-md5");
10948
- if (md5 && md5 !== btoa(String.fromCharCode(...hexBytes(awsMd5(bytes)))))
10949
- return this.error(
10950
- "BadDigest",
10951
- "The Content-MD5 you specified did not match what we received",
10952
- 400,
10953
- path
10954
- );
10955
- for (const [name2, expected] of Object.entries(checksums)) {
10956
- const algorithm = name2.slice("x-amz-checksum-".length);
10957
- if (CHECKSUM_ALGORITHMS.includes(algorithm) && await checksum(algorithm, bytes) !== expected)
10958
- return this.error(
10959
- "BadDigest",
10960
- `The ${algorithm.toUpperCase()} you specified did not match the calculated checksum.`,
10961
- 400,
10962
- path
10963
- );
10964
- }
10965
- return { bytes, checksums };
10966
- }
10967
- async bucketConfiguration(bucket, key, request, url) {
10968
- if (key) return void 0;
10969
- if (url.searchParams.has("location") && request.method === "GET")
10970
- return xml('<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>');
10971
- const kinds = {
10972
- versioning: ["VersioningConfiguration", ""],
10973
- tagging: ["Tagging", "NoSuchTagSet"],
10974
- cors: ["CORSConfiguration", "NoSuchCORSConfiguration"],
10975
- lifecycle: ["LifecycleConfiguration", "NoSuchLifecycleConfiguration"],
10976
- notification: ["NotificationConfiguration", ""],
10977
- encryption: [
10978
- "ServerSideEncryptionConfiguration",
10979
- "ServerSideEncryptionConfigurationNotFoundError"
10980
- ],
10981
- website: ["WebsiteConfiguration", "NoSuchWebsiteConfiguration"],
10982
- publicAccessBlock: ["PublicAccessBlockConfiguration", "NoSuchPublicAccessBlockConfiguration"],
10983
- ownershipControls: ["OwnershipControls", "OwnershipControlsNotFoundError"],
10984
- policy: ["", "NoSuchBucketPolicy"]
10985
- };
10986
- const kind = Object.keys(kinds).find((name2) => url.searchParams.has(name2));
10987
- if (!kind) return void 0;
10988
- const [root, missing] = kinds[kind];
10989
- const id = `${bucket}:${kind}`;
10990
- if (request.method === "PUT") {
10991
- const body = await request.text();
10992
- try {
10993
- if (kind === "policy") JSON.parse(body);
10994
- else if (!(root in awsParseXml(body))) throw new TypeError();
10995
- } catch {
10996
- return this.error(
10997
- kind === "policy" ? "MalformedPolicy" : "MalformedXML",
10998
- "Malformed configuration",
10999
- 400,
11000
- url.pathname
11001
- );
11002
- }
11003
- if (kind === "versioning" && !/<Status>(Enabled|Suspended)<\/Status>/.test(body))
11004
- return this.error("MalformedXML", "Invalid versioning status", 400, url.pathname);
11005
- if (kind === "cors") {
11006
- const invalid = invalidCors(parseCors(body));
11007
- if (invalid) return this.error(invalid[0], invalid[1], 400, url.pathname);
11008
- }
11009
- this.state.configurations.insert(id, { body });
11010
- return new Response(null, { status: 200 });
11011
- }
11012
- if (request.method === "DELETE") {
11013
- this.state.configurations.delete(id);
11014
- return new Response(null, { status: 204 });
11015
- }
11016
- if (request.method === "GET") {
11017
- const stored = this.state.configurations.get(id);
11018
- if (stored)
11019
- return new Response(stored.body, {
11020
- headers: { "content-type": kind === "policy" ? "application/json" : "application/xml" }
11021
- });
11022
- return missing ? this.error(missing, "The configuration does not exist", 404, url.pathname) : xml(`<${root} xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`);
11023
- }
11024
- return this.error("MethodNotAllowed", "Method not allowed", 405, url.pathname);
11025
- }
11026
- corsRules(bucket) {
11027
- const stored = this.state.configurations.get(`${bucket}:cors`);
11028
- return stored ? parseCors(stored.body) : void 0;
11029
- }
11030
- /**
11031
- * The browser preflight (`OPTIONS` on a bucket or object URL). S3 refuses one it cannot match
11032
- * with 403 AccessForbidden "CORSResponse: ..." and no `Access-Control-*` headers.
11033
- */
11034
- preflight(bucket, request, url) {
11035
- if (!this.state.buckets.has(bucket))
11036
- return this.error("NoSuchBucket", "The specified bucket does not exist", 404, url.pathname, {
11037
- BucketName: bucket
11038
- });
11039
- const origin = request.headers.get("origin");
11040
- if (!origin)
11041
- return this.error(
11042
- "BadRequest",
11043
- "Insufficient information. Origin request header needed.",
11044
- 400,
11045
- url.pathname
11046
- );
11047
- const method = request.headers.get("access-control-request-method");
11048
- if (!method || !CORS_METHODS.includes(method))
11049
- return this.error(
11050
- "BadRequest",
11051
- `Invalid Access-Control-Request-Method: ${method}`,
11052
- 400,
11053
- url.pathname
11054
- );
11055
- const requested = (request.headers.get("access-control-request-headers") ?? "").split(",").map((name2) => name2.trim().toLowerCase()).filter(Boolean);
11056
- const rules = this.corsRules(bucket);
11057
- const refuse = (message) => this.error("AccessForbidden", `CORSResponse: ${message}`, 403, url.pathname, {
11058
- Method: method,
11059
- ResourceType: url.pathname.indexOf("/", 1) < 0 ? "BUCKET" : "OBJECT"
11060
- });
11061
- if (!rules) return refuse("CORS is not enabled for this bucket.");
11062
- const rule = matchRule(rules, origin, method, requested);
11063
- if (!rule)
11064
- return refuse(
11065
- "This CORS request is not allowed. This is usually because the evalution of Origin, request method / Access-Control-Request-Method or Access-Control-Request-Headers are not whitelisted by the resource's CORS spec."
11066
- );
11067
- return new Response(null, {
11068
- status: 200,
11069
- headers: {
11070
- ...corsHeaders(rule, origin),
11071
- ...requested.length ? { "access-control-allow-headers": requested.join(", ") } : {},
11072
- ...rule.maxAge ? { "access-control-max-age": rule.maxAge } : {},
11073
- vary: PREFLIGHT_VARY
11074
- }
11075
- });
11076
- }
11077
- /** A matching rule adds the `Access-Control-*` headers to an actual cross-origin response. */
11078
- withCors(bucket, request, response) {
11079
- const origin = request.headers.get("origin");
11080
- if (!origin || !bucket || !this.state.buckets.has(bucket)) return response;
11081
- const rule = matchRule(this.corsRules(bucket) ?? [], origin, request.method);
11082
- if (!rule) return response;
11083
- for (const [name2, value] of Object.entries(corsHeaders(rule, origin)))
11084
- response.headers.set(name2, value);
11085
- response.headers.append("vary", "Origin");
11086
- return response;
11087
- }
11088
- async objectTagging(bucket, key, request, url) {
11089
- const object = url.searchParams.has("versionId") ? this.state.versions.get(
11090
- this.versionKey(bucket, key, url.searchParams.get("versionId"))
11091
- ) : this.state.object(bucket, key);
11092
- if (!object || object.deleteMarker)
11093
- return this.error("NoSuchKey", "The specified key does not exist", 404, url.pathname);
11094
- if (request.method === "GET")
11095
- return xml(
11096
- `<Tagging><TagSet>${Object.entries(object.tags ?? {}).map(
11097
- ([name2, value]) => `<Tag><Key>${xmlEscape(name2)}</Key><Value>${xmlEscape(value)}</Value></Tag>`
11098
- ).join("")}</TagSet></Tagging>`
11099
- );
11100
- let tags = {};
11101
- if (request.method === "PUT") {
11102
- try {
11103
- const tagging = awsParseXml(await request.text()).Tagging;
11104
- const value = tagging?.TagSet?.Tag;
11105
- const list2 = Array.isArray(value) ? value : value ? [value] : [];
11106
- if (list2.length > 10 || list2.some((tag) => typeof tag.Key !== "string" || typeof tag.Value !== "string") || new Set(list2.map((tag) => tag.Key)).size !== list2.length)
11107
- throw new TypeError();
11108
- tags = Object.fromEntries(list2.map((tag) => [tag.Key, tag.Value]));
11109
- } catch {
11110
- return this.error("MalformedXML", "Invalid tag set", 400, url.pathname);
11111
- }
11112
- } else if (request.method !== "DELETE")
11113
- return this.error("MethodNotAllowed", "Method not allowed", 405, url.pathname);
11114
- const updated = { ...object, tags };
11115
- if (object.versionId)
11116
- this.state.versions.insert(this.versionKey(bucket, key, object.versionId), updated);
11117
- if (this.state.object(bucket, key)?.versionId === object.versionId)
11118
- this.state.objects.insert(this.state.objectId(bucket, key), updated);
11119
- return new Response(null, { status: request.method === "DELETE" ? 204 : 200 });
11120
- }
11121
- listParts(bucket, key, url) {
11122
- const id = url.searchParams.get("uploadId");
11123
- const upload = this.state.uploads.get(id);
11124
- if (!upload || upload.bucket !== bucket || upload.key !== key)
11125
- return this.error("NoSuchUpload", "The specified upload does not exist", 404, url.pathname);
11126
- const marker = Number(url.searchParams.get("part-number-marker") ?? 0);
11127
- const max = Math.min(1e3, Number(url.searchParams.get("max-parts") ?? 1e3));
11128
- if (!Number.isInteger(max) || max < 0 || !Number.isInteger(marker) || marker < 0)
11129
- return this.error("InvalidArgument", "Invalid pagination", 400, url.pathname);
11130
- const all = this.state.parts.list({ where: (part) => part.uploadId === id && part.partNumber > marker }).map(({ value }) => value).sort((a, b) => a.partNumber - b.partNumber);
11131
- const page = all.slice(0, max);
11132
- return xml(
11133
- `<ListPartsResult><Bucket>${xmlEscape(bucket)}</Bucket><Key>${xmlEscape(key)}</Key><UploadId>${xmlEscape(id)}</UploadId><PartNumberMarker>${marker}</PartNumberMarker><NextPartNumberMarker>${page.at(-1)?.partNumber ?? marker}</NextPartNumberMarker><MaxParts>${max}</MaxParts><IsTruncated>${all.length > page.length}</IsTruncated>${page.map((part) => `<Part><PartNumber>${part.partNumber}</PartNumber><ETag>${xmlEscape(part.etag)}</ETag><Size>${part.bytes.length}</Size><LastModified>${new Date(upload.initiated).toISOString()}</LastModified></Part>`).join("")}</ListPartsResult>`
11134
- );
11135
- }
11136
- listUploads(bucket, url) {
11137
- const uploads = this.state.uploads.list({
11138
- where: (value) => value.bucket === bucket && value.key.startsWith(url.searchParams.get("prefix") ?? "")
11139
- }).map(({ value }) => value);
11140
- return xml(
11141
- `<ListMultipartUploadsResult><Bucket>${xmlEscape(bucket)}</Bucket><IsTruncated>false</IsTruncated>${uploads.map((upload) => `<Upload><Key>${xmlEscape(upload.key)}</Key><UploadId>${upload.id}</UploadId><Initiated>${new Date(upload.initiated).toISOString()}</Initiated><StorageClass>STANDARD</StorageClass></Upload>`).join("")}</ListMultipartUploadsResult>`
11142
- );
11143
- }
11144
- listVersions(bucket, url) {
11145
- const versions = this.state.versions.list({
11146
- where: (value) => value.bucket === bucket && value.key.startsWith(url.searchParams.get("prefix") ?? ""),
11147
- order: "newest"
11148
- }).map(({ value }) => value);
11149
- return xml(
11150
- `<ListVersionsResult><Name>${xmlEscape(bucket)}</Name><Prefix>${xmlEscape(url.searchParams.get("prefix") ?? "")}</Prefix><IsTruncated>false</IsTruncated>${versions.map((object) => {
11151
- const type = object.deleteMarker ? "DeleteMarker" : "Version";
11152
- return `<${type}><Key>${xmlEscape(object.key)}</Key><VersionId>${object.versionId}</VersionId><IsLatest>${this.state.object(bucket, object.key)?.versionId === object.versionId}</IsLatest><LastModified>${new Date(object.lastModified).toISOString()}</LastModified>${object.deleteMarker ? "" : `<ETag>${xmlEscape(object.etag)}</ETag><Size>${object.bytes.length}</Size><StorageClass>${object.storageClass ?? "STANDARD"}</StorageClass>`}</${type}>`;
11153
- }).join("")}</ListVersionsResult>`
11154
- );
11155
- }
9796
+ return `${awsMd5(bytes)}-${partEtags.length}`;
11156
9797
  };
11157
9798
 
11158
9799
  export {
9800
+ clearNamespace,
9801
+ awsParseXml,
9802
+ Collection,
11159
9803
  normalizeIdBase,
9804
+ IdSequence,
9805
+ bootSqlite,
11160
9806
  createClock,
11161
9807
  restoreClock,
11162
9808
  parseDuration,
@@ -11164,15 +9810,14 @@ export {
11164
9810
  normalizeBootControls,
11165
9811
  parseFaultHeader,
11166
9812
  resolveAdminPrefix,
9813
+ sigV4AccessKeyId,
11167
9814
  ownedTransport,
11168
- document,
11169
- operationIds,
11170
- supportedOperationIds,
11171
- S3_PRESETS,
11172
- createRuntime2 as createRuntime,
11173
- S3_NAMESPACE,
11174
- S3_MAX_UPLOAD_BYTES,
11175
- accessKeyCredential,
11176
- S3API
11177
- };
11178
- //# sourceMappingURL=chunk-5QCRU4MS.js.map
9815
+ signers,
9816
+ createWebhookHub,
9817
+ faultEffect,
9818
+ createRuntime,
9819
+ md5Hex,
9820
+ md5Base64,
9821
+ multipartEtag
9822
+ };
9823
+ //# sourceMappingURL=chunk-OLJWFVFY.js.map