@inlang/paraglide-js 1.2.0 → 1.2.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,31 +1,39 @@
1
1
  import { Command } from "commander";
2
2
  import { type ProjectSettings } from "@inlang/sdk";
3
3
  import { Logger } from "../../services/logger/index.js";
4
+ import { type Repository } from "@lix-js/client";
5
+ import type { NodeishFilesystem } from "@lix-js/fs";
6
+ type Context = {
7
+ logger: Logger;
8
+ repo: Repository;
9
+ };
4
10
  export declare const initCommand: Command;
5
- export declare const initializeInlangProject: (logger: Logger) => Promise<string>;
11
+ export declare const initializeInlangProject: (ctx: Context) => Promise<string>;
6
12
  export declare const maybeAddVsCodeExtension: (args: {
7
13
  projectPath: string;
8
- }, logger: Logger) => Promise<void>;
9
- export declare const addParaglideJsToDevDependencies: (logger: Logger) => Promise<void>;
10
- export declare const findExistingInlangProjectPath: () => Promise<string | undefined>;
14
+ }, ctx: Context) => Promise<void>;
15
+ export declare const addParaglideJsToDevDependencies: (ctx: Context) => Promise<void>;
16
+ export declare const findExistingInlangProjectPath: (ctx: Context) => Promise<string | undefined>;
11
17
  export declare const existingProjectFlow: (args: {
12
18
  existingProjectPath: string;
13
- }, logger: Logger) => Promise<undefined>;
14
- export declare const createNewProjectFlow: (logger: Logger) => Promise<undefined>;
19
+ }, ctx: Context) => Promise<undefined>;
20
+ export declare const createNewProjectFlow: (ctx: Context) => Promise<undefined>;
15
21
  export declare const newProjectTemplate: ProjectSettings;
16
- export declare const checkIfPackageJsonExists: (logger: Logger) => Promise<undefined>;
17
- export declare const checkIfUncommittedChanges: (logger: Logger) => Promise<void>;
22
+ export declare const checkIfPackageJsonExists: (ctx: Context) => Promise<undefined>;
23
+ export declare const checkIfUncommittedChanges: (ctx: Context) => Promise<void>;
18
24
  export declare const addCompileStepToPackageJSON: (args: {
19
25
  projectPath: string;
20
- }, logger: Logger) => Promise<undefined>;
26
+ }, ctx: Context) => Promise<undefined>;
21
27
  /**
22
28
  * Ensures that the moduleResolution compiler option is set to "bundler" or similar in the tsconfig.json.
23
29
  *
24
30
  * Otherwise, types defined in `package.exports` are not resolved by TypeScript. Leading to type
25
31
  * errors with Paraglide-JS.
26
32
  */
27
- export declare const maybeChangeTsConfigModuleResolution: (logger: Logger) => Promise<void>;
33
+ export declare const maybeChangeTsConfigModuleResolution: (ctx: Context) => Promise<void>;
28
34
  /**
29
35
  * Paraligde JS compiles to JS with JSDoc comments. TypeScript doesn't allow JS files by default.
30
36
  */
31
- export declare const maybeChangeTsConfigAllowJs: (logger: Logger) => Promise<void>;
37
+ export declare const maybeChangeTsConfigAllowJs: (ctx: Context) => Promise<void>;
38
+ export declare function fileExists(filePath: string, nodeishFs: NodeishFilesystem): Promise<boolean>;
39
+ export {};
package/dist/index.js CHANGED
@@ -20428,7 +20428,7 @@ var require_package = __commonJS({
20428
20428
  var require_main = __commonJS({
20429
20429
  "../../../../node_modules/.pnpm/dotenv@16.3.1/node_modules/dotenv/lib/main.js"(exports, module) {
20430
20430
  init_define_ENV_DEFINED_IN_BUILD_STEP();
20431
- var fs4 = __require("fs");
20431
+ var fs2 = __require("fs");
20432
20432
  var path3 = __require("path");
20433
20433
  var os = __require("os");
20434
20434
  var crypto3 = __require("crypto");
@@ -20553,7 +20553,7 @@ var require_main = __commonJS({
20553
20553
  }
20554
20554
  }
20555
20555
  try {
20556
- const parsed = DotenvModule.parse(fs4.readFileSync(dotenvPath, { encoding }));
20556
+ const parsed = DotenvModule.parse(fs2.readFileSync(dotenvPath, { encoding }));
20557
20557
  let processEnv = process.env;
20558
20558
  if (options && options.processEnv != null) {
20559
20559
  processEnv = options.processEnv;
@@ -20572,7 +20572,7 @@ var require_main = __commonJS({
20572
20572
  if (_dotenvKey(options).length === 0) {
20573
20573
  return DotenvModule.configDotenv(options);
20574
20574
  }
20575
- if (!fs4.existsSync(vaultPath)) {
20575
+ if (!fs2.existsSync(vaultPath)) {
20576
20576
  _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
20577
20577
  return DotenvModule.configDotenv(options);
20578
20578
  }
@@ -23847,7 +23847,7 @@ var createEffect4 = createEffect3;
23847
23847
  // ../../../../lix/source-code/client/dist/git/commit.js
23848
23848
  init_define_ENV_DEFINED_IN_BUILD_STEP();
23849
23849
  import { walk, TREE, STAGE, writeTree, commit as doCommit } from "isomorphic-git";
23850
- async function commit({ fs: fs4, dir, ref, author, message }) {
23850
+ async function commit({ fs: fs2, dir, ref, author, message }) {
23851
23851
  const fileStates = {};
23852
23852
  async function createTree(currentFolder, fileStates2) {
23853
23853
  const entries = [];
@@ -23875,10 +23875,10 @@ async function commit({ fs: fs4, dir, ref, author, message }) {
23875
23875
  });
23876
23876
  }
23877
23877
  }
23878
- return await writeTree({ fs: fs4, dir, tree: entries });
23878
+ return await writeTree({ fs: fs2, dir, tree: entries });
23879
23879
  }
23880
23880
  await walk({
23881
- fs: fs4,
23881
+ fs: fs2,
23882
23882
  dir,
23883
23883
  // cache, gitdir,
23884
23884
  trees: [TREE({ ref }), STAGE()],
@@ -23938,7 +23938,7 @@ async function commit({ fs: fs4, dir, ref, author, message }) {
23938
23938
  });
23939
23939
  const tree = await createTree("/", fileStates);
23940
23940
  return doCommit({
23941
- fs: fs4,
23941
+ fs: fs2,
23942
23942
  dir,
23943
23943
  author,
23944
23944
  message,
@@ -24497,6 +24497,38 @@ async function generateProjectId(args) {
24497
24497
  return void 0;
24498
24498
  }
24499
24499
 
24500
+ // ../../sdk/dist/telemetry/capture.js
24501
+ init_define_ENV_DEFINED_IN_BUILD_STEP();
24502
+
24503
+ // ../../sdk/dist/env-variables/index.js
24504
+ init_define_ENV_DEFINED_IN_BUILD_STEP();
24505
+ var ENV_VARIABLES = {
24506
+ PUBLIC_POSTHOG_TOKEN: "phc_m5yJZCxjOGxF8CJvP5sQ3H0d76xpnLrsmiZHduT4jDz"
24507
+ };
24508
+
24509
+ // ../../sdk/dist/telemetry/capture.js
24510
+ var capture = async (event, args) => {
24511
+ if (ENV_VARIABLES.PUBLIC_POSTHOG_TOKEN === void 0) {
24512
+ return;
24513
+ }
24514
+ try {
24515
+ await fetch("https://eu.posthog.com/capture/", {
24516
+ method: "POST",
24517
+ body: JSON.stringify({
24518
+ api_key: ENV_VARIABLES.PUBLIC_POSTHOG_TOKEN,
24519
+ event,
24520
+ // id is "unknown" because no user information is available
24521
+ distinct_id: "unknown",
24522
+ properties: {
24523
+ $groups: { project: args.projectId },
24524
+ ...args.properties
24525
+ }
24526
+ })
24527
+ });
24528
+ } catch (e) {
24529
+ }
24530
+ };
24531
+
24500
24532
  // ../../sdk/dist/loadProject.js
24501
24533
  var settingsCompiler = import_compiler3.TypeCompiler.Compile(ProjectSettings);
24502
24534
  async function loadProject(args) {
@@ -24511,30 +24543,26 @@ Valid examples:
24511
24543
  - "/path/to/green-elephant.inlang
24512
24544
  `, { argument: "projectPath" });
24513
24545
  }
24514
- let fs4;
24546
+ let fs2;
24515
24547
  if (args.nodeishFs) {
24516
- fs4 = args.nodeishFs;
24548
+ fs2 = args.nodeishFs;
24517
24549
  } else if (args.repo) {
24518
- fs4 = args.repo.nodeishFs;
24550
+ fs2 = args.repo.nodeishFs;
24519
24551
  } else {
24520
24552
  throw new LoadProjectInvalidArgument(`Repo missing from arguments.`, { argument: "repo" });
24521
24553
  }
24522
24554
  const nodeishFs = createNodeishFsWithAbsolutePaths({
24523
24555
  projectPath,
24524
- nodeishFs: fs4
24556
+ nodeishFs: fs2
24525
24557
  });
24526
- await maybeMigrateToDirectory({ nodeishFs: fs4, projectPath });
24558
+ await maybeMigrateToDirectory({ nodeishFs: fs2, projectPath });
24527
24559
  await maybeCreateFirstProjectId({ projectPath, repo: args.repo });
24528
24560
  return await createRoot2(async () => {
24561
+ const { data: projectId } = await tryCatch(() => fs2.readFile(args.projectPath + "/project_id", { encoding: "utf-8" }));
24529
24562
  const [initialized, markInitAsComplete, markInitAsFailed] = createAwaitable();
24530
24563
  const [settings, _setSettings] = createSignal2();
24531
24564
  createEffect2(() => {
24532
- loadSettings({ settingsFilePath: projectPath + "/settings.json", nodeishFs }).then((settings2) => {
24533
- var _a;
24534
- setSettings(settings2);
24535
- const project_settings = settings2;
24536
- (_a = args._capture) == null ? void 0 : _a.call(args, "SDK used settings", { project_settings });
24537
- }).catch((err) => {
24565
+ loadSettings({ settingsFilePath: projectPath + "/settings.json", nodeishFs }).then((settings2) => setSettings(settings2)).catch((err) => {
24538
24566
  markInitAsFailed(err);
24539
24567
  });
24540
24568
  });
@@ -24572,10 +24600,10 @@ Valid examples:
24572
24600
  markInitAsFailed(void 0);
24573
24601
  return;
24574
24602
  }
24575
- const loadAndSetMessages = async (fs5) => {
24603
+ const loadAndSetMessages = async (fs3) => {
24576
24604
  makeTrulyAsync(_resolvedModules.resolvedPluginApi.loadMessages({
24577
24605
  settings: settingsValue,
24578
- nodeishFs: fs5
24606
+ nodeishFs: fs3
24579
24607
  })).then((messages2) => {
24580
24608
  setMessages(messages2);
24581
24609
  markInitAsComplete();
@@ -24644,6 +24672,20 @@ Valid examples:
24644
24672
  createEffect2(() => {
24645
24673
  debouncedSave(messagesQuery.getAll());
24646
24674
  });
24675
+ let projectLoadedCapturedAlready = false;
24676
+ if (projectId && projectLoadedCapturedAlready === false) {
24677
+ projectLoadedCapturedAlready = true;
24678
+ await capture("SDK loaded project", {
24679
+ projectId,
24680
+ properties: {
24681
+ appId: args.appId,
24682
+ settings: settings(),
24683
+ installedPluginIds: installedPlugins().map((p) => p.id),
24684
+ installedMessageLintRuleIds: installedMessageLintRules().map((r) => r.id),
24685
+ numberOfMessages: messagesQuery.includedMessageIds().length
24686
+ }
24687
+ });
24688
+ }
24647
24689
  return {
24648
24690
  installed: {
24649
24691
  plugins: createSubscribable(() => installedPlugins()),
@@ -24652,8 +24694,6 @@ Valid examples:
24652
24694
  errors: createSubscribable(() => [
24653
24695
  ...initializeError ? [initializeError] : [],
24654
24696
  ...resolvedModules() ? resolvedModules().errors : []
24655
- // have a query error exposed
24656
- //...(lintErrors() ?? []),
24657
24697
  ]),
24658
24698
  settings: createSubscribable(() => settings()),
24659
24699
  setSettings,
@@ -29069,12 +29109,12 @@ var telemetry = new Proxy(posthog, {
29069
29109
  if (publicEnv.PUBLIC_POSTHOG_TOKEN === void 0) {
29070
29110
  return () => void 0;
29071
29111
  } else if (prop === "capture") {
29072
- return capture;
29112
+ return capture2;
29073
29113
  }
29074
29114
  return target[prop];
29075
29115
  }
29076
29116
  });
29077
- function capture(args) {
29117
+ function capture2(args) {
29078
29118
  return posthog.capture({
29079
29119
  ...args,
29080
29120
  distinctId: "unknown"
@@ -29285,7 +29325,7 @@ export function isAvailableLanguageTag(thing) {
29285
29325
  };
29286
29326
 
29287
29327
  // src/cli/commands/compile.ts
29288
- import fs from "node:fs/promises";
29328
+ import nodeFsPromises from "node:fs/promises";
29289
29329
  import { resolve } from "node:path";
29290
29330
  import { Command } from "commander";
29291
29331
 
@@ -29294,32 +29334,30 @@ init_define_ENV_DEFINED_IN_BUILD_STEP();
29294
29334
  import path from "node:path";
29295
29335
  import crypto2 from "node:crypto";
29296
29336
  var previousOutputHash;
29297
- async function writeOutput(outputDirectory, output, fs4) {
29337
+ async function writeOutput(outputDirectory, output, fs2) {
29298
29338
  const currentOutputHash = hashOutput(output, outputDirectory);
29299
29339
  if (currentOutputHash === previousOutputHash)
29300
29340
  return;
29301
- await fs4.access(outputDirectory).catch(async () => {
29302
- await fs4.mkdir(outputDirectory, { recursive: true });
29341
+ await fs2.access(outputDirectory).catch(async () => {
29342
+ await fs2.mkdir(outputDirectory, { recursive: true });
29303
29343
  });
29304
- const files = await fs4.readdir(outputDirectory);
29344
+ const files = await fs2.readdir(outputDirectory);
29305
29345
  await Promise.allSettled(
29306
29346
  files.map(async (file) => {
29307
- await fs4.unlink(outputDirectory + "/" + file);
29347
+ await fs2.unlink(outputDirectory + "/" + file);
29308
29348
  })
29309
29349
  );
29310
29350
  await Promise.allSettled(
29311
29351
  Object.keys(output).map(async (filePath) => {
29312
29352
  const fullPath = path.resolve(outputDirectory, filePath);
29313
29353
  const directory = path.dirname(fullPath);
29314
- await fs4.mkdir(directory, { recursive: true });
29354
+ await fs2.mkdir(directory, { recursive: true });
29315
29355
  })
29316
29356
  );
29317
29357
  await Promise.allSettled(
29318
29358
  Object.entries(output).map(async ([filePath, fileContent]) => {
29319
29359
  const fullPath = path.resolve(outputDirectory, filePath);
29320
- await fs4.writeFile(fullPath, fileContent, {
29321
- encoding: "utf-8"
29322
- });
29360
+ await fs2.writeFile(fullPath, fileContent);
29323
29361
  })
29324
29362
  );
29325
29363
  previousOutputHash = currentOutputHash;
@@ -29399,51 +29437,22 @@ var compileCommand = new Command().name("compile").summary("Compiles inlang Para
29399
29437
  const path3 = resolve(process.cwd(), options.project);
29400
29438
  const outputDirectory = resolve(process.cwd(), options.outdir);
29401
29439
  logger.info(`Compiling inlang project at "${options.project}".`);
29402
- const repoRoot = await findRepoRoot({ nodeishFs: fs, path: path3 });
29403
- let project;
29440
+ const repoRoot = await findRepoRoot({ nodeishFs: nodeFsPromises, path: path3 });
29441
+ const repo = await openRepository(repoRoot || process.cwd(), {
29442
+ nodeishFs: nodeFsPromises
29443
+ });
29404
29444
  if (!repoRoot) {
29405
29445
  logger.warn(`Could not find repository root for path ${path3}`);
29406
- project = exitIfErrors(
29407
- await loadProject({
29408
- projectPath: path3,
29409
- nodeishFs: fs,
29410
- _capture(id, props) {
29411
- telemetry.capture({
29412
- // @ts-ignore the event types
29413
- event: id,
29414
- properties: props
29415
- });
29416
- }
29417
- }),
29418
- logger
29419
- );
29420
- } else {
29421
- const repo = await openRepository(repoRoot, {
29422
- nodeishFs: fs
29423
- });
29424
- project = exitIfErrors(
29425
- await loadProject({
29426
- projectPath: path3,
29427
- repo,
29428
- _capture(id, props) {
29429
- telemetry.capture({
29430
- // @ts-ignore the event types
29431
- event: id,
29432
- properties: props
29433
- });
29434
- }
29435
- }),
29436
- logger
29437
- );
29438
- }
29439
- async function execute() {
29440
- const output = compile({
29441
- messages: project.query.messages.getAll(),
29442
- settings: project.settings()
29443
- });
29444
- await writeOutput(outputDirectory, output, fs);
29445
29446
  }
29446
- await execute();
29447
+ const project = exitIfErrors(
29448
+ await loadProject({
29449
+ projectPath: path3,
29450
+ repo,
29451
+ appId: "library.inlang.paraglideJs"
29452
+ }),
29453
+ logger
29454
+ );
29455
+ await executeCompilation(project, outputDirectory, repo.nodeishFs);
29447
29456
  if (options.watch) {
29448
29457
  process.on("SIGINT", () => {
29449
29458
  logger.ln().info("Stopping the watcher.");
@@ -29457,7 +29466,7 @@ var compileCommand = new Command().name("compile").summary("Compiles inlang Para
29457
29466
  if (numChanges === 1)
29458
29467
  return;
29459
29468
  logger.info("Messages changed. Recompiling...");
29460
- await execute();
29469
+ await executeCompilation(project, outputDirectory, repo.nodeishFs);
29461
29470
  });
29462
29471
  while (true) {
29463
29472
  await new Promise((resolve3) => setTimeout(resolve3, 1e4));
@@ -29465,6 +29474,13 @@ var compileCommand = new Command().name("compile").summary("Compiles inlang Para
29465
29474
  }
29466
29475
  logger.info("Sucessfully compiled the project.");
29467
29476
  });
29477
+ async function executeCompilation(project, outputDirectory, fs2) {
29478
+ const output = compile({
29479
+ messages: project.query.messages.getAll(),
29480
+ settings: project.settings()
29481
+ });
29482
+ await writeOutput(outputDirectory, output, fs2);
29483
+ }
29468
29484
  var exitIfErrors = (project, logger) => {
29469
29485
  if (project.errors().length > 0) {
29470
29486
  logger.warn(`The project has errors:`);
@@ -29479,8 +29495,6 @@ var exitIfErrors = (project, logger) => {
29479
29495
  // src/cli/commands/init.ts
29480
29496
  init_define_ENV_DEFINED_IN_BUILD_STEP();
29481
29497
  import { Command as Command2 } from "commander";
29482
- import fs3 from "node:fs/promises";
29483
- import fsSync from "node:fs";
29484
29498
  import consola2 from "consola";
29485
29499
  import { resolve as resolve2 } from "node:path";
29486
29500
  import { detectJsonFormatting } from "@inlang/detect-json-formatting";
@@ -29490,7 +29504,7 @@ import childProcess from "node:child_process";
29490
29504
  // src/cli/state.ts
29491
29505
  init_define_ENV_DEFINED_IN_BUILD_STEP();
29492
29506
  import path2 from "node:path";
29493
- import fs2 from "node:fs";
29507
+ import fs from "node:fs";
29494
29508
  import { fileURLToPath } from "node:url";
29495
29509
  var version = (() => {
29496
29510
  const currentFilePath = fileURLToPath(import.meta.url).split(path2.sep).join(path2.posix.sep);
@@ -29498,31 +29512,42 @@ var version = (() => {
29498
29512
  0,
29499
29513
  currentFilePath.indexOf("/paraglide-js/") + "/paraglide-js".length
29500
29514
  );
29501
- return JSON.parse(fs2.readFileSync(`${paraglideDirectory}/package.json`, "utf-8")).version;
29515
+ return JSON.parse(fs.readFileSync(`${paraglideDirectory}/package.json`, "utf-8")).version;
29502
29516
  })();
29503
29517
 
29504
29518
  // src/cli/commands/init.ts
29505
29519
  import dedent2 from "dedent";
29520
+ import nodeFsPromises2 from "node:fs/promises";
29506
29521
  var DEFAULT_PROJECT_PATH = "./project.inlang";
29507
29522
  var initCommand = new Command2().name("init").summary("Initializes inlang Paraglide-JS.").action(async () => {
29508
- const logger = new Logger({ silent: false, prefix: false });
29509
- logger.box("Welcome to inlang Paraglide-JS \u{1FA82}");
29523
+ const repoRoot = await findRepoRoot({
29524
+ nodeishFs: nodeFsPromises2,
29525
+ path: process.cwd()
29526
+ });
29527
+ const repo = await openRepository(repoRoot ?? process.cwd(), {
29528
+ nodeishFs: nodeFsPromises2
29529
+ });
29530
+ const ctx = {
29531
+ logger: new Logger({ silent: false, prefix: false }),
29532
+ repo
29533
+ };
29534
+ ctx.logger.box("Welcome to inlang Paraglide-JS \u{1FA82}");
29510
29535
  telemetry.capture({ event: "PARAGLIDE-JS init started" });
29511
- await checkIfUncommittedChanges(logger);
29512
- await checkIfPackageJsonExists(logger);
29513
- const projectPath = await initializeInlangProject(logger);
29536
+ await checkIfUncommittedChanges(ctx);
29537
+ await checkIfPackageJsonExists(ctx);
29538
+ const projectPath = await initializeInlangProject(ctx);
29514
29539
  telemetry.capture({ event: "PARAGLIDE-JS init project initialized" });
29515
- await addParaglideJsToDevDependencies(logger);
29540
+ await addParaglideJsToDevDependencies(ctx);
29516
29541
  telemetry.capture({ event: "PARAGLIDE-JS init added to devDependencies" });
29517
- await addCompileStepToPackageJSON({ projectPath }, logger);
29542
+ await addCompileStepToPackageJSON({ projectPath }, ctx);
29518
29543
  telemetry.capture({ event: "PARAGLIDE-JS init added compile commands" });
29519
- await maybeChangeTsConfigModuleResolution(logger);
29520
- await maybeChangeTsConfigAllowJs(logger);
29521
- await maybeAddVsCodeExtension({ projectPath }, logger);
29544
+ await maybeChangeTsConfigModuleResolution(ctx);
29545
+ await maybeChangeTsConfigAllowJs(ctx);
29546
+ await maybeAddVsCodeExtension({ projectPath }, ctx);
29522
29547
  telemetry.capture({ event: "PARAGLIDE-JS init finished" });
29523
29548
  const absoluteSettingsPath = resolve2(projectPath, "settings.json");
29524
29549
  const relativeSettingsFilePath = absoluteSettingsPath.replace(process.cwd(), ".");
29525
- logger.box(
29550
+ ctx.logger.box(
29526
29551
  dedent2`inlang Paraglide-JS has been set up sucessfully.
29527
29552
 
29528
29553
  1. Run your install command (npm i, yarn install, etc)
@@ -29534,28 +29559,31 @@ var initCommand = new Command2().name("init").summary("Initializes inlang Paragl
29534
29559
  `
29535
29560
  );
29536
29561
  });
29537
- var initializeInlangProject = async (logger) => {
29538
- const existingProjectPath = await findExistingInlangProjectPath();
29562
+ var initializeInlangProject = async (ctx) => {
29563
+ const existingProjectPath = await findExistingInlangProjectPath(ctx);
29539
29564
  if (existingProjectPath) {
29540
- await existingProjectFlow({ existingProjectPath }, logger);
29565
+ await existingProjectFlow({ existingProjectPath }, ctx);
29541
29566
  return existingProjectPath;
29542
29567
  } else {
29543
- await createNewProjectFlow(logger);
29568
+ await createNewProjectFlow(ctx);
29544
29569
  return DEFAULT_PROJECT_PATH;
29545
29570
  }
29546
29571
  };
29547
- var maybeAddVsCodeExtension = async (args, logger) => {
29548
- const response = await prompt(`Are you using VSCode?`, {
29549
- type: "confirm",
29550
- initial: true
29551
- });
29552
- if (response === false) {
29553
- return;
29572
+ var maybeAddVsCodeExtension = async (args, ctx) => {
29573
+ var _a;
29574
+ const isCertainlyVsCode = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.TERM_PROGRAM) === "vscode";
29575
+ let response = isCertainlyVsCode;
29576
+ if (!isCertainlyVsCode) {
29577
+ response = await prompt(`Are you using VSCode?`, {
29578
+ type: "confirm",
29579
+ initial: true
29580
+ });
29554
29581
  }
29582
+ if (response === false)
29583
+ return;
29555
29584
  const project = await loadProject({
29556
29585
  projectPath: resolve2(process.cwd(), args.projectPath),
29557
- //@ts-ignore
29558
- nodeishFs: fs3
29586
+ repo: ctx.repo
29559
29587
  });
29560
29588
  const settings = project.settings();
29561
29589
  if (settings.modules.some((m) => m.includes("plugin-m-function-matcher")) === false) {
@@ -29566,7 +29594,9 @@ var maybeAddVsCodeExtension = async (args, logger) => {
29566
29594
  }
29567
29595
  let extensions = {};
29568
29596
  try {
29569
- extensions = JSON5.parse(await fs3.readFile("./.vscode/extensions.json", { encoding: "utf-8" }));
29597
+ extensions = JSON5.parse(
29598
+ await ctx.repo.nodeishFs.readFile("./.vscode/extensions.json", { encoding: "utf-8" })
29599
+ );
29570
29600
  } catch {
29571
29601
  }
29572
29602
  if (extensions.recommendations === void 0) {
@@ -29574,34 +29604,45 @@ var maybeAddVsCodeExtension = async (args, logger) => {
29574
29604
  }
29575
29605
  if (extensions.recommendations.includes("inlang.vs-code-extension") === false) {
29576
29606
  extensions.recommendations.push("inlang.vs-code-extension");
29577
- if (fsSync.existsSync("./.vscode") === false) {
29578
- await fs3.mkdir("./.vscode");
29607
+ if (await fileExists("./.vscode", ctx.repo.nodeishFs) === false) {
29608
+ await ctx.repo.nodeishFs.mkdir("./.vscode");
29579
29609
  }
29580
- await fs3.writeFile("./.vscode/extensions.json", JSON.stringify(extensions, void 0, 2));
29581
- logger.success("Added the inlang vs code extension to the workspace recommendations.");
29610
+ await ctx.repo.nodeishFs.writeFile(
29611
+ "./.vscode/extensions.json",
29612
+ JSON.stringify(extensions, void 0, 2)
29613
+ );
29614
+ ctx.logger.success("Added the inlang vs code extension to the workspace recommendations.");
29582
29615
  }
29583
29616
  };
29584
- var addParaglideJsToDevDependencies = async (logger) => {
29585
- const file = await fs3.readFile("./package.json", { encoding: "utf-8" });
29617
+ var addParaglideJsToDevDependencies = async (ctx) => {
29618
+ const file = await ctx.repo.nodeishFs.readFile("./package.json", { encoding: "utf-8" });
29586
29619
  const stringify = detectJsonFormatting(file);
29587
- const pkg = JSON.parse(file);
29620
+ let pkg = {};
29621
+ try {
29622
+ pkg = JSON.parse(file);
29623
+ } catch {
29624
+ ctx.logger.error(
29625
+ `Your ./package.json does not contain valid JSON. Please fix it and try again.`
29626
+ );
29627
+ process.exit(1);
29628
+ }
29588
29629
  if (pkg.devDependencies === void 0) {
29589
29630
  pkg.devDependencies = {};
29590
29631
  }
29591
29632
  pkg.devDependencies["@inlang/paraglide-js"] = version;
29592
- await fs3.writeFile("./package.json", stringify(pkg));
29593
- logger.success("Added @inlang/paraglide-js to the devDependencies in package.json.");
29633
+ await ctx.repo.nodeishFs.writeFile("./package.json", stringify(pkg));
29634
+ ctx.logger.success("Added @inlang/paraglide-js to the devDependencies in package.json.");
29594
29635
  };
29595
- var findExistingInlangProjectPath = async () => {
29636
+ var findExistingInlangProjectPath = async (ctx) => {
29596
29637
  for (const path3 of ["./project.inlang", "../project.inlang", "../../project.inlang"]) {
29597
- if (fsSync.existsSync(path3)) {
29638
+ if (await fileExists(path3, ctx.repo.nodeishFs)) {
29598
29639
  return path3;
29599
29640
  }
29600
29641
  continue;
29601
29642
  }
29602
29643
  return void 0;
29603
29644
  };
29604
- var existingProjectFlow = async (args, logger) => {
29645
+ var existingProjectFlow = async (args, ctx) => {
29605
29646
  const selection = await prompt(
29606
29647
  `Do you want to use the inlang project at "${args.existingProjectPath}" or create a new project?`,
29607
29648
  {
@@ -29613,43 +29654,41 @@ var existingProjectFlow = async (args, logger) => {
29613
29654
  }
29614
29655
  );
29615
29656
  if (selection === "newProject") {
29616
- return createNewProjectFlow(logger);
29657
+ return createNewProjectFlow(ctx);
29617
29658
  }
29618
29659
  const project = await loadProject({
29619
29660
  projectPath: resolve2(process.cwd(), args.existingProjectPath),
29620
- //@ts-ignore
29621
- nodeishFs: fs3
29661
+ repo: ctx.repo
29622
29662
  });
29623
29663
  if (project.errors().length > 0) {
29624
- logger.error("The project contains errors: ");
29664
+ ctx.logger.error("The project contains errors: ");
29625
29665
  for (const error of project.errors()) {
29626
- logger.error(error);
29666
+ ctx.logger.error(error);
29627
29667
  }
29628
29668
  process.exit(1);
29629
29669
  }
29630
29670
  };
29631
- var createNewProjectFlow = async (logger) => {
29632
- logger.info(`Creating a new inlang project in the current working directory.`);
29633
- await fs3.mkdir(DEFAULT_PROJECT_PATH, { recursive: true });
29634
- await fs3.writeFile(
29671
+ var createNewProjectFlow = async (ctx) => {
29672
+ ctx.logger.info(`Creating a new inlang project in the current working directory.`);
29673
+ await ctx.repo.nodeishFs.mkdir(DEFAULT_PROJECT_PATH, { recursive: true });
29674
+ await ctx.repo.nodeishFs.writeFile(
29635
29675
  DEFAULT_PROJECT_PATH + "/settings.json",
29636
29676
  JSON.stringify(newProjectTemplate, void 0, 2)
29637
29677
  );
29638
29678
  const project = await loadProject({
29639
29679
  projectPath: resolve2(process.cwd(), DEFAULT_PROJECT_PATH),
29640
- //@ts-ignore
29641
- nodeishFs: fs3
29680
+ repo: ctx.repo
29642
29681
  });
29643
29682
  if (project.errors().length > 0) {
29644
- logger.warn(
29683
+ ctx.logger.warn(
29645
29684
  "Failed to create a new inlang project.\n\nThis is likely an internal bug. Please file an issue at https://github.com/opral/monorepo."
29646
29685
  );
29647
29686
  for (const error of project.errors()) {
29648
- logger.error(error);
29687
+ ctx.logger.error(error);
29649
29688
  }
29650
29689
  return process.exit(1);
29651
29690
  } else {
29652
- logger.success("Successfully created a new inlang project.");
29691
+ ctx.logger.success("Successfully created a new inlang project.");
29653
29692
  }
29654
29693
  };
29655
29694
  var newProjectTemplate = {
@@ -29676,20 +29715,21 @@ var newProjectTemplate = {
29676
29715
  pathPattern: "./messages/{languageTag}.json"
29677
29716
  }
29678
29717
  };
29679
- var checkIfPackageJsonExists = async (logger) => {
29680
- if (fsSync.existsSync("./package.json") === false) {
29681
- logger.warn(
29718
+ var checkIfPackageJsonExists = async (ctx) => {
29719
+ const exists = await fileExists("./package.json", ctx.repo.nodeishFs);
29720
+ if (exists === false) {
29721
+ ctx.logger.warn(
29682
29722
  "No package.json found in the current working directory. Please change the working directory to the directory with a package.json file."
29683
29723
  );
29684
29724
  return process.exit(0);
29685
29725
  }
29686
29726
  };
29687
- var checkIfUncommittedChanges = async (logger) => {
29727
+ var checkIfUncommittedChanges = async (ctx) => {
29688
29728
  try {
29689
- if (childProcess.execSync("git status --porcelain").toString().length === 0) {
29729
+ if ((await execAsync("git status --porcelain")).toString().length === 0) {
29690
29730
  return;
29691
29731
  }
29692
- logger.info(
29732
+ ctx.logger.info(
29693
29733
  `You have uncommitted changes.
29694
29734
 
29695
29735
  Please commit your changes before initializing inlang Paraglide-JS. Committing outstanding changes ensures that you don't lose any work, and see the changes the paraglide-js init command introduces.`
@@ -29710,9 +29750,9 @@ Please commit your changes before initializing inlang Paraglide-JS. Committing o
29710
29750
  return;
29711
29751
  }
29712
29752
  };
29713
- var addCompileStepToPackageJSON = async (args, logger) => {
29753
+ var addCompileStepToPackageJSON = async (args, ctx) => {
29714
29754
  var _a, _b;
29715
- const file = await fs3.readFile("./package.json", { encoding: "utf-8" });
29755
+ const file = await ctx.repo.nodeishFs.readFile("./package.json", { encoding: "utf-8" });
29716
29756
  const stringify = detectJsonFormatting(file);
29717
29757
  const pkg = JSON.parse(file);
29718
29758
  if (pkg.scripts === void 0) {
@@ -29728,7 +29768,7 @@ var addCompileStepToPackageJSON = async (args, logger) => {
29728
29768
  } else if (((_b = pkg == null ? void 0 : pkg.scripts) == null ? void 0 : _b.build.includes("paraglide-js compile")) === false) {
29729
29769
  pkg.scripts.build = `paraglide-js compile --project ${args.projectPath} && ${pkg.scripts.build}`;
29730
29770
  } else {
29731
- logger.warn(`The "build" script in the \`package.json\` already contains a "paraglide-js compile" command.
29771
+ ctx.logger.warn(`The "build" script in the \`package.json\` already contains a "paraglide-js compile" command.
29732
29772
 
29733
29773
  Please add the following command to your build script manually:
29734
29774
 
@@ -29741,30 +29781,32 @@ Please add the following command to your build script manually:
29741
29781
  }
29742
29782
  );
29743
29783
  if (response === false) {
29744
- logger.log("Please add the paraglide-js compile to your build script and try again.");
29784
+ ctx.logger.log("Please add the paraglide-js compile to your build script and try again.");
29745
29785
  return process.exit(0);
29746
29786
  } else {
29747
29787
  return;
29748
29788
  }
29749
29789
  }
29750
- await fs3.writeFile("./package.json", stringify(pkg));
29751
- logger.success("Successfully added the compile command to the build step in package.json.");
29790
+ await ctx.repo.nodeishFs.writeFile("./package.json", stringify(pkg));
29791
+ ctx.logger.success("Successfully added the compile command to the build step in package.json.");
29752
29792
  };
29753
- var maybeChangeTsConfigModuleResolution = async (logger) => {
29793
+ var maybeChangeTsConfigModuleResolution = async (ctx) => {
29754
29794
  var _a, _b, _c;
29755
- if (fsSync.existsSync("./tsconfig.json") === false) {
29795
+ if (await fileExists("./tsconfig.json", ctx.repo.nodeishFs) === false) {
29756
29796
  return;
29757
29797
  }
29758
- const file = await fs3.readFile("./tsconfig.json", { encoding: "utf-8" });
29798
+ const file = await ctx.repo.nodeishFs.readFile("./tsconfig.json", { encoding: "utf-8" });
29759
29799
  const tsconfig = JSON5.parse(file);
29760
29800
  let parentTsConfig;
29761
29801
  if (tsconfig.extends) {
29762
29802
  try {
29763
29803
  const parentTsConfigPath = resolve2(process.cwd(), tsconfig.extends);
29764
- const parentTsConfigFile = await fs3.readFile(parentTsConfigPath, { encoding: "utf-8" });
29804
+ const parentTsConfigFile = await ctx.repo.nodeishFs.readFile(parentTsConfigPath, {
29805
+ encoding: "utf-8"
29806
+ });
29765
29807
  parentTsConfig = JSON5.parse(parentTsConfigFile);
29766
29808
  } catch {
29767
- logger.warn(
29809
+ ctx.logger.warn(
29768
29810
  `The tsconfig.json is extended from a tsconfig that couldn't be read. Maybe the file doesn't exist yet or is a NPM package. Continuing without taking the extended from tsconfig into consideration.`
29769
29811
  );
29770
29812
  }
@@ -29774,7 +29816,7 @@ var maybeChangeTsConfigModuleResolution = async (logger) => {
29774
29816
  if (moduleResolution && invalidOptions.includes(moduleResolution.toLowerCase()) === false) {
29775
29817
  return;
29776
29818
  }
29777
- logger.info(
29819
+ ctx.logger.info(
29778
29820
  `You need to set the \`compilerOptions.moduleResolution\` to "Bundler" in the \`tsconfig.json\` file:
29779
29821
 
29780
29822
  \`{
@@ -29793,32 +29835,34 @@ var maybeChangeTsConfigModuleResolution = async (logger) => {
29793
29835
  }
29794
29836
  );
29795
29837
  if (response === false) {
29796
- logger.warn("Continuing without adjusting the tsconfig.json. This may lead to type errors.");
29838
+ ctx.logger.warn(
29839
+ "Continuing without adjusting the tsconfig.json. This may lead to type errors."
29840
+ );
29797
29841
  return;
29798
29842
  }
29799
- const file2 = await fs3.readFile("./tsconfig.json", { encoding: "utf-8" });
29843
+ const file2 = await ctx.repo.nodeishFs.readFile("./tsconfig.json", { encoding: "utf-8" });
29800
29844
  const tsconfig2 = JSON5.parse(file2);
29801
29845
  if (((_c = tsconfig2 == null ? void 0 : tsconfig2.compilerOptions) == null ? void 0 : _c.moduleResolution) && tsconfig2.compilerOptions.moduleResolution.toLowerCase() === "bundler") {
29802
29846
  isValid2 = true;
29803
29847
  return;
29804
29848
  } else {
29805
- logger.error(
29849
+ ctx.logger.error(
29806
29850
  "The compiler options have not been adjusted. Please set the `compilerOptions.moduleResolution` to `Bundler`."
29807
29851
  );
29808
29852
  }
29809
29853
  }
29810
29854
  };
29811
- var maybeChangeTsConfigAllowJs = async (logger) => {
29855
+ var maybeChangeTsConfigAllowJs = async (ctx) => {
29812
29856
  var _a, _b;
29813
- if (fsSync.existsSync("./tsconfig.json") === false) {
29857
+ if (await fileExists("./tsconfig.json", ctx.repo.nodeishFs) === false) {
29814
29858
  return;
29815
29859
  }
29816
- const file = await fs3.readFile("./tsconfig.json", { encoding: "utf-8" });
29860
+ const file = await ctx.repo.nodeishFs.readFile("./tsconfig.json", { encoding: "utf-8" });
29817
29861
  const tsconfig = JSON5.parse(file);
29818
29862
  if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.allowJs) === true) {
29819
29863
  return;
29820
29864
  }
29821
- logger.info(
29865
+ ctx.logger.info(
29822
29866
  `You need to set the \`compilerOptions.allowJs\` to \`true\` in the \`tsconfig.json\` file:
29823
29867
 
29824
29868
  \`{
@@ -29834,16 +29878,18 @@ var maybeChangeTsConfigAllowJs = async (logger) => {
29834
29878
  initial: true
29835
29879
  });
29836
29880
  if (response === false) {
29837
- logger.warn("Continuing without adjusting the tsconfig.json. This may lead to type errors.");
29881
+ ctx.logger.warn(
29882
+ "Continuing without adjusting the tsconfig.json. This may lead to type errors."
29883
+ );
29838
29884
  return;
29839
29885
  }
29840
- const file2 = await fs3.readFile("./tsconfig.json", { encoding: "utf-8" });
29886
+ const file2 = await ctx.repo.nodeishFs.readFile("./tsconfig.json", { encoding: "utf-8" });
29841
29887
  const tsconfig2 = JSON5.parse(file2);
29842
29888
  if (((_b = tsconfig2 == null ? void 0 : tsconfig2.compilerOptions) == null ? void 0 : _b.allowJs) === true) {
29843
29889
  isValid2 = true;
29844
29890
  return;
29845
29891
  } else {
29846
- logger.error(
29892
+ ctx.logger.error(
29847
29893
  "The compiler options have not been adjusted. Please set the `compilerOptions.allowJs` to `true`."
29848
29894
  );
29849
29895
  }
@@ -29856,6 +29902,29 @@ var prompt = async (message, options) => {
29856
29902
  }
29857
29903
  return response;
29858
29904
  };
29905
+ async function fileExists(filePath, nodeishFs) {
29906
+ try {
29907
+ await nodeishFs.stat(filePath);
29908
+ return true;
29909
+ } catch (error) {
29910
+ if (error.code === "ENOENT") {
29911
+ return false;
29912
+ } else {
29913
+ throw new Error(`Failed to check if file exists: ${error}`, { cause: error });
29914
+ }
29915
+ }
29916
+ }
29917
+ function execAsync(command) {
29918
+ return new Promise((resolve3, reject) => {
29919
+ childProcess.exec(command, (error, stdout) => {
29920
+ if (error) {
29921
+ reject(error);
29922
+ } else {
29923
+ resolve3(stdout);
29924
+ }
29925
+ });
29926
+ });
29927
+ }
29859
29928
 
29860
29929
  // src/cli/main.ts
29861
29930
  var cli = new Command3().name("paraglide-js").addCommand(compileCommand).addCommand(initCommand).showHelpAfterError().version(version);
@@ -1,3 +1,2 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type nodeFsPromises from "node:fs/promises";
3
- export declare function writeOutput(outputDirectory: string, output: Record<string, string>, fs: typeof nodeFsPromises): Promise<void>;
1
+ import type { NodeishFilesystem } from "@lix-js/fs";
2
+ export declare function writeOutput(outputDirectory: string, output: Record<string, string>, fs: NodeishFilesystem): Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@inlang/paraglide-js",
3
3
  "type": "module",
4
- "version": "1.2.0",
4
+ "version": "1.2.1",
5
5
  "license": "Apache-2.0",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -37,14 +37,15 @@
37
37
  "isomorphic-git": "1.24.5",
38
38
  "json5": "2.2.3",
39
39
  "posthog-node": "3.1.3",
40
- "@inlang/language-tag": "1.3.0",
41
- "@inlang/detect-json-formatting": "1.0.0"
40
+ "@inlang/detect-json-formatting": "1.0.0",
41
+ "@inlang/language-tag": "1.4.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@rollup/plugin-terser": "0.4.3",
45
45
  "@rollup/plugin-virtual": "3.0.1",
46
46
  "@ts-morph/bootstrap": "0.20.0",
47
47
  "@types/minimist": "1.2.3",
48
+ "@types/node": "^20.11.2",
48
49
  "@vitest/coverage-v8": "0.34.3",
49
50
  "cross-env": "^7.0.3",
50
51
  "esbuild": "^0.19.7",
@@ -52,11 +53,12 @@
52
53
  "rollup": "3.29.1",
53
54
  "typescript": "5.2.2",
54
55
  "vitest": "0.34.3",
55
- "@lix-js/client": "0.5.0",
56
56
  "@inlang/env-variables": "0.2.0",
57
- "@inlang/telemetry": "0.3.3",
58
- "@inlang/sdk": "0.22.0",
59
- "@lix-js/fs": "0.5.0"
57
+ "@inlang/sdk": "0.23.0",
58
+ "@inlang/telemetry": "0.3.4",
59
+ "@lix-js/client": "0.5.0",
60
+ "@lix-js/fs": "0.5.0",
61
+ "@inlang/plugin-message-format": "2.0.0"
60
62
  },
61
63
  "exports": {
62
64
  "./internal": {