elm-pages 3.0.0-beta.12 → 3.0.0-beta.14

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 (77) hide show
  1. package/README.md +1 -1
  2. package/codegen/elm-pages-codegen.js +1496 -1126
  3. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/Pages-Review-DeadCodeEliminateData.elmi +0 -0
  4. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/Pages-Review-DeadCodeEliminateData.elmo +0 -0
  5. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/Pages-Review-DeadCodeEliminateDataTest.elmo +0 -0
  6. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/d.dat +0 -0
  7. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/i.dat +0 -0
  8. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/o.dat +0 -0
  9. package/generator/dead-code-review/elm-stuff/tests-0.19.1/elm.json +1 -1
  10. package/generator/dead-code-review/elm-stuff/tests-0.19.1/js/Runner.elm.js +151 -39
  11. package/generator/dead-code-review/elm-stuff/tests-0.19.1/js/node_runner.js +1 -1
  12. package/generator/dead-code-review/elm-stuff/tests-0.19.1/js/node_supervisor.js +1 -1
  13. package/generator/dead-code-review/elm.json +3 -2
  14. package/generator/dead-code-review/src/Pages/Review/DeadCodeEliminateData.elm +58 -10
  15. package/generator/dead-code-review/tests/Pages/Review/DeadCodeEliminateDataTest.elm +45 -29
  16. package/generator/review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/d.dat +0 -0
  17. package/generator/review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/i.dat +0 -0
  18. package/generator/review/elm-stuff/tests-0.19.1/elm-stuff/0.19.1/o.dat +0 -0
  19. package/generator/review/elm-stuff/tests-0.19.1/elm.json +1 -1
  20. package/generator/review/elm-stuff/tests-0.19.1/js/Runner.elm.js +45 -4
  21. package/generator/review/elm-stuff/tests-0.19.1/js/node_runner.js +1 -1
  22. package/generator/review/elm-stuff/tests-0.19.1/js/node_supervisor.js +1 -1
  23. package/generator/review/elm.json +3 -3
  24. package/generator/src/RouteBuilder.elm +66 -52
  25. package/generator/src/SharedTemplate.elm +3 -2
  26. package/generator/src/SiteConfig.elm +3 -2
  27. package/generator/src/build.js +6 -6
  28. package/generator/src/cli.js +12 -7
  29. package/generator/src/compatibility-key.js +1 -1
  30. package/generator/src/dev-server.js +7 -7
  31. package/generator/src/render-test.js +109 -0
  32. package/generator/src/render.js +77 -51
  33. package/generator/src/request-cache.js +149 -158
  34. package/generator/template/app/Api.elm +2 -2
  35. package/generator/template/app/Route/Index.elm +3 -3
  36. package/generator/template/app/Shared.elm +3 -3
  37. package/generator/template/app/Site.elm +3 -3
  38. package/package.json +11 -11
  39. package/src/ApiRoute.elm +63 -57
  40. package/src/BackendTask/Env.elm +87 -0
  41. package/src/{DataSource → BackendTask}/File.elm +89 -43
  42. package/src/{DataSource → BackendTask}/Glob.elm +134 -125
  43. package/src/BackendTask/Http.elm +637 -0
  44. package/src/{DataSource → BackendTask}/Internal/Glob.elm +1 -1
  45. package/src/BackendTask/Internal/Request.elm +28 -0
  46. package/src/BackendTask/Port.elm +202 -0
  47. package/src/{DataSource.elm → BackendTask.elm} +223 -207
  48. package/src/Exception.elm +37 -0
  49. package/src/Form.elm +20 -20
  50. package/src/Head.elm +7 -7
  51. package/src/Internal/ApiRoute.elm +7 -5
  52. package/src/PageServerResponse.elm +6 -1
  53. package/src/Pages/Generate.elm +35 -63
  54. package/src/Pages/Internal/Platform/Cli.elm +422 -731
  55. package/src/Pages/Internal/Platform/Cli.elm.bak +22 -22
  56. package/src/Pages/Internal/Platform/CompatibilityKey.elm +1 -1
  57. package/src/Pages/Internal/Platform/Effect.elm +0 -1
  58. package/src/Pages/Internal/Platform/GeneratorApplication.elm +53 -113
  59. package/src/Pages/Internal/Platform/StaticResponses.elm +72 -256
  60. package/src/Pages/Internal/Platform/ToJsPayload.elm +4 -4
  61. package/src/Pages/Internal/Platform.elm +25 -31
  62. package/src/Pages/Internal/Script.elm +17 -0
  63. package/src/Pages/Internal/StaticHttpBody.elm +35 -1
  64. package/src/Pages/Manifest.elm +5 -4
  65. package/src/Pages/ProgramConfig.elm +8 -7
  66. package/src/Pages/Script.elm +34 -25
  67. package/src/Pages/SiteConfig.elm +3 -2
  68. package/src/Pages/StaticHttp/Request.elm +2 -2
  69. package/src/Pages/StaticHttpRequest.elm +37 -90
  70. package/src/RequestsAndPending.elm +8 -19
  71. package/src/Server/Request.elm +14 -14
  72. package/src/Server/Session.elm +34 -34
  73. package/src/Server/SetCookie.elm +1 -1
  74. package/src/DataSource/Env.elm +0 -62
  75. package/src/DataSource/Http.elm +0 -446
  76. package/src/DataSource/Internal/Request.elm +0 -20
  77. package/src/DataSource/Port.elm +0 -90
@@ -111,6 +111,9 @@ async function main() {
111
111
  }
112
112
  try {
113
113
  // await codegen.generate("");
114
+ ensureDirSync(
115
+ path.join(process.cwd(), ".elm-pages", "http-response-cache")
116
+ );
114
117
  if (fs.existsSync("./codegen/")) {
115
118
  await runElmCodegenInstall();
116
119
  }
@@ -126,7 +129,7 @@ async function main() {
126
129
  "./script/elm-stuff/elm-pages/elm.json"
127
130
  );
128
131
 
129
- const portDataSourceCompiled = esbuild
132
+ const portBackendTaskCompiled = esbuild
130
133
  .build({
131
134
  entryPoints: ["./port-data-source"],
132
135
  platform: "node",
@@ -147,16 +150,17 @@ async function main() {
147
150
  }
148
151
  })
149
152
  .catch((error) => {
150
- const portDataSourceFileFound =
153
+ const portBackendTaskFileFound =
151
154
  globby.sync("./port-data-source.*").length > 0;
152
- if (portDataSourceFileFound) {
155
+ if (portBackendTaskFileFound) {
153
156
  // don't present error if there are no files matching port-data-source
154
157
  // if there are files matching port-data-source, warn the user in case something went wrong loading it
155
158
  console.error("Failed to start port-data-source watcher", error);
156
159
  }
157
160
  });
158
- const portsPath = await portDataSourceCompiled;
159
- const resolvedPortsPath = path.join(process.cwd(), portsPath);
161
+ const portsPath = await portBackendTaskCompiled;
162
+ const resolvedPortsPath =
163
+ portsPath && path.join(process.cwd(), portsPath);
160
164
 
161
165
  process.chdir("./script");
162
166
  // TODO have option for compiling with --debug or not (maybe allow running with elm-optimize-level-2 as well?)
@@ -265,7 +269,8 @@ function generatorWrapperFile(moduleName) {
265
269
  return `port module Main exposing (main)
266
270
 
267
271
  import Bytes
268
- import DataSource exposing (DataSource)
272
+ import BackendTask exposing (BackendTask)
273
+ import Exception
269
274
  import Cli.Program as Program
270
275
  import Json.Decode as Decode
271
276
  import Json.Encode as Encode
@@ -273,7 +278,7 @@ import Pages.Internal.Platform.GeneratorApplication
273
278
  import ${moduleName}
274
279
 
275
280
 
276
- main : Program.StatefulProgram Pages.Internal.Platform.GeneratorApplication.Model Pages.Internal.Platform.GeneratorApplication.Msg (DataSource ()) Pages.Internal.Platform.GeneratorApplication.Flags
281
+ main : Program.StatefulProgram Pages.Internal.Platform.GeneratorApplication.Model Pages.Internal.Platform.GeneratorApplication.Msg (BackendTask Exception.Throwable ()) Pages.Internal.Platform.GeneratorApplication.Flags
277
282
  main =
278
283
  Pages.Internal.Platform.GeneratorApplication.app
279
284
  { data = ${moduleName}.run
@@ -1 +1 @@
1
- module.exports = { compatibilityKey: 2 };
1
+ module.exports = { compatibilityKey: 4 };
@@ -174,9 +174,9 @@ async function start(options) {
174
174
  console.log("Watching port-data-source...");
175
175
  })
176
176
  .catch((error) => {
177
- const portDataSourceFileFound =
177
+ const portBackendTaskFileFound =
178
178
  globby.sync("./port-data-source.*").length > 0;
179
- if (portDataSourceFileFound) {
179
+ if (portBackendTaskFileFound) {
180
180
  // don't present error if there are no files matching port-data-source
181
181
  // if there are files matching port-data-source, warn the user in case something went wrong loading it
182
182
  console.error("Failed to start port-data-source watcher", error);
@@ -282,18 +282,18 @@ async function start(options) {
282
282
  // TODO use similar logic in the workers? Or don't use cache at all?
283
283
  // const changedPathRelative = path.relative(process.cwd(), pathThatChanged);
284
284
  //
285
- // Object.keys(global.staticHttpCache).forEach((dataSourceKey) => {
286
- // if (dataSourceKey.includes(`file://${changedPathRelative}`)) {
287
- // delete global.staticHttpCache[dataSourceKey];
285
+ // Object.keys(global.staticHttpCache).forEach((backendTaskKey) => {
286
+ // if (backendTaskKey.includes(`file://${changedPathRelative}`)) {
287
+ // delete global.staticHttpCache[backendTaskKey];
288
288
  // } else if (
289
289
  // (eventName === "add" ||
290
290
  // eventName === "unlink" ||
291
291
  // eventName === "change" ||
292
292
  // eventName === "addDir" ||
293
293
  // eventName === "unlinkDir") &&
294
- // dataSourceKey.startsWith("glob://")
294
+ // backendTaskKey.startsWith("glob://")
295
295
  // ) {
296
- // delete global.staticHttpCache[dataSourceKey];
296
+ // delete global.staticHttpCache[backendTaskKey];
297
297
  // }
298
298
  // });
299
299
  clients.forEach((client) => {
@@ -0,0 +1,109 @@
1
+ const renderer = require("../../generator/src/render");
2
+ const path = require("path");
3
+ const compiledElmPath = path.join(process.cwd(), "elm-stuff/elm-pages/elm.js");
4
+ const codegen = require("./codegen.js");
5
+ const {
6
+ compileElmForBrowser,
7
+ runElmReview,
8
+ compileCliApp,
9
+ } = require("./compile-elm.js");
10
+ const { restoreColorSafe } = require("./error-formatter");
11
+
12
+ async function run({ pathname, serverRequest }) {
13
+ try {
14
+ const basePath = "/";
15
+ await codegen.generate(basePath);
16
+ console.log("Compiling...");
17
+ await compileCliApp(
18
+ { port: 1234, base: basePath, https: false, debug: true },
19
+ ".elm-pages/Main.elm",
20
+
21
+ path.join(process.cwd(), "elm-stuff/elm-pages/", "elm.js"),
22
+
23
+ // "elm.js",
24
+ "elm-stuff/elm-pages/",
25
+ path.join("elm-stuff/elm-pages/", "elm.js")
26
+ );
27
+ console.log("Compiling DONE");
28
+
29
+ const portsFilePath =
30
+ ".elm-pages/compiled-ports/port-data-source-FA2IJND6.js";
31
+ const mode = "dev-server";
32
+
33
+ const renderResult = await renderer.render(
34
+ portsFilePath,
35
+ basePath,
36
+ require(compiledElmPath),
37
+ mode,
38
+ pathname,
39
+ serverRequest,
40
+ function (patterns) {},
41
+ true
42
+ );
43
+ console.log("renderResult", renderResult);
44
+ } catch (error) {
45
+ console.log("ERROR");
46
+ console.log(restoreColorSafe(error));
47
+ }
48
+ }
49
+
50
+ // run({
51
+ // serverRequest: {
52
+ // method: "POST",
53
+ // headers: {
54
+ // host: "localhost:1234",
55
+ // cookie: "darkMode=%7B%7D.X1hjuYBa1OZulUomD5yrPy6VcYeY3sC7SKZVGViT0Q4",
56
+ // accept: "*/*",
57
+ // "accept-language": "en-US,en;q=0.9",
58
+ // connection: "keep-alive",
59
+ // "content-type": "application/x-www-form-urlencoded",
60
+ // origin: "http://localhost:1234",
61
+ // referer: "http://localhost:1234/dark-mode",
62
+ // },
63
+ // rawUrl: "http://localhost:1234/dark-mode/content.dat",
64
+ // body: "name=1",
65
+ // requestTime: 1671391652138,
66
+ // multiPartFormData: null,
67
+ // },
68
+ // pathname: "/dark-mode/content.dat",
69
+ // });
70
+
71
+ // run({
72
+ // pathname: "/fetcher/content.dat",
73
+ // serverRequest: {
74
+ // method: "POST",
75
+ // headers: {
76
+ // host: "localhost:1234",
77
+ // cookie: "darkMode=%7B%7D",
78
+ // accept: "*/*",
79
+ // "content-type": "application/x-www-form-urlencoded",
80
+ // origin: "http://localhost:1234",
81
+ // referer: "http://localhost:1234/fetcher",
82
+ // },
83
+ // rawUrl: "http://localhost:1234/fetcher/content.dat",
84
+ // body: "name=1",
85
+ // requestTime: 1671296755228,
86
+ // multiPartFormData: null,
87
+ // },
88
+ // });
89
+
90
+ run({
91
+ serverRequest: {
92
+ method: "POST",
93
+ headers: {
94
+ host: "localhost:1234",
95
+ "cache-control": "max-age=0",
96
+ accept:
97
+ "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
98
+ "content-type": "application/x-www-form-urlencoded",
99
+ referer: "http://localhost:1234/login",
100
+ cookie:
101
+ "darkMode=%7B%22darkMode%22%3A%22%22%7D.vtrl8xZXjtx9E3iidJrgurAz4Vk7rnMQmf6zKiAbwNo; mysession=%7B%7D.YX1rW5PIpRFkjgIjLn4p9iyl5r9kWLYHqQUYxAYKJgQ",
102
+ },
103
+ rawUrl: "http://localhost:1234/login/content.dat",
104
+ body: "name=1",
105
+ requestTime: 1671391652138,
106
+ multiPartFormData: null,
107
+ },
108
+ pathname: "/login/content.dat",
109
+ });
@@ -16,8 +16,8 @@ process.on("unhandledRejection", (error) => {
16
16
  console.error(error);
17
17
  });
18
18
  let foundErrors;
19
- let pendingDataSourceResponses;
20
- let pendingDataSourceCount;
19
+ let pendingBackendTaskResponses = new Map();
20
+ let pendingBackendTaskCount;
21
21
 
22
22
  module.exports = { render, runGenerator };
23
23
 
@@ -27,7 +27,7 @@ module.exports = { render, runGenerator };
27
27
  * @param {Object} elmModule
28
28
  * @param {string} path
29
29
  * @param {{ method: string; hostname: string; query: Record<string, string | undefined>; headers: Record<string, string>; host: string; pathname: string; port: number | null; protocol: string; rawUrl: string; }} request
30
- * @param {(pattern: string) => void} addDataSourceWatcher
30
+ * @param {(pattern: string) => void} addBackendTaskWatcher
31
31
  * @param {boolean} hasFsAccess
32
32
  * @returns
33
33
  */
@@ -38,15 +38,15 @@ async function render(
38
38
  mode,
39
39
  path,
40
40
  request,
41
- addDataSourceWatcher,
41
+ addBackendTaskWatcher,
42
42
  hasFsAccess
43
43
  ) {
44
44
  const { fs, resetInMemoryFs } = require("./request-cache-fs.js")(hasFsAccess);
45
45
  resetInMemoryFs();
46
46
  foundErrors = false;
47
- pendingDataSourceResponses = [];
48
- pendingDataSourceCount = 0;
49
- // since init/update are never called in pre-renders, and DataSource.Http is called using pure NodeJS HTTP fetching
47
+ pendingBackendTaskResponses = new Map();
48
+ pendingBackendTaskCount = 0;
49
+ // since init/update are never called in pre-renders, and BackendTask.Http is called using pure NodeJS HTTP fetching
50
50
  // we can provide a fake HTTP instead of xhr2 (which is otherwise needed for Elm HTTP requests from Node)
51
51
  XMLHttpRequest = {};
52
52
  const result = await runElmApp(
@@ -56,7 +56,7 @@ async function render(
56
56
  mode,
57
57
  path,
58
58
  request,
59
- addDataSourceWatcher,
59
+ addBackendTaskWatcher,
60
60
  fs,
61
61
  hasFsAccess
62
62
  );
@@ -74,9 +74,9 @@ async function runGenerator(cliOptions, portsFile, elmModule) {
74
74
  const { fs, resetInMemoryFs } = require("./request-cache-fs.js")(true);
75
75
  resetInMemoryFs();
76
76
  foundErrors = false;
77
- pendingDataSourceResponses = [];
78
- pendingDataSourceCount = 0;
79
- // since init/update are never called in pre-renders, and DataSource.Http is called using pure NodeJS HTTP fetching
77
+ pendingBackendTaskResponses = new Map();
78
+ pendingBackendTaskCount = 0;
79
+ // since init/update are never called in pre-renders, and BackendTask.Http is called using pure NodeJS HTTP fetching
80
80
  // we can provide a fake HTTP instead of xhr2 (which is otherwise needed for Elm HTTP requests from Node)
81
81
  XMLHttpRequest = {};
82
82
  const result = await runGeneratorAppHelp(
@@ -178,12 +178,14 @@ function runGeneratorAppHelp(
178
178
  );
179
179
  }
180
180
  } else if (fromElm.tag === "DoHttp") {
181
- const requestToPerform = fromElm.args[0];
181
+ const requestHash = fromElm.args[0];
182
+ const requestToPerform = fromElm.args[1];
182
183
  if (
183
184
  requestToPerform.url !== "elm-pages-internal://port" &&
184
185
  requestToPerform.url.startsWith("elm-pages-internal://")
185
186
  ) {
186
187
  runInternalJob(
188
+ requestHash,
187
189
  app,
188
190
  mode,
189
191
  requestToPerform,
@@ -193,6 +195,7 @@ function runGeneratorAppHelp(
193
195
  );
194
196
  } else {
195
197
  runHttpJob(
198
+ requestHash,
196
199
  portsFile,
197
200
  app,
198
201
  mode,
@@ -225,7 +228,7 @@ function runGeneratorAppHelp(
225
228
  * @param {string} pagePath
226
229
  * @param {string} mode
227
230
  * @param {{ method: string; hostname: string; query: string; headers: Object; host: string; pathname: string; port: string; protocol: string; rawUrl: string; }} request
228
- * @param {(pattern: string) => void} addDataSourceWatcher
231
+ * @param {(pattern: string) => void} addBackendTaskWatcher
229
232
  * @returns {Promise<({is404: boolean} & ( { kind: 'json'; contentJson: string} | { kind: 'html'; htmlString: string } | { kind: 'api-response'; body: string; }) )>}
230
233
  */
231
234
  function runElmApp(
@@ -235,7 +238,7 @@ function runElmApp(
235
238
  mode,
236
239
  pagePath,
237
240
  request,
238
- addDataSourceWatcher,
241
+ addBackendTaskWatcher,
239
242
  fs,
240
243
  hasFsAccess
241
244
  ) {
@@ -318,12 +321,14 @@ function runElmApp(
318
321
  );
319
322
  }
320
323
  } else if (fromElm.tag === "DoHttp") {
321
- const requestToPerform = fromElm.args[0];
324
+ const requestHash = fromElm.args[0];
325
+ const requestToPerform = fromElm.args[1];
322
326
  if (
323
327
  requestToPerform.url !== "elm-pages-internal://port" &&
324
328
  requestToPerform.url.startsWith("elm-pages-internal://")
325
329
  ) {
326
330
  runInternalJob(
331
+ requestHash,
327
332
  app,
328
333
  mode,
329
334
  requestToPerform,
@@ -333,6 +338,7 @@ function runElmApp(
333
338
  );
334
339
  } else {
335
340
  runHttpJob(
341
+ requestHash,
336
342
  portsFile,
337
343
  app,
338
344
  mode,
@@ -352,7 +358,7 @@ function runElmApp(
352
358
  app.ports.toJsPort.subscribe(portHandler);
353
359
  app.ports.sendPageData.subscribe(portHandler);
354
360
  }).finally(() => {
355
- addDataSourceWatcher(patternsToWatch);
361
+ addBackendTaskWatcher(patternsToWatch);
356
362
  try {
357
363
  killApp();
358
364
  killApp = null;
@@ -401,6 +407,7 @@ async function outputString(
401
407
  /** @typedef { { head: any[]; errors: any[]; contentJson: any[]; html: string; route: string; title: string; } } Arg */
402
408
 
403
409
  async function runHttpJob(
410
+ requestHash,
404
411
  portsFile,
405
412
  app,
406
413
  mode,
@@ -409,9 +416,9 @@ async function runHttpJob(
409
416
  hasFsAccess,
410
417
  useCache
411
418
  ) {
412
- pendingDataSourceCount += 1;
419
+ pendingBackendTaskCount += 1;
413
420
  try {
414
- const responseFilePath = await lookupOrPerform(
421
+ const lookupResponse = await lookupOrPerform(
415
422
  portsFile,
416
423
  mode,
417
424
  requestToPerform,
@@ -419,16 +426,26 @@ async function runHttpJob(
419
426
  useCache
420
427
  );
421
428
 
422
- pendingDataSourceResponses.push({
423
- request: requestToPerform,
424
- response: JSON.parse(
425
- (await fs.promises.readFile(responseFilePath, "utf8")).toString()
426
- ),
427
- });
429
+ if (lookupResponse.kind === "cache-response-path") {
430
+ const responseFilePath = lookupResponse.value;
431
+ pendingBackendTaskResponses.set(requestHash, {
432
+ request: requestToPerform,
433
+ response: JSON.parse(
434
+ (await fs.promises.readFile(responseFilePath, "utf8")).toString()
435
+ ),
436
+ });
437
+ } else if (lookupResponse.kind === "response-json") {
438
+ pendingBackendTaskResponses.set(requestHash, {
439
+ request: requestToPerform,
440
+ response: lookupResponse.value,
441
+ });
442
+ } else {
443
+ throw `Unexpected kind ${lookupResponse}`;
444
+ }
428
445
  } catch (error) {
429
446
  sendError(app, error);
430
447
  } finally {
431
- pendingDataSourceCount -= 1;
448
+ pendingBackendTaskCount -= 1;
432
449
  flushIfDone(app);
433
450
  }
434
451
  }
@@ -447,6 +464,7 @@ function jsonResponse(request, json) {
447
464
  }
448
465
 
449
466
  async function runInternalJob(
467
+ requestHash,
450
468
  app,
451
469
  mode,
452
470
  requestToPerform,
@@ -455,41 +473,52 @@ async function runInternalJob(
455
473
  patternsToWatch
456
474
  ) {
457
475
  try {
458
- pendingDataSourceCount += 1;
476
+ pendingBackendTaskCount += 1;
459
477
 
460
478
  if (requestToPerform.url === "elm-pages-internal://log") {
461
- pendingDataSourceResponses.push(await runLogJob(requestToPerform));
479
+ pendingBackendTaskResponses.set(
480
+ requestHash,
481
+ await runLogJob(requestToPerform)
482
+ );
462
483
  } else if (requestToPerform.url === "elm-pages-internal://read-file") {
463
- pendingDataSourceResponses.push(
484
+ pendingBackendTaskResponses.set(
485
+ requestHash,
464
486
  await readFileJobNew(requestToPerform, patternsToWatch)
465
487
  );
466
488
  } else if (requestToPerform.url === "elm-pages-internal://glob") {
467
- pendingDataSourceResponses.push(
489
+ pendingBackendTaskResponses.set(
490
+ requestHash,
468
491
  await runGlobNew(requestToPerform, patternsToWatch)
469
492
  );
470
493
  } else if (requestToPerform.url === "elm-pages-internal://env") {
471
- pendingDataSourceResponses.push(
494
+ pendingBackendTaskResponses.set(
495
+ requestHash,
472
496
  await runEnvJob(requestToPerform, patternsToWatch)
473
497
  );
474
498
  } else if (requestToPerform.url === "elm-pages-internal://encrypt") {
475
- pendingDataSourceResponses.push(
499
+ pendingBackendTaskResponses.set(
500
+ requestHash,
476
501
  await runEncryptJob(requestToPerform, patternsToWatch)
477
502
  );
478
503
  } else if (requestToPerform.url === "elm-pages-internal://decrypt") {
479
- pendingDataSourceResponses.push(
504
+ pendingBackendTaskResponses.set(
505
+ requestHash,
480
506
  await runDecryptJob(requestToPerform, patternsToWatch)
481
507
  );
482
508
  } else if (requestToPerform.url === "elm-pages-internal://write-file") {
483
- pendingDataSourceResponses.push(await runWriteFileJob(requestToPerform));
509
+ pendingBackendTaskResponses.set(
510
+ requestHash,
511
+ await runWriteFileJob(requestToPerform)
512
+ );
484
513
  } else {
485
- throw `Unexpected internal DataSource request format: ${kleur.yellow(
514
+ throw `Unexpected internal BackendTask request format: ${kleur.yellow(
486
515
  JSON.stringify(2, null, requestToPerform)
487
516
  )}`;
488
517
  }
489
518
  } catch (error) {
490
519
  sendError(app, error);
491
520
  } finally {
492
- pendingDataSourceCount -= 1;
521
+ pendingBackendTaskCount -= 1;
493
522
  flushIfDone(app);
494
523
  }
495
524
  }
@@ -505,6 +534,7 @@ async function readFileJobNew(req, patternsToWatch) {
505
534
  path.join(process.env.LAMBDA_TASK_ROOT || process.cwd(), filePath)
506
535
  )
507
536
  ).toString();
537
+ // TODO does this throw an error if there is invalid frontmatter?
508
538
  const parsedFile = matter(fileContents);
509
539
 
510
540
  return jsonResponse(req, {
@@ -513,12 +543,9 @@ async function readFileJobNew(req, patternsToWatch) {
513
543
  rawFile: fileContents,
514
544
  });
515
545
  } catch (error) {
516
- throw {
517
- title: "DataSource.File Error",
518
- message: `A DataSource.File read failed because I couldn't find this file: ${kleur.yellow(
519
- filePath
520
- )}\n${kleur.red(error.toString())}`,
521
- };
546
+ return jsonResponse(req, {
547
+ errorCode: error.code,
548
+ });
522
549
  }
523
550
  }
524
551
  async function runWriteFileJob(req) {
@@ -531,8 +558,8 @@ async function runWriteFileJob(req) {
531
558
  } catch (error) {
532
559
  console.trace(error);
533
560
  throw {
534
- title: "DataSource Error",
535
- message: `DataSource.Generator.writeFile failed for file path: ${kleur.yellow(
561
+ title: "BackendTask Error",
562
+ message: `BackendTask.Generator.writeFile failed for file path: ${kleur.yellow(
536
563
  data.path
537
564
  )}\n${kleur.red(error.toString())}`,
538
565
  };
@@ -589,7 +616,7 @@ async function runEncryptJob(req, patternsToWatch) {
589
616
  );
590
617
  } catch (e) {
591
618
  throw {
592
- title: "DataSource Encrypt Error",
619
+ title: "BackendTask Encrypt Error",
593
620
  message:
594
621
  e.toString() + e.stack + "\n\n" + JSON.stringify(rawRequest, null, 2),
595
622
  };
@@ -606,7 +633,7 @@ async function runDecryptJob(req, patternsToWatch) {
606
633
  return jsonResponse(req, JSON.parse(signed || "null"));
607
634
  } catch (e) {
608
635
  throw {
609
- title: "DataSource Decrypt Error",
636
+ title: "BackendTask Decrypt Error",
610
637
  message:
611
638
  e.toString() + e.stack + "\n\n" + JSON.stringify(rawRequest, null, 2),
612
639
  };
@@ -615,10 +642,10 @@ async function runDecryptJob(req, patternsToWatch) {
615
642
 
616
643
  function flushIfDone(app) {
617
644
  if (foundErrors) {
618
- pendingDataSourceResponses = [];
619
- } else if (pendingDataSourceCount === 0) {
645
+ pendingBackendTaskResponses = new Map();
646
+ } else if (pendingBackendTaskCount === 0) {
620
647
  // console.log(
621
- // `Flushing ${pendingDataSourceResponses.length} items in ${timeUntilThreshold}ms`
648
+ // `Flushing ${pendingBackendTaskResponses.length} items in ${timeUntilThreshold}ms`
622
649
  // );
623
650
 
624
651
  flushQueue(app);
@@ -626,10 +653,9 @@ function flushIfDone(app) {
626
653
  }
627
654
 
628
655
  function flushQueue(app) {
629
- const temp = pendingDataSourceResponses;
630
- pendingDataSourceResponses = [];
656
+ app.ports.gotBatchSub.send(Object.fromEntries(pendingBackendTaskResponses));
657
+ pendingBackendTaskResponses = new Map();
631
658
  // console.log("@@@ FLUSHING", temp.length);
632
- app.ports.gotBatchSub.send(temp);
633
659
  }
634
660
 
635
661
  /**