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