@venizia/ignis-helpers 0.4.8-8 → 0.4.8

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.
Files changed (199) hide show
  1. package/README.md +2 -3
  2. package/dist/esm/common/constants/app.d.ts +1 -3
  3. package/dist/esm/common/constants/app.js +1 -11
  4. package/dist/esm/common/constants/app.js.map +1 -1
  5. package/dist/esm/common/constants/http.d.ts +4 -0
  6. package/dist/esm/common/constants/http.js +5 -0
  7. package/dist/esm/common/constants/http.js.map +1 -1
  8. package/dist/esm/common/constants/mime.d.ts +0 -2
  9. package/dist/esm/common/constants/mime.js +0 -4
  10. package/dist/esm/common/constants/mime.js.map +1 -1
  11. package/dist/esm/common/redact.js.map +1 -1
  12. package/dist/esm/common/types/class.d.ts +14 -12
  13. package/dist/esm/common/types/class.js.map +1 -1
  14. package/dist/esm/common/types/const-value.d.ts +3 -3
  15. package/dist/esm/common/types/const-value.js.map +1 -1
  16. package/dist/esm/common/types/field-mapping.d.ts +6 -8
  17. package/dist/esm/common/types/field-mapping.js +0 -10
  18. package/dist/esm/common/types/field-mapping.js.map +1 -1
  19. package/dist/esm/common/types/index.d.ts +1 -0
  20. package/dist/esm/common/types/index.js +1 -0
  21. package/dist/esm/common/types/index.js.map +1 -1
  22. package/dist/esm/common/types/injection.d.ts +1 -1
  23. package/dist/esm/common/types/injection.js.map +1 -1
  24. package/dist/esm/common/types/json.d.ts +14 -0
  25. package/dist/esm/common/types/json.js +2 -0
  26. package/dist/esm/common/types/json.js.map +1 -0
  27. package/dist/esm/common/types/utility.d.ts +0 -4
  28. package/dist/esm/common/types/utility.js.map +1 -1
  29. package/dist/esm/modules/env/app-env.d.ts +17 -8
  30. package/dist/esm/modules/env/app-env.js +18 -15
  31. package/dist/esm/modules/env/app-env.js.map +1 -1
  32. package/dist/esm/modules/env/common/types.d.ts +22 -6
  33. package/dist/esm/modules/env/common/types.js.map +1 -1
  34. package/dist/esm/modules/logger/base/abstract.d.ts +6 -7
  35. package/dist/esm/modules/logger/base/abstract.js.map +1 -1
  36. package/dist/esm/modules/logger/base/base.d.ts +7 -8
  37. package/dist/esm/modules/logger/base/base.js.map +1 -1
  38. package/dist/esm/modules/logger/base/console.d.ts +6 -7
  39. package/dist/esm/modules/logger/base/console.js.map +1 -1
  40. package/dist/esm/modules/logger/common/types.d.ts +7 -7
  41. package/dist/esm/modules/logger/common/types.js.map +1 -1
  42. package/dist/esm/modules/logger/factory.js.map +1 -1
  43. package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
  44. package/dist/esm/modules/logger/hf/logger.d.ts +6 -7
  45. package/dist/esm/modules/logger/hf/logger.js.map +1 -1
  46. package/dist/esm/modules/logger/pino/backing.js.map +1 -1
  47. package/dist/esm/modules/logger/pino/destination.d.ts +1 -1
  48. package/dist/esm/modules/logger/pino/destination.js.map +1 -1
  49. package/dist/esm/modules/logger/pino/logger.d.ts +1 -2
  50. package/dist/esm/modules/logger/pino/logger.js.map +1 -1
  51. package/dist/esm/modules/logger/winston/formats.js +2 -2
  52. package/dist/esm/modules/logger/winston/formats.js.map +1 -1
  53. package/dist/esm/modules/logger/winston/logger.d.ts +1 -2
  54. package/dist/esm/modules/logger/winston/logger.js.map +1 -1
  55. package/dist/esm/modules/logger/winston/transports/dgram.transport.d.ts +1 -1
  56. package/dist/esm/modules/logger/winston/transports/dgram.transport.js +1 -1
  57. package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  58. package/dist/esm/modules/network/http-request/common/constants.d.ts +0 -2
  59. package/dist/esm/modules/network/http-request/common/constants.js +0 -4
  60. package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
  61. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +6 -6
  62. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  63. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +2 -3
  64. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  65. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +1 -1
  66. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  67. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +1 -2
  68. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +5 -6
  69. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  70. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.d.ts +4 -4
  71. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  72. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  73. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts +3 -5
  74. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +0 -8
  75. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  76. package/dist/esm/modules/network/utilities/query-string.d.ts +2 -2
  77. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  78. package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -2
  79. package/dist/esm/modules/network/utilities/url-safety/common/constants.js +0 -4
  80. package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
  81. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
  82. package/dist/esm/modules/queue/bullmq/helper.d.ts +23 -10
  83. package/dist/esm/modules/queue/bullmq/helper.js +57 -10
  84. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  85. package/dist/esm/modules/queue/common/constants.d.ts +6 -2
  86. package/dist/esm/modules/queue/common/constants.js +6 -4
  87. package/dist/esm/modules/queue/common/constants.js.map +1 -1
  88. package/dist/esm/modules/queue/internal/sequential/common/types.d.ts +2 -4
  89. package/dist/esm/modules/queue/internal/sequential/common/types.js +0 -4
  90. package/dist/esm/modules/queue/internal/sequential/common/types.js.map +1 -1
  91. package/dist/esm/modules/queue/kafka/base.d.ts +1 -1
  92. package/dist/esm/modules/queue/kafka/base.js +13 -2
  93. package/dist/esm/modules/queue/kafka/base.js.map +1 -1
  94. package/dist/esm/modules/queue/kafka/common/constants.d.ts +0 -4
  95. package/dist/esm/modules/queue/kafka/common/constants.js +0 -8
  96. package/dist/esm/modules/queue/kafka/common/constants.js.map +1 -1
  97. package/dist/esm/modules/redis/base/abstract.helper.d.ts +13 -2
  98. package/dist/esm/modules/redis/base/abstract.helper.js +53 -45
  99. package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
  100. package/dist/esm/modules/redis/cluster/cluster.helper.d.ts +1 -2
  101. package/dist/esm/modules/redis/cluster/cluster.helper.js +21 -9
  102. package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
  103. package/dist/esm/modules/redis/cluster/index.d.ts +1 -0
  104. package/dist/esm/modules/redis/cluster/index.js +1 -0
  105. package/dist/esm/modules/redis/cluster/index.js.map +1 -1
  106. package/dist/esm/modules/redis/cluster/types.d.ts +20 -0
  107. package/dist/esm/modules/redis/cluster/types.js +2 -0
  108. package/dist/esm/modules/redis/cluster/types.js.map +1 -0
  109. package/dist/esm/modules/redis/common/constants.d.ts +15 -19
  110. package/dist/esm/modules/redis/common/constants.js +16 -18
  111. package/dist/esm/modules/redis/common/constants.js.map +1 -1
  112. package/dist/esm/modules/redis/common/types.d.ts +10 -60
  113. package/dist/esm/modules/redis/common/types.js.map +1 -1
  114. package/dist/esm/modules/redis/factory.d.ts +7 -25
  115. package/dist/esm/modules/redis/factory.js +9 -18
  116. package/dist/esm/modules/redis/factory.js.map +1 -1
  117. package/dist/esm/modules/redis/sentinel/constants.d.ts +14 -0
  118. package/dist/esm/modules/redis/sentinel/constants.js +11 -0
  119. package/dist/esm/modules/redis/sentinel/constants.js.map +1 -0
  120. package/dist/esm/modules/redis/sentinel/index.d.ts +2 -0
  121. package/dist/esm/modules/redis/sentinel/index.js +2 -0
  122. package/dist/esm/modules/redis/sentinel/index.js.map +1 -1
  123. package/dist/esm/modules/redis/sentinel/sentinel.helper.d.ts +1 -2
  124. package/dist/esm/modules/redis/sentinel/sentinel.helper.js +25 -15
  125. package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  126. package/dist/esm/modules/redis/sentinel/types.d.ts +26 -0
  127. package/dist/esm/modules/redis/sentinel/types.js +2 -0
  128. package/dist/esm/modules/redis/sentinel/types.js.map +1 -0
  129. package/dist/esm/modules/redis/single/index.d.ts +1 -0
  130. package/dist/esm/modules/redis/single/index.js +1 -0
  131. package/dist/esm/modules/redis/single/index.js.map +1 -1
  132. package/dist/esm/modules/redis/single/single.helper.d.ts +1 -2
  133. package/dist/esm/modules/redis/single/single.helper.js +5 -6
  134. package/dist/esm/modules/redis/single/single.helper.js.map +1 -1
  135. package/dist/esm/modules/redis/single/types.d.ts +15 -0
  136. package/dist/esm/modules/redis/single/types.js +2 -0
  137. package/dist/esm/modules/redis/single/types.js.map +1 -0
  138. package/dist/esm/modules/secrets/base/abstract.helper.js +6 -1
  139. package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
  140. package/dist/esm/modules/secrets/common/types/registration.d.ts +25 -6
  141. package/dist/esm/modules/secrets/common/types/registration.js.map +1 -1
  142. package/dist/esm/modules/secrets/dotenv/dotenv.helper.js +1 -1
  143. package/dist/esm/modules/secrets/dotenv/dotenv.helper.js.map +1 -1
  144. package/dist/esm/modules/secrets/factory.js +7 -6
  145. package/dist/esm/modules/secrets/factory.js.map +1 -1
  146. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.d.ts +12 -10
  147. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +50 -25
  148. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  149. package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -1
  150. package/dist/esm/modules/socket/socket-io/common/types/client.d.ts +2 -2
  151. package/dist/esm/modules/socket/socket-io/common/types/client.js.map +1 -1
  152. package/dist/esm/modules/socket/socket-io/common/types/server.d.ts +3 -1
  153. package/dist/esm/modules/socket/socket-io/common/types/server.js.map +1 -1
  154. package/dist/esm/modules/socket/socket-io/server/helper.d.ts +2 -2
  155. package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
  156. package/dist/esm/modules/storage/base.d.ts +26 -57
  157. package/dist/esm/modules/storage/base.js +76 -127
  158. package/dist/esm/modules/storage/base.js.map +1 -1
  159. package/dist/esm/modules/storage/bun-s3/helper.d.ts +22 -37
  160. package/dist/esm/modules/storage/bun-s3/helper.js +131 -132
  161. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  162. package/dist/esm/modules/storage/bun-s3/utility.d.ts +15 -8
  163. package/dist/esm/modules/storage/bun-s3/utility.js +66 -47
  164. package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
  165. package/dist/esm/modules/storage/common/constants.d.ts +36 -2
  166. package/dist/esm/modules/storage/common/constants.js +34 -4
  167. package/dist/esm/modules/storage/common/constants.js.map +1 -1
  168. package/dist/esm/modules/storage/common/errors.d.ts +26 -0
  169. package/dist/esm/modules/storage/common/errors.js +23 -0
  170. package/dist/esm/modules/storage/common/errors.js.map +1 -1
  171. package/dist/esm/modules/storage/common/types.d.ts +99 -57
  172. package/dist/esm/modules/storage/common/types.js.map +1 -1
  173. package/dist/esm/modules/storage/common/utility.d.ts +8 -0
  174. package/dist/esm/modules/storage/common/utility.js +14 -2
  175. package/dist/esm/modules/storage/common/utility.js.map +1 -1
  176. package/dist/esm/modules/storage/disk/helper.d.ts +4 -8
  177. package/dist/esm/modules/storage/disk/helper.js +3 -1
  178. package/dist/esm/modules/storage/disk/helper.js.map +1 -1
  179. package/dist/esm/modules/storage/in-memory/helper.d.ts +2 -3
  180. package/dist/esm/modules/storage/in-memory/helper.js.map +1 -1
  181. package/dist/esm/modules/worker-thread/common/types.d.ts +2 -2
  182. package/dist/esm/modules/worker-thread/common/types.js.map +1 -1
  183. package/dist/esm/modules/worker-thread/thread/abstract.d.ts +2 -2
  184. package/dist/esm/modules/worker-thread/thread/abstract.js.map +1 -1
  185. package/dist/esm/modules/worker-thread/worker-pool.d.ts +1 -1
  186. package/dist/esm/modules/worker-thread/worker-pool.js.map +1 -1
  187. package/dist/esm/utilities/module.utility.d.ts +8 -5
  188. package/dist/esm/utilities/module.utility.js +5 -1
  189. package/dist/esm/utilities/module.utility.js.map +1 -1
  190. package/dist/esm/utilities/parse.utility.d.ts +34 -6
  191. package/dist/esm/utilities/parse.utility.js +82 -15
  192. package/dist/esm/utilities/parse.utility.js.map +1 -1
  193. package/dist/esm/utilities/performance.utility.d.ts +3 -3
  194. package/dist/esm/utilities/performance.utility.js.map +1 -1
  195. package/dist/esm/utilities/promise.utility.d.ts +1 -1
  196. package/dist/esm/utilities/promise.utility.js.map +1 -1
  197. package/dist/esm/utilities/request.utility.d.ts +9 -11
  198. package/dist/esm/utilities/request.utility.js.map +1 -1
  199. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import { type IDuration } from '../../../common/index.js';
2
2
  import { type Readable } from 'node:stream';
3
+ import type { TStorageType } from './constants.js';
3
4
  /** One file handed to `upload`. `buffer` is the whole body; `folderPath`, when set, nests the object under that folder and is depth-checked. */
4
5
  export interface IUploadFile {
5
6
  originalName: string;
@@ -8,7 +9,7 @@ export interface IUploadFile {
8
9
  size: number;
9
10
  encoding?: string;
10
11
  folderPath?: string;
11
- [key: string | symbol]: any;
12
+ [key: string | symbol]: unknown;
12
13
  }
13
14
  /** `metaLink` is a union: the old pair allowed both present, or neither. */
14
15
  export interface IUploadResult {
@@ -19,7 +20,7 @@ export interface IUploadResult {
19
20
  };
20
21
  link: string;
21
22
  metaLink?: {
22
- data: any;
23
+ data: unknown;
23
24
  } | {
24
25
  error: string;
25
26
  };
@@ -27,7 +28,7 @@ export interface IUploadResult {
27
28
  /** `mimetype` is named because consumers persist it; `any` let it be renamed silently. */
28
29
  export interface IObjectMetadata {
29
30
  mimetype?: string;
30
- [key: string]: any;
31
+ [key: string]: unknown;
31
32
  }
32
33
  /** What `getStat` reports for one object. `size` is in bytes. */
33
34
  export interface IFileStat {
@@ -88,8 +89,88 @@ export interface IStorageHelperOptions {
88
89
  scope?: string;
89
90
  identifier?: string;
90
91
  }
92
+ /** What a read may require of the object: its ETag, or an exact version. A read that finds other content fails with `StorageErrors.PRECONDITION_FAILED`. A backend that cannot honour it refuses the read. */
93
+ export interface IStorageReadCondition {
94
+ ifMatch?: string;
95
+ versionId?: string;
96
+ }
97
+ /** A byte window of an object. `end` is inclusive, like the HTTP `Range` header. */
98
+ export interface IByteRange {
99
+ start: number;
100
+ end?: number;
101
+ }
102
+ /** `getObjectStream`: one object, an optional byte window, and what the object must still be. */
103
+ export type TObjectStreamOptions = IObjectLocation & {
104
+ range?: IByteRange;
105
+ } & IStorageReadCondition;
106
+ /** `upload`: the files, and the rules their names and keys must meet. */
107
+ export interface IUploadOptions {
108
+ bucket: IBucketRef;
109
+ files: IUploadFile[];
110
+ /**
111
+ * Folders the caller's `folderPath` may carry.
112
+ *
113
+ * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH
114
+ */
115
+ maxFolderDepth?: number;
116
+ /**
117
+ * Folders the finished key may carry, a scope the `normalizeNameFn` adds included.
118
+ *
119
+ * @default `maxFolderDepth`
120
+ */
121
+ maxKeyDepth?: number;
122
+ normalizeNameFn?: (opts: {
123
+ file: TUploadNaming;
124
+ }) => string;
125
+ normalizeLinkFn?: (opts: IObjectLocation) => string;
126
+ }
127
+ /** `writeStream`: one object written from a stream, so a large body never lands in this process. */
128
+ export interface IWriteStreamOptions extends IObjectLocation {
129
+ source: ReadableStream<Uint8Array> | Blob | Response | Request;
130
+ contentType?: string;
131
+ /**
132
+ * Folder nesting the key may carry, as `upload` takes it.
133
+ *
134
+ * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH
135
+ */
136
+ maxFolderDepth?: number;
137
+ }
138
+ /** `copyObject`: a copy within one bucket. */
139
+ export interface ICopyObjectOptions {
140
+ bucket: IBucketRef;
141
+ source: IObjectRef;
142
+ destination: IObjectRef;
143
+ /** Copy only if the source still has this ETag; otherwise `StorageErrors.PRECONDITION_FAILED`. */
144
+ ifMatch?: string;
145
+ /** Copy this exact version of the source. */
146
+ sourceVersionId?: string;
147
+ }
148
+ /** `presignPost`: the one object a browser form may be posted under, and its size ceiling. */
149
+ export interface IPresignPostOptions extends IObjectLocation {
150
+ maxBytes: number;
151
+ contentType?: string;
152
+ expiresIn?: IDuration;
153
+ }
154
+ /** `presignPut`. Every option is SIGNED - the client must send it back unchanged. */
155
+ export interface IPresignPutOptions extends IObjectLocation {
156
+ expiresIn?: IDuration;
157
+ /** The object's tag set, written at the moment it is stored. */
158
+ tagging?: Record<string, string>;
159
+ /** Pins the body to EXACTLY this many bytes. A retry at a different size is refused. */
160
+ contentLength?: number;
161
+ /** Pins the stored content type. Unsigned, the uploader picks what is stored - and the stored type is what a browser later renders. */
162
+ contentType?: string;
163
+ }
164
+ /** `presignGet`. */
165
+ export interface IPresignGetOptions extends IObjectLocation {
166
+ expiresIn?: IDuration;
167
+ responseContentType?: string;
168
+ responseContentDisposition?: string;
169
+ }
91
170
  /** The contract every storage backend (disk, in-memory, S3) implements. Buckets and objects are addressed by `IBucketRef` and `IObjectRef`. */
92
171
  export interface IStorageHelper {
172
+ /** The backend this helper writes to. The helpers IGNIS ships declare it; a custom helper may leave it out. */
173
+ readonly storageType?: TStorageType;
93
174
  isValidSegment(opts: {
94
175
  segment: string;
95
176
  }): boolean;
@@ -114,74 +195,35 @@ export interface IStorageHelper {
114
195
  bucket: IBucketRef;
115
196
  }): Promise<boolean>;
116
197
  getObject(opts: IObjectLocation & {
117
- options?: any;
198
+ options?: unknown;
118
199
  }): Promise<Readable>;
119
200
  /** A web stream, what a `Response` body wants. `range` includes `end`, like the HTTP header. */
120
- getObjectStream(opts: IObjectLocation & {
121
- range?: {
122
- start: number;
123
- end?: number;
124
- };
125
- }): Promise<ReadableStream<Uint8Array>>;
201
+ getObjectStream(opts: TObjectStreamOptions): Promise<ReadableStream<Uint8Array>>;
126
202
  getStat(opts: IObjectLocation): Promise<IFileStat>;
127
203
  listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;
128
- upload(opts: {
129
- bucket: IBucketRef;
130
- files: IUploadFile[];
131
- maxFolderDepth?: number;
132
- normalizeNameFn?: (opts: {
133
- file: TUploadNaming;
134
- }) => string;
135
- normalizeLinkFn?: (opts: IObjectLocation) => string;
136
- }): Promise<IUploadResult[]>;
204
+ upload(opts: IUploadOptions): Promise<IUploadResult[]>;
137
205
  /**
138
206
  * Writes an object from a stream, so a large body never lands in this process. A backend whose
139
207
  * transport takes a stream overrides it; the default buffers, which is the thing to avoid.
140
208
  */
141
- writeStream(opts: IObjectLocation & {
142
- source: ReadableStream<Uint8Array> | Blob | Response | Request;
143
- contentType?: string;
144
- /**
145
- * Folder nesting the key may carry, as `upload` takes it.
146
- *
147
- * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH
148
- */
149
- maxFolderDepth?: number;
150
- }): Promise<void>;
209
+ writeStream(opts: IWriteStreamOptions): Promise<void>;
151
210
  /** Copies within one bucket, server side - the bytes never travel through this process. */
152
- copyObject(opts: {
153
- bucket: IBucketRef;
154
- source: IObjectRef;
155
- destination: IObjectRef;
156
- }): Promise<void>;
211
+ copyObject(opts: ICopyObjectOptions): Promise<void>;
157
212
  removeObject(opts: IObjectLocation): Promise<void>;
158
213
  removeObjects(opts: {
159
214
  bucket: IBucketRef;
160
215
  objects: IObjectRef[];
161
216
  }): Promise<void>;
162
- /** The form a browser posts straight to the storage. Unlike a presigned PUT, a policy carries `content-length-range`, so "at most N bytes" is expressible - a signed PUT binds the length to one exact value. */
163
- presignPost(opts: {
164
- bucket: IBucketRef;
165
- keyPrefix: string;
166
- maxBytes: number;
167
- contentType?: string;
168
- expiresIn?: IDuration;
169
- }): Promise<IPostPolicy>;
170
- /** A URL a browser may PUT one object to. Every extra option below is SIGNED - the client must send it back unchanged. A pinned size is exact, never a ceiling; for a ceiling use {@link IStorageHelper.presignPost}. */
171
- presignPut(opts: IObjectLocation & {
172
- expiresIn?: IDuration;
173
- /** The object's tag set, written at the moment it is stored. */
174
- tagging?: Record<string, string>;
175
- /** Pins the body to EXACTLY this many bytes. A retry at a different size is refused. */
176
- contentLength?: number;
177
- /** Pins the stored content type. Unsigned, the uploader picks what is stored - and the stored type is what a browser later renders. */
178
- contentType?: string;
179
- }): Promise<string>;
180
- presignGet(opts: IObjectLocation & {
181
- expiresIn?: IDuration;
182
- responseContentType?: string;
183
- responseContentDisposition?: string;
184
- }): Promise<string>;
217
+ /**
218
+ * The form a browser posts straight to the storage, good for exactly ONE object: the policy signs
219
+ * `object.key` as it stands, and `formData` carries that key, so the client does not add it.
220
+ * Unlike a presigned PUT, a policy carries `content-length-range`, so "at most N bytes" is
221
+ * expressible - a signed PUT binds the length to one exact value.
222
+ */
223
+ presignPost(opts: IPresignPostOptions): Promise<IPostPolicy>;
224
+ /** A URL a browser may PUT one object to. Every option is SIGNED; a pinned size is exact, never a ceiling - for a ceiling use {@link IStorageHelper.presignPost}. */
225
+ presignPut(opts: IPresignPutOptions): Promise<string>;
226
+ presignGet(opts: IPresignGetOptions): Promise<string>;
185
227
  getObjectTags(opts: IObjectLocation): Promise<Record<string, string>>;
186
228
  replaceObjectTags(opts: IObjectLocation & {
187
229
  tags: Record<string, string>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type IDuration } from '@/common';\nimport { type Readable } from 'node:stream';\n\n/** One file handed to `upload`. `buffer` is the whole body; `folderPath`, when set, nests the object under that folder and is depth-checked. */\nexport interface IUploadFile {\n originalName: string;\n mimetype: string;\n buffer: Buffer;\n size: number;\n encoding?: string;\n folderPath?: string;\n [key: string | symbol]: any;\n}\n\n/** `metaLink` is a union: the old pair allowed both present, or neither. */\nexport interface IUploadResult {\n bucket: IBucketRef;\n object: IObjectRef & { size: number; contentType: string };\n link: string;\n metaLink?: { data: any } | { error: string };\n}\n\n/** `mimetype` is named because consumers persist it; `any` let it be renamed silently. */\nexport interface IObjectMetadata {\n mimetype?: string;\n [key: string]: any;\n}\n\n/** What `getStat` reports for one object. `size` is in bytes. */\nexport interface IFileStat {\n size: number;\n metadata: IObjectMetadata;\n lastModified?: Date;\n etag?: string;\n versionId?: string;\n}\n\n/** A bucket as `getBuckets`, `getBucket` and `createBucket` report it. */\nexport interface IBucketInfo {\n name: string;\n creationDate: Date;\n}\n\n/** One entry of `listObjects`. `name` is the full object key. */\nexport interface IObjectInfo {\n name?: string;\n size?: number;\n lastModified?: Date;\n etag?: string;\n prefix?: string;\n}\n\n/** One bucket. */\nexport interface IBucketRef {\n name: string;\n}\n\n/** The parts of an upload a naming hook needs; `IUploadFile` already declares both. */\nexport type TUploadNaming = Pick<IUploadFile, 'originalName' | 'folderPath'>;\n\n/** One object. `key` is the S3 term. */\nexport interface IObjectRef {\n key: string;\n}\n\n/** Which bucket, which object. */\nexport interface IObjectLocation {\n bucket: IBucketRef;\n object: IObjectRef;\n}\n\n/** Filters for `listObjects`. `maxKeys` caps the result, and `0` returns nothing. */\nexport interface IListObjectsOptions {\n bucket: IBucketRef;\n prefix?: string;\n\n /**\n * Whether the listing descends into folders.\n *\n * @default false\n */\n useRecursive?: boolean;\n maxKeys?: number;\n}\n\n/** What `presignPost` hands a browser: where to post, the fields to post with it, and when the grant dies. */\nexport interface IPostPolicy {\n postURL: string;\n formData: Record<string, string>;\n expiresAt: string;\n}\n\n/** Logger `scope` and `identifier` for a storage helper. */\nexport interface IStorageHelperOptions {\n scope?: string;\n identifier?: string;\n}\n\n/** The contract every storage backend (disk, in-memory, S3) implements. Buckets and objects are addressed by `IBucketRef` and `IObjectRef`. */\nexport interface IStorageHelper {\n isValidSegment(opts: { segment: string }): boolean;\n isValidBucketName(opts: { bucket: IBucketRef }): boolean;\n isValidObjectKey(opts: { object: IObjectRef; maxDepth?: number }): boolean;\n\n hasBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n getBuckets(): Promise<IBucketInfo[]>;\n getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n removeBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n\n getObject(opts: IObjectLocation & { options?: any }): Promise<Readable>;\n\n /** A web stream, what a `Response` body wants. `range` includes `end`, like the HTTP header. */\n getObjectStream(\n opts: IObjectLocation & { range?: { start: number; end?: number } },\n ): Promise<ReadableStream<Uint8Array>>;\n getStat(opts: IObjectLocation): Promise<IFileStat>;\n listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;\n\n upload(opts: {\n bucket: IBucketRef;\n files: IUploadFile[];\n maxFolderDepth?: number;\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n }): Promise<IUploadResult[]>;\n\n /**\n * Writes an object from a stream, so a large body never lands in this process. A backend whose\n * transport takes a stream overrides it; the default buffers, which is the thing to avoid.\n */\n writeStream(\n opts: IObjectLocation & {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n /**\n * Folder nesting the key may carry, as `upload` takes it.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n },\n ): Promise<void>;\n\n /** Copies within one bucket, server side - the bytes never travel through this process. */\n copyObject(opts: {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n }): Promise<void>;\n\n removeObject(opts: IObjectLocation): Promise<void>;\n removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void>;\n\n /** The form a browser posts straight to the storage. Unlike a presigned PUT, a policy carries `content-length-range`, so \"at most N bytes\" is expressible - a signed PUT binds the length to one exact value. */\n presignPost(opts: {\n bucket: IBucketRef;\n keyPrefix: string;\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n }): Promise<IPostPolicy>;\n\n /** A URL a browser may PUT one object to. Every extra option below is SIGNED - the client must send it back unchanged. A pinned size is exact, never a ceiling; for a ceiling use {@link IStorageHelper.presignPost}. */\n presignPut(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n /** The object's tag set, written at the moment it is stored. */\n tagging?: Record<string, string>;\n /** Pins the body to EXACTLY this many bytes. A retry at a different size is refused. */\n contentLength?: number;\n /** Pins the stored content type. Unsigned, the uploader picks what is stored - and the stored type is what a browser later renders. */\n contentType?: string;\n },\n ): Promise<string>;\n presignGet(\n opts: IObjectLocation & {\n expiresIn?: IDuration;\n responseContentType?: string;\n responseContentDisposition?: string;\n },\n ): Promise<string>;\n\n getObjectTags(opts: IObjectLocation): Promise<Record<string, string>>;\n replaceObjectTags(opts: IObjectLocation & { tags: Record<string, string> }): Promise<void>;\n\n getMediaType(opts: { mimeType: string }): string;\n getMimeType(opts: { filename: string }): string;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type IDuration } from '@/common';\nimport { type Readable } from 'node:stream';\nimport type { TStorageType } from './constants';\n\n/** One file handed to `upload`. `buffer` is the whole body; `folderPath`, when set, nests the object under that folder and is depth-checked. */\nexport interface IUploadFile {\n originalName: string;\n mimetype: string;\n buffer: Buffer;\n size: number;\n encoding?: string;\n folderPath?: string;\n [key: string | symbol]: unknown;\n}\n\n/** `metaLink` is a union: the old pair allowed both present, or neither. */\nexport interface IUploadResult {\n bucket: IBucketRef;\n object: IObjectRef & { size: number; contentType: string };\n link: string;\n metaLink?: { data: unknown } | { error: string };\n}\n\n/** `mimetype` is named because consumers persist it; `any` let it be renamed silently. */\nexport interface IObjectMetadata {\n mimetype?: string;\n [key: string]: unknown;\n}\n\n/** What `getStat` reports for one object. `size` is in bytes. */\nexport interface IFileStat {\n size: number;\n metadata: IObjectMetadata;\n lastModified?: Date;\n etag?: string;\n versionId?: string;\n}\n\n/** A bucket as `getBuckets`, `getBucket` and `createBucket` report it. */\nexport interface IBucketInfo {\n name: string;\n creationDate: Date;\n}\n\n/** One entry of `listObjects`. `name` is the full object key. */\nexport interface IObjectInfo {\n name?: string;\n size?: number;\n lastModified?: Date;\n etag?: string;\n prefix?: string;\n}\n\n/** One bucket. */\nexport interface IBucketRef {\n name: string;\n}\n\n/** The parts of an upload a naming hook needs; `IUploadFile` already declares both. */\nexport type TUploadNaming = Pick<IUploadFile, 'originalName' | 'folderPath'>;\n\n/** One object. `key` is the S3 term. */\nexport interface IObjectRef {\n key: string;\n}\n\n/** Which bucket, which object. */\nexport interface IObjectLocation {\n bucket: IBucketRef;\n object: IObjectRef;\n}\n\n/** Filters for `listObjects`. `maxKeys` caps the result, and `0` returns nothing. */\nexport interface IListObjectsOptions {\n bucket: IBucketRef;\n prefix?: string;\n\n /**\n * Whether the listing descends into folders.\n *\n * @default false\n */\n useRecursive?: boolean;\n maxKeys?: number;\n}\n\n/** What `presignPost` hands a browser: where to post, the fields to post with it, and when the grant dies. */\nexport interface IPostPolicy {\n postURL: string;\n formData: Record<string, string>;\n expiresAt: string;\n}\n\n/** Logger `scope` and `identifier` for a storage helper. */\nexport interface IStorageHelperOptions {\n scope?: string;\n identifier?: string;\n}\n\n/** What a read may require of the object: its ETag, or an exact version. A read that finds other content fails with `StorageErrors.PRECONDITION_FAILED`. A backend that cannot honour it refuses the read. */\nexport interface IStorageReadCondition {\n ifMatch?: string;\n versionId?: string;\n}\n\n/** A byte window of an object. `end` is inclusive, like the HTTP `Range` header. */\nexport interface IByteRange {\n start: number;\n end?: number;\n}\n\n/** `getObjectStream`: one object, an optional byte window, and what the object must still be. */\nexport type TObjectStreamOptions = IObjectLocation & { range?: IByteRange } & IStorageReadCondition;\n\n/** `upload`: the files, and the rules their names and keys must meet. */\nexport interface IUploadOptions {\n bucket: IBucketRef;\n files: IUploadFile[];\n /**\n * Folders the caller's `folderPath` may carry.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n /**\n * Folders the finished key may carry, a scope the `normalizeNameFn` adds included.\n *\n * @default `maxFolderDepth`\n */\n maxKeyDepth?: number;\n normalizeNameFn?: (opts: { file: TUploadNaming }) => string;\n normalizeLinkFn?: (opts: IObjectLocation) => string;\n}\n\n/** `writeStream`: one object written from a stream, so a large body never lands in this process. */\nexport interface IWriteStreamOptions extends IObjectLocation {\n source: ReadableStream<Uint8Array> | Blob | Response | Request;\n contentType?: string;\n /**\n * Folder nesting the key may carry, as `upload` takes it.\n *\n * @default BaseStorageHelper.DEFAULT_MAX_FOLDER_DEPTH\n */\n maxFolderDepth?: number;\n}\n\n/** `copyObject`: a copy within one bucket. */\nexport interface ICopyObjectOptions {\n bucket: IBucketRef;\n source: IObjectRef;\n destination: IObjectRef;\n /** Copy only if the source still has this ETag; otherwise `StorageErrors.PRECONDITION_FAILED`. */\n ifMatch?: string;\n /** Copy this exact version of the source. */\n sourceVersionId?: string;\n}\n\n/** `presignPost`: the one object a browser form may be posted under, and its size ceiling. */\nexport interface IPresignPostOptions extends IObjectLocation {\n maxBytes: number;\n contentType?: string;\n expiresIn?: IDuration;\n}\n\n/** `presignPut`. Every option is SIGNED - the client must send it back unchanged. */\nexport interface IPresignPutOptions extends IObjectLocation {\n expiresIn?: IDuration;\n /** The object's tag set, written at the moment it is stored. */\n tagging?: Record<string, string>;\n /** Pins the body to EXACTLY this many bytes. A retry at a different size is refused. */\n contentLength?: number;\n /** Pins the stored content type. Unsigned, the uploader picks what is stored - and the stored type is what a browser later renders. */\n contentType?: string;\n}\n\n/** `presignGet`. */\nexport interface IPresignGetOptions extends IObjectLocation {\n expiresIn?: IDuration;\n responseContentType?: string;\n responseContentDisposition?: string;\n}\n\n/** The contract every storage backend (disk, in-memory, S3) implements. Buckets and objects are addressed by `IBucketRef` and `IObjectRef`. */\nexport interface IStorageHelper {\n /** The backend this helper writes to. The helpers IGNIS ships declare it; a custom helper may leave it out. */\n readonly storageType?: TStorageType;\n\n isValidSegment(opts: { segment: string }): boolean;\n isValidBucketName(opts: { bucket: IBucketRef }): boolean;\n isValidObjectKey(opts: { object: IObjectRef; maxDepth?: number }): boolean;\n\n hasBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n getBuckets(): Promise<IBucketInfo[]>;\n getBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n createBucket(opts: { bucket: IBucketRef }): Promise<IBucketInfo | null>;\n removeBucket(opts: { bucket: IBucketRef }): Promise<boolean>;\n\n getObject(opts: IObjectLocation & { options?: unknown }): Promise<Readable>;\n\n /** A web stream, what a `Response` body wants. `range` includes `end`, like the HTTP header. */\n getObjectStream(opts: TObjectStreamOptions): Promise<ReadableStream<Uint8Array>>;\n getStat(opts: IObjectLocation): Promise<IFileStat>;\n listObjects(opts: IListObjectsOptions): Promise<IObjectInfo[]>;\n\n upload(opts: IUploadOptions): Promise<IUploadResult[]>;\n\n /**\n * Writes an object from a stream, so a large body never lands in this process. A backend whose\n * transport takes a stream overrides it; the default buffers, which is the thing to avoid.\n */\n writeStream(opts: IWriteStreamOptions): Promise<void>;\n\n /** Copies within one bucket, server side - the bytes never travel through this process. */\n copyObject(opts: ICopyObjectOptions): Promise<void>;\n\n removeObject(opts: IObjectLocation): Promise<void>;\n removeObjects(opts: { bucket: IBucketRef; objects: IObjectRef[] }): Promise<void>;\n\n /**\n * The form a browser posts straight to the storage, good for exactly ONE object: the policy signs\n * `object.key` as it stands, and `formData` carries that key, so the client does not add it.\n * Unlike a presigned PUT, a policy carries `content-length-range`, so \"at most N bytes\" is\n * expressible - a signed PUT binds the length to one exact value.\n */\n presignPost(opts: IPresignPostOptions): Promise<IPostPolicy>;\n\n /** A URL a browser may PUT one object to. Every option is SIGNED; a pinned size is exact, never a ceiling - for a ceiling use {@link IStorageHelper.presignPost}. */\n presignPut(opts: IPresignPutOptions): Promise<string>;\n presignGet(opts: IPresignGetOptions): Promise<string>;\n\n getObjectTags(opts: IObjectLocation): Promise<Record<string, string>>;\n replaceObjectTags(opts: IObjectLocation & { tags: Record<string, string> }): Promise<void>;\n\n getMediaType(opts: { mimeType: string }): string;\n getMimeType(opts: { filename: string }): string;\n}\n"]}
@@ -5,6 +5,14 @@ export declare class StorageUtility {
5
5
  static isNotFoundError(opts: {
6
6
  error: unknown;
7
7
  }): boolean;
8
+ /** A version id that names a version. S3 and MinIO answer the literal `null`, or nothing, for an object in a bucket where versioning is off or suspended. */
9
+ static realVersionId(opts: {
10
+ value?: string | null;
11
+ }): string | undefined;
12
+ /** "The expected content is gone", across SDKs: S3 and MinIO answer 412. */
13
+ static isPreconditionFailedError(opts: {
14
+ error: unknown;
15
+ }): boolean;
8
16
  /** S3 presigns in whole seconds. An unknown unit is refused; `null` would read as "no expiry". */
9
17
  static toExpirySeconds(opts: {
10
18
  expiresIn: IDuration;
@@ -1,19 +1,31 @@
1
1
  import { DurationMultipliers } from '../../../common/index.js';
2
2
  import { HTTP } from '../../../common/constants/index.js';
3
3
  import { getError } from '../../error/index.js';
4
- import { StoragePresignLimits } from './constants.js';
4
+ import { S3Defaults, StoragePresignLimits } from './constants.js';
5
5
  /** Backend-neutral checks shared by storage helpers: recognising a "not found" error and turning an `IDuration` into presign seconds. */
6
6
  export class StorageUtility {
7
7
  /** "Not there", across SDKs. Both minio and Bun report `S3Error` in `name`, so `code` and status decide. */
8
8
  static isNotFoundError(opts) {
9
9
  const { error } = opts;
10
10
  const source = error;
11
- if (source?.statusCode === HTTP.ResultCodes.RS_4.NotFound || source?.status === 404) {
11
+ if (source?.statusCode === HTTP.ResultCodes.RS_4.NotFound ||
12
+ source?.status === HTTP.ResultCodes.RS_4.NotFound) {
12
13
  return true;
13
14
  }
14
15
  const marker = `${source?.code ?? ''} ${source?.name ?? ''}`.toLowerCase();
15
16
  return ['nosuchkey', 'nosuchbucket', 'notfound'].some((needle) => marker.includes(needle));
16
17
  }
18
+ /** A version id that names a version. S3 and MinIO answer the literal `null`, or nothing, for an object in a bucket where versioning is off or suspended. */
19
+ static realVersionId(opts) {
20
+ const { value } = opts;
21
+ return !value || value === S3Defaults.NULL_VERSION_ID ? undefined : value;
22
+ }
23
+ /** "The expected content is gone", across SDKs: S3 and MinIO answer 412. */
24
+ static isPreconditionFailedError(opts) {
25
+ const source = opts.error;
26
+ return (source?.statusCode === HTTP.ResultCodes.RS_4.PreconditionFailed ||
27
+ source?.status === HTTP.ResultCodes.RS_4.PreconditionFailed);
28
+ }
17
29
  /** S3 presigns in whole seconds. An unknown unit is refused; `null` would read as "no expiry". */
18
30
  static toExpirySeconds(opts) {
19
31
  const { expiresIn, operation } = opts;
@@ -1 +1 @@
1
- {"version":3,"file":"utility.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAkB,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,yIAAyI;AACzI,MAAM,OAAO,cAAc;IACzB,4GAA4G;IAC5G,MAAM,CAAC,eAAe,CAAC,IAAwB;QAC7C,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvB,MAAM,MAAM,GAAG,KAA+E,CAAC;QAE/F,IAAI,MAAM,EAAE,UAAU,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ,IAAI,MAAM,EAAE,MAAM,KAAK,GAAG,EAAE,CAAC;YACpF,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,MAAM,GAAG,GAAG,MAAM,EAAE,IAAI,IAAI,EAAE,IAAI,MAAM,EAAE,IAAI,IAAI,EAAE,EAAE,CAAC,WAAW,EAAE,CAAC;QAE3E,OAAO,CAAC,WAAW,EAAE,cAAc,EAAE,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7F,CAAC;IAED,kGAAkG;IAClG,MAAM,CAAC,eAAe,CAAC,IAAiD;QACtE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,YAAY,GAAG,mBAAmB,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;QAEnE,IAAI,YAAY,KAAK,IAAI,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;YAC/C,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,SAAS,4BAA4B,SAAS,EAAE,IAAI,aAAa,SAAS,EAAE,KAAK,EAAE;aACjG,CAAC,CAAC;QACL,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;QAErE,iGAAiG;QACjG,gGAAgG;QAChG,IAAI,OAAO,GAAG,oBAAoB,CAAC,sBAAsB,EAAE,CAAC;YAC1D,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,SAAS,wDAAwD,SAAS,CAAC,IAAI,aAAa,SAAS,CAAC,KAAK,EAAE;aAC3H,CAAC,CAAC;QACL,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { DurationMultipliers, type IDuration } from '@/common';\nimport { HTTP } from '@/common/constants';\nimport { getError } from '@/modules/error';\nimport { StoragePresignLimits } from './constants';\n\n/** Backend-neutral checks shared by storage helpers: recognising a \"not found\" error and turning an `IDuration` into presign seconds. */\nexport class StorageUtility {\n /** \"Not there\", across SDKs. Both minio and Bun report `S3Error` in `name`, so `code` and status decide. */\n static isNotFoundError(opts: { error: unknown }): boolean {\n const { error } = opts;\n const source = error as { statusCode?: number; status?: number; code?: string; name?: string };\n\n if (source?.statusCode === HTTP.ResultCodes.RS_4.NotFound || source?.status === 404) {\n return true;\n }\n\n const marker = `${source?.code ?? ''} ${source?.name ?? ''}`.toLowerCase();\n\n return ['nosuchkey', 'nosuchbucket', 'notfound'].some((needle) => marker.includes(needle));\n }\n\n /** S3 presigns in whole seconds. An unknown unit is refused; `null` would read as \"no expiry\". */\n static toExpirySeconds(opts: { expiresIn: IDuration; operation: string }): number {\n const { expiresIn, operation } = opts;\n const milliseconds = DurationMultipliers.toMilliseconds(expiresIn);\n\n if (milliseconds === null || milliseconds <= 0) {\n throw getError({\n message: `[${operation}] Invalid expiry | unit: ${expiresIn?.unit} | value: ${expiresIn?.value}`,\n });\n }\n\n const seconds = Math.ceil(milliseconds / DurationMultipliers.SECOND);\n\n // SigV4 caps a presigned URL at 7 days. `IDuration` accepts `month` and `year`, which type-check\n // and then produce a URL the provider rejects - refused here, where the unit is still readable.\n if (seconds > StoragePresignLimits.MAX_EXPIRES_IN_SECONDS) {\n throw getError({\n message: `[${operation}] Expiry exceeds the SigV4 maximum of 7 days | unit: ${expiresIn.unit} | value: ${expiresIn.value}`,\n });\n }\n\n return seconds;\n }\n}\n"]}
1
+ {"version":3,"file":"utility.js","sourceRoot":"","sources":["../../../../../src/modules/storage/common/utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAkB,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAE/D,yIAAyI;AACzI,MAAM,OAAO,cAAc;IACzB,4GAA4G;IAC5G,MAAM,CAAC,eAAe,CAAC,IAAwB;QAC7C,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvB,MAAM,MAAM,GAAG,KAA+E,CAAC;QAE/F,IACE,MAAM,EAAE,UAAU,KAAK,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ;YACrD,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC,WAAW,CAAC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AAE;aACjG,CAAC,CAAC;QACL,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC;QAErE,iGAAiG;QACjG,gGAAgG;QAChG,IAAI,OAAO,GAAG,oBAAoB,CAAC,sBAAsB,EAAE,CAAC;YAC1D,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,SAAS,wDAAwD,SAAS,CAAC,IAAI,aAAa,SAAS,CAAC,KAAK,EAAE;aAC3H,CAAC,CAAC;QACL,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { DurationMultipliers, type IDuration } from '@/common';\nimport { HTTP } from '@/common/constants';\nimport { getError } from '@/modules/error';\nimport { S3Defaults, StoragePresignLimits } from './constants';\n\n/** Backend-neutral checks shared by storage helpers: recognising a \"not found\" error and turning an `IDuration` into presign seconds. */\nexport class StorageUtility {\n /** \"Not there\", across SDKs. Both minio and Bun report `S3Error` in `name`, so `code` and status decide. */\n static isNotFoundError(opts: { error: unknown }): boolean {\n const { error } = opts;\n const source = error as { statusCode?: number; status?: number; code?: string; name?: string };\n\n if (\n source?.statusCode === HTTP.ResultCodes.RS_4.NotFound ||\n source?.status === HTTP.ResultCodes.RS_4.NotFound\n ) {\n return true;\n }\n\n const marker = `${source?.code ?? ''} ${source?.name ?? ''}`.toLowerCase();\n\n return ['nosuchkey', 'nosuchbucket', 'notfound'].some((needle) => marker.includes(needle));\n }\n\n /** A version id that names a version. S3 and MinIO answer the literal `null`, or nothing, for an object in a bucket where versioning is off or suspended. */\n static realVersionId(opts: { value?: string | null }): string | undefined {\n const { value } = opts;\n\n return !value || value === S3Defaults.NULL_VERSION_ID ? undefined : value;\n }\n\n /** \"The expected content is gone\", across SDKs: S3 and MinIO answer 412. */\n static isPreconditionFailedError(opts: { error: unknown }): boolean {\n const source = opts.error as { statusCode?: number; status?: number } | null | undefined;\n\n return (\n source?.statusCode === HTTP.ResultCodes.RS_4.PreconditionFailed ||\n source?.status === HTTP.ResultCodes.RS_4.PreconditionFailed\n );\n }\n\n /** S3 presigns in whole seconds. An unknown unit is refused; `null` would read as \"no expiry\". */\n static toExpirySeconds(opts: { expiresIn: IDuration; operation: string }): number {\n const { expiresIn, operation } = opts;\n const milliseconds = DurationMultipliers.toMilliseconds(expiresIn);\n\n if (milliseconds === null || milliseconds <= 0) {\n throw getError({\n message: `[${operation}] Invalid expiry | unit: ${expiresIn?.unit} | value: ${expiresIn?.value}`,\n });\n }\n\n const seconds = Math.ceil(milliseconds / DurationMultipliers.SECOND);\n\n // SigV4 caps a presigned URL at 7 days. `IDuration` accepts `month` and `year`, which type-check\n // and then produce a URL the provider rejects - refused here, where the unit is still readable.\n if (seconds > StoragePresignLimits.MAX_EXPIRES_IN_SECONDS) {\n throw getError({\n message: `[${operation}] Expiry exceeds the SigV4 maximum of 7 days | unit: ${expiresIn.unit} | value: ${expiresIn.value}`,\n });\n }\n\n return seconds;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { Readable } from 'node:stream';
2
2
  import { BaseStorageHelper } from '../base.js';
3
- import { type IBucketInfo, type IBucketRef, type IFileStat, type IListObjectsOptions, type IObjectInfo, type IObjectLocation, type IObjectRef, type IStorageHelperOptions, type IUploadFile } from '../common/index.js';
3
+ import { type IBucketInfo, type IBucketRef, type IFileStat, type IListObjectsOptions, type IObjectInfo, type IObjectLocation, type IObjectRef, type IStorageHelperOptions, type IUploadFile, type TObjectStreamOptions } from '../common/index.js';
4
4
  /** Options for `DiskHelper`; `basePath` is created when missing. */
5
5
  export interface IDiskHelperOptions extends IStorageHelperOptions {
6
6
  /** Base directory every bucket lives under. */
@@ -8,6 +8,7 @@ export interface IDiskHelperOptions extends IStorageHelperOptions {
8
8
  }
9
9
  /** 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. */
10
10
  export declare class DiskHelper extends BaseStorageHelper {
11
+ readonly storageType = "disk";
11
12
  private basePath;
12
13
  constructor(options: IDiskHelperOptions);
13
14
  private getBucketPath;
@@ -56,15 +57,10 @@ export declare class DiskHelper extends BaseStorageHelper {
56
57
  file: IUploadFile;
57
58
  }): Promise<void>;
58
59
  getObject(opts: IObjectLocation & {
59
- options?: any;
60
+ options?: unknown;
60
61
  }): Promise<Readable>;
61
62
  /** `createReadStream` seeks natively, so a range never reads the bytes before it. */
62
- getObjectStream(opts: IObjectLocation & {
63
- range?: {
64
- start: number;
65
- end?: number;
66
- };
67
- }): Promise<ReadableStream<Uint8Array>>;
63
+ getObjectStream(opts: TObjectStreamOptions): Promise<ReadableStream<Uint8Array>>;
68
64
  getStat(opts: IObjectLocation): Promise<IFileStat>;
69
65
  removeObject(opts: IObjectLocation): Promise<void>;
70
66
  removeObjects(opts: {
@@ -7,7 +7,7 @@ import fsp from 'node:fs/promises';
7
7
  import path from 'node:path';
8
8
  import { Readable } from 'node:stream';
9
9
  import { BaseStorageHelper } from '../base.js';
10
- import { StorageErrors, } from '../common/index.js';
10
+ import { StorageErrors, StorageTypes, } from '../common/index.js';
11
11
  /** 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. */
12
12
  export class DiskHelper extends BaseStorageHelper {
13
13
  constructor(options) {
@@ -15,6 +15,7 @@ export class DiskHelper extends BaseStorageHelper {
15
15
  scope: options.scope ?? DiskHelper.name,
16
16
  identifier: options.identifier ?? DiskHelper.name,
17
17
  });
18
+ this.storageType = StorageTypes.DISK;
18
19
  this.basePath = path.resolve(options.basePath);
19
20
  if (!fs.existsSync(this.basePath)) {
20
21
  fs.mkdirSync(this.basePath, { recursive: true });
@@ -275,6 +276,7 @@ export class DiskHelper extends BaseStorageHelper {
275
276
  /** `createReadStream` seeks natively, so a range never reads the bytes before it. */
276
277
  async getObjectStream(opts) {
277
278
  const { bucket, object, range } = opts;
279
+ this.refuseReadCondition({ condition: opts, operation: 'getObjectStream' });
278
280
  const objectPath = await this.resolveContainedObjectPath({ bucket, object });
279
281
  const result = await this.isFile({ target: objectPath });
280
282
  if (!result) {
@@ -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,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,IAAI,CAAC,IAAI,CAAC,IAAI,C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AC;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"]}
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,EAWL,aAAa,EACb,YAAY,GACb,MAAM,WAAW,CAAC;AAQnB,kNAAkN;AAClN,MAAM,OAAO,UAAW,SAAQ,iBAAiB;IAK/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;QARI,gBAAW,GAAG,YAAY,CAAC,IAAI,CAAC;QASvC,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,EA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Q,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 { 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 type TObjectStreamOptions,\n StorageErrors,\n StorageTypes,\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 readonly storageType = StorageTypes.DISK;\n\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?: unknown }): 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(opts: TObjectStreamOptions): Promise<ReadableStream<Uint8Array>> {\n const { bucket, object, range } = opts;\n this.refuseReadCondition({ condition: opts, operation: 'getObjectStream' });\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"]}
@@ -1,12 +1,11 @@
1
- import { type AnyObject } from '../../../common/index.js';
2
1
  import { BaseHelper } from '../../base.js';
3
2
  /** An in-process keyed container, NOT an `IStorageHelper`: it stores values, not objects in a bucket. */
4
- export declare class MemoryStorageHelper<T extends object = AnyObject> extends BaseHelper {
3
+ export declare class MemoryStorageHelper<T extends object = Record<string, unknown>> extends BaseHelper {
5
4
  private container;
6
5
  constructor(opts?: {
7
6
  scope?: string;
8
7
  });
9
- static newInstance<T extends object = AnyObject>(): MemoryStorageHelper<T>;
8
+ static newInstance<T extends object = Record<string, unknown>>(): MemoryStorageHelper<T>;
10
9
  isBound(key: keyof T): boolean;
11
10
  get<K extends keyof T>(key: K): T[K] | undefined;
12
11
  set<K extends keyof T>(key: K, value: T[K]): void;
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/in-memory/helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,yGAAyG;AACzG,MAAM,OAAO,mBAAkD,SAAQ,UAAU;IAG/E,YAAY,IAAyB;QACnC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAHpD,cAAS,GAAG,IAAI,GAAG,EAAuB,CAAC;IAInD,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,mBAAmB,EAAK,CAAC;IACtC,CAAC;IAED,OAAO,CAAC,GAAY;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,GAAG,CAAoB,GAAM;QAC3B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAqB,CAAC;IACrD,CAAC;IAED,GAAG,CAAoB,GAAM,EAAE,KAAW;QACxC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,uFAAuF;IACvF,KAAK,CAAC,GAAY;QAChB,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;IAED,IAAI;QACF,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;IAC7B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,gGAAgG;IAChG,YAAY;QACV,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,SAAiC,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { type AnyObject } from '@/common';\nimport { BaseHelper } from '@/modules/base';\n\n/** An in-process keyed container, NOT an `IStorageHelper`: it stores values, not objects in a bucket. */\nexport class MemoryStorageHelper<T extends object = AnyObject> extends BaseHelper {\n private container = new Map<keyof T, T[keyof T]>();\n\n constructor(opts?: { scope?: string }) {\n super({ scope: opts?.scope ?? MemoryStorageHelper.name });\n }\n\n static newInstance<T extends object = AnyObject>() {\n return new MemoryStorageHelper<T>();\n }\n\n isBound(key: keyof T): boolean {\n return this.container.has(key);\n }\n\n get<K extends keyof T>(key: K): T[K] | undefined {\n return this.container.get(key) as T[K] | undefined;\n }\n\n set<K extends keyof T>(key: K, value: T[K]): void {\n this.container.set(key, value);\n }\n\n /** `false` when the key was not bound, so a caller can tell a removal from a no-op. */\n unset(key: keyof T): boolean {\n return this.container.delete(key);\n }\n\n keys(): Array<keyof T> {\n return [...this.container.keys()];\n }\n\n get size(): number {\n return this.container.size;\n }\n\n clear(): void {\n this.container.clear();\n }\n\n /** A COPY: handing out the live map let a caller mutate this helper's state behind its back. */\n getContainer(): Record<string, unknown> {\n return Object.fromEntries(this.container as Map<string, unknown>);\n }\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/in-memory/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,yGAAyG;AACzG,MAAM,OAAO,mBAAgE,SAAQ,UAAU;IAG7F,YAAY,IAAyB;QACnC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAHpD,cAAS,GAAG,IAAI,GAAG,EAAuB,CAAC;IAInD,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,mBAAmB,EAAK,CAAC;IACtC,CAAC;IAED,OAAO,CAAC,GAAY;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,GAAG,CAAoB,GAAM;QAC3B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAqB,CAAC;IACrD,CAAC;IAED,GAAG,CAAoB,GAAM,EAAE,KAAW;QACxC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,uFAAuF;IACvF,KAAK,CAAC,GAAY;QAChB,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;IAED,IAAI;QACF,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;IAC7B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,gGAAgG;IAChG,YAAY;QACV,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,SAAiC,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@/modules/base';\n\n/** An in-process keyed container, NOT an `IStorageHelper`: it stores values, not objects in a bucket. */\nexport class MemoryStorageHelper<T extends object = Record<string, unknown>> extends BaseHelper {\n private container = new Map<keyof T, T[keyof T]>();\n\n constructor(opts?: { scope?: string }) {\n super({ scope: opts?.scope ?? MemoryStorageHelper.name });\n }\n\n static newInstance<T extends object = Record<string, unknown>>() {\n return new MemoryStorageHelper<T>();\n }\n\n isBound(key: keyof T): boolean {\n return this.container.has(key);\n }\n\n get<K extends keyof T>(key: K): T[K] | undefined {\n return this.container.get(key) as T[K] | undefined;\n }\n\n set<K extends keyof T>(key: K, value: T[K]): void {\n this.container.set(key, value);\n }\n\n /** `false` when the key was not bound, so a caller can tell a removal from a no-op. */\n unset(key: keyof T): boolean {\n return this.container.delete(key);\n }\n\n keys(): Array<keyof T> {\n return [...this.container.keys()];\n }\n\n get size(): number {\n return this.container.size;\n }\n\n clear(): void {\n this.container.clear();\n }\n\n /** A COPY: handing out the live map let a caller mutate this helper's state behind its back. */\n getContainer(): Record<string, unknown> {\n return Object.fromEntries(this.container as Map<string, unknown>);\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type AnyType, type ValueOrPromise } from '../../../common/types/index.js';
1
+ import { type ValueOrPromise } from '../../../common/types/index.js';
2
2
  import { type MessagePort, type Transferable, type Worker, type WorkerOptions } from 'node:worker_threads';
3
3
  /** A managed `Worker` and the hooks fired for its lifecycle events. */
4
4
  export interface IWorker<MessageType> {
@@ -21,7 +21,7 @@ export interface IWorker<MessageType> {
21
21
  /** Message buses held by a worker thread, keyed by name. */
22
22
  export interface IWorkerThread {
23
23
  buses: {
24
- [workerKey: string | symbol]: IWorkerBus<AnyType, AnyType>;
24
+ [workerKey: string | symbol]: IWorkerBus<never, never>;
25
25
  };
26
26
  }
27
27
  /** The callbacks a bus invokes for the events of its port. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type AnyType, type ValueOrPromise } from '@/common/types';\nimport {\n type MessagePort,\n type Transferable,\n type Worker,\n type WorkerOptions,\n} from 'node:worker_threads';\n\n/** A managed `Worker` and the hooks fired for its lifecycle events. */\nexport interface IWorker<MessageType> {\n worker: Worker;\n options: WorkerOptions;\n\n onOnline(): ValueOrPromise<void>;\n onExit(opts: { code: string | number }): ValueOrPromise<void>;\n onError(opts: { error: Error }): ValueOrPromise<void>;\n onMessage(opts: { message: MessageType }): ValueOrPromise<void>;\n onMessageError(opts: { error: Error }): ValueOrPromise<void>;\n}\n\n/** Message buses held by a worker thread, keyed by name. */\nexport interface IWorkerThread {\n buses: {\n [workerKey: string | symbol]: IWorkerBus<AnyType, AnyType>;\n };\n}\n\n/** The callbacks a bus invokes for the events of its port. */\nexport interface IWorkerMessageBusHandler<IConsumePayload> {\n onMessage: (opts: { message: IConsumePayload }) => ValueOrPromise<void>;\n\n onClose: () => ValueOrPromise<void>;\n onError: (opts: { error: Error }) => ValueOrPromise<void>;\n onExit: (opts: { exitCode: number | string }) => ValueOrPromise<void>;\n}\n\n/** A message channel over a `MessagePort`: `handler` receives incoming messages, `postMessage` sends outgoing ones, with optional hooks around each send. */\nexport interface IWorkerBus<IConsumePayload, IPublishPayload> {\n port: MessagePort;\n handler: IWorkerMessageBusHandler<IConsumePayload>;\n\n onBeforePostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n onAfterPostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n postMessage(opts: {\n message: IPublishPayload;\n transferList: readonly Transferable[] | undefined;\n }): ValueOrPromise<void>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type ValueOrPromise } from '@/common/types';\nimport {\n type MessagePort,\n type Transferable,\n type Worker,\n type WorkerOptions,\n} from 'node:worker_threads';\n\n/** A managed `Worker` and the hooks fired for its lifecycle events. */\nexport interface IWorker<MessageType> {\n worker: Worker;\n options: WorkerOptions;\n\n onOnline(): ValueOrPromise<void>;\n onExit(opts: { code: string | number }): ValueOrPromise<void>;\n onError(opts: { error: Error }): ValueOrPromise<void>;\n onMessage(opts: { message: MessageType }): ValueOrPromise<void>;\n onMessageError(opts: { error: Error }): ValueOrPromise<void>;\n}\n\n/** Message buses held by a worker thread, keyed by name. */\nexport interface IWorkerThread {\n buses: {\n [workerKey: string | symbol]: IWorkerBus<never, never>;\n };\n}\n\n/** The callbacks a bus invokes for the events of its port. */\nexport interface IWorkerMessageBusHandler<IConsumePayload> {\n onMessage: (opts: { message: IConsumePayload }) => ValueOrPromise<void>;\n\n onClose: () => ValueOrPromise<void>;\n onError: (opts: { error: Error }) => ValueOrPromise<void>;\n onExit: (opts: { exitCode: number | string }) => ValueOrPromise<void>;\n}\n\n/** A message channel over a `MessagePort`: `handler` receives incoming messages, `postMessage` sends outgoing ones, with optional hooks around each send. */\nexport interface IWorkerBus<IConsumePayload, IPublishPayload> {\n port: MessagePort;\n handler: IWorkerMessageBusHandler<IConsumePayload>;\n\n onBeforePostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n onAfterPostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n postMessage(opts: {\n message: IPublishPayload;\n transferList: readonly Transferable[] | undefined;\n }): ValueOrPromise<void>;\n}\n"]}
@@ -1,10 +1,10 @@
1
- import { type AnyType, type ValueOrPromise } from '../../../common/types/index.js';
1
+ import { type ValueOrPromise } from '../../../common/types/index.js';
2
2
  import { BaseHelper } from '../../base.js';
3
3
  import { type IWorkerBus, type IWorkerThread } from '../common/index.js';
4
4
  /** Base for the worker-side helper that holds message buses by key. */
5
5
  export declare abstract class AbstractWorkerThreadHelper extends BaseHelper implements IWorkerThread {
6
6
  buses: {
7
- [workerKey: string | symbol]: IWorkerBus<AnyType, AnyType>;
7
+ [workerKey: string | symbol]: IWorkerBus<never, never>;
8
8
  };
9
9
  abstract bindWorkerBus<IC, IP>(opts: {
10
10
  key: string;