@argos-ci/core 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2022 Smooth Code
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ <p align="center">
2
+ <a href="https://argos-ci.com/?utm_source=github&utm_medium=logo" target="_blank">
3
+ <img src="https://raw.githubusercontent.com/argos-ci/argos/main/resources/logos/logo-github-readme.png" alt="Argos" width="300" height="61">
4
+ </a>
5
+ </p>
6
+
7
+ _Argos is a visual testing solution that fits in your workflow to avoid visual regression. Takes screenshots on each commit and be notified if something changes._
8
+
9
+ # Argos JavaScript SDK Core
10
+
11
+ Argos Core JavaScript SDK contains interface definitions, base classes and utilities for building Argos JavaScript SDKs, like `@argos-ci/cli` or using it directly with Node.js.
12
+
13
+ [![npm version](https://img.shields.io/npm/v/@argos-ci/core.svg)](https://www.npmjs.com/package/@argos-ci/core)
14
+ [![npm dm](https://img.shields.io/npm/dm/@argos-ci/core.svg)](https://www.npmjs.com/package/@argos-ci/core)
15
+ [![npm dt](https://img.shields.io/npm/dt/@argos-ci/core.svg)](https://www.npmjs.com/package/@argos-ci/core)
16
+
17
+ ## Links
18
+
19
+ - [Official SDK Docs](https://docs.argos-ci.com)
20
+ - [API Reference](https://js-sdk-reference.argos-ci.com)
package/dist/index.cjs ADDED
@@ -0,0 +1,5 @@
1
+ exports.upload = async (params)=>{
2
+ // @ts-ignore
3
+ const { upload } = await import('./index.mjs');
4
+ return upload(params);
5
+ };
@@ -0,0 +1,42 @@
1
+ interface UploadParameters {
2
+ /** Globs matching image file paths to upload */
3
+ files?: string[];
4
+ /** Root directory to look for image to upload (default to current directory) */
5
+ root?: string;
6
+ /** Globs matching image file paths to ignore (default to "**\/*.{png,jpg,jpeg}") */
7
+ ignore?: string[];
8
+ /** Base URL of Argos API (default to "https://api.argos-ci.com/v2/") */
9
+ apiBaseUrl?: string;
10
+ /** Git commit */
11
+ commit?: string;
12
+ /** Git branch */
13
+ branch?: string;
14
+ /** Argos repository token */
15
+ token?: string;
16
+ /** Name of the build used to trigger multiple Argos builds on one commit */
17
+ buildName?: string;
18
+ /** Parallel test suite mode */
19
+ parallel?: {
20
+ /** Unique build ID for this parallel build */
21
+ nonce: string;
22
+ /** The number of parallel nodes being ran */
23
+ total: number;
24
+ } | false;
25
+ }
26
+ /**
27
+ * Upload screenshots to argos-ci.com.
28
+ */
29
+ declare const upload: (params: UploadParameters) => Promise<{
30
+ build: {
31
+ id: string;
32
+ url: string;
33
+ };
34
+ screenshots: {
35
+ optimizedPath: string;
36
+ hash: any;
37
+ name: string;
38
+ path: string;
39
+ }[];
40
+ }>;
41
+
42
+ export { UploadParameters, upload };
package/dist/index.mjs ADDED
@@ -0,0 +1,363 @@
1
+ import convict from 'convict';
2
+ import envCi from 'env-ci';
3
+ import { execSync } from 'child_process';
4
+ import { resolve } from 'node:path';
5
+ import glob from 'fast-glob';
6
+ import { promisify } from 'node:util';
7
+ import sharp from 'sharp';
8
+ import tmp from 'tmp';
9
+ import { createReadStream } from 'node:fs';
10
+ import { createHash } from 'node:crypto';
11
+ import axios from 'axios';
12
+ import { readFile } from 'node:fs/promises';
13
+ import createDebug from 'debug';
14
+
15
+ const mustBeApiBaseUrl = (value)=>{
16
+ const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
17
+ if (!URL_REGEX.test(value)) {
18
+ throw new Error("Invalid Argos API base URL");
19
+ }
20
+ };
21
+ const mustBeCommit = (value)=>{
22
+ const SHA1_REGEX = /^[0-9a-f]{40}$/;
23
+ if (!SHA1_REGEX.test(value)) {
24
+ const SHA1_SHORT_REGEX = /^[0-9a-f]{7}$/;
25
+ if (SHA1_SHORT_REGEX.test(value)) {
26
+ throw new Error("Short SHA1 is not allowed");
27
+ }
28
+ throw new Error("Invalid commit");
29
+ }
30
+ };
31
+ const mustBeArgosToken = (value)=>{
32
+ if (value.length !== 40) {
33
+ throw new Error("Must be a valid Argos repository token");
34
+ }
35
+ };
36
+ const schema = {
37
+ apiBaseUrl: {
38
+ env: "ARGOS_API_BASE_URL",
39
+ default: "https://api.argos-ci.com/v2/",
40
+ format: mustBeApiBaseUrl
41
+ },
42
+ commit: {
43
+ env: "ARGOS_COMMIT",
44
+ default: "",
45
+ format: mustBeCommit
46
+ },
47
+ branch: {
48
+ env: "ARGOS_BRANCH",
49
+ default: null,
50
+ format: String,
51
+ nullable: true
52
+ },
53
+ token: {
54
+ env: "ARGOS_TOKEN",
55
+ default: "",
56
+ format: mustBeArgosToken
57
+ },
58
+ buildName: {
59
+ env: "ARGOS_BUILD_NAME",
60
+ default: null,
61
+ format: String,
62
+ nullable: true
63
+ },
64
+ parallel: {
65
+ env: "ARGOS_PARALLEL",
66
+ default: false,
67
+ format: Boolean
68
+ },
69
+ parallelNonce: {
70
+ env: "ARGOS_PARALLEL_NONCE",
71
+ format: String,
72
+ default: null,
73
+ nullable: true
74
+ },
75
+ parallelTotal: {
76
+ env: "ARGOS_PARALLEL_TOTAL",
77
+ format: "nat",
78
+ default: null,
79
+ nullable: true
80
+ },
81
+ ciService: {
82
+ format: String,
83
+ default: null,
84
+ nullable: true
85
+ }
86
+ };
87
+ const createConfig = ()=>{
88
+ return convict(schema, {
89
+ args: []
90
+ });
91
+ };
92
+
93
+ /**
94
+ * Omit undefined properties from an object.
95
+ */ const omitUndefined = (obj)=>{
96
+ const result = {};
97
+ Object.keys(obj).forEach((key)=>{
98
+ if (obj[key] !== undefined) {
99
+ result[key] = obj[key];
100
+ }
101
+ });
102
+ return result;
103
+ };
104
+
105
+ const service$1 = {
106
+ detect: ({ env })=>Boolean(env.HEROKU_TEST_RUN_ID),
107
+ config: ({ env })=>({
108
+ name: "Heroku",
109
+ commit: env.HEROKU_TEST_RUN_COMMIT_VERSION || null,
110
+ branch: env.HEROKU_TEST_RUN_BRANCH || null
111
+ })
112
+ };
113
+
114
+ const getSha = ({ env })=>{
115
+ const isPr = env.GITHUB_EVENT_NAME === "pull_request" || env.GITHUB_EVENT_NAME === "pull_request_target";
116
+ if (isPr) {
117
+ const mergeCommitRegex = /^[a-z0-9]{40} [a-z0-9]{40}$/;
118
+ const mergeCommitMessage = execSync("git show --no-patch --format=%P").toString().trim();
119
+ console.log(`Handling PR with parent hash(es) '${mergeCommitMessage}' of current commit.`);
120
+ if (mergeCommitRegex.exec(mergeCommitMessage)) {
121
+ const mergeCommit = mergeCommitMessage.split(" ")[1];
122
+ console.log(`Fixing merge commit SHA ${process.env.GITHUB_SHA} -> ${mergeCommit}`);
123
+ return mergeCommit;
124
+ } else if (mergeCommitMessage === "") {
125
+ console.error(`
126
+ Issue detecting commit SHA. Please run actions/checkout with "fetch-depth: 2":
127
+
128
+ steps:
129
+ - uses: actions/checkout@v3
130
+ with:
131
+ fetch-depth: 2
132
+ `.trim());
133
+ process.exit(1);
134
+ } else {
135
+ console.error(`Commit with SHA ${process.env.GITHUB_SHA} is not a valid commit`);
136
+ process.exit(1);
137
+ }
138
+ }
139
+ return process.env.GITHUB_SHA ?? null;
140
+ };
141
+ function getBranch({ env }) {
142
+ if (env.GITHUB_HEAD_REF) {
143
+ return env.GITHUB_HEAD_REF;
144
+ }
145
+ const branchRegex = /refs\/heads\/(.*)/;
146
+ const branchMatches = branchRegex.exec(env.GITHUB_REF || "");
147
+ if (branchMatches) {
148
+ return branchMatches[1];
149
+ }
150
+ return null;
151
+ }
152
+ const service = {
153
+ detect: ({ env })=>Boolean(env.GITHUB_ACTIONS),
154
+ config: ({ env })=>({
155
+ name: "GiHub Actions",
156
+ commit: getSha({
157
+ env
158
+ }),
159
+ branch: getBranch({
160
+ env
161
+ })
162
+ })
163
+ };
164
+
165
+ const services = [
166
+ service$1,
167
+ service
168
+ ];
169
+ const getCiEnvironment = ({ env =process.env } = {})=>{
170
+ const ctx = {
171
+ env
172
+ };
173
+ const service = services.find((service)=>service.detect(ctx));
174
+ // Internal service matched
175
+ if (service) {
176
+ return service.config(ctx);
177
+ }
178
+ // Fallback on env-ci detection
179
+ const ciContext = envCi(ctx);
180
+ const name = ciContext.isCi ? ciContext.name ?? null : ciContext.commit ? "Git" : null;
181
+ const commit = ciContext.commit ?? null;
182
+ const branch = ciContext.branch ?? null;
183
+ return commit ? {
184
+ name,
185
+ commit,
186
+ branch
187
+ } : null;
188
+ };
189
+
190
+ const discoverScreenshots = async (patterns, { root =process.cwd() , ignore } = {})=>{
191
+ const matches = await glob(patterns, {
192
+ onlyFiles: true,
193
+ ignore,
194
+ cwd: root
195
+ });
196
+ return matches.map((match)=>({
197
+ name: match,
198
+ path: resolve(root, match)
199
+ }));
200
+ };
201
+
202
+ const tmpFile = promisify(tmp.file);
203
+ const optimizeScreenshot = async (filepath)=>{
204
+ const resultFilePath = await tmpFile();
205
+ await sharp(filepath).resize(1024, 1024, {
206
+ fit: "inside",
207
+ withoutEnlargement: true
208
+ }).jpeg().toFile(resultFilePath);
209
+ return resultFilePath;
210
+ };
211
+
212
+ const hashFile = async (filepath)=>{
213
+ const fileStream = createReadStream(filepath);
214
+ const hash = createHash("sha256");
215
+ await new Promise((resolve, reject)=>{
216
+ fileStream.on("error", reject);
217
+ hash.on("error", reject);
218
+ hash.on("finish", resolve);
219
+ fileStream.pipe(hash);
220
+ });
221
+ return hash.read().toString("hex");
222
+ };
223
+
224
+ const createArgosApiClient = (options)=>{
225
+ const axiosInstance = axios.create({
226
+ baseURL: options.baseUrl,
227
+ headers: {
228
+ Authorization: `Bearer ${options.token}`,
229
+ "Content-Type": "application/json",
230
+ Accept: "application/json"
231
+ }
232
+ });
233
+ const call = async (method, path, data)=>{
234
+ try {
235
+ const response = await axiosInstance.request({
236
+ method,
237
+ url: path,
238
+ data
239
+ });
240
+ return response.data;
241
+ } catch (error) {
242
+ throw error;
243
+ }
244
+ };
245
+ return {
246
+ createBuild: async (input)=>{
247
+ return call("POST", "/builds", input);
248
+ },
249
+ updateBuild: async (input)=>{
250
+ const { buildId , ...body } = input;
251
+ return call("PUT", `/builds/${buildId}`, body);
252
+ }
253
+ };
254
+ };
255
+
256
+ const upload$1 = async (input)=>{
257
+ const file = await readFile(input.path);
258
+ await axios({
259
+ method: "PUT",
260
+ url: input.url,
261
+ data: file,
262
+ headers: {
263
+ "Content-Type": "image/png"
264
+ }
265
+ });
266
+ };
267
+
268
+ const debug = createDebug("@argos-ci/core");
269
+
270
+ const getConfigFromOptions = (options)=>{
271
+ const { apiBaseUrl , commit , branch , token , buildName , parallel } = options;
272
+ const config = createConfig();
273
+ config.load(omitUndefined({
274
+ apiBaseUrl,
275
+ commit,
276
+ branch,
277
+ token,
278
+ buildName,
279
+ parallel: Boolean(parallel),
280
+ parallelNonce: parallel ? parallel.nonce : null,
281
+ parallelTotal: parallel ? parallel.total : null
282
+ }));
283
+ if (!config.get("commit")) {
284
+ const ciEnv = getCiEnvironment();
285
+ if (ciEnv) {
286
+ config.load(omitUndefined({
287
+ commit: ciEnv.commit,
288
+ branch: ciEnv.branch,
289
+ ciService: ciEnv.name
290
+ }));
291
+ }
292
+ }
293
+ config.validate();
294
+ return config.get();
295
+ };
296
+ /**
297
+ * Upload screenshots to argos-ci.com.
298
+ */ const upload = async (params)=>{
299
+ // Read config
300
+ const config = getConfigFromOptions(params);
301
+ const files = params.files ?? [
302
+ "**/*.{png,jpg,jpeg}"
303
+ ];
304
+ // Collect screenshots
305
+ const foundScreenshots = await discoverScreenshots(files, {
306
+ root: params.root,
307
+ ignore: params.ignore
308
+ });
309
+ // Optimize & compute hashes
310
+ const screenshots = await Promise.all(foundScreenshots.map(async (screenshot)=>{
311
+ const optimizedPath = await optimizeScreenshot(screenshot.path);
312
+ const hash = await hashFile(optimizedPath);
313
+ return {
314
+ ...screenshot,
315
+ optimizedPath,
316
+ hash
317
+ };
318
+ }));
319
+ const apiClient = createArgosApiClient({
320
+ baseUrl: config.apiBaseUrl,
321
+ token: config.token
322
+ });
323
+ // Create build
324
+ debug("Creating build");
325
+ const result = await apiClient.createBuild({
326
+ commit: config.commit,
327
+ branch: config.branch,
328
+ name: config.buildName,
329
+ parallel: config.parallel,
330
+ parallelNonce: config.parallelNonce,
331
+ screenshotKeys: screenshots.map((screenshot)=>screenshot.hash)
332
+ });
333
+ debug("Got screenshots", result);
334
+ // Upload screenshots
335
+ debug("Uploading screenshots");
336
+ await Promise.all(result.screenshots.map(async ({ key , putUrl })=>{
337
+ const screenshot = screenshots.find((s)=>s.hash === key);
338
+ if (!screenshot) {
339
+ throw new Error(`Invariant: screenshot with hash ${key} not found`);
340
+ }
341
+ await upload$1({
342
+ url: putUrl,
343
+ path: screenshot.optimizedPath
344
+ });
345
+ }));
346
+ // Update build
347
+ debug("Updating build");
348
+ await apiClient.updateBuild({
349
+ buildId: result.build.id,
350
+ screenshots: screenshots.map((screenshot)=>({
351
+ key: screenshot.hash,
352
+ name: screenshot.name
353
+ })),
354
+ parallel: config.parallel,
355
+ parallelTotal: config.parallelTotal
356
+ });
357
+ return {
358
+ build: result.build,
359
+ screenshots
360
+ };
361
+ };
362
+
363
+ export { upload };
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@argos-ci/core",
3
+ "description": "Visual testing solution to avoid visual regression. The core component of Argos SDK that handles build creation.",
4
+ "version": "0.1.0",
5
+ "scripts": {
6
+ "prebuild": "rm -rf dist",
7
+ "build": "rollup -c",
8
+ "e2e": "node ./e2e/upload.cjs && node ./e2e/upload.mjs"
9
+ },
10
+ "type": "module",
11
+ "main": "./dist/index.cjs",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "require": "./dist/index.cjs",
16
+ "import": "./dist/index.mjs",
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.mjs"
19
+ },
20
+ "./package.json": "./package.json"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/argos-ci/argos-javascript.git",
25
+ "directory": "packages/core"
26
+ },
27
+ "homepage": "https://github.com/argos-ci/argos-javascript/tree/main/packages/core#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/argos-ci/argos-javascript/issues"
30
+ },
31
+ "engines": {
32
+ "node": ">=16.14.0"
33
+ },
34
+ "license": "MIT",
35
+ "keywords": [
36
+ "argos",
37
+ "automation",
38
+ "test automation",
39
+ "testing",
40
+ "visual testing",
41
+ "regression",
42
+ "visual regression"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "dependencies": {
48
+ "axios": "^0.27.2",
49
+ "convict": "^6.2.3",
50
+ "debug": "^4.3.4",
51
+ "env-ci": "^7.3.0",
52
+ "fast-glob": "^3.2.11",
53
+ "sharp": "^0.30.7",
54
+ "tmp": "^0.2.1"
55
+ },
56
+ "devDependencies": {
57
+ "@types/convict": "^6.1.1",
58
+ "msw": "^0.44.2",
59
+ "rollup": "^2.78.0",
60
+ "rollup-plugin-dts": "^4.2.2",
61
+ "rollup-plugin-swc3": "^0.3.0"
62
+ },
63
+ "gitHead": "ff22c7f1ecf8cbbd1468440b3247d10b3b7b7310"
64
+ }