@jchat/addon-sdk 1.0.0-alpha.11 → 1.0.0-alpha.12

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.
@@ -1,13 +1,13 @@
1
- import { t as AddonManifest } from "./contracts.mjs";
1
+ import { AddonManifest } from "./contracts.mjs";
2
2
  //#region src/diagnostics.d.ts
3
3
  /**
4
4
  * Diagnostic result status indicator for addon validation checks. - `"pass"`: The diagnostic check
5
5
  * passed successfully. - `"warning"`: Non-critical warning (e.g. source maps present in
6
6
  * production). - `"error"`: Critical failure blocking addon installation or distribution.
7
7
  */
8
- type AddonDiagnosticStatus = "pass" | "warning" | "error";
8
+ export type AddonDiagnosticStatus = "pass" | "warning" | "error";
9
9
  /** Represents an individual diagnostic check result for an addon package. */
10
- interface AddonPackageDiagnostic {
10
+ export interface AddonPackageDiagnostic {
11
11
  /** Unique identifier for the diagnostic check (e.g. `"jchat"`, `"package-size"`). */
12
12
  id: string;
13
13
  /** Human-readable title for the diagnostic check. */
@@ -18,7 +18,7 @@ interface AddonPackageDiagnostic {
18
18
  message: string;
19
19
  }
20
20
  /** Options required to run diagnostic validation on an addon build package. */
21
- interface AddonPackageDiagnosticOptions {
21
+ export interface AddonPackageDiagnosticOptions {
22
22
  /** Absolute path to the compiled addon build output directory (`build/`). */
23
23
  buildDir: string;
24
24
  /** Parsed addon manifest object (`manifest.json`). */
@@ -45,7 +45,7 @@ interface AddonPackageDiagnosticOptions {
45
45
  * @returns Semver range string matching the current major series (e.g. `">=1.2.0 <2.0.0"`).
46
46
  * @throws {@link Error} If the input is not a valid semantic version string.
47
47
  */
48
- declare function createCompatibleMajorRange(version: string): string;
48
+ export declare function createCompatibleMajorRange(version: string): string;
49
49
  /**
50
50
  * Performs comprehensive diagnostic validation checks on an addon package build directory.
51
51
  *
@@ -57,13 +57,12 @@ declare function createCompatibleMajorRange(version: string): string;
57
57
  * versions.
58
58
  * @returns Array of {@link AddonPackageDiagnostic} results.
59
59
  */
60
- declare function diagnoseAddonPackage(options: AddonPackageDiagnosticOptions): AddonPackageDiagnostic[];
60
+ export declare function diagnoseAddonPackage(options: AddonPackageDiagnosticOptions): AddonPackageDiagnostic[];
61
61
  /**
62
62
  * Checks whether any diagnostic check in a diagnostic list returned a critical error.
63
63
  *
64
64
  * @param diagnostics - Array of diagnostic check results to evaluate.
65
65
  * @returns `true` if at least one check has `status === "error"`, otherwise `false`.
66
66
  */
67
- declare function hasAddonDiagnosticErrors(diagnostics: readonly AddonPackageDiagnostic[]): boolean;
68
- //#endregion
69
- export { AddonDiagnosticStatus, AddonPackageDiagnostic, AddonPackageDiagnosticOptions, createCompatibleMajorRange, diagnoseAddonPackage, hasAddonDiagnosticErrors };
67
+ export declare function hasAddonDiagnosticErrors(diagnostics: readonly AddonPackageDiagnostic[]): boolean;
68
+ //#endregion
@@ -76,7 +76,7 @@ function diagnoseAddonPackage(options) {
76
76
  const productionArchive = path$1.join(buildDir, `${manifest.id}-${manifest.version}.zip`);
77
77
  const hasProductionArchive = fs$1.existsSync(productionArchive) && fs$1.statSync(productionArchive).isFile();
78
78
  const totalBytes = options.productionPackage && hasProductionArchive ? fs$1.statSync(productionArchive).size : files.filter((file) => file !== productionArchive).reduce((total, file) => total + fs$1.statSync(file).size, 0);
79
- const maxBytes = options.maxBytes ?? 25 * 1024 * 1024;
79
+ const maxBytes = options.maxBytes ?? 26214400;
80
80
  diagnostics.push({
81
81
  id: "package-size",
82
82
  label: "Package size",
@@ -0,0 +1,17 @@
1
+ //#region src/i18n-validator.d.ts
2
+ export interface AddonLocaleValidationResult {
3
+ valid: boolean;
4
+ errors: string[];
5
+ missingFiles: string[];
6
+ missingKeys: Record<string, string[]>;
7
+ extraKeys: Record<string, string[]>;
8
+ }
9
+ /**
10
+ * Validates that an addon's `locales/` directory contains valid translation files for all 20 host
11
+ * languages with 100% key parity against `en.json`.
12
+ *
13
+ * @param dirPath - Path to the addon's locales directory.
14
+ * @param domainName - Optional label for error messages (defaults to "Addon").
15
+ */
16
+ export declare function validateAddonLocales(dirPath: string, domainName?: string): AddonLocaleValidationResult;
17
+ //#endregion
@@ -0,0 +1,90 @@
1
+ import { t as HOST_LANGUAGES } from "./i18n.mjs";
2
+ import * as fs$1 from "node:fs";
3
+ import * as path$1 from "node:path";
4
+ //#region src/i18n-validator.ts
5
+ function extractNestedKeys(obj, prefix = "") {
6
+ if (!obj || typeof obj !== "object") return [];
7
+ const keys = [];
8
+ for (const [key, value] of Object.entries(obj)) {
9
+ const fullKey = prefix ? `${prefix}.${key}` : key;
10
+ if (value && typeof value === "object" && !Array.isArray(value)) keys.push(...extractNestedKeys(value, fullKey));
11
+ else keys.push(fullKey);
12
+ }
13
+ return keys;
14
+ }
15
+ /**
16
+ * Validates that an addon's `locales/` directory contains valid translation files for all 20 host
17
+ * languages with 100% key parity against `en.json`.
18
+ *
19
+ * @param dirPath - Path to the addon's locales directory.
20
+ * @param domainName - Optional label for error messages (defaults to "Addon").
21
+ */
22
+ function validateAddonLocales(dirPath, domainName = "Addon") {
23
+ const errors = [];
24
+ const missingFiles = [];
25
+ const missingKeys = {};
26
+ const extraKeys = {};
27
+ const enPath = path$1.join(dirPath, "en.json");
28
+ if (!fs$1.existsSync(enPath)) {
29
+ const errorMsg = `[${domainName}] Missing base locale file: en.json`;
30
+ errors.push(errorMsg);
31
+ missingFiles.push("en.json");
32
+ return {
33
+ valid: false,
34
+ errors,
35
+ missingFiles,
36
+ missingKeys,
37
+ extraKeys
38
+ };
39
+ }
40
+ let enContent;
41
+ try {
42
+ enContent = JSON.parse(fs$1.readFileSync(enPath, "utf-8"));
43
+ } catch (err) {
44
+ const errorMsg = `[${domainName}] Invalid JSON in en.json: ${err instanceof Error ? err.message : String(err)}`;
45
+ errors.push(errorMsg);
46
+ return {
47
+ valid: false,
48
+ errors,
49
+ missingFiles,
50
+ missingKeys,
51
+ extraKeys
52
+ };
53
+ }
54
+ const enKeys = new Set(extractNestedKeys(enContent));
55
+ for (const lang of HOST_LANGUAGES) {
56
+ if (lang === "en") continue;
57
+ const langFileName = `${lang}.json`;
58
+ const langPath = path$1.join(dirPath, langFileName);
59
+ if (!fs$1.existsSync(langPath)) {
60
+ errors.push(`[${domainName}] Missing locale file: ${langFileName}`);
61
+ missingFiles.push(langFileName);
62
+ continue;
63
+ }
64
+ try {
65
+ const langContent = JSON.parse(fs$1.readFileSync(langPath, "utf-8"));
66
+ const langKeys = new Set(extractNestedKeys(langContent));
67
+ for (const key of enKeys) if (!langKeys.has(key)) {
68
+ errors.push(`[${domainName}] Missing key in ${langFileName}: "${key}"`);
69
+ if (!missingKeys[lang]) missingKeys[lang] = [];
70
+ missingKeys[lang].push(key);
71
+ }
72
+ for (const key of langKeys) if (!enKeys.has(key)) {
73
+ errors.push(`[${domainName}] Extra key in ${langFileName} (not in en.json): "${key}"`);
74
+ if (!extraKeys[lang]) extraKeys[lang] = [];
75
+ extraKeys[lang].push(key);
76
+ }
77
+ } catch (err) {
78
+ errors.push(`[${domainName}] Invalid JSON in ${langFileName}: ${err instanceof Error ? err.message : String(err)}`);
79
+ }
80
+ }
81
+ return {
82
+ valid: errors.length === 0,
83
+ errors,
84
+ missingFiles,
85
+ missingKeys,
86
+ extraKeys
87
+ };
88
+ }
89
+ //#endregion
90
+ export { validateAddonLocales };
package/dist/i18n.mjs ADDED
@@ -0,0 +1,191 @@
1
+ import { createContext, useContext, useEffect, useMemo, useState } from "react";
2
+ //#region src/i18n.ts
3
+ function checkIsRtl(code) {
4
+ if (!code) return false;
5
+ const normalized = code.toLowerCase().split("-")[0];
6
+ return normalized === "ar" || normalized === "he" || normalized === "ur";
7
+ }
8
+ function getLanguageDirection(code) {
9
+ return checkIsRtl(code) ? "rtl" : "ltr";
10
+ }
11
+ function interpolate(text, params) {
12
+ if (!params) return text;
13
+ return text.replace(/\{\{\s*(\w+)\s*\}\}|\{\s*(\w+)\s*\}/g, (match, key1, key2) => {
14
+ const key = key1 || key2;
15
+ return key in params ? String(params[key]) : match;
16
+ });
17
+ }
18
+ const HOST_LANGUAGES = [
19
+ "ar",
20
+ "bg",
21
+ "hr",
22
+ "de",
23
+ "el",
24
+ "en",
25
+ "es",
26
+ "fr",
27
+ "he",
28
+ "hi",
29
+ "kn",
30
+ "ml",
31
+ "nl",
32
+ "pt",
33
+ "ro",
34
+ "ru",
35
+ "ta",
36
+ "te",
37
+ "tr",
38
+ "ur"
39
+ ];
40
+ const LocaleContext = createContext({
41
+ locale: "en",
42
+ dir: "ltr"
43
+ });
44
+ /** Resolves a nested key in an object dictionary using dot-notation (e.g. "buttons.submit") */
45
+ function resolveNestedKey(obj, keyPath) {
46
+ if (!obj || typeof obj !== "object") return void 0;
47
+ const segments = keyPath.split(".");
48
+ let current = obj;
49
+ for (const seg of segments) if (current && typeof current === "object" && seg in current) current = current[seg];
50
+ else return;
51
+ return current;
52
+ }
53
+ /**
54
+ * Creates a standalone translation function for backend server routes (`src/api.ts`) or utilities.
55
+ *
56
+ * @param resources - Dictionary of translation resources (e.g., `{ en: enJson, ta: taJson }`).
57
+ * @param defaultLocale - Default locale to use if not specified per call (defaults to "en").
58
+ * @param fallbackLocale - Fallback locale if a key is missing in the target language (defaults to
59
+ * "en").
60
+ */
61
+ function createTranslator(resources = {}, defaultLocale = "en", fallbackLocale = "en") {
62
+ return (key, paramsOrLang, maybeLang) => {
63
+ let params;
64
+ let lang = defaultLocale;
65
+ if (typeof paramsOrLang === "string") lang = paramsOrLang;
66
+ else if (paramsOrLang && typeof paramsOrLang === "object") {
67
+ params = paramsOrLang;
68
+ if (typeof maybeLang === "string") lang = maybeLang;
69
+ }
70
+ const normalizedLang = (lang || defaultLocale).toLowerCase().split("-")[0];
71
+ const normalizedFallback = fallbackLocale.toLowerCase().split("-")[0];
72
+ const langDict = resources[normalizedLang];
73
+ let resolved = resolveNestedKey(langDict, key);
74
+ if (resolved === void 0 && normalizedLang !== normalizedFallback) {
75
+ const fallbackDict = resources[normalizedFallback];
76
+ resolved = resolveNestedKey(fallbackDict, key);
77
+ }
78
+ if (typeof resolved === "string") return interpolate(resolved, params);
79
+ return typeof resolved === "number" || typeof resolved === "boolean" ? String(resolved) : interpolate(key, params);
80
+ };
81
+ }
82
+ /**
83
+ * Hook to access the current active host locale and text direction in an addon component.
84
+ *
85
+ * @example
86
+ * ;```tsx
87
+ * import { useLocale } from "@jchat/addon-sdk"
88
+ *
89
+ * export default function MyAddon() {
90
+ * const { locale, dir, isRtl } = useLocale()
91
+ * return <div dir={dir}>Current language: {locale}</div>
92
+ * }
93
+ * ```
94
+ */
95
+ function useLocale() {
96
+ const context = useContext(LocaleContext);
97
+ const locale = context?.locale || "en";
98
+ const dir = context?.dir || getLanguageDirection(locale);
99
+ return {
100
+ locale,
101
+ dir,
102
+ isRtl: dir === "rtl" || checkIsRtl(locale)
103
+ };
104
+ }
105
+ const loadedChunkCache = {};
106
+ /**
107
+ * Hook to access translation function and locale metadata inside addon components. Automatically
108
+ * synchronizes with host language switches and falls back to English. Supports static dictionary
109
+ * resources or dynamic async locale loaders.
110
+ *
111
+ * @example
112
+ * ;```tsx
113
+ * import { useTranslation } from "@jchat/addon-sdk"
114
+ * import locales from "./locales"
115
+ *
116
+ * export default function MyAddon() {
117
+ * const { t, locale, dir } = useTranslation(locales)
118
+ * return (
119
+ * <div dir={dir}>
120
+ * <h1>{t("welcome", { name: "Guest" })}</h1>
121
+ * </div>
122
+ * )
123
+ * }
124
+ * ```
125
+ *
126
+ * @param resourcesOrLoader - Addon-scoped translation dictionaries or async chunk loader.
127
+ * @param fallbackLocale - Fallback language code when a string is missing (default: "en").
128
+ */
129
+ function useTranslation(resourcesOrLoader = {}, fallbackLocale = "en") {
130
+ const { locale, dir, isRtl } = useLocale();
131
+ const isLoader = typeof resourcesOrLoader === "function";
132
+ const [dynamicResources, setDynamicResources] = useState(() => {
133
+ return isLoader ? loadedChunkCache : resourcesOrLoader;
134
+ });
135
+ const [isReady, setIsReady] = useState(!isLoader);
136
+ useEffect(() => {
137
+ if (!isLoader) {
138
+ setDynamicResources(resourcesOrLoader);
139
+ setIsReady(true);
140
+ return;
141
+ }
142
+ const loader = resourcesOrLoader;
143
+ const normLocale = locale.toLowerCase().split("-")[0];
144
+ if (loadedChunkCache[normLocale]) {
145
+ setDynamicResources((prev) => ({
146
+ ...prev,
147
+ [normLocale]: loadedChunkCache[normLocale]
148
+ }));
149
+ setIsReady(true);
150
+ return;
151
+ }
152
+ let isMounted = true;
153
+ Promise.resolve(loader(normLocale)).then((dict) => {
154
+ if (!isMounted || !dict) return;
155
+ loadedChunkCache[normLocale] = dict;
156
+ setDynamicResources((prev) => ({
157
+ ...prev,
158
+ [normLocale]: dict
159
+ }));
160
+ setIsReady(true);
161
+ }).catch((err) => {
162
+ console.warn(`[addon-sdk] Failed to dynamically load locale chunk "${normLocale}":`, err);
163
+ if (isMounted) setIsReady(true);
164
+ });
165
+ return () => {
166
+ isMounted = false;
167
+ };
168
+ }, [
169
+ isLoader,
170
+ resourcesOrLoader,
171
+ locale
172
+ ]);
173
+ const translator = useMemo(() => {
174
+ return createTranslator(dynamicResources, locale, fallbackLocale);
175
+ }, [
176
+ dynamicResources,
177
+ locale,
178
+ fallbackLocale
179
+ ]);
180
+ return {
181
+ t: useMemo(() => {
182
+ return (key, params) => translator(key, params, locale);
183
+ }, [translator, locale]),
184
+ locale,
185
+ dir,
186
+ isRtl,
187
+ isReady
188
+ };
189
+ }
190
+ //#endregion
191
+ export { useTranslation as a, useLocale as i, LocaleContext as n, createTranslator as r, HOST_LANGUAGES as t };
@@ -0,0 +1,4 @@
1
+ import { i as IconPack, n as IconComponent, r as IconName, t as ICON_NAMES } from "./types.mjs";
2
+ import { a as getIconPack, c as lucidePack, i as fa6Pack, l as phosphorPack, n as Icons, o as heroPack, r as Youtube, s as isIconName, t as IconPackName, u as resolveIcon } from "./index.mjs";
3
+ export * from "lucide-react";
4
+ export { ICON_NAMES, type IconComponent, type IconName, type IconPack, IconPackName, Icons, Icons as default, Youtube, fa6Pack, getIconPack, heroPack, isIconName, lucidePack, phosphorPack, resolveIcon };
package/dist/icon.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import { i as IconPack, n as IconComponent, r as IconName, t as ICON_NAMES } from "./types.d.mts";
2
+ import { a as getIconPack, c as lucidePack, i as fa6Pack, l as phosphorPack, n as Icons, o as heroPack, r as Youtube, s as isIconName, t as IconPackName, u as resolveIcon } from "./index.d.mts";
3
+ export * from "lucide-react";
4
+ export { ICON_NAMES, IconComponent, IconName, IconPack, IconPackName, Icons, Icons as default, Youtube, fa6Pack, getIconPack, heroPack, isIconName, lucidePack, phosphorPack, resolveIcon };