@axiumine/koa-utils 9.2.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,7 +34,6 @@ yarn add @node-rs/bcrypt graphql mongoose redis
34
34
  | `graphql` | `graphQL/throw/*`, `graphQL/schema/types/*`, `graphQL/schema/GraphQLInput/*`, the mutations, and every subpath that raises a `GraphQLError` through a `throw*` helper: `lib/checkEmailLen`, `lib/checkPwdLen`, `lib/tryCatchRethrow`, `lib/MongoDB/*`, `lib/MariaDB/throwSqlErrors`, `lib/throwIfNotValidEnumValue`, `lib/access/create*Flow`, `lib/access/*Mailer`, `koa/customFormatErrorFn`, `koa/tdwKoaErrorHandler`, the `koa/middleware/*` handlers, `koa/router/verifyEmail`, `email/SocketLabsLib`, `files/uploadTempImage` and `files/reEncodeTo*` |
35
35
  | `mongoose` | `dataSources/MongoDB`, the models (`graphQL/models/MongoDB/*`), the mutations other than `logout` and `refresh`, `lib/db/*`, `lib/OBJECTID_0_OBJ`, `lib/access/create*Flow`, `koa/router/verifyEmail`, `koa/middleware/authenticatedAuthorizationHandler`, `koa/middleware/authenticatedResourceHandler` (its types are also named by a few `.d.mts` files) |
36
36
  | `redis` | `dataSources/Redis`, the `login*` / `logout` / `refresh` mutations, `koa/middleware/authenticatedAuthorizationHandler`, `koa/middleware/authenticatedLogoutHandler`, `koa/middleware/authenticatedResourceHandler` |
37
- | `@socketlabs/email` | `email/SocketLabsLib`, `email/createSocketLabsSender`, `lib/access/createResetPwdFlow`, `lib/access/createVerifyEmailFlow`, `lib/access/resetPwdMailer`, `lib/access/verifyEmailMailer`, `koa/router/verifyEmail`, and the `signUp` / `login*` / `resetPwd` / `updatePassword` / `emailChangeHashVerify` mutations |
38
37
  | `@gltf-transform/core`, `@gltf-transform/extensions`, `@gltf-transform/functions`, `gltf-validator`, `meshoptimizer` | `files/sanitiseGlb`, `files/sanitiseGlbFile` only (the GLB sanitiser; `sharp` is needed there too). `gltf-validator` is published only as `2.0.0-dev.*` prereleases, so its peer range is `>=2.0.0-0 <3` |
39
38
  | `clamscan` | `files/scanVirus`, `files/uploadTempImage`, `files/uploadTempPdf` |
40
39
  | `file-type` | `files/validateMimeType`, `files/validateMimeTypeImages`, `files/validateJpgPngMimeType`, `files/validateMimeTypeGlb`, `files/uploadTempImage`, `files/uploadTempPdf` — loaded lazily, at first call |
@@ -50,7 +49,7 @@ yarn add @node-rs/bcrypt graphql mongoose redis
50
49
 
51
50
  A subpath that reaches no peer needs nothing installed, not even `koa` (it appears there only as a type you pass in): `koa/createKoaErrorHandler`, a Koa error middleware you configure with `statusOf`, `bodyOf`, `report` and `noBodyStatuses`, and its two type files `koa/IKoaErrorHandlerOptions` and `koa/IKoaErrorHandlerContext`. `koa/tdwKoaErrorHandler` is the same middleware preconfigured for GraphQL errors, Sentry and dotenv, which is why it needs the peers above.
52
51
 
53
- `email/createSocketLabsSender` needs only `@socketlabs/email`: it builds a function that sends one mail you composed, with your own `serverId` and `apiKey`, and returns `{ ok: true }` or `{ ok: false, code }` instead of throwing on a rejected send. It reads no environment variable and loads no Sentry, no dotenv and no `graphql`; its four type files (`email/ISocketLabsSenderOptions`, `ISocketLabsMessage`, `ISocketLabsSendResult`, `ISocketLabsClient`) need nothing installed. `email/SocketLabsLib` sends through it and adds the copy, the HTML template, the environment variables and the Sentry report.
52
+ `email/createSocketLabsSender` needs nothing installed: it builds a function that sends one mail you composed, with your own `serverId` and `apiKey`, and returns `{ ok: true }` or `{ ok: false, code }` instead of throwing on a rejected send. It posts to the SocketLabs Injection API with Node's built-in `fetch` (a timeout, and retries on a timeout or a 429, 500, 502, 503 or 504 answer), reads no environment variable and loads no Sentry, no dotenv and no `graphql`; its four type files (`email/ISocketLabsSenderOptions`, `ISocketLabsMessage`, `ISocketLabsSendResult`, `ISocketLabsClient`) need nothing installed either. `email/SocketLabsLib` sends through it and adds the copy, the HTML template, the environment variables and the Sentry report. `@socketlabs/email` is not a peer of this package any more and nothing here imports it: remove it from your project if this package was the only reason you installed it (it depends on `axios` 0.21, which has published advisories). Node's `fetch` does not read `HTTP_PROXY` / `HTTPS_PROXY` on its own: behind a proxy, start Node with `NODE_USE_ENV_PROXY=1`.
54
53
 
55
54
  The PostgreSQL kit under `lib/PostgreSQL/{error,parse,pool,url,counter,tx,guard,role,clock,lock}/` reaches no peer either, `pg` included: `lib/PostgreSQL/pool/createPool` takes the `pg` module you imported as its `driver` argument and talks to it through structural types, so you install `pg` yourself for your own code and the kit never imports it. It holds the pool factory (URL allow-list, `SHOW timezone` must answer `UTC`, one connect deadline, a listener for idle-client errors), `lib/PostgreSQL/tx/withTx` (one transaction wrapper: closed `BEGIN`, `SET LOCAL lock_timeout`, a bounded retry on deadlocks and serialisation failures, and an error factory you pass in), string parsers for `date`, `time`, `timestamptz`, `int8`, `uuid` and arrays of them that never build a `Date`, closed-reason `DbParseError`, `DbConnectError` and `DbTxError`, SQLSTATE readers, `lib/PostgreSQL/error/mapDbError` (turns any driver failure into an error of your own family through a constraint table you pass in, and logs a closed reason, never the driver text), `lib/PostgreSQL/guard/assertAffected` and `guardVersion` (say why an update matched no row), `lib/PostgreSQL/role/assertRole` (a boot check that the connected database role has no dangerous attribute, owns nothing, has no unlisted membership and holds the grants you list, with a closed-reason `RoleAssertionError`), `lib/PostgreSQL/clock/createDbClock` (the server time read once per transaction, which a write transaction may read only after a lock), `lib/PostgreSQL/lock/createLockOrderTracker` (the order of the locks of a transaction from a spec you give, checked before each statement) with the small parts for writing your own lock helpers (the kit exports no lock clause), and `databaseUrlReason`, a strict check for a database URL. See [docs/code/lib-postgres.md](https://github.com/Axiumine/koa-utils/blob/main/docs/code/lib-postgres.md).
56
55
 
@@ -326,7 +325,7 @@ yarn check:static # every static gate: caps, lint, typecheck (src, scripts, spec
326
325
  yarn clean
327
326
  ```
328
327
 
329
- Source files are `.mts`. Imports use `.mjs` extension explicitly (NodeNext). Path aliases (`@lib/*`, `@throw/*`, `@models/*`, `@context/*`, `@stypes/*`, `@private/*`, `@email/*`, `@dataSources/*`) are rewritten to relative paths in emitted code via `typescript-transform-paths` (run through `tspc`, the `ts-patch` wrapper).
328
+ Source files are `.mts`. Imports use `.mjs` extension explicitly (NodeNext). Path aliases (`@lib/*`, `@throw/*`, `@models/*`, `@context/*`, `@stypes/*`, `@private/*`, `@email/*`, `@dataSources/*`) are rewritten to relative paths in the emitted `.mjs` / `.d.mts` right after `tsc`, by `scripts/rewrite-path-aliases.mts`, which reads the alias map from the tsconfig `paths`. The build is a plain `tsc` plus that step: it does not patch the compiler or need a transformer plugin.
330
329
 
331
330
  Adding a new public symbol requires both:
332
331
  1. Creating `src/<area>/<Name>.mts`
@@ -1,7 +1,8 @@
1
1
  /**
2
- * The part of a SocketLabs client that {@link createSocketLabsSender} calls. `SocketLabsClient` fits it, and so does a
3
- * test double such as `{ send: async () => ({}) }`. It is declared here because the SocketLabs SDK ships no types
4
- * and this package never imports a type from it, so `.d.mts` files that name this interface need no peer.
2
+ * The part of a SocketLabs client that {@link createSocketLabsSender} calls. The client the sender builds fits it, so does
3
+ * the `SocketLabsClient` of the SocketLabs Node SDK if you still use it, and so does a test double such as
4
+ * `{ send: async () => ({}) }`. A client resolves when the mail was accepted and rejects when it was not; the sender turns
5
+ * the rejection into `{ ok: false, code }`. It is declared here so `.d.mts` files that name this interface need no package.
5
6
  */
6
7
  export interface ISocketLabsClient {
7
8
  send(message: unknown): Promise<unknown>;
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * One mail handed to the function that {@link createSocketLabsSender} returns. A single recipient, no attachments,
3
- * no copies. `text` and `html` are both optional here, but the SDK rejects a message with neither (`MessageValidationEmptyMessage`).
3
+ * no copies. `text` and `html` are both optional here, but a message with neither is not sent: the send fails with the code `MessageValidationEmptyMessage`.
4
4
  */
5
5
  export interface ISocketLabsMessage {
6
6
  /** Sender address. */
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * What the function from {@link createSocketLabsSender} resolves to. A failed send does not reject: it resolves to
3
- * `{ ok: false, code }`, where `code` is the `name` of the SDK's result enum (`'Timeout'`, `'InvalidAuthentication'`,
4
- * `'Warning'`, ...) or `'UnknownError'` when the rejection carries none. The code is all that is exposed: never the
5
- * SDK's response message, the per-recipient results or the raw rejection, which can hold recipients and a receipt.
3
+ * `{ ok: false, code }`, where `code` is a SocketLabs result name (`'Timeout'`, `'InvalidAuthentication'`,
4
+ * `'Warning'`, ...) or `'UnknownError'` when the rejection carries none. The code is all that is exposed: never a
5
+ * response message, the per-recipient results or the raw rejection, which can hold recipients and a receipt.
6
6
  */
7
7
  export type ISocketLabsSendResult = {
8
8
  ok: true;
@@ -1,7 +1,7 @@
1
1
  import type { ISocketLabsClient } from './ISocketLabsClient.mjs';
2
2
  /**
3
3
  * Options of {@link createSocketLabsSender}. Nothing is read from the environment: you pass the credentials.
4
- * There is no `endpointUrl` and no proxy option on purpose, so the sender can only talk to the SDK's default endpoint.
4
+ * There is no `endpointUrl` and no proxy option on purpose, so the sender can only talk to the SocketLabs Injection API.
5
5
  */
6
6
  export interface ISocketLabsSenderOptions {
7
7
  /** SocketLabs server id. Not validated here. Ignored when `client` is given. */
@@ -9,21 +9,22 @@ export interface ISocketLabsSenderOptions {
9
9
  /** SocketLabs injection API key. Not validated here, never put in an error text. Ignored when `client` is given. */
10
10
  apiKey: string;
11
11
  /**
12
- * Timeout of one HTTP request, in seconds. Default 120. Must be finite and above 0, else `RangeError` when the
13
- * sender is created. Unused when `client` is given.
12
+ * Timeout of one HTTP request, in seconds, counted from the start of the request to the last byte of the answer. Default 120.
13
+ * Must be finite and above 0, else `RangeError` when the sender is created. Unused when `client` is given.
14
14
  */
15
15
  requestTimeout?: number | undefined;
16
16
  /**
17
- * How many times the SDK retries a failed request. Default 3. Must be an integer from 0 to 5, else `RangeError` when
18
- * the sender is created. Unused when `client` is given. Retries add to the time one send can take
19
- * (up to `requestTimeout` x (1 + `numberOfRetries`) plus the SDK's back-off), and a retry after a timeout can deliver the mail twice.
17
+ * How many times the client retries a failed request: a timeout, or a 429, 500, 502, 503 or 504 answer (`Retry-After` is not read). Default 3. Must be an
18
+ * integer from 0 to 5, else `RangeError` when the sender is created. Unused when `client` is given. Retries add to the time
19
+ * one send can take (up to `requestTimeout` x (1 + `numberOfRetries`) plus a back-off of 1 to 10 s before each retry), and a
20
+ * retry after a timeout can deliver the mail twice.
20
21
  */
21
22
  numberOfRetries?: number | undefined;
22
- /** Use this client instead of building a `SocketLabsClient`. For tests and for a client you configure yourself. */
23
+ /** Use this client instead of the built-in one. For tests and for a client you configure yourself. */
23
24
  client?: ISocketLabsClient | undefined;
24
25
  /**
25
26
  * Called with the raw rejection of a failed send, before the sender resolves to `{ ok: false, code }`. Default: nothing.
26
- * The value is whatever the client rejected with (a `SendResponse`, an `Error`, a `TypeError`, a string, `null`) and can
27
+ * The value is whatever the client rejected with (the built-in client rejects with an `Error` that carries a `result`; another client may reject with a `SendResponse`, a `TypeError`, a string, `null`) and can
27
28
  * hold recipients and a transaction receipt: do not log or serialise it as is. A throw from here rejects the sender's promise.
28
29
  */
29
30
  onError?: ((rejection: unknown) => void) | undefined;
@@ -42,21 +42,8 @@ export declare class SocketLabsLib {
42
42
  */
43
43
  sendEmailVerify(emailTo: string, hash: string, name?: string, linkBase?: string, linkPath?: string): Promise<boolean>;
44
44
  /**
45
- * A timed-out send is reported as failed and is not retried by this class. The client is built with
46
- * `numberOfRetries: 3`; whether the SDK retries a timeout has not been verified.
47
- *
48
- statusCode: ECONNABORTED
49
- Error in sending the email
50
- SendResponse {
51
- transactionReceipt: null,
52
- addressResults: null,
53
- result: {
54
- name: 'Timeout',
55
- value: 1,
56
- message: 'A timeout occurred sending the message'
57
- },
58
- responseMessage: 'A timeout occurred sending the message'
59
- }
45
+ * A timed-out send is retried by the client (`numberOfRetries: 3`, with a back-off of 1 to 10 s between tries). When the
46
+ * last try times out as well, the send is reported as failed and the template methods return `false`. This class adds no retry of its own.
60
47
  */
61
48
  sendEmailChangeVerify(emailTo: string, hash: string, name?: string): Promise<boolean>;
62
49
  sendWelcome(emailTo: string): Promise<boolean>;
@@ -5,9 +5,9 @@ import { confirmationLink, httpLinkBase } from "../private/email/messageParts.mj
5
5
  import * as notice from "../private/email/noticeMessages.mjs";
6
6
  import { orFalse } from "../private/email/orFalse.mjs";
7
7
  import * as reset from "../private/email/resetMessages.mjs";
8
+ import { createSocketLabsClient } from "../private/email/socketLabsClient.mjs";
8
9
  import { loadEnv } from "../private/lib/loadEnv.mjs";
9
10
  import * as Sentry from "../private/lib/sentry.mjs";
10
- import { SocketLabsClient } from '@socketlabs/email';
11
11
  import { createSocketLabsSender } from './createSocketLabsSender.mjs';
12
12
  loadEnv();
13
13
  export class SocketLabsLib {
@@ -24,9 +24,7 @@ export class SocketLabsLib {
24
24
  /* c8 ignore next -- env fallback '0' covered only when SOCKETLABS_SERVER_ID is unset */
25
25
  const serverId = parseInt(process.env['SOCKETLABS_SERVER_ID'] || '0');
26
26
  const apiKey = `${process.env['SOCKETLABS_SERVER_APIKEY']}`;
27
- // The import is `any` (src/types/socketlabs-email.d.ts): one assertion gives the constructor the shape used here
28
- const Client = SocketLabsClient;
29
- this.client = new Client(serverId, apiKey, { requestTimeout: 120, numberOfRetries: 3 });
27
+ this.client = createSocketLabsClient({ serverId, apiKey, requestTimeout: 120, numberOfRetries: 3 });
30
28
  this.credentials = { serverId, apiKey };
31
29
  this.platformName = `${process.env['PLATFORM_NAME']}`;
32
30
  this.linkBase = `${process.env['APP_DOMAIN']}`;
@@ -105,21 +103,8 @@ export class SocketLabsLib {
105
103
  }
106
104
  */
107
105
  /**
108
- * A timed-out send is reported as failed and is not retried by this class. The client is built with
109
- * `numberOfRetries: 3`; whether the SDK retries a timeout has not been verified.
110
- *
111
- statusCode: ECONNABORTED
112
- Error in sending the email
113
- SendResponse {
114
- transactionReceipt: null,
115
- addressResults: null,
116
- result: {
117
- name: 'Timeout',
118
- value: 1,
119
- message: 'A timeout occurred sending the message'
120
- },
121
- responseMessage: 'A timeout occurred sending the message'
122
- }
106
+ * A timed-out send is retried by the client (`numberOfRetries: 3`, with a back-off of 1 to 10 s between tries). When the
107
+ * last try times out as well, the send is reported as failed and the template methods return `false`. This class adds no retry of its own.
123
108
  */
124
109
  async sendEmailChangeVerify(emailTo, hash, name = '') {
125
110
  const link = `${httpLinkBase(this.linkBase)}/check/verify-change-email/${encodeURI(emailTo)}/${hash}`;
@@ -4,16 +4,17 @@ import type { ISocketLabsSendResult } from './ISocketLabsSendResult.mjs';
4
4
  /**
5
5
  * Builds a function that sends one mail through SocketLabs and reports the outcome as a value.
6
6
  *
7
- * The returned function builds a `BasicMessage` (setters in the order `setFromAddress`, `setSubject`, `setTextBody`,
8
- * `setHtmlBody`, `setTo`, `setMessageId`) and passes it to the client. On success it resolves to `{ ok: true }`. When the
9
- * client rejects it calls `onError` with the raw rejection and resolves to `{ ok: false, code }`, where `code` is
10
- * `rejection.result.name` if that is a string and `'UnknownError'` otherwise.
7
+ * The returned function builds the message (`buildBasicMessage`: the fields of the SocketLabs SDK's `BasicMessage`) and passes
8
+ * it to the client. On success it resolves to `{ ok: true }`. When the client rejects it calls `onError` with the raw
9
+ * rejection and resolves to `{ ok: false, code }`, where `code` is `rejection.result.name` if that is a string and
10
+ * `'UnknownError'` otherwise.
11
11
  *
12
- * There is no `try`/`catch`: a throw from a setter or from `client.send` itself, and a throw from `onError`, reject the
13
- * returned promise, and when a setter throws `client.send` is never called.
12
+ * There is no `try`/`catch`: a throw from the message builder (a field that is not a string), from `client.send` itself,
13
+ * and from `onError`, reject the returned promise, and when the builder throws `client.send` is never called.
14
14
  *
15
- * It reads no environment variable and checks nothing about `serverId` and `apiKey`: the SDK rejects bad credentials
16
- * at send time. Importing it loads the SocketLabs SDK (the optional peer of this subpath) and nothing else: no Sentry, no dotenv.
15
+ * The built-in client posts with `fetch` to the SocketLabs Injection API and nothing else; it needs no package. The sender reads no
16
+ * environment variable and checks nothing about `serverId` and `apiKey` when it is created: a bad pair is rejected at
17
+ * send time and comes back as a code. Importing it loads no peer: no Sentry, no dotenv.
17
18
  *
18
19
  * @throws RangeError `requestTimeout` is not a finite number above 0, or `numberOfRetries` is not an integer from 0 to 5. The text never holds the API key.
19
20
  */
@@ -1,15 +1,13 @@
1
- import { BasicMessage, SocketLabsClient } from '@socketlabs/email';
1
+ import { createSocketLabsClient } from "../private/email/socketLabsClient.mjs";
2
+ import { buildBasicMessage } from "../private/email/socketLabsMessage.mjs";
2
3
  /** Seconds, what `SocketLabsLib` has always passed. */
3
4
  const DEFAULT_REQUEST_TIMEOUT = 120;
4
5
  /** What `SocketLabsLib` has always passed. */
5
6
  const DEFAULT_NUMBER_OF_RETRIES = 3;
6
7
  /** Upper bound of `numberOfRetries`: every retry can run a full timeout, so a larger value outlives any sane job lease. */
7
8
  const MAX_NUMBER_OF_RETRIES = 5;
8
- /** The SDK's own name for a rejection it cannot classify (`sendResultEnum.UnknownError`). */
9
+ /** The name a failure gets when nothing classifies it: the name the SocketLabs SDK's result enum gave it. */
9
10
  const UNKNOWN_ERROR = 'UnknownError';
10
- // The import is `any` (src/types/socketlabs-email.d.ts): one assertion each gives the two classes the shapes above
11
- const Message = BasicMessage;
12
- const Client = SocketLabsClient;
13
11
  // Messages name the constraint, never the value: the options object also holds the API key
14
12
  function assertRequestTimeout(requestTimeout) {
15
13
  if (!Number.isFinite(requestTimeout) || requestTimeout <= 0) {
@@ -21,7 +19,7 @@ function assertNumberOfRetries(numberOfRetries) {
21
19
  throw new RangeError(`numberOfRetries must be an integer from 0 to ${MAX_NUMBER_OF_RETRIES}`);
22
20
  }
23
21
  }
24
- /** `rejection.result.name` when it is a string, else `'UnknownError'`. The SDK rejects with a `SendResponse` whose `result` is one of its enum values. */
22
+ /** `rejection.result.name` when it is a string, else `'UnknownError'`. The built-in client rejects with an error whose `result` holds the name. */
25
23
  const codeOf = (rejection) => {
26
24
  const name = rejection?.result?.name;
27
25
  return typeof name === 'string' ? name : UNKNOWN_ERROR;
@@ -29,16 +27,17 @@ const codeOf = (rejection) => {
29
27
  /**
30
28
  * Builds a function that sends one mail through SocketLabs and reports the outcome as a value.
31
29
  *
32
- * The returned function builds a `BasicMessage` (setters in the order `setFromAddress`, `setSubject`, `setTextBody`,
33
- * `setHtmlBody`, `setTo`, `setMessageId`) and passes it to the client. On success it resolves to `{ ok: true }`. When the
34
- * client rejects it calls `onError` with the raw rejection and resolves to `{ ok: false, code }`, where `code` is
35
- * `rejection.result.name` if that is a string and `'UnknownError'` otherwise.
30
+ * The returned function builds the message (`buildBasicMessage`: the fields of the SocketLabs SDK's `BasicMessage`) and passes
31
+ * it to the client. On success it resolves to `{ ok: true }`. When the client rejects it calls `onError` with the raw
32
+ * rejection and resolves to `{ ok: false, code }`, where `code` is `rejection.result.name` if that is a string and
33
+ * `'UnknownError'` otherwise.
36
34
  *
37
- * There is no `try`/`catch`: a throw from a setter or from `client.send` itself, and a throw from `onError`, reject the
38
- * returned promise, and when a setter throws `client.send` is never called.
35
+ * There is no `try`/`catch`: a throw from the message builder (a field that is not a string), from `client.send` itself,
36
+ * and from `onError`, reject the returned promise, and when the builder throws `client.send` is never called.
39
37
  *
40
- * It reads no environment variable and checks nothing about `serverId` and `apiKey`: the SDK rejects bad credentials
41
- * at send time. Importing it loads the SocketLabs SDK (the optional peer of this subpath) and nothing else: no Sentry, no dotenv.
38
+ * The built-in client posts with `fetch` to the SocketLabs Injection API and nothing else; it needs no package. The sender reads no
39
+ * environment variable and checks nothing about `serverId` and `apiKey` when it is created: a bad pair is rejected at
40
+ * send time and comes back as a code. Importing it loads no peer: no Sentry, no dotenv.
42
41
  *
43
42
  * @throws RangeError `requestTimeout` is not a finite number above 0, or `numberOfRetries` is not an integer from 0 to 5. The text never holds the API key.
44
43
  */
@@ -47,16 +46,11 @@ export function createSocketLabsSender(options) {
47
46
  const numberOfRetries = options.numberOfRetries ?? DEFAULT_NUMBER_OF_RETRIES;
48
47
  assertRequestTimeout(requestTimeout);
49
48
  assertNumberOfRetries(numberOfRetries);
50
- const client = options.client ?? new Client(options.serverId, options.apiKey, { requestTimeout, numberOfRetries });
49
+ const client = options.client ??
50
+ createSocketLabsClient({ serverId: options.serverId, apiKey: options.apiKey, requestTimeout, numberOfRetries });
51
51
  const { onError } = options;
52
52
  return async function sendSocketLabsMessage(message) {
53
- const basicMessage = new Message();
54
- basicMessage.setFromAddress(message.from, message.fromName);
55
- basicMessage.setSubject(message.subject);
56
- basicMessage.setTextBody(message.text);
57
- basicMessage.setHtmlBody(message.html);
58
- basicMessage.setTo(message.to);
59
- basicMessage.setMessageId(message.messageId);
53
+ const basicMessage = buildBasicMessage(message);
60
54
  return client.send(basicMessage).then(() => ({ ok: true }), (rejection) => {
61
55
  onError?.(rejection);
62
56
  return { ok: false, code: codeOf(rejection) };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * One address of a message. A key with no value is absent, never `undefined`: that is how the SocketLabs SDK's
3
+ * `EmailAddress` held it, and a client double that checks `'friendlyName' in from` keeps working.
4
+ */
5
+ export interface ISocketLabsAddress {
6
+ emailAddress?: string;
7
+ friendlyName?: string;
8
+ }
9
+ /**
10
+ * The message `createSocketLabsSender` hands to `client.send`: the data fields of the SDK's `BasicMessage`, with the
11
+ * same names, so a double written against the SDK reads it unchanged and an SDK `SocketLabsClient` can still send it.
12
+ * A field with no value is absent.
13
+ */
14
+ export interface ISocketLabsBasicMessage {
15
+ messageType: 'basic';
16
+ from: ISocketLabsAddress;
17
+ to: ISocketLabsAddress[];
18
+ subject?: string;
19
+ textBody?: string;
20
+ htmlBody?: string;
21
+ messageId?: string;
22
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISocketLabsBasicMessage.mjs.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * What a send came to, before it is turned into a resolution or a rejection. `name` is the SocketLabs result name
3
+ * (`'Success'`, `'Timeout'`, `'InvalidAuthentication'`, ...); it is absent when the outcome could not be classified,
4
+ * which the sender reports as `'UnknownError'`.
5
+ */
6
+ export interface ISocketLabsOutcome {
7
+ name?: string;
8
+ transactionReceipt?: string;
9
+ addressResults?: Record<string, unknown>[];
10
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ISocketLabsOutcome.mjs.map
@@ -0,0 +1,17 @@
1
+ import type { ISocketLabsOutcome } from './ISocketLabsOutcome.mjs';
2
+ /**
3
+ * What the built-in client rejects with when a send fails. It has the fields the SocketLabs SDK's `SendResponse` had
4
+ * (`result.name`, `transactionReceipt`, `addressResults`) and is an `Error`, so a report made from it has a stack and a
5
+ * title. The text holds the result name and nothing else: no key, no recipient, no body. `addressResults` can hold
6
+ * recipients and `transactionReceipt` is the server's receipt, so the object is not for logging as it is.
7
+ */
8
+ export declare class SocketLabsSendError extends Error {
9
+ readonly name = "SocketLabsSendError";
10
+ /** Absent, as a key, when the failure could not be classified. `declare` so no empty field is emitted. */
11
+ readonly result?: {
12
+ name: string;
13
+ };
14
+ readonly transactionReceipt: string | null;
15
+ readonly addressResults: Record<string, unknown>[] | null;
16
+ constructor(outcome: ISocketLabsOutcome);
17
+ }
@@ -0,0 +1,21 @@
1
+ const UNKNOWN_ERROR = 'UnknownError';
2
+ /**
3
+ * What the built-in client rejects with when a send fails. It has the fields the SocketLabs SDK's `SendResponse` had
4
+ * (`result.name`, `transactionReceipt`, `addressResults`) and is an `Error`, so a report made from it has a stack and a
5
+ * title. The text holds the result name and nothing else: no key, no recipient, no body. `addressResults` can hold
6
+ * recipients and `transactionReceipt` is the server's receipt, so the object is not for logging as it is.
7
+ */
8
+ export class SocketLabsSendError extends Error {
9
+ name = 'SocketLabsSendError';
10
+ transactionReceipt;
11
+ addressResults;
12
+ constructor(outcome) {
13
+ super(`SocketLabs send failed: ${outcome.name ?? UNKNOWN_ERROR}`);
14
+ if (outcome.name !== undefined) {
15
+ this.result = { name: outcome.name };
16
+ }
17
+ this.transactionReceipt = outcome.transactionReceipt ?? null;
18
+ this.addressResults = outcome.addressResults ?? null;
19
+ }
20
+ }
21
+ //# sourceMappingURL=SocketLabsSendError.mjs.map
@@ -0,0 +1,26 @@
1
+ import type { ISocketLabsClient } from "../../email/ISocketLabsClient.mjs";
2
+ export interface ISocketLabsClientOptions {
3
+ serverId: number;
4
+ apiKey: string;
5
+ /** Seconds one request may take, from the start of the call to the last byte of the answer. Finite and above 0. */
6
+ requestTimeout: number;
7
+ /** Retries after the first attempt, from 0 to 5. */
8
+ numberOfRetries: number;
9
+ /** Tests only: where to post. The sender never passes it, so the endpoint cannot be changed from outside. */
10
+ endpointUrl?: string;
11
+ /** Tests only: the wait between attempts. */
12
+ sleep?: (ms: number) => Promise<unknown>;
13
+ /** Tests only: the randomness of the back-off, a function returning a number from 0 up to 1. */
14
+ random?: () => number;
15
+ }
16
+ /**
17
+ * The wait before retry number `retry` (0 for the first), the SDK's `promise-retry` setting: `minTimeout` 1000, factor 2,
18
+ * randomised by a factor from 1 up to 2, `maxTimeout` 10000. So 1-2 s, 2-4 s, 4-8 s, 8-10 s, then 10 s.
19
+ */
20
+ export declare function backoffMs(retry: number, random: () => number): number;
21
+ /**
22
+ * A client for the SocketLabs Injection API built on `fetch`, replacing the `@socketlabs/email` SDK. `send` takes the message
23
+ * `buildBasicMessage` makes and resolves with the outcome when SocketLabs accepted it. Every failure rejects with a
24
+ * `SocketLabsSendError` whose `result.name` is the code `createSocketLabsSender` reports; a failure that cannot be classified has no `result`.
25
+ */
26
+ export declare function createSocketLabsClient(options: ISocketLabsClientOptions): ISocketLabsClient;
@@ -0,0 +1,80 @@
1
+ import { sleepMs } from "../../lib/sleepMs.mjs";
2
+ import { buildInjectionRequest, credentialsOutcome, messageOutcome } from './socketLabsRequest.mjs';
3
+ import { parseInjectionResponse } from './socketLabsResponse.mjs';
4
+ import { SocketLabsSendError } from './SocketLabsSendError.mjs';
5
+ /** The SocketLabs Injection API, the only host the client talks to. Fixed: nothing a caller passes can change it. */
6
+ const INJECTION_ENDPOINT = 'https://inject.socketlabs.com/api/v1/email';
7
+ /**
8
+ * The statuses retried, besides a timeout: the four the SDK retried (500, 502, 503, 504) and 429, which is retried on purpose, a deviation
9
+ * from the SDK. A 429 means the request was rejected, so a retry cannot deliver the mail twice. No other 4xx is retried, and no network
10
+ * error either: that request may have reached SocketLabs, so a retry could send the mail twice. `Retry-After` is not read.
11
+ */
12
+ const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
13
+ const BACKOFF_MIN_MS = 1000;
14
+ const BACKOFF_MAX_MS = 10_000;
15
+ /** Longest delay a Node timer can hold: a larger one makes it fire after 1 ms. */
16
+ const MAX_TIMEOUT_MS = 2_147_483_647;
17
+ /**
18
+ * The wait before retry number `retry` (0 for the first), the SDK's `promise-retry` setting: `minTimeout` 1000, factor 2,
19
+ * randomised by a factor from 1 up to 2, `maxTimeout` 10000. So 1-2 s, 2-4 s, 4-8 s, 8-10 s, then 10 s.
20
+ */
21
+ export function backoffMs(retry, random) {
22
+ return Math.min((random() + 1) * BACKOFF_MIN_MS * 2 ** retry, BACKOFF_MAX_MS);
23
+ }
24
+ async function post(url, request, timeoutMs) {
25
+ const signal = AbortSignal.timeout(timeoutMs);
26
+ try {
27
+ // redirect 'error': the key and the mail go to the endpoint above and nowhere else
28
+ const response = await fetch(url, {
29
+ method: 'POST',
30
+ headers: request.headers,
31
+ body: request.body,
32
+ signal,
33
+ redirect: 'error'
34
+ });
35
+ return { kind: 'http', status: response.status, text: await response.text() };
36
+ }
37
+ catch {
38
+ // The error itself is dropped on purpose: it comes from the HTTP stack and nothing in it is worth the risk of carrying a header value
39
+ return signal.aborted ? { kind: 'timeout' } : { kind: 'network' };
40
+ }
41
+ }
42
+ const isRetryable = (attempt) => attempt.kind === 'timeout' || (attempt.kind === 'http' && RETRY_STATUSES.has(attempt.status));
43
+ function outcomeOf(attempt) {
44
+ if (attempt.kind === 'timeout') {
45
+ return { name: 'Timeout' };
46
+ }
47
+ return attempt.kind === 'network' ? {} : parseInjectionResponse(attempt.status, attempt.text);
48
+ }
49
+ /**
50
+ * A client for the SocketLabs Injection API built on `fetch`, replacing the `@socketlabs/email` SDK. `send` takes the message
51
+ * `buildBasicMessage` makes and resolves with the outcome when SocketLabs accepted it. Every failure rejects with a
52
+ * `SocketLabsSendError` whose `result.name` is the code `createSocketLabsSender` reports; a failure that cannot be classified has no `result`.
53
+ */
54
+ export function createSocketLabsClient(options) {
55
+ const { serverId, apiKey, numberOfRetries } = options;
56
+ const url = options.endpointUrl ?? INJECTION_ENDPOINT;
57
+ const sleep = options.sleep ?? sleepMs;
58
+ const random = options.random ?? Math.random;
59
+ const timeoutMs = Math.min(Math.ceil(options.requestTimeout * 1000), MAX_TIMEOUT_MS);
60
+ return {
61
+ async send(message) {
62
+ const invalid = credentialsOutcome(serverId, apiKey) ?? messageOutcome(message);
63
+ if (invalid) {
64
+ throw new SocketLabsSendError(invalid);
65
+ }
66
+ const request = buildInjectionRequest(serverId, apiKey, message);
67
+ let attempt = await post(url, request, timeoutMs);
68
+ for (let retry = 0; retry < numberOfRetries && isRetryable(attempt); retry++) {
69
+ await sleep(backoffMs(retry, random));
70
+ attempt = await post(url, request, timeoutMs);
71
+ }
72
+ const outcome = outcomeOf(attempt);
73
+ if (outcome.name === 'Success') {
74
+ return outcome;
75
+ }
76
+ throw new SocketLabsSendError(outcome);
77
+ }
78
+ };
79
+ }
80
+ //# sourceMappingURL=socketLabsClient.mjs.map
@@ -0,0 +1,9 @@
1
+ import type { ISocketLabsMessage } from "../../email/ISocketLabsMessage.mjs";
2
+ import type { ISocketLabsBasicMessage } from './ISocketLabsBasicMessage.mjs';
3
+ /**
4
+ * Turns what the caller of `createSocketLabsSender` passes into the message `client.send` receives. Fields are read in the
5
+ * order from, from name, subject, text, html, to, message id, so when two are wrong the first of them is the one reported.
6
+ *
7
+ * @throws TypeError a field that is set but is not a string.
8
+ */
9
+ export declare function buildBasicMessage(message: ISocketLabsMessage): ISocketLabsBasicMessage;
@@ -0,0 +1,36 @@
1
+ import { withDefined } from './withDefined.mjs';
2
+ /**
3
+ * An absent value (`undefined`, `null`, `''`, `0`, `false`) gives `undefined`, a string gives itself and anything else
4
+ * throws. The text names the field, never the value.
5
+ */
6
+ function asText(value, label) {
7
+ if (!value) {
8
+ return undefined;
9
+ }
10
+ if (typeof value !== 'string') {
11
+ throw new TypeError(`Invalid ${label}, type of 'string' was expected.`);
12
+ }
13
+ return value;
14
+ }
15
+ /**
16
+ * Turns what the caller of `createSocketLabsSender` passes into the message `client.send` receives. Fields are read in the
17
+ * order from, from name, subject, text, html, to, message id, so when two are wrong the first of them is the one reported.
18
+ *
19
+ * @throws TypeError a field that is set but is not a string.
20
+ */
21
+ export function buildBasicMessage(message) {
22
+ const emailAddress = asText(message.from, 'from address');
23
+ const friendlyName = asText(message.fromName, 'from name');
24
+ const subject = asText(message.subject, 'subject');
25
+ const textBody = asText(message.text, 'text body');
26
+ const htmlBody = asText(message.html, 'html body');
27
+ const recipient = asText(message.to, 'to address');
28
+ const messageId = asText(message.messageId, 'message id');
29
+ return {
30
+ messageType: 'basic',
31
+ from: withDefined({ emailAddress, friendlyName }),
32
+ to: recipient === undefined ? [] : [{ emailAddress: recipient }],
33
+ ...withDefined({ subject, textBody, htmlBody, messageId })
34
+ };
35
+ }
36
+ //# sourceMappingURL=socketLabsMessage.mjs.map
@@ -0,0 +1,19 @@
1
+ import type { ISocketLabsBasicMessage } from './ISocketLabsBasicMessage.mjs';
2
+ import type { ISocketLabsOutcome } from './ISocketLabsOutcome.mjs';
3
+ /** `undefined` when `serverId` is a positive integer and `apiKey` a non-empty string, else the SDK's `AuthenticationValidationFailed`. */
4
+ export declare function credentialsOutcome(serverId: unknown, apiKey: unknown): ISocketLabsOutcome | undefined;
5
+ /**
6
+ * `undefined` when the message can be sent, else the outcome the SDK's validator gave, checked in its order: subject, from
7
+ * address, body, recipients. Nothing is sent for a message that fails here.
8
+ */
9
+ export declare function messageOutcome(message: ISocketLabsBasicMessage): ISocketLabsOutcome | undefined;
10
+ export interface IInjectionRequest {
11
+ headers: Record<string, string>;
12
+ body: string;
13
+ }
14
+ /**
15
+ * What the SDK's `createRequest` sends. A key of the form `<20>.<40>` travels as `Authorization: Bearer <key>` and stays out of
16
+ * the body; any other key travels as `apiKey` in the body and there is no `Authorization` header. The body is
17
+ * `{ serverId, messages: [message] }`. The key is never put anywhere else.
18
+ */
19
+ export declare function buildInjectionRequest(serverId: number, apiKey: string, message: ISocketLabsBasicMessage): IInjectionRequest;
@@ -0,0 +1,86 @@
1
+ /** Longest address the SDK accepts, in characters. */
2
+ const MAX_ADDRESS_LENGTH = 320;
3
+ /** A key of the form `<20 characters>.<40 characters>` is sent as a bearer token; any other key goes in the body. */
4
+ const STRUCTURED_KEY_LENGTH = 61;
5
+ const STRUCTURED_KEY_SEPARATOR_AT = 20;
6
+ const USER_AGENT = `@axiumine/koa-utils (nodejs ${process.version})`;
7
+ /** The same checks as the SDK's `EmailAddress.isValid`: one `@` with something on both sides, none of `,` `;` or a space. */
8
+ function isValidAddress(address) {
9
+ if (address === undefined || address.length > MAX_ADDRESS_LENGTH) {
10
+ return false;
11
+ }
12
+ const parts = address.split('@');
13
+ return parts.length === 2 && parts.every((part) => part.trim().length > 0) && !/[ ,;]/.test(address);
14
+ }
15
+ /** `undefined` when `serverId` is a positive integer and `apiKey` a non-empty string, else the SDK's `AuthenticationValidationFailed`. */
16
+ export function credentialsOutcome(serverId, apiKey) {
17
+ const valid = typeof apiKey === 'string' && apiKey !== '' && typeof serverId === 'number' && Number.isInteger(serverId) && serverId > 0;
18
+ return valid ? undefined : { name: 'AuthenticationValidationFailed' };
19
+ }
20
+ /**
21
+ * `undefined` when the message can be sent, else the outcome the SDK's validator gave, checked in its order: subject, from
22
+ * address, body, recipients. Nothing is sent for a message that fails here.
23
+ */
24
+ export function messageOutcome(message) {
25
+ const { from, to } = message;
26
+ if (!message.subject) {
27
+ return { name: 'MessageValidationEmptySubject' };
28
+ }
29
+ if (!from.emailAddress) {
30
+ return { name: 'EmailAddressValidationMissingFrom' };
31
+ }
32
+ if (!isValidAddress(from.emailAddress)) {
33
+ return { name: 'EmailAddressValidationInvalidFrom' };
34
+ }
35
+ if (!message.htmlBody && !message.textBody) {
36
+ return { name: 'MessageValidationEmptyMessage' };
37
+ }
38
+ if (to.length === 0) {
39
+ return { name: 'RecipientValidationNoneInMessage' };
40
+ }
41
+ const invalid = to.filter((address) => !isValidAddress(address.emailAddress));
42
+ if (invalid.length > 0) {
43
+ return {
44
+ name: 'RecipientValidationInvalidRecipients',
45
+ addressResults: invalid.map((address) => ({
46
+ emailAddress: address.emailAddress,
47
+ accepted: false,
48
+ errorCode: 'InvalidAddress'
49
+ }))
50
+ };
51
+ }
52
+ return undefined;
53
+ }
54
+ // `undefined` values drop out of JSON.stringify, which leaves the keys of the SDK's `BasicMessage.toJSON`, in its order
55
+ const addressJson = ({ emailAddress, friendlyName }) => ({ emailAddress, friendlyName });
56
+ /** One message as the Injection API takes it. */
57
+ function messageJson(message) {
58
+ return {
59
+ subject: message.subject,
60
+ htmlBody: message.htmlBody,
61
+ textBody: message.textBody,
62
+ messageId: message.messageId,
63
+ from: addressJson(message.from),
64
+ to: message.to.map(addressJson)
65
+ };
66
+ }
67
+ const isStructuredApiKey = (apiKey) => apiKey.length === STRUCTURED_KEY_LENGTH && apiKey.indexOf('.') === STRUCTURED_KEY_SEPARATOR_AT;
68
+ /**
69
+ * What the SDK's `createRequest` sends. A key of the form `<20>.<40>` travels as `Authorization: Bearer <key>` and stays out of
70
+ * the body; any other key travels as `apiKey` in the body and there is no `Authorization` header. The body is
71
+ * `{ serverId, messages: [message] }`. The key is never put anywhere else.
72
+ */
73
+ export function buildInjectionRequest(serverId, apiKey, message) {
74
+ const bearer = isStructuredApiKey(apiKey);
75
+ const headers = {
76
+ 'Content-Type': 'application/json;charset=utf-8',
77
+ Accept: 'application/json',
78
+ 'User-Agent': USER_AGENT
79
+ };
80
+ if (bearer) {
81
+ headers['Authorization'] = `Bearer ${apiKey}`;
82
+ }
83
+ const messages = [messageJson(message)];
84
+ return { headers, body: JSON.stringify(bearer ? { serverId, messages } : { apiKey, serverId, messages }) };
85
+ }
86
+ //# sourceMappingURL=socketLabsRequest.mjs.map
@@ -0,0 +1,10 @@
1
+ import type { ISocketLabsOutcome } from './ISocketLabsOutcome.mjs';
2
+ /**
3
+ * Reads the answer of the Injection API, the way the SDK's `SendResponse.parse` does for a response axios let through.
4
+ *
5
+ * Only a `200` is read. Any other status gives an outcome with no name: the SDK looked the status up in a result enum
6
+ * that has no numeric keys, so a `401`, a `500` and a `408` all arrived unclassified. On a `200` the `ErrorCode` of the
7
+ * body names the result; a `Warning` takes the `ErrorCode` of the first message result when that one is known, which
8
+ * is how a rejected recipient shows up. The transaction receipt and the address results ride along for `onError`.
9
+ */
10
+ export declare function parseInjectionResponse(status: number, text: string): ISocketLabsOutcome;
@@ -0,0 +1,49 @@
1
+ import { withDefined } from './withDefined.mjs';
2
+ /** The `ErrorCode` values the Injection API can send, as named in the SocketLabs SDK's result enum. Any other string is not classified. */
3
+ const API_CODES = new Set(('Success Warning InternalError MessageTooLarge TooManyRecipients InvalidData OverQuota TooManyErrors InvalidAuthentication ' +
4
+ 'AccountDisabled TooManyMessages NoValidRecipients InvalidAddress InvalidAttachment NoMessages EmptyMessage EmptySubject ' +
5
+ 'InvalidFrom EmptyToAddress NoValidBodyParts InvalidTemplateId TemplateHasNoContent MessageBodyConflict InvalidMergeData ' +
6
+ 'MetadataOrTagsAreTooLarge').split(' '));
7
+ const isRecord = (value) => typeof value === 'object' && value !== null;
8
+ /** The code when it is a string the API is known to send, else `undefined`. A lookup in a set, so `'constructor'` is not a code. */
9
+ const apiCode = (value) => (typeof value === 'string' && API_CODES.has(value) ? value : undefined);
10
+ const receiptOf = (value) => (typeof value === 'string' && value.length > 0 ? value : undefined);
11
+ const firstMessageResult = (messageResults) => {
12
+ const first = Array.isArray(messageResults) ? messageResults[0] : undefined;
13
+ return isRecord(first) ? first : undefined;
14
+ };
15
+ /**
16
+ * Reads the answer of the Injection API, the way the SDK's `SendResponse.parse` does for a response axios let through.
17
+ *
18
+ * Only a `200` is read. Any other status gives an outcome with no name: the SDK looked the status up in a result enum
19
+ * that has no numeric keys, so a `401`, a `500` and a `408` all arrived unclassified. On a `200` the `ErrorCode` of the
20
+ * body names the result; a `Warning` takes the `ErrorCode` of the first message result when that one is known, which
21
+ * is how a rejected recipient shows up. The transaction receipt and the address results ride along for `onError`.
22
+ */
23
+ export function parseInjectionResponse(status, text) {
24
+ if (status !== 200) {
25
+ return {};
26
+ }
27
+ let body;
28
+ try {
29
+ body = JSON.parse(text);
30
+ }
31
+ catch {
32
+ return { name: 'UnknownError' };
33
+ }
34
+ if (!isRecord(body)) {
35
+ return {};
36
+ }
37
+ const first = firstMessageResult(body['MessageResults']);
38
+ let name = apiCode(body['ErrorCode']);
39
+ if (name === 'Warning' && first) {
40
+ name = apiCode(first['ErrorCode']) ?? name;
41
+ }
42
+ const addressResults = first?.['AddressResults'];
43
+ return withDefined({
44
+ name,
45
+ transactionReceipt: receiptOf(body['TransactionReceipt']),
46
+ addressResults: Array.isArray(addressResults) ? addressResults.filter(isRecord) : undefined
47
+ });
48
+ }
49
+ //# sourceMappingURL=socketLabsResponse.mjs.map
@@ -0,0 +1,4 @@
1
+ /** The same fields without the ones whose value is `undefined`: such a key is absent in the result, not present with no value. */
2
+ export declare function withDefined<T extends Record<string, unknown>>(fields: T): {
3
+ [K in keyof T]?: Exclude<T[K], undefined>;
4
+ };
@@ -0,0 +1,5 @@
1
+ /** The same fields without the ones whose value is `undefined`: such a key is absent in the result, not present with no value. */
2
+ export function withDefined(fields) {
3
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
4
+ }
5
+ //# sourceMappingURL=withDefined.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiumine/koa-utils",
3
- "version": "9.2.0",
3
+ "version": "9.3.0",
4
4
  "description": "Koa Utils",
5
5
  "type": "module",
6
6
  "repository": {
@@ -24,7 +24,7 @@
24
24
  "prepare:all": "echo 'read REAMDE' && rm -rf dist && yarn run build:all",
25
25
  "build:all": "yarn run build:cjs && yarn run build:esm",
26
26
  "build:cjs": "yarn run tsc -p tsconfig.cjs.json && find dist/cjs -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.cjs\"' {} \\; && cp -R dist/cjs/* dist/ && rm -rf dist/cjs",
27
- "build:esm": "yarn run tspc -p tsconfig.json && find dist/esm -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.mjs\"' {} \\; && cp -R dist/esm/* dist/ && find dist -name \"*.mjs.map\" -exec sed -i -E 's#(\"sources\":\\[\")\\.\\./#\\1#' {} + && rm -rf dist/esm",
27
+ "build:esm": "yarn run tsc -p tsconfig.json && find dist/esm -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.mjs\"' {} \\; && node scripts/rewrite-path-aliases.mts tsconfig.json && cp -R dist/esm/* dist/ && find dist -name \"*.mjs.map\" -exec sed -i -E 's#(\"sources\":\\[\")\\.\\./#\\1#' {} + && rm -rf dist/esm",
28
28
  "lint": "eslint --fix && prettier --write 'src/**/*.mts' 'scripts/**/*.mts'",
29
29
  "lint:check": "eslint --max-warnings 0 --cache && prettier --check 'src/**/*.mts' 'scripts/**/*.mts'",
30
30
  "typecheck": "tsc -p tsconfig.check.json --noEmit",
@@ -42,7 +42,7 @@
42
42
  "leak:check": "node --expose-gc scripts/leak-check.mts",
43
43
  "check:static": "yarn caps && yarn lint:check && yarn typecheck && yarn typecheck:scripts && yarn typecheck:tests && yarn knip && yarn type-coverage && yarn fta",
44
44
  "clean": "rm -rf ./dist",
45
- "build:tests": "rm -rf dist-test && yarn run tspc -p tsconfig.build-tests.json && find dist-test -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.mjs\"' {} \\;",
45
+ "build:tests": "rm -rf dist-test && yarn run tsc -p tsconfig.build-tests.json && find dist-test -type f -name \"*.js\" -exec bash -c 'mv \"$0\" \"${0%.js}.mjs\"' {} \\; && node scripts/rewrite-path-aliases.mts tsconfig.build-tests.json",
46
46
  "test": "yarn build && yarn build:tests && mocha",
47
47
  "test:watch": "mocha --watch",
48
48
  "test:coverage": "yarn build && yarn build:tests && c8 mocha",
@@ -1254,7 +1254,6 @@
1254
1254
  "@gltf-transform/functions": "<5",
1255
1255
  "@node-rs/bcrypt": "<2",
1256
1256
  "@sentry/node": "<11",
1257
- "@socketlabs/email": "<2",
1258
1257
  "clamscan": "<3",
1259
1258
  "dotenv": "<18",
1260
1259
  "file-type": "<23",
@@ -1289,9 +1288,6 @@
1289
1288
  "@sentry/node": {
1290
1289
  "optional": true
1291
1290
  },
1292
- "@socketlabs/email": {
1293
- "optional": true
1294
- },
1295
1291
  "clamscan": {
1296
1292
  "optional": true
1297
1293
  },
@@ -1354,7 +1350,6 @@
1354
1350
  "@gltf-transform/functions": "^4.5.1",
1355
1351
  "@node-rs/bcrypt": "^1.10.9",
1356
1352
  "@sentry/node": "^10.78.0",
1357
- "@socketlabs/email": "^1.4.4",
1358
1353
  "@stryker-mutator/core": "10.1.1",
1359
1354
  "@stryker-mutator/mocha-runner": "10.1.1",
1360
1355
  "@stryker-mutator/typescript-checker": "10.1.1",
@@ -1372,7 +1367,7 @@
1372
1367
  "chai": "^6.3.0",
1373
1368
  "clamscan": "^2.4.0",
1374
1369
  "dotenv": "^17.4.2",
1375
- "eslint": "^10.14.0",
1370
+ "eslint": "^10.15.0",
1376
1371
  "eslint-config-prettier": "^10.1.8",
1377
1372
  "eslint-import-resolver-typescript": "^4.4.5",
1378
1373
  "eslint-plugin-n": "^18.5.0",
@@ -1380,23 +1375,23 @@
1380
1375
  "eslint-plugin-security": "^4.2.1",
1381
1376
  "eslint-plugin-simple-import-sort": "^14.0.0",
1382
1377
  "eslint-plugin-sonarjs": "^4.2.2",
1383
- "fast-check": "^4.10.2",
1378
+ "fast-check": "^4.10.3",
1384
1379
  "file-type": "^22.3.0",
1385
1380
  "fs-extra": "^11.4.1",
1386
1381
  "fta-cli": "^3.1.0",
1387
1382
  "gltf-validator": "^2.0.0-dev.3.10",
1388
1383
  "graphql": "^16.15.0",
1389
1384
  "keygrip": "^1.1.0",
1390
- "knip": "^6.44.2",
1385
+ "knip": "^6.45.1",
1391
1386
  "koa": "^3.3.0",
1392
1387
  "mariadb": "^3.5.5",
1393
1388
  "meshoptimizer": "^1.3.0",
1394
1389
  "mocha": "^12.0.3",
1395
1390
  "mongodb-memory-server": "^11.3.0",
1396
- "mongoose": "^9.12.1",
1391
+ "mongoose": "^9.12.2",
1397
1392
  "patch-package": "8.0.1",
1398
1393
  "pg": "^8.23.1",
1399
- "prettier": "^3.9.10",
1394
+ "prettier": "^3.10.1",
1400
1395
  "redis": "^6.3.1",
1401
1396
  "reflect-metadata": "^0.2.2",
1402
1397
  "sequelize": "^6.37.8",
@@ -1404,15 +1399,12 @@
1404
1399
  "sharp": "^0.35.3",
1405
1400
  "sinon": "^22.1.0",
1406
1401
  "ts-node": "^10.9.2",
1407
- "ts-patch": "^4.0.1",
1408
1402
  "type-coverage": "^2.31.2",
1409
1403
  "typescript": "^6.0.3",
1410
1404
  "typescript-eslint": "8.72.2",
1411
- "typescript-transform-paths": "^4.0.0",
1412
1405
  "uuid": "^14.0.3"
1413
1406
  },
1414
1407
  "resolutions": {
1415
- "@socketlabs/email/axios": "^1.21.0",
1416
1408
  "sequelize/uuid": "^11.1.1",
1417
1409
  "typed-rest-client/qs": "^6.16.1",
1418
1410
  "glob": "^14.0.2",