wrangler 0.0.0-e9ab55a → 0.0.0-ed4f2ef

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.
Files changed (102) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +33 -16
  6. package/pages/functions/buildWorker.ts +1 -1
  7. package/pages/functions/filepath-routing.test.ts +212 -28
  8. package/pages/functions/filepath-routing.ts +83 -130
  9. package/pages/functions/routes.ts +11 -18
  10. package/pages/functions/template-worker.ts +3 -9
  11. package/src/__tests__/configuration.test.ts +2874 -0
  12. package/src/__tests__/dev.test.tsx +582 -61
  13. package/src/__tests__/guess-worker-format.test.ts +83 -0
  14. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  15. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  16. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  17. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  18. package/src/__tests__/helpers/mock-bin.ts +36 -0
  19. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +52 -16
  20. package/src/__tests__/helpers/mock-console.ts +70 -0
  21. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +127 -0
  30. package/src/__tests__/index.test.ts +777 -77
  31. package/src/__tests__/jest.setup.ts +58 -6
  32. package/src/__tests__/kv.test.ts +716 -462
  33. package/src/__tests__/package-manager.test.ts +206 -0
  34. package/src/__tests__/pages.test.ts +180 -0
  35. package/src/__tests__/parse.test.ts +322 -0
  36. package/src/__tests__/publish.test.ts +3915 -71
  37. package/src/__tests__/r2.test.ts +198 -0
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +425 -0
  40. package/src/__tests__/sentry.test.ts +146 -0
  41. package/src/__tests__/tail.test.ts +638 -0
  42. package/src/__tests__/user.test.ts +83 -0
  43. package/src/__tests__/whoami.test.tsx +95 -0
  44. package/src/bundle.ts +155 -0
  45. package/src/cfetch/index.ts +21 -19
  46. package/src/cfetch/internal.ts +92 -22
  47. package/src/cli.ts +14 -2
  48. package/src/config/README.md +107 -0
  49. package/src/config/config.ts +229 -0
  50. package/src/config/diagnostics.ts +80 -0
  51. package/src/config/environment.ts +371 -0
  52. package/src/config/index.ts +62 -0
  53. package/src/config/validation-helpers.ts +557 -0
  54. package/src/config/validation.ts +1240 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +69 -24
  56. package/src/create-worker-upload-form.ts +240 -0
  57. package/src/dev/dev.tsx +413 -0
  58. package/src/dev/local.tsx +287 -0
  59. package/src/dev/remote.tsx +209 -0
  60. package/src/dev/use-esbuild.ts +109 -0
  61. package/src/dialogs.tsx +2 -2
  62. package/src/entry.ts +256 -0
  63. package/src/environment-variables.ts +33 -0
  64. package/src/errors.ts +11 -0
  65. package/src/https-options.ts +122 -0
  66. package/src/index.tsx +1310 -849
  67. package/src/inspect.ts +102 -21
  68. package/src/intl-polyfill.d.ts +139 -0
  69. package/src/{kv.tsx → kv.ts} +104 -61
  70. package/src/miniflare-cli/README.md +30 -0
  71. package/src/miniflare-cli/enum-keys.ts +17 -0
  72. package/src/miniflare-cli/index.ts +38 -0
  73. package/src/module-collection.ts +228 -35
  74. package/src/open-in-browser.ts +25 -0
  75. package/src/package-manager.ts +126 -0
  76. package/src/pages.tsx +214 -48
  77. package/src/parse.ts +183 -0
  78. package/src/paths.ts +26 -0
  79. package/src/proxy.ts +192 -39
  80. package/src/publish.ts +321 -318
  81. package/src/r2.ts +50 -0
  82. package/src/reporting.ts +131 -0
  83. package/src/selfsigned.d.ts +29 -0
  84. package/src/sites.tsx +224 -62
  85. package/src/tail/filters.ts +279 -0
  86. package/src/tail/index.ts +299 -0
  87. package/src/tail/printing.ts +62 -0
  88. package/src/user.tsx +317 -178
  89. package/src/whoami.tsx +69 -0
  90. package/src/{api/worker.ts → worker.ts} +54 -37
  91. package/templates/new-worker.js +15 -0
  92. package/templates/new-worker.ts +15 -0
  93. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  94. package/templates/tsconfig.json +105 -0
  95. package/wrangler-dist/cli.js +131262 -112648
  96. package/wrangler-dist/cli.js.map +3 -3
  97. package/src/__tests__/run-in-tmp.ts +0 -19
  98. package/src/__tests__/run-wrangler.ts +0 -32
  99. package/src/api/form_data.ts +0 -131
  100. package/src/config.ts +0 -646
  101. package/src/dev.tsx +0 -784
  102. package/src/tail.tsx +0 -73
package/src/pages.tsx CHANGED
@@ -1,36 +1,82 @@
1
1
  /* eslint-disable no-shadow */
2
2
 
3
- import type { BuilderCallback } from "yargs";
4
- import { join } from "path";
5
- import { tmpdir } from "os";
6
- import { existsSync, lstatSync, readFileSync, writeFileSync } from "fs";
7
- import { execSync, spawn } from "child_process";
8
- import { URL } from "url";
9
- import { getType } from "mime";
10
- import open from "open";
3
+ import { execSync, spawn } from "node:child_process";
4
+ import { existsSync, lstatSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { URL } from "node:url";
11
8
  import { watch } from "chokidar";
12
- import type { BuildResult } from "esbuild";
9
+ import { render } from "ink";
10
+ import Table from "ink-table";
11
+ import { getType } from "mime";
12
+ import React from "react";
13
+ import { format } from "timeago.js";
13
14
  import { buildWorker } from "../pages/functions/buildWorker";
14
- import type { Config } from "../pages/functions/routes";
15
- import { writeRoutesModule } from "../pages/functions/routes";
16
15
  import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
16
+ import { writeRoutesModule } from "../pages/functions/routes";
17
+ import { fetchResult } from "./cfetch";
18
+ import { readConfig } from "./config";
19
+ import { FatalError } from "./errors";
20
+ import openInBrowser from "./open-in-browser";
21
+ import { toUrlPath } from "./paths";
22
+ import { requireAuth } from "./user";
23
+ import type { Config } from "../pages/functions/routes";
24
+ import type { Headers, Request, fetch } from "@miniflare/core";
25
+ import type { BuildResult } from "esbuild";
26
+ import type { MiniflareOptions } from "miniflare";
27
+ import type { BuilderCallback } from "yargs";
28
+
29
+ type ConfigPath = string | undefined;
30
+
31
+ export type Project = {
32
+ name: string;
33
+ domains: Array<string>;
34
+ source?: {
35
+ type: string;
36
+ };
37
+ latest_deployment: {
38
+ modified_on: string;
39
+ };
40
+ };
41
+
42
+ export type Deployment = {
43
+ id: string;
44
+ environment: string;
45
+ deployment_trigger: {
46
+ metadata: {
47
+ commit_hash: string;
48
+ branch: string;
49
+ };
50
+ };
51
+ url: string;
52
+ latest_stage: {
53
+ status: string;
54
+ ended_on: string;
55
+ };
56
+ project_name: string;
57
+ };
17
58
 
18
59
  // Defer importing miniflare until we really need it. This takes ~0.5s
19
60
  // and also modifies some `stream/web` and `undici` prototypes, so we
20
61
  // don't want to do this if pages commands aren't being called.
21
- import type { Headers, Request, fetch } from "@miniflare/core";
22
- import type { MiniflareOptions } from "miniflare";
23
62
 
24
- const EXIT_CALLBACKS: (() => void)[] = [];
25
- const EXIT = (message?: string, code?: number) => {
26
- if (message) console.log(message);
27
- if (code) process.exitCode = code;
28
- EXIT_CALLBACKS.forEach((callback) => callback());
29
- process.exit(code);
63
+ export const pagesBetaWarning =
64
+ "🚧 'wrangler pages <command>' is a beta command. Please report any issues to https://github.com/cloudflare/wrangler2/issues/new/choose";
65
+
66
+ const CLEANUP_CALLBACKS: (() => void)[] = [];
67
+ const CLEANUP = () => {
68
+ CLEANUP_CALLBACKS.forEach((callback) => callback());
69
+ RUNNING_BUILDERS.forEach((builder) => builder.stop?.());
30
70
  };
31
71
 
32
- process.on("SIGINT", () => EXIT());
33
- process.on("SIGTERM", () => EXIT());
72
+ process.on("SIGINT", () => {
73
+ CLEANUP();
74
+ process.exit();
75
+ });
76
+ process.on("SIGTERM", () => {
77
+ CLEANUP();
78
+ process.exit();
79
+ });
34
80
 
35
81
  function isWindows() {
36
82
  return process.platform === "win32";
@@ -103,11 +149,13 @@ async function spawnProxyProcess({
103
149
  port?: number;
104
150
  command: (string | number)[];
105
151
  }): Promise<void | number> {
106
- if (command.length === 0)
107
- return EXIT(
152
+ if (command.length === 0) {
153
+ CLEANUP();
154
+ throw new FatalError(
108
155
  "Must specify a directory of static assets to serve or a command to run.",
109
156
  1
110
157
  );
158
+ }
111
159
 
112
160
  console.log(`Running ${command.join(" ")}...`);
113
161
  const proxy = spawn(
@@ -121,7 +169,7 @@ async function spawnProxyProcess({
121
169
  },
122
170
  }
123
171
  );
124
- EXIT_CALLBACKS.push(() => {
172
+ CLEANUP_CALLBACKS.push(() => {
125
173
  proxy.kill();
126
174
  });
127
175
 
@@ -152,7 +200,8 @@ async function spawnProxyProcess({
152
200
  .filter((port) => port !== undefined)[0];
153
201
 
154
202
  if (port === undefined) {
155
- return EXIT(
203
+ CLEANUP();
204
+ throw new FatalError(
156
205
  "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
157
206
  1
158
207
  );
@@ -665,16 +714,17 @@ async function buildFunctions({
665
714
  );
666
715
 
667
716
  const routesModule = join(tmpdir(), "./functionsRoutes.mjs");
717
+ const baseURL = toUrlPath("/");
668
718
 
669
719
  const config: Config = await generateConfigFromFileTree({
670
720
  baseDir: functionsDirectory,
671
- baseURL: "/",
721
+ baseURL,
672
722
  });
673
723
 
674
724
  if (outputConfigPath) {
675
725
  writeFileSync(
676
726
  outputConfigPath,
677
- JSON.stringify({ ...config, baseURL: "/" }, null, 2)
727
+ JSON.stringify({ ...config, baseURL }, null, 2)
678
728
  );
679
729
  }
680
730
 
@@ -757,7 +807,8 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
757
807
  description: "Auto reload HTML pages when change is detected",
758
808
  },
759
809
  // TODO: Miniflare user options
760
- });
810
+ })
811
+ .epilogue(pagesBetaWarning);
761
812
  },
762
813
  async ({
763
814
  local,
@@ -769,8 +820,11 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
769
820
  kv: kvs = [],
770
821
  do: durableObjects = [],
771
822
  "live-reload": liveReload,
772
- "--": remaining = [],
823
+ _: [_pages, _dev, ...remaining],
773
824
  }) => {
825
+ // Beta message for `wrangler pages <commands>` usage
826
+ console.log(pagesBetaWarning);
827
+
774
828
  if (!local) {
775
829
  console.error("Only local mode is supported at the moment.");
776
830
  return;
@@ -793,8 +847,8 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
793
847
 
794
848
  let miniflareArgs: MiniflareOptions = {};
795
849
 
796
- let scriptReadyResolve;
797
- const scriptReadyPromise = new Promise(
850
+ let scriptReadyResolve: () => void;
851
+ const scriptReadyPromise = new Promise<void>(
798
852
  (resolve) => (scriptReadyResolve = resolve)
799
853
  );
800
854
 
@@ -803,13 +857,15 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
803
857
 
804
858
  console.log(`Compiling worker to "${scriptPath}"...`);
805
859
 
806
- await buildFunctions({
807
- scriptPath,
808
- functionsDirectory,
809
- sourcemap: true,
810
- watch: true,
811
- onEnd: () => scriptReadyResolve(),
812
- });
860
+ try {
861
+ await buildFunctions({
862
+ scriptPath,
863
+ functionsDirectory,
864
+ sourcemap: true,
865
+ watch: true,
866
+ onEnd: () => scriptReadyResolve(),
867
+ });
868
+ } catch {}
813
869
 
814
870
  watch([functionsDirectory], {
815
871
  persistent: true,
@@ -828,6 +884,9 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
828
884
  scriptPath,
829
885
  };
830
886
  } else {
887
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
888
+ scriptReadyResolve!();
889
+
831
890
  const scriptPath =
832
891
  directory !== undefined
833
892
  ? join(directory, singleWorkerScriptPath)
@@ -890,13 +949,15 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
890
949
  // User bindings
891
950
  bindings: {
892
951
  ...Object.fromEntries(
893
- bindings.map((binding) => binding.toString().split("="))
952
+ bindings
953
+ .map((binding) => binding.toString().split("="))
954
+ .map(([key, ...values]) => [key, values.join("=")])
894
955
  ),
895
956
  },
896
957
 
897
958
  // env.ASSETS.fetch
898
959
  serviceBindings: {
899
- async ASSETS(request) {
960
+ async ASSETS(request: Request) {
900
961
  if (proxyPort) {
901
962
  try {
902
963
  const url = new URL(request.url);
@@ -941,9 +1002,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
941
1002
  console.log(`Serving at http://localhost:${port}/`);
942
1003
 
943
1004
  if (process.env.BROWSER !== "none") {
944
- const childProcess = await open(`http://localhost:${port}/`);
945
- // fail silently if the open command doesn't work (e.g. in GitHub Codespaces)
946
- childProcess.on("error", (_err) => {});
1005
+ await openInBrowser(`http://localhost:${port}/`);
947
1006
  }
948
1007
 
949
1008
  if (directory !== undefined && liveReload) {
@@ -955,17 +1014,20 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
955
1014
  });
956
1015
  }
957
1016
 
958
- EXIT_CALLBACKS.push(() => {
1017
+ CLEANUP_CALLBACKS.push(() => {
959
1018
  server.close();
960
1019
  miniflare.dispose().catch((err) => miniflare.log.error(err));
961
1020
  });
962
1021
  } catch (e) {
963
- miniflare.log.error(e);
964
- EXIT("Could not start Miniflare.", 1);
1022
+ miniflare.log.error(e as Error);
1023
+ CLEANUP();
1024
+ throw new FatalError("Could not start Miniflare.", 1);
965
1025
  }
966
1026
  }
967
1027
  )
968
- .command("functions", "Cloudflare Pages Functions", (yargs) =>
1028
+ .command("functions", false, (yargs) =>
1029
+ // we hide this command from help output because
1030
+ // it's not meant to be used directly right now
969
1031
  yargs.command(
970
1032
  "build [directory]",
971
1033
  "Compile a folder of Cloudflare Pages Functions into a single Worker",
@@ -1009,7 +1071,8 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1009
1071
  description:
1010
1072
  "Watch for changes to the functions and automatically rebuild the Worker script",
1011
1073
  },
1012
- }),
1074
+ })
1075
+ .epilogue(pagesBetaWarning),
1013
1076
  async ({
1014
1077
  directory,
1015
1078
  "script-path": scriptPath,
@@ -1019,6 +1082,9 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1019
1082
  fallbackService,
1020
1083
  watch,
1021
1084
  }) => {
1085
+ // Beta message for `wrangler pages <commands>` usage
1086
+ console.log(pagesBetaWarning);
1087
+
1022
1088
  await buildFunctions({
1023
1089
  scriptPath,
1024
1090
  outputConfigPath,
@@ -1030,6 +1096,80 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
1030
1096
  });
1031
1097
  }
1032
1098
  )
1099
+ )
1100
+ .command("project", false, (yargs) =>
1101
+ yargs.command(
1102
+ "list",
1103
+ "List your Cloudflare Pages projects",
1104
+ () => {},
1105
+ async (args) => {
1106
+ const config = readConfig(args.config as ConfigPath, args);
1107
+ const accountId = await requireAuth(config);
1108
+
1109
+ const projects: Array<Project> = await listProjects({ accountId });
1110
+
1111
+ const data = projects.map((project) => {
1112
+ return {
1113
+ "Project Name": project.name,
1114
+ "Project Domains": `${project.domains.join(", ")}`,
1115
+ "Git Provider": project.source ? "Yes" : "No",
1116
+ "Last Modified": format(project.latest_deployment.modified_on),
1117
+ };
1118
+ });
1119
+ render(<Table data={data}></Table>);
1120
+ }
1121
+ )
1122
+ )
1123
+ .command("deployment", false, (yargs) =>
1124
+ yargs.command(
1125
+ "list",
1126
+ "List deployments in your Cloudflare Pages project",
1127
+ (yargs) =>
1128
+ yargs.options({
1129
+ project: {
1130
+ type: "string",
1131
+ demandOption: true,
1132
+ description:
1133
+ "The name of the project you would like to list deployments for",
1134
+ },
1135
+ }),
1136
+ async (args) => {
1137
+ const config = readConfig(args.config as ConfigPath, args);
1138
+ const accountId = await requireAuth(config);
1139
+
1140
+ const deployments: Array<Deployment> = await fetchResult(
1141
+ `/accounts/${accountId}/pages/projects/${args.project}/deployments`
1142
+ );
1143
+
1144
+ const titleCase = (word: string) =>
1145
+ word.charAt(0).toUpperCase() + word.slice(1);
1146
+
1147
+ const shortSha = (sha: string) => sha.slice(0, 7);
1148
+
1149
+ const getStatus = (deployment: Deployment) => {
1150
+ // Return a pretty time since timestamp if successful otherwise the status
1151
+ if (deployment.latest_stage.status === `success`) {
1152
+ return format(deployment.latest_stage.ended_on);
1153
+ }
1154
+ return titleCase(deployment.latest_stage.status);
1155
+ };
1156
+
1157
+ const data = deployments.map((deployment) => {
1158
+ return {
1159
+ Environment: titleCase(deployment.environment),
1160
+ Branch: deployment.deployment_trigger.metadata.branch,
1161
+ Source: shortSha(
1162
+ deployment.deployment_trigger.metadata.commit_hash
1163
+ ),
1164
+ Deployment: deployment.url,
1165
+ Status: getStatus(deployment),
1166
+ // TODO: Use a url shortener
1167
+ Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
1168
+ };
1169
+ });
1170
+ render(<Table data={data}></Table>);
1171
+ }
1172
+ )
1033
1173
  );
1034
1174
  };
1035
1175
 
@@ -1038,3 +1178,29 @@ const invalidAssetsFetch: typeof fetch = () => {
1038
1178
  "Trying to fetch assets directly when there is no `directory` option specified, and not in `local` mode."
1039
1179
  );
1040
1180
  };
1181
+
1182
+ const listProjects = async ({
1183
+ accountId,
1184
+ }: {
1185
+ accountId: string;
1186
+ }): Promise<Array<Project>> => {
1187
+ const pageSize = 10;
1188
+ let page = 1;
1189
+ const results = [];
1190
+ while (results.length % pageSize === 0) {
1191
+ const json: Array<Project> = await fetchResult(
1192
+ `/accounts/${accountId}/pages/projects`,
1193
+ {},
1194
+ new URLSearchParams({
1195
+ per_page: pageSize.toString(),
1196
+ page: page.toString(),
1197
+ })
1198
+ );
1199
+ page++;
1200
+ results.push(...json);
1201
+ if (json.length < pageSize) {
1202
+ break;
1203
+ }
1204
+ }
1205
+ return results;
1206
+ };
package/src/parse.ts ADDED
@@ -0,0 +1,183 @@
1
+ import * as fs from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import TOML from "@iarna/toml";
4
+ import { formatMessagesSync } from "esbuild";
5
+
6
+ export type Message = {
7
+ text: string;
8
+ location?: Location;
9
+ notes?: Message[];
10
+ kind?: "warning" | "error";
11
+ };
12
+
13
+ export type Location = File & {
14
+ line: number;
15
+ column: number;
16
+ length?: number;
17
+ lineText?: string;
18
+ suggestion?: string;
19
+ };
20
+
21
+ export type File = {
22
+ file?: string;
23
+ fileText?: string;
24
+ };
25
+
26
+ /**
27
+ * Formats a `Message` using esbuild's pretty-printing algorithm.
28
+ */
29
+ export function formatMessage(
30
+ { text, notes, location, kind = "error" }: Message,
31
+ color = true
32
+ ): string {
33
+ const input = { text, notes, location };
34
+ delete input.location?.fileText;
35
+ for (const note of notes ?? []) {
36
+ delete note.location?.fileText;
37
+ }
38
+ const lines = formatMessagesSync([input], {
39
+ color,
40
+ kind: kind,
41
+ terminalWidth: process.stderr.columns,
42
+ });
43
+ return lines.join("\n");
44
+ }
45
+
46
+ /**
47
+ * An error that's thrown when something fails to parse.
48
+ */
49
+ export class ParseError extends Error implements Message {
50
+ readonly text: string;
51
+ readonly notes: Message[];
52
+ readonly location?: Location;
53
+ readonly kind: "warning" | "error";
54
+
55
+ constructor({ text, notes, location, kind }: Message) {
56
+ super(text);
57
+ this.name = this.constructor.name;
58
+ this.text = text;
59
+ this.notes = notes ?? [];
60
+ this.location = location;
61
+ this.kind = kind ?? "error";
62
+ }
63
+ }
64
+
65
+ /* eslint-disable @typescript-eslint/no-explicit-any */
66
+
67
+ const TOML_ERROR_NAME = "TomlError";
68
+ const TOML_ERROR_SUFFIX = " at row ";
69
+
70
+ type TomlError = Error & {
71
+ line: number;
72
+ col: number;
73
+ };
74
+
75
+ /**
76
+ * A wrapper around `TOML.parse` that throws a `ParseError`.
77
+ */
78
+ export function parseTOML(input: string, file?: string): object {
79
+ try {
80
+ return TOML.parse(input);
81
+ } catch (err) {
82
+ const { name, message, line, col } = err as TomlError;
83
+ if (name !== TOML_ERROR_NAME) {
84
+ throw err;
85
+ }
86
+ const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
87
+ const lineText = input.split("\n")[line];
88
+ const location = {
89
+ lineText,
90
+ line: line + 1,
91
+ column: col - 1,
92
+ file,
93
+ fileText: input,
94
+ };
95
+ throw new ParseError({ text, location });
96
+ }
97
+ }
98
+
99
+ const JSON_ERROR_SUFFIX = " in JSON at position ";
100
+
101
+ /**
102
+ * A wrapper around `JSON.parse` that throws a `ParseError`.
103
+ */
104
+ export function parseJSON(input: string, file?: string): any {
105
+ try {
106
+ return JSON.parse(input);
107
+ } catch (err) {
108
+ const { message } = err as Error;
109
+ const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
110
+ if (index < 0) {
111
+ throw err;
112
+ }
113
+ const text = message.substring(0, index);
114
+ const position = parseInt(
115
+ message.substring(index + JSON_ERROR_SUFFIX.length)
116
+ );
117
+ const location = indexLocation({ file, fileText: input }, position);
118
+ throw new ParseError({ text, location });
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Reads a file and parses it based on its type.
124
+ */
125
+ export function readFileSync(file: string): string {
126
+ try {
127
+ return fs.readFileSync(file, { encoding: "utf-8" });
128
+ } catch (err) {
129
+ const { message } = err as Error;
130
+ throw new ParseError({
131
+ text: `Could not read file: ${file}`,
132
+ notes: [
133
+ {
134
+ text: message.replace(file, resolve(file)),
135
+ },
136
+ ],
137
+ });
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Calculates the line and column location from an index.
143
+ */
144
+ export function indexLocation(file: File, index: number): Location {
145
+ let lineText,
146
+ line = 0,
147
+ column = 0,
148
+ cursor = 0;
149
+ const { fileText = "" } = file;
150
+ for (const row of fileText.split("\n")) {
151
+ line++;
152
+ cursor += row.length + 1;
153
+ if (cursor >= index) {
154
+ lineText = row;
155
+ column = row.length - (cursor - index);
156
+ break;
157
+ }
158
+ }
159
+ return { lineText, line, column, ...file };
160
+ }
161
+
162
+ /**
163
+ * Guesses the line and column location of a search query.
164
+ */
165
+ export function searchLocation(file: File, query: unknown): Location {
166
+ let lineText,
167
+ length,
168
+ line = 0,
169
+ column = 0;
170
+ const queryText = String(query);
171
+ const { fileText = "" } = file;
172
+ for (const content of fileText.split("\n")) {
173
+ line++;
174
+ const index = content.indexOf(queryText);
175
+ if (index >= 0) {
176
+ lineText = content;
177
+ column = index;
178
+ length = queryText.length;
179
+ break;
180
+ }
181
+ }
182
+ return { lineText, line, column, length, ...file };
183
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { assert } from "console";
2
+
3
+ type DiscriminatedPath<Discriminator extends string> = string & {
4
+ _discriminator: Discriminator;
5
+ };
6
+
7
+ /**
8
+ * A branded string that expects to be URL compatible.
9
+ *
10
+ * Require this type when you want callers to ensure that they have converted file-path strings into URL-safe paths.
11
+ */
12
+ export type UrlPath = DiscriminatedPath<"UrlPath">;
13
+
14
+ /**
15
+ * Convert a file-path string to a URL-path string.
16
+ *
17
+ * Use this helper to convert a `string` to a `UrlPath` when it is not clear whether the string needs normalizing.
18
+ * Replaces all back-slashes with forward-slashes, and throws an error if the path contains a drive letter (e.g. `C:`).
19
+ */
20
+ export function toUrlPath(path: string): UrlPath {
21
+ assert(
22
+ !/^[a-z]:/i.test(path),
23
+ "Tried to convert a Windows file path with a drive to a URL path."
24
+ );
25
+ return path.replace(/\\/g, "/") as UrlPath;
26
+ }