nesties 1.1.5 → 1.1.7
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/dist/index.cjs +577 -24
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.mjs +577 -18
- package/dist/index.mjs.map +4 -4
- package/dist/src/i18n-module/i18n-decorator.d.ts +2 -0
- package/dist/src/i18n-module/i18n-factory.d.ts +8 -0
- package/dist/src/i18n-module/i18n-middleware.type.d.ts +3 -0
- package/dist/src/i18n-module/i18n-module.options.d.ts +6 -0
- package/dist/src/i18n-module/i18n-token.d.ts +5 -0
- package/dist/src/i18n-module/i18n.interceptor.d.ts +7 -0
- package/dist/src/i18n-module/i18n.module.d.ts +3 -0
- package/dist/src/i18n-module/i18n.service.d.ts +22 -0
- package/dist/src/i18n-module/index.d.ts +9 -0
- package/dist/src/i18n-module/locale.pipe.d.ts +14 -0
- package/dist/src/i18n-module/middlewares/index.d.ts +1 -0
- package/dist/src/i18n-module/middlewares/lookup.d.ts +9 -0
- package/dist/src/resolver.d.ts +12 -0
- package/dist/src/token.guard.d.ts +10 -3
- package/dist/src/utility/awaitable.d.ts +1 -0
- package/dist/src/utility/parse-i18n.d.ts +14 -0
- package/index.ts +2 -0
- package/package.json +3 -2
- /package/dist/src/{abort-http-signal.d.ts → utility/abort-http-signal.d.ts} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -207,40 +207,164 @@ import {
|
|
|
207
207
|
UseGuards
|
|
208
208
|
} from "@nestjs/common";
|
|
209
209
|
import { ConfigService } from "@nestjs/config";
|
|
210
|
-
import { ApiHeader } from "@nestjs/swagger";
|
|
210
|
+
import { ApiHeader as ApiHeader2 } from "@nestjs/swagger";
|
|
211
|
+
|
|
212
|
+
// src/resolver.ts
|
|
213
|
+
import {
|
|
214
|
+
ApiHeader,
|
|
215
|
+
ApiQuery
|
|
216
|
+
} from "@nestjs/swagger";
|
|
217
|
+
var coerceToString = (v) => {
|
|
218
|
+
if (v == null) return void 0;
|
|
219
|
+
if (v === false) return void 0;
|
|
220
|
+
if (Array.isArray(v)) return v.length ? coerceToString(v[0]) : void 0;
|
|
221
|
+
if (typeof v === "string") return v;
|
|
222
|
+
if (typeof v === "number") return String(v);
|
|
223
|
+
return void 0;
|
|
224
|
+
};
|
|
225
|
+
var getHeader = (req, name) => {
|
|
226
|
+
const viaMethod = typeof req.getHeader === "function" && req.getHeader(name) || typeof req.header === "function" && req.header(name) || typeof req.get === "function" && req.get(name);
|
|
227
|
+
if (viaMethod) {
|
|
228
|
+
return coerceToString(viaMethod);
|
|
229
|
+
}
|
|
230
|
+
const n = name.toLowerCase();
|
|
231
|
+
const headers = req.headers ?? {};
|
|
232
|
+
if (n in headers) return coerceToString(headers[n]);
|
|
233
|
+
const hit = Object.entries(headers).find(([k]) => k.toLowerCase() === n)?.[1];
|
|
234
|
+
return coerceToString(hit);
|
|
235
|
+
};
|
|
236
|
+
var pickPrimaryFromAcceptLanguage = (v) => {
|
|
237
|
+
if (!v) return void 0;
|
|
238
|
+
const first = v.split(",")[0]?.trim();
|
|
239
|
+
return first?.split(";")[0]?.trim() || first;
|
|
240
|
+
};
|
|
241
|
+
function getQueryValue(req, key) {
|
|
242
|
+
const q = req.query;
|
|
243
|
+
if (q && typeof q === "object" && !("raw" in q)) {
|
|
244
|
+
const v = q[key];
|
|
245
|
+
if (v != null) return coerceToString(v);
|
|
246
|
+
}
|
|
247
|
+
const rawUrl = req.originalUrl ?? req.url;
|
|
248
|
+
if (typeof rawUrl === "string" && rawUrl.includes("?")) {
|
|
249
|
+
try {
|
|
250
|
+
const search = rawUrl.startsWith("http") ? new URL(rawUrl).search : new URL(rawUrl, "http://localhost").search;
|
|
251
|
+
if (search) {
|
|
252
|
+
const params = new URLSearchParams(search);
|
|
253
|
+
const val = params.get(key);
|
|
254
|
+
if (val != null) return val;
|
|
255
|
+
}
|
|
256
|
+
} catch {
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return void 0;
|
|
260
|
+
}
|
|
261
|
+
var createResolver = (_options) => {
|
|
262
|
+
if (typeof _options === "function") {
|
|
263
|
+
return _options;
|
|
264
|
+
}
|
|
265
|
+
const options = _options;
|
|
266
|
+
const field = options.paramType;
|
|
267
|
+
let name = options.paramName;
|
|
268
|
+
if (field === "header") name = name.toLowerCase();
|
|
269
|
+
return (ctx) => {
|
|
270
|
+
const req = ctx.switchToHttp().getRequest();
|
|
271
|
+
if (field === "header") {
|
|
272
|
+
let raw = getHeader(req, name);
|
|
273
|
+
if (name === "accept-language") raw = pickPrimaryFromAcceptLanguage(raw);
|
|
274
|
+
return raw;
|
|
275
|
+
}
|
|
276
|
+
if (field === "query") {
|
|
277
|
+
return getQueryValue(req, name);
|
|
278
|
+
}
|
|
279
|
+
throw new Error(`Unsupported paramType: ${field}`);
|
|
280
|
+
};
|
|
281
|
+
};
|
|
282
|
+
var ApiFromResolver = (_options, extras = {}) => {
|
|
283
|
+
if (typeof _options === "function") {
|
|
284
|
+
return () => {
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
const options = _options;
|
|
288
|
+
const paramType = options?.paramType;
|
|
289
|
+
const apiOptions = {
|
|
290
|
+
name: options.paramName,
|
|
291
|
+
...extras
|
|
292
|
+
};
|
|
293
|
+
return paramType === "header" ? ApiHeader(apiOptions) : paramType === "query" ? ApiQuery({ type: "string", ...apiOptions }) : () => {
|
|
294
|
+
};
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
// src/token.guard.ts
|
|
298
|
+
import { MetadataSetter, Reflector } from "typed-reflector";
|
|
299
|
+
import { ModuleRef } from "@nestjs/core";
|
|
300
|
+
var reflector = new Reflector();
|
|
301
|
+
var Metadata = new MetadataSetter();
|
|
302
|
+
var defaultHeaderName = "x-server-token";
|
|
303
|
+
var defaultConfigName = "SERVER_TOKEN";
|
|
304
|
+
var defaultErrorCode = 401;
|
|
211
305
|
var TokenGuard = class {
|
|
212
|
-
constructor(config) {
|
|
306
|
+
constructor(config, moduleRef) {
|
|
213
307
|
this.config = config;
|
|
214
|
-
this.
|
|
308
|
+
this.moduleRef = moduleRef;
|
|
215
309
|
}
|
|
216
310
|
async canActivate(context) {
|
|
217
|
-
const
|
|
218
|
-
const
|
|
219
|
-
|
|
220
|
-
|
|
311
|
+
const controller = context.getClass();
|
|
312
|
+
const handlerName = context.getHandler()?.name;
|
|
313
|
+
let config = {};
|
|
314
|
+
if (controller) {
|
|
315
|
+
if (handlerName) {
|
|
316
|
+
config = reflector.get("requireTokenOptions", controller, handlerName) || {};
|
|
317
|
+
} else {
|
|
318
|
+
config = reflector.get("requireTokenOptions", controller) || {};
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const resolver = createResolver(
|
|
322
|
+
config.resolver || { paramType: "header", paramName: defaultHeaderName }
|
|
323
|
+
);
|
|
324
|
+
const tokenSource = config.tokenSource || defaultConfigName;
|
|
325
|
+
const [tokenFromClient, tokenFromConfig] = await Promise.all([
|
|
326
|
+
resolver(context, this.moduleRef),
|
|
327
|
+
typeof tokenSource === "function" ? tokenSource(context, this.moduleRef) : this.config.get(tokenSource)
|
|
328
|
+
]);
|
|
329
|
+
if (tokenFromConfig && tokenFromConfig !== tokenFromClient) {
|
|
330
|
+
throw new BlankReturnMessageDto(
|
|
331
|
+
config.errorCode || defaultErrorCode,
|
|
332
|
+
"Unauthorized"
|
|
333
|
+
).toException();
|
|
221
334
|
}
|
|
222
335
|
return true;
|
|
223
336
|
}
|
|
224
337
|
};
|
|
225
338
|
TokenGuard = __decorateClass([
|
|
226
339
|
Injectable(),
|
|
227
|
-
__decorateParam(0, Inject(ConfigService))
|
|
340
|
+
__decorateParam(0, Inject(ConfigService)),
|
|
341
|
+
__decorateParam(1, Inject(ModuleRef))
|
|
228
342
|
], TokenGuard);
|
|
229
|
-
var RequireToken = () =>
|
|
230
|
-
|
|
231
|
-
ApiHeader({
|
|
232
|
-
name: "x-server-token",
|
|
343
|
+
var RequireToken = (options = {}) => {
|
|
344
|
+
const swaggerDec = options.resolver ? ApiFromResolver(options.resolver, {
|
|
233
345
|
description: "Server token",
|
|
234
346
|
required: false
|
|
235
|
-
})
|
|
236
|
-
|
|
237
|
-
|
|
347
|
+
}) : ApiHeader2({
|
|
348
|
+
name: defaultHeaderName,
|
|
349
|
+
description: "Server token",
|
|
350
|
+
required: false
|
|
351
|
+
});
|
|
352
|
+
return MergeClassOrMethodDecorators([
|
|
353
|
+
UseGuards(TokenGuard),
|
|
354
|
+
swaggerDec,
|
|
355
|
+
ApiError(
|
|
356
|
+
options.errorCode || defaultErrorCode,
|
|
357
|
+
"Incorrect server token provided"
|
|
358
|
+
),
|
|
359
|
+
...options ? [Metadata.set("requireTokenOptions", options)] : []
|
|
360
|
+
]);
|
|
361
|
+
};
|
|
238
362
|
|
|
239
363
|
// src/abort-utils.ts
|
|
240
364
|
import { Observable, takeUntil } from "rxjs";
|
|
241
365
|
import { createParamDecorator } from "@nestjs/common";
|
|
242
366
|
|
|
243
|
-
// src/abort-http-signal.ts
|
|
367
|
+
// src/utility/abort-http-signal.ts
|
|
244
368
|
function toRawReq(req) {
|
|
245
369
|
if (req?.raw?.socket) return req.raw;
|
|
246
370
|
return req;
|
|
@@ -342,7 +466,7 @@ var AbortSignalProvider = createProvider(
|
|
|
342
466
|
var InjectAbortSignal = () => Inject2(ABORT_SIGNAL);
|
|
343
467
|
|
|
344
468
|
// src/abortable-module/abortable.token.ts
|
|
345
|
-
import { ContextIdFactory, ModuleRef, REQUEST as REQUEST2 } from "@nestjs/core";
|
|
469
|
+
import { ContextIdFactory, ModuleRef as ModuleRef2, REQUEST as REQUEST2 } from "@nestjs/core";
|
|
346
470
|
var tokenMemo = /* @__PURE__ */ new Map();
|
|
347
471
|
var abortableToken = (token) => {
|
|
348
472
|
if (tokenMemo.has(token)) return tokenMemo.get(token);
|
|
@@ -372,7 +496,7 @@ function createAbortableProvider(token, opts) {
|
|
|
372
496
|
{
|
|
373
497
|
provide,
|
|
374
498
|
scope: Scope2.REQUEST,
|
|
375
|
-
inject: [
|
|
499
|
+
inject: [ModuleRef2, REQUEST2, ABORT_SIGNAL]
|
|
376
500
|
},
|
|
377
501
|
async (moduleRef, req, signal) => {
|
|
378
502
|
const ctxId = ContextIdFactory.getByRequest(req);
|
|
@@ -414,6 +538,431 @@ var AbortableModule = class {
|
|
|
414
538
|
AbortableModule = __decorateClass([
|
|
415
539
|
Module({})
|
|
416
540
|
], AbortableModule);
|
|
541
|
+
|
|
542
|
+
// src/i18n-module/i18n.service.ts
|
|
543
|
+
import {
|
|
544
|
+
ConsoleLogger,
|
|
545
|
+
HttpException as HttpException2,
|
|
546
|
+
Inject as Inject4,
|
|
547
|
+
Injectable as Injectable2
|
|
548
|
+
} from "@nestjs/common";
|
|
549
|
+
|
|
550
|
+
// src/i18n-module/i18n-token.ts
|
|
551
|
+
import { ConfigurableModuleBuilder } from "@nestjs/common";
|
|
552
|
+
var I18nResolverToken = Symbol("I18nResolverToken");
|
|
553
|
+
var { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new ConfigurableModuleBuilder().build();
|
|
554
|
+
var I18nModuleOptionsToken = MODULE_OPTIONS_TOKEN;
|
|
555
|
+
|
|
556
|
+
// src/utility/parse-i18n.ts
|
|
557
|
+
var parseI18n = (text) => {
|
|
558
|
+
const pieces = [];
|
|
559
|
+
if (!text) return pieces;
|
|
560
|
+
let i = 0;
|
|
561
|
+
const n = text.length;
|
|
562
|
+
while (i < n) {
|
|
563
|
+
const start = text.indexOf("#{", i);
|
|
564
|
+
if (start === -1) {
|
|
565
|
+
if (i < n) pieces.push({ type: "raw", value: text.slice(i) });
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
let j = start + 2;
|
|
569
|
+
let depth = 1;
|
|
570
|
+
while (j < n && depth > 0) {
|
|
571
|
+
const ch = text.charCodeAt(j);
|
|
572
|
+
if (ch === 123) depth++;
|
|
573
|
+
else if (ch === 125) depth--;
|
|
574
|
+
j++;
|
|
575
|
+
}
|
|
576
|
+
if (depth !== 0) {
|
|
577
|
+
pieces.push({ type: "raw", value: text.slice(i) });
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
if (start > i) {
|
|
581
|
+
pieces.push({ type: "raw", value: text.slice(i, start) });
|
|
582
|
+
}
|
|
583
|
+
const rawInner = text.slice(start + 2, j - 1);
|
|
584
|
+
const key = rawInner.trim();
|
|
585
|
+
pieces.push({ type: "ph", rawInner, key });
|
|
586
|
+
i = j;
|
|
587
|
+
}
|
|
588
|
+
return pieces;
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
// src/i18n-module/i18n.service.ts
|
|
592
|
+
import { ModuleRef as ModuleRef3 } from "@nestjs/core";
|
|
593
|
+
var I18nService = class {
|
|
594
|
+
constructor(options, moduleRef) {
|
|
595
|
+
this.options = options;
|
|
596
|
+
this.moduleRef = moduleRef;
|
|
597
|
+
this.resolver = createResolver(this.options.resolver);
|
|
598
|
+
this.locales = new Set(this.options.locales);
|
|
599
|
+
this.defaultLocale = this.options.defaultLocale ?? this.options.locales[0];
|
|
600
|
+
this.middlewares = [];
|
|
601
|
+
this.logger = new ConsoleLogger("I18nService");
|
|
602
|
+
}
|
|
603
|
+
middleware(mw, prior = false) {
|
|
604
|
+
if (prior) {
|
|
605
|
+
this.middlewares.unshift(mw);
|
|
606
|
+
} else {
|
|
607
|
+
this.middlewares.push(mw);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
buildFallbackChain(locale) {
|
|
611
|
+
const best = this.getExactLocale(locale);
|
|
612
|
+
const parts = [];
|
|
613
|
+
const segs = best.split("-");
|
|
614
|
+
for (let i = segs.length; i > 1; i--)
|
|
615
|
+
parts.push(segs.slice(0, i).join("-"));
|
|
616
|
+
parts.push(segs[0]);
|
|
617
|
+
if (!parts.includes(this.defaultLocale)) parts.push(this.defaultLocale);
|
|
618
|
+
return Array.from(new Set(parts)).filter((p) => this.locales.has(p));
|
|
619
|
+
}
|
|
620
|
+
async applyMiddlewares(locale, text, ctx) {
|
|
621
|
+
const mws = this.middlewares;
|
|
622
|
+
const tryLocale = async (loc) => {
|
|
623
|
+
const dispatch = async (i) => {
|
|
624
|
+
if (i >= mws.length) return void 0;
|
|
625
|
+
const mw = mws[i];
|
|
626
|
+
let nextCalled = false;
|
|
627
|
+
const next = async () => {
|
|
628
|
+
nextCalled = true;
|
|
629
|
+
return dispatch(i + 1);
|
|
630
|
+
};
|
|
631
|
+
try {
|
|
632
|
+
const res = await mw(loc, text, next, ctx);
|
|
633
|
+
if (res == null && !nextCalled) {
|
|
634
|
+
return dispatch(i + 1);
|
|
635
|
+
}
|
|
636
|
+
return res;
|
|
637
|
+
} catch (e) {
|
|
638
|
+
if (e instanceof HttpException2) {
|
|
639
|
+
throw e;
|
|
640
|
+
}
|
|
641
|
+
this.logger.warn(`Middleware at index ${i} threw an error: ${e}`);
|
|
642
|
+
return dispatch(i + 1);
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
return dispatch(0);
|
|
646
|
+
};
|
|
647
|
+
for (const loc of this.buildFallbackChain(locale)) {
|
|
648
|
+
const result = await tryLocale(loc);
|
|
649
|
+
if (result != null) {
|
|
650
|
+
return result;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return void 0;
|
|
654
|
+
}
|
|
655
|
+
getExactLocale(locale) {
|
|
656
|
+
const input = (locale ?? "").trim();
|
|
657
|
+
if (!input) return this.defaultLocale;
|
|
658
|
+
if (this.locales.has(input)) return input;
|
|
659
|
+
const entries = Array.from(this.locales).map((l) => ({
|
|
660
|
+
orig: l,
|
|
661
|
+
lower: l.toLowerCase()
|
|
662
|
+
}));
|
|
663
|
+
const lower = input.toLowerCase();
|
|
664
|
+
const exact = entries.find((e) => e.lower === lower);
|
|
665
|
+
if (exact) return exact.orig;
|
|
666
|
+
const parts = lower.split("-");
|
|
667
|
+
while (parts.length > 1) {
|
|
668
|
+
parts.pop();
|
|
669
|
+
const candidate = parts.join("-");
|
|
670
|
+
const hit = entries.find((e) => e.lower === candidate);
|
|
671
|
+
if (hit) return hit.orig;
|
|
672
|
+
}
|
|
673
|
+
return this.defaultLocale;
|
|
674
|
+
}
|
|
675
|
+
async getExactLocaleFromRequest(ctx) {
|
|
676
|
+
const locale = await this.resolver(ctx, this.moduleRef);
|
|
677
|
+
return this.getExactLocale(locale);
|
|
678
|
+
}
|
|
679
|
+
async translateString(locale, text, ctx) {
|
|
680
|
+
if (!text) return text;
|
|
681
|
+
locale = this.getExactLocale(locale);
|
|
682
|
+
const pieces = parseI18n(text);
|
|
683
|
+
if (!pieces.some((p) => p.type === "ph")) {
|
|
684
|
+
return pieces.map((p) => p.type === "raw" ? p.value : `#{${p.rawInner}}`).join("");
|
|
685
|
+
}
|
|
686
|
+
const promises = [];
|
|
687
|
+
for (const p of pieces) {
|
|
688
|
+
if (p.type === "ph") {
|
|
689
|
+
promises.push(this.applyMiddlewares(locale, p.key, ctx));
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
const results = await Promise.all(promises);
|
|
693
|
+
let out = "";
|
|
694
|
+
let k = 0;
|
|
695
|
+
for (const p of pieces) {
|
|
696
|
+
if (p.type === "raw") {
|
|
697
|
+
out += p.value;
|
|
698
|
+
} else {
|
|
699
|
+
const r = results[k++];
|
|
700
|
+
out += r == null ? `#{${p.rawInner}}` : r;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return out;
|
|
704
|
+
}
|
|
705
|
+
async translate(locale, obj, ctx) {
|
|
706
|
+
const visited = /* @__PURE__ */ new WeakSet();
|
|
707
|
+
const isBuiltInObject = (v) => {
|
|
708
|
+
if (v == null || typeof v !== "object") return false;
|
|
709
|
+
if (v instanceof Date || v instanceof RegExp || v instanceof Map || v instanceof Set || v instanceof WeakMap || v instanceof WeakSet || v instanceof ArrayBuffer || v instanceof DataView || ArrayBuffer.isView(v))
|
|
710
|
+
return true;
|
|
711
|
+
const tag = Object.prototype.toString.call(v);
|
|
712
|
+
switch (tag) {
|
|
713
|
+
case "[object URL]":
|
|
714
|
+
case "[object URLSearchParams]":
|
|
715
|
+
case "[object Error]":
|
|
716
|
+
case "[object Blob]":
|
|
717
|
+
case "[object File]":
|
|
718
|
+
case "[object FormData]":
|
|
719
|
+
return true;
|
|
720
|
+
default:
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
const translateObjectPreservingProto = async (value) => {
|
|
725
|
+
const proto = Object.getPrototypeOf(value);
|
|
726
|
+
const out = Object.create(proto);
|
|
727
|
+
const keys = Reflect.ownKeys(value);
|
|
728
|
+
await Promise.all(
|
|
729
|
+
keys.map(async (key) => {
|
|
730
|
+
const desc = Object.getOwnPropertyDescriptor(value, key);
|
|
731
|
+
if (!desc) return;
|
|
732
|
+
if ("value" in desc) {
|
|
733
|
+
const newVal = await visit(desc.value);
|
|
734
|
+
Object.defineProperty(out, key, { ...desc, value: newVal });
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
Object.defineProperty(out, key, desc);
|
|
738
|
+
let current = void 0;
|
|
739
|
+
if (typeof desc.get === "function") {
|
|
740
|
+
try {
|
|
741
|
+
current = desc.get.call(value);
|
|
742
|
+
} catch {
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (current === void 0) return;
|
|
746
|
+
try {
|
|
747
|
+
const newVal = await visit(current);
|
|
748
|
+
if (typeof desc.set === "function") {
|
|
749
|
+
try {
|
|
750
|
+
desc.set.call(out, newVal);
|
|
751
|
+
} catch {
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
} catch {
|
|
755
|
+
}
|
|
756
|
+
})
|
|
757
|
+
);
|
|
758
|
+
return out;
|
|
759
|
+
};
|
|
760
|
+
const isTranslatable = (v) => {
|
|
761
|
+
if (!v) return { ok: false };
|
|
762
|
+
const t = typeof v;
|
|
763
|
+
if (t === "number" || t === "bigint" || t === "symbol" || t === "function") {
|
|
764
|
+
return { ok: false };
|
|
765
|
+
}
|
|
766
|
+
if (t === "string") return { ok: true, kind: "string" };
|
|
767
|
+
if (t === "object") {
|
|
768
|
+
return { ok: true, kind: "object" };
|
|
769
|
+
}
|
|
770
|
+
return { ok: false };
|
|
771
|
+
};
|
|
772
|
+
const visit = async (value) => {
|
|
773
|
+
const check = isTranslatable(value);
|
|
774
|
+
if (!check.ok) {
|
|
775
|
+
return value;
|
|
776
|
+
}
|
|
777
|
+
if (check.kind === "string") {
|
|
778
|
+
return this.translateString(locale, value, ctx);
|
|
779
|
+
}
|
|
780
|
+
if (value instanceof Promise) {
|
|
781
|
+
return value.then((resolved) => visit(resolved));
|
|
782
|
+
}
|
|
783
|
+
if (typeof value === "object") {
|
|
784
|
+
if (!Array.isArray(value) && isBuiltInObject(value)) return value;
|
|
785
|
+
if (visited.has(value)) return value;
|
|
786
|
+
visited.add(value);
|
|
787
|
+
if (Array.isArray(value)) {
|
|
788
|
+
const out = await Promise.all(value.map((v) => visit(v)));
|
|
789
|
+
return out;
|
|
790
|
+
}
|
|
791
|
+
return translateObjectPreservingProto(value);
|
|
792
|
+
}
|
|
793
|
+
return value;
|
|
794
|
+
};
|
|
795
|
+
return visit(obj);
|
|
796
|
+
}
|
|
797
|
+
async translateRequest(ctx, obj) {
|
|
798
|
+
const locale = await this.resolver(ctx, this.moduleRef);
|
|
799
|
+
return this.translate(locale, obj, ctx);
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
I18nService = __decorateClass([
|
|
803
|
+
Injectable2(),
|
|
804
|
+
__decorateParam(0, Inject4(I18nModuleOptionsToken)),
|
|
805
|
+
__decorateParam(1, Inject4(ModuleRef3))
|
|
806
|
+
], I18nService);
|
|
807
|
+
|
|
808
|
+
// src/i18n-module/i18n.module.ts
|
|
809
|
+
import { Global, Module as Module2 } from "@nestjs/common";
|
|
810
|
+
|
|
811
|
+
// src/i18n-module/locale.pipe.ts
|
|
812
|
+
import {
|
|
813
|
+
createParamDecorator as createParamDecorator2,
|
|
814
|
+
Inject as Inject5,
|
|
815
|
+
Injectable as Injectable3
|
|
816
|
+
} from "@nestjs/common";
|
|
817
|
+
var LocalePipe = class {
|
|
818
|
+
constructor(i18nService) {
|
|
819
|
+
this.i18nService = i18nService;
|
|
820
|
+
}
|
|
821
|
+
async transform(ctx, metadata) {
|
|
822
|
+
const resolver = ctx.resolver;
|
|
823
|
+
if (resolver) {
|
|
824
|
+
const _resolver = createResolver(resolver);
|
|
825
|
+
const locale = await _resolver(ctx.ctx, void 0);
|
|
826
|
+
return this.i18nService.getExactLocale(locale);
|
|
827
|
+
} else {
|
|
828
|
+
return this.i18nService.getExactLocaleFromRequest(ctx.ctx);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
LocalePipe = __decorateClass([
|
|
833
|
+
Injectable3(),
|
|
834
|
+
__decorateParam(0, Inject5(I18nService))
|
|
835
|
+
], LocalePipe);
|
|
836
|
+
var _dec = createParamDecorator2((resolver, ctx) => {
|
|
837
|
+
return { ctx, resolver };
|
|
838
|
+
});
|
|
839
|
+
var PutLocale = (resolver) => _dec(resolver, LocalePipe);
|
|
840
|
+
|
|
841
|
+
// src/i18n-module/i18n.module.ts
|
|
842
|
+
var I18nModule = class extends ConfigurableModuleClass {
|
|
843
|
+
};
|
|
844
|
+
I18nModule = __decorateClass([
|
|
845
|
+
Global(),
|
|
846
|
+
Module2({
|
|
847
|
+
providers: [I18nService, LocalePipe],
|
|
848
|
+
exports: [I18nService, LocalePipe]
|
|
849
|
+
})
|
|
850
|
+
], I18nModule);
|
|
851
|
+
|
|
852
|
+
// src/i18n-module/i18n-decorator.ts
|
|
853
|
+
import { UseInterceptors } from "@nestjs/common";
|
|
854
|
+
|
|
855
|
+
// src/i18n-module/i18n.interceptor.ts
|
|
856
|
+
import {
|
|
857
|
+
HttpException as HttpException3,
|
|
858
|
+
Inject as Inject6,
|
|
859
|
+
Injectable as Injectable4
|
|
860
|
+
} from "@nestjs/common";
|
|
861
|
+
import { from, throwError } from "rxjs";
|
|
862
|
+
import { catchError, mergeMap } from "rxjs/operators";
|
|
863
|
+
var I18nInterceptor = class {
|
|
864
|
+
constructor(i18nService) {
|
|
865
|
+
this.i18nService = i18nService;
|
|
866
|
+
}
|
|
867
|
+
intercept(context, next) {
|
|
868
|
+
return next.handle().pipe(
|
|
869
|
+
// 成功路径:把响应体交给 i18n 做异步翻译
|
|
870
|
+
mergeMap((data) => this.i18nService.translateRequest(context, data)),
|
|
871
|
+
// 错误路径:若是 HttpException,把其 response 翻译后再抛
|
|
872
|
+
catchError((err) => {
|
|
873
|
+
if (err instanceof HttpException3) {
|
|
874
|
+
const status = err.getStatus();
|
|
875
|
+
const resp = err.getResponse();
|
|
876
|
+
return from(this.i18nService.translateRequest(context, resp)).pipe(
|
|
877
|
+
mergeMap(
|
|
878
|
+
(translated) => throwError(
|
|
879
|
+
() => new HttpException3(translated, status, { cause: err })
|
|
880
|
+
)
|
|
881
|
+
)
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
return throwError(() => err);
|
|
885
|
+
})
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
I18nInterceptor = __decorateClass([
|
|
890
|
+
Injectable4(),
|
|
891
|
+
__decorateParam(0, Inject6(I18nService))
|
|
892
|
+
], I18nInterceptor);
|
|
893
|
+
|
|
894
|
+
// src/i18n-module/i18n-decorator.ts
|
|
895
|
+
var createI18nDecorator = (options) => {
|
|
896
|
+
return () => MergeClassOrMethodDecorators([
|
|
897
|
+
UseInterceptors(I18nInterceptor),
|
|
898
|
+
ApiFromResolver(options.resolver, {
|
|
899
|
+
description: "Locale for internationalization",
|
|
900
|
+
required: false,
|
|
901
|
+
default: options.defaultLocale ?? options.locales[0],
|
|
902
|
+
enum: options.locales
|
|
903
|
+
})
|
|
904
|
+
]);
|
|
905
|
+
};
|
|
906
|
+
|
|
907
|
+
// src/i18n-module/i18n-factory.ts
|
|
908
|
+
var createI18n = (options) => {
|
|
909
|
+
if (!options.resolver) {
|
|
910
|
+
options.resolver = {
|
|
911
|
+
paramType: "header",
|
|
912
|
+
paramName: "x-client-language"
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
return {
|
|
916
|
+
UseI18n: createI18nDecorator(options),
|
|
917
|
+
I18nModule: I18nModule.register(options)
|
|
918
|
+
};
|
|
919
|
+
};
|
|
920
|
+
|
|
921
|
+
// src/i18n-module/middlewares/lookup.ts
|
|
922
|
+
var I18nLookupMiddleware = (dict, options) => {
|
|
923
|
+
const matchType = options?.matchType ?? "exact";
|
|
924
|
+
const dictFactory = typeof dict === "function" ? dict : () => dict;
|
|
925
|
+
const pickBestByHierarchy = (input, locales) => {
|
|
926
|
+
if (!input) return void 0;
|
|
927
|
+
const entries = locales.map((l) => ({ orig: l, lower: l.toLowerCase() }));
|
|
928
|
+
const lower = input.toLowerCase();
|
|
929
|
+
const exact = entries.find((e) => e.lower === lower);
|
|
930
|
+
if (exact) return exact.orig;
|
|
931
|
+
const parts = lower.split("-");
|
|
932
|
+
while (parts.length > 1) {
|
|
933
|
+
parts.pop();
|
|
934
|
+
const candidate = parts.join("-");
|
|
935
|
+
const hit = entries.find((e) => e.lower === candidate);
|
|
936
|
+
if (hit) return hit.orig;
|
|
937
|
+
}
|
|
938
|
+
return void 0;
|
|
939
|
+
};
|
|
940
|
+
return async (locale, key, next, ctx) => {
|
|
941
|
+
const dictResolved = await dictFactory(locale, key, ctx);
|
|
942
|
+
let dictionary = dictResolved[locale];
|
|
943
|
+
if (!dictionary) {
|
|
944
|
+
if (matchType === "hierarchy") {
|
|
945
|
+
const best = pickBestByHierarchy(locale, Object.keys(dictResolved));
|
|
946
|
+
if (best) dictionary = dictResolved[best];
|
|
947
|
+
} else if (matchType === "startsWith") {
|
|
948
|
+
const keys = Object.keys(dictResolved).filter(
|
|
949
|
+
(k) => locale.startsWith(k)
|
|
950
|
+
);
|
|
951
|
+
if (keys.length) {
|
|
952
|
+
const best = keys.reduce((a, b) => b.length > a.length ? b : a);
|
|
953
|
+
dictionary = dictResolved[best];
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (dictionary && Object.prototype.hasOwnProperty.call(dictionary, key)) {
|
|
958
|
+
const val = dictionary[key];
|
|
959
|
+
if (val != null) {
|
|
960
|
+
return val;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return next();
|
|
964
|
+
};
|
|
965
|
+
};
|
|
417
966
|
export {
|
|
418
967
|
ABORT_SIGNAL,
|
|
419
968
|
AbortSignalProvider,
|
|
@@ -421,6 +970,7 @@ export {
|
|
|
421
970
|
ApiBlankResponse,
|
|
422
971
|
ApiError,
|
|
423
972
|
ApiErrorTyped,
|
|
973
|
+
ApiFromResolver,
|
|
424
974
|
ApiTypeResponse,
|
|
425
975
|
As,
|
|
426
976
|
BlankPaginatedReturnMessageDto,
|
|
@@ -430,22 +980,31 @@ export {
|
|
|
430
980
|
DataQuery,
|
|
431
981
|
GenericPaginatedReturnMessageDto,
|
|
432
982
|
GenericReturnMessageDto,
|
|
983
|
+
I18nInterceptor,
|
|
984
|
+
I18nLookupMiddleware,
|
|
985
|
+
I18nModule,
|
|
986
|
+
I18nService,
|
|
433
987
|
InjectAbortSignal,
|
|
434
988
|
InjectAbortable,
|
|
435
989
|
InsertField,
|
|
990
|
+
LocalePipe,
|
|
436
991
|
MergeClassDecorators,
|
|
437
992
|
MergeClassOrMethodDecorators,
|
|
438
993
|
MergeMethodDecorators,
|
|
439
994
|
MergeParameterDecorators,
|
|
440
995
|
MergePropertyDecorators,
|
|
441
996
|
PaginatedReturnMessageDto,
|
|
997
|
+
PutLocale,
|
|
442
998
|
RequireToken,
|
|
443
999
|
ReturnMessageDto,
|
|
444
1000
|
StringReturnMessageDto,
|
|
445
1001
|
TokenGuard,
|
|
446
1002
|
abortableToken,
|
|
447
1003
|
createAbortableProvider,
|
|
1004
|
+
createI18n,
|
|
1005
|
+
createI18nDecorator,
|
|
448
1006
|
createProvider,
|
|
1007
|
+
createResolver,
|
|
449
1008
|
fromAbortable,
|
|
450
1009
|
getClassFromClassOrArray,
|
|
451
1010
|
takeUntilAbort
|