fabrique 0.0.1 → 0.2.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.
Files changed (45) hide show
  1. package/.editorconfig +7 -0
  2. package/.nvmrc +1 -0
  3. package/.prettierrc +7 -0
  4. package/LICENSE +21 -0
  5. package/README.md +218 -0
  6. package/package.json +24 -9
  7. package/src/actions/create.js +123 -0
  8. package/src/actions/refactor.js +166 -0
  9. package/src/actions/upgrade.js +157 -0
  10. package/src/actions/verdaccio.js +20 -0
  11. package/src/helpers/cmd.js +45 -0
  12. package/src/helpers/fs/exists.js +10 -0
  13. package/src/helpers/fs/explore.js +18 -0
  14. package/src/helpers/fs/read-json-file.js +11 -0
  15. package/src/helpers/fs/write-file-safe.js +13 -0
  16. package/src/helpers/fs/write-json-file.js +12 -0
  17. package/src/helpers/handle-error.js +14 -0
  18. package/src/helpers/list-available-templates.js +11 -0
  19. package/src/helpers/log/log-error.js +7 -0
  20. package/src/helpers/log/log.js +28 -0
  21. package/src/helpers/paths.constant.js +15 -0
  22. package/src/helpers/replace-pattern.js +16 -0
  23. package/src/index.js +43 -0
  24. package/templates/lib/.editorconfig +7 -0
  25. package/templates/lib/.nvmrc +1 -0
  26. package/templates/lib/.prettierrc +7 -0
  27. package/templates/lib/.yarnrc.yml +6 -0
  28. package/templates/lib/CONTRIBUTING.md +40 -0
  29. package/templates/lib/LICENSE +21 -0
  30. package/templates/lib/README.md +15 -0
  31. package/templates/lib/fabrique/actions/build.js +355 -0
  32. package/templates/lib/fabrique/helpers/cmd.js +44 -0
  33. package/templates/lib/fabrique/test/tools.ts +18 -0
  34. package/templates/lib/package.json +30 -0
  35. package/templates/lib/src/add.test.ts +8 -0
  36. package/templates/lib/src/add.ts +3 -0
  37. package/templates/lib/src/style.private.scss +5 -0
  38. package/templates/lib/src/style.scss +5 -0
  39. package/templates/lib/src/sub.private.ts +3 -0
  40. package/templates/lib/src/variables.scss +1 -0
  41. package/templates/lib/tsconfig.build.json +17 -0
  42. package/templates/lib/tsconfig.json +37 -0
  43. package/templates/lib/vitest.config.ts +7 -0
  44. package/tsconfig.json +43 -0
  45. package/index.js +0 -13
@@ -0,0 +1,157 @@
1
+ import { confirm, select } from '@inquirer/prompts';
2
+ import chalk from 'chalk';
3
+ import { mkdir, readFile } from 'node:fs/promises';
4
+ import { join, relative } from 'node:path';
5
+ import { cmd } from '../helpers/cmd.js';
6
+ import { explore } from '../helpers/fs/explore.js';
7
+ import { readJsonFile } from '../helpers/fs/read-json-file.js';
8
+ import { writeFileSafe } from '../helpers/fs/write-file-safe.js';
9
+ import { writeJsonFile } from '../helpers/fs/write-json-file.js';
10
+ import { listAvailableTemplates } from '../helpers/list-available-templates.js';
11
+ import { log } from '../helpers/log/log.js';
12
+ import { ROOT_PATH, getTemplatePath } from '../helpers/paths.constant.js';
13
+
14
+ /**
15
+ * Upgrades an existing library.
16
+ *
17
+ * @return {Promise<void>}
18
+ */
19
+ export async function upgrade({ force = false } = {}) {
20
+ const destinationPath = '.';
21
+
22
+ const version = (await readJsonFile(join(ROOT_PATH, 'package.json'))).version;
23
+ const destinationPackage = await readJsonFile(join(destinationPath, 'package.json'));
24
+
25
+ const templates = await listAvailableTemplates();
26
+ let type;
27
+
28
+ if (Object.hasOwn(destinationPackage, 'fabrique')) {
29
+ type = destinationPackage.fabrique.type;
30
+
31
+ if (!templates.includes(type)) {
32
+ throw new Error(`type must be one of the following: ${templates.join(', ')}.`);
33
+ }
34
+
35
+ if (!force && destinationPackage.fabrique.version === version) {
36
+ log('warn', 'Library already up-to-date.');
37
+ if (
38
+ !(await confirm({
39
+ message: 'Force the update ?',
40
+ default: false,
41
+ }))
42
+ ) {
43
+ return;
44
+ }
45
+ }
46
+ } else {
47
+ if (!force) {
48
+ log('warn', 'Not a "fabrique" lib.');
49
+ if (
50
+ !(await confirm({
51
+ message: 'Upgrade anyway ?',
52
+ default: true,
53
+ }))
54
+ ) {
55
+ return;
56
+ }
57
+ }
58
+ type = await select({
59
+ message: 'Select a type',
60
+ choices: templates.map((template) => {
61
+ return {
62
+ value: template,
63
+ };
64
+ }),
65
+ default: templates[0],
66
+ });
67
+ }
68
+
69
+ console.log(chalk.magentaBright('Upgrading the library...'));
70
+
71
+ const templatePath = getTemplatePath(type);
72
+
73
+ await Promise.all([
74
+ upgradeFiles(templatePath, destinationPath),
75
+ upgradePackage({
76
+ templatePath,
77
+ destinationPath,
78
+ destinationPackage,
79
+ fabriqueConfig: {
80
+ version,
81
+ type,
82
+ },
83
+ }),
84
+ ]);
85
+
86
+ // update dependencies
87
+ await cmd('yarn', [], {
88
+ cwd: destinationPath,
89
+ });
90
+
91
+ log('success', `Library ${JSON.stringify(destinationPackage.name)} updated.`);
92
+ }
93
+
94
+ async function upgradeFiles(templatePath, destinationPath) {
95
+ // files to exclude
96
+ const exclude = [
97
+ /^src(?:\/.*)?$/,
98
+ /^README\.md$/,
99
+ /^LICENSE$/,
100
+ /^package\.json$/,
101
+ /^yarn\.lock$/,
102
+ ];
103
+
104
+ for await (const [path, stats] of explore(templatePath)) {
105
+ const entryRelativePath = relative(templatePath, path);
106
+ const entryDestinationPath = join(destinationPath, entryRelativePath);
107
+
108
+ if (exclude.every((exclude) => !exclude.test(entryRelativePath))) {
109
+ if (stats.isFile()) {
110
+ console.log(chalk.yellowBright('override:'), entryRelativePath);
111
+ await writeFileSafe(entryDestinationPath, await readFile(path, { encoding: 'utf8' }));
112
+ } else if (stats.isDirectory()) {
113
+ await mkdir(entryDestinationPath, { recursive: true });
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Upgrades the destination `package.json`.
121
+ *
122
+ * @param {string} templatePath
123
+ * @param {string} destinationPath
124
+ * @param {any} destinationPackage
125
+ * @param {{version: string; type: string;}} fabriqueConfig
126
+ * @return {Promise<void>}
127
+ */
128
+ async function upgradePackage({
129
+ templatePath,
130
+ destinationPath,
131
+ destinationPackage,
132
+ fabriqueConfig,
133
+ }) {
134
+ const templatePackage = await readJsonFile(join(templatePath, 'package.json'));
135
+
136
+ const newPackageJson = {
137
+ ...templatePackage,
138
+ ...destinationPackage,
139
+ scripts: {
140
+ ...Object.fromEntries(
141
+ Object.entries(destinationPackage.scripts ?? {}).filter(([key, value]) => {
142
+ return !key.startsWith('fb:');
143
+ }),
144
+ ),
145
+ ...templatePackage.scripts,
146
+ },
147
+ devDependencies: {
148
+ ...destinationPackage.devDependencies,
149
+ ...templatePackage.devDependencies,
150
+ },
151
+ packageManager: templatePackage.packageManager,
152
+ fabrique: fabriqueConfig,
153
+ };
154
+
155
+ console.log(chalk.yellowBright('merge:'), 'package.json');
156
+ await writeJsonFile(join(destinationPath, 'package.json'), newPackageJson);
157
+ }
@@ -0,0 +1,20 @@
1
+ import { cmd } from '../helpers/cmd.js';
2
+
3
+ /**
4
+ * Lanches verdaccio
5
+ */
6
+ export async function verdaccio() {
7
+ /*
8
+ import { dirname } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ const cwd = dirname(fileURLToPath(import.meta.url));
11
+ */
12
+ // lsof -i tcp:4873 | awk '/4873/{print $2}' | xargs kill
13
+
14
+ try {
15
+ await cmd('verdaccio', ['--listen', '0.0.0.0:4873']);
16
+ } catch {
17
+ await cmd('npm', ['install', '--global', 'verdaccio']);
18
+ await cmd('verdaccio', ['--listen', '0.0.0.0:4873']);
19
+ }
20
+ }
@@ -0,0 +1,45 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ /**
4
+ * Runs "command" into the terminal.
5
+ * @param {string} command
6
+ * @param {readonly string[]} args
7
+ * @param {SpawnOptions | undefined} options
8
+ */
9
+ export async function cmd(command, args = [], options) {
10
+ return new Promise((resolve, reject) => {
11
+ console.log(`> ${command} ${args.join(' ')}`);
12
+
13
+ const childProcess = spawn(command, args, {
14
+ cwd: process.cwd(),
15
+ shell: process.platform === 'win32',
16
+ detached: false,
17
+ stdio: 'inherit',
18
+ ...options,
19
+ });
20
+
21
+ childProcess.on('exit', (code) => {
22
+ if (code === 0) {
23
+ resolve();
24
+ } else {
25
+ reject(new Error(`Exit with code ${code}.`));
26
+ }
27
+ });
28
+
29
+ childProcess.on('error', (err) => {
30
+ reject(err);
31
+ });
32
+
33
+ // process.on('SIGINT', () => {
34
+ // childProcess.kill('SIGINT');
35
+ // });
36
+ //
37
+ // process.on('SIGTERM', () => {
38
+ // childProcess.kill('SIGTERM');
39
+ // });
40
+ //
41
+ // process.on('SIGBREAK', () => {
42
+ // childProcess.kill('SIGBREAK');
43
+ // });
44
+ });
45
+ }
@@ -0,0 +1,10 @@
1
+ import { access, constants } from 'node:fs/promises';
2
+
3
+ export async function exists(path, mode = constants.R_OK) {
4
+ try {
5
+ await access(path, mode);
6
+ return true;
7
+ } catch {
8
+ return false;
9
+ }
10
+ }
@@ -0,0 +1,18 @@
1
+ import { lstat, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ /**
5
+ * @param {string} path
6
+ * @return {AsyncGenerator<readonly [path: string, stats: Stats]>}
7
+ */
8
+ export async function* explore(path) {
9
+ const stats = await lstat(path);
10
+ yield [path, stats];
11
+
12
+ if (stats.isDirectory()) {
13
+ const files = await readdir(path);
14
+ for (const file of files) {
15
+ yield* explore(join(path, file));
16
+ }
17
+ }
18
+ }
@@ -0,0 +1,11 @@
1
+ import { readFile } from 'node:fs/promises';
2
+
3
+ /**
4
+ * Reads a json file.
5
+ *
6
+ * @param {string} path
7
+ * @return {Promise<any>}
8
+ */
9
+ export async function readJsonFile(path) {
10
+ return JSON.parse(await readFile(path, { encoding: 'utf8' }));
11
+ }
@@ -0,0 +1,13 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+
4
+ /**
5
+ * @param {string} path
6
+ * @param {string|NodeJS.ArrayBufferView} content
7
+ * @param {any?} options
8
+ * @return {Promise<void>}
9
+ */
10
+ export async function writeFileSafe(path, content, options) {
11
+ await mkdir(dirname(path), { recursive: true });
12
+ await writeFile(path, content, options);
13
+ }
@@ -0,0 +1,12 @@
1
+ import { writeFileSafe } from './write-file-safe.js';
2
+
3
+ /**
4
+ * Write a json file.
5
+ *
6
+ * @param {string} path
7
+ * @param {json} any
8
+ * @return {Promise<void>}
9
+ */
10
+ export function writeJsonFile(path, json) {
11
+ return writeFileSafe(path, JSON.stringify(json, null, 2));
12
+ }
@@ -0,0 +1,14 @@
1
+ import { logError } from './log/log-error.js';
2
+
3
+ export function handleError(callback) {
4
+ return (...args) => {
5
+ try {
6
+ const result = callback(...args);
7
+ if (result instanceof Promise) {
8
+ return result.catch(logError);
9
+ }
10
+ } catch (error) {
11
+ logError(error);
12
+ }
13
+ };
14
+ }
@@ -0,0 +1,11 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { TEMPLATES_PATH } from './paths.constant.js';
3
+
4
+ /**
5
+ * List the available templates.
6
+ *
7
+ * @return {Promise<string[]>}
8
+ */
9
+ export function listAvailableTemplates() {
10
+ return readdir(TEMPLATES_PATH);
11
+ }
@@ -0,0 +1,7 @@
1
+ import { log } from './log.js';
2
+
3
+ export function logError(error) {
4
+ log('error', error.message);
5
+ console.log('\n----------------------------------\n');
6
+ console.log(error);
7
+ }
@@ -0,0 +1,28 @@
1
+ import chalk from 'chalk';
2
+
3
+ /**
4
+ * @param {'none' | 'error' | 'warn' | 'success'} type
5
+ * @param {string} message
6
+ */
7
+ export function log(type, message) {
8
+ if (type === 'none') {
9
+ console.log(message);
10
+ } else {
11
+ let color;
12
+ switch (type) {
13
+ case 'warn':
14
+ color = chalk.yellowBright;
15
+ break;
16
+ case 'error':
17
+ color = chalk.redBright;
18
+ break;
19
+ case 'success':
20
+ color = chalk.greenBright;
21
+ break;
22
+ default:
23
+ throw new Error('Invalid type');
24
+ }
25
+
26
+ console.log(color(`${chalk.bold(`[${type.toUpperCase()}]:`)} ${message}`));
27
+ }
28
+ }
@@ -0,0 +1,15 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ export const ROOT_PATH = join(dirname(fileURLToPath(import.meta.url)), '../..');
5
+ export const TEMPLATES_PATH = join(ROOT_PATH, 'templates');
6
+
7
+ /**
8
+ * Returns the template path from its name.
9
+ *
10
+ * @param {string} name
11
+ * @return {string}
12
+ */
13
+ export function getTemplatePath(name) {
14
+ return join(TEMPLATES_PATH, name);
15
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Replaces some patterns (`{{name}}`) into content.
3
+ *
4
+ * @param {string} content
5
+ * @param {Record<string, string>} values
6
+ * @return {string}
7
+ */
8
+ export function replacePattern(content, values) {
9
+ return content.replace(/\{\{(\w+)\}\}/g, (_, pattern) => {
10
+ if (Object.hasOwn(values, pattern)) {
11
+ return values[pattern];
12
+ } else {
13
+ throw new Error(`Unknown pattern ${JSON.stringify(pattern)}.`);
14
+ }
15
+ });
16
+ }
package/src/index.js ADDED
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from 'commander';
4
+ import { create } from './actions/create.js';
5
+ import { refactor } from './actions/refactor.js';
6
+ import { upgrade } from './actions/upgrade.js';
7
+ import { verdaccio } from './actions/verdaccio.js';
8
+ import { handleError } from './helpers/handle-error.js';
9
+ import pkg from '../package.json' with { type: 'json' };
10
+
11
+ // tuto: https://medium.com/nmc-techblog/building-a-cli-with-node-js-in-2024-c278802a3ef5
12
+
13
+ program.name('fabrique').description('CLI to build typescript libraries.').version(pkg.version);
14
+
15
+ // CMD: create <type> <name>
16
+ program
17
+ .command('create')
18
+ .description('create a new library')
19
+ .argument('<type>', 'type')
20
+ .argument('<name>', 'name')
21
+ .action(handleError(create));
22
+
23
+ // CMD: upgrade
24
+ program
25
+ .command('upgrade')
26
+ .description('upgrade an existing library')
27
+ .option('--force', 'forces the update', false)
28
+ .action(handleError(upgrade));
29
+
30
+ // CMD: refactor <from> <to>
31
+ program
32
+ .command('refactor')
33
+ .description('refactor recursively many files')
34
+ .argument('<from>', 'from')
35
+ .argument('<to>', 'to')
36
+ .option('--dry', 'runs without modifying the files', false)
37
+ .option('--cwd', 'common working directory', process.cwd)
38
+ .action(handleError(refactor));
39
+
40
+ // CMD: verdaccio
41
+ program.command('verdaccio').description('lanches verdaccio').action(handleError(verdaccio));
42
+
43
+ program.parse();
@@ -0,0 +1,7 @@
1
+ [*]
2
+ charset = utf-8
3
+ insert_final_newline = true
4
+ end_of_line = lf
5
+ indent_style = space
6
+ indent_size = 2
7
+ max_line_length = 100
@@ -0,0 +1 @@
1
+ v22
@@ -0,0 +1,7 @@
1
+ {
2
+ "singleQuote": true,
3
+ "printWidth": 100,
4
+ "singleAttributePerLine": true,
5
+ "organizeImportsSkipDestructiveCodeActions": true,
6
+ "plugins": ["prettier-plugin-organize-imports"]
7
+ }
@@ -0,0 +1,6 @@
1
+ nodeLinker: node-modules
2
+
3
+ npmRegistryServer: "http://localhost:4873"
4
+
5
+ unsafeHttpWhitelist:
6
+ - localhost
@@ -0,0 +1,40 @@
1
+ # Contributing
2
+
3
+ This projet is open to everyone. Feel free to test the library, share it, improve it, and create merge requests.
4
+
5
+ ### Getting started
6
+
7
+ The library requires [Node.js](https://nodejs.org/en) `22+` and [yarn](https://yarnpkg.com/).
8
+
9
+ First, we have to switch to the correct version of node:
10
+
11
+ ```shell
12
+ nvm use
13
+ ```
14
+
15
+ If you don't have [nvm](https://github.com/nvm-sh/nvm), you may manually install and use Node.js 22+.
16
+
17
+ Then, we have to use the proper package manager (here `yarn`):
18
+
19
+ ```shell
20
+ corepack enable
21
+ ```
22
+
23
+ And install the dependencies:
24
+
25
+ ```shell
26
+ yarn install
27
+ ```
28
+
29
+ ### Code
30
+
31
+ - The source code is located in the `src` directory.
32
+ - The projet uses [prettier](https://prettier.io/) to format the code. You'll want to enable and configure it in your IDE.
33
+ - The tests are run with [vitest](https://vitest.dev)
34
+
35
+ ### Commands
36
+
37
+ - `fb:build`: builds the library.
38
+ - `fb:format`: formats the code using `prettier`.
39
+ - `fb:test`: runs the tests using `vitest`.
40
+ - `fb:dev`: builds the lib in `dev` mode, and publishes it on a local `verdaccio`.
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2024 {{author}}
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,15 @@
1
+ [![npm (scoped)](https://img.shields.io/npm/v/{{libname}}.svg)](https://www.npmjs.com/package/{{libname}})
2
+ ![npm](https://img.shields.io/npm/dm/{{libname}}.svg)
3
+ ![NPM](https://img.shields.io/npm/l/{{libname}}.svg)
4
+ ![npm type definitions](https://img.shields.io/npm/types/{{libname}}.svg)
5
+
6
+ ## {{libname}}
7
+
8
+
9
+ ## 📦 Installation
10
+
11
+ ```shell
12
+ yarn add {{libname}}
13
+ # or
14
+ npm install {{libname}} --save
15
+ ```