Skip to content

Commit

Permalink
got optional localizer working
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Jan 9, 2024
1 parent 09a8656 commit 14e231a
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 64 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@
"@typescript-eslint/eslint-plugin": "5.58.0",
"@typescript-eslint/parser": "5.59.1",
"discord.js": "^14.11.0",
"esbuild": "^0.17.0",
"eslint": "8.39.0",
"prettier": "2.8.8",
"shrimple-locales": "^0.1.2",
"tsup": "^6.7.0",
"typescript": "5.0.2",
"vitest": "latest"
Expand Down Expand Up @@ -96,7 +96,7 @@
"url": "git+https://github.com/sern-handler/handler.git"
},
"homepage": "https://sern.dev",
"optionalDependencies": {
"peerDependencies": {
"shrimple-locales": "^0.1.2"
}
}
42 changes: 36 additions & 6 deletions src/core/ioc/base.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import * as assert from 'assert';
import { composeRoot, useContainer } from './dependency-injection';
import type { DependencyConfiguration } from '../../types/ioc';
import { useContainer } from './dependency-injection';
import type { CoreDependencies, DependencyConfiguration } from '../../types/ioc';
import { CoreContainer } from './container';
import { Result } from 'ts-results-es';
import { DefaultServices } from '../_internal';
import { AnyFunction } from '../../types/utility';
import type { Logging } from '../contracts/logging';
import { requir } from '../module-loading';
import { fileURLToPath } from 'node:url';
import path from 'path';

//SIDE EFFECT: GLOBAL DI
let containerSubject: CoreContainer<Partial<Dependencies>>;
Expand Down Expand Up @@ -93,13 +95,41 @@ export const insertLogger = (containerSubject: CoreContainer<any>) => {
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
}

export const insertLocalizer = async (containerSubject: CoreContainer<any>) => {
const { ShrimpleLocalizer } = requir('../structures/services/localizer');
const insertLocalizer = async (containerSubject: CoreContainer<any>) => {
const packageDirectory = fileURLToPath(import.meta.url);
const pathToLocalizer= path.resolve(packageDirectory, "../", "optional", "localizer");
const { ShrimpleLocalizer } = requir(pathToLocalizer);
containerSubject
.add({'@sern/localizer': new ShrimpleLocalizer() });
.upsert({'@sern/localizer': new ShrimpleLocalizer() });
}

/**
* Given the user's conf, check for any excluded/included dependency keys.
* Then, call conf.build to get the rest of the users' dependencies.
* Finally, update the containerSubject with the new container state
* @param conf
*/
function composeRoot(
container: CoreContainer<Partial<Dependencies>>,
conf: DependencyConfiguration,
) {
//container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger');
if (!hasLogger) {
insertLogger(container);
}
if(conf.include?.includes('@sern/localizer')) {
insertLocalizer(container);
}
//Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);

if (!hasLogger) {
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
}

container.ready();
}

export async function makeDependencies<const T extends Dependencies>
(conf: ValidDependencyConfig) {
Expand All @@ -118,7 +148,7 @@ export async function makeDependencies<const T extends Dependencies>
}

if(included.includes('@sern/localizer')) {
await insertLocalizer(containerSubject);
insertLocalizer(containerSubject);
}

containerSubject.ready();
Expand Down
32 changes: 2 additions & 30 deletions src/core/ioc/dependency-injection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import type { CoreDependencies, DependencyConfiguration, IntoDependencies } from '../../types/ioc';
import { requir } from '../module-loading';
import { insertLogger, useContainerRaw } from './base';
import { CoreContainer } from './container';
import type { IntoDependencies } from '../../types/ioc';
import { useContainerRaw } from './base';

/**
* @__PURE__
Expand Down Expand Up @@ -47,33 +45,7 @@ export function Services<const T extends (keyof Dependencies)[]>(...keys: [...T]
return keys.map(k => container.get(k)!) as IntoDependencies<T>;
}

/**
* Given the user's conf, check for any excluded/included dependency keys.
* Then, call conf.build to get the rest of the users' dependencies.
* Finally, update the containerSubject with the new container state
* @param conf
*/
export function composeRoot(
container: CoreContainer<Partial<Dependencies>>,
conf: DependencyConfiguration,
) {
//container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger');
if (!hasLogger) {
insertLogger(container);
}
if(conf.include?.includes('@sern/localizer')) {
container.add({ '@sern/localizer': requir('shrimple-locales') });
}
//Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);

if (!hasLogger) {
container.get('@sern/logger')?.info({ message: 'All dependencies loaded successfully.' });
}

container.ready();
}

export function useContainer<const T extends Dependencies>() {
return <V extends (keyof T)[]>(...keys: [...V]) =>
Expand Down
20 changes: 0 additions & 20 deletions src/core/structures/optional/localizer.ts

This file was deleted.

35 changes: 35 additions & 0 deletions src/optional/localizer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { Localizer, Init } from '../core/contracts'
import { Localization } from 'shrimple-locales'
import fs from 'node:fs/promises'
import { join, resolve } from 'node:path';
import { filename } from '../core/module-loading'
/**
* @internal
* @since 2.0.0
* Version 4.0.0 will internalize this api. Please refrain from using ModuleStore!
*/
export class ShrimpleLocalizer implements Localizer, Init {
private __localization!: Localization;
constructor(){}
translate(text: string): string {
return this.__localization.get(text);
}

async init() {
this.__localization = new Localization({
defaultLocale: "en",
fallbackLocale: "en",
locales: await this.readLocalizationDirectory()
});
}

private async readLocalizationDirectory() {
const translationFiles = [];
const localPath = resolve('locals');
for(const json of await fs.readdir(localPath)) {
translationFiles.push({ [filename(json)]:
JSON.parse(await fs.readFile(join(localPath, json), 'utf8')) })
}
return translationFiles.reduce((acc, cur ) => ({ ...cur, ...acc }), {});
}
}
2 changes: 1 addition & 1 deletion tsup.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { defineConfig } from 'tsup';
const shared = {
entry: ['src/index.ts', 'src/core/structures/optional/localizer.ts'],
entry: ['src/index.ts', 'src/optional/localizer.ts'],
external: ['discord.js', 'iti', 'shrimple-locales'],
platform: 'node',
clean: true,
Expand Down
8 changes: 3 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,6 @@ __metadata:
"@typescript-eslint/parser": 5.59.1
callsites: ^3.1.0
discord.js: ^14.11.0
esbuild: ^0.17.0
eslint: 8.39.0
iti: ^0.6.0
prettier: 2.8.8
Expand All @@ -639,9 +638,8 @@ __metadata:
tsup: ^6.7.0
typescript: 5.0.2
vitest: latest
dependenciesMeta:
shrimple-locales:
optional: true
peerDependencies:
shrimple-locales: ^0.1.2
languageName: unknown
linkType: soft

Expand Down Expand Up @@ -1453,7 +1451,7 @@ __metadata:
languageName: node
linkType: hard

"esbuild@npm:^0.17.0, esbuild@npm:^0.17.6":
"esbuild@npm:^0.17.6":
version: 0.17.19
resolution: "esbuild@npm:0.17.19"
dependencies:
Expand Down

0 comments on commit 14e231a

Please sign in to comment.