salat 3.2.0 → 3.3.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.
package/dist/app.js CHANGED
@@ -1,31 +1,26 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
2
  // Project's dependencies
8
- const chalk_1 = __importDefault(require("chalk"));
9
- const utils_1 = require("./utils");
3
+ import { displayResult, getCityId, getCityName, getData, parsePrayerTimesFromResponse, } from "#utils";
4
+ import chalk from "chalk";
10
5
  // Project's data
11
- const constants_1 = require("./constants");
12
- const cities_json_1 = __importDefault(require("./data/cities.json"));
6
+ import { BANNER, LOCAL_STORAGE_PATH } from "#constants";
7
+ import citiesData from "./data/cities.json" with { type: "json" };
13
8
  // Setting up localStorage
14
- const node_localstorage_1 = require("node-localstorage");
9
+ import { LocalStorage } from "node-localstorage";
15
10
  const args = process.argv;
16
11
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
17
12
  // Logging function
18
- const green = (msg) => console.log(chalk_1.default.green(msg));
13
+ const green = (msg) => console.log(chalk.green(msg));
19
14
  // Cast citiesData to City[] properly
20
- const cities = cities_json_1.default;
21
- const localStorage = new node_localstorage_1.LocalStorage(constants_1.LOCAL_STORAGE_PATH);
15
+ const cities = citiesData;
16
+ const localStorage = new LocalStorage(LOCAL_STORAGE_PATH);
22
17
  const cityNameArg = args[2];
23
- const cityName = (0, utils_1.getCityName)(cityNameArg, cities);
18
+ const cityName = getCityName(cityNameArg, cities);
24
19
  // Convert string ID to number since getCityId returns number and getData expects number
25
- const cityId = (0, utils_1.getCityId)(cityName, cities);
20
+ const cityId = getCityId(cityName, cities);
26
21
  const main = async () => {
27
22
  // Printing a banner ('cause I'm cool and I can do it XD)
28
- green(constants_1.BANNER);
23
+ green(BANNER);
29
24
  const storageKey = `${cityName.toLowerCase()}_${new Date().toLocaleDateString()}`;
30
25
  let item = localStorage.getItem(storageKey);
31
26
  // Disable localStorage for local development
@@ -39,8 +34,8 @@ const main = async () => {
39
34
  }
40
35
  else {
41
36
  try {
42
- const data = await (0, utils_1.getData)(cityId);
43
- prayers = (0, utils_1.parsePrayerTimesFromResponse)(data);
37
+ const data = await getData(cityId);
38
+ prayers = parsePrayerTimesFromResponse(data);
44
39
  localStorage.setItem(storageKey, JSON.stringify(prayers));
45
40
  }
46
41
  catch (ex) {
@@ -51,7 +46,7 @@ const main = async () => {
51
46
  }
52
47
  }
53
48
  console.clear();
54
- (0, utils_1.displayResult)(prayers, cityName);
49
+ displayResult(prayers, cityName);
55
50
  };
56
51
  (async () => {
57
52
  await main();
package/dist/constants.js CHANGED
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOCAL_STORAGE_PATH = exports.DEFAULT_CITY = exports.NOT_FOUND_ERROR = exports.BANNER = exports.API_URL = void 0;
4
- exports.API_URL = "https://www.habous.gov.ma/prieres/horaire-api.php";
5
- exports.BANNER = ``;
6
- exports.NOT_FOUND_ERROR = `
1
+ export const API_URL = "https://www.habous.gov.ma/prieres/horaire-api.php";
2
+ export const BANNER = ``;
3
+ export const NOT_FOUND_ERROR = `
7
4
  Your city was not found in the list
8
5
  Using the default city
9
6
  ----------------------
10
7
  You may need to check the spelling
11
8
  `;
12
- exports.DEFAULT_CITY = "Marrakech";
13
- exports.LOCAL_STORAGE_PATH = "./storage";
9
+ export const DEFAULT_CITY = "Marrakech";
10
+ export const LOCAL_STORAGE_PATH = "./storage";
package/dist/types.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
package/dist/utils.js CHANGED
@@ -1,45 +1,36 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.displayResult = exports.parsePrayerTimesFromResponse = exports.getData = exports.getCityId = exports.getCityName = void 0;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- const domino_1 = __importDefault(require("domino"));
9
- const node_fetch_1 = __importDefault(require("node-fetch"));
10
- const constants_1 = require("./constants");
11
- const prayers_json_1 = __importDefault(require("./data/prayers.json"));
12
- const error = (msg) => console.log(chalk_1.default.red(msg));
13
- const getCityName = (arg, cities) => {
1
+ import { API_URL, DEFAULT_CITY, NOT_FOUND_ERROR } from "#constants";
2
+ import chalk from "chalk";
3
+ import domino from "domino";
4
+ import fetch from "node-fetch";
5
+ import prayersData from "./data/prayers.json" with { type: "json" };
6
+ const error = (msg) => console.error(chalk.red(msg));
7
+ export const getCityName = (arg, cities) => {
14
8
  if (arg == null)
15
- return constants_1.DEFAULT_CITY;
9
+ return DEFAULT_CITY;
16
10
  const index = getCityIndex(arg, cities);
17
11
  if (index === -1) {
18
- error(constants_1.NOT_FOUND_ERROR);
19
- return constants_1.DEFAULT_CITY;
12
+ error(NOT_FOUND_ERROR);
13
+ return DEFAULT_CITY;
20
14
  }
21
15
  return arg;
22
16
  };
23
- exports.getCityName = getCityName;
24
- const getCityId = (arg, cities) => {
17
+ export const getCityId = (arg, cities) => {
25
18
  const parsed = parseInt(arg);
26
19
  if (parsed && cities.length >= parsed) {
27
20
  return parsed;
28
21
  }
29
22
  return getCityIndex(arg, cities) + 1;
30
23
  };
31
- exports.getCityId = getCityId;
32
24
  const getCityIndex = (city, cities) => cities.map((e) => e.name.toLowerCase()).indexOf(city.toLowerCase());
33
- const getData = async (cityId) => {
34
- const response = await (0, node_fetch_1.default)(`${constants_1.API_URL}?ville=${cityId}`, {});
25
+ export const getData = async (cityId) => {
26
+ const response = await fetch(`${API_URL}?ville=${cityId}`, {});
35
27
  return await response.text();
36
28
  };
37
- exports.getData = getData;
38
- const parsePrayerTimesFromResponse = (response) => {
39
- const window = domino_1.default.createWindow(response);
29
+ export const parsePrayerTimesFromResponse = (response) => {
30
+ const window = domino.createWindow(response);
40
31
  const document = window.document;
41
32
  const tds = document.getElementsByTagName("td");
42
- const prayers = JSON.parse(JSON.stringify(prayers_json_1.default));
33
+ const prayers = JSON.parse(JSON.stringify(prayersData));
43
34
  let j = 0;
44
35
  for (let i = 1; i < tds.length && j < prayers.length; i += 2) {
45
36
  prayers[j].time = tds[i].textContent.trim();
@@ -53,7 +44,6 @@ const parsePrayerTimesFromResponse = (response) => {
53
44
  return acc;
54
45
  }, {});
55
46
  };
56
- exports.parsePrayerTimesFromResponse = parsePrayerTimesFromResponse;
57
47
  function tConv24(time24) {
58
48
  const [hours, minutes] = time24.split(":");
59
49
  const hour = Number(hours);
@@ -64,13 +54,12 @@ function tConv24(time24) {
64
54
  const ampm = hour < 12 ? "AM" : "PM";
65
55
  return `${formattedTime} ${ampm}`;
66
56
  }
67
- const displayResult = (prayers, city) => {
57
+ export const displayResult = (prayers, city) => {
68
58
  if (!prayers)
69
59
  return;
70
60
  console.log(` 🧭 ${city}, Morocco\n\n 📆 ${new Date().toDateString()}\n`);
71
61
  Object.keys(prayers).forEach((key) => {
72
- console.log(` ${chalk_1.default.cyan(key.padEnd(7, " "))} --> ${chalk_1.default.green(tConv24(prayers[key]))}`);
62
+ console.log(` ${chalk.cyan(key.padEnd(7, " "))} --> ${chalk.green(tConv24(prayers[key]))}`);
73
63
  });
74
64
  console.log("\n");
75
65
  };
76
- exports.displayResult = displayResult;
@@ -0,0 +1,75 @@
1
+ import * as constants from '#constants';
2
+ import { getCityId, getCityName, parsePrayerTimesFromResponse } from '#utils';
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ // Mock cities data
5
+ const mockCities = [
6
+ { id: 1, name: 'Casablanca' },
7
+ { id: 2, name: 'Rabat' },
8
+ { id: 3, name: 'Fes' },
9
+ ];
10
+ describe('utils', () => {
11
+ describe('getCityName', () => {
12
+ it('should return the default city if no argument is provided', () => {
13
+ expect(getCityName(undefined, mockCities)).toBe(constants.DEFAULT_CITY);
14
+ });
15
+ it('should return the city name if it exists', () => {
16
+ expect(getCityName('Casablanca', mockCities)).toBe('Casablanca');
17
+ });
18
+ it('should return default city and log error if city does not exist', () => {
19
+ // Spy on console.error using vitest
20
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => { });
21
+ expect(getCityName('UnknownCity', mockCities)).toBe(constants.DEFAULT_CITY);
22
+ // We expect some error message to be logged.
23
+ // The actual implementation logs with chalk.red, so we just check it was called.
24
+ expect(consoleSpy).toHaveBeenCalled();
25
+ consoleSpy.mockRestore();
26
+ });
27
+ it('should be case insensitive', () => {
28
+ expect(getCityName('casablanca', mockCities)).toBe('casablanca');
29
+ expect(getCityName('RaBaT', mockCities)).toBe('RaBaT');
30
+ });
31
+ });
32
+ describe('getCityId', () => {
33
+ it('should return the ID if a number is provided as string', () => {
34
+ expect(getCityId('2', mockCities)).toBe(2);
35
+ });
36
+ it('should return the ID based on index + 1 if name is provided', () => {
37
+ // 'Casablanca' is at index 0, so ID should be 1
38
+ expect(getCityId('Casablanca', mockCities)).toBe(1);
39
+ // 'Rabat' is at index 1, so ID should be 2
40
+ expect(getCityId('Rabat', mockCities)).toBe(2);
41
+ });
42
+ it('should handle case insensitivity for city names', () => {
43
+ expect(getCityId('fes', mockCities)).toBe(3);
44
+ });
45
+ });
46
+ describe('parsePrayerTimesFromResponse', () => {
47
+ it('should parse prayer times correctly from HTML', () => {
48
+ const mockHtml = `
49
+ <html>
50
+ <body>
51
+ <table>
52
+ <tr><td>Fajr</td><td>05:30</td></tr>
53
+ <tr><td>Chourouk</td><td>07:00</td></tr>
54
+ <tr><td>Dhuhr</td><td>12:30</td></tr>
55
+ <tr><td>Asr</td><td>15:45</td></tr>
56
+ <tr><td>Maghrib</td><td>18:20</td></tr>
57
+ <tr><td>Isha</td><td>19:50</td></tr>
58
+ </table>
59
+ </body>
60
+ </html>
61
+ `;
62
+ // Note: The actual implementation expects td elements in a specific order (key, value, key, value...)
63
+ // And it relies on prayersData keys.
64
+ // We need to match the structure expected by the function.
65
+ // The function iterates tds with i=1, i+=2. meaning it takes index 1, 3, 5... as times.
66
+ const results = parsePrayerTimesFromResponse(mockHtml);
67
+ // Based on default prayers.json keys, let's assume we expect those values.
68
+ // Since we mocked the HTML, if the code pushes to 'prayers' array from 'prayersData',
69
+ // and then updates .time property from tds.
70
+ // checking if it returns an object with times
71
+ expect(results).toHaveProperty('Fajr');
72
+ expect(results).toHaveProperty('Dhuhr');
73
+ });
74
+ });
75
+ });
package/package.json CHANGED
@@ -1,24 +1,29 @@
1
1
  {
2
2
  "name": "salat",
3
- "version": "3.2.0",
3
+ "version": "3.3.1",
4
+ "imports": {
5
+ "#*": "./dist/*.js"
6
+ },
4
7
  "description": "Daily Moroccan prayers time, right in your console, at the tip of your fingers",
5
8
  "homepage": "https://kafiln.github.io/salat-cli/",
6
9
  "main": "dist/app.js",
7
10
  "bin": {
8
11
  "salat": "dist/app.js"
9
12
  },
13
+ "type": "module",
10
14
  "dependencies": {
11
- "chalk": "^2.4.2",
15
+ "chalk": "^5.3.0",
12
16
  "domino": "^2.1.6",
13
- "node-fetch": "^2.7.0",
14
- "node-localstorage": "^1.3.1"
17
+ "node-fetch": "^3.3.2",
18
+ "node-localstorage": "^3.0.5"
15
19
  },
16
20
  "scripts": {
17
- "dev": "ts-node src/app.ts",
21
+ "dev": "node --no-warnings --loader ts-node/esm src/app.ts",
18
22
  "build": "tsc",
19
23
  "start": "node dist/app.js",
20
24
  "prestart": "npm run build",
21
- "prepublishOnly": "npm run build"
25
+ "prepublishOnly": "npm run build",
26
+ "test": "vitest run"
22
27
  },
23
28
  "keywords": [
24
29
  "prayers",
@@ -37,6 +42,7 @@
37
42
  "@types/node-localstorage": "^1.3.3",
38
43
  "nodemon": "^3.1.0",
39
44
  "ts-node": "^10.9.2",
40
- "typescript": "^5.9.3"
45
+ "typescript": "^5.9.3",
46
+ "vitest": "^4.0.18"
41
47
  }
42
48
  }
package/src/app.ts CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // Project's dependencies
4
- import chalk from "chalk";
5
4
  import {
6
5
  displayResult,
7
6
  getCityId,
8
7
  getCityName,
9
8
  getData,
10
9
  parsePrayerTimesFromResponse,
11
- } from "./utils";
10
+ } from "#utils";
11
+ import chalk from "chalk";
12
12
 
13
13
  // Project's data
14
- import { BANNER, LOCAL_STORAGE_PATH } from "./constants";
15
- import citiesData from "./data/cities.json";
16
- import { City, PrayerTimes } from "./types";
14
+ import { BANNER, LOCAL_STORAGE_PATH } from "#constants";
15
+ import { City, PrayerTimes } from "#types";
16
+ import citiesData from "./data/cities.json" with { type: "json" };
17
17
 
18
18
  // Setting up localStorage
19
19
  import { LocalStorage } from "node-localstorage";
@@ -0,0 +1,92 @@
1
+
2
+ import * as constants from '#constants';
3
+ import { City } from '#types';
4
+ import { getCityId, getCityName, parsePrayerTimesFromResponse } from '#utils';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+
7
+ // Mock cities data
8
+ const mockCities: City[] = [
9
+ { id: 1, name: 'Casablanca' },
10
+ { id: 2, name: 'Rabat' },
11
+ { id: 3, name: 'Fes' },
12
+ ];
13
+
14
+ describe('utils', () => {
15
+ describe('getCityName', () => {
16
+ it('should return the default city if no argument is provided', () => {
17
+ expect(getCityName(undefined, mockCities)).toBe(constants.DEFAULT_CITY);
18
+ });
19
+
20
+ it('should return the city name if it exists', () => {
21
+ expect(getCityName('Casablanca', mockCities)).toBe('Casablanca');
22
+ });
23
+
24
+ it('should return default city and log error if city does not exist', () => {
25
+ // Spy on console.error using vitest
26
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
27
+
28
+ expect(getCityName('UnknownCity', mockCities)).toBe(constants.DEFAULT_CITY);
29
+
30
+ // We expect some error message to be logged.
31
+ // The actual implementation logs with chalk.red, so we just check it was called.
32
+ expect(consoleSpy).toHaveBeenCalled();
33
+ consoleSpy.mockRestore();
34
+ });
35
+
36
+ it('should be case insensitive', () => {
37
+ expect(getCityName('casablanca', mockCities)).toBe('casablanca');
38
+ expect(getCityName('RaBaT', mockCities)).toBe('RaBaT');
39
+ });
40
+ });
41
+
42
+ describe('getCityId', () => {
43
+ it('should return the ID if a number is provided as string', () => {
44
+ expect(getCityId('2', mockCities)).toBe(2);
45
+ });
46
+
47
+ it('should return the ID based on index + 1 if name is provided', () => {
48
+ // 'Casablanca' is at index 0, so ID should be 1
49
+ expect(getCityId('Casablanca', mockCities)).toBe(1);
50
+ // 'Rabat' is at index 1, so ID should be 2
51
+ expect(getCityId('Rabat', mockCities)).toBe(2);
52
+ });
53
+
54
+ it('should handle case insensitivity for city names', () => {
55
+ expect(getCityId('fes', mockCities)).toBe(3);
56
+ });
57
+ });
58
+
59
+ describe('parsePrayerTimesFromResponse', () => {
60
+ it('should parse prayer times correctly from HTML', () => {
61
+ const mockHtml = `
62
+ <html>
63
+ <body>
64
+ <table>
65
+ <tr><td>Fajr</td><td>05:30</td></tr>
66
+ <tr><td>Chourouk</td><td>07:00</td></tr>
67
+ <tr><td>Dhuhr</td><td>12:30</td></tr>
68
+ <tr><td>Asr</td><td>15:45</td></tr>
69
+ <tr><td>Maghrib</td><td>18:20</td></tr>
70
+ <tr><td>Isha</td><td>19:50</td></tr>
71
+ </table>
72
+ </body>
73
+ </html>
74
+ `;
75
+
76
+ // Note: The actual implementation expects td elements in a specific order (key, value, key, value...)
77
+ // And it relies on prayersData keys.
78
+ // We need to match the structure expected by the function.
79
+ // The function iterates tds with i=1, i+=2. meaning it takes index 1, 3, 5... as times.
80
+
81
+ const results = parsePrayerTimesFromResponse(mockHtml);
82
+
83
+ // Based on default prayers.json keys, let's assume we expect those values.
84
+ // Since we mocked the HTML, if the code pushes to 'prayers' array from 'prayersData',
85
+ // and then updates .time property from tds.
86
+
87
+ // checking if it returns an object with times
88
+ expect(results).toHaveProperty('Fajr');
89
+ expect(results).toHaveProperty('Dhuhr');
90
+ });
91
+ });
92
+ });
package/src/utils.ts CHANGED
@@ -1,11 +1,11 @@
1
+ import { API_URL, DEFAULT_CITY, NOT_FOUND_ERROR } from "#constants";
2
+ import { City, PrayerDef, PrayerTimes } from "#types";
1
3
  import chalk from "chalk";
2
4
  import domino from "domino";
3
5
  import fetch from "node-fetch";
4
- import { API_URL, DEFAULT_CITY, NOT_FOUND_ERROR } from "./constants";
5
- import prayersData from "./data/prayers.json";
6
- import { City, PrayerDef, PrayerTimes } from "./types";
6
+ import prayersData from "./data/prayers.json" with { type: "json" };
7
7
 
8
- const error = (msg: string) => console.log(chalk.red(msg));
8
+ const error = (msg: string) => console.error(chalk.red(msg));
9
9
 
10
10
  export const getCityName = (arg: string | undefined, cities: City[]): string => {
11
11
  if (arg == null) return DEFAULT_CITY;
@@ -0,0 +1,46 @@
1
+
2
+ import { exec } from 'child_process';
3
+ import path from 'path';
4
+ import util from 'util';
5
+ import { describe, expect, it } from 'vitest';
6
+
7
+ import { dirname } from 'path';
8
+ import { fileURLToPath } from 'url';
9
+
10
+ const __filename = fileURLToPath(import.meta.url);
11
+ const __dirname = dirname(__filename);
12
+
13
+ const execPromise = util.promisify(exec);
14
+ const appPath = path.join(__dirname, '../src/app.ts');
15
+
16
+ describe('CLI E2E', () => {
17
+ it('should run and display prayer times for default city', async () => {
18
+ // Running via ts-node to avoid build step dependency in tests
19
+ // using npx ts-node might be slower but works without pre-build
20
+ const { stdout, stderr } = await execPromise(`node --no-warnings --loader ts-node/esm ${appPath}`);
21
+
22
+ expect(stderr).toBe('');
23
+ expect(stdout).toContain('Marrakech'); // Default city
24
+ expect(stdout).toContain('Fajr');
25
+ expect(stdout).toContain('Isha');
26
+ }, 10000); // increase timeout for CLI execution
27
+
28
+ it('should run and display prayer times for a specific city', async () => {
29
+ const { stdout } = await execPromise(`node --no-warnings --loader ts-node/esm ${appPath} "Rabat"`);
30
+
31
+ expect(stdout).toContain('Rabat');
32
+ expect(stdout).toContain('Fajr');
33
+ }, 10000);
34
+
35
+ it('should handle invalid city gracefully', async () => {
36
+ const { stdout } = await execPromise(`node --no-warnings --loader ts-node/esm ${appPath} "InvalidCity"`);
37
+
38
+ // As per utils.ts, it returns default city (Casablanca) and logs error (NOT_FOUND_ERROR)
39
+ // Note: The error is logged to console.log, so it might appear in stdout or just be visible.
40
+ // utils.ts: error(NOT_FOUND_ERROR) -> console.log(chalk.red(msg))
41
+
42
+ expect(stdout).toContain('Marrakech');
43
+ // We might want to check for the error message if it's printed to stdout
44
+ // BUT utils.ts uses console.log for error as well.
45
+ }, 10000);
46
+ });
package/tsconfig.json CHANGED
@@ -1,15 +1,23 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "CommonJS",
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
5
  "rootDir": "./src",
6
6
  "outDir": "./dist",
7
7
  "esModuleInterop": true,
8
8
  "forceConsistentCasingInFileNames": true,
9
9
  "strict": true,
10
10
  "skipLibCheck": true,
11
- "resolveJsonModule": true
11
+ "moduleResolution": "NodeNext",
12
+ "resolveJsonModule": true,
13
+ "baseUrl": "./",
14
+ "paths": {
15
+ "#*": ["./src/*.ts"]
16
+ }
12
17
  },
13
18
  "include": ["src/**/*"],
14
- "exclude": ["node_modules"]
19
+ "exclude": ["node_modules"],
20
+ "ts-node": {
21
+ "esm": true
22
+ }
15
23
  }
@@ -0,0 +1,9 @@
1
+
2
+ import { defineConfig } from 'vitest/config'
3
+
4
+ export default defineConfig({
5
+ test: {
6
+ include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', 'tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
7
+ environment: 'node',
8
+ },
9
+ })