@uipkge/nuxt 0.1.20 → 0.1.22

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/module.d.mts CHANGED
@@ -15,6 +15,18 @@ interface ModuleOptions {
15
15
  * Default: 'en'
16
16
  */
17
17
  locale?: string;
18
+ /**
19
+ * Controls which features are active:
20
+ * - 'full' (default): key sync in dev + CDN translation loading
21
+ * - 'sync-only': key sync in dev only — you manage translation loading yourself
22
+ * - 'cdn-only': CDN translation loading only — no key sync
23
+ */
24
+ mode?: "full" | "sync-only" | "cdn-only";
25
+ /**
26
+ * Shorthand for mode: when false, equivalent to mode: 'sync-only'.
27
+ * Ignored if `mode` is explicitly set.
28
+ */
29
+ fetchTranslations?: boolean;
18
30
  }
19
31
  declare const _default: nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
20
32
 
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.0.0"
6
6
  },
7
- "version": "0.1.20",
7
+ "version": "0.1.22",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -11,25 +11,43 @@ const module$1 = defineNuxtModule({
11
11
  cdnUrl: "https://cdn.i18now.com",
12
12
  environment: "dev",
13
13
  syncIn: ["development"],
14
- locale: "en"
14
+ locale: "en",
15
+ mode: "full",
16
+ fetchTranslations: true
15
17
  },
16
18
  async setup(options, nuxt) {
17
19
  const resolver = createResolver(import.meta.url);
20
+ const mode = options.mode ?? (options.fetchTranslations === false ? "sync-only" : "full");
21
+ const enableSync = mode === "full" || mode === "sync-only";
22
+ const enableFetch = mode === "full" || mode === "cdn-only";
18
23
  if (!options.projectId) {
19
- console.warn("[i18now] projectId is required. The module will not work until it is set.");
24
+ console.warn(
25
+ "[i18now] projectId is required. The module will not work until it is set."
26
+ );
20
27
  }
21
- if (!options.apiKey) {
22
- console.warn("[i18now] apiKey is required. The module will not work until it is set.");
28
+ if (enableSync && !options.apiKey) {
29
+ console.warn(
30
+ "[i18now] apiKey is required for key sync. Sync will not work until it is set."
31
+ );
23
32
  }
24
- if (options.cdnUrl && !options.cdnUrl.startsWith("http")) {
25
- console.warn("[i18now] cdnUrl should be a valid HTTP(S) URL. Got: " + options.cdnUrl);
33
+ if (enableFetch && options.cdnUrl && !options.cdnUrl.startsWith("http")) {
34
+ console.warn(
35
+ "[i18now] cdnUrl should be a valid HTTP(S) URL. Got: " + options.cdnUrl
36
+ );
26
37
  }
27
- const dangerousEnvs = (options.syncIn ?? []).filter(
28
- (e) => ["production", "staging", "prod", "stage"].includes(e.toLowerCase())
29
- );
30
- if (dangerousEnvs.length > 0) {
31
- console.error(
32
- `[i18now] DANGER: syncIn includes "${dangerousEnvs.join('", "')}" \u2014 key sync is enabled in a production-like environment. This will expose your API key to users and flood i18now with production traffic. syncIn should only contain "development".`
38
+ if (enableSync) {
39
+ const dangerousEnvs = (options.syncIn ?? []).filter(
40
+ (e) => ["production", "staging", "prod", "stage"].includes(e.toLowerCase())
41
+ );
42
+ if (dangerousEnvs.length > 0) {
43
+ console.error(
44
+ `[i18now] DANGER: syncIn includes "${dangerousEnvs.join('", "')}" \u2014 key sync is enabled in a production-like environment. This will expose your API key to users and flood i18now with production traffic. syncIn should only contain "development".`
45
+ );
46
+ }
47
+ }
48
+ if (import.meta.dev) {
49
+ console.log(
50
+ `[i18now] mode: ${mode} (sync: ${enableSync}, fetch: ${enableFetch})`
33
51
  );
34
52
  }
35
53
  nuxt.options.runtimeConfig.public.i18now = {
@@ -39,16 +57,18 @@ const module$1 = defineNuxtModule({
39
57
  locale: options.locale,
40
58
  // Dev-only fields — only included when the sync client plugin is active.
41
59
  // In production builds these are undefined and the client plugin is not registered.
42
- ...nuxt.options.dev ? {
60
+ ...nuxt.options.dev && enableSync ? {
43
61
  apiKey: options.apiKey,
44
62
  host: options.host,
45
63
  syncIn: options.syncIn
46
64
  } : {}
47
65
  };
48
- addPlugin({
49
- src: resolver.resolve("./runtime/plugin"),
50
- mode: "server"
51
- });
66
+ if (enableFetch) {
67
+ addPlugin({
68
+ src: resolver.resolve("./runtime/plugin"),
69
+ mode: "server"
70
+ });
71
+ }
52
72
  addImports([
53
73
  {
54
74
  name: "useI18now",
@@ -62,18 +82,34 @@ const module$1 = defineNuxtModule({
62
82
  }
63
83
  ]);
64
84
  if (nuxt.options.dev) {
65
- addPlugin({
66
- src: resolver.resolve("./runtime/plugin.client"),
67
- mode: "client"
68
- });
69
- addPlugin({
70
- src: resolver.resolve("./runtime/plugin.suppress-warnings")
71
- });
85
+ if (enableSync && enableFetch) {
86
+ addPlugin({
87
+ src: resolver.resolve("./runtime/plugin.client"),
88
+ mode: "client"
89
+ });
90
+ } else if (enableSync) {
91
+ addPlugin({
92
+ src: resolver.resolve("./runtime/plugin.sync-only.client"),
93
+ mode: "client"
94
+ });
95
+ } else if (enableFetch) {
96
+ addPlugin({
97
+ src: resolver.resolve("./runtime/plugin.cdn.client"),
98
+ mode: "client"
99
+ });
100
+ }
101
+ if (enableSync) {
102
+ addPlugin({
103
+ src: resolver.resolve("./runtime/plugin.suppress-warnings")
104
+ });
105
+ }
72
106
  } else {
73
- addPlugin({
74
- src: resolver.resolve("./runtime/plugin.cdn.client"),
75
- mode: "client"
76
- });
107
+ if (enableFetch) {
108
+ addPlugin({
109
+ src: resolver.resolve("./runtime/plugin.cdn.client"),
110
+ mode: "client"
111
+ });
112
+ }
77
113
  }
78
114
  }
79
115
  });
@@ -26,8 +26,8 @@ export interface I18nowLocale {
26
26
  * ```
27
27
  */
28
28
  export declare function useI18nowLocales(): {
29
- locales: import("vue").ComputedRef<any>;
30
- sourceLocale: import("vue").ComputedRef<any>;
29
+ locales: any;
30
+ sourceLocale: any;
31
31
  pending: any;
32
32
  error: any;
33
33
  refresh: any;
@@ -1,6 +1,6 @@
1
1
  import { defineNuxtPlugin, useRuntimeConfig } from "#app";
2
2
  function createI18nowSyncer(options) {
3
- const { endpoint, apiKey, debug = false, maxTracked = 2e3, maxRetries = 3 } = options;
3
+ const { endpoint, extraBody, debug = false, maxTracked = 2e3, maxRetries = 3 } = options;
4
4
  const existingKeys = /* @__PURE__ */ new Set();
5
5
  const synced = /* @__PURE__ */ new Set();
6
6
  const retries = /* @__PURE__ */ new Map();
@@ -14,7 +14,7 @@ function createI18nowSyncer(options) {
14
14
  fetch(endpoint, {
15
15
  method: "POST",
16
16
  headers: { "Content-Type": "application/json" },
17
- body: JSON.stringify({ apiKey, keys })
17
+ body: JSON.stringify({ keys, ...extraBody })
18
18
  }).then((res) => {
19
19
  if (!res.ok) {
20
20
  if (debug) {
@@ -43,6 +43,18 @@ function createI18nowSyncer(options) {
43
43
  }
44
44
  function syncKey(key, value) {
45
45
  if (synced.has(key) || synced.size >= maxTracked) return;
46
+ if (!value || !/^[\w-]+(?:\.[\w-]+)*$/.test(key)) {
47
+ console.error(`[i18now] Invalid key skipped: "${key}" \u2014 keys must be dotted paths (e.g. "common.save")`);
48
+ return;
49
+ }
50
+ if (key.length > 100) {
51
+ console.error(`[i18now] Key "${key.slice(0, 20)}..." exceeds 100 character limit. Skipped.`);
52
+ return;
53
+ }
54
+ if (value.length > 1e3) {
55
+ console.error(`[i18now] Value for key "${key}" exceeds 1,000 character limit (${value.length} chars). Skipped.`);
56
+ return;
57
+ }
46
58
  synced.add(key);
47
59
  pending.set(key, value);
48
60
  if (!flushTimer) flushTimer = setTimeout(flush, 0);
@@ -63,7 +75,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
63
75
  const i18nGlobal = nuxtApp.$i18n ?? nuxtApp.vueApp.config.globalProperties.$i18n;
64
76
  const syncer = createI18nowSyncer({
65
77
  endpoint: `${host}/api/v1/projects/${projectId}/sync`,
66
- apiKey,
78
+ extraBody: { apiKey },
67
79
  debug: import.meta.dev
68
80
  });
69
81
  const locale = i18nGlobal?.locale?.value ?? i18nGlobal?.locale ?? configLocale;
@@ -22,9 +22,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
22
22
  }
23
23
  return;
24
24
  }
25
- const messages = data;
26
- if (i18n) i18n.mergeLocaleMessage(locale, messages);
27
- nuxtApp.payload.i18nowCdnKeys = Object.keys(messages);
25
+ if (i18n) i18n.mergeLocaleMessage(locale, data);
28
26
  } catch (err) {
29
27
  if (import.meta.dev) {
30
28
  console.warn(`[i18now] Failed to load locale '${locale}' from CDN:`, err);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Sync-only client plugin — key sync + $t patching, but NO mergeLocaleMessage.
3
+ *
4
+ * CDN is fetched only to populate existingKeys (for smart deduplication).
5
+ * Translations are NOT merged into vue-i18n — the user manages loading themselves.
6
+ */
7
+ declare const _default: (nuxtApp: unknown) => Promise<{
8
+ provide: {
9
+ i18nowSync: {
10
+ syncKey: (key: string, value: string) => void;
11
+ existingKeys: Set<string>;
12
+ };
13
+ };
14
+ } | undefined>;
15
+ export default _default;
@@ -0,0 +1,124 @@
1
+ import { defineNuxtPlugin, useRuntimeConfig } from "#app";
2
+ function createI18nowSyncer(options) {
3
+ const { endpoint, extraBody, debug = false, maxTracked = 2e3, maxRetries = 3 } = options;
4
+ const existingKeys = /* @__PURE__ */ new Set();
5
+ const synced = /* @__PURE__ */ new Set();
6
+ const retries = /* @__PURE__ */ new Map();
7
+ const pending = /* @__PURE__ */ new Map();
8
+ let flushTimer = null;
9
+ function flush() {
10
+ flushTimer = null;
11
+ if (pending.size === 0) return;
12
+ const keys = Array.from(pending.entries()).map(([key, value]) => ({ key, value }));
13
+ pending.clear();
14
+ fetch(endpoint, {
15
+ method: "POST",
16
+ headers: { "Content-Type": "application/json" },
17
+ body: JSON.stringify({ keys, ...extraBody })
18
+ }).then((res) => {
19
+ if (!res.ok) {
20
+ if (debug) {
21
+ res.json().then((data) => console.warn(`[i18now] Sync failed (${res.status}):`, data?.error ?? data?.statusMessage ?? data)).catch(() => console.warn(`[i18now] Sync failed with status ${res.status}`));
22
+ }
23
+ throw Object.assign(new Error(`${res.status}`), { status: res.status });
24
+ }
25
+ }).catch((err) => {
26
+ const status = err.status ?? 0;
27
+ const retryable = status === 0 || status === 429 || status >= 500;
28
+ for (const { key } of keys) {
29
+ if (!retryable) {
30
+ retries.delete(key);
31
+ continue;
32
+ }
33
+ const attempts = (retries.get(key) ?? 0) + 1;
34
+ if (attempts < maxRetries) {
35
+ retries.set(key, attempts);
36
+ synced.delete(key);
37
+ } else {
38
+ retries.delete(key);
39
+ if (debug) console.warn(`[i18now] Gave up syncing "${key}" after ${maxRetries} attempts.`);
40
+ }
41
+ }
42
+ });
43
+ }
44
+ function syncKey(key, value) {
45
+ if (synced.has(key) || synced.size >= maxTracked) return;
46
+ if (!value || !/^[\w-]+(?:\.[\w-]+)*$/.test(key)) {
47
+ console.error(`[i18now] Invalid key skipped: "${key}" \u2014 keys must be dotted paths (e.g. "common.save")`);
48
+ return;
49
+ }
50
+ if (key.length > 100) {
51
+ console.error(`[i18now] Key "${key.slice(0, 20)}..." exceeds 100 character limit. Skipped.`);
52
+ return;
53
+ }
54
+ if (value.length > 1e3) {
55
+ console.error(`[i18now] Value for key "${key}" exceeds 1,000 character limit (${value.length} chars). Skipped.`);
56
+ return;
57
+ }
58
+ synced.add(key);
59
+ pending.set(key, value);
60
+ if (!flushTimer) flushTimer = setTimeout(flush, 0);
61
+ }
62
+ function setExistingKeys(keys) {
63
+ existingKeys.clear();
64
+ for (const key of keys) existingKeys.add(key);
65
+ }
66
+ return { syncKey, existingKeys, setExistingKeys };
67
+ }
68
+ export default defineNuxtPlugin(async (nuxtApp) => {
69
+ const { projectId, apiKey, host, cdnUrl, environment, syncIn, locale: configLocale } = useRuntimeConfig().public.i18now;
70
+ if (!syncIn.includes(process.env.NODE_ENV ?? "production")) return;
71
+ if (!projectId) {
72
+ console.warn("[i18now] projectId is not set \u2014 key sync disabled.");
73
+ return;
74
+ }
75
+ const i18nGlobal = nuxtApp.$i18n ?? nuxtApp.vueApp.config.globalProperties.$i18n;
76
+ const syncer = createI18nowSyncer({
77
+ endpoint: `${host}/api/v1/projects/${projectId}/sync`,
78
+ extraBody: { apiKey },
79
+ debug: import.meta.dev
80
+ });
81
+ const locale = i18nGlobal?.locale?.value ?? i18nGlobal?.locale ?? configLocale;
82
+ async function loadExistingKeys(targetLocale) {
83
+ try {
84
+ const url = `${cdnUrl}/${projectId}/publish/${environment}/${targetLocale}.json`;
85
+ const res = await fetch(url, { signal: AbortSignal.timeout(5e3) });
86
+ if (res.ok) {
87
+ const data = await res.json();
88
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) {
89
+ syncer.setExistingKeys(Object.keys(data));
90
+ return;
91
+ }
92
+ }
93
+ syncer.setExistingKeys([]);
94
+ } catch {
95
+ syncer.setExistingKeys([]);
96
+ if (import.meta.dev) {
97
+ console.warn("[i18now] Could not fetch existing keys from CDN \u2014 all keys will be synced (backend deduplicates).");
98
+ }
99
+ }
100
+ }
101
+ let currentLocale = locale;
102
+ await loadExistingKeys(locale);
103
+ const originalGlobalT = nuxtApp.vueApp.config.globalProperties.$t;
104
+ if (originalGlobalT) {
105
+ nuxtApp.vueApp.config.globalProperties.$t = function(key, defaultValue, ...rest) {
106
+ const result = defaultValue !== void 0 ? originalGlobalT.call(this, key, defaultValue) : originalGlobalT.call(this, key);
107
+ const defaultStr = typeof defaultValue === "string" ? defaultValue : typeof rest[0] === "string" ? rest[0] : void 0;
108
+ if (!syncer.existingKeys.has(key) && defaultStr !== void 0) {
109
+ syncer.syncKey(key, defaultStr);
110
+ }
111
+ return result;
112
+ };
113
+ }
114
+ nuxtApp.hook("i18n:beforeLocaleSwitch", async ({ newLocale }) => {
115
+ if (newLocale === currentLocale) return;
116
+ currentLocale = newLocale;
117
+ await loadExistingKeys(newLocale);
118
+ });
119
+ return {
120
+ provide: {
121
+ i18nowSync: { syncKey: syncer.syncKey, existingKeys: syncer.existingKeys }
122
+ }
123
+ };
124
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uipkge/nuxt",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -36,8 +36,7 @@
36
36
  "@nuxt/module-builder": "^1.0.0",
37
37
  "happy-dom": "^17.0.0",
38
38
  "nuxt": "^3.0.0",
39
- "vitest": "^4.0.0",
40
- "@uipkge/core": "0.1.1"
39
+ "vitest": "^4.0.0"
41
40
  },
42
41
  "scripts": {
43
42
  "build": "nuxt-module-build build",