@nextlyhq/storage-s3 0.0.2-alpha.77 → 0.0.2-alpha.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -101,7 +101,7 @@ s3Storage({
101
101
  });
102
102
  ```
103
103
 
104
- With `clientUploads`, the browser asks for a pre-signed URL with the file's name, type and exact size. Nextly checks them first (name, extension, type allowlist, size; never an SVG), and the URL binds the type and the exact size, so S3 refuses any other file. The bytes themselves don't pass through Nextly, so their content is not checked.
104
+ With `clientUploads`, the browser asks for a pre-signed URL with the file's name, type and exact size. Nextly checks them first (name, extension, type allowlist, size; never an SVG), and the URL binds the type and the exact size, so S3 refuses any other file. It binds the configured `cacheControl` too, so a direct upload is cached as a server upload is: send every header in the response's `headers`, as it is (a bucket CORS rule that lists its allowed headers must allow `content-type` and `cache-control`). The bytes themselves don't pass through Nextly, so their content is not checked.
105
105
 
106
106
  ## Main exports
107
107
 
package/dist/index.cjs CHANGED
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
3
3
  let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
4
4
  let _aws_sdk_s3_request_presigner = require("@aws-sdk/s3-request-presigner");
5
- // ../nextly/dist/nextly-error-C_MDZmJc.mjs
5
+ // ../nextly/dist/nextly-error-jIKkC0DY.mjs
6
6
  function isDbError(err) {
7
7
  if (!err || typeof err !== "object") return false;
8
8
  const obj = err;
@@ -92,6 +92,8 @@ const NEXTLY_ERROR_STATUS = {
92
92
  PAYLOAD_TOO_LARGE: 413,
93
93
  UNSUPPORTED_MEDIA_TYPE: 415,
94
94
  BUSINESS_RULE_VIOLATION: 422,
95
+ WORKFLOW_STEP_NOT_SUBMIT: 400,
96
+ WORKFLOW_NO_SUBMIT_STEP: 409,
95
97
  INTERNAL_ERROR: 500,
96
98
  DATABASE_ERROR: 500,
97
99
  DATABASE_BUSY: 503,
@@ -125,10 +127,13 @@ const NEXTLY_ERROR_STATUS = {
125
127
  NEXTLY_DATABASE_NOT_SET_UP: 503,
126
128
  NEXTLY_DATABASE_NOT_MIGRATED: 503,
127
129
  NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
130
+ NEXTLY_CORE_UPGRADE_UNSUPPORTED: 409,
131
+ NEXTLY_CORE_UPGRADE_INCOMPLETE: 500,
128
132
  NEXTLY_MIGRATION_DRIFT: 409,
129
133
  NEXTLY_MIGRATION_APPLY_FAILED: 500,
130
134
  NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
131
135
  NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
136
+ NEXTLY_MIGRATION_NOT_PROVEN: 409,
132
137
  NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
133
138
  NEXTLY_MIGRATION_FILE_MISSING: 404,
134
139
  NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
@@ -179,6 +184,9 @@ const NEXTLY_ERROR_STATUS = {
179
184
  NEXTLY_PER_LANGUAGE_STORAGE_CHANGED: 500,
180
185
  NEXTLY_PER_LANGUAGE_STORAGE_MIXED: 500,
181
186
  NEXTLY_PER_LANGUAGE_STORAGE_LANGUAGES_UNDECLARED: 500,
187
+ NEXTLY_LANGUAGE_CODES_COLLIDE: 500,
188
+ NEXTLY_LANGUAGE_CODES_NOT_UPGRADED: 500,
189
+ NEXTLY_UPGRADE_LOCALISATION_UNRESOLVED: 500,
182
190
  NEXTLY_POSTGRES_SCHEMA_MOVED: 500
183
191
  };
184
192
  ({ ...Object.fromEntries([
@@ -569,6 +577,37 @@ var NextlyError = class NextlyError extends Error {
569
577
  });
570
578
  }
571
579
  /**
580
+ * A submit for review naming a step that does not submit: an approval, a
581
+ * request for changes or a move. Its own code, so a caller that may only
582
+ * submit is told this is not a step it can take this way, never the refusal
583
+ * the step itself would meet. Names the step, the caller's own word.
584
+ */
585
+ static stepNotSubmit(opts) {
586
+ return new NextlyError({
587
+ code: "WORKFLOW_STEP_NOT_SUBMIT",
588
+ publicMessage: "That step does not submit for review.",
589
+ publicData: { step: opts.step },
590
+ logContext: opts.logContext
591
+ });
592
+ }
593
+ /**
594
+ * A submit for review naming no step, of a part whose stage no submit step
595
+ * leaves: content already in review, or a workflow that enters review by
596
+ * another kind of step. Names the part and its stage, which a read of the
597
+ * document tells the caller anyway.
598
+ */
599
+ static noSubmitStep(opts) {
600
+ return new NextlyError({
601
+ code: "WORKFLOW_NO_SUBMIT_STEP",
602
+ publicMessage: "No step submits this content for review from the stage it is in.",
603
+ publicData: {
604
+ part: opts.part,
605
+ stage: opts.stage
606
+ },
607
+ logContext: opts.logContext
608
+ });
609
+ }
610
+ /**
572
611
  * An API key refused because its role allows more than the person creating
573
612
  * it may do. The sentence is FORBIDDEN's and names no permission; which one
574
613
  * exceeded goes to the log through `logContext`. The code is its own, so a
@@ -878,7 +917,7 @@ var NextlyError = class NextlyError extends Error {
878
917
  return NextlyError.isCode(err, "RATE_LIMITED");
879
918
  }
880
919
  };
881
- // ../nextly/dist/validate-external-url-DF_HNT6F.mjs
920
+ // ../nextly/dist/validate-external-url-ZJNqaKd2.mjs
882
921
  /** Default response body cap: reject anything larger before buffering it all. */
883
922
  /**
884
923
  * How many bytes a bounded external read may buffer, absent a caller's own cap.
@@ -968,6 +1007,63 @@ function resolveReadBounds(options) {
968
1007
  timeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS
969
1008
  };
970
1009
  }
1010
+ // src/storage-key.ts
1011
+ /**
1012
+ * The key a new file is stored under in the bucket.
1013
+ *
1014
+ * One definition for both ways a file arrives: a server upload
1015
+ * (`S3StorageAdapter.upload`, given the collection's prefix as `folder`) and a
1016
+ * direct browser upload (the plugin's `getClientUploadUrl`, which builds the
1017
+ * key before signing it), so the two cannot disagree about the slash after
1018
+ * the prefix and store one collection's files in two places.
1019
+ *
1020
+ * @module storage-key
1021
+ */
1022
+ /**
1023
+ * Sanitize a filename to prevent directory traversal and S3 key issues.
1024
+ *
1025
+ * Keeps only the basename, and replaces every character outside
1026
+ * `a-z A-Z 0-9 . _ -` with a hyphen.
1027
+ *
1028
+ * @param filename - Original filename
1029
+ * @returns Sanitized filename safe for S3 keys
1030
+ */
1031
+ function sanitizeFilename(filename) {
1032
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1033
+ }
1034
+ /**
1035
+ * The folder without its trailing slashes, so `"proofs"` and `"proofs/"` name
1036
+ * the same folder and a folder of only slashes names none.
1037
+ *
1038
+ * Trimmed by a loop rather than a pattern: the value is configuration, and a
1039
+ * loop has no backtracking for a long run of slashes to exploit.
1040
+ */
1041
+ function folderName(folder) {
1042
+ if (!folder) return "";
1043
+ let end = folder.length;
1044
+ while (end > 0 && folder[end - 1] === "/") end--;
1045
+ return folder.slice(0, end);
1046
+ }
1047
+ /**
1048
+ * Generate a unique storage key with a date-based layout.
1049
+ *
1050
+ * Creates keys in the format `{folder}/{year}/{month}/{uuid}-{sanitized-filename}`,
1051
+ * or `{year}/{month}/{uuid}-{sanitized-filename}` with no folder. The folder
1052
+ * may be written with or without a trailing slash; the key has exactly one.
1053
+ *
1054
+ * @param filename - Original filename (will be sanitized)
1055
+ * @param folder - Optional folder/prefix for organizing uploads
1056
+ * @returns Generated storage key
1057
+ */
1058
+ function generateStorageKey(filename, folder) {
1059
+ const sanitized = sanitizeFilename(filename);
1060
+ const uuid = crypto.randomUUID();
1061
+ const date = /* @__PURE__ */ new Date();
1062
+ const year = date.getFullYear();
1063
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1064
+ const name = folderName(folder);
1065
+ return `${name ? `${name}/${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1066
+ }
971
1067
  // src/adapter.ts
972
1068
  /**
973
1069
  * S3 Storage Adapter
@@ -1139,7 +1235,7 @@ var S3StorageAdapter = class {
1139
1235
  */
1140
1236
  async upload(buffer, options) {
1141
1237
  const client = this.ensureClient();
1142
- const key = this.generateKey(options.filename, options.folder);
1238
+ const key = generateStorageKey(options.filename, options.folder);
1143
1239
  const uploadParams = {
1144
1240
  Bucket: this.resolvedConfig.bucket,
1145
1241
  Key: key,
@@ -1150,7 +1246,7 @@ var S3StorageAdapter = class {
1150
1246
  if (!this.isR2) uploadParams.ACL = this.resolvedConfig.acl;
1151
1247
  const disposition = options.contentDisposition ?? this.resolvedConfig.contentDisposition;
1152
1248
  if (disposition) {
1153
- const filename = this.sanitizeFilename(options.filename);
1249
+ const filename = sanitizeFilename(options.filename);
1154
1250
  uploadParams.ContentDisposition = disposition === "attachment" ? `attachment; filename="${filename}"` : "inline";
1155
1251
  }
1156
1252
  uploadParams.Metadata = { "original-filename": options.filename };
@@ -1164,6 +1260,32 @@ var S3StorageAdapter = class {
1164
1260
  };
1165
1261
  }
1166
1262
  /**
1263
+ * Write bytes at exactly `filePath`, beside a file already in the bucket.
1264
+ *
1265
+ * Core uses it to keep a file made from a stored one, such as a resized
1266
+ * copy of an image, under a key derived from the original's. One request,
1267
+ * since such a file is small, with the same cache setting and access as an
1268
+ * upload, so it is served the way its original is.
1269
+ *
1270
+ * @experimental
1271
+ */
1272
+ async uploadAt(filePath, buffer, options) {
1273
+ const client = this.ensureClient();
1274
+ const params = {
1275
+ Bucket: this.resolvedConfig.bucket,
1276
+ Key: filePath,
1277
+ Body: buffer,
1278
+ ContentType: options.mimeType,
1279
+ CacheControl: this.resolvedConfig.cacheControl
1280
+ };
1281
+ if (!this.isR2) params.ACL = this.resolvedConfig.acl;
1282
+ await client.send(new _aws_sdk_client_s3.PutObjectCommand(params));
1283
+ return {
1284
+ url: this.getPublicUrl(filePath),
1285
+ path: filePath
1286
+ };
1287
+ }
1288
+ /**
1167
1289
  * Delete file from S3.
1168
1290
  *
1169
1291
  * @param filePath - Storage path/key to delete
@@ -1401,6 +1523,12 @@ var S3StorageAdapter = class {
1401
1523
  * itself refuses a body of another type or length. The browser sets the
1402
1524
  * length from the body; it is not a header the client sends.
1403
1525
  *
1526
+ * It covers the configured `Cache-Control` too, which is returned in
1527
+ * `headers`: S3 stores an object's Cache-Control only from the upload
1528
+ * request's own header, so a browser upload is served with the same caching
1529
+ * as a server one only when the client sends it. The client must send every
1530
+ * header in `headers`, as it is; one left out fails the signature.
1531
+ *
1404
1532
  * @param key - Storage path/key for the upload
1405
1533
  * @param mimeType - MIME type of the file being uploaded
1406
1534
  * @param expiresIn - URL validity in seconds, at most the configured
@@ -1424,41 +1552,22 @@ var S3StorageAdapter = class {
1424
1552
  return {
1425
1553
  uploadUrl: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, command, {
1426
1554
  expiresIn: expiration,
1427
- signableHeaders: /* @__PURE__ */ new Set(["content-type", "content-length"])
1555
+ signableHeaders: /* @__PURE__ */ new Set([
1556
+ "content-type",
1557
+ "content-length",
1558
+ "cache-control"
1559
+ ])
1428
1560
  }),
1429
1561
  path: key,
1430
1562
  method: "PUT",
1431
- headers: { "Content-Type": mimeType },
1563
+ headers: {
1564
+ "Content-Type": mimeType,
1565
+ "Cache-Control": this.resolvedConfig.cacheControl
1566
+ },
1432
1567
  expiresAt: new Date(Date.now() + expiration * 1e3)
1433
1568
  };
1434
1569
  }
1435
1570
  /**
1436
- * Generate a unique storage key with date-based prefix.
1437
- *
1438
- * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}
1439
- *
1440
- * @param filename - Original filename (will be sanitized)
1441
- * @param folder - Optional folder/prefix for organizing uploads
1442
- * @returns Generated storage key
1443
- */
1444
- generateKey(filename, folder) {
1445
- const sanitized = this.sanitizeFilename(filename);
1446
- const uuid = crypto.randomUUID();
1447
- const date = /* @__PURE__ */ new Date();
1448
- const year = date.getFullYear();
1449
- const month = String(date.getMonth() + 1).padStart(2, "0");
1450
- return `${folder ? `${folder}/${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1451
- }
1452
- /**
1453
- * Sanitize filename to prevent directory traversal and S3 key issues.
1454
- *
1455
- * @param filename - Original filename
1456
- * @returns Sanitized filename safe for S3 keys
1457
- */
1458
- sanitizeFilename(filename) {
1459
- return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1460
- }
1461
- /**
1462
1571
  * Check if an error is a "not found" error from S3.
1463
1572
  *
1464
1573
  * @param error - Error to check
@@ -1615,36 +1724,6 @@ function s3Storage(config) {
1615
1724
  }
1616
1725
  };
1617
1726
  }
1618
- /**
1619
- * Generate a unique storage key with date-based prefix.
1620
- *
1621
- * Creates keys in format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}
1622
- * This matches the format used by S3StorageAdapter for consistency.
1623
- *
1624
- * @param filename - Original filename (will be sanitized)
1625
- * @param prefix - Optional folder/prefix for organizing uploads
1626
- * @returns Generated storage key
1627
- */
1628
- function generateStorageKey(filename, prefix) {
1629
- const sanitized = sanitizeFilename(filename);
1630
- const uuid = crypto.randomUUID();
1631
- const date = /* @__PURE__ */ new Date();
1632
- const year = date.getFullYear();
1633
- const month = String(date.getMonth() + 1).padStart(2, "0");
1634
- return `${prefix ? `${prefix}${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1635
- }
1636
- /**
1637
- * Sanitize filename to prevent directory traversal and S3 key issues.
1638
- *
1639
- * Removes path separators and replaces unsafe characters with hyphens.
1640
- * Keeps only: a-z, A-Z, 0-9, dot, underscore, hyphen
1641
- *
1642
- * @param filename - Original filename
1643
- * @returns Sanitized filename safe for S3 keys
1644
- */
1645
- function sanitizeFilename(filename) {
1646
- return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1647
- }
1648
1727
  // src/index.ts
1649
1728
  const PACKAGE_NAME = "@nextly/storage-s3";
1650
1729
  const PACKAGE_VERSION = "0.1.0";