@inlang/paraglide-js 2.2.0 → 2.3.1

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,2 +1,2 @@
1
- export declare const paraglideRspackPlugin: (options: import("../index.js").CompilerOptions) => RspackPluginInstance;
1
+ export declare const paraglideRspackPlugin: (options: import("../index.js").CompilerOptions) => import("unplugin").RspackPluginInstance;
2
2
  //# sourceMappingURL=rspack.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rspack.d.ts","sourceRoot":"","sources":["../../src/bundler-plugins/rspack.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,qBAAqB,0EAAsC,CAAC"}
1
+ {"version":3,"file":"rspack.d.ts","sourceRoot":"","sources":["../../src/bundler-plugins/rspack.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,qBAAqB,6FAAsC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"unplugin.d.ts","sourceRoot":"","sources":["../../src/bundler-plugins/unplugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAMhD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAavE,eAAO,MAAM,eAAe,EAAE,eAAe,CAAC,eAAe,CAyH3D,CAAC"}
1
+ {"version":3,"file":"unplugin.d.ts","sourceRoot":"","sources":["../../src/bundler-plugins/unplugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAMhD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAavE,eAAO,MAAM,eAAe,EAAE,eAAe,CAAC,eAAe,CA2H3D,CAAC"}
@@ -36,6 +36,8 @@ export const unpluginFactory = (args) => ({
36
36
  catch (error) {
37
37
  logger.error("Failed to compile project:", error.message);
38
38
  logger.info("Please check your translation files for syntax errors.");
39
+ if (isProduction)
40
+ throw error;
39
41
  }
40
42
  finally {
41
43
  // in any case add the files to watch
@@ -118,6 +120,8 @@ export const unpluginFactory = (args) => ({
118
120
  catch (error) {
119
121
  logger.warn("Failed to compile project:", error.message);
120
122
  logger.warn("Please check your translation files for syntax errors.");
123
+ if (isProduction)
124
+ throw error;
121
125
  }
122
126
  });
123
127
  },
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=unplugin.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unplugin.test.d.ts","sourceRoot":"","sources":["../../src/bundler-plugins/unplugin.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,75 @@
1
+ import { test, expect, beforeEach, afterEach, vi } from "vitest";
2
+ import { paraglideVitePlugin } from "../bundler-plugins/vite.js";
3
+ import consola from "consola";
4
+ import { memfs } from "memfs";
5
+ import { loadProjectInMemory, newProject, saveProjectToDirectory, } from "@inlang/sdk";
6
+ let originalNodeEnv;
7
+ beforeEach(() => {
8
+ originalNodeEnv = process.env.NODE_ENV;
9
+ // Mock logging methods to suppress error messages in tests
10
+ consola.mockTypes(() => vi.fn());
11
+ });
12
+ afterEach(() => {
13
+ if (originalNodeEnv !== undefined) {
14
+ process.env.NODE_ENV = originalNodeEnv;
15
+ }
16
+ else {
17
+ delete process.env.NODE_ENV;
18
+ }
19
+ });
20
+ test("vite plugin does not throw when compilation is successful", async () => {
21
+ // Create and save a viable project to the virtual file system
22
+ const project = await loadProjectInMemory({
23
+ blob: await newProject({
24
+ settings: {
25
+ baseLocale: "en",
26
+ locales: ["en", "de", "fr"],
27
+ },
28
+ }),
29
+ });
30
+ const fs = memfs().fs;
31
+ await saveProjectToDirectory({
32
+ project,
33
+ path: "/project.inlang",
34
+ fs: fs.promises,
35
+ });
36
+ const plugin = paraglideVitePlugin({
37
+ project: "/project.inlang",
38
+ outdir: "/test-output",
39
+ fs: fs,
40
+ });
41
+ const mockContext = {
42
+ addWatchFile: () => { },
43
+ };
44
+ await expect(plugin.buildStart?.call(mockContext)).resolves.toBeUndefined();
45
+ });
46
+ test("vite plugin does not throw on compilation errors in development", async () => {
47
+ process.env.NODE_ENV = "development";
48
+ // Use memfs with no project (simulates missing project)
49
+ const fs = memfs().fs;
50
+ const plugin = paraglideVitePlugin({
51
+ project: "/non-existent-project.inlang",
52
+ outdir: "/test-output",
53
+ fs: fs,
54
+ });
55
+ const mockContext = {
56
+ addWatchFile: () => { },
57
+ };
58
+ // In development mode - should catch errors and NOT throw
59
+ await expect(plugin.buildStart?.call(mockContext)).resolves.toBeUndefined();
60
+ });
61
+ test("vite plugin throws on compilation errors at build time", async () => {
62
+ process.env.NODE_ENV = "production";
63
+ // Use memfs with no project (simulates missing project)
64
+ const fs = memfs().fs;
65
+ const plugin = paraglideVitePlugin({
66
+ project: "/non-existent-project.inlang",
67
+ outdir: "/test-output",
68
+ fs: fs,
69
+ });
70
+ const mockContext = {
71
+ addWatchFile: () => { },
72
+ };
73
+ // In production mode - should throw the error
74
+ await expect(plugin.buildStart?.call(mockContext)).rejects.toThrow();
75
+ });
@@ -1 +1 @@
1
- {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../../src/compiler/compile.ts"],"names":[],"mappings":"AASA,OAAO,EAEN,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAS/B,MAAM,MAAM,iBAAiB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;CACjD,CAAC;AAIF;;;;;;;;;;;;GAYG;AACH,wBAAsB,OAAO,CAC5B,OAAO,EAAE,eAAe,GAAG;IAC1B,mBAAmB,CAAC,EAAE,iBAAiB,CAAC;CACxC,GACC,OAAO,CAAC,iBAAiB,CAAC,CAqE5B"}
1
+ {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../../src/compiler/compile.ts"],"names":[],"mappings":"AASA,OAAO,EAEN,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAS/B,MAAM,MAAM,iBAAiB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;CACjD,CAAC;AAIF;;;;;;;;;;;;GAYG;AACH,wBAAsB,OAAO,CAC5B,OAAO,EAAE,eAAe,GAAG;IAC1B,mBAAmB,CAAC,EAAE,iBAAiB,CAAC;CACxC,GACC,OAAO,CAAC,iBAAiB,CAAC,CAuE5B"}
@@ -3,7 +3,10 @@ import path from "node:path";
3
3
  import { ENV_VARIABLES } from "../services/env-variables/index.js";
4
4
  import { compileProject } from "./compile-project.js";
5
5
  import { writeOutput } from "../services/file-handling/write-output.js";
6
- import { getLocalAccount, saveLocalAccount, } from "../services/account/index.js";
6
+ // import {
7
+ // getLocalAccount,
8
+ // saveLocalAccount,
9
+ // } from "../services/account/index.js";
7
10
  import { defaultCompilerOptions, } from "./compiler-options.js";
8
11
  import { Logger } from "../services/logger/index.js";
9
12
  // This is a workaround to prevent multiple compilations from running at the same time.
@@ -35,11 +38,11 @@ export async function compile(options) {
35
38
  try {
36
39
  const fs = withDefaultOptions.fs ?? (await import("node:fs"));
37
40
  const absoluteOutdir = path.resolve(process.cwd(), withDefaultOptions.outdir);
38
- const localAccount = getLocalAccount({ fs });
41
+ // const localAccount = getLocalAccount({ fs });
39
42
  const project = await loadProjectFromDirectory({
40
43
  path: withDefaultOptions.project,
41
44
  fs,
42
- account: localAccount,
45
+ // account: localAccount,
43
46
  appId: ENV_VARIABLES.PARJS_APP_ID,
44
47
  });
45
48
  const output = await compileProject({
@@ -53,13 +56,15 @@ export async function compile(options) {
53
56
  fs: fs.promises,
54
57
  previousOutputHashes: options.previousCompilation?.outputHashes,
55
58
  });
56
- if (!localAccount) {
57
- const activeAccount = await project.lix.db
58
- .selectFrom("active_account")
59
- .selectAll()
60
- .executeTakeFirstOrThrow();
61
- saveLocalAccount({ fs, account: activeAccount });
62
- }
59
+ // if (!localAccount) {
60
+ // const activeAccount = await project.lix.db
61
+ // .selectFrom("active_account as aa")
62
+ // .innerJoin("account_all as a", "a.id", "aa.account_id")
63
+ // .where("a.lixcol_version_id", "=", "global")
64
+ // .select(["a.id", "a.name"])
65
+ // .executeTakeFirstOrThrow();
66
+ // saveLocalAccount({ fs, account: activeAccount });
67
+ // }
63
68
  const warningsAndErrors = await project.errors.get();
64
69
  for (const warningOrError of warningsAndErrors) {
65
70
  logger.warn(warningOrError);
@@ -30,7 +30,7 @@ test("loads a project and compiles it", async () => {
30
30
  //runtime.js and messages.js are always compiled with the default options
31
31
  expect(files).toEqual(expect.arrayContaining(["runtime.js", "server.js", "messages.js"]));
32
32
  });
33
- test("loads a local account from app data if exists", async () => {
33
+ test.skip("loads a local account from app data if exists", async () => {
34
34
  const accountPath = getAccountFilePath();
35
35
  const fs = memfs({
36
36
  [accountPath]: JSON.stringify({ id: "mock", name: "test" }),
@@ -56,7 +56,7 @@ test("loads a local account from app data if exists", async () => {
56
56
  });
57
57
  expect(spy).toHaveBeenCalledWith(accountPath, "utf8");
58
58
  });
59
- test("saves the local account to app data if not exists", async () => {
59
+ test.skip("saves the local account to app data if not exists", async () => {
60
60
  const accountPath = getAccountFilePath();
61
61
  const fs = memfs().fs;
62
62
  const project = await loadProjectInMemory({
@@ -6,16 +6,19 @@
6
6
  * reloading is disabled, you need to ensure that the UI is updated
7
7
  * to reflect the new locale.
8
8
  *
9
+ * If any custom strategy's \`setLocale\` function is async, then this
10
+ * function will become async as well.
11
+ *
9
12
  * @example
10
13
  * setLocale('en');
11
14
  *
12
15
  * @example
13
16
  * setLocale('en', { reload: false });
14
17
  *
15
- * @type {(newLocale: Locale, options?: { reload?: boolean }) => void}
18
+ * @type {(newLocale: Locale, options?: { reload?: boolean }) => Promise<void> | void}
16
19
  */
17
20
  export let setLocale: (newLocale: Locale, options?: {
18
21
  reload?: boolean;
19
- }) => void;
22
+ }) => Promise<void> | void;
20
23
  export function overwriteSetLocale(fn: (newLocale: Locale) => void): void;
21
24
  //# sourceMappingURL=set-locale.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"set-locale.d.ts","sourceRoot":"","sources":["../../../src/compiler/runtime/set-locale.js"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;;GAeG;AACH,sBAFU,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,KAAK,IAAI,CA8FnE;AAgBK,uCAFI,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAIrC"}
1
+ {"version":3,"file":"set-locale.d.ts","sourceRoot":"","sources":["../../../src/compiler/runtime/set-locale.js"],"names":[],"mappings":"AAgCA;;;;;;;;;;;;;;;;;;GAkBG;AACH,sBAFU,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAmGnF;AAgBK,uCAFI,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,QAIrC"}
@@ -2,6 +2,22 @@ import { getLocale } from "./get-locale.js";
2
2
  import { localizeUrl } from "./localize-url.js";
3
3
  import { customClientStrategies, isCustomStrategy } from "./strategy.js";
4
4
  import { cookieDomain, cookieMaxAge, cookieName, isServer, localStorageKey, strategy, TREE_SHAKE_COOKIE_STRATEGY_USED, TREE_SHAKE_GLOBAL_VARIABLE_STRATEGY_USED, TREE_SHAKE_LOCAL_STORAGE_STRATEGY_USED, TREE_SHAKE_URL_STRATEGY_USED, } from "./variables.js";
5
+ /**
6
+ * Navigates to the localized URL, or reloads the current page
7
+ *
8
+ * @param {string} [newLocation] The new location
9
+ * @return {undefined}
10
+ */
11
+ const navigateOrReload = (newLocation) => {
12
+ if (newLocation) {
13
+ // reload the page by navigating to the new url
14
+ window.location.href = newLocation;
15
+ }
16
+ else {
17
+ // reload the page to reflect the new locale
18
+ window.location.reload();
19
+ }
20
+ };
5
21
  /**
6
22
  * Set the locale.
7
23
  *
@@ -10,13 +26,16 @@ import { cookieDomain, cookieMaxAge, cookieName, isServer, localStorageKey, stra
10
26
  * reloading is disabled, you need to ensure that the UI is updated
11
27
  * to reflect the new locale.
12
28
  *
29
+ * If any custom strategy's \`setLocale\` function is async, then this
30
+ * function will become async as well.
31
+ *
13
32
  * @example
14
33
  * setLocale('en');
15
34
  *
16
35
  * @example
17
36
  * setLocale('en', { reload: false });
18
37
  *
19
- * @type {(newLocale: Locale, options?: { reload?: boolean }) => void}
38
+ * @type {(newLocale: Locale, options?: { reload?: boolean }) => Promise<void> | void}
20
39
  */
21
40
  export let setLocale = (newLocale, options) => {
22
41
  const optionsWithDefaults = {
@@ -32,6 +51,8 @@ export let setLocale = (newLocale, options) => {
32
51
  catch {
33
52
  // do nothing, no locale has been set yet.
34
53
  }
54
+ /** @type {Array<Promise<any>>} */
55
+ const customSetLocalePromises = [];
35
56
  /** @type {string | undefined} */
36
57
  let newLocation = undefined;
37
58
  for (const strat of strategy) {
@@ -85,8 +106,9 @@ export let setLocale = (newLocale, options) => {
85
106
  // Handle async setLocale - fire and forget
86
107
  if (result instanceof Promise) {
87
108
  result.catch((error) => {
88
- console.warn(`Custom strategy "${strat}" setLocale failed:`, error);
109
+ error.message = `Custom strategy "${strat}" setLocale failed: ${error.message}`;
89
110
  });
111
+ customSetLocalePromises.push(result);
90
112
  }
91
113
  }
92
114
  }
@@ -95,13 +117,14 @@ export let setLocale = (newLocale, options) => {
95
117
  optionsWithDefaults.reload &&
96
118
  window.location &&
97
119
  newLocale !== currentLocale) {
98
- if (newLocation) {
99
- // reload the page by navigating to the new url
100
- window.location.href = newLocation;
120
+ if (customSetLocalePromises.length) {
121
+ // Wait for any async custom setLocale functions
122
+ return Promise.all(customSetLocalePromises).then(() => {
123
+ navigateOrReload(newLocation);
124
+ });
101
125
  }
102
126
  else {
103
- // reload the page to reflect the new locale
104
- window.location.reload();
127
+ navigateOrReload(newLocation);
105
128
  }
106
129
  }
107
130
  return;
@@ -317,6 +317,102 @@ test("calls setLocale on multiple custom strategies", async () => {
317
317
  expect(customLocale1).toBe("de");
318
318
  expect(customLocale2).toBe("de");
319
319
  });
320
+ test("awaits async setLocale functions to resolve in custom strategy", async () => {
321
+ let customLocale1 = "en";
322
+ globalThis.window = {
323
+ location: {
324
+ reload: vi.fn(),
325
+ },
326
+ };
327
+ const runtime = await createParaglide({
328
+ blob: await newProject({
329
+ settings: {
330
+ baseLocale: "en",
331
+ locales: ["en", "fr", "de"],
332
+ },
333
+ }),
334
+ strategy: ["custom-async", "baseLocale"],
335
+ isServer: "false",
336
+ });
337
+ runtime.defineCustomClientStrategy("custom-async", {
338
+ getLocale: () => customLocale1,
339
+ setLocale: async (locale) => {
340
+ customLocale1 = locale;
341
+ },
342
+ });
343
+ const setLocalePromise = runtime.setLocale("de");
344
+ expect(window.location.reload).not.toHaveBeenCalled();
345
+ await setLocalePromise;
346
+ // Verify that setLocale resolved before reload was called
347
+ expect(window.location.reload).toHaveBeenCalledTimes(1);
348
+ expect(customLocale1).toBe("de");
349
+ });
350
+ test("awaits async setLocale functions to resolve in multiple custom strategies", async () => {
351
+ let customLocale1 = "en";
352
+ let customLocale2 = "en";
353
+ globalThis.window = {
354
+ location: {
355
+ reload: vi.fn(),
356
+ },
357
+ };
358
+ const runtime = await createParaglide({
359
+ blob: await newProject({
360
+ settings: {
361
+ baseLocale: "en",
362
+ locales: ["en", "fr", "de"],
363
+ },
364
+ }),
365
+ strategy: ["custom-async1", "custom-async2", "baseLocale"],
366
+ isServer: "false",
367
+ });
368
+ runtime.defineCustomClientStrategy("custom-async1", {
369
+ getLocale: () => customLocale1,
370
+ setLocale: async (locale) => {
371
+ customLocale1 = locale;
372
+ },
373
+ });
374
+ runtime.defineCustomClientStrategy("custom-async2", {
375
+ getLocale: () => customLocale2,
376
+ setLocale: async (locale) => {
377
+ customLocale2 = locale;
378
+ },
379
+ });
380
+ const setLocalePromise = runtime.setLocale("de");
381
+ expect(window.location.reload).not.toHaveBeenCalled();
382
+ await setLocalePromise;
383
+ // Verify that setLocale resolved before reload was called
384
+ expect(window.location.reload).toHaveBeenCalledTimes(1);
385
+ expect(customLocale1).toBe("de");
386
+ expect(customLocale2).toBe("de");
387
+ });
388
+ test("reload should not run if async setLocale function rejects in custom strategy", async () => {
389
+ const customLocale1 = "en";
390
+ globalThis.window = {
391
+ location: {
392
+ reload: vi.fn(),
393
+ },
394
+ };
395
+ const runtime = await createParaglide({
396
+ blob: await newProject({
397
+ settings: {
398
+ baseLocale: "en",
399
+ locales: ["en", "fr", "de"],
400
+ },
401
+ }),
402
+ strategy: ["custom-async", "baseLocale"],
403
+ isServer: "false",
404
+ });
405
+ runtime.defineCustomClientStrategy("custom-async", {
406
+ getLocale: () => customLocale1,
407
+ setLocale: async () => {
408
+ throw new Error("fetch error");
409
+ },
410
+ });
411
+ await expect(() => runtime.setLocale("de")).rejects.toThrowError(`Custom strategy "custom-async" setLocale failed: fetch error`);
412
+ // Verify that reload was never called
413
+ expect(window.location.reload).toHaveBeenCalledTimes(0);
414
+ expect(customLocale1).toBe("en");
415
+ });
320
416
  test("custom strategy setLocale works with cookie and localStorage", async () => {
321
417
  let customData = "en";
322
418
  globalThis.document = { cookie: "" };
@@ -1,6 +1,6 @@
1
1
  export declare const ENV_VARIABLES: {
2
2
  PARJS_APP_ID: string;
3
- PARJS_POSTHOG_TOKEN: string;
3
+ PARJS_POSTHOG_TOKEN: undefined;
4
4
  PARJS_PACKAGE_VERSION: string;
5
5
  };
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,5 @@
1
1
  export const ENV_VARIABLES = {
2
2
  PARJS_APP_ID: "library.inlang.paraglideJs",
3
- PARJS_POSTHOG_TOKEN: "phc_m5yJZCxjOGxF8CJvP5sQ3H0d76xpnLrsmiZHduT4jDz",
4
- PARJS_PACKAGE_VERSION: "2.2.0",
3
+ PARJS_POSTHOG_TOKEN: undefined,
4
+ PARJS_PACKAGE_VERSION: "2.3.0",
5
5
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@inlang/paraglide-js",
3
3
  "type": "module",
4
- "version": "2.2.0",
4
+ "version": "2.3.1",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -26,13 +26,13 @@
26
26
  "./urlpattern-polyfill": "./dist/urlpattern-polyfill/index.js"
27
27
  },
28
28
  "dependencies": {
29
+ "@inlang/sdk": "2.4.9",
29
30
  "commander": "11.1.0",
30
31
  "consola": "3.4.0",
31
32
  "json5": "2.2.3",
32
33
  "unplugin": "^2.1.2",
33
34
  "urlpattern-polyfill": "^10.0.0",
34
- "@inlang/recommend-sherlock": "0.2.1",
35
- "@inlang/sdk": "2.4.9"
35
+ "@inlang/recommend-sherlock": "0.2.1"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@eslint/js": "^9.18.0",
@@ -44,14 +44,13 @@
44
44
  "memfs": "4.17.0",
45
45
  "prettier": "^3.4.2",
46
46
  "rolldown": "1.0.0-beta.1",
47
- "typedoc": "^0.28.5",
48
- "typedoc-plugin-markdown": "^4.7.0",
47
+ "typedoc": "0.28.12",
48
+ "typedoc-plugin-markdown": "4.7.0",
49
49
  "typedoc-plugin-missing-exports": "4.0.0",
50
- "typescript": "^5.7.3",
50
+ "typescript": "5.8.3",
51
51
  "typescript-eslint": "^8.20.0",
52
52
  "vitest": "2.1.8",
53
53
  "@inlang/plugin-message-format": "4.0.0",
54
- "@inlang/paraglide-js": "2.2.0",
55
54
  "@opral/tsconfig": "1.1.0"
56
55
  },
57
56
  "keywords": [