create-platformatic 3.0.0-alpha.1 → 3.0.0-alpha.4

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # create-platformatic
1
+ # create-wattpm
2
2
 
3
3
  Platformatic Creator
4
4
 
package/bin/cli.js ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { checkNodeVersionForServices } from '@platformatic/foundation'
4
+ import { createPlatformatic } from 'create-wattpm'
5
+ import parseArgs from 'minimist'
6
+ import { readFile } from 'node:fs/promises'
7
+ import { join } from 'node:path'
8
+
9
+ checkNodeVersionForServices()
10
+
11
+ const _args = process.argv.slice(2)
12
+ const args = parseArgs(_args, {
13
+ alias: {
14
+ v: 'version'
15
+ }
16
+ })
17
+
18
+ if (args.version) {
19
+ console.log('v' + JSON.parse(await readFile(join(import.meta.dirname, 'package.json'), 'utf8')).version)
20
+ process.exit(0)
21
+ }
22
+
23
+ await createPlatformatic(_args)
package/eslint.config.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict'
1
+ import neostandard from 'neostandard'
2
2
 
3
- module.exports = require('neostandard')({})
3
+ export default neostandard()
package/package.json CHANGED
@@ -1,60 +1,33 @@
1
1
  {
2
2
  "name": "create-platformatic",
3
- "version": "3.0.0-alpha.1",
3
+ "version": "3.0.0-alpha.4",
4
4
  "description": "Create platformatic application interactive tool",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/platformatic/platformatic.git"
8
8
  },
9
- "exports": {
10
- ".": "./bin/create-platformatic.mjs"
11
- },
12
9
  "bin": {
13
- "create-platformatic": "./bin/create-platformatic.mjs"
10
+ "create-platformatic": "./bin/cli.js"
14
11
  },
12
+ "type": "module",
15
13
  "license": "Apache-2.0",
16
14
  "author": "Platformatic Inc. <oss@platformatic.dev> (https://platformatic.dev)",
17
15
  "dependencies": {
18
- "columnify": "^1.6.0",
19
- "commist": "^3.2.0",
20
- "es-main": "^1.3.0",
21
- "execa": "^9.0.0",
22
- "help-me": "^5.0.0",
23
- "inquirer": "^9.2.16",
24
- "minimist": "^1.2.8",
25
- "ora": "^6.3.1",
26
- "pino": "^9.0.0",
27
- "pino-pretty": "^13.0.0",
28
- "resolve": "^1.22.8",
29
- "semver": "^7.6.0",
30
- "strip-ansi": "^7.1.0",
31
- "undici": "^7.0.0",
32
- "which": "^3.0.1",
33
- "@platformatic/generators": "3.0.0-alpha.1",
34
- "@platformatic/utils": "3.0.0-alpha.1"
16
+ "@platformatic/foundation": "3.0.0-alpha.4",
17
+ "create-wattpm": "3.0.0-alpha.4"
35
18
  },
36
19
  "devDependencies": {
37
- "@types/node": "^22.5.0",
38
- "ajv": "^8.12.0",
39
20
  "borp": "^0.20.0",
40
- "c8": "^10.0.0",
41
- "cross-env": "^7.0.3",
42
- "dotenv": "^16.4.5",
43
21
  "eslint": "9",
44
- "esmock": "^2.6.4",
45
- "fastify": "^5.0.0",
46
- "neostandard": "^0.12.0",
47
- "typescript": "~5.8.0",
48
- "yaml": "^2.4.1",
49
- "@platformatic/composer": "3.0.0-alpha.1",
50
- "@platformatic/db": "3.0.0-alpha.1",
51
- "@platformatic/service": "3.0.0-alpha.1",
52
- "@platformatic/runtime": "3.0.0-alpha.1"
22
+ "import-in-the-middle": "^1.14.2",
23
+ "neostandard": "^0.12.0"
24
+ },
25
+ "engines": {
26
+ "node": ">=22.18.0"
53
27
  },
54
28
  "scripts": {
55
- "test:cli": "borp --pattern \"test/cli/*test.mjs\" --timeout=1200000 --concurrency=1",
56
- "test:unit": "pnpm run lint && cross-env NODE_OPTIONS=\"--loader=esmock --no-warnings\" borp --pattern \"test/unit/*test.mjs\" --timeout=1200000 --concurrency=1",
57
- "test": "npm run test:unit && npm run test:cli",
58
- "lint": "eslint"
29
+ "test": "pnpm run lint && borp --timeout 1200000 --concurrency 1",
30
+ "lint": "eslint",
31
+ "license": "license-checker --production --onlyAllow 'Apache-2.0;MIT;ISC;BSD-2-Clause;BSD-3-Clause;CC-BY-4.0;BlueOak-1.0.0'"
59
32
  }
60
33
  }
@@ -0,0 +1,15 @@
1
+ import { execa } from 'execa'
2
+ import { deepStrictEqual } from 'node:assert'
3
+ import { resolve } from 'node:path'
4
+ import { test } from 'node:test'
5
+ import { pathToFileURL } from 'node:url'
6
+
7
+ test('should be an alias for create-wattpm', async t => {
8
+ const { stdout } = await execa(process.argv[0], [
9
+ '--import',
10
+ pathToFileURL(resolve(import.meta.dirname, './loader.js')).toString(),
11
+ resolve(import.meta.dirname, '../bin/cli.js')
12
+ ])
13
+
14
+ deepStrictEqual(stdout.trim(), 'OK')
15
+ })
package/test/loader.js ADDED
@@ -0,0 +1,13 @@
1
+ import { Hook } from 'import-in-the-middle'
2
+ import { register } from 'node:module'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ register('import-in-the-middle/hook.mjs', import.meta.url)
6
+
7
+ // The package name will not work as we are in a pnpm workspace
8
+ // eslint-disable-next-line no-new
9
+ new Hook([fileURLToPath(new URL('../../create-wattpm/lib/index.js', import.meta.url))], function (exported) {
10
+ exported.createPlatformatic = async function () {
11
+ console.log('OK')
12
+ }
13
+ })
@@ -1,27 +0,0 @@
1
- #!/usr/bin/env node
2
- import { checkNodeVersionForServices } from '@platformatic/utils'
3
- import isMain from 'es-main'
4
- import { readFile } from 'fs/promises'
5
- import parseArgs from 'minimist'
6
- import { join } from 'node:path'
7
- import { createPlatformatic } from '../src/index.mjs'
8
-
9
- if (isMain(import.meta)) {
10
- checkNodeVersionForServices()
11
-
12
- const _args = process.argv.slice(2)
13
- const args = parseArgs(_args, {
14
- alias: {
15
- v: 'version'
16
- }
17
- })
18
-
19
- if (args.version) {
20
- console.log('v' + JSON.parse(await readFile(join(import.meta.dirname, 'package.json'), 'utf8')).version)
21
- process.exit(0)
22
- }
23
- await createPlatformatic(_args)
24
- }
25
-
26
- export * from '../src/index.mjs'
27
- export * from '../src/utils.mjs'
@@ -1,108 +0,0 @@
1
- import { execa } from 'execa'
2
-
3
- export const GIT_FIRST_COMMIT_MESSAGE = 'Platformatic project started! 🚀'
4
- export const GIT_MAIN_BRANCH = 'main'
5
-
6
- /**
7
- * Creates a Git repository and performs the initial commit if it doesn't already exist.
8
- *
9
- * This function checks if Git is installed, initializes a Git repository in the specified
10
- * directory if it's not already a Git repository, and performs the initial commit.
11
- *
12
- * @param {import('pino.').BaseLogger} logger - The logger interface for logging messages.
13
- * @param {string} [dir='.'] - The target directory where the Git repository should be created.
14
- */
15
- export async function createGitRepository (logger, dir = '.') {
16
- if (!await isGitInstalled()) {
17
- logger.error('Git is not installed')
18
- return
19
- }
20
-
21
- if (!await gitInit(logger, dir)) {
22
- return
23
- }
24
-
25
- if (!await gitCommit(logger, dir)) {
26
- return
27
- }
28
-
29
- logger.info('Git repository initialized.')
30
- }
31
-
32
- /**
33
- * Checks if Git is installed on the system.
34
- *
35
- * @async
36
- * @returns {Promise<boolean>} A Promise that resolves to true if Git is installed, false otherwise.
37
- */
38
- async function isGitInstalled () {
39
- try {
40
- await execa('git', ['--version'])
41
- return true
42
- } catch (err) {
43
- return false
44
- }
45
- }
46
-
47
- /**
48
- * Checks if a Git repository exists in the specified directory.
49
- *
50
- * @async
51
- * @param {string} dir - The directory to check for a Git repository.
52
- * @returns {Promise<boolean>} A Promise that resolves to true if a Git repository exists in the directory, false otherwise.
53
- */
54
- async function doesGitRepositoryExist (dir) {
55
- try {
56
- await execa('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dir })
57
- return true
58
- } catch (e) {
59
- return false
60
- }
61
- }
62
-
63
- /**
64
- * Initializes a Git repository in the specified directory if it doesn't already exist.
65
- *
66
- * @async
67
- * @param {import('pino.').BaseLogger} - The logger object for logging messages.
68
- * @param {string} dir - The directory where the Git repository should be initialized.
69
- * @returns {Promise<boolean>} A Promise that resolves to true if the Git repository is successfully initialized, false otherwise.
70
- */
71
- async function gitInit (logger, dir) {
72
- try {
73
- if (await doesGitRepositoryExist(dir)) {
74
- logger.info('Git repository already exists.')
75
- return false
76
- }
77
-
78
- await execa('git', ['init', '-b', GIT_MAIN_BRANCH], { cwd: dir })
79
- logger.debug('Git repository initialized.')
80
- return true
81
- } catch (err) {
82
- logger.error('Git repository init failed.')
83
- logger.debug({ err })
84
- return false
85
- }
86
- }
87
-
88
- /**
89
- * Commits changes in a Git repository located in the specified directory.
90
- *
91
- * @async
92
- * @param {import('pino.').BaseLogger} - The logger object for logging messages.
93
- * @param {string} dir - The directory of the Git repository where changes should be committed.
94
- * @returns {Promise<boolean>} A Promise that resolves to true if the Git commit is successful, false otherwise.
95
- */
96
- async function gitCommit (logger, dir) {
97
- try {
98
- await execa('git', ['add', '-A'], { cwd: dir })
99
- await execa('git', ['commit', '-n', '-m', GIT_FIRST_COMMIT_MESSAGE], { cwd: dir })
100
- logger.debug('Git commit done.')
101
- return true
102
- } catch (err) {
103
- console.log(err)
104
- logger.error('Git commit failed.')
105
- logger.debug({ err })
106
- return false
107
- }
108
- }
package/src/index.mjs DELETED
@@ -1,486 +0,0 @@
1
- import { ImportGenerator } from '@platformatic/generators'
2
- import {
3
- createDirectory,
4
- detectApplicationType,
5
- executeWithTimeout,
6
- findConfigurationFileRecursive,
7
- generateDashedName,
8
- getPkgManager,
9
- loadConfigurationFile,
10
- searchJavascriptFiles
11
- } from '@platformatic/utils'
12
- import { execa } from 'execa'
13
- import defaultInquirer from 'inquirer'
14
- import parseArgs from 'minimist'
15
- import { existsSync } from 'node:fs'
16
- import { readFile, writeFile } from 'node:fs/promises'
17
- import { basename, dirname, join, resolve } from 'node:path'
18
- import { fileURLToPath, pathToFileURL } from 'node:url'
19
- import ora from 'ora'
20
- import pino from 'pino'
21
- import pretty from 'pino-pretty'
22
- import resolveModule from 'resolve'
23
- import { request } from 'undici'
24
- import { createGitRepository } from './create-git-repository.mjs'
25
- import { findComposerConfigFile, getUsername, getVersion, say } from './utils.mjs'
26
- const MARKETPLACE_HOST = 'https://marketplace.platformatic.dev'
27
- const defaultStackables = ['@platformatic/service', '@platformatic/composer', '@platformatic/db']
28
-
29
- export async function fetchStackables (marketplaceHost, modules = []) {
30
- const stackables = new Set([...modules, ...defaultStackables])
31
-
32
- // Skip the remote network request if we are running tests
33
- if (process.env.MARKETPLACE_TEST) {
34
- return Array.from(stackables)
35
- }
36
-
37
- let response
38
- try {
39
- response = await executeWithTimeout(request(new URL('/templates', marketplaceHost || MARKETPLACE_HOST)), 5000)
40
- } catch (err) {
41
- // No-op: we just use the default stackables
42
- }
43
-
44
- if (response && response.statusCode === 200) {
45
- for (const stackable of await response.body.json()) {
46
- stackables.add(stackable.name)
47
- }
48
- }
49
-
50
- return Array.from(stackables)
51
- }
52
-
53
- export async function chooseStackable (inquirer, stackables) {
54
- const options = await inquirer.prompt({
55
- type: 'list',
56
- name: 'type',
57
- message: 'Which kind of service do you want to create?',
58
- default: stackables[0],
59
- choices: stackables
60
- })
61
-
62
- return options.type
63
- }
64
-
65
- async function getPackageVersion (pkg, projectDir) {
66
- let main
67
- try {
68
- main = import.meta.resolve(pkg)
69
- } catch {
70
- main = resolveModule.sync(pkg, { basedir: projectDir })
71
- }
72
-
73
- if (main.startsWith('file:')) {
74
- main = fileURLToPath(main)
75
- }
76
-
77
- let root = dirname(main)
78
-
79
- while (!existsSync(join(root, 'package.json'))) {
80
- const parent = dirname(root)
81
-
82
- if (parent === root) {
83
- // We reached the root of the filesystem
84
- throw new Error(`Could not find package.json for ${pkg}.`)
85
- }
86
-
87
- root = parent
88
- }
89
-
90
- const packageJsonPath = JSON.parse(await readFile(join(root, 'package.json'), 'utf-8'))
91
- return packageJsonPath.version
92
- }
93
-
94
- async function importOrLocal ({ pkgManager, name, projectDir, pkg }) {
95
- try {
96
- return await import(pkg)
97
- } catch (err) {
98
- try {
99
- const fileToImport = resolveModule.sync(pkg, { basedir: projectDir })
100
- return await import(pathToFileURL(fileToImport))
101
- } catch {
102
- // No-op
103
- }
104
-
105
- let version = ''
106
-
107
- if (defaultStackables.includes(pkg) || pkg === '@platformatic/runtime') {
108
- // Let's find if we are using one of the default stackables
109
- // If we are, we have to use the "local" version of the package
110
-
111
- const meta = await JSON.parse(await readFile(join(import.meta.dirname, '..', 'package.json'), 'utf-8'))
112
- if (meta.version.includes('-')) {
113
- version = `@${meta.version}`
114
- } else {
115
- version = `@^${meta.version}`
116
- }
117
- }
118
-
119
- const spinner = ora(`Installing ${pkg + version} using ${pkgManager} ...`).start()
120
- const args = []
121
-
122
- if (pkgManager === 'pnpm' && existsSync(resolve(projectDir, 'pnpm-workspace.yaml'))) {
123
- args.push('-w')
124
- }
125
-
126
- await execa(pkgManager, ['install', ...args, pkg + version], { cwd: projectDir })
127
- spinner.succeed()
128
-
129
- const fileToImport = resolveModule.sync(pkg, { basedir: projectDir })
130
- return await import(pathToFileURL(fileToImport))
131
- }
132
- }
133
-
134
- async function findApplicationRoot (projectDir) {
135
- if (existsSync(resolve(projectDir, 'package.json'))) {
136
- return projectDir
137
- }
138
-
139
- const files = await searchJavascriptFiles(projectDir)
140
-
141
- if (files.length > 0) {
142
- return dirname(resolve(projectDir, files[0]))
143
- }
144
-
145
- return null
146
- }
147
-
148
- export async function wrapApplication (
149
- logger,
150
- inquirer,
151
- packageManager,
152
- module,
153
- install,
154
- projectDir,
155
- additionalGeneratorOptions = {},
156
- additionalGeneratorConfig = {}
157
- ) {
158
- const projectName = basename(projectDir)
159
-
160
- const runtime = await importOrLocal({
161
- pkgManager: packageManager,
162
- name: projectName,
163
- projectDir,
164
- pkg: '@platformatic/runtime'
165
- })
166
-
167
- const generator = new runtime.WrappedGenerator({
168
- logger,
169
- module,
170
- name: projectName,
171
- inquirer,
172
- ...additionalGeneratorOptions
173
- })
174
- generator.setConfig({
175
- ...generator.config,
176
- ...additionalGeneratorConfig,
177
- targetDirectory: projectDir,
178
- typescript: false
179
- })
180
-
181
- await generator.ask()
182
- await generator.prepare()
183
- await generator.writeFiles()
184
-
185
- if (install) {
186
- logger.info(`Installing dependencies for the application using ${packageManager} ...`)
187
- await execa(packageManager, ['install'], { cwd: projectDir, stdio: 'inherit' })
188
- }
189
-
190
- logger.info(`You are all set! Run \`${packageManager} start\` to start your project.`)
191
- }
192
-
193
- export async function createPlatformatic (argv) {
194
- const args = parseArgs(argv, {
195
- default: {
196
- install: true,
197
- module: []
198
- },
199
- boolean: ['install'],
200
- string: ['global-config', 'marketplace-host', 'module']
201
- })
202
-
203
- const username = await getUsername()
204
- const version = await getVersion()
205
- const greeting = username ? `Hello ${username},` : 'Hello,'
206
- await say(`${greeting} welcome to ${version ? `Platformatic ${version}!` : 'Platformatic!'}`)
207
-
208
- const logger = pino(
209
- pretty({
210
- translateTime: 'SYS:HH:MM:ss',
211
- ignore: 'hostname,pid'
212
- })
213
- )
214
-
215
- const pkgManager = getPkgManager()
216
- const modules = Array.isArray(args.module) ? args.module : [args.module]
217
- await createApplication(logger, pkgManager, modules, args['marketplace-host'], args['install'])
218
- }
219
-
220
- export async function createApplication (
221
- logger,
222
- packageManager,
223
- modules,
224
- marketplaceHost,
225
- install,
226
- additionalGeneratorOptions = {},
227
- additionalGeneratorConfig = {}
228
- ) {
229
- // This is only used for testing for now, but might be useful in the future
230
- const inquirer = process.env.USER_INPUT_HANDLER ? await import(process.env.USER_INPUT_HANDLER) : defaultInquirer
231
-
232
- // Check in the directory and its parents if there is a config file
233
- let shouldChooseProjectDir = true
234
- let projectDir = process.cwd()
235
- const runtimeConfigFile = await findConfigurationFileRecursive(projectDir, null, '@platformatic/runtime')
236
-
237
- if (runtimeConfigFile) {
238
- shouldChooseProjectDir = false
239
- projectDir = dirname(runtimeConfigFile)
240
- } else {
241
- // Check the current directory for suitable config files
242
- const applicationRoot = await findApplicationRoot(projectDir)
243
-
244
- if (applicationRoot) {
245
- // detectApplicationType cannot throw here as findApplicationRoot already checks for the existence of Javascript files
246
- const { name: module, label } = await detectApplicationType(projectDir)
247
-
248
- // Check if the file belongs to a Watt application, this can happen for instance if we executed watt create
249
- // in the services folder
250
- const existingRuntime = await findConfigurationFileRecursive(applicationRoot, null, '@platformatic/runtime')
251
-
252
- if (!existingRuntime) {
253
- // If there is a watt.json file with a runtime property, we assume we already executed watt create and we exit.
254
- const existingService = await findComposerConfigFile(projectDir)
255
-
256
- if (existingService) {
257
- const serviceConfig = await loadConfigurationFile(existingService)
258
-
259
- if (serviceConfig.runtime) {
260
- await say(`The ${label} application has already been wrapped into Watt.`)
261
- return
262
- }
263
- }
264
-
265
- const { shouldWrap } = await inquirer.prompt({
266
- type: 'list',
267
- name: 'shouldWrap',
268
- message: `This folder seems to already contain a ${label} application. Do you want to wrap into Watt?`,
269
- // default: 'yes',
270
- choices: [
271
- { name: 'yes', value: true },
272
- { name: 'no', value: false }
273
- ]
274
- })
275
-
276
- if (shouldWrap) {
277
- return wrapApplication(
278
- logger,
279
- inquirer,
280
- packageManager,
281
- module,
282
- install,
283
- process.cwd(),
284
- additionalGeneratorOptions,
285
- { ...additionalGeneratorConfig, skipTypescript: true }
286
- )
287
- }
288
- } else {
289
- projectDir = dirname(existingRuntime)
290
- shouldChooseProjectDir = false
291
- }
292
- }
293
- }
294
-
295
- if (shouldChooseProjectDir) {
296
- const optionsDir = await inquirer.prompt({
297
- type: 'input',
298
- name: 'dir',
299
- message: 'Where would you like to create your project?',
300
- default: 'platformatic'
301
- })
302
-
303
- projectDir = resolve(process.cwd(), optionsDir.dir)
304
- await createDirectory(projectDir)
305
- process.chdir(projectDir)
306
- }
307
-
308
- const projectName = basename(projectDir)
309
-
310
- const runtime = await importOrLocal({
311
- pkgManager: packageManager,
312
- name: projectName,
313
- projectDir,
314
- pkg: '@platformatic/runtime'
315
- })
316
-
317
- const generator = new runtime.Generator({
318
- logger,
319
- name: projectName,
320
- inquirer,
321
- ...additionalGeneratorOptions
322
- })
323
-
324
- generator.setConfig({
325
- ...generator.config,
326
- ...additionalGeneratorConfig,
327
- targetDirectory: projectDir
328
- })
329
-
330
- await generator.populateFromExistingConfig()
331
- if (generator.existingConfig) {
332
- await say('Using existing configuration ...')
333
- }
334
-
335
- const stackables = await fetchStackables(marketplaceHost, modules)
336
-
337
- const names = generator.existingServices ?? []
338
-
339
- while (true) {
340
- const stackableName = await chooseStackable(inquirer, stackables)
341
- // await say(`Creating a ${stackable} project in ${projectDir}...`)
342
-
343
- const stackable = await importOrLocal({
344
- pkgManager: packageManager,
345
- name: projectName,
346
- projectDir,
347
- pkg: stackableName
348
- })
349
-
350
- const { serviceName } = await inquirer.prompt({
351
- type: 'input',
352
- name: 'serviceName',
353
- message: 'What is the name of the service?',
354
- default: generateDashedName(),
355
- validate: value => {
356
- if (value.length === 0) {
357
- return 'Please enter a name'
358
- }
359
-
360
- if (value.includes(' ')) {
361
- return 'Please enter a name without spaces'
362
- }
363
-
364
- if (names.includes(value)) {
365
- return 'This name is already used, please choose another one.'
366
- }
367
-
368
- return true
369
- }
370
- })
371
-
372
- names.push(serviceName)
373
-
374
- const stackableGenerator = stackable.Generator
375
- ? new stackable.Generator({
376
- logger,
377
- inquirer,
378
- serviceName,
379
- parent: generator,
380
- ...additionalGeneratorOptions
381
- })
382
- : new ImportGenerator({
383
- logger,
384
- inquirer,
385
- serviceName,
386
- module: stackableName,
387
- version: await getPackageVersion(stackableName, projectDir),
388
- parent: generator,
389
- ...additionalGeneratorOptions
390
- })
391
-
392
- stackableGenerator.setConfig({
393
- ...stackableGenerator.config,
394
- ...additionalGeneratorConfig,
395
- serviceName
396
- })
397
-
398
- generator.addService(stackableGenerator, serviceName)
399
-
400
- await stackableGenerator.ask()
401
-
402
- const { shouldBreak } = await inquirer.prompt([
403
- {
404
- type: 'list',
405
- name: 'shouldBreak',
406
- message: 'Do you want to create another service?',
407
- default: false,
408
- choices: [
409
- { name: 'yes', value: false },
410
- { name: 'no', value: true }
411
- ]
412
- }
413
- ])
414
-
415
- if (shouldBreak) {
416
- break
417
- }
418
- }
419
-
420
- let entrypoint = ''
421
- const chooseEntrypoint = names.length > 1 && (!generator.existingConfigRaw || !generator.existingConfigRaw.entrypoint)
422
-
423
- if (chooseEntrypoint) {
424
- const results = await inquirer.prompt([
425
- {
426
- type: 'list',
427
- name: 'entrypoint',
428
- message: 'Which service should be exposed?',
429
- choices: names.map(name => ({ name, value: name }))
430
- }
431
- ])
432
- entrypoint = results.entrypoint
433
- } else {
434
- entrypoint = names[0]
435
- }
436
-
437
- generator.setEntryPoint(entrypoint)
438
-
439
- await generator.ask()
440
- await generator.prepare()
441
-
442
- if (chooseEntrypoint) {
443
- await generator.updateConfigEntryPoint(entrypoint)
444
- }
445
-
446
- await generator.writeFiles()
447
-
448
- // Create project here
449
- if (!generator.existingConfigRaw) {
450
- const { initGitRepository } = await inquirer.prompt({
451
- type: 'list',
452
- name: 'initGitRepository',
453
- message: 'Do you want to init the git repository?',
454
- default: false,
455
- choices: [
456
- { name: 'yes', value: true },
457
- { name: 'no', value: false }
458
- ]
459
- })
460
-
461
- if (initGitRepository) {
462
- await createGitRepository(logger, projectDir)
463
- }
464
- }
465
-
466
- if (packageManager === 'pnpm') {
467
- // add pnpm-workspace.yaml file if needed
468
- const content = `packages:
469
- # all packages in direct subdirs of packages/
470
- - 'services/*'
471
- - 'web/*'`
472
- await writeFile(join(projectDir, 'pnpm-workspace.yaml'), content)
473
- }
474
-
475
- if (typeof install === 'function') {
476
- await install(projectDir, generator.runtimeConfig, packageManager)
477
- } else if (install) {
478
- const spinner = ora('Installing dependencies...').start()
479
- await execa(packageManager, ['install'], { cwd: projectDir })
480
- spinner.succeed()
481
- }
482
-
483
- logger.info('Project created successfully, executing post-install actions...')
484
- await generator.postInstallActions()
485
- logger.info(`You are all set! Run \`${packageManager} start\` to start your project.`)
486
- }
package/src/utils.mjs DELETED
@@ -1,156 +0,0 @@
1
- import { findConfigurationFile } from '@platformatic/utils'
2
- import { execa } from 'execa'
3
- import { access, constants, readFile } from 'fs/promises'
4
- import { createRequire } from 'module'
5
- import { dirname, join, resolve } from 'path'
6
- import * as url from 'url'
7
-
8
- export const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
9
- export const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
10
- const __dirname = url.fileURLToPath(new URL('.', import.meta.url))
11
-
12
- const ansiCodes = {
13
- // Platformatic Green: #21FA90
14
- pltGreen: '\u001B[38;2;33;250;144m',
15
- bell: '\u0007',
16
- reset: '\u001b[0m',
17
- erasePreviousLine: '\u001b[1K'
18
- }
19
-
20
- export async function isFileAccessible (filename, directory) {
21
- try {
22
- const filePath = directory ? resolve(directory, filename) : filename
23
- await access(filePath)
24
- return true
25
- } catch (err) {
26
- return false
27
- }
28
- }
29
- /**
30
- * Gets the username from git config or `whoami` command
31
- * @returns string | null
32
- */
33
- export const getUsername = async () => {
34
- try {
35
- const { stdout } = await execa('git', ['config', 'user.name'])
36
- if (stdout?.trim()) {
37
- return stdout.trim()
38
- }
39
- } catch (err) {
40
- // ignore: git failed
41
- }
42
- try {
43
- const { stdout } = await execa('whoami')
44
- if (stdout?.trim()) {
45
- return stdout.trim()
46
- }
47
- } catch (err) {
48
- // ignore: whoami failed
49
- }
50
-
51
- return null
52
- }
53
- /**
54
- * Get the platformatic package version from package.json
55
- * @returns string
56
- */
57
- /* c8 ignore next 4 */
58
- export const getVersion = async () => {
59
- const data = await readFile(join(import.meta.dirname, '..', 'package.json'), 'utf8')
60
- return JSON.parse(data).version
61
- }
62
-
63
- export async function isDirectoryWriteable (directory) {
64
- try {
65
- await access(directory, constants.R_OK | constants.W_OK)
66
- return true
67
- } catch (err) {
68
- return false
69
- }
70
- }
71
-
72
- export const findConfigFile = async directory => findConfigurationFile(directory)
73
- export const findDBConfigFile = async directory => findConfigurationFile(directory, 'db')
74
- export const findServiceConfigFile = async directory => findConfigurationFile(directory, 'service')
75
- export const findComposerConfigFile = async directory => findConfigurationFile(directory, 'composer')
76
- export const findRuntimeConfigFile = async directory => findConfigurationFile(directory, 'runtime')
77
-
78
- /**
79
- * Gets the version of the specified dependency package from package.json
80
- * @param {string} dependencyName
81
- * @returns string
82
- */
83
- export const getDependencyVersion = async dependencyName => {
84
- const rootPackageJson = join(__dirname, '..', 'package.json')
85
- const packageJsonContents = JSON.parse(await readFile(rootPackageJson, 'utf8'))
86
- const dependencies = packageJsonContents.dependencies
87
- const devDependencies = packageJsonContents.devDependencies
88
- const regexp = /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)/
89
- if (dependencies[dependencyName]) {
90
- const match = dependencies[dependencyName].match(regexp)
91
- if (!match) {
92
- return await resolveWorkspaceDependency(dependencyName)
93
- }
94
- return match[0]
95
- }
96
-
97
- if (devDependencies[dependencyName]) {
98
- const match = devDependencies[dependencyName].match(regexp)
99
- if (!match) {
100
- return await resolveWorkspaceDependency(dependencyName)
101
- }
102
- return match[0]
103
- }
104
-
105
- async function resolveWorkspaceDependency (dependencyName) {
106
- const require = createRequire(import.meta.url)
107
- let dependencyPath = dirname(require.resolve(dependencyName))
108
- // some deps are resolved not at their root level
109
- // for instance 'typescript' will be risolved in its own ./lib directory
110
- // next loop is to find the nearest parent directory that contains a package.json file
111
- while (!(await isFileAccessible(join(dependencyPath, 'package.json')))) {
112
- dependencyPath = join(dependencyPath, '..')
113
- if (dependencyPath === '/') {
114
- throw new Error(`Cannot find package.json for ${dependencyName}`)
115
- }
116
- }
117
- const pathToPackageJson = join(dependencyPath, 'package.json')
118
- const packageJsonFile = await readFile(pathToPackageJson, 'utf-8')
119
- const packageJson = JSON.parse(packageJsonFile)
120
- return packageJson.version
121
- }
122
- }
123
-
124
- export function convertServiceNameToPrefix (serviceName) {
125
- return serviceName.replace(/-/g, '_').toUpperCase()
126
- }
127
-
128
- export function addPrefixToEnv (env, prefix) {
129
- const output = {}
130
- Object.entries(env).forEach(([key, value]) => {
131
- output[`${prefix}_${key}`] = value
132
- })
133
- return output
134
- }
135
-
136
- export async function say (message) {
137
- // Disable if not supporting colors
138
- if (process.env.NO_COLOR) {
139
- console.log(message)
140
- return
141
- }
142
-
143
- const words = message.split(' ')
144
-
145
- for (let i = 0; i <= words.length; i++) {
146
- if (i > 0) {
147
- process.stdout.write('\r' + ansiCodes.erasePreviousLine)
148
- }
149
-
150
- process.stdout.write(ansiCodes.pltGreen + words.slice(0, i).join(' ') + ansiCodes.reset + ansiCodes.bell)
151
- await sleep(randomBetween(75, 100))
152
- }
153
-
154
- process.stdout.write('\n')
155
- await sleep(randomBetween(75, 200))
156
- }