@venizia/ignis-helpers 0.4.8-5 → 0.4.8-6

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.
@@ -26,6 +26,7 @@ export type { IBuildOptions, IHeightWhereOptions, ILeavesOptions, INodeWithPath,
26
26
  export { TreeWalker } from './modules/tree/walk.js';
27
27
  export { BuildInfoRegistry } from './utilities/build-info.utility.js';
28
28
  export type { IBuildInfo, TBuildInfoRecord } from './utilities/build-info.utility.js';
29
+ export { EchoUtility } from './utilities/echo.utility.js';
29
30
  export { ParseUtility } from './utilities/parse.utility.js';
30
31
  export { PerformanceUtility } from './utilities/performance.utility.js';
31
32
  export { PromiseUtility } from './utilities/promise.utility.js';
package/dist/esm/core.js CHANGED
@@ -33,6 +33,7 @@ export { TreeWalker } from './modules/tree/walk.js';
33
33
  // cannot itself become a subpath. Named one at a time here instead of widening the barrel: every
34
34
  // symbol below is verified free of node builtins/globals.
35
35
  export { BuildInfoRegistry } from './utilities/build-info.utility.js';
36
+ export { EchoUtility } from './utilities/echo.utility.js';
36
37
  export { ParseUtility } from './utilities/parse.utility.js';
37
38
  export { PerformanceUtility } from './utilities/performance.utility.js';
38
39
  export { PromiseUtility } from './utilities/promise.utility.js';
@@ -1 +1 @@
1
- {"version":3,"file":"core.js","sourceRoot":"","sources":["../../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,6FAA6F;AAC7F,8DAA8D;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AAE1D,6HAA6H;AAC7H,iHAAiH;AACjH,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,cAAc,qDAAqD,CAAC;AACpE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AAE,aAAa,EAAE,MAAM,2CAA2C,CAAC","sourcesContent":["export { BaseHelper } from './modules/base';\n// By name, never `export *` from `./modules/env`: that barrel also carries `Environment` and\n// `applicationEnvironment`, both of which read `process.env`.\nexport { EnvironmentNames } from './modules/env/names';\nexport * from './modules/error';\nexport { LogLevels } from './modules/logger/common/types';\nexport type { ILogger, ILoggerProvider, TLogLevel } from './modules/logger/common/types';\n// The one way to get a logger, the same in the browser and on the server: `LoggerFactory` imports nothing from node, and its\n// default provider is the console. An application chooses another with `LoggerFactory.use({ provider, level })`.\nexport { ConsoleLogger } from './modules/logger/base/console';\nexport { LoggerFactory } from './modules/logger/factory';\nexport * from './modules/network/http-request/fetcher/base-fetcher';\n// The node fetcher carries no node builtin - its one `querystring.stringify` is written out - so the\n// framework HTTP layer is reachable from a browser bundle, and a connector on HTTP need not\n// re-implement one.\nexport * from './modules/network/http-request/fetcher/node-fetcher';\nexport * from './modules/network/http-request/base-network-request.helper';\nexport * from './modules/pool';\nexport * from './modules/queue/internal/hf';\nexport * from './modules/temporal';\nexport * from './modules/uid';\n// The url guard, pure half only: `UrlPolicy` decides a url and a literal address with string and\n// number work. Its sibling `UrlIngest` reaches `node:dns` and stays out of this subpath.\nexport * from './modules/network/utilities/url-safety/common/constants';\nexport type { IUrlSafetyPolicy } from './modules/network/utilities/url-safety/common/types';\nexport * from './modules/network/utilities/url-safety/policy';\nexport * from './modules/network/utilities/query-string';\nexport { RetryBackoffStrategies, RetryJitterModes } from './modules/retry/common/constants';\nexport type { TRetryBackoffStrategy, TRetryJitterMode } from './modules/retry/common/constants';\nexport type { IRetryBackoffOptions, IRetryContext } from './modules/retry/common/types';\nexport { RetryHelper } from './modules/retry/helper';\nexport { SlugHelper } from './modules/slug/helper';\nexport { TreeBuilder } from './modules/tree/builder';\nexport type {\n IBuildOptions,\n IHeightWhereOptions,\n ILeavesOptions,\n INodeWithPath,\n IPrintOptions,\n ITreeNode,\n IWalkAsyncOptions,\n IWalkOptions,\n TNodePredicate,\n TOnVisit,\n TOnVisitAsync,\n} from './modules/tree/common/types';\nexport { TreeWalker } from './modules/tree/walk';\n\n// Pure value/type utilities that already live under the root barrel's `./utilities` re-export -\n// that barrel also carries node-only siblings (module.utility.ts, request.utility.ts), so it\n// cannot itself become a subpath. Named one at a time here instead of widening the barrel: every\n// symbol below is verified free of node builtins/globals.\nexport { BuildInfoRegistry } from './utilities/build-info.utility';\nexport type { IBuildInfo, TBuildInfoRecord } from './utilities/build-info.utility';\nexport { ParseUtility } from './utilities/parse.utility';\nexport { PerformanceUtility } from './utilities/performance.utility';\nexport { PromiseUtility } from './utilities/promise.utility';\nexport { RecordUtility } from './utilities/record.utility';\nexport { FormBodyUtility, RequestBodyErrors } from './utilities/form-body.utility';\nexport { ProjectRootRegistry } from './utilities/project-root.utility';\n\n// `ECDH` is the one crypto algorithm that is browser-pure: it runs over `crypto.subtle`, `btoa` and `atob`. It and its\n// base class come by leaf path, never the algorithms barrel, which also carries `AES` and `RSA`\n// (server code: they use `Buffer`, and `AES` reads files with `node:fs`).\nexport { AbstractCryptoAlgorithm } from './modules/crypto/algorithms/abstract.algorithm';\nexport { ECDH } from './modules/crypto/algorithms/ecdh.algorithm';\nexport type {\n ECDHAlgorithmType,\n IECDHEncryptedPayload,\n IECDHExtraOptions,\n} from './modules/crypto/algorithms/ecdh.algorithm';\n\n// Type-only: erased at compile time, so re-exporting these carries no runtime/bundle cost even\n// though the concrete classes they describe (the other crypto algorithms, the ioredis-backed helper) are not\n// themselves part of this pure surface.\nexport { AESAlgorithms } from './modules/crypto/algorithms/aes.constants';\nexport type { AESAlgorithmType } from './modules/crypto/algorithms/aes.constants';\nexport type { IRedisHelper } from './modules/redis/common/interfaces';\n"]}
1
+ {"version":3,"file":"core.js","sourceRoot":"","sources":["../../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,6FAA6F;AAC7F,8DAA8D;AAC9D,OAAO,EAAE,gBAAg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OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAEvE,uHAAuH;AACvH,gGAAgG;AAChG,0EAA0E;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,gDAAgD,CAAC;AACzF,OAAO,EAAE,IAAI,EAAE,MAAM,4CAA4C,CAAC;AAOlE,+FAA+F;AAC/F,6GAA6G;AAC7G,wCAAwC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC","sourcesContent":["export { BaseHelper } from './modules/base';\n// By name, never `export *` from `./modules/env`: that barrel also carries `Environment` and\n// `applicationEnvironment`, both of which read `process.env`.\nexport { EnvironmentNames } from './modules/env/names';\nexport * from './modules/error';\nexport { LogLevels } from './modules/logger/common/types';\nexport type { ILogger, ILoggerProvider, TLogLevel } from './modules/logger/common/types';\n// The one way to get a logger, the same in the browser and on the server: `LoggerFactory` imports nothing from node, and its\n// default provider is the console. An application chooses another with `LoggerFactory.use({ provider, level })`.\nexport { ConsoleLogger } from './modules/logger/base/console';\nexport { LoggerFactory } from './modules/logger/factory';\nexport * from './modules/network/http-request/fetcher/base-fetcher';\n// The node fetcher carries no node builtin - its one `querystring.stringify` is written out - so the\n// framework HTTP layer is reachable from a browser bundle, and a connector on HTTP need not\n// re-implement one.\nexport * from './modules/network/http-request/fetcher/node-fetcher';\nexport * from './modules/network/http-request/base-network-request.helper';\nexport * from './modules/pool';\nexport * from './modules/queue/internal/hf';\nexport * from './modules/temporal';\nexport * from './modules/uid';\n// The url guard, pure half only: `UrlPolicy` decides a url and a literal address with string and\n// number work. Its sibling `UrlIngest` reaches `node:dns` and stays out of this subpath.\nexport * from './modules/network/utilities/url-safety/common/constants';\nexport type { IUrlSafetyPolicy } from './modules/network/utilities/url-safety/common/types';\nexport * from './modules/network/utilities/url-safety/policy';\nexport * from './modules/network/utilities/query-string';\nexport { RetryBackoffStrategies, RetryJitterModes } from './modules/retry/common/constants';\nexport type { TRetryBackoffStrategy, TRetryJitterMode } from './modules/retry/common/constants';\nexport type { IRetryBackoffOptions, IRetryContext } from './modules/retry/common/types';\nexport { RetryHelper } from './modules/retry/helper';\nexport { SlugHelper } from './modules/slug/helper';\nexport { TreeBuilder } from './modules/tree/builder';\nexport type {\n IBuildOptions,\n IHeightWhereOptions,\n ILeavesOptions,\n INodeWithPath,\n IPrintOptions,\n ITreeNode,\n IWalkAsyncOptions,\n IWalkOptions,\n TNodePredicate,\n TOnVisit,\n TOnVisitAsync,\n} from './modules/tree/common/types';\nexport { TreeWalker } from './modules/tree/walk';\n\n// Pure value/type utilities that already live under the root barrel's `./utilities` re-export -\n// that barrel also carries node-only siblings (module.utility.ts, request.utility.ts), so it\n// cannot itself become a subpath. Named one at a time here instead of widening the barrel: every\n// symbol below is verified free of node builtins/globals.\nexport { BuildInfoRegistry } from './utilities/build-info.utility';\nexport type { IBuildInfo, TBuildInfoRecord } from './utilities/build-info.utility';\nexport { EchoUtility } from './utilities/echo.utility';\nexport { ParseUtility } from './utilities/parse.utility';\nexport { PerformanceUtility } from './utilities/performance.utility';\nexport { PromiseUtility } from './utilities/promise.utility';\nexport { RecordUtility } from './utilities/record.utility';\nexport { FormBodyUtility, RequestBodyErrors } from './utilities/form-body.utility';\nexport { ProjectRootRegistry } from './utilities/project-root.utility';\n\n// `ECDH` is the one crypto algorithm that is browser-pure: it runs over `crypto.subtle`, `btoa` and `atob`. It and its\n// base class come by leaf path, never the algorithms barrel, which also carries `AES` and `RSA`\n// (server code: they use `Buffer`, and `AES` reads files with `node:fs`).\nexport { AbstractCryptoAlgorithm } from './modules/crypto/algorithms/abstract.algorithm';\nexport { ECDH } from './modules/crypto/algorithms/ecdh.algorithm';\nexport type {\n ECDHAlgorithmType,\n IECDHEncryptedPayload,\n IECDHExtraOptions,\n} from './modules/crypto/algorithms/ecdh.algorithm';\n\n// Type-only: erased at compile time, so re-exporting these carries no runtime/bundle cost even\n// though the concrete classes they describe (the other crypto algorithms, the ioredis-backed helper) are not\n// themselves part of this pure surface.\nexport { AESAlgorithms } from './modules/crypto/algorithms/aes.constants';\nexport type { AESAlgorithmType } from './modules/crypto/algorithms/aes.constants';\nexport type { IRedisHelper } from './modules/redis/common/interfaces';\n"]}
@@ -2,6 +2,7 @@ import { ObjectUtility } from '@venizia/ignis-inversion';
2
2
  import { ContentTypeTable, MimeTypes } from '../../common/index.js';
3
3
  import { BaseHelper } from '../base.js';
4
4
  import { getError } from '../error/index.js';
5
+ import { EchoUtility } from '../../utilities/echo.utility.js';
5
6
  import { PromiseUtility } from '../../utilities/promise.utility.js';
6
7
  import { Readable } from 'node:stream';
7
8
  import { StorageUtility, StorageConcurrency, StorageErrors } from './common/index.js';
@@ -17,7 +18,9 @@ export class BaseStorageHelper extends BaseHelper {
17
18
  isValidSegment(opts) {
18
19
  const name = opts.segment;
19
20
  if (typeof name !== 'string') {
20
- this.logger.for(this.isValidSegment.name).error('Invalid name provided: %j', name);
21
+ this.logger
22
+ .for(this.isValidSegment.name)
23
+ .error('Invalid name provided: %s', EchoUtility.toSafeEcho({ value: name }));
21
24
  return false;
22
25
  }
23
26
  if (!name || ObjectUtility.isEmpty({ value: name })) {
@@ -27,18 +30,20 @@ export class BaseStorageHelper extends BaseHelper {
27
30
  if (name.includes('..') || name.includes('/') || name.includes('\\')) {
28
31
  this.logger
29
32
  .for(this.isValidSegment.name)
30
- .error('Name contains invalid path characters: %s', name);
33
+ .error('Name contains invalid path characters: %s', EchoUtility.toSafeEcho({ value: name }));
31
34
  return false;
32
35
  }
33
36
  if (name.startsWith('.')) {
34
- this.logger.for(this.isValidSegment.name).error('Name cannot start with a dot: %s', name);
37
+ this.logger
38
+ .for(this.isValidSegment.name)
39
+ .error('Name cannot start with a dot: %s', EchoUtility.toSafeEcho({ value: name }));
35
40
  return false;
36
41
  }
37
42
  const dangerousChars = /[;|&$`<>{}[\]!#]/;
38
43
  if (dangerousChars.test(name)) {
39
44
  this.logger
40
45
  .for(this.isValidSegment.name)
41
- .error('Name contains dangerous characters: %s', name);
46
+ .error('Name contains dangerous characters: %s', EchoUtility.toSafeEcho({ value: name }));
42
47
  return false;
43
48
  }
44
49
  if (BaseStorageHelper.UNSAFE_NAME_CHARACTERS.test(name)) {
@@ -51,13 +56,13 @@ export class BaseStorageHelper extends BaseHelper {
51
56
  if (name.length > 255) {
52
57
  this.logger
53
58
  .for(this.isValidSegment.name)
54
- .error('Name is too long (%d characters): %s', name.length, name);
59
+ .error('Name is too long (%d characters): %s', name.length, EchoUtility.toSafeEcho({ value: name }));
55
60
  return false;
56
61
  }
57
62
  if (name.trim().length === 0) {
58
63
  this.logger
59
64
  .for(this.isValidSegment.name)
60
- .error('Name cannot be empty or whitespace only: "%s"', name);
65
+ .error('Name cannot be empty or whitespace only: %s', EchoUtility.toSafeEcho({ value: name }));
61
66
  return false;
62
67
  }
63
68
  return true;
@@ -92,7 +97,7 @@ export class BaseStorageHelper extends BaseHelper {
92
97
  if (segments.some((s) => s.length === 0)) {
93
98
  this.logger
94
99
  .for(this.isValidKeyPath.name)
95
- .error('Path contains empty segments (double slashes): %s', pathStr);
100
+ .error('Path contains empty segments (double slashes): %s', EchoUtility.toSafeEcho({ value: pathStr }));
96
101
  return false;
97
102
  }
98
103
  // segments include the filename, so depth is one less.
@@ -100,21 +105,21 @@ export class BaseStorageHelper extends BaseHelper {
100
105
  if (folderDepth > maxDepth) {
101
106
  this.logger
102
107
  .for(this.isValidKeyPath.name)
103
- .error('Path exceeds max folder depth (%d): %s (depth: %d)', maxDepth, pathStr, folderDepth);
108
+ .error('Path exceeds max folder depth (%d): %s (depth: %d)', maxDepth, EchoUtility.toSafeEcho({ value: pathStr }), folderDepth);
104
109
  return false;
105
110
  }
106
111
  for (const segment of segments) {
107
112
  if (!this.isValidSegment({ segment })) {
108
113
  this.logger
109
114
  .for(this.isValidKeyPath.name)
110
- .error('Path segment failed validation: %s (in path: %s)', segment, pathStr);
115
+ .error('Path segment failed validation: %s (in path: %s)', EchoUtility.toSafeEcho({ value: segment }), EchoUtility.toSafeEcho({ value: pathStr }));
111
116
  return false;
112
117
  }
113
118
  }
114
119
  if (normalized.length > 1024) {
115
120
  this.logger
116
121
  .for(this.isValidKeyPath.name)
117
- .error('Path is too long (%d characters): %s', normalized.length, pathStr);
122
+ .error('Path is too long (%d characters): %s', normalized.length, EchoUtility.toSafeEcho({ value: pathStr }));
118
123
  return false;
119
124
  }
120
125
  return true;
@@ -152,13 +157,15 @@ export class BaseStorageHelper extends BaseHelper {
152
157
  isValidOriginalName(opts) {
153
158
  const { name } = opts;
154
159
  if (typeof name !== 'string' || name.trim().length === 0 || name.length > 255) {
155
- this.logger.for(this.isValidOriginalName.name).error('Invalid original name: %j', name);
160
+ this.logger
161
+ .for(this.isValidOriginalName.name)
162
+ .error('Invalid original name: %s', EchoUtility.toSafeEcho({ value: name }));
156
163
  return false;
157
164
  }
158
165
  if (BaseStorageHelper.UNSAFE_NAME_CHARACTERS.test(name)) {
159
166
  this.logger
160
167
  .for(this.isValidOriginalName.name)
161
- .error('Original name contains a control character or a lone surrogate: %j', name);
168
+ .error('Original name contains a control character or a lone surrogate: %s', EchoUtility.toSafeEcho({ value: name }));
162
169
  return false;
163
170
  }
164
171
  return true;
@@ -206,7 +213,7 @@ export class BaseStorageHelper extends BaseHelper {
206
213
  const isExists = await this.hasBucket({ bucket });
207
214
  if (!isExists) {
208
215
  throw getError({
209
- message: `[upload] Bucket does not exist | name: ${bucket.name}`,
216
+ message: `[upload] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: bucket.name })}`,
210
217
  });
211
218
  }
212
219
  this.validateUploadFiles({
@@ -225,7 +232,7 @@ export class BaseStorageHelper extends BaseHelper {
225
232
  : this.normalizeObjectName({ file: naming });
226
233
  if (!this.isValidObjectKey({ object: { key }, maxDepth: maxFolderDepth })) {
227
234
  throw getError({
228
- message: `[upload] Invalid normalized object name | name: ${key}`,
235
+ message: `[upload] Invalid normalized object name | name: ${EchoUtility.toSafeText({ value: key })}`,
229
236
  });
230
237
  }
231
238
  return key;
@@ -243,7 +250,7 @@ export class BaseStorageHelper extends BaseHelper {
243
250
  await this.writeObject({ bucket, object, file });
244
251
  this.logger
245
252
  .for(this.upload.name)
246
- .info('Uploaded: %j | Took: %s (ms)', { key, link, mimeType, encoding, size }, performance.now() - t);
253
+ .info('Uploaded: %s | Took: %s (ms)', EchoUtility.toSafeEcho({ value: { key, link, mimeType, encoding, size } }), performance.now() - t);
247
254
  return {
248
255
  bucket: { name: bucket.name },
249
256
  object: { key, size, contentType: mimeType },
@@ -305,16 +312,20 @@ export class BaseStorageHelper extends BaseHelper {
305
312
  const { bucket, object, source, contentType } = opts;
306
313
  // The same depth rule `upload` applies, as `BunS3Helper.writeStream` does: one object, two doors, one answer.
307
314
  if (!this.isValidObjectKey({ object, maxDepth: opts.maxFolderDepth })) {
308
- throw getError({ message: `[writeStream] Invalid object name | key: ${object.key}` });
315
+ throw getError({
316
+ message: `[writeStream] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,
317
+ });
309
318
  }
310
319
  if (!this.isValidBucketName({ bucket })) {
311
- throw getError({ message: `[storage] Invalid bucket name | bucket: ${bucket.name}` });
320
+ throw getError({
321
+ message: `[storage] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,
322
+ });
312
323
  }
313
324
  // As `upload` does: a write never creates the bucket.
314
325
  const result2 = await this.hasBucket({ bucket });
315
326
  if (!result2) {
316
327
  throw getError({
317
- message: `[writeStream] Bucket does not exist | name: ${bucket.name}`,
328
+ message: `[writeStream] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: bucket.name })}`,
318
329
  });
319
330
  }
320
331
  const body = source instanceof Response || source instanceof Request ? source : new Response(source);
@@ -350,7 +361,7 @@ export class BaseStorageHelper extends BaseHelper {
350
361
  }
351
362
  return getError({
352
363
  error: StorageErrors.OBJECT_NOT_FOUND,
353
- message: `[${operation}] Object not found | bucket: ${bucket.name} | key: ${object.key}`,
364
+ message: `[${operation}] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,
354
365
  });
355
366
  }
356
367
  // No transport for these: throwing beats returning undefined, which reads as a valid empty result.
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/modules/storage/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAkB,SAAS,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAevC,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE7E,+IAA+I;AAC/I,MAAM,OAAgB,iBAAkB,SAAQ,UAAU;IACxD,YAAY,IAA2C;QACrD,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;IAED,WAAW,CAAC,IAA0B;QACpC,OAAO,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;IAED,gGAAgG;IAChG,cAAc,CAAC,IAAyB;QACtC,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC;QAE1B,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,2BAA2B,EAAE,IAAI,CAAC,CAAC;YAEnF,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,CAAC,IAAI,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,IAAI,E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ACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,kEAAkE;SACrG,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,KAAsB;QACxC,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,gEAAgE;SACnG,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,iBAAiB,CACrB,KAAyD;QAEzD,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,oEAAoE;SACvG,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { ContentTypeTable, type IDuration, MimeTypes } from '@/common';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport { Readable } from 'node:stream';\nimport {\n type IBucketInfo,\n type IBucketRef,\n type IFileStat,\n type IListObjectsOptions,\n type IObjectInfo,\n type IObjectLocation,\n type IPostPolicy,\n type IObjectRef,\n type IStorageHelper,\n type IUploadFile,\n type IUploadResult,\n type TUploadNaming,\n} from './common';\nimport { StorageUtility, StorageConcurrency, StorageErrors } from './common';\n\n/** Shared base for storage helpers: MIME lookup, name and path validation, and upload naming. Concrete helpers implement the backend calls. */\nexport abstract class BaseStorageHelper extends BaseHelper implements IStorageHelper {\n constructor(opts: { scope: string; identifier: string }) {\n super(opts);\n }\n\n getMimeType(opts: { filename: string }): string {\n return ContentTypeTable.resolve(opts);\n }\n\n /** One path segment or file name: no separator, no traversal, no control or shell character. */\n isValidSegment(opts: { segment: string }): boolean {\n const name = opts.segment;\n\n if (typeof name !== 'string') {\n this.logger.for(this.isValidSegment.name).error('Invalid name provided: %j', name);\n\n return false;\n }\n\n if (!name || ObjectUtility.isEmpty({ value: name })) {\n this.logger.for(this.isValidSegment.name).error('Empty name provided');\n\n return false;\n }\n\n if (name.includes('..') || name.includes('/') || name.includes('\\\\')) {\n this.logger\n .for(this.isValidSegment.name)\n .error('Name contains invalid path characters: %s', name);\n\n return false;\n }\n\n if (name.startsWith('.')) {\n this.logger.for(this.isValidSegment.name).error('Name cannot start with a dot: %s', name);\n\n return false;\n }\n\n const dangerousChars = /[;|&$`<>{}[\\]!#]/;\n\n if (dangerousChars.test(name)) {\n this.logger\n .for(this.isValidSegment.name)\n .error('Name contains dangerous characters: %s', name);\n\n return false;\n }\n\n if (BaseStorageHelper.UNSAFE_NAME_CHARACTERS.test(name)) {\n // The length, not the name: a control character in a log line is the line's own to forge.\n this.logger\n .for(this.isValidSegment.name)\n .error('Name contains a control or bidirectional character | length: %d', name.length);\n\n return false;\n }\n\n if (name.length > 255) {\n this.logger\n .for(this.isValidSegment.name)\n .error('Name is too long (%d characters): %s', name.length, name);\n\n return false;\n }\n\n if (name.trim().length === 0) {\n this.logger\n .for(this.isValidSegment.name)\n .error('Name cannot be empty or whitespace only: \"%s\"', name);\n\n return false;\n }\n\n return true;\n }\n\n static readonly DEFAULT_MAX_FOLDER_DEPTH = 2;\n\n /** Control characters, lone surrogates, the line and paragraph separators (U+2028, U+2029) and the bidirectional marks and overrides: never part of a file name or a key (the overrides make `gpj.exe` display as `exe.jpg`), and a control character or a surrogate cannot be encoded into a header. */\n private static readonly UNSAFE_NAME_CHARACTERS =\n /[\\p{Cc}\\p{Cs}\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069]/u;\n\n /** A bucket name is one segment; a separator in it would silently address a different bucket. */\n isValidBucketName(opts: { bucket: IBucketRef }): boolean {\n return this.isValidSegment({ segment: opts.bucket.name });\n }\n\n /** A whole object key: every segment valid, and no deeper than `maxDepth` folders. */\n isValidObjectKey(opts: { object: IObjectRef; maxDepth?: number }): boolean {\n return this.isValidKeyPath({ path: opts.object.key, maxDepth: opts.maxDepth });\n }\n\n /** The shared rule behind `isValidObjectKey` and the folder check inside `upload`. */\n protected isValidKeyPath(opts: { path: string; maxDepth?: number }): boolean {\n const { path: pathStr } = opts;\n const maxDepth = opts.maxDepth ?? BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH;\n\n if (typeof pathStr !== 'string' || !pathStr || ObjectUtility.isEmpty({ value: pathStr })) {\n this.logger.for(this.isValidKeyPath.name).error('Empty or invalid path provided');\n\n return false;\n }\n\n const normalized = pathStr.replace(/^\\/+|\\/+$/g, '');\n\n if (!normalized) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error('Path resolved to empty after trimming slashes');\n\n return false;\n }\n\n const segments = normalized.split('/');\n\n if (segments.some((s) => s.length === 0)) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error('Path contains empty segments (double slashes): %s', pathStr);\n\n return false;\n }\n\n // segments include the filename, so depth is one less.\n const folderDepth = segments.length - 1;\n\n if (folderDepth > maxDepth) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error(\n 'Path exceeds max folder depth (%d): %s (depth: %d)',\n maxDepth,\n pathStr,\n folderDepth,\n );\n\n return false;\n }\n\n for (const segment of segments) {\n if (!this.isValidSegment({ segment })) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error('Path segment failed validation: %s (in path: %s)', segment, pathStr);\n\n return false;\n }\n }\n\n if (normalized.length > 1024) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error('Path is too long (%d characters): %s', normalized.length, pathStr);\n\n return false;\n }\n\n return true;\n }\n\n getMediaType(opts: { mimeType: string }): string {\n const { mimeType } = opts;\n\n if (mimeType?.toLowerCase()?.startsWith(MimeTypes.IMAGE)) {\n return MimeTypes.IMAGE;\n }\n\n if (mimeType?.toLowerCase()?.startsWith(MimeTypes.VIDEO)) {\n return MimeTypes.VIDEO;\n }\n\n if (mimeType?.toLowerCase()?.startsWith(MimeTypes.TEXT)) {\n return MimeTypes.TEXT;\n }\n\n return MimeTypes.UNKNOWN;\n }\n\n /** Public URL prefix; keeps its trailing slash. */\n protected abstract get defaultLinkPrefix(): string;\n\n /** Backend write step; owns its metadata and error handling. */\n protected abstract writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void>;\n\n protected normalizeObjectName(opts: { file: TUploadNaming }): string {\n const { originalName, folderPath } = opts.file;\n const normalizedFileName = originalName.toLowerCase().replace(/ /g, '_');\n\n if (!folderPath) {\n return normalizedFileName;\n }\n\n return `${folderPath.toLowerCase().replace(/ /g, '_')}/${normalizedFileName}`;\n }\n\n protected normalizeObjectLink(opts: IObjectLocation): string {\n const bucketName = opts.bucket.name;\n const encodedName = opts.object.key\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n\n return `${this.defaultLinkPrefix}${bucketName}/${encodedName}`;\n }\n\n /** An original name that is only metadata - the key is resolved elsewhere and validated on its own. */\n protected isValidOriginalName(opts: { name: string }): boolean {\n const { name } = opts;\n\n if (typeof name !== 'string' || name.trim().length === 0 || name.length > 255) {\n this.logger.for(this.isValidOriginalName.name).error('Invalid original name: %j', name);\n\n return false;\n }\n\n if (BaseStorageHelper.UNSAFE_NAME_CHARACTERS.test(name)) {\n this.logger\n .for(this.isValidOriginalName.name)\n .error('Original name contains a control character or a lone surrogate: %j', name);\n\n return false;\n }\n\n return true;\n }\n\n /** `isKeyResolvedByCaller`: a `normalizeNameFn` decides the key, so the original name is metadata and meets the metadata rule, not the key rule. */\n protected validateUploadFiles(opts: {\n files: IUploadFile[];\n maxFolderDepth?: number;\n isKeyResolvedByCaller?: boolean;\n }): void {\n const { files, maxFolderDepth, isKeyResolvedByCaller = false } = opts;\n\n for (const file of files) {\n this.validateUploadFile({ file, maxFolderDepth, isKeyResolvedByCaller });\n }\n }\n\n private validateUploadFile(opts: {\n file: IUploadFile;\n maxFolderDepth?: number;\n isKeyResolvedByCaller: boolean;\n }): void {\n const { file, maxFolderDepth, isKeyResolvedByCaller } = opts;\n const { originalName, size, folderPath } = file;\n\n const isNameValid = isKeyResolvedByCaller\n ? this.isValidOriginalName({ name: originalName })\n : this.isValidSegment({ segment: originalName });\n\n if (!isNameValid) {\n throw getError({ message: '[upload] Invalid original file name' });\n }\n\n // Checked against the CALLER's depth, before the body is spooled. `isValidKeyPath` measures an\n // object path (one folder deeper than a bare folderPath), so the depth is checked directly.\n if (folderPath) {\n const depthLimit = maxFolderDepth ?? BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH;\n const folderSegments = folderPath.replace(/^\\/+|\\/+$/g, '').split('/');\n\n if (folderSegments.length > depthLimit) {\n throw getError({\n message: `[upload] Invalid folder path | depth: ${folderSegments.length} | max: ${depthLimit}`,\n });\n }\n\n if (!this.isValidKeyPath({ path: folderPath, maxDepth: depthLimit })) {\n throw getError({ message: '[upload] Invalid folder path' });\n }\n }\n\n // Missing or negative is invalid; zero is a legitimate empty file.\n if (size === undefined || size === null || size < 0) {\n throw getError({ message: `[upload] Invalid file size | size: ${size}` });\n }\n }\n\n async upload(opts: {\n bucket: IBucketRef;\n files: IUploadFile[];\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n /**\n * Folder nesting allowed.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n }): Promise<IUploadResult[]> {\n const { bucket, files, normalizeNameFn, normalizeLinkFn, maxFolderDepth } = opts;\n\n if (!files || files.length === 0) {\n return [];\n }\n\n const isExists = await this.hasBucket({ bucket });\n\n if (!isExists) {\n throw getError({\n message: `[upload] Bucket does not exist | name: ${bucket.name}`,\n });\n }\n\n this.validateUploadFiles({\n files,\n maxFolderDepth,\n isKeyResolvedByCaller: normalizeNameFn !== undefined,\n });\n\n // Every key is resolved and validated before the first write, so one bad key stores nothing.\n const keys = files.map((file) => {\n const naming: TUploadNaming = {\n originalName: file.originalName,\n folderPath: file.folderPath,\n };\n const key = normalizeNameFn\n ? normalizeNameFn({ file: naming })\n : this.normalizeObjectName({ file: naming });\n\n if (!this.isValidObjectKey({ object: { key }, maxDepth: maxFolderDepth })) {\n throw getError({\n message: `[upload] Invalid normalized object name | name: ${key}`,\n });\n }\n\n return key;\n });\n\n return this.mapWithConcurrency({\n items: files,\n task: async ({ item: file, index }) => {\n const { mimetype: mimeType, size, encoding } = file;\n const t = performance.now();\n const key = keys[index];\n\n const object: IObjectRef = { key };\n const link = normalizeLinkFn\n ? normalizeLinkFn({ bucket, object })\n : this.normalizeObjectLink({ bucket, object });\n\n await this.writeObject({ bucket, object, file });\n\n this.logger\n .for(this.upload.name)\n .info(\n 'Uploaded: %j | Took: %s (ms)',\n { key, link, mimeType, encoding, size },\n performance.now() - t,\n );\n\n return {\n bucket: { name: bucket.name },\n object: { key, size, contentType: mimeType },\n link,\n };\n },\n });\n }\n\n /** Correct anywhere; overridden by a backend whose transport is already a web stream. */\n async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n const source = await this.getObject({ bucket, object });\n\n if (!range) {\n return Readable.toWeb(source) as ReadableStream<Uint8Array>;\n }\n\n // No native range here: take the window off the front of the full stream. `pull` rather than\n // `start`, so one chunk is read per demand instead of the whole range landing in memory.\n const { start, end } = range;\n const chunks = source[Symbol.asyncIterator]();\n let offset = 0;\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n while (true) {\n const next = await chunks.next();\n\n if (next.done) {\n controller.close();\n\n return;\n }\n\n const bytes = next.value as Uint8Array;\n const chunkEnd = offset + bytes.byteLength;\n const from = Math.max(start - offset, 0);\n const to =\n end === undefined ? bytes.byteLength : Math.min(end + 1 - offset, bytes.byteLength);\n const isWanted = chunkEnd > start && from < to;\n\n if (isWanted) {\n controller.enqueue(bytes.subarray(from, to));\n }\n\n offset = chunkEnd;\n\n if (end !== undefined && offset > end) {\n source.destroy();\n controller.close();\n\n return;\n }\n\n if (isWanted) {\n return;\n }\n }\n },\n\n // Without this a client that aborts leaves the backend stream draining to nowhere.\n cancel() {\n source.destroy();\n },\n });\n }\n\n /**\n * Correct anywhere, and the wrong path to stay on: it buffers, so a backend whose transport takes\n * a stream overrides it. `BunS3Helper` does.\n */\n async writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n maxFolderDepth?: number;\n },\n ): Promise<void> {\n const { bucket, object, source, contentType } = opts;\n\n // The same depth rule `upload` applies, as `BunS3Helper.writeStream` does: one object, two doors, one answer.\n if (!this.isValidObjectKey({ object, maxDepth: opts.maxFolderDepth })) {\n throw getError({ message: `[writeStream] Invalid object name | key: ${object.key}` });\n }\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({ message: `[storage] Invalid bucket name | bucket: ${bucket.name}` });\n }\n\n // As `upload` does: a write never creates the bucket.\n const result2 = await this.hasBucket({ bucket });\n\n if (!result2) {\n throw getError({\n message: `[writeStream] Bucket does not exist | name: ${bucket.name}`,\n });\n }\n\n const body =\n source instanceof Response || source instanceof Request ? source : new Response(source);\n const result = await body.arrayBuffer();\n const buffer = Buffer.from(result);\n\n await this.writeObject({\n bucket,\n object,\n file: {\n originalName: object.key,\n mimetype: contentType ?? this.getMimeType({ filename: object.key }),\n buffer,\n size: buffer.length,\n },\n });\n }\n\n /** Bounded fan-out on the shared limiter; unbounded exhausts sockets and gets rate limited. */\n protected async mapWithConcurrency<Item, Result>(opts: {\n items: Item[];\n limit?: number;\n task: (taskOptions: { item: Item; index: number }) => Promise<Result>;\n }): Promise<Result[]> {\n const { items, task } = opts;\n\n if (items.length === 0) {\n return [];\n }\n\n return PromiseUtility.executeWithLimit({\n limit: Math.max(1, opts.limit ?? StorageConcurrency.DEFAULT_LIMIT),\n tasks: items.map((item, index) => () => task({ item, index })),\n });\n }\n\n /** A \"not there\" failure becomes a catalogued 404; every other failure passes through unchanged. */\n protected asStorageError(opts: IObjectLocation & { error: unknown; operation: string }): unknown {\n const { error, operation, bucket, object } = opts;\n\n if (!StorageUtility.isNotFoundError({ error })) {\n return error;\n }\n\n return getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[${operation}] Object not found | bucket: ${bucket.name} | key: ${object.key}`,\n });\n }\n\n // No transport for these: throwing beats returning undefined, which reads as a valid empty result.\n async copyObject(_opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void> {\n throw getError({\n message: `[${this.constructor.name}.copyObject] Server-side copy is not supported by this helper`,\n });\n }\n\n async presignPost(_opts: {\n bucket: IBucketRef;\n keyPrefix: string;\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n }): Promise<IPostPolicy> {\n throw getError({\n message: `[${this.constructor.name}.presignPost] Signed POST policies are not supported by this helper`,\n });\n }\n\n async presignPut(\n _opts: IObjectLocation & {\n expiresIn?: IDuration;\n tagging?: Record<string, string>;\n contentLength?: number;\n contentType?: string;\n },\n ): Promise<string> {\n throw getError({\n message: `[${this.constructor.name}.presignPut] Presigned PUT URLs are not supported by this helper`,\n });\n }\n\n async presignGet(\n _opts: IObjectLocation & { expiresIn?: IDuration; responseContentType?: string },\n ): Promise<string> {\n throw getError({\n message: `[${this.constructor.name}.presignGet] Presigned GET URLs are not supported by this helper`,\n });\n }\n\n async getObjectTags(_opts: IObjectLocation): Promise<Record<string, string>> {\n throw getError({\n message: `[${this.constructor.name}.getObjectTags] Object tagging is not supported by this helper`,\n });\n }\n\n async replaceObjectTags(\n _opts: IObjectLocation & { tags: Record<string, string> },\n ): Promise<void> {\n throw getError({\n message: `[${this.constructor.name}.replaceObjectTags] Object tagging is not supported by this helper`,\n });\n }\n\n abstract hasBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n abstract getBuckets(): Promise<IBucketInfo[]>;\n abstract getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n abstract createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n abstract removeBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n\n abstract getObject(opts: IObjectLocation & { options?: any }): Promise<Readable>;\n abstract getStat(opts: IObjectLocation): Promise<IFileStat>;\n abstract removeObject(opts: IObjectLocation): Promise<void>;\n abstract removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void>;\n abstract listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/modules/storage/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAkB,SAAS,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAevC,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE7E,+IAA+I;AAC/I,MAAM,OAAgB,iBAAkB,SAAQ,UAAU;IACxD,YAAY,IAA2C;QACrD,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;IAED,WAAW,CAAC,IAA0B;QACpC,OAAO,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;IAED,gGAAgG;IAChG,cAAc,CAAC,IAAyB;QACtC,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC;QAE1B,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC;iBAC7B,KAAK,CAAC,2BAA2B,EAAE,WAAW,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YAE/E,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAA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,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,aAAa,CAAC,KAAsB;QACxC,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,gEAAgE;SACnG,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,iBAAiB,CACrB,KAAyD;QAEzD,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,oEAAoE;SACvG,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { ContentTypeTable, type IDuration, MimeTypes } from '@/common';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { EchoUtility } from '@/utilities/echo.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport { Readable } from 'node:stream';\nimport {\n type IBucketInfo,\n type IBucketRef,\n type IFileStat,\n type IListObjectsOptions,\n type IObjectInfo,\n type IObjectLocation,\n type IPostPolicy,\n type IObjectRef,\n type IStorageHelper,\n type IUploadFile,\n type IUploadResult,\n type TUploadNaming,\n} from './common';\nimport { StorageUtility, StorageConcurrency, StorageErrors } from './common';\n\n/** Shared base for storage helpers: MIME lookup, name and path validation, and upload naming. Concrete helpers implement the backend calls. */\nexport abstract class BaseStorageHelper extends BaseHelper implements IStorageHelper {\n constructor(opts: { scope: string; identifier: string }) {\n super(opts);\n }\n\n getMimeType(opts: { filename: string }): string {\n return ContentTypeTable.resolve(opts);\n }\n\n /** One path segment or file name: no separator, no traversal, no control or shell character. */\n isValidSegment(opts: { segment: string }): boolean {\n const name = opts.segment;\n\n if (typeof name !== 'string') {\n this.logger\n .for(this.isValidSegment.name)\n .error('Invalid name provided: %s', EchoUtility.toSafeEcho({ value: name }));\n\n return false;\n }\n\n if (!name || ObjectUtility.isEmpty({ value: name })) {\n this.logger.for(this.isValidSegment.name).error('Empty name provided');\n\n return false;\n }\n\n if (name.includes('..') || name.includes('/') || name.includes('\\\\')) {\n this.logger\n .for(this.isValidSegment.name)\n .error(\n 'Name contains invalid path characters: %s',\n EchoUtility.toSafeEcho({ value: name }),\n );\n\n return false;\n }\n\n if (name.startsWith('.')) {\n this.logger\n .for(this.isValidSegment.name)\n .error('Name cannot start with a dot: %s', EchoUtility.toSafeEcho({ value: name }));\n\n return false;\n }\n\n const dangerousChars = /[;|&$`<>{}[\\]!#]/;\n\n if (dangerousChars.test(name)) {\n this.logger\n .for(this.isValidSegment.name)\n .error('Name contains dangerous characters: %s', EchoUtility.toSafeEcho({ value: name }));\n\n return false;\n }\n\n if (BaseStorageHelper.UNSAFE_NAME_CHARACTERS.test(name)) {\n // The length, not the name: a control character in a log line is the line's own to forge.\n this.logger\n .for(this.isValidSegment.name)\n .error('Name contains a control or bidirectional character | length: %d', name.length);\n\n return false;\n }\n\n if (name.length > 255) {\n this.logger\n .for(this.isValidSegment.name)\n .error(\n 'Name is too long (%d characters): %s',\n name.length,\n EchoUtility.toSafeEcho({ value: name }),\n );\n\n return false;\n }\n\n if (name.trim().length === 0) {\n this.logger\n .for(this.isValidSegment.name)\n .error(\n 'Name cannot be empty or whitespace only: %s',\n EchoUtility.toSafeEcho({ value: name }),\n );\n\n return false;\n }\n\n return true;\n }\n\n static readonly DEFAULT_MAX_FOLDER_DEPTH = 2;\n\n /** Control characters, lone surrogates, the line and paragraph separators (U+2028, U+2029) and the bidirectional marks and overrides: never part of a file name or a key (the overrides make `gpj.exe` display as `exe.jpg`), and a control character or a surrogate cannot be encoded into a header. */\n private static readonly UNSAFE_NAME_CHARACTERS =\n /[\\p{Cc}\\p{Cs}\\u061C\\u200E\\u200F\\u2028\\u2029\\u202A-\\u202E\\u2066-\\u2069]/u;\n\n /** A bucket name is one segment; a separator in it would silently address a different bucket. */\n isValidBucketName(opts: { bucket: IBucketRef }): boolean {\n return this.isValidSegment({ segment: opts.bucket.name });\n }\n\n /** A whole object key: every segment valid, and no deeper than `maxDepth` folders. */\n isValidObjectKey(opts: { object: IObjectRef; maxDepth?: number }): boolean {\n return this.isValidKeyPath({ path: opts.object.key, maxDepth: opts.maxDepth });\n }\n\n /** The shared rule behind `isValidObjectKey` and the folder check inside `upload`. */\n protected isValidKeyPath(opts: { path: string; maxDepth?: number }): boolean {\n const { path: pathStr } = opts;\n const maxDepth = opts.maxDepth ?? BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH;\n\n if (typeof pathStr !== 'string' || !pathStr || ObjectUtility.isEmpty({ value: pathStr })) {\n this.logger.for(this.isValidKeyPath.name).error('Empty or invalid path provided');\n\n return false;\n }\n\n const normalized = pathStr.replace(/^\\/+|\\/+$/g, '');\n\n if (!normalized) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error('Path resolved to empty after trimming slashes');\n\n return false;\n }\n\n const segments = normalized.split('/');\n\n if (segments.some((s) => s.length === 0)) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error(\n 'Path contains empty segments (double slashes): %s',\n EchoUtility.toSafeEcho({ value: pathStr }),\n );\n\n return false;\n }\n\n // segments include the filename, so depth is one less.\n const folderDepth = segments.length - 1;\n\n if (folderDepth > maxDepth) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error(\n 'Path exceeds max folder depth (%d): %s (depth: %d)',\n maxDepth,\n EchoUtility.toSafeEcho({ value: pathStr }),\n folderDepth,\n );\n\n return false;\n }\n\n for (const segment of segments) {\n if (!this.isValidSegment({ segment })) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error(\n 'Path segment failed validation: %s (in path: %s)',\n EchoUtility.toSafeEcho({ value: segment }),\n EchoUtility.toSafeEcho({ value: pathStr }),\n );\n\n return false;\n }\n }\n\n if (normalized.length > 1024) {\n this.logger\n .for(this.isValidKeyPath.name)\n .error(\n 'Path is too long (%d characters): %s',\n normalized.length,\n EchoUtility.toSafeEcho({ value: pathStr }),\n );\n\n return false;\n }\n\n return true;\n }\n\n getMediaType(opts: { mimeType: string }): string {\n const { mimeType } = opts;\n\n if (mimeType?.toLowerCase()?.startsWith(MimeTypes.IMAGE)) {\n return MimeTypes.IMAGE;\n }\n\n if (mimeType?.toLowerCase()?.startsWith(MimeTypes.VIDEO)) {\n return MimeTypes.VIDEO;\n }\n\n if (mimeType?.toLowerCase()?.startsWith(MimeTypes.TEXT)) {\n return MimeTypes.TEXT;\n }\n\n return MimeTypes.UNKNOWN;\n }\n\n /** Public URL prefix; keeps its trailing slash. */\n protected abstract get defaultLinkPrefix(): string;\n\n /** Backend write step; owns its metadata and error handling. */\n protected abstract writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void>;\n\n protected normalizeObjectName(opts: { file: TUploadNaming }): string {\n const { originalName, folderPath } = opts.file;\n const normalizedFileName = originalName.toLowerCase().replace(/ /g, '_');\n\n if (!folderPath) {\n return normalizedFileName;\n }\n\n return `${folderPath.toLowerCase().replace(/ /g, '_')}/${normalizedFileName}`;\n }\n\n protected normalizeObjectLink(opts: IObjectLocation): string {\n const bucketName = opts.bucket.name;\n const encodedName = opts.object.key\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n\n return `${this.defaultLinkPrefix}${bucketName}/${encodedName}`;\n }\n\n /** An original name that is only metadata - the key is resolved elsewhere and validated on its own. */\n protected isValidOriginalName(opts: { name: string }): boolean {\n const { name } = opts;\n\n if (typeof name !== 'string' || name.trim().length === 0 || name.length > 255) {\n this.logger\n .for(this.isValidOriginalName.name)\n .error('Invalid original name: %s', EchoUtility.toSafeEcho({ value: name }));\n\n return false;\n }\n\n if (BaseStorageHelper.UNSAFE_NAME_CHARACTERS.test(name)) {\n this.logger\n .for(this.isValidOriginalName.name)\n .error(\n 'Original name contains a control character or a lone surrogate: %s',\n EchoUtility.toSafeEcho({ value: name }),\n );\n\n return false;\n }\n\n return true;\n }\n\n /** `isKeyResolvedByCaller`: a `normalizeNameFn` decides the key, so the original name is metadata and meets the metadata rule, not the key rule. */\n protected validateUploadFiles(opts: {\n files: IUploadFile[];\n maxFolderDepth?: number;\n isKeyResolvedByCaller?: boolean;\n }): void {\n const { files, maxFolderDepth, isKeyResolvedByCaller = false } = opts;\n\n for (const file of files) {\n this.validateUploadFile({ file, maxFolderDepth, isKeyResolvedByCaller });\n }\n }\n\n private validateUploadFile(opts: {\n file: IUploadFile;\n maxFolderDepth?: number;\n isKeyResolvedByCaller: boolean;\n }): void {\n const { file, maxFolderDepth, isKeyResolvedByCaller } = opts;\n const { originalName, size, folderPath } = file;\n\n const isNameValid = isKeyResolvedByCaller\n ? this.isValidOriginalName({ name: originalName })\n : this.isValidSegment({ segment: originalName });\n\n if (!isNameValid) {\n throw getError({ message: '[upload] Invalid original file name' });\n }\n\n // Checked against the CALLER's depth, before the body is spooled. `isValidKeyPath` measures an\n // object path (one folder deeper than a bare folderPath), so the depth is checked directly.\n if (folderPath) {\n const depthLimit = maxFolderDepth ?? BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH;\n const folderSegments = folderPath.replace(/^\\/+|\\/+$/g, '').split('/');\n\n if (folderSegments.length > depthLimit) {\n throw getError({\n message: `[upload] Invalid folder path | depth: ${folderSegments.length} | max: ${depthLimit}`,\n });\n }\n\n if (!this.isValidKeyPath({ path: folderPath, maxDepth: depthLimit })) {\n throw getError({ message: '[upload] Invalid folder path' });\n }\n }\n\n // Missing or negative is invalid; zero is a legitimate empty file.\n if (size === undefined || size === null || size < 0) {\n throw getError({ message: `[upload] Invalid file size | size: ${size}` });\n }\n }\n\n async upload(opts: {\n bucket: IBucketRef;\n files: IUploadFile[];\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n /**\n * Folder nesting allowed.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n }): Promise<IUploadResult[]> {\n const { bucket, files, normalizeNameFn, normalizeLinkFn, maxFolderDepth } = opts;\n\n if (!files || files.length === 0) {\n return [];\n }\n\n const isExists = await this.hasBucket({ bucket });\n\n if (!isExists) {\n throw getError({\n message: `[upload] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n this.validateUploadFiles({\n files,\n maxFolderDepth,\n isKeyResolvedByCaller: normalizeNameFn !== undefined,\n });\n\n // Every key is resolved and validated before the first write, so one bad key stores nothing.\n const keys = files.map((file) => {\n const naming: TUploadNaming = {\n originalName: file.originalName,\n folderPath: file.folderPath,\n };\n const key = normalizeNameFn\n ? normalizeNameFn({ file: naming })\n : this.normalizeObjectName({ file: naming });\n\n if (!this.isValidObjectKey({ object: { key }, maxDepth: maxFolderDepth })) {\n throw getError({\n message: `[upload] Invalid normalized object name | name: ${EchoUtility.toSafeText({ value: key })}`,\n });\n }\n\n return key;\n });\n\n return this.mapWithConcurrency({\n items: files,\n task: async ({ item: file, index }) => {\n const { mimetype: mimeType, size, encoding } = file;\n const t = performance.now();\n const key = keys[index];\n\n const object: IObjectRef = { key };\n const link = normalizeLinkFn\n ? normalizeLinkFn({ bucket, object })\n : this.normalizeObjectLink({ bucket, object });\n\n await this.writeObject({ bucket, object, file });\n\n this.logger\n .for(this.upload.name)\n .info(\n 'Uploaded: %s | Took: %s (ms)',\n EchoUtility.toSafeEcho({ value: { key, link, mimeType, encoding, size } }),\n performance.now() - t,\n );\n\n return {\n bucket: { name: bucket.name },\n object: { key, size, contentType: mimeType },\n link,\n };\n },\n });\n }\n\n /** Correct anywhere; overridden by a backend whose transport is already a web stream. */\n async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n const source = await this.getObject({ bucket, object });\n\n if (!range) {\n return Readable.toWeb(source) as ReadableStream<Uint8Array>;\n }\n\n // No native range here: take the window off the front of the full stream. `pull` rather than\n // `start`, so one chunk is read per demand instead of the whole range landing in memory.\n const { start, end } = range;\n const chunks = source[Symbol.asyncIterator]();\n let offset = 0;\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n while (true) {\n const next = await chunks.next();\n\n if (next.done) {\n controller.close();\n\n return;\n }\n\n const bytes = next.value as Uint8Array;\n const chunkEnd = offset + bytes.byteLength;\n const from = Math.max(start - offset, 0);\n const to =\n end === undefined ? bytes.byteLength : Math.min(end + 1 - offset, bytes.byteLength);\n const isWanted = chunkEnd > start && from < to;\n\n if (isWanted) {\n controller.enqueue(bytes.subarray(from, to));\n }\n\n offset = chunkEnd;\n\n if (end !== undefined && offset > end) {\n source.destroy();\n controller.close();\n\n return;\n }\n\n if (isWanted) {\n return;\n }\n }\n },\n\n // Without this a client that aborts leaves the backend stream draining to nowhere.\n cancel() {\n source.destroy();\n },\n });\n }\n\n /**\n * Correct anywhere, and the wrong path to stay on: it buffers, so a backend whose transport takes\n * a stream overrides it. `BunS3Helper` does.\n */\n async writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n maxFolderDepth?: number;\n },\n ): Promise<void> {\n const { bucket, object, source, contentType } = opts;\n\n // The same depth rule `upload` applies, as `BunS3Helper.writeStream` does: one object, two doors, one answer.\n if (!this.isValidObjectKey({ object, maxDepth: opts.maxFolderDepth })) {\n throw getError({\n message: `[writeStream] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[storage] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n // As `upload` does: a write never creates the bucket.\n const result2 = await this.hasBucket({ bucket });\n\n if (!result2) {\n throw getError({\n message: `[writeStream] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n const body =\n source instanceof Response || source instanceof Request ? source : new Response(source);\n const result = await body.arrayBuffer();\n const buffer = Buffer.from(result);\n\n await this.writeObject({\n bucket,\n object,\n file: {\n originalName: object.key,\n mimetype: contentType ?? this.getMimeType({ filename: object.key }),\n buffer,\n size: buffer.length,\n },\n });\n }\n\n /** Bounded fan-out on the shared limiter; unbounded exhausts sockets and gets rate limited. */\n protected async mapWithConcurrency<Item, Result>(opts: {\n items: Item[];\n limit?: number;\n task: (taskOptions: { item: Item; index: number }) => Promise<Result>;\n }): Promise<Result[]> {\n const { items, task } = opts;\n\n if (items.length === 0) {\n return [];\n }\n\n return PromiseUtility.executeWithLimit({\n limit: Math.max(1, opts.limit ?? StorageConcurrency.DEFAULT_LIMIT),\n tasks: items.map((item, index) => () => task({ item, index })),\n });\n }\n\n /** A \"not there\" failure becomes a catalogued 404; every other failure passes through unchanged. */\n protected asStorageError(opts: IObjectLocation & { error: unknown; operation: string }): unknown {\n const { error, operation, bucket, object } = opts;\n\n if (!StorageUtility.isNotFoundError({ error })) {\n return error;\n }\n\n return getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[${operation}] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n // No transport for these: throwing beats returning undefined, which reads as a valid empty result.\n async copyObject(_opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void> {\n throw getError({\n message: `[${this.constructor.name}.copyObject] Server-side copy is not supported by this helper`,\n });\n }\n\n async presignPost(_opts: {\n bucket: IBucketRef;\n keyPrefix: string;\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n }): Promise<IPostPolicy> {\n throw getError({\n message: `[${this.constructor.name}.presignPost] Signed POST policies are not supported by this helper`,\n });\n }\n\n async presignPut(\n _opts: IObjectLocation & {\n expiresIn?: IDuration;\n tagging?: Record<string, string>;\n contentLength?: number;\n contentType?: string;\n },\n ): Promise<string> {\n throw getError({\n message: `[${this.constructor.name}.presignPut] Presigned PUT URLs are not supported by this helper`,\n });\n }\n\n async presignGet(\n _opts: IObjectLocation & { expiresIn?: IDuration; responseContentType?: string },\n ): Promise<string> {\n throw getError({\n message: `[${this.constructor.name}.presignGet] Presigned GET URLs are not supported by this helper`,\n });\n }\n\n async getObjectTags(_opts: IObjectLocation): Promise<Record<string, string>> {\n throw getError({\n message: `[${this.constructor.name}.getObjectTags] Object tagging is not supported by this helper`,\n });\n }\n\n async replaceObjectTags(\n _opts: IObjectLocation & { tags: Record<string, string> },\n ): Promise<void> {\n throw getError({\n message: `[${this.constructor.name}.replaceObjectTags] Object tagging is not supported by this helper`,\n });\n }\n\n abstract hasBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n abstract getBuckets(): Promise<IBucketInfo[]>;\n abstract getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n abstract createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n abstract removeBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n\n abstract getObject(opts: IObjectLocation & { options?: any }): Promise<Readable>;\n abstract getStat(opts: IObjectLocation): Promise<IFileStat>;\n abstract removeObject(opts: IObjectLocation): Promise<void>;\n abstract removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void>;\n abstract listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { getError } from '../../error/index.js';
2
2
  import { ErrorPrettier } from '../../logger/index.js';
3
+ import { EchoUtility } from '../../../utilities/echo.utility.js';
3
4
  import { S3Client } from 'bun';
4
5
  import { Readable } from 'node:stream';
5
6
  import { BaseStorageHelper } from '../base.js';
@@ -50,7 +51,7 @@ export class BunS3Helper extends BaseStorageHelper {
50
51
  // The bucket becomes a label of the host, so it must be one: anything else (a dot, a slash, an `@`, a port) would steer the request to another host.
51
52
  if (!S3_HOST_LABEL_PATTERN.test(opts.bucket)) {
52
53
  throw getError({
53
- message: `[objectEndpoint] A bucket used in a host must be one lower-case DNS label (a-z, 0-9, hyphen; 1-63 characters) | bucket: '${opts.bucket}'`,
54
+ message: `[objectEndpoint] A bucket used in a host must be one lower-case DNS label (a-z, 0-9, hyphen; 1-63 characters) | bucket: '${EchoUtility.toSafeText({ value: opts.bucket })}'`,
54
55
  });
55
56
  }
56
57
  const parsed = new URL(host);
@@ -94,7 +95,7 @@ export class BunS3Helper extends BaseStorageHelper {
94
95
  catch (error) {
95
96
  // A missing bucket is the answer; a credentials or network failure is not, and must not vanish.
96
97
  if (!StorageUtility.isNotFoundError({ error })) {
97
- this.logger.warn('[hasBucket] Cannot determine bucket existence - reporting false | bucket: %s | %s', name, ErrorPrettier.format({ error }));
98
+ this.logger.warn('[hasBucket] Cannot determine bucket existence - reporting false | bucket: %s | %s', EchoUtility.toSafeEcho({ value: name }), ErrorPrettier.format({ error }));
98
99
  }
99
100
  return false;
100
101
  }
@@ -211,7 +212,7 @@ export class BunS3Helper extends BaseStorageHelper {
211
212
  const response = await fetch(request.url, { method: 'PUT', headers: request.headers });
212
213
  if (!response.ok) {
213
214
  throw getError({
214
- message: `[copyObject] Copy failed | bucket: ${bucket.name} | source: ${source.key} | status: ${response.status}`,
215
+ message: `[copyObject] Copy failed | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | source: ${EchoUtility.toSafeText({ value: source.key })} | status: ${response.status}`,
215
216
  });
216
217
  }
217
218
  }
@@ -354,7 +355,9 @@ export class BunS3Helper extends BaseStorageHelper {
354
355
  const { bucket, object, source, contentType } = opts;
355
356
  // The same depth rule `upload` applies: one object, two doors, one answer.
356
357
  if (!this.isValidObjectKey({ object, maxDepth: opts.maxFolderDepth })) {
357
- throw getError({ message: `[writeStream] Invalid object name | key: ${object.key}` });
358
+ throw getError({
359
+ message: `[writeStream] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,
360
+ });
358
361
  }
359
362
  // Bun's `write` takes a Response, not a bare ReadableStream; wrapping streams, never buffers.
360
363
  const body = source instanceof ReadableStream ? new Response(source) : source;
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/bun-s3/helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EA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L,CAAC;YAED,iBAAiB,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,SAAS,CAAC;QACxF,CAAC,QAAQ,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,KAAK,EAAE;QAEtD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import type { IDuration } from '@/common';\nimport { getError } from '@/modules/error';\nimport { ErrorPrettier } from '@/modules/logger';\nimport { S3Client } from 'bun';\nimport { Readable } from 'node:stream';\nimport { BaseStorageHelper } from '../base';\nimport type {\n IBucketInfo,\n IBucketRef,\n IFileStat,\n IListObjectsOptions,\n IObjectInfo,\n IObjectLocation,\n IObjectRef,\n IPostPolicy,\n IStorageHelperOptions,\n IUploadFile,\n} from '../common';\nimport { S3Audiences, StorageUtility, StoragePresignDefaults } from '../common';\nimport type { TS3Audience } from '../common';\nimport { S3SignatureUtility } from './utility';\n\n/** One lower-case DNS label: the only shape a bucket may have when it becomes part of a host. */\nconst S3_HOST_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/** Options for `BunS3Helper`. Unset `partSize`, `queueSize` and `retry` leave Bun defaults in force. */\nexport interface IBunS3HelperOptions extends IStorageHelperOptions {\n accessKey: string;\n secretKey: string;\n /** @default 'us-east-1' */\n region?: string;\n sessionToken?: string;\n /** `default` is the host THIS process talks to; `public` is the host a browser is handed. `host` is inside every SigV4 signature, so a URL signed against an internal name cannot be rewritten later - which is why the two are separate rather than one value patched afterwards. */\n endpoint: {\n default: string;\n /** @default endpoint.default */\n public?: string;\n };\n\n /**\n * `https://<bucket>.<endpoint>/<key>` instead of `<endpoint>/<bucket>/<key>`. AWS requires it; MinIO and R2 do not.\n *\n * @default false\n */\n virtualHostedStyle?: boolean;\n partSize?: number;\n queueSize?: number;\n\n /** Retries Bun performs on a failed part before the write fails. */\n retry?: number;\n}\n\n/** Storage helper for S3-compatible object stores through Bun's `S3Client`. Uses separate hosts for calls this process makes and for URLs handed to browsers. */\nexport class BunS3Helper extends BaseStorageHelper {\n private client: S3Client;\n private credentials: {\n accessKey: string;\n secretKey: string;\n endpoint: { default: string; public: string };\n region: string;\n sessionToken?: string;\n virtualHostedStyle: boolean;\n };\n\n /** Undefined leaves Bun's own defaults in force. */\n private transfer: { partSize?: number; queueSize?: number; retry?: number };\n\n constructor(options: IBunS3HelperOptions) {\n super({\n scope: options.scope ?? BunS3Helper.name,\n identifier: options.identifier ?? BunS3Helper.name,\n });\n\n this.credentials = {\n accessKey: options.accessKey,\n secretKey: options.secretKey,\n endpoint: {\n default: options.endpoint.default,\n // Falls back to the default, so one reachable host still serves both audiences.\n public: options.endpoint.public ?? options.endpoint.default,\n },\n region: options.region ?? 'us-east-1',\n sessionToken: options.sessionToken,\n virtualHostedStyle: options.virtualHostedStyle ?? false,\n };\n\n this.transfer = {\n partSize: options.partSize,\n queueSize: options.queueSize,\n retry: options.retry,\n };\n\n this.client = new S3Client({\n accessKeyId: options.accessKey,\n secretAccessKey: options.secretKey,\n endpoint: options.endpoint.default,\n region: options.region,\n sessionToken: options.sessionToken,\n virtualHostedStyle: options.virtualHostedStyle,\n });\n }\n\n /** One bucket's objects, in either addressing style. `audience` picks the host: `server` for a call this process makes, `browser` for a URL it hands out. Virtual-hosted derives the per-bucket host, because the bucket arrives per call. */\n private objectEndpoint(opts: { bucket: string; audience: TS3Audience }): {\n endpoint: string;\n pathPrefix: string;\n } {\n const { endpoint, virtualHostedStyle } = this.credentials;\n const host = opts.audience === S3Audiences.BROWSER ? endpoint.public : endpoint.default;\n\n if (!virtualHostedStyle) {\n return { endpoint: host, pathPrefix: `/${opts.bucket}` };\n }\n\n // The bucket becomes a label of the host, so it must be one: anything else (a dot, a slash, an `@`, a port) would steer the request to another host.\n if (!S3_HOST_LABEL_PATTERN.test(opts.bucket)) {\n throw getError({\n message: `[objectEndpoint] A bucket used in a host must be one lower-case DNS label (a-z, 0-9, hyphen; 1-63 characters) | bucket: '${opts.bucket}'`,\n });\n }\n\n const parsed = new URL(host);\n parsed.hostname = `${opts.bucket}.${parsed.hostname}`;\n\n return { endpoint: parsed.origin, pathPrefix: '' };\n }\n\n /** Per-call overrides, so one client serves every bucket in either addressing style. */\n private presignOptions(opts: { bucket: string }): {\n bucket: string;\n endpoint: string;\n virtualHostedStyle?: boolean;\n } {\n const { virtualHostedStyle } = this.credentials;\n const { endpoint } = this.objectEndpoint({\n bucket: opts.bucket,\n audience: S3Audiences.BROWSER,\n });\n\n return {\n bucket: opts.bucket,\n endpoint,\n ...(virtualHostedStyle ? { virtualHostedStyle: true } : {}),\n };\n }\n\n /**\n * What a call this process makes on one bucket's objects (or its listing) passes to Bun's client. Path style needs only the\n * bucket. Virtual-hosted style needs the bucket's own host as well: Bun puts the bucket in neither the host nor the path in that\n * mode, so a call without it goes to the bare endpoint (`PUT /k.png` on the endpoint host) and never reaches the object.\n */\n private callOptions(opts: { bucket: string }): {\n bucket: string;\n endpoint?: string;\n virtualHostedStyle?: boolean;\n } {\n if (!this.credentials.virtualHostedStyle) {\n return { bucket: opts.bucket };\n }\n\n const { endpoint } = this.objectEndpoint({ bucket: opts.bucket, audience: S3Audiences.SERVER });\n\n return { bucket: opts.bucket, endpoint, virtualHostedStyle: true };\n }\n\n async hasBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return false;\n }\n\n try {\n await this.client.list({ maxKeys: 1 }, this.callOptions({ bucket: name }));\n\n return true;\n } catch (error) {\n // A missing bucket is the answer; a credentials or network failure is not, and must not vanish.\n if (!StorageUtility.isNotFoundError({ error })) {\n this.logger.warn(\n '[hasBucket] Cannot determine bucket existence - reporting false | bucket: %s | %s',\n name,\n ErrorPrettier.format({ error }),\n );\n }\n\n return false;\n }\n }\n\n async getBuckets(): Promise<IBucketInfo[]> {\n // A bucket operation is a call this process makes, so it goes to the default host.\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const endpoint = this.credentials.endpoint.default;\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'GET',\n endpoint,\n path: '/',\n accessKey,\n secretKey,\n region,\n sessionToken,\n });\n\n const response = await fetch(url, { method: 'GET', headers });\n const xml = await response.text();\n\n if (!response.ok) {\n throw getError({ message: `[getBuckets] S3 error: ${xml}` });\n }\n\n const buckets: IBucketInfo[] = [];\n const bucketMatches = xml.matchAll(\n /<Bucket>\\s*<Name>(.*?)<\\/Name>\\s*<CreationDate>(.*?)<\\/CreationDate>\\s*<\\/Bucket>/gs,\n );\n\n for (const match of bucketMatches) {\n buckets.push({\n name: match[1],\n creationDate: new Date(match[2]),\n });\n }\n\n return buckets;\n }\n\n /** S3 exposes a creation date only through `ListBuckets`, so one full listing is the cheapest correct answer. */\n async getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return null;\n }\n\n const buckets = await this.getBuckets();\n\n return buckets.find((bucket) => bucket.name === name) ?? null;\n }\n\n async createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({ message: '[createBucket] Invalid name to create bucket!' });\n }\n\n // A bucket operation is a call this process makes, so it goes to the default host.\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const endpoint = this.credentials.endpoint.default;\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'PUT',\n endpoint,\n path: `/${name}`,\n accessKey: accessKey,\n secretKey,\n region,\n sessionToken,\n });\n\n const response = await fetch(url, { method: 'PUT', headers });\n\n if (!response.ok) {\n const xml = await response.text();\n throw getError({ message: `[createBucket] S3 error: ${xml}` });\n }\n\n return this.getBucket(opts);\n }\n\n async removeBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({ message: '[removeBucket] Invalid name to remove bucket!' });\n }\n\n // A bucket operation is a call this process makes, so it goes to the default host.\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const endpoint = this.credentials.endpoint.default;\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'DELETE',\n endpoint,\n path: `/${name}`,\n accessKey: accessKey,\n secretKey: secretKey,\n region,\n sessionToken,\n });\n\n const response = await fetch(url, { method: 'DELETE', headers });\n\n if (!response.ok) {\n const xml = await response.text();\n throw getError({ message: `[removeBucket] S3 error: ${xml}` });\n }\n\n return true;\n }\n\n override async copyObject(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void> {\n const { bucket, source, destination } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucket.name,\n audience: S3Audiences.SERVER,\n });\n\n // `x-amz-copy-source` is what makes this server side: S3 reads the source itself, so a 500 MB\n // object never travels through this process. The encoded value is both signed and sent.\n const request = await S3SignatureUtility.buildSignedRequest({\n method: 'PUT',\n endpoint,\n path: `${pathPrefix}/${destination.key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n headers: {\n 'x-amz-copy-source': S3SignatureUtility.buildCopySource({\n bucket: bucket.name,\n key: source.key,\n }),\n },\n });\n\n const response = await fetch(request.url, { method: 'PUT', headers: request.headers });\n\n if (!response.ok) {\n throw getError({\n message: `[copyObject] Copy failed | bucket: ${bucket.name} | source: ${source.key} | status: ${response.status}`,\n });\n }\n }\n\n override async presignPost(opts: {\n bucket: IBucketRef;\n keyPrefix: string;\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n }): Promise<IPostPolicy> {\n const {\n bucket,\n keyPrefix,\n maxBytes,\n contentType,\n expiresIn = StoragePresignDefaults.POST_EXPIRES_IN,\n } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n\n // The browser posts to the BUCKET, not to an object - the key travels as a form field, because\n // the policy only constrains its prefix.\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucket.name,\n audience: S3Audiences.BROWSER,\n });\n const { formData, expiresAt } = await S3SignatureUtility.buildPostPolicy({\n bucket: bucket.name,\n keyPrefix,\n maxBytes,\n expiresInSeconds: StorageUtility.toExpirySeconds({ expiresIn, operation: 'presignPost' }),\n accessKey,\n secretKey,\n region,\n sessionToken,\n contentType,\n });\n\n return { postURL: `${endpoint.replace(/\\/$/, '')}${pathPrefix}`, formData, expiresAt };\n }\n\n override async presignPut(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n tagging?: Record<string, string>;\n contentLength?: number;\n contentType?: string;\n },\n ): Promise<string> {\n const {\n bucket,\n object,\n tagging,\n contentLength,\n contentType,\n expiresIn = StoragePresignDefaults.PUT_EXPIRES_IN,\n } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n\n // Not `client.presign`: its options are method and expiry only, and a tag that is merely SENT\n // is a tag S3 ignores. These two have to be inside the signature to exist at all.\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucket.name,\n audience: S3Audiences.BROWSER,\n });\n\n return S3SignatureUtility.buildPresignedUrl({\n method: 'PUT',\n endpoint,\n path: `${pathPrefix}/${object.key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n expiresInSeconds: StorageUtility.toExpirySeconds({ expiresIn, operation: 'presignPut' }),\n headers: {\n ...(tagging\n ? { 'x-amz-tagging': S3SignatureUtility.buildTaggingHeader({ tags: tagging }) }\n : {}),\n ...(contentLength === undefined ? {} : { 'content-length': String(contentLength) }),\n ...(contentType ? { 'content-type': contentType } : {}),\n },\n });\n }\n\n override async presignGet(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n responseContentType?: string;\n responseContentDisposition?: string;\n },\n ): Promise<string> {\n const {\n bucket,\n object,\n expiresIn = StoragePresignDefaults.GET_EXPIRES_IN,\n responseContentType,\n responseContentDisposition,\n } = opts;\n\n return this.client.presign(object.key, {\n ...this.presignOptions({ bucket: bucket.name }),\n method: 'GET',\n expiresIn: StorageUtility.toExpirySeconds({ expiresIn, operation: 'presignGet' }),\n ...(responseContentType ? { type: responseContentType } : {}),\n ...(responseContentDisposition ? { contentDisposition: responseContentDisposition } : {}),\n });\n }\n\n override async getObjectTags(opts: IObjectLocation): Promise<Record<string, string>> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucketName,\n audience: S3Audiences.SERVER,\n });\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'GET',\n endpoint,\n path: `${pathPrefix}/${key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n query: { tagging: '' },\n });\n\n const response = await fetch(url, { method: 'GET', headers });\n\n // S3 answers a missing tag set with 404: the empty case, not a failure.\n if (response.status === 404) {\n return {};\n }\n\n const body = await response.text();\n\n if (!response.ok) {\n throw getError({\n message: `[getObjectTags] S3 error | status: ${response.status} | body: ${body}`,\n });\n }\n\n return S3SignatureUtility.parseTaggingXml({ xml: body });\n }\n\n override async replaceObjectTags(\n opts: IObjectLocation & { tags: Record<string, string> },\n ): Promise<void> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const { tags } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucketName,\n audience: S3Audiences.SERVER,\n });\n const requestBody = S3SignatureUtility.buildTaggingXml({ tags });\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'PUT',\n endpoint,\n path: `${pathPrefix}/${key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n query: { tagging: '' },\n body: requestBody,\n });\n\n const response = await fetch(url, { method: 'PUT', headers, body: requestBody });\n\n if (!response.ok) {\n const body = await response.text();\n throw getError({\n message: `[replaceObjectTags] S3 error | status: ${response.status} | body: ${body}`,\n });\n }\n }\n\n protected get defaultLinkPrefix(): string {\n return '/static-assets/';\n }\n\n protected async writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void> {\n const { file } = opts;\n const bucketName = opts.bucket.name;\n const { mimetype: mimeType, buffer } = file;\n\n await this.client.write(opts.object.key, buffer, {\n ...this.callOptions({ bucket: bucketName }),\n type: mimeType,\n partSize: this.transfer.partSize,\n queueSize: this.transfer.queueSize,\n retry: this.transfer.retry,\n });\n }\n\n /** Streams without holding the object in memory. `upload` carries a `Buffer`, so it cannot; this is the path for anything large. */\n override async writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n maxFolderDepth?: number;\n },\n ): Promise<void> {\n const { bucket, object, source, contentType } = opts;\n\n // The same depth rule `upload` applies: one object, two doors, one answer.\n if (!this.isValidObjectKey({ object, maxDepth: opts.maxFolderDepth })) {\n throw getError({ message: `[writeStream] Invalid object name | key: ${object.key}` });\n }\n\n // Bun's `write` takes a Response, not a bare ReadableStream; wrapping streams, never buffers.\n const body = source instanceof ReadableStream ? new Response(source) : source;\n\n await this.client.write(object.key, body, {\n ...this.callOptions({ bucket: bucket.name }),\n ...(contentType ? { type: contentType } : {}),\n partSize: this.transfer.partSize,\n queueSize: this.transfer.queueSize,\n retry: this.transfer.retry,\n });\n }\n\n /** `S3File.stream()` is lazy: it reaches the network on first read, so a `try` here never sees a 404 - the failure arrives on the stream. */\n async getObject(opts: IObjectLocation & { options?: any }): Promise<Readable> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const source = this.client.file(key, this.callOptions({ bucket: bucketName })).stream();\n\n return Readable.fromWeb(source as ReadableStream<Uint8Array>, {\n // Keeps backpressure meaningful rather than draining S3 into memory.\n objectMode: false,\n });\n }\n\n /** The conversion-free path a `Response` body wants. `slice` makes it a ranged GET, so only the requested bytes leave S3. */\n override async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const { range } = opts;\n const file = this.client.file(key, this.callOptions({ bucket: bucketName }));\n\n if (!range) {\n return file.stream() as ReadableStream<Uint8Array>;\n }\n\n // HTTP ranges include `end`; `slice` excludes it.\n const window =\n range.end === undefined ? file.slice(range.start) : file.slice(range.start, range.end + 1);\n\n return window.stream() as ReadableStream<Uint8Array>;\n }\n\n async getStat(opts: IObjectLocation): Promise<IFileStat> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n\n try {\n const stat = await this.client.stat(key, this.callOptions({ bucket: bucketName }));\n\n return {\n size: stat.size,\n // One key, not two spellings. The served type comes from the object name; this is diagnostic.\n metadata: { mimetype: stat.type },\n lastModified: stat.lastModified,\n etag: stat.etag,\n };\n } catch (error) {\n throw this.asStorageError({\n error,\n operation: 'getStat',\n bucket: opts.bucket,\n object: opts.object,\n });\n }\n }\n\n async removeObject(opts: IObjectLocation): Promise<void> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n\n try {\n await this.client.delete(key, this.callOptions({ bucket: bucketName }));\n } catch (error) {\n throw this.asStorageError({\n error,\n operation: 'removeObject',\n bucket: opts.bucket,\n object: opts.object,\n });\n }\n }\n\n async removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void> {\n const { bucket, objects } = opts;\n\n await this.mapWithConcurrency({\n items: objects,\n task: ({ item: object }) => this.removeObject({ bucket, object }),\n });\n }\n\n /** S3 caps a call at 1000 keys and continues through `nextContinuationToken`. `useRecursive: false` maps to `delimiter: '/'`. */\n async listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]> {\n const { prefix, useRecursive = false, maxKeys } = opts;\n const bucketName = opts.bucket.name;\n\n // `maxKeys: 0` means zero, not unlimited.\n const limit = maxKeys ?? Number.POSITIVE_INFINITY;\n\n if (limit <= 0) {\n return [];\n }\n\n const objects: IObjectInfo[] = [];\n let continuationToken: string | undefined;\n\n do {\n const remaining = limit - objects.length;\n const response = await this.client.list(\n {\n prefix,\n continuationToken,\n ...(useRecursive ? {} : { delimiter: '/' }),\n ...(Number.isFinite(remaining) ? { maxKeys: Math.min(remaining, 1000) } : {}),\n },\n this.callOptions({ bucket: bucketName }),\n );\n\n const responseContents = response.contents ?? [];\n\n for (const entry of responseContents) {\n objects.push({\n name: entry.key,\n size: entry.size,\n lastModified: entry.lastModified ? new Date(entry.lastModified) : undefined,\n etag: entry.eTag,\n });\n }\n\n continuationToken = response.isTruncated ? response.nextContinuationToken : undefined;\n } while (continuationToken && objects.length < limit);\n\n return objects;\n }\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/bun-s3/helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAa5C,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAEhF,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAE/C,iGAAiG;AACjG,MAAM,qBAAqB,GAAG,wCAAwC,CAAC;AA6BvE,iKAAiK;AACjK,MAAM,OAAO,WAAY,SAAQ,iBAAiB;IAchD,YAAY,OAA4B;QACtC,KAAK,CAAC;YACJ,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,WAAW,CAAC,IAAI;YACxC,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,WAAW,CAAC,IAAI;SACnD,CAAC,CAAC;QAEH,IAAI,CAAC,WAAW,GAAG;YACjB,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,SAAS,EAAE,OAAO,CAAC,SA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rC;gBACE,MAAM;gBACN,iBAAiB;gBACjB,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;gBAC3C,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC9E,EACD,IAAI,CAAC,WAAW,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CACzC,CAAC;YAEF,MAAM,gBAAgB,GAAG,QAAQ,CAAC,QAAQ,IAAI,EAAE,CAAC;YAEjD,KAAK,MAAM,KAAK,IAAI,gBAAgB,EAAE,CAAC;gBACrC,OAAO,CAAC,IAAI,CAAC;oBACX,IAAI,EAAE,KAAK,CAAC,GAAG;oBACf,IAAI,EAAE,KAAK,CAAC,IAAI;oBAChB,YAAY,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS;oBAC3E,IAAI,EAAE,KAAK,CAAC,IAAI;iBACjB,CAAC,CAAC;YACL,CAAC;YAED,iBAAiB,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,SAAS,CAAC;QACxF,CAAC,QAAQ,iBAAiB,IAAI,OAAO,CAAC,MAAM,GAAG,KAAK,EAAE;QAEtD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import type { IDuration } from '@/common';\nimport { getError } from '@/modules/error';\nimport { ErrorPrettier } from '@/modules/logger';\nimport { EchoUtility } from '@/utilities/echo.utility';\nimport { S3Client } from 'bun';\nimport { Readable } from 'node:stream';\nimport { BaseStorageHelper } from '../base';\nimport type {\n IBucketInfo,\n IBucketRef,\n IFileStat,\n IListObjectsOptions,\n IObjectInfo,\n IObjectLocation,\n IObjectRef,\n IPostPolicy,\n IStorageHelperOptions,\n IUploadFile,\n} from '../common';\nimport { S3Audiences, StorageUtility, StoragePresignDefaults } from '../common';\nimport type { TS3Audience } from '../common';\nimport { S3SignatureUtility } from './utility';\n\n/** One lower-case DNS label: the only shape a bucket may have when it becomes part of a host. */\nconst S3_HOST_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/** Options for `BunS3Helper`. Unset `partSize`, `queueSize` and `retry` leave Bun defaults in force. */\nexport interface IBunS3HelperOptions extends IStorageHelperOptions {\n accessKey: string;\n secretKey: string;\n /** @default 'us-east-1' */\n region?: string;\n sessionToken?: string;\n /** `default` is the host THIS process talks to; `public` is the host a browser is handed. `host` is inside every SigV4 signature, so a URL signed against an internal name cannot be rewritten later - which is why the two are separate rather than one value patched afterwards. */\n endpoint: {\n default: string;\n /** @default endpoint.default */\n public?: string;\n };\n\n /**\n * `https://<bucket>.<endpoint>/<key>` instead of `<endpoint>/<bucket>/<key>`. AWS requires it; MinIO and R2 do not.\n *\n * @default false\n */\n virtualHostedStyle?: boolean;\n partSize?: number;\n queueSize?: number;\n\n /** Retries Bun performs on a failed part before the write fails. */\n retry?: number;\n}\n\n/** Storage helper for S3-compatible object stores through Bun's `S3Client`. Uses separate hosts for calls this process makes and for URLs handed to browsers. */\nexport class BunS3Helper extends BaseStorageHelper {\n private client: S3Client;\n private credentials: {\n accessKey: string;\n secretKey: string;\n endpoint: { default: string; public: string };\n region: string;\n sessionToken?: string;\n virtualHostedStyle: boolean;\n };\n\n /** Undefined leaves Bun's own defaults in force. */\n private transfer: { partSize?: number; queueSize?: number; retry?: number };\n\n constructor(options: IBunS3HelperOptions) {\n super({\n scope: options.scope ?? BunS3Helper.name,\n identifier: options.identifier ?? BunS3Helper.name,\n });\n\n this.credentials = {\n accessKey: options.accessKey,\n secretKey: options.secretKey,\n endpoint: {\n default: options.endpoint.default,\n // Falls back to the default, so one reachable host still serves both audiences.\n public: options.endpoint.public ?? options.endpoint.default,\n },\n region: options.region ?? 'us-east-1',\n sessionToken: options.sessionToken,\n virtualHostedStyle: options.virtualHostedStyle ?? false,\n };\n\n this.transfer = {\n partSize: options.partSize,\n queueSize: options.queueSize,\n retry: options.retry,\n };\n\n this.client = new S3Client({\n accessKeyId: options.accessKey,\n secretAccessKey: options.secretKey,\n endpoint: options.endpoint.default,\n region: options.region,\n sessionToken: options.sessionToken,\n virtualHostedStyle: options.virtualHostedStyle,\n });\n }\n\n /** One bucket's objects, in either addressing style. `audience` picks the host: `server` for a call this process makes, `browser` for a URL it hands out. Virtual-hosted derives the per-bucket host, because the bucket arrives per call. */\n private objectEndpoint(opts: { bucket: string; audience: TS3Audience }): {\n endpoint: string;\n pathPrefix: string;\n } {\n const { endpoint, virtualHostedStyle } = this.credentials;\n const host = opts.audience === S3Audiences.BROWSER ? endpoint.public : endpoint.default;\n\n if (!virtualHostedStyle) {\n return { endpoint: host, pathPrefix: `/${opts.bucket}` };\n }\n\n // The bucket becomes a label of the host, so it must be one: anything else (a dot, a slash, an `@`, a port) would steer the request to another host.\n if (!S3_HOST_LABEL_PATTERN.test(opts.bucket)) {\n throw getError({\n message: `[objectEndpoint] A bucket used in a host must be one lower-case DNS label (a-z, 0-9, hyphen; 1-63 characters) | bucket: '${EchoUtility.toSafeText({ value: opts.bucket })}'`,\n });\n }\n\n const parsed = new URL(host);\n parsed.hostname = `${opts.bucket}.${parsed.hostname}`;\n\n return { endpoint: parsed.origin, pathPrefix: '' };\n }\n\n /** Per-call overrides, so one client serves every bucket in either addressing style. */\n private presignOptions(opts: { bucket: string }): {\n bucket: string;\n endpoint: string;\n virtualHostedStyle?: boolean;\n } {\n const { virtualHostedStyle } = this.credentials;\n const { endpoint } = this.objectEndpoint({\n bucket: opts.bucket,\n audience: S3Audiences.BROWSER,\n });\n\n return {\n bucket: opts.bucket,\n endpoint,\n ...(virtualHostedStyle ? { virtualHostedStyle: true } : {}),\n };\n }\n\n /**\n * What a call this process makes on one bucket's objects (or its listing) passes to Bun's client. Path style needs only the\n * bucket. Virtual-hosted style needs the bucket's own host as well: Bun puts the bucket in neither the host nor the path in that\n * mode, so a call without it goes to the bare endpoint (`PUT /k.png` on the endpoint host) and never reaches the object.\n */\n private callOptions(opts: { bucket: string }): {\n bucket: string;\n endpoint?: string;\n virtualHostedStyle?: boolean;\n } {\n if (!this.credentials.virtualHostedStyle) {\n return { bucket: opts.bucket };\n }\n\n const { endpoint } = this.objectEndpoint({ bucket: opts.bucket, audience: S3Audiences.SERVER });\n\n return { bucket: opts.bucket, endpoint, virtualHostedStyle: true };\n }\n\n async hasBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return false;\n }\n\n try {\n await this.client.list({ maxKeys: 1 }, this.callOptions({ bucket: name }));\n\n return true;\n } catch (error) {\n // A missing bucket is the answer; a credentials or network failure is not, and must not vanish.\n if (!StorageUtility.isNotFoundError({ error })) {\n this.logger.warn(\n '[hasBucket] Cannot determine bucket existence - reporting false | bucket: %s | %s',\n EchoUtility.toSafeEcho({ value: name }),\n ErrorPrettier.format({ error }),\n );\n }\n\n return false;\n }\n }\n\n async getBuckets(): Promise<IBucketInfo[]> {\n // A bucket operation is a call this process makes, so it goes to the default host.\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const endpoint = this.credentials.endpoint.default;\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'GET',\n endpoint,\n path: '/',\n accessKey,\n secretKey,\n region,\n sessionToken,\n });\n\n const response = await fetch(url, { method: 'GET', headers });\n const xml = await response.text();\n\n if (!response.ok) {\n throw getError({ message: `[getBuckets] S3 error: ${xml}` });\n }\n\n const buckets: IBucketInfo[] = [];\n const bucketMatches = xml.matchAll(\n /<Bucket>\\s*<Name>(.*?)<\\/Name>\\s*<CreationDate>(.*?)<\\/CreationDate>\\s*<\\/Bucket>/gs,\n );\n\n for (const match of bucketMatches) {\n buckets.push({\n name: match[1],\n creationDate: new Date(match[2]),\n });\n }\n\n return buckets;\n }\n\n /** S3 exposes a creation date only through `ListBuckets`, so one full listing is the cheapest correct answer. */\n async getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return null;\n }\n\n const buckets = await this.getBuckets();\n\n return buckets.find((bucket) => bucket.name === name) ?? null;\n }\n\n async createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({ message: '[createBucket] Invalid name to create bucket!' });\n }\n\n // A bucket operation is a call this process makes, so it goes to the default host.\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const endpoint = this.credentials.endpoint.default;\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'PUT',\n endpoint,\n path: `/${name}`,\n accessKey: accessKey,\n secretKey,\n region,\n sessionToken,\n });\n\n const response = await fetch(url, { method: 'PUT', headers });\n\n if (!response.ok) {\n const xml = await response.text();\n throw getError({ message: `[createBucket] S3 error: ${xml}` });\n }\n\n return this.getBucket(opts);\n }\n\n async removeBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({ message: '[removeBucket] Invalid name to remove bucket!' });\n }\n\n // A bucket operation is a call this process makes, so it goes to the default host.\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const endpoint = this.credentials.endpoint.default;\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'DELETE',\n endpoint,\n path: `/${name}`,\n accessKey: accessKey,\n secretKey: secretKey,\n region,\n sessionToken,\n });\n\n const response = await fetch(url, { method: 'DELETE', headers });\n\n if (!response.ok) {\n const xml = await response.text();\n throw getError({ message: `[removeBucket] S3 error: ${xml}` });\n }\n\n return true;\n }\n\n override async copyObject(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void> {\n const { bucket, source, destination } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucket.name,\n audience: S3Audiences.SERVER,\n });\n\n // `x-amz-copy-source` is what makes this server side: S3 reads the source itself, so a 500 MB\n // object never travels through this process. The encoded value is both signed and sent.\n const request = await S3SignatureUtility.buildSignedRequest({\n method: 'PUT',\n endpoint,\n path: `${pathPrefix}/${destination.key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n headers: {\n 'x-amz-copy-source': S3SignatureUtility.buildCopySource({\n bucket: bucket.name,\n key: source.key,\n }),\n },\n });\n\n const response = await fetch(request.url, { method: 'PUT', headers: request.headers });\n\n if (!response.ok) {\n throw getError({\n message: `[copyObject] Copy failed | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | source: ${EchoUtility.toSafeText({ value: source.key })} | status: ${response.status}`,\n });\n }\n }\n\n override async presignPost(opts: {\n bucket: IBucketRef;\n keyPrefix: string;\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n }): Promise<IPostPolicy> {\n const {\n bucket,\n keyPrefix,\n maxBytes,\n contentType,\n expiresIn = StoragePresignDefaults.POST_EXPIRES_IN,\n } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n\n // The browser posts to the BUCKET, not to an object - the key travels as a form field, because\n // the policy only constrains its prefix.\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucket.name,\n audience: S3Audiences.BROWSER,\n });\n const { formData, expiresAt } = await S3SignatureUtility.buildPostPolicy({\n bucket: bucket.name,\n keyPrefix,\n maxBytes,\n expiresInSeconds: StorageUtility.toExpirySeconds({ expiresIn, operation: 'presignPost' }),\n accessKey,\n secretKey,\n region,\n sessionToken,\n contentType,\n });\n\n return { postURL: `${endpoint.replace(/\\/$/, '')}${pathPrefix}`, formData, expiresAt };\n }\n\n override async presignPut(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n tagging?: Record<string, string>;\n contentLength?: number;\n contentType?: string;\n },\n ): Promise<string> {\n const {\n bucket,\n object,\n tagging,\n contentLength,\n contentType,\n expiresIn = StoragePresignDefaults.PUT_EXPIRES_IN,\n } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n\n // Not `client.presign`: its options are method and expiry only, and a tag that is merely SENT\n // is a tag S3 ignores. These two have to be inside the signature to exist at all.\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucket.name,\n audience: S3Audiences.BROWSER,\n });\n\n return S3SignatureUtility.buildPresignedUrl({\n method: 'PUT',\n endpoint,\n path: `${pathPrefix}/${object.key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n expiresInSeconds: StorageUtility.toExpirySeconds({ expiresIn, operation: 'presignPut' }),\n headers: {\n ...(tagging\n ? { 'x-amz-tagging': S3SignatureUtility.buildTaggingHeader({ tags: tagging }) }\n : {}),\n ...(contentLength === undefined ? {} : { 'content-length': String(contentLength) }),\n ...(contentType ? { 'content-type': contentType } : {}),\n },\n });\n }\n\n override async presignGet(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n responseContentType?: string;\n responseContentDisposition?: string;\n },\n ): Promise<string> {\n const {\n bucket,\n object,\n expiresIn = StoragePresignDefaults.GET_EXPIRES_IN,\n responseContentType,\n responseContentDisposition,\n } = opts;\n\n return this.client.presign(object.key, {\n ...this.presignOptions({ bucket: bucket.name }),\n method: 'GET',\n expiresIn: StorageUtility.toExpirySeconds({ expiresIn, operation: 'presignGet' }),\n ...(responseContentType ? { type: responseContentType } : {}),\n ...(responseContentDisposition ? { contentDisposition: responseContentDisposition } : {}),\n });\n }\n\n override async getObjectTags(opts: IObjectLocation): Promise<Record<string, string>> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucketName,\n audience: S3Audiences.SERVER,\n });\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'GET',\n endpoint,\n path: `${pathPrefix}/${key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n query: { tagging: '' },\n });\n\n const response = await fetch(url, { method: 'GET', headers });\n\n // S3 answers a missing tag set with 404: the empty case, not a failure.\n if (response.status === 404) {\n return {};\n }\n\n const body = await response.text();\n\n if (!response.ok) {\n throw getError({\n message: `[getObjectTags] S3 error | status: ${response.status} | body: ${body}`,\n });\n }\n\n return S3SignatureUtility.parseTaggingXml({ xml: body });\n }\n\n override async replaceObjectTags(\n opts: IObjectLocation & { tags: Record<string, string> },\n ): Promise<void> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const { tags } = opts;\n const { accessKey, secretKey, region, sessionToken } = this.credentials;\n const { endpoint, pathPrefix } = this.objectEndpoint({\n bucket: bucketName,\n audience: S3Audiences.SERVER,\n });\n const requestBody = S3SignatureUtility.buildTaggingXml({ tags });\n\n const { url, headers } = await S3SignatureUtility.buildSignedRequest({\n method: 'PUT',\n endpoint,\n path: `${pathPrefix}/${key}`,\n accessKey,\n secretKey,\n region,\n sessionToken,\n query: { tagging: '' },\n body: requestBody,\n });\n\n const response = await fetch(url, { method: 'PUT', headers, body: requestBody });\n\n if (!response.ok) {\n const body = await response.text();\n throw getError({\n message: `[replaceObjectTags] S3 error | status: ${response.status} | body: ${body}`,\n });\n }\n }\n\n protected get defaultLinkPrefix(): string {\n return '/static-assets/';\n }\n\n protected async writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void> {\n const { file } = opts;\n const bucketName = opts.bucket.name;\n const { mimetype: mimeType, buffer } = file;\n\n await this.client.write(opts.object.key, buffer, {\n ...this.callOptions({ bucket: bucketName }),\n type: mimeType,\n partSize: this.transfer.partSize,\n queueSize: this.transfer.queueSize,\n retry: this.transfer.retry,\n });\n }\n\n /** Streams without holding the object in memory. `upload` carries a `Buffer`, so it cannot; this is the path for anything large. */\n override async writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n maxFolderDepth?: number;\n },\n ): Promise<void> {\n const { bucket, object, source, contentType } = opts;\n\n // The same depth rule `upload` applies: one object, two doors, one answer.\n if (!this.isValidObjectKey({ object, maxDepth: opts.maxFolderDepth })) {\n throw getError({\n message: `[writeStream] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n // Bun's `write` takes a Response, not a bare ReadableStream; wrapping streams, never buffers.\n const body = source instanceof ReadableStream ? new Response(source) : source;\n\n await this.client.write(object.key, body, {\n ...this.callOptions({ bucket: bucket.name }),\n ...(contentType ? { type: contentType } : {}),\n partSize: this.transfer.partSize,\n queueSize: this.transfer.queueSize,\n retry: this.transfer.retry,\n });\n }\n\n /** `S3File.stream()` is lazy: it reaches the network on first read, so a `try` here never sees a 404 - the failure arrives on the stream. */\n async getObject(opts: IObjectLocation & { options?: any }): Promise<Readable> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const source = this.client.file(key, this.callOptions({ bucket: bucketName })).stream();\n\n return Readable.fromWeb(source as ReadableStream<Uint8Array>, {\n // Keeps backpressure meaningful rather than draining S3 into memory.\n objectMode: false,\n });\n }\n\n /** The conversion-free path a `Response` body wants. `slice` makes it a ranged GET, so only the requested bytes leave S3. */\n override async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n const { range } = opts;\n const file = this.client.file(key, this.callOptions({ bucket: bucketName }));\n\n if (!range) {\n return file.stream() as ReadableStream<Uint8Array>;\n }\n\n // HTTP ranges include `end`; `slice` excludes it.\n const window =\n range.end === undefined ? file.slice(range.start) : file.slice(range.start, range.end + 1);\n\n return window.stream() as ReadableStream<Uint8Array>;\n }\n\n async getStat(opts: IObjectLocation): Promise<IFileStat> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n\n try {\n const stat = await this.client.stat(key, this.callOptions({ bucket: bucketName }));\n\n return {\n size: stat.size,\n // One key, not two spellings. The served type comes from the object name; this is diagnostic.\n metadata: { mimetype: stat.type },\n lastModified: stat.lastModified,\n etag: stat.etag,\n };\n } catch (error) {\n throw this.asStorageError({\n error,\n operation: 'getStat',\n bucket: opts.bucket,\n object: opts.object,\n });\n }\n }\n\n async removeObject(opts: IObjectLocation): Promise<void> {\n const bucketName = opts.bucket.name;\n const key = opts.object.key;\n\n try {\n await this.client.delete(key, this.callOptions({ bucket: bucketName }));\n } catch (error) {\n throw this.asStorageError({\n error,\n operation: 'removeObject',\n bucket: opts.bucket,\n object: opts.object,\n });\n }\n }\n\n async removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void> {\n const { bucket, objects } = opts;\n\n await this.mapWithConcurrency({\n items: objects,\n task: ({ item: object }) => this.removeObject({ bucket, object }),\n });\n }\n\n /** S3 caps a call at 1000 keys and continues through `nextContinuationToken`. `useRecursive: false` maps to `delimiter: '/'`. */\n async listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]> {\n const { prefix, useRecursive = false, maxKeys } = opts;\n const bucketName = opts.bucket.name;\n\n // `maxKeys: 0` means zero, not unlimited.\n const limit = maxKeys ?? Number.POSITIVE_INFINITY;\n\n if (limit <= 0) {\n return [];\n }\n\n const objects: IObjectInfo[] = [];\n let continuationToken: string | undefined;\n\n do {\n const remaining = limit - objects.length;\n const response = await this.client.list(\n {\n prefix,\n continuationToken,\n ...(useRecursive ? {} : { delimiter: '/' }),\n ...(Number.isFinite(remaining) ? { maxKeys: Math.min(remaining, 1000) } : {}),\n },\n this.callOptions({ bucket: bucketName }),\n );\n\n const responseContents = response.contents ?? [];\n\n for (const entry of responseContents) {\n objects.push({\n name: entry.key,\n size: entry.size,\n lastModified: entry.lastModified ? new Date(entry.lastModified) : undefined,\n etag: entry.eTag,\n });\n }\n\n continuationToken = response.isTruncated ? response.nextContinuationToken : undefined;\n } while (continuationToken && objects.length < limit);\n\n return objects;\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { HTTP } from '../../../common/constants/http.js';
2
2
  import { getError } from '../../error/index.js';
3
3
  import { ErrorPrettier } from '../../logger/index.js';
4
+ import { EchoUtility } from '../../../utilities/echo.utility.js';
4
5
  import fs from 'node:fs';
5
6
  import fsp from 'node:fs/promises';
6
7
  import path from 'node:path';
@@ -73,7 +74,9 @@ export class DiskHelper extends BaseStorageHelper {
73
74
  toRealPathError(opts) {
74
75
  const { error } = opts;
75
76
  const code = error?.code ?? 'UNKNOWN';
76
- this.logger.error('Cannot resolve the real path of a storage target | code: %s | %s', code, error);
77
+ this.logger.error('Cannot resolve the real path of a storage target | code: %s | %s', code,
78
+ // A system error quotes the path it failed on; the path is a caller's key under the storage root.
79
+ EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }));
77
80
  // A server-side fault, not the caller's: the default status of `getError` is a 400.
78
81
  return getError({
79
82
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
@@ -104,7 +107,9 @@ export class DiskHelper extends BaseStorageHelper {
104
107
  const objectPath = this.resolveObjectPath(opts);
105
108
  const result = await this.isInsideRoot({ target: objectPath });
106
109
  if (!result) {
107
- throw getError({ message: `[storage] Invalid object name | key: ${opts.object.key}` });
110
+ throw getError({
111
+ message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: opts.object.key })}`,
112
+ });
108
113
  }
109
114
  return objectPath;
110
115
  }
@@ -112,15 +117,21 @@ export class DiskHelper extends BaseStorageHelper {
112
117
  resolveObjectPath(opts) {
113
118
  const { bucket, object } = opts;
114
119
  if (!this.isValidBucketName({ bucket })) {
115
- throw getError({ message: `[storage] Invalid bucket name | bucket: ${bucket.name}` });
120
+ throw getError({
121
+ message: `[storage] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,
122
+ });
116
123
  }
117
124
  if (!this.isValidObjectKey({ object, maxDepth: Number.MAX_SAFE_INTEGER })) {
118
- throw getError({ message: `[storage] Invalid object name | key: ${object.key}` });
125
+ throw getError({
126
+ message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,
127
+ });
119
128
  }
120
129
  const bucketPath = this.getBucketPath({ bucket });
121
130
  const objectPath = path.resolve(bucketPath, object.key);
122
131
  if (objectPath !== bucketPath && !objectPath.startsWith(`${bucketPath}${path.sep}`)) {
123
- throw getError({ message: `[storage] Invalid object name | key: ${object.key}` });
132
+ throw getError({
133
+ message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,
134
+ });
124
135
  }
125
136
  return objectPath;
126
137
  }
@@ -133,7 +144,9 @@ export class DiskHelper extends BaseStorageHelper {
133
144
  }
134
145
  catch (error) {
135
146
  if (error?.code !== 'ENOENT') {
136
- this.logger.warn('[statOrNull] Cannot determine existence, reporting missing | path: %s | %s', target, ErrorPrettier.format({ error }));
147
+ this.logger.warn('[statOrNull] Cannot determine existence, reporting missing | path: %s | %s', EchoUtility.toSafeEcho({ value: target }),
148
+ // The error's own text quotes the path, so it is escaped like the path is.
149
+ EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }));
137
150
  }
138
151
  return null;
139
152
  }
@@ -207,7 +220,7 @@ export class DiskHelper extends BaseStorageHelper {
207
220
  const result = await this.exists({ target: bucketPath });
208
221
  if (result) {
209
222
  throw getError({
210
- message: `[createBucket] Bucket already exists | name: ${name}`,
223
+ message: `[createBucket] Bucket already exists | name: ${EchoUtility.toSafeText({ value: name })}`,
211
224
  });
212
225
  }
213
226
  await fsp.mkdir(bucketPath, { recursive: true });
@@ -224,13 +237,13 @@ export class DiskHelper extends BaseStorageHelper {
224
237
  const result = await this.isReachableBucketPath({ target: bucketPath });
225
238
  if (!result) {
226
239
  throw getError({
227
- message: `[removeBucket] Bucket does not exist | name: ${name}`,
240
+ message: `[removeBucket] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: name })}`,
228
241
  });
229
242
  }
230
243
  const files = await fsp.readdir(bucketPath);
231
244
  if (files.length > 0) {
232
245
  throw getError({
233
- message: `[removeBucket] Bucket is not empty | name: ${name}`,
246
+ message: `[removeBucket] Bucket is not empty | name: ${EchoUtility.toSafeText({ value: name })}`,
234
247
  });
235
248
  }
236
249
  await fsp.rmdir(bucketPath);
@@ -254,7 +267,7 @@ export class DiskHelper extends BaseStorageHelper {
254
267
  if (!result) {
255
268
  throw getError({
256
269
  error: StorageErrors.OBJECT_NOT_FOUND,
257
- message: `[getObject] Object not found | bucket: ${bucket.name} | key: ${object.key}`,
270
+ message: `[getObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,
258
271
  });
259
272
  }
260
273
  return fs.createReadStream(objectPath);
@@ -267,7 +280,7 @@ export class DiskHelper extends BaseStorageHelper {
267
280
  if (!result) {
268
281
  throw getError({
269
282
  error: StorageErrors.OBJECT_NOT_FOUND,
270
- message: `[getObjectStream] Object not found | bucket: ${bucket.name} | key: ${object.key}`,
283
+ message: `[getObjectStream] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,
271
284
  });
272
285
  }
273
286
  const source = fs.createReadStream(objectPath, range ? { start: range.start, end: range.end } : {});
@@ -280,7 +293,7 @@ export class DiskHelper extends BaseStorageHelper {
280
293
  if (!stat?.isFile()) {
281
294
  throw getError({
282
295
  error: StorageErrors.OBJECT_NOT_FOUND,
283
- message: `[getStat] Object not found | bucket: ${bucket.name} | key: ${object.key}`,
296
+ message: `[getStat] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,
284
297
  });
285
298
  }
286
299
  return {
@@ -298,7 +311,7 @@ export class DiskHelper extends BaseStorageHelper {
298
311
  if (!result) {
299
312
  throw getError({
300
313
  error: StorageErrors.OBJECT_NOT_FOUND,
301
- message: `[removeObject] Object not found | bucket: ${bucket.name} | key: ${object.key}`,
314
+ message: `[removeObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,
302
315
  });
303
316
  }
304
317
  await fsp.unlink(objectPath);
@@ -314,7 +327,9 @@ export class DiskHelper extends BaseStorageHelper {
314
327
  async listObjects(opts) {
315
328
  const { bucket, prefix = '', useRecursive = false, maxKeys } = opts;
316
329
  if (!this.isValidBucketName({ bucket })) {
317
- throw getError({ message: `[listObjects] Invalid bucket name | bucket: ${bucket.name}` });
330
+ throw getError({
331
+ message: `[listObjects] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,
332
+ });
318
333
  }
319
334
  // `maxKeys: 0` means zero, not unlimited.
320
335
  const limit = maxKeys ?? Number.POSITIVE_INFINITY;
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/disk/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,GAAG,MAAM,kBAAkB,CAAC;AAEnC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAUL,aAAa,GACd,MAAM,WAAW,CAAC;AAQnB,kNAAkN;AAClN,MAAM,OAAO,UAAW,SAAQ,iBAAiB;IAG/C,YAAY,OAA2B;QACrC,KAAK,CAAC;YACJ,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,UAAU,CAAC,IAAI;YACvC,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,UAAU,CAAC,IAAI;SAClD,CAAC,CAAC;QACH,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AS,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;gBAExD,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;oBACxB,oEAAoE;oBACpE,MAAM,QAAQ,GAAG,CAAC,MAAM,IAAI,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;oBAEvF,IAAI,YAAY,IAAI,QAAQ,EAAE,CAAC;wBAC7B,MAAM,aAAa,CAAC,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;oBAC5E,CAAC;oBAED,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;oBAChE,SAAS;gBACX,CAAC;gBAED,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;gBAE1D,IAAI,CAAC,IAAI,EAAE,CAAC;oBACV,SAAS;gBACX,CAAC;gBAED,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;YAC9E,CAAC;QACH,CAAC,CAAC;QAEF,MAAM,aAAa,CAAC,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;QAEzD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport { ErrorPrettier } from '@/modules/logger';\nimport fs from 'node:fs';\nimport fsp from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport { BaseStorageHelper } from '../base';\nimport {\n type IBucketInfo,\n type IBucketRef,\n type IFileStat,\n type IListObjectsOptions,\n type IObjectInfo,\n type IObjectLocation,\n type IObjectRef,\n type IStorageHelperOptions,\n type IUploadFile,\n StorageErrors,\n} from '../common';\n\n/** Options for `DiskHelper`; `basePath` is created when missing. */\nexport interface IDiskHelperOptions extends IStorageHelperOptions {\n /** Base directory every bucket lives under. */\n basePath: string;\n}\n\n/** Storage backed by the local filesystem: each bucket is a directory under `basePath`, each object a file whose key is its relative path. Names are validated and resolved paths must stay inside the bucket. */\nexport class DiskHelper extends BaseStorageHelper {\n private basePath: string;\n\n constructor(options: IDiskHelperOptions) {\n super({\n scope: options.scope ?? DiskHelper.name,\n identifier: options.identifier ?? DiskHelper.name,\n });\n this.basePath = path.resolve(options.basePath);\n\n if (!fs.existsSync(this.basePath)) {\n fs.mkdirSync(this.basePath, { recursive: true });\n }\n }\n\n private getBucketPath(opts: { bucket: IBucketRef }): string {\n return path.join(this.basePath, opts.bucket.name);\n }\n\n /**\n * Whether `target`, with every symbolic link followed, lies inside the real storage root. A target that does not exist\n * yet is judged by its nearest existing parent (a write creates the rest beneath it); a link whose own target is\n * missing is refused, because writing through it would create the file where the link points.\n */\n private async isInsideRoot(opts: { target: string }): Promise<boolean> {\n const root = await this.realpathOrFail({ target: this.basePath });\n let probe = opts.target;\n\n for (;;) {\n try {\n const real = await fsp.realpath(probe);\n\n return real === root || real.startsWith(`${root}${path.sep}`);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code;\n\n // A link loop or a path the system refuses as too long is not a place a name can lead to.\n if (code === 'ELOOP' || code === 'ENAMETOOLONG') {\n return false;\n }\n\n if (code !== 'ENOENT' && code !== 'ENOTDIR') {\n throw this.toRealPathError({ error });\n }\n }\n\n const link = await this.lstatOrNull({ target: probe });\n\n if (link?.isSymbolicLink()) {\n return false;\n }\n\n const parent = path.dirname(probe);\n\n if (parent === probe) {\n return false;\n }\n\n probe = parent;\n }\n }\n\n /** The real path of `target`; a failure leaves as {@link DiskHelper.toRealPathError} answers it. */\n private async realpathOrFail(opts: { target: string }): Promise<string> {\n try {\n const result = await fsp.realpath(opts.target);\n\n return result;\n } catch (error) {\n throw this.toRealPathError({ error });\n }\n }\n\n /**\n * What a failed `realpath` is reported as: the code, never the path. Node's message holds the absolute path of the\n * server, and a refusal reaches the caller of the storage API. The full error stays in the log.\n */\n private toRealPathError(opts: { error: unknown }) {\n const { error } = opts;\n const code = (error as NodeJS.ErrnoException)?.code ?? 'UNKNOWN';\n\n this.logger.error(\n 'Cannot resolve the real path of a storage target | code: %s | %s',\n code,\n error,\n );\n\n // A server-side fault, not the caller's: the default status of `getError` is a 400.\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[storage] Cannot resolve the real path of a storage target | code: ${code}`,\n });\n }\n\n /** `null` when nothing is there (or it cannot be read): the caller walks up to the parent and judges that. */\n private async lstatOrNull(opts: { target: string }): Promise<Stats | null> {\n try {\n const result = await fsp.lstat(opts.target);\n\n return result;\n // eslint-disable-next-line venizia/no-silent-catch -- a missing or unreadable entry is the answer here: the containment walk goes on to its parent\n } catch {\n return null;\n }\n }\n\n /** A directory that exists AND lies inside the real root: a bucket that is a link leading outside is not one. */\n private async isReachableBucketPath(opts: { target: string }): Promise<boolean> {\n const inside = await this.isInsideRoot(opts);\n\n if (!inside) {\n return false;\n }\n\n return this.exists(opts);\n }\n\n /** The path of an object after the checks of {@link DiskHelper.resolveObjectPath} and the real-path containment check. */\n private async resolveContainedObjectPath(opts: IObjectLocation): Promise<string> {\n const objectPath = this.resolveObjectPath(opts);\n\n const result = await this.isInsideRoot({ target: objectPath });\n\n if (!result) {\n throw getError({ message: `[storage] Invalid object name | key: ${opts.object.key}` });\n }\n\n return objectPath;\n }\n\n /** Validates the name AND the resolved path: containment survives a naming rule we get wrong. */\n private resolveObjectPath(opts: IObjectLocation): string {\n const { bucket, object } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({ message: `[storage] Invalid bucket name | bucket: ${bucket.name}` });\n }\n\n if (!this.isValidObjectKey({ object, maxDepth: Number.MAX_SAFE_INTEGER })) {\n throw getError({ message: `[storage] Invalid object name | key: ${object.key}` });\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const objectPath = path.resolve(bucketPath, object.key);\n\n if (objectPath !== bucketPath && !objectPath.startsWith(`${bucketPath}${path.sep}`)) {\n throw getError({ message: `[storage] Invalid object name | key: ${object.key}` });\n }\n\n return objectPath;\n }\n\n /** `null` means not there. Anything but ENOENT is logged: it may exist and be unreadable. */\n private async statOrNull(opts: { target: string }): Promise<Stats | null> {\n const { target } = opts;\n\n try {\n const result = await fsp.stat(target);\n\n return result;\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n this.logger.warn(\n '[statOrNull] Cannot determine existence, reporting missing | path: %s | %s',\n target,\n ErrorPrettier.format({ error }),\n );\n }\n\n return null;\n }\n }\n\n private async exists(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result !== null;\n }\n\n /** An object is a regular file: a directory under the same path is not one, so it reads as not found. */\n private async isFile(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result?.isFile() ?? false;\n }\n\n /** One `stat` answers existence and type. */\n async hasBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n if (!this.isValidBucketName(opts)) {\n return false;\n }\n\n const target = this.getBucketPath(opts);\n\n // A bucket that is a link leading outside the root is not a bucket.\n const result = await this.isInsideRoot({ target });\n\n if (!result) {\n return false;\n }\n\n const stat = await this.statOrNull({ target });\n\n return stat?.isDirectory() ?? false;\n }\n\n async getBuckets(): Promise<IBucketInfo[]> {\n const result = await this.exists({ target: this.basePath });\n\n if (!result) {\n return [];\n }\n\n const entries = await fsp.readdir(this.basePath, { withFileTypes: true });\n const buckets: IBucketInfo[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n const bucketPath = path.join(this.basePath, entry.name);\n const stat = await fsp.stat(bucketPath);\n buckets.push({\n name: entry.name,\n creationDate: stat.birthtime,\n });\n }\n }\n\n return buckets;\n }\n\n async getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return null;\n }\n\n const target = this.getBucketPath(opts);\n const inside = await this.isInsideRoot({ target });\n\n if (!inside) {\n return null;\n }\n\n const stat = await this.statOrNull({ target });\n\n if (!stat?.isDirectory()) {\n return null;\n }\n\n return { name, creationDate: stat.birthtime };\n }\n\n async createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[createBucket] Invalid name to create bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.exists({ target: bucketPath });\n\n if (result) {\n throw getError({\n message: `[createBucket] Bucket already exists | name: ${name}`,\n });\n }\n\n await fsp.mkdir(bucketPath, { recursive: true });\n\n return this.getBucket(opts);\n }\n\n async removeBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[removeBucket] Invalid name to remove bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n throw getError({\n message: `[removeBucket] Bucket does not exist | name: ${name}`,\n });\n }\n\n const files = await fsp.readdir(bucketPath);\n\n if (files.length > 0) {\n throw getError({\n message: `[removeBucket] Bucket is not empty | name: ${name}`,\n });\n }\n\n await fsp.rmdir(bucketPath);\n\n return true;\n }\n\n protected get defaultLinkPrefix(): string {\n return '/static-resources/';\n }\n\n protected async writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void> {\n const { bucket, object, file } = opts;\n // The same validated, contained path every other operation uses: `writeStream` reaches here without `upload`'s checks.\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n // `recursive` succeeds on an existing directory; probing first wastes a syscall per file.\n await fsp.mkdir(path.dirname(objectPath), { recursive: true });\n await fsp.writeFile(objectPath, file.buffer);\n }\n\n async getObject(opts: IObjectLocation & { options?: any }): Promise<Readable> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObject] Object not found | bucket: ${bucket.name} | key: ${object.key}`,\n });\n }\n\n return fs.createReadStream(objectPath);\n }\n\n /** `createReadStream` seeks natively, so a range never reads the bytes before it. */\n override async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObjectStream] Object not found | bucket: ${bucket.name} | key: ${object.key}`,\n });\n }\n\n const source = fs.createReadStream(\n objectPath,\n range ? { start: range.start, end: range.end } : {},\n );\n\n return Readable.toWeb(source) as ReadableStream<Uint8Array>;\n }\n\n async getStat(opts: IObjectLocation): Promise<IFileStat> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n const stat = await this.statOrNull({ target: objectPath });\n\n if (!stat?.isFile()) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getStat] Object not found | bucket: ${bucket.name} | key: ${object.key}`,\n });\n }\n\n return {\n size: stat.size,\n lastModified: stat.mtime,\n metadata: {\n mimetype: this.getMimeType({ filename: object.key }),\n },\n };\n }\n\n async removeObject(opts: IObjectLocation): Promise<void> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[removeObject] Object not found | bucket: ${bucket.name} | key: ${object.key}`,\n });\n }\n\n await fsp.unlink(objectPath);\n }\n\n // Bounded concurrency; one failure stops the batch.\n async removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void> {\n const { bucket, objects } = opts;\n\n await this.mapWithConcurrency({\n items: objects,\n task: ({ item: object }) => this.removeObject({ bucket, object }),\n });\n }\n\n async listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]> {\n const { bucket, prefix = '', useRecursive = false, maxKeys } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({ message: `[listObjects] Invalid bucket name | bucket: ${bucket.name}` });\n }\n\n // `maxKeys: 0` means zero, not unlimited.\n const limit = maxKeys ?? Number.POSITIVE_INFINITY;\n\n if (limit <= 0) {\n return [];\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n return [];\n }\n\n const objects: IObjectInfo[] = [];\n\n const scanDirectory = async (scanOptions: {\n directory: { path: string; prefix?: string };\n }): Promise<void> => {\n const { directory } = scanOptions;\n\n if (objects.length >= limit) {\n return;\n }\n\n const entries = await fsp.readdir(directory.path, { withFileTypes: true });\n\n for (const entry of entries) {\n if (objects.length >= limit) {\n return;\n }\n\n // An object key always joins on '/'; `path.join` would emit '\\' on Windows.\n const entryKey = directory.prefix ? `${directory.prefix}/${entry.name}` : entry.name;\n const entryPath = path.join(directory.path, entry.name);\n\n if (entry.isDirectory()) {\n // A prefix that cannot match below here makes descending pointless.\n const canMatch = !prefix || prefix.startsWith(entryKey) || entryKey.startsWith(prefix);\n\n if (useRecursive && canMatch) {\n await scanDirectory({ directory: { path: entryPath, prefix: entryKey } });\n }\n\n continue;\n }\n\n if (!entry.isFile() || (prefix && !entryKey.startsWith(prefix))) {\n continue;\n }\n\n const stat = await this.statOrNull({ target: entryPath });\n\n if (!stat) {\n continue;\n }\n\n objects.push({ name: entryKey, size: stat.size, lastModified: stat.mtime });\n }\n };\n\n await scanDirectory({ directory: { path: bucketPath } });\n\n return objects;\n }\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/disk/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,GAAG,MAAM,kBAAkB,CAAC;AAEnC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAUL,aAAa,GACd,MAAM,WAAW,CAAC;AAQnB,kNAAkN;AAClN,MAAM,OAAO,UAAW,SAAQ,iBAAiB;IAG/C,YAAY,OAA2B;QACrC,KAAK,CAAC;YACJ,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,UAAU,CAAC,IAAI;YACvC,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,UAAU,CAAC,IAAI;SAClD,CAAC,CAAC;QACH,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QAE/C,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAClC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACnD,CAAC;IACH,CAAC;IAEO,aAAa,CAAC,IAA4B;QAChD,OAAO,I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5E,CAAC;oBAED,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;oBAChE,SAAS;gBACX,CAAC;gBAED,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;gBAE1D,IAAI,CAAC,IAAI,EAAE,CAAC;oBACV,SAAS;gBACX,CAAC;gBAED,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;YAC9E,CAAC;QACH,CAAC,CAAC;QAEF,MAAM,aAAa,CAAC,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;QAEzD,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport { ErrorPrettier } from '@/modules/logger';\nimport { EchoUtility } from '@/utilities/echo.utility';\nimport fs from 'node:fs';\nimport fsp from 'node:fs/promises';\nimport type { Stats } from 'node:fs';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport { BaseStorageHelper } from '../base';\nimport {\n type IBucketInfo,\n type IBucketRef,\n type IFileStat,\n type IListObjectsOptions,\n type IObjectInfo,\n type IObjectLocation,\n type IObjectRef,\n type IStorageHelperOptions,\n type IUploadFile,\n StorageErrors,\n} from '../common';\n\n/** Options for `DiskHelper`; `basePath` is created when missing. */\nexport interface IDiskHelperOptions extends IStorageHelperOptions {\n /** Base directory every bucket lives under. */\n basePath: string;\n}\n\n/** Storage backed by the local filesystem: each bucket is a directory under `basePath`, each object a file whose key is its relative path. Names are validated and resolved paths must stay inside the bucket. */\nexport class DiskHelper extends BaseStorageHelper {\n private basePath: string;\n\n constructor(options: IDiskHelperOptions) {\n super({\n scope: options.scope ?? DiskHelper.name,\n identifier: options.identifier ?? DiskHelper.name,\n });\n this.basePath = path.resolve(options.basePath);\n\n if (!fs.existsSync(this.basePath)) {\n fs.mkdirSync(this.basePath, { recursive: true });\n }\n }\n\n private getBucketPath(opts: { bucket: IBucketRef }): string {\n return path.join(this.basePath, opts.bucket.name);\n }\n\n /**\n * Whether `target`, with every symbolic link followed, lies inside the real storage root. A target that does not exist\n * yet is judged by its nearest existing parent (a write creates the rest beneath it); a link whose own target is\n * missing is refused, because writing through it would create the file where the link points.\n */\n private async isInsideRoot(opts: { target: string }): Promise<boolean> {\n const root = await this.realpathOrFail({ target: this.basePath });\n let probe = opts.target;\n\n for (;;) {\n try {\n const real = await fsp.realpath(probe);\n\n return real === root || real.startsWith(`${root}${path.sep}`);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException)?.code;\n\n // A link loop or a path the system refuses as too long is not a place a name can lead to.\n if (code === 'ELOOP' || code === 'ENAMETOOLONG') {\n return false;\n }\n\n if (code !== 'ENOENT' && code !== 'ENOTDIR') {\n throw this.toRealPathError({ error });\n }\n }\n\n const link = await this.lstatOrNull({ target: probe });\n\n if (link?.isSymbolicLink()) {\n return false;\n }\n\n const parent = path.dirname(probe);\n\n if (parent === probe) {\n return false;\n }\n\n probe = parent;\n }\n }\n\n /** The real path of `target`; a failure leaves as {@link DiskHelper.toRealPathError} answers it. */\n private async realpathOrFail(opts: { target: string }): Promise<string> {\n try {\n const result = await fsp.realpath(opts.target);\n\n return result;\n } catch (error) {\n throw this.toRealPathError({ error });\n }\n }\n\n /**\n * What a failed `realpath` is reported as: the code, never the path. Node's message holds the absolute path of the\n * server, and a refusal reaches the caller of the storage API. The full error stays in the log.\n */\n private toRealPathError(opts: { error: unknown }) {\n const { error } = opts;\n const code = (error as NodeJS.ErrnoException)?.code ?? 'UNKNOWN';\n\n this.logger.error(\n 'Cannot resolve the real path of a storage target | code: %s | %s',\n code,\n // A system error quotes the path it failed on; the path is a caller's key under the storage root.\n EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }),\n );\n\n // A server-side fault, not the caller's: the default status of `getError` is a 400.\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[storage] Cannot resolve the real path of a storage target | code: ${code}`,\n });\n }\n\n /** `null` when nothing is there (or it cannot be read): the caller walks up to the parent and judges that. */\n private async lstatOrNull(opts: { target: string }): Promise<Stats | null> {\n try {\n const result = await fsp.lstat(opts.target);\n\n return result;\n // eslint-disable-next-line venizia/no-silent-catch -- a missing or unreadable entry is the answer here: the containment walk goes on to its parent\n } catch {\n return null;\n }\n }\n\n /** A directory that exists AND lies inside the real root: a bucket that is a link leading outside is not one. */\n private async isReachableBucketPath(opts: { target: string }): Promise<boolean> {\n const inside = await this.isInsideRoot(opts);\n\n if (!inside) {\n return false;\n }\n\n return this.exists(opts);\n }\n\n /** The path of an object after the checks of {@link DiskHelper.resolveObjectPath} and the real-path containment check. */\n private async resolveContainedObjectPath(opts: IObjectLocation): Promise<string> {\n const objectPath = this.resolveObjectPath(opts);\n\n const result = await this.isInsideRoot({ target: objectPath });\n\n if (!result) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: opts.object.key })}`,\n });\n }\n\n return objectPath;\n }\n\n /** Validates the name AND the resolved path: containment survives a naming rule we get wrong. */\n private resolveObjectPath(opts: IObjectLocation): string {\n const { bucket, object } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[storage] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n if (!this.isValidObjectKey({ object, maxDepth: Number.MAX_SAFE_INTEGER })) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const objectPath = path.resolve(bucketPath, object.key);\n\n if (objectPath !== bucketPath && !objectPath.startsWith(`${bucketPath}${path.sep}`)) {\n throw getError({\n message: `[storage] Invalid object name | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return objectPath;\n }\n\n /** `null` means not there. Anything but ENOENT is logged: it may exist and be unreadable. */\n private async statOrNull(opts: { target: string }): Promise<Stats | null> {\n const { target } = opts;\n\n try {\n const result = await fsp.stat(target);\n\n return result;\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n this.logger.warn(\n '[statOrNull] Cannot determine existence, reporting missing | path: %s | %s',\n EchoUtility.toSafeEcho({ value: target }),\n // The error's own text quotes the path, so it is escaped like the path is.\n EchoUtility.toSafeEcho({ value: ErrorPrettier.format({ error }) }),\n );\n }\n\n return null;\n }\n }\n\n private async exists(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result !== null;\n }\n\n /** An object is a regular file: a directory under the same path is not one, so it reads as not found. */\n private async isFile(opts: { target: string }): Promise<boolean> {\n const result = await this.statOrNull(opts);\n\n return result?.isFile() ?? false;\n }\n\n /** One `stat` answers existence and type. */\n async hasBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n if (!this.isValidBucketName(opts)) {\n return false;\n }\n\n const target = this.getBucketPath(opts);\n\n // A bucket that is a link leading outside the root is not a bucket.\n const result = await this.isInsideRoot({ target });\n\n if (!result) {\n return false;\n }\n\n const stat = await this.statOrNull({ target });\n\n return stat?.isDirectory() ?? false;\n }\n\n async getBuckets(): Promise<IBucketInfo[]> {\n const result = await this.exists({ target: this.basePath });\n\n if (!result) {\n return [];\n }\n\n const entries = await fsp.readdir(this.basePath, { withFileTypes: true });\n const buckets: IBucketInfo[] = [];\n\n for (const entry of entries) {\n if (entry.isDirectory()) {\n const bucketPath = path.join(this.basePath, entry.name);\n const stat = await fsp.stat(bucketPath);\n buckets.push({\n name: entry.name,\n creationDate: stat.birthtime,\n });\n }\n }\n\n return buckets;\n }\n\n async getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n return null;\n }\n\n const target = this.getBucketPath(opts);\n const inside = await this.isInsideRoot({ target });\n\n if (!inside) {\n return null;\n }\n\n const stat = await this.statOrNull({ target });\n\n if (!stat?.isDirectory()) {\n return null;\n }\n\n return { name, creationDate: stat.birthtime };\n }\n\n async createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[createBucket] Invalid name to create bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.exists({ target: bucketPath });\n\n if (result) {\n throw getError({\n message: `[createBucket] Bucket already exists | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n await fsp.mkdir(bucketPath, { recursive: true });\n\n return this.getBucket(opts);\n }\n\n async removeBucket(opts: { bucket: IBucketRef }): Promise<boolean> {\n const { name } = opts.bucket;\n\n if (!this.isValidBucketName(opts)) {\n throw getError({\n message: '[removeBucket] Invalid name to remove bucket!',\n });\n }\n\n const bucketPath = this.getBucketPath(opts);\n\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n throw getError({\n message: `[removeBucket] Bucket does not exist | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n const files = await fsp.readdir(bucketPath);\n\n if (files.length > 0) {\n throw getError({\n message: `[removeBucket] Bucket is not empty | name: ${EchoUtility.toSafeText({ value: name })}`,\n });\n }\n\n await fsp.rmdir(bucketPath);\n\n return true;\n }\n\n protected get defaultLinkPrefix(): string {\n return '/static-resources/';\n }\n\n protected async writeObject(opts: IObjectLocation & { file: IUploadFile }): Promise<void> {\n const { bucket, object, file } = opts;\n // The same validated, contained path every other operation uses: `writeStream` reaches here without `upload`'s checks.\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n // `recursive` succeeds on an existing directory; probing first wastes a syscall per file.\n await fsp.mkdir(path.dirname(objectPath), { recursive: true });\n await fsp.writeFile(objectPath, file.buffer);\n }\n\n async getObject(opts: IObjectLocation & { options?: any }): Promise<Readable> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return fs.createReadStream(objectPath);\n }\n\n /** `createReadStream` seeks natively, so a range never reads the bytes before it. */\n override async getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getObjectStream] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n const source = fs.createReadStream(\n objectPath,\n range ? { start: range.start, end: range.end } : {},\n );\n\n return Readable.toWeb(source) as ReadableStream<Uint8Array>;\n }\n\n async getStat(opts: IObjectLocation): Promise<IFileStat> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n const stat = await this.statOrNull({ target: objectPath });\n\n if (!stat?.isFile()) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[getStat] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n return {\n size: stat.size,\n lastModified: stat.mtime,\n metadata: {\n mimetype: this.getMimeType({ filename: object.key }),\n },\n };\n }\n\n async removeObject(opts: IObjectLocation): Promise<void> {\n const { bucket, object } = opts;\n const objectPath = await this.resolveContainedObjectPath({ bucket, object });\n\n const result = await this.isFile({ target: objectPath });\n\n if (!result) {\n throw getError({\n error: StorageErrors.OBJECT_NOT_FOUND,\n message: `[removeObject] Object not found | bucket: ${EchoUtility.toSafeText({ value: bucket.name })} | key: ${EchoUtility.toSafeText({ value: object.key })}`,\n });\n }\n\n await fsp.unlink(objectPath);\n }\n\n // Bounded concurrency; one failure stops the batch.\n async removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void> {\n const { bucket, objects } = opts;\n\n await this.mapWithConcurrency({\n items: objects,\n task: ({ item: object }) => this.removeObject({ bucket, object }),\n });\n }\n\n async listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]> {\n const { bucket, prefix = '', useRecursive = false, maxKeys } = opts;\n\n if (!this.isValidBucketName({ bucket })) {\n throw getError({\n message: `[listObjects] Invalid bucket name | bucket: ${EchoUtility.toSafeText({ value: bucket.name })}`,\n });\n }\n\n // `maxKeys: 0` means zero, not unlimited.\n const limit = maxKeys ?? Number.POSITIVE_INFINITY;\n\n if (limit <= 0) {\n return [];\n }\n\n const bucketPath = this.getBucketPath({ bucket });\n const result = await this.isReachableBucketPath({ target: bucketPath });\n\n if (!result) {\n return [];\n }\n\n const objects: IObjectInfo[] = [];\n\n const scanDirectory = async (scanOptions: {\n directory: { path: string; prefix?: string };\n }): Promise<void> => {\n const { directory } = scanOptions;\n\n if (objects.length >= limit) {\n return;\n }\n\n const entries = await fsp.readdir(directory.path, { withFileTypes: true });\n\n for (const entry of entries) {\n if (objects.length >= limit) {\n return;\n }\n\n // An object key always joins on '/'; `path.join` would emit '\\' on Windows.\n const entryKey = directory.prefix ? `${directory.prefix}/${entry.name}` : entry.name;\n const entryPath = path.join(directory.path, entry.name);\n\n if (entry.isDirectory()) {\n // A prefix that cannot match below here makes descending pointless.\n const canMatch = !prefix || prefix.startsWith(entryKey) || entryKey.startsWith(prefix);\n\n if (useRecursive && canMatch) {\n await scanDirectory({ directory: { path: entryPath, prefix: entryKey } });\n }\n\n continue;\n }\n\n if (!entry.isFile() || (prefix && !entryKey.startsWith(prefix))) {\n continue;\n }\n\n const stat = await this.statOrNull({ target: entryPath });\n\n if (!stat) {\n continue;\n }\n\n objects.push({ name: entryKey, size: stat.size, lastModified: stat.mtime });\n }\n };\n\n await scanDirectory({ directory: { path: bucketPath } });\n\n return objects;\n }\n}\n"]}
@@ -0,0 +1,35 @@
1
+ /** A caller's value made safe to put inside a log line or an error message. Pure string work, no node import, so it ships on `/core`. */
2
+ export declare class EchoUtility {
3
+ /**
4
+ * What can forge or hide part of a line: C0 controls (a line break, an escape sequence), DEL and C1 controls
5
+ * (U+0085 is a line break to some viewers), lone surrogates, the soft hyphen, the Arabic letter mark, the
6
+ * Mongolian vowel separator, the zero-width and directional marks (U+200B-U+200F), the line and paragraph
7
+ * separators and every bidirectional override and isolate (U+2028-U+202E, U+2060-U+206F), the byte order mark
8
+ * (U+FEFF), the interlinear annotation marks and the Unicode tag characters. The `u` flag makes the surrogate
9
+ * range match a LONE surrogate only; a valid pair is one character and stays.
10
+ */
11
+ private static readonly UNSAFE_CHARACTERS;
12
+ /** A value JSON cannot take (a cycle, a `BigInt`) is named by its type, never thrown over: a log line must not fail. */
13
+ private static stringify;
14
+ private static escapeUnsafe;
15
+ /**
16
+ * The value as one quoted, single-line token: a string becomes `"a.txt"`, anything else its JSON. Every character
17
+ * that can break a line or reorder what a reader sees becomes a `\uXXXX` (or `\u{XXXXX}`) escape.
18
+ *
19
+ * Use it for every caller-chosen value that reaches a log line (a key, a bucket, a file name, a path): hand the
20
+ * result to a `%s`, never to a template that then adds the quotes again.
21
+ */
22
+ static toSafeEcho(opts: {
23
+ value: unknown;
24
+ }): string;
25
+ /**
26
+ * The value with every unsafe character escaped and nothing else changed: no quotes, and `"` and `\` stay.
27
+ * For a caller's value inside a message that is read as text (a thrown error's message, which reaches the
28
+ * caller and the error log), where an ordinary name must read unchanged. A value that is not a
29
+ * string is written as `toSafeEcho` writes it.
30
+ */
31
+ static toSafeText(opts: {
32
+ value: unknown;
33
+ }): string;
34
+ }
35
+ //# sourceMappingURL=echo.utility.d.ts.map
@@ -0,0 +1,54 @@
1
+ /** A caller's value made safe to put inside a log line or an error message. Pure string work, no node import, so it ships on `/core`. */
2
+ export class EchoUtility {
3
+ /**
4
+ * What can forge or hide part of a line: C0 controls (a line break, an escape sequence), DEL and C1 controls
5
+ * (U+0085 is a line break to some viewers), lone surrogates, the soft hyphen, the Arabic letter mark, the
6
+ * Mongolian vowel separator, the zero-width and directional marks (U+200B-U+200F), the line and paragraph
7
+ * separators and every bidirectional override and isolate (U+2028-U+202E, U+2060-U+206F), the byte order mark
8
+ * (U+FEFF), the interlinear annotation marks and the Unicode tag characters. The `u` flag makes the surrogate
9
+ * range match a LONE surrogate only; a valid pair is one character and stays.
10
+ */
11
+ static { this.UNSAFE_CHARACTERS = /[\p{Cc}\p{Cs}\u00ad\u061c\u180e\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff\ufff9-\ufffb\u{e0000}-\u{e007f}]/gu; }
12
+ /** A value JSON cannot take (a cycle, a `BigInt`) is named by its type, never thrown over: a log line must not fail. */
13
+ static stringify(opts) {
14
+ const { value } = opts;
15
+ try {
16
+ return JSON.stringify(value) ?? `<${typeof value}>`;
17
+ }
18
+ catch {
19
+ return `<${typeof value}>`;
20
+ }
21
+ }
22
+ static escapeUnsafe(opts) {
23
+ return opts.text.replace(EchoUtility.UNSAFE_CHARACTERS, (character) => {
24
+ const code = character.codePointAt(0) ?? 0;
25
+ return code > 0xffff
26
+ ? `\\u{${code.toString(16)}}`
27
+ : `\\u${code.toString(16).padStart(4, '0')}`;
28
+ });
29
+ }
30
+ /**
31
+ * The value as one quoted, single-line token: a string becomes `"a.txt"`, anything else its JSON. Every character
32
+ * that can break a line or reorder what a reader sees becomes a `\uXXXX` (or `\u{XXXXX}`) escape.
33
+ *
34
+ * Use it for every caller-chosen value that reaches a log line (a key, a bucket, a file name, a path): hand the
35
+ * result to a `%s`, never to a template that then adds the quotes again.
36
+ */
37
+ static toSafeEcho(opts) {
38
+ return EchoUtility.escapeUnsafe({ text: EchoUtility.stringify(opts) });
39
+ }
40
+ /**
41
+ * The value with every unsafe character escaped and nothing else changed: no quotes, and `"` and `\` stay.
42
+ * For a caller's value inside a message that is read as text (a thrown error's message, which reaches the
43
+ * caller and the error log), where an ordinary name must read unchanged. A value that is not a
44
+ * string is written as `toSafeEcho` writes it.
45
+ */
46
+ static toSafeText(opts) {
47
+ const { value } = opts;
48
+ if (typeof value !== 'string') {
49
+ return EchoUtility.toSafeEcho({ value });
50
+ }
51
+ return EchoUtility.escapeUnsafe({ text: value });
52
+ }
53
+ }
54
+ //# sourceMappingURL=echo.utility.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"echo.utility.js","sourceRoot":"","sources":["../../../src/utilities/echo.utility.ts"],"names":[],"mappings":"AAAA,yIAAyI;AACzI,MAAM,OAAO,WAAW;IACtB;;;;;;;OAOG;aACqB,sBAAiB,GACvC,iHAAiH,CAAC;IAEpH,wHAAwH;IAChH,MAAM,CAAC,SAAS,CAAC,IAAwB;QAC/C,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,IAAI,OAAO,KAAK,GAAG,CAAC;QACtD,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,OAAO,KAAK,GAAG,CAAC;QAC7B,CAAC;IACH,CAAC;IAEO,MAAM,CAAC,YAAY,CAAC,IAAsB;QAChD,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,iBAAiB,EAAE,CAAC,SAAS,EAAE,EAAE;YACpE,MAAM,IAAI,GAAG,SAAS,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAE3C,OAAO,IAAI,GAAG,MAAM;gBAClB,CAAC,CAAC,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG;gBAC7B,CAAC,CAAC,MAAM,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;QACjD,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,UAAU,CAAC,IAAwB;QACxC,OAAO,WAAW,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzE,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,UAAU,CAAC,IAAwB;QACxC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,OAAO,WAAW,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAC3C,CAAC;QAED,OAAO,WAAW,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACnD,CAAC","sourcesContent":["/** A caller's value made safe to put inside a log line or an error message. Pure string work, no node import, so it ships on `/core`. */\nexport class EchoUtility {\n /**\n * What can forge or hide part of a line: C0 controls (a line break, an escape sequence), DEL and C1 controls\n * (U+0085 is a line break to some viewers), lone surrogates, the soft hyphen, the Arabic letter mark, the\n * Mongolian vowel separator, the zero-width and directional marks (U+200B-U+200F), the line and paragraph\n * separators and every bidirectional override and isolate (U+2028-U+202E, U+2060-U+206F), the byte order mark\n * (U+FEFF), the interlinear annotation marks and the Unicode tag characters. The `u` flag makes the surrogate\n * range match a LONE surrogate only; a valid pair is one character and stays.\n */\n private static readonly UNSAFE_CHARACTERS =\n /[\\p{Cc}\\p{Cs}\\u00ad\\u061c\\u180e\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u206f\\ufeff\\ufff9-\\ufffb\\u{e0000}-\\u{e007f}]/gu;\n\n /** A value JSON cannot take (a cycle, a `BigInt`) is named by its type, never thrown over: a log line must not fail. */\n private static stringify(opts: { value: unknown }): string {\n const { value } = opts;\n\n try {\n return JSON.stringify(value) ?? `<${typeof value}>`;\n } catch {\n return `<${typeof value}>`;\n }\n }\n\n private static escapeUnsafe(opts: { text: string }): string {\n return opts.text.replace(EchoUtility.UNSAFE_CHARACTERS, (character) => {\n const code = character.codePointAt(0) ?? 0;\n\n return code > 0xffff\n ? `\\\\u{${code.toString(16)}}`\n : `\\\\u${code.toString(16).padStart(4, '0')}`;\n });\n }\n\n /**\n * The value as one quoted, single-line token: a string becomes `\"a.txt\"`, anything else its JSON. Every character\n * that can break a line or reorder what a reader sees becomes a `\\uXXXX` (or `\\u{XXXXX}`) escape.\n *\n * Use it for every caller-chosen value that reaches a log line (a key, a bucket, a file name, a path): hand the\n * result to a `%s`, never to a template that then adds the quotes again.\n */\n static toSafeEcho(opts: { value: unknown }): string {\n return EchoUtility.escapeUnsafe({ text: EchoUtility.stringify(opts) });\n }\n\n /**\n * The value with every unsafe character escaped and nothing else changed: no quotes, and `\"` and `\\` stay.\n * For a caller's value inside a message that is read as text (a thrown error's message, which reaches the\n * caller and the error log), where an ordinary name must read unchanged. A value that is not a\n * string is written as `toSafeEcho` writes it.\n */\n static toSafeText(opts: { value: unknown }): string {\n const { value } = opts;\n\n if (typeof value !== 'string') {\n return EchoUtility.toSafeEcho({ value });\n }\n\n return EchoUtility.escapeUnsafe({ text: value });\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  export * from './build-info.utility.js';
2
2
  export { FormBodyUtility } from './form-body.utility.js';
3
+ export * from './echo.utility.js';
3
4
  export * from './error.utility.js';
4
5
  export * from './hr-time.utility.js';
5
6
  export * from './module.utility.js';
@@ -1,6 +1,7 @@
1
1
  export * from './build-info.utility.js';
2
2
  // `RequestBodyErrors` stays on `/core`: consumers name it through the kernel's `RequestErrors`.
3
3
  export { FormBodyUtility } from './form-body.utility.js';
4
+ export * from './echo.utility.js';
4
5
  export * from './error.utility.js';
5
6
  export * from './hr-time.utility.js';
6
7
  export * from './module.utility.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,gGAAgG;AAChG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,mBAAmB,CAAC","sourcesContent":["export * from './build-info.utility';\n// `RequestBodyErrors` stays on `/core`: consumers name it through the kernel's `RequestErrors`.\nexport { FormBodyUtility } from './form-body.utility';\nexport * from './error.utility';\nexport * from './hr-time.utility';\nexport * from './module.utility';\nexport * from './parse.utility';\nexport * from './performance.utility';\nexport * from './promise.utility';\nexport * from './record.utility';\nexport * from './request.utility';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utilities/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,gGAAgG;AAChG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,mBAAmB,CAAC","sourcesContent":["export * from './build-info.utility';\n// `RequestBodyErrors` stays on `/core`: consumers name it through the kernel's `RequestErrors`.\nexport { FormBodyUtility } from './form-body.utility';\nexport * from './echo.utility';\nexport * from './error.utility';\nexport * from './hr-time.utility';\nexport * from './module.utility';\nexport * from './parse.utility';\nexport * from './performance.utility';\nexport * from './promise.utility';\nexport * from './record.utility';\nexport * from './request.utility';\n"]}
@@ -2,8 +2,17 @@
2
2
  export declare class RecordUtility {
3
3
  /** A non-null object, arrays included: the narrowest check before reading string keys off an `unknown`. A type guard, so it keeps its positional `value`. */
4
4
  static isRecord(value: unknown): value is Record<string, unknown>;
5
- /** A non-null object that is not an array: `isRecord` without the arrays. A class instance (an `Error`, a `Date`) passes; there is no prototype check, so this is not lodash's `isPlainObject`. */
5
+ /** A non-null object that is not an array: `isRecord` without the arrays. A class instance (an `Error`, a `Date`) passes; there is no prototype check; use `isPlainObject` for that. */
6
6
  static isPlainRecord(value: unknown): value is Record<string, unknown>;
7
+ /**
8
+ * A non-null object whose prototype is exactly `Object.prototype` or `null`: an object literal, `JSON.parse` output,
9
+ * `Object.create(null)`. Where `isRecord` and `isPlainRecord` look only at the type of the value, this one reads the
10
+ * prototype, so an array, a class instance (an `Error`, a `Date`, a `Map`), a function and an object from another
11
+ * realm (its `Object.prototype` is not this realm's) answer `false`. `Object.create(Object.create(null))` also
12
+ * answers `false`: its prototype is an object, not `null`. Use it for input that must be literal-shaped (a JSON
13
+ * body, a config). It never throws: a Proxy whose `getPrototypeOf` trap throws answers `false`.
14
+ */
15
+ static isPlainObject(value: unknown): value is Record<string, unknown>;
7
16
  /**
8
17
  * Reads `value` along `path` (an array of keys; a number reads an array index) and answers `undefined` when any step
9
18
  * is missing, null or not an object, where `ParseUtility.getDeepProperty` throws. Only own properties are read: a
@@ -4,10 +4,31 @@ export class RecordUtility {
4
4
  static isRecord(value) {
5
5
  return typeof value === 'object' && value !== null;
6
6
  }
7
- /** A non-null object that is not an array: `isRecord` without the arrays. A class instance (an `Error`, a `Date`) passes; there is no prototype check, so this is not lodash's `isPlainObject`. */
7
+ /** A non-null object that is not an array: `isRecord` without the arrays. A class instance (an `Error`, a `Date`) passes; there is no prototype check; use `isPlainObject` for that. */
8
8
  static isPlainRecord(value) {
9
9
  return RecordUtility.isRecord(value) && !Array.isArray(value);
10
10
  }
11
+ /**
12
+ * A non-null object whose prototype is exactly `Object.prototype` or `null`: an object literal, `JSON.parse` output,
13
+ * `Object.create(null)`. Where `isRecord` and `isPlainRecord` look only at the type of the value, this one reads the
14
+ * prototype, so an array, a class instance (an `Error`, a `Date`, a `Map`), a function and an object from another
15
+ * realm (its `Object.prototype` is not this realm's) answer `false`. `Object.create(Object.create(null))` also
16
+ * answers `false`: its prototype is an object, not `null`. Use it for input that must be literal-shaped (a JSON
17
+ * body, a config). It never throws: a Proxy whose `getPrototypeOf` trap throws answers `false`.
18
+ */
19
+ static isPlainObject(value) {
20
+ if (!RecordUtility.isRecord(value)) {
21
+ return false;
22
+ }
23
+ try {
24
+ const prototype = Object.getPrototypeOf(value);
25
+ return prototype === null || prototype === Object.prototype;
26
+ // eslint-disable-next-line venizia/no-silent-catch -- a revoked or hostile Proxy throws from the trap; `false` is the answer of a guard, and the cause is of no use to the caller
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
11
32
  /**
12
33
  * Reads `value` along `path` (an array of keys; a number reads an array index) and answers `undefined` when any step
13
34
  * is missing, null or not an object, where `ParseUtility.getDeepProperty` throws. Only own properties are read: a
@@ -1 +1 @@
1
- {"version":3,"file":"record.utility.js","sourceRoot":"","sources":["../../../src/utilities/record.utility.ts"],"names":[],"mappings":"AAAA,gLAAgL;AAChL,MAAM,OAAO,aAAa;IACxB,6JAA6J;IAC7J,MAAM,CAAC,QAAQ,CAAC,KAAc;QAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;IACrD,CAAC;IAED,mMAAmM;IACnM,MAAM,CAAC,aAAa,CAAC,KAAc;QACjC,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAChE,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,IAAI,CAAC,IAA8D;QACxE,IAAI,OAAO,GAAY,IAAI,CAAC,KAAK,CAAC;QAElC,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC5B,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;gBACrE,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QACzB,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["/** Narrowing of an `unknown` value, such as a wire payload, to an object whose string keys can be read, and a safe deep read of one; no node import, so it ships on `/core`. */\nexport class RecordUtility {\n /** A non-null object, arrays included: the narrowest check before reading string keys off an `unknown`. A type guard, so it keeps its positional `value`. */\n static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n }\n\n /** A non-null object that is not an array: `isRecord` without the arrays. A class instance (an `Error`, a `Date`) passes; there is no prototype check, so this is not lodash's `isPlainObject`. */\n static isPlainRecord(value: unknown): value is Record<string, unknown> {\n return RecordUtility.isRecord(value) && !Array.isArray(value);\n }\n\n /**\n * Reads `value` along `path` (an array of keys; a number reads an array index) and answers `undefined` when any step\n * is missing, null or not an object, where `ParseUtility.getDeepProperty` throws. Only own properties are read: a\n * name such as `__proto__`, `constructor` or `toString` is never found through the prototype, so a path taken from\n * input cannot reach the prototype chain. An empty `path` answers `value` itself. The answer is `unknown`: narrow it.\n */\n static read(opts: { value: unknown; path: ReadonlyArray<string | number> }): unknown {\n let current: unknown = opts.value;\n\n for (const key of opts.path) {\n if (!RecordUtility.isRecord(current) || !Object.hasOwn(current, key)) {\n return undefined;\n }\n\n current = current[key];\n }\n\n return current;\n }\n}\n"]}
1
+ {"version":3,"file":"record.utility.js","sourceRoot":"","sources":["../../../src/utilities/record.utility.ts"],"names":[],"mappings":"AAAA,gLAAgL;AAChL,MAAM,OAAO,aAAa;IACxB,6JAA6J;IAC7J,MAAM,CAAC,QAAQ,CAAC,KAAc;QAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;IACrD,CAAC;IAED,wLAAwL;IACxL,MAAM,CAAC,aAAa,CAAC,KAAc;QACjC,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAChE,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,aAAa,CAAC,KAAc;QACjC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,CAAC;YACH,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;YAE/C,OAAO,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,MAAM,CAAC,SAAS,CAAC;YAC5D,kLAAkL;QACpL,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,IAAI,CAAC,IAA8D;QACxE,IAAI,OAAO,GAAY,IAAI,CAAC,KAAK,CAAC;QAElC,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC5B,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;gBACrE,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QACzB,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["/** Narrowing of an `unknown` value, such as a wire payload, to an object whose string keys can be read, and a safe deep read of one; no node import, so it ships on `/core`. */\nexport class RecordUtility {\n /** A non-null object, arrays included: the narrowest check before reading string keys off an `unknown`. A type guard, so it keeps its positional `value`. */\n static isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n }\n\n /** A non-null object that is not an array: `isRecord` without the arrays. A class instance (an `Error`, a `Date`) passes; there is no prototype check; use `isPlainObject` for that. */\n static isPlainRecord(value: unknown): value is Record<string, unknown> {\n return RecordUtility.isRecord(value) && !Array.isArray(value);\n }\n\n /**\n * A non-null object whose prototype is exactly `Object.prototype` or `null`: an object literal, `JSON.parse` output,\n * `Object.create(null)`. Where `isRecord` and `isPlainRecord` look only at the type of the value, this one reads the\n * prototype, so an array, a class instance (an `Error`, a `Date`, a `Map`), a function and an object from another\n * realm (its `Object.prototype` is not this realm's) answer `false`. `Object.create(Object.create(null))` also\n * answers `false`: its prototype is an object, not `null`. Use it for input that must be literal-shaped (a JSON\n * body, a config). It never throws: a Proxy whose `getPrototypeOf` trap throws answers `false`.\n */\n static isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!RecordUtility.isRecord(value)) {\n return false;\n }\n\n try {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === null || prototype === Object.prototype;\n // eslint-disable-next-line venizia/no-silent-catch -- a revoked or hostile Proxy throws from the trap; `false` is the answer of a guard, and the cause is of no use to the caller\n } catch {\n return false;\n }\n }\n\n /**\n * Reads `value` along `path` (an array of keys; a number reads an array index) and answers `undefined` when any step\n * is missing, null or not an object, where `ParseUtility.getDeepProperty` throws. Only own properties are read: a\n * name such as `__proto__`, `constructor` or `toString` is never found through the prototype, so a path taken from\n * input cannot reach the prototype chain. An empty `path` answers `value` itself. The answer is `unknown`: narrow it.\n */\n static read(opts: { value: unknown; path: ReadonlyArray<string | number> }): unknown {\n let current: unknown = opts.value;\n\n for (const key of opts.path) {\n if (!RecordUtility.isRecord(current) || !Object.hasOwn(current, key)) {\n return undefined;\n }\n\n current = current[key];\n }\n\n return current;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-helpers",
3
- "version": "0.4.8-5",
3
+ "version": "0.4.8-6",
4
4
  "description": "Production-ready TypeScript utility library: pluggable logging (winston or pino behind one ILogger contract), Redis single/cluster/sentinel with pub/sub, BullMQ/MQTT/Kafka message queues, MinIO/Disk/Bun-S3 object storage, AES-256/RSA/ECDH cryptography, Snowflake UID generation, cron scheduling, Socket.IO/WebSocket, TCP/TLS/UDP networking, HTTP clients, secrets/Vault, worker thread pools, and environment management. Sub-path imports isolate optional peer dependencies so the root barrel never forces a peer into your bundle.",
5
5
  "keywords": [
6
6
  "aes",
@@ -176,7 +176,7 @@
176
176
  "force-update": "sh ../../scripts/build/force-update.sh"
177
177
  },
178
178
  "dependencies": {
179
- "@venizia/ignis-inversion": "0.4.7-2",
179
+ "@venizia/ignis-inversion": "0.4.7-3",
180
180
  "reflect-metadata": "^0.2.2",
181
181
  "zod": "^4.6.7"
182
182
  },
@@ -188,7 +188,7 @@
188
188
  "@socket.io/redis-emitter": "^5.1.0",
189
189
  "@types/bun": "^1.4.3",
190
190
  "@types/luxon": "^3.7.6",
191
- "@venizia/dev-configs": "0.4.8-2",
191
+ "@venizia/dev-configs": "0.4.8-3",
192
192
  "axios": "^1.20.0",
193
193
  "bullmq": "^6.4.0",
194
194
  "cron": "^4.4.0",