@applicaster/zapplicaster-cli 16.0.0-alpha.1833861900 → 16.0.0-alpha.1852433906

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 (40) hide show
  1. package/package.json +5 -5
  2. package/src/commands/prepareWorkspace/__tests__/__snapshots__/configurator.test.js.snap +2 -0
  3. package/src/commands/prepareWorkspace/__tests__/buildPluginsCreator.test.js +99 -0
  4. package/src/commands/prepareWorkspace/appBootstrapper.js +9 -0
  5. package/src/commands/prepareWorkspace/buildPluginsCreator.js +61 -0
  6. package/src/commands/prepareWorkspace/configFilesRetriever.js +3 -0
  7. package/src/commands/prepareWorkspace/configurator.js +26 -1
  8. package/src/commands/prepareWorkspace/parseFonts.js +6 -0
  9. package/src/commands/publishPackage/index.js +1 -0
  10. package/src/commands/publishPlugin/README.md +194 -0
  11. package/src/commands/publishPlugin/__tests__/commitToGit.test.js +1 -1
  12. package/src/commands/publishPlugin/__tests__/configurator.test.js +2 -2
  13. package/src/commands/publishPlugin/__tests__/manifests/android.json +3 -1
  14. package/src/commands/publishPlugin/__tests__/manifests/android_for_quickbrick.json +6 -0
  15. package/src/commands/publishPlugin/__tests__/manifests/android_tv_for_quickbrick.json +6 -0
  16. package/src/commands/publishPlugin/__tests__/manifests/ios.json +3 -1
  17. package/src/commands/publishPlugin/__tests__/manifests/ios_for_quickbrick.json +6 -0
  18. package/src/commands/publishPlugin/__tests__/manifests/tvos_for_quickbrick.json +6 -0
  19. package/src/commands/publishPlugin/__tests__/zappApi.test.js +271 -0
  20. package/src/commands/publishPlugin/__tests__/zappifestPublish.test.js +109 -33
  21. package/src/commands/publishPlugin/commitToGit.js +1 -1
  22. package/src/commands/publishPlugin/configurator.js +1 -1
  23. package/src/commands/publishPlugin/generateManifest.js +1 -0
  24. package/src/commands/publishPlugin/index.js +1 -0
  25. package/src/commands/publishPlugin/updateCorePluginsIfNeeded.js +22 -12
  26. package/src/commands/publishPlugin/zappApi.js +283 -0
  27. package/src/commands/publishPlugin/zappifestPublish.js +123 -8
  28. package/src/commands/reloadConfig/__tests__/__snapshots__/reloadConfig.test.js.snap +58 -0
  29. package/src/commands/reloadConfig/__tests__/reloadConfig.test.js +86 -0
  30. package/src/commands/reloadConfig/index.js +6 -6
  31. package/src/commands/utils/__tests__/publishTiming.test.js +130 -0
  32. package/src/commands/utils/publishTiming.js +35 -0
  33. package/src/download/__tests__/download.test.js +53 -0
  34. package/src/download/index.js +65 -1
  35. package/src/file/index.js +15 -9
  36. package/src/taskRunner/__tests__/taskRunner.test.js +82 -0
  37. package/src/taskRunner/index.js +20 -3
  38. package/src/templates/__tests__/__snapshots__/templates.test.js.snap +1 -1
  39. package/src/templates/index.js +1 -0
  40. package/src/commands/publishPlugin/__tests__/__snapshots__/zappifestPublish.test.js.snap +0 -5
@@ -0,0 +1,130 @@
1
+ jest.mock("../../../logger", () => ({
2
+ log: jest.fn(),
3
+ }));
4
+
5
+ const logger = require("../../../logger");
6
+ const { measurePublishStep } = require("../publishTiming");
7
+
8
+ const originalTimingFlag = process.env.QB_PUBLISH_TIMINGS;
9
+
10
+ const details = {
11
+ packageName: "@applicaster/example",
12
+ version: "16.0.0-alpha.123",
13
+ };
14
+
15
+ const records = () =>
16
+ logger.log.mock.calls.map(([line]) =>
17
+ JSON.parse(line.slice("[publish-timing] ".length))
18
+ );
19
+
20
+ describe("publish timing", () => {
21
+ beforeEach(() => {
22
+ logger.log.mockClear();
23
+ delete process.env.QB_PUBLISH_TIMINGS;
24
+ });
25
+
26
+ afterEach(() => {
27
+ jest.restoreAllMocks();
28
+
29
+ if (originalTimingFlag === undefined) {
30
+ delete process.env.QB_PUBLISH_TIMINGS;
31
+ } else {
32
+ process.env.QB_PUBLISH_TIMINGS = originalTimingFlag;
33
+ }
34
+ });
35
+
36
+ it("does not log unless explicitly enabled and preserves the result", async () => {
37
+ const operation = jest.fn(async () => "published");
38
+
39
+ await expect(measurePublishStep("npm", details, operation)).resolves.toBe(
40
+ "published"
41
+ );
42
+
43
+ expect(operation).toHaveBeenCalledTimes(1);
44
+ expect(logger.log).not.toHaveBeenCalled();
45
+ });
46
+
47
+ it("preserves failures when timing is disabled", async () => {
48
+ const error = new Error("publish failed");
49
+
50
+ await expect(
51
+ measurePublishStep("npm", details, async () => {
52
+ throw error;
53
+ })
54
+ ).rejects.toBe(error);
55
+
56
+ expect(logger.log).not.toHaveBeenCalled();
57
+ });
58
+
59
+ it("logs correlated start/end records with monotonic milliseconds", async () => {
60
+ process.env.QB_PUBLISH_TIMINGS = "true";
61
+
62
+ jest
63
+ .spyOn(process.hrtime, "bigint")
64
+ .mockReturnValueOnce(1000000000n)
65
+ .mockReturnValueOnce(1000000000n)
66
+ .mockReturnValueOnce(1250500000n);
67
+
68
+ const result = { published: true };
69
+ const operation = jest.fn(async () => result);
70
+
71
+ await expect(measurePublishStep("npm", details, operation)).resolves.toBe(
72
+ result
73
+ );
74
+
75
+ expect(operation).toHaveBeenCalledTimes(1);
76
+
77
+ expect(records()).toEqual([
78
+ {
79
+ ...details,
80
+ stage: "npm",
81
+ startedAt: expect.any(String),
82
+ status: "started",
83
+ durationMs: 0,
84
+ },
85
+ {
86
+ ...details,
87
+ stage: "npm",
88
+ startedAt: records()[0].startedAt,
89
+ status: "succeeded",
90
+ durationMs: 250.5,
91
+ },
92
+ ]);
93
+ });
94
+
95
+ it("records failures without swallowing them or logging error contents", async () => {
96
+ process.env.QB_PUBLISH_TIMINGS = "true";
97
+ const error = new Error("sensitive registry response");
98
+
99
+ await expect(
100
+ measurePublishStep("npm", details, async () => {
101
+ throw error;
102
+ })
103
+ ).rejects.toBe(error);
104
+
105
+ expect(records().map(({ status }) => status)).toEqual([
106
+ "started",
107
+ "failed",
108
+ ]);
109
+
110
+ expect(logger.log.mock.calls.flat().join("")).not.toContain(error.message);
111
+ });
112
+
113
+ it("keeps overlapping packages identifiable", async () => {
114
+ process.env.QB_PUBLISH_TIMINGS = "true";
115
+
116
+ await Promise.all(
117
+ ["first", "second"].map((packageName) =>
118
+ measurePublishStep("npm", { ...details, packageName }, async () => true)
119
+ )
120
+ );
121
+
122
+ for (const packageName of ["first", "second"]) {
123
+ expect(
124
+ records()
125
+ .filter((record) => record.packageName === packageName)
126
+ .map(({ status }) => status)
127
+ ).toEqual(["started", "succeeded"]);
128
+ }
129
+ });
130
+ });
@@ -0,0 +1,35 @@
1
+ const logger = require("../../logger");
2
+
3
+ async function measurePublishStep(stage, details, operation) {
4
+ if (process.env.QB_PUBLISH_TIMINGS !== "true") {
5
+ return operation();
6
+ }
7
+
8
+ const startedAt = new Date().toISOString();
9
+ const start = process.hrtime.bigint();
10
+ const context = { ...details, stage, startedAt };
11
+
12
+ const report = (status) => {
13
+ logger.log(
14
+ `[publish-timing] ${JSON.stringify({
15
+ ...context,
16
+ status,
17
+ durationMs: Number(process.hrtime.bigint() - start) / 1e6,
18
+ })}`
19
+ );
20
+ };
21
+
22
+ report("started");
23
+
24
+ try {
25
+ const result = await operation();
26
+ report("succeeded");
27
+
28
+ return result;
29
+ } catch (error) {
30
+ report("failed");
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ module.exports = { measurePublishStep };
@@ -1,6 +1,7 @@
1
1
  const { saveRemoteJsonToFile, saveAssets, saveFontFiles } = require("../index");
2
2
  const nock = require("nock");
3
3
  const R = require("ramda");
4
+ const fs = require("fs");
4
5
  const logger = require("../../logger");
5
6
 
6
7
  const getFileName = R.compose(R.last, R.split("/"));
@@ -109,9 +110,37 @@ describe("saveAssets", () => {
109
110
 
110
111
  afterEach(() => {
111
112
  clearAllMocks();
113
+
114
+ ["existsSync", "openSync", "closeSync", "readSync", "readFileSync"].forEach(
115
+ (method) => {
116
+ if (fs[method] && fs[method].mockRestore) {
117
+ fs[method].mockRestore();
118
+ }
119
+ }
120
+ );
112
121
  });
113
122
 
123
+ function mockDownloadedFile({ isZip, content } = {}) {
124
+ jest.spyOn(fs, "existsSync").mockReturnValue(true);
125
+ jest.spyOn(fs, "openSync").mockReturnValue(1);
126
+ jest.spyOn(fs, "closeSync").mockImplementation(() => ({}));
127
+
128
+ jest.spyOn(fs, "readSync").mockImplementation((fd, buffer) => {
129
+ const header = isZip
130
+ ? Buffer.from([0x50, 0x4b, 0x03, 0x04])
131
+ : Buffer.from("<?xm");
132
+
133
+ header.copy(buffer);
134
+
135
+ return 4;
136
+ });
137
+
138
+ jest.spyOn(fs, "readFileSync").mockReturnValue(content || "");
139
+ }
140
+
114
141
  it("downloads the files with cURL, and unzips the assets", () => {
142
+ mockDownloadedFile({ isZip: true });
143
+
115
144
  saveAssets({ destinationPath, platform }, assetsUrl);
116
145
 
117
146
  expect(loggerSpy).toHaveBeenCalledWith(`saving assets from ${assetsUrl}`);
@@ -122,6 +151,30 @@ describe("saveAssets", () => {
122
151
  filePath
123
152
  );
124
153
  });
154
+
155
+ it("throws a clear error and skips unzip when the bundle is not a zip", () => {
156
+ mockDownloadedFile({
157
+ isZip: false,
158
+ content:
159
+ '<?xml version="1.0" encoding="UTF-8"?><Error><Code>AccessDenied</Code></Error>',
160
+ });
161
+
162
+ expect(() => saveAssets({ destinationPath, platform }, assetsUrl)).toThrow(
163
+ /AccessDenied/
164
+ );
165
+
166
+ expect(shell.unzip).not.toHaveBeenCalled();
167
+ });
168
+
169
+ it("throws a clear error when the bundle was not downloaded", () => {
170
+ jest.spyOn(fs, "existsSync").mockReturnValue(false);
171
+
172
+ expect(() => saveAssets({ destinationPath, platform }, assetsUrl)).toThrow(
173
+ /was not downloaded/
174
+ );
175
+
176
+ expect(shell.unzip).not.toHaveBeenCalled();
177
+ });
125
178
  });
126
179
 
127
180
  describe("saveFontFiles", () => {
@@ -1,4 +1,5 @@
1
1
  const R = require("ramda");
2
+ const fs = require("fs");
2
3
  const axios = require("axios");
3
4
  const { resolve } = require("path");
4
5
  const { curlFile, curlMultipleFiles, unzip } = require("../shell");
@@ -12,6 +13,64 @@ const getFileName = R.ifElse(
12
13
  R.prop("name")
13
14
  );
14
15
 
16
+ // Local file signature for a zip archive: "PK\x03\x04"
17
+ const ZIP_SIGNATURE = "504b0304";
18
+
19
+ /**
20
+ * checks whether a file on disk is a real zip archive by reading its magic bytes.
21
+ * @param {String} file path to the file to inspect
22
+ * @returns {Boolean} true if the file starts with the zip local file signature
23
+ */
24
+ function isZipFile(file) {
25
+ const fd = fs.openSync(file, "r");
26
+
27
+ try {
28
+ const header = Buffer.alloc(4);
29
+ const bytesRead = fs.readSync(fd, header, 0, 4, 0);
30
+
31
+ return bytesRead === 4 && header.toString("hex") === ZIP_SIGNATURE;
32
+ } finally {
33
+ fs.closeSync(fd);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * verifies that the downloaded assets bundle is a real zip archive.
39
+ * The assets CDN responds with a small XML/HTML body (e.g. S3 "AccessDenied")
40
+ * when the bundle is missing or not yet published. Because the download uses
41
+ * `curl -O` without `-f`, that error body is saved as assets.zip and the process
42
+ * continues, only to crash later in webpack with a confusing parse error. This
43
+ * check fails fast in the prepare step with an actionable message instead.
44
+ * @param {String} file path to the downloaded assets bundle
45
+ * @param {String} assetsUrl original url, surfaced in the error message
46
+ */
47
+ function assertValidAssetsBundle(file, assetsUrl) {
48
+ if (!fs.existsSync(file)) {
49
+ throw new Error(
50
+ `Assets bundle was not downloaded from ${assetsUrl}. ` +
51
+ "Verify the app has a published build with generated assets for this platform."
52
+ );
53
+ }
54
+
55
+ if (isZipFile(file)) {
56
+ return;
57
+ }
58
+
59
+ const preview = fs
60
+ .readFileSync(file, "utf8")
61
+ .replace(/\s+/g, " ")
62
+ .trim()
63
+ .slice(0, 300);
64
+
65
+ throw new Error(
66
+ `Invalid assets bundle downloaded from ${assetsUrl} - expected a zip archive ` +
67
+ `but received non-zip content:\n "${preview}"\n` +
68
+ "This usually means the assets bundle has not been generated/published for " +
69
+ 'this platform, or the URL is not accessible (e.g. S3 "AccessDenied"). ' +
70
+ "Publish a build with assets for this platform before preparing the workspace."
71
+ );
72
+ }
73
+
15
74
  /**
16
75
  * saves a remote json file in the app's configuration folder.
17
76
  * curried function of the shape saveRemoteJsonToFile(configuration)(fileUrl)
@@ -65,7 +124,12 @@ function saveAssets({ destinationPath, platform }, assetsUrl) {
65
124
  });
66
125
 
67
126
  curlFile(assetsUrl, filePath);
68
- unzip(resolve(filePath, fileName), filePath);
127
+
128
+ const downloadedFile = resolve(filePath, fileName);
129
+
130
+ assertValidAssetsBundle(downloadedFile, assetsUrl);
131
+
132
+ unzip(downloadedFile, filePath);
69
133
  }
70
134
 
71
135
  /**
package/src/file/index.js CHANGED
@@ -61,8 +61,13 @@ function destinationFileNameMapper(destinationFileName) {
61
61
  /**
62
62
  * Copies an array of files from a folder to another
63
63
  *
64
+ * Each entry can either be a string (same relative path for source and
65
+ * destination) or an object `{ source, destination }` when a file should be
66
+ * read from one relative path and written to another. The latter lets several
67
+ * platforms reuse a single set of bundled assets without duplicating them.
68
+ *
64
69
  * @param {String} source folder of the files
65
- * @param {String[]} files list of the files
70
+ * @param {(String|{source: String, destination: String})[]} files list of the files
66
71
  * @param {String} destination path
67
72
  * @returns {Promise[]} array of promises with the status of the copied files
68
73
  */
@@ -72,14 +77,15 @@ function copyFiles(source, filesOrFilesGetter, destination, config) {
72
77
  ? filesOrFilesGetter(config)
73
78
  : filesOrFilesGetter;
74
79
 
75
- return R.map(
76
- (file) =>
77
- copyFileSync(
78
- join(source, file),
79
- destinationFileNameMapper(join(destination, file))
80
- ),
81
- files
82
- );
80
+ return R.map((file) => {
81
+ const sourceFile = typeof file === "string" ? file : file.source;
82
+ const destinationFile = typeof file === "string" ? file : file.destination;
83
+
84
+ return copyFileSync(
85
+ join(source, sourceFile),
86
+ destinationFileNameMapper(join(destination, destinationFile))
87
+ );
88
+ }, files);
83
89
  }
84
90
 
85
91
  module.exports = {
@@ -260,4 +260,86 @@ describe("taskRunner", () => {
260
260
  );
261
261
  });
262
262
  });
263
+
264
+ describe("publish timing", () => {
265
+ const originalTimingFlag = process.env.QB_PUBLISH_TIMINGS;
266
+
267
+ beforeEach(() => {
268
+ process.env.QB_PUBLISH_TIMINGS = "true";
269
+ logSpy.mockClear();
270
+ });
271
+
272
+ afterEach(() => {
273
+ if (originalTimingFlag === undefined) {
274
+ delete process.env.QB_PUBLISH_TIMINGS;
275
+ } else {
276
+ process.env.QB_PUBLISH_TIMINGS = originalTimingFlag;
277
+ }
278
+ });
279
+
280
+ it.each([
281
+ { pluginPackageJson: { name: "plugin" }, version: "1.0.0-alpha.1" },
282
+ { packageName: "package", version: "1.0.0-rc.1" },
283
+ ])("identifies each timed publish stage for %j", async (configuration) => {
284
+ await taskRunner({
285
+ ...task,
286
+ logTimings: true,
287
+ configurator: async () => configuration,
288
+ steps: [steps[0]],
289
+ cleanUp: undefined,
290
+ })({});
291
+
292
+ const timingRecords = logSpy.mock.calls
293
+ .filter(([line]) => line.startsWith("[publish-timing] "))
294
+ .map(([line]) => JSON.parse(line.slice("[publish-timing] ".length)));
295
+
296
+ expect(timingRecords).toEqual([
297
+ expect.objectContaining({
298
+ task: name,
299
+ packageName:
300
+ configuration.pluginPackageJson?.name || configuration.packageName,
301
+ version: configuration.version,
302
+ stage: step1Sstart,
303
+ status: "started",
304
+ }),
305
+ expect.objectContaining({ status: "succeeded" }),
306
+ ]);
307
+ });
308
+
309
+ it("leaves non-publish tasks uninstrumented", async () => {
310
+ await taskRunner({ ...task, cleanUp: undefined })({});
311
+
312
+ expect(logSpy).not.toHaveBeenCalled();
313
+ });
314
+
315
+ it("records the failed stage before the existing error handler", async () => {
316
+ await taskRunner({
317
+ ...task,
318
+ logTimings: true,
319
+ configurator: async () => ({
320
+ packageName: "package",
321
+ version: "1.0.0",
322
+ }),
323
+ steps: [failing_step],
324
+ cleanUp: undefined,
325
+ })({});
326
+
327
+ const lastRecord = JSON.parse(
328
+ logSpy.mock.calls[1][0].slice("[publish-timing] ".length)
329
+ );
330
+
331
+ expect(lastRecord).toEqual(
332
+ expect.objectContaining({ stage: "failing step", status: "failed" })
333
+ );
334
+
335
+ expect(errorSpy).toHaveBeenCalledWith(
336
+ failing_step.error,
337
+ FAILING_STEP_ERROR
338
+ );
339
+
340
+ expect(logSpy.mock.invocationCallOrder[1]).toBeLessThan(
341
+ errorSpy.mock.invocationCallOrder[0]
342
+ );
343
+ });
344
+ });
263
345
  });
@@ -6,6 +6,7 @@
6
6
 
7
7
  const R = require("ramda");
8
8
  const logger = require("../logger");
9
+ const { measurePublishStep } = require("../commands/utils/publishTiming");
9
10
 
10
11
  /**
11
12
  * @typedef step
@@ -27,6 +28,7 @@ const logger = require("../logger");
27
28
  * for the task. invoked with { cliArgs, cliOptions }
28
29
  * @property {step[]} task.steps: array of steps to perform
29
30
  * @property {Function?} task.cleanup: Optional cleanup function to run after the task is finished
31
+ * @property {Boolean?} task.logTimings: Enable publish timing when QB_PUBLISH_TIMINGS is true
30
32
  */
31
33
 
32
34
  /**
@@ -85,13 +87,27 @@ async function gatherConfiguration(configurator, { cliArgs, cliOptions }) {
85
87
  * Runs a step within a given task
86
88
  * @param {Object} configuration object built from the configurator function above
87
89
  * @param {step} step within a task - see typedef above
90
+ * @param {String?} taskName: Task name for publish timing records
88
91
  * @returns {Void} returns void to make sure async steps run sequentially
89
92
  */
90
- async function runStep(configuration, step) {
93
+ async function runStep(configuration, step, taskName) {
91
94
  logger.startStep(step.start);
92
95
 
93
96
  try {
94
- await step.run(configuration);
97
+ if (taskName) {
98
+ await measurePublishStep(
99
+ step.start,
100
+ {
101
+ task: taskName,
102
+ packageName:
103
+ configuration.pluginPackageJson?.name || configuration.packageName,
104
+ version: configuration.version,
105
+ },
106
+ () => step.run(configuration)
107
+ );
108
+ } else {
109
+ await step.run(configuration);
110
+ }
95
111
  } catch (e) {
96
112
  logger.error(step.error || e.message, e);
97
113
  }
@@ -113,6 +129,7 @@ function taskRunner(task) {
113
129
  configurator = function () {},
114
130
  steps,
115
131
  cleanUp,
132
+ logTimings = false,
116
133
  } = task;
117
134
 
118
135
  return async function (...args) {
@@ -143,7 +160,7 @@ function taskRunner(task) {
143
160
  logger.endStep("configuration retrieved");
144
161
 
145
162
  for (const step of steps) {
146
- await runStep(configuration, step);
163
+ await runStep(configuration, step, logTimings ? name : undefined);
147
164
  }
148
165
 
149
166
  if (cleanUp) {
@@ -32,4 +32,4 @@ exports[`resolveAppTemplate retrieves the template from the provided path if pro
32
32
  }
33
33
  `;
34
34
 
35
- exports[`resolveAppTemplate throws if resolving a template for an unknown platform 1`] = `"could not find template for foo - available templates: ios,android,samsung_tv,lg_tv,vizio,apple_tv,android_tv,amazon"`;
35
+ exports[`resolveAppTemplate throws if resolving a template for an unknown platform 1`] = `"could not find template for foo - available templates: ios,android,samsung_tv,lg_tv,vidaa,vizio,apple_tv,android_tv,amazon"`;
@@ -27,6 +27,7 @@ const templatesMap = {
27
27
  android: "@applicaster/zapp-react-native-cli-template",
28
28
  samsung_tv: "@applicaster/zapp-react-dom-cli-template",
29
29
  lg_tv: "@applicaster/zapp-react-dom-cli-template",
30
+ vidaa: "@applicaster/zapp-react-dom-cli-template",
30
31
  vizio: "@applicaster/zapp-react-dom-cli-template",
31
32
  apple_tv: "@applicaster/zapp-react-native-tvos-cli-template",
32
33
  android_tv: "@applicaster/zapp-react-native-android-tv-cli-template",
@@ -1,5 +0,0 @@
1
- // Jest Snapshot v1, https://goo.gl/fbAQLP
2
-
3
- exports[`publish zappifests it throws if a manifest cannot be found 1`] = `[Error: cannot resolve manifest]`;
4
-
5
- exports[`publish zappifests it throws if the zappifest command fails 1`] = `[Error: zappifest failed]`;