@contember/create 2.2.0-alpha.1 → 2.2.0-alpha.10

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 (96) hide show
  1. package/CLAUDE.md +22 -0
  2. package/dist/development/run.cjs +7 -7
  3. package/dist/development/run.cjs.map +1 -1
  4. package/dist/development/run.js +8 -8
  5. package/dist/development/run.js.map +1 -1
  6. package/dist/development/src/commands/WorkspaceCreateCommand.cjs +27 -13
  7. package/dist/development/src/commands/WorkspaceCreateCommand.cjs.map +1 -1
  8. package/dist/development/src/commands/WorkspaceCreateCommand.js +28 -14
  9. package/dist/development/src/commands/WorkspaceCreateCommand.js.map +1 -1
  10. package/dist/development/src/lib/TemplateInstaller.cjs +72 -60
  11. package/dist/development/src/lib/TemplateInstaller.cjs.map +1 -1
  12. package/dist/development/src/lib/TemplateInstaller.js +72 -60
  13. package/dist/development/src/lib/TemplateInstaller.js.map +1 -1
  14. package/dist/production/run.cjs +7 -7
  15. package/dist/production/run.cjs.map +1 -1
  16. package/dist/production/run.js +8 -8
  17. package/dist/production/run.js.map +1 -1
  18. package/dist/production/src/commands/WorkspaceCreateCommand.cjs +27 -13
  19. package/dist/production/src/commands/WorkspaceCreateCommand.cjs.map +1 -1
  20. package/dist/production/src/commands/WorkspaceCreateCommand.js +28 -14
  21. package/dist/production/src/commands/WorkspaceCreateCommand.js.map +1 -1
  22. package/dist/production/src/lib/TemplateInstaller.cjs +72 -60
  23. package/dist/production/src/lib/TemplateInstaller.cjs.map +1 -1
  24. package/dist/production/src/lib/TemplateInstaller.js +72 -60
  25. package/dist/production/src/lib/TemplateInstaller.js.map +1 -1
  26. package/dist/types/commands/WorkspaceCreateCommand.d.ts +15 -3
  27. package/dist/types/commands/WorkspaceCreateCommand.d.ts.map +1 -1
  28. package/dist/types/lib/FileSystem.d.ts.map +1 -1
  29. package/dist/types/lib/TemplateInstaller.d.ts +9 -1
  30. package/dist/types/lib/TemplateInstaller.d.ts.map +1 -1
  31. package/dist/types/tsconfig.tsbuildinfo +1 -1
  32. package/package.json +2 -2
  33. package/resources/templates/default/README.md +3 -1
  34. package/resources/templates/default/admin/app/components/navigation.tsx +95 -8
  35. package/resources/templates/default/admin/app/pages/tenant.tsx +328 -77
  36. package/resources/templates/default/admin/entrypoint/components/login.tsx +1 -1
  37. package/resources/templates/default/admin/entrypoint/pages/magicLink.tsx +1 -1
  38. package/resources/templates/default/admin/entrypoint/pages/magicLinkSent.tsx +1 -1
  39. package/resources/templates/default/admin/entrypoint/pages/passwordReset.tsx +1 -1
  40. package/resources/templates/default/admin/entrypoint/pages/resetRequest.tsx +1 -1
  41. package/resources/templates/default/admin/entrypoint/pages/resetRequestSuccess.tsx +1 -1
  42. package/resources/templates/default/admin/lib/tenant/config/auth-policy-list.tsx +86 -0
  43. package/resources/templates/default/admin/lib/tenant/config/common.tsx +71 -0
  44. package/resources/templates/default/admin/lib/tenant/config/identity-provider-list.tsx +113 -0
  45. package/resources/templates/default/admin/lib/tenant/config/index.ts +5 -0
  46. package/resources/templates/default/admin/lib/tenant/config/mail-template-list.tsx +108 -0
  47. package/resources/templates/default/admin/lib/tenant/config/tenant-config-view.tsx +182 -0
  48. package/resources/templates/default/admin/lib/tenant/dict.ts +450 -4
  49. package/resources/templates/default/admin/lib/tenant/errors.ts +10 -0
  50. package/resources/templates/default/admin/lib/tenant/forms/add-project-member.tsx +57 -0
  51. package/resources/templates/default/admin/lib/tenant/forms/change-my-profile.tsx +40 -0
  52. package/resources/templates/default/admin/lib/tenant/forms/change-profile.tsx +55 -0
  53. package/resources/templates/default/admin/lib/tenant/forms/common.tsx +9 -2
  54. package/resources/templates/default/admin/lib/tenant/forms/create-global-api-key.tsx +69 -0
  55. package/resources/templates/default/admin/lib/tenant/forms/global-roles-control.tsx +113 -0
  56. package/resources/templates/default/admin/lib/tenant/forms/index.ts +11 -0
  57. package/resources/templates/default/admin/lib/tenant/forms/invite.tsx +42 -4
  58. package/resources/templates/default/admin/lib/tenant/forms/login.tsx +4 -10
  59. package/resources/templates/default/admin/lib/tenant/forms/memberships-control.tsx +3 -1
  60. package/resources/templates/default/admin/lib/tenant/forms/mfa-code-fields.tsx +81 -0
  61. package/resources/templates/default/admin/lib/tenant/forms/passwordless-signin.tsx +4 -10
  62. package/resources/templates/default/admin/lib/tenant/forms/set-person-password.tsx +58 -0
  63. package/resources/templates/default/admin/lib/tenant/forms/set-project-secret.tsx +59 -0
  64. package/resources/templates/default/admin/lib/tenant/forms/sign-up.tsx +73 -0
  65. package/resources/templates/default/admin/lib/tenant/hooks/index.ts +2 -0
  66. package/resources/templates/default/admin/lib/tenant/idp/identity-provider-connections.tsx +124 -0
  67. package/resources/templates/default/admin/lib/tenant/idp/index.ts +1 -0
  68. package/resources/templates/default/admin/lib/tenant/index.ts +7 -0
  69. package/resources/templates/default/admin/lib/tenant/listing/api-key-list.tsx +160 -22
  70. package/resources/templates/default/admin/lib/tenant/listing/auth-log-list.tsx +179 -0
  71. package/resources/templates/default/admin/lib/tenant/listing/global-api-key-list.tsx +149 -0
  72. package/resources/templates/default/admin/lib/tenant/listing/index.ts +7 -0
  73. package/resources/templates/default/admin/lib/tenant/listing/member-delete-dialog.tsx +1 -1
  74. package/resources/templates/default/admin/lib/tenant/listing/member-list.tsx +20 -11
  75. package/resources/templates/default/admin/lib/tenant/listing/mfa.tsx +29 -0
  76. package/resources/templates/default/admin/lib/tenant/listing/person-actions.tsx +179 -0
  77. package/resources/templates/default/admin/lib/tenant/listing/person-detail.tsx +141 -0
  78. package/resources/templates/default/admin/lib/tenant/listing/person-list.tsx +13 -2
  79. package/resources/templates/default/admin/lib/tenant/listing/persons-list.tsx +128 -0
  80. package/resources/templates/default/admin/lib/tenant/listing/project-secret-list.tsx +82 -0
  81. package/resources/templates/default/admin/lib/tenant/otp/backup-codes.tsx +81 -0
  82. package/resources/templates/default/admin/lib/tenant/otp/email-otp-setup.tsx +133 -0
  83. package/resources/templates/default/admin/lib/tenant/otp/index.ts +2 -0
  84. package/resources/templates/default/admin/lib/tenant/security/index.ts +2 -0
  85. package/resources/templates/default/admin/lib/tenant/security/passwordless-toggle.tsx +63 -0
  86. package/resources/templates/default/admin/lib/tenant/security/session-list.tsx +143 -0
  87. package/resources/templates/default/admin/package.json +1 -0
  88. package/resources/templates/default/docker/object-storage/README.md +13 -0
  89. package/resources/templates/default/docker/object-storage/identities.json +13 -0
  90. package/resources/templates/default/docker-compose.yaml +29 -7
  91. package/src/commands/WorkspaceCreateCommand.ts +42 -14
  92. package/src/lib/TemplateInstaller.ts +87 -69
  93. package/src/run.ts +8 -7
  94. package/tests/cases/unit/create-process.test.ts +66 -0
  95. package/tests/cases/unit/template-installer-cleanup.test.ts +150 -0
  96. package/tests/cases/unit/workspace-create.test.ts +81 -0
@@ -18,11 +18,15 @@ services:
18
18
  DEFAULT_DB_USER: 'contember'
19
19
  DEFAULT_DB_PASSWORD: 'contember'
20
20
 
21
+ # The host port, not the service name: the engine only signs URLs here and hands them to the
22
+ # browser, which resolves them itself.
21
23
  DEFAULT_S3_ENDPOINT: 'http://localhost:1483'
22
24
  DEFAULT_S3_BUCKET: 'contember'
23
25
  DEFAULT_S3_REGION: ''
24
26
  DEFAULT_S3_KEY: 'contember'
25
27
  DEFAULT_S3_SECRET: 'contember'
28
+ # A Contember provider name, not the image behind `object-storage`: it selects path-style
29
+ # addressing and no object ACL (public read comes from the store's own config instead).
26
30
  DEFAULT_S3_PROVIDER: 'minio'
27
31
 
28
32
  TENANT_MAILER_HOST: 'mailhog'
@@ -81,19 +85,37 @@ services:
81
85
  timeout: 5s
82
86
  retries: 10
83
87
 
84
- minio:
85
- image: bitnami/minio
88
+ object-storage:
89
+ image: chrislusf/seaweedfs:4.42
90
+
91
+ # `mini` runs master + volume + filer + S3 in a single process. Both flags override a default
92
+ # that would bite you: `autoCreateBucket` is on by default and silently creates a bucket on the
93
+ # first write, so a typo would look like a working upload, and telemetry is on by default and
94
+ # reports to telemetry.seaweedfs.com every 24 h.
95
+ command: >
96
+ mini -dir=/data -s3.port=9000 -s3.config=/etc/seaweedfs/identities.json
97
+ -s3.autoCreateBucket=false -master.telemetry=false
86
98
 
87
99
  environment:
88
- MINIO_ROOT_USER: 'contember'
89
- MINIO_ROOT_PASSWORD: 'contember'
90
- MINIO_DEFAULT_BUCKETS: 'contember:download'
100
+ # Created on start, an existing one left alone. Public read and the signing credentials live
101
+ # in the identities file — see docker/object-storage/README.md.
102
+ S3_BUCKET: 'contember'
91
103
 
92
104
  ports:
93
105
  - '1483:9000'
94
106
 
95
107
  volumes:
96
- - minio-data:/bitnami/minio/data
108
+ - object-storage-data:/data
109
+ - ./docker/object-storage/identities.json:/etc/seaweedfs/identities.json:ro
110
+
111
+ # The S3 port starts answering ~0.5 s before the bucket exists, so probing it (or `/healthz`)
112
+ # would report ready while an upload still fails with `NoSuchBucket`. The filer 404s on a bucket
113
+ # that isn't there yet, so ask it instead.
114
+ healthcheck:
115
+ test: [ 'CMD-SHELL', 'curl -fsS -o /dev/null "http://127.0.0.1:8888/buckets/contember/?limit=1"' ]
116
+ interval: 2s
117
+ timeout: 3s
118
+ retries: 30
97
119
 
98
120
  mailhog:
99
121
  image: mailhog/mailhog
@@ -121,4 +143,4 @@ services:
121
143
 
122
144
  volumes:
123
145
  pgsql-data: ~
124
- minio-data: ~
146
+ object-storage-data: ~
@@ -1,4 +1,4 @@
1
- import { Command, CommandConfiguration, Input } from '@contember/cli-common'
1
+ import { Command, CommandConfiguration, escapeTerminalText, Input, Output } from '@contember/cli-common'
2
2
  import { join } from 'node:path'
3
3
  import chalk from 'chalk'
4
4
  import { TemplateInstaller } from '../lib/TemplateInstaller.js'
@@ -13,9 +13,29 @@ type Options = {
13
13
  template: string
14
14
  }
15
15
 
16
+ export interface WorkspaceCreateResult {
17
+ projectName: string
18
+ projectDirectory: string
19
+ template: string
20
+ packageManager: string
21
+ }
22
+
23
+ export interface WorkspaceCreateRuntime {
24
+ cwd(): string
25
+ getPackageVersion(): Promise<string>
26
+ detectPackageManager(): string
27
+ }
28
+
29
+ const defaultRuntime: WorkspaceCreateRuntime = {
30
+ cwd: () => process.cwd(),
31
+ getPackageVersion,
32
+ detectPackageManager,
33
+ }
34
+
16
35
  export class WorkspaceCreateCommand extends Command<Args, Options> {
17
36
  constructor(
18
- private readonly templateInstaller: TemplateInstaller,
37
+ private readonly templateInstaller: Pick<TemplateInstaller, 'installTemplate'>,
38
+ private readonly runtime: WorkspaceCreateRuntime = defaultRuntime,
19
39
  ) {
20
40
  super()
21
41
  }
@@ -26,35 +46,43 @@ export class WorkspaceCreateCommand extends Command<Args, Options> {
26
46
  configuration.option('template').shortcut('t').valueRequired().description('Template name or remote source')
27
47
  }
28
48
 
29
- protected async execute(input: Input<Args, Options>): Promise<void> {
49
+ protected async execute(input: Input<Args, Options>, output: Output): Promise<void> {
30
50
  const projectName = input.getArgument('projectName')
31
- const projectDirectory = join(process.cwd(), projectName)
32
- const packageManager = detectPackageManager()
51
+ const projectDirectory = join(this.runtime.cwd(), projectName)
52
+ const packageManager = this.runtime.detectPackageManager()
33
53
  const template = input.getOption('template') ?? 'default'
34
54
 
35
55
  await this.templateInstaller.installTemplate(template, projectDirectory, {
36
- version: await getPackageVersion(),
56
+ version: await this.runtime.getPackageVersion(),
37
57
  projectName: projectName,
38
58
  packageManager: packageManager,
39
59
  })
40
60
 
41
- console.log(createDocs(projectDirectory, projectName, packageManager))
61
+ const result: WorkspaceCreateResult = { projectName, projectDirectory, template, packageManager }
62
+ output.data(result, {
63
+ human: value => createDocs(value),
64
+ quiet: value => value.projectDirectory,
65
+ })
42
66
  }
43
67
  }
44
68
 
45
- const createDocs = (projectDirectory: string, projectName: string, packageManager: string) => `
46
- Contember project successfully created in ${projectDirectory}
69
+ const createDocs = ({ projectDirectory, projectName, packageManager }: WorkspaceCreateResult) => {
70
+ const safeProjectDirectory = escapeTerminalText(projectDirectory)
71
+ const safeProjectName = escapeTerminalText(projectName)
72
+ const safePackageManager = escapeTerminalText(packageManager)
73
+ return `
74
+ Contember project successfully created in ${safeProjectDirectory}
47
75
 
48
76
  Next steps:
49
77
 
50
78
  1. Navigate to the project directory:
51
- $ ${chalk.green(`cd ${projectName}`)}
79
+ $ ${chalk.green(`cd ${safeProjectName}`)}
52
80
 
53
81
  2. Install dependencies:
54
- $ ${chalk.green(`${packageManager} install`)}
82
+ $ ${chalk.green(`${safePackageManager} install`)}
55
83
 
56
84
  3. Start the Contember stack:
57
- $ ${chalk.green(`${packageManager} start`)}
85
+ $ ${chalk.green(`${safePackageManager} start`)}
58
86
 
59
87
  Available services:
60
88
 
@@ -67,10 +95,10 @@ ${chalk.bold('API & Backend')}
67
95
 
68
96
  ${chalk.bold('Development Tools')}
69
97
  - PostgreSQL database ${chalk.blue('http://localhost:1482')} ${chalk.grey('credentials: contember / contember')}
70
- - Minio S3 storage ${chalk.blue('http://localhost:1483')}
98
+ - S3 object storage ${chalk.blue('http://localhost:1483')} ${chalk.grey('credentials: contember / contember')}
71
99
  - Mailpit SMTP testing ${chalk.blue('http://localhost:1484')}
72
100
  - Adminer DB manager ${chalk.blue('http://localhost:1485')}
73
- - Minio Dashboard ${chalk.blue('http://localhost:1486')} ${chalk.grey('credentials: contember / contember')}
74
101
 
75
102
  ${chalk.bold('Need help?')} Ask the community: https://github.com/orgs/contember/discussions
76
103
  `
104
+ }
@@ -1,7 +1,18 @@
1
1
  import { join } from 'node:path'
2
- import { FileSystem } from './FileSystem.js'
3
- import jsyaml from 'js-yaml'
4
2
  import degit from 'degit'
3
+ import jsyaml from 'js-yaml'
4
+ import { FileSystem } from './FileSystem.js'
5
+
6
+ interface TemplateInstallerOutput {
7
+ warn(message: string): void
8
+ }
9
+
10
+ type CloneTemplate = (source: string, target: string) => Promise<void>
11
+
12
+ const cloneTemplate: CloneTemplate = async (source, target) => {
13
+ const emitter = degit(source, { cache: false, force: true, verbose: true })
14
+ await emitter.clone(target)
15
+ }
5
16
 
6
17
  export class TemplateInstaller {
7
18
  private localTemplates: Record<string, string>
@@ -9,6 +20,8 @@ export class TemplateInstaller {
9
20
  constructor(
10
21
  private readonly resourceDir: string,
11
22
  private readonly fs: FileSystem,
23
+ private readonly output: TemplateInstallerOutput,
24
+ private readonly clone: CloneTemplate = cloneTemplate,
12
25
  ) {
13
26
  this.localTemplates = {
14
27
  ['default']: join(this.resourceDir, 'templates/default'),
@@ -20,85 +33,90 @@ export class TemplateInstaller {
20
33
  targetDir: string,
21
34
  variables: Record<string, string> = {},
22
35
  ) => {
23
- let removeTemplate = () => {}
36
+ let temporaryTemplateDir: string | undefined
37
+ let remoteTemplate: string | undefined
24
38
 
25
39
  if (this.localTemplates[template]) {
26
40
  template = this.localTemplates[template]
27
41
  } else {
28
- const tmpDir = await this.fs.createTempDir()
29
-
30
- try {
31
- const emitter = degit(template, { cache: false, force: true, verbose: true })
32
- await emitter.clone(tmpDir)
42
+ remoteTemplate = template
43
+ temporaryTemplateDir = await this.fs.createTempDir()
44
+ template = temporaryTemplateDir
45
+ }
33
46
 
34
- removeTemplate = () => {
35
- try {
36
- this.fs.remove(tmpDir, { recursive: true, force: true })
37
- } catch (error) {
38
- console.error(`Failed to clean up template: ${error}`)
39
- }
47
+ try {
48
+ if (remoteTemplate !== undefined) {
49
+ try {
50
+ await this.clone(remoteTemplate, template)
51
+ } catch (error) {
52
+ throw new Error(`Failed to clone template from repository: ${error}`)
40
53
  }
41
-
42
- template = tmpDir
43
- } catch (error) {
44
- throw new Error(`Failed to clone template from repository: ${error}`)
45
54
  }
46
- }
47
55
 
48
- const templateConfigFile = join(template, 'contember.template.yaml')
49
- if (!(await this.fs.pathExists(templateConfigFile))) {
50
- removeTemplate()
51
- throw new Error(`${template} is not a Contember template`)
52
- }
53
- const config = (await this.readYaml(templateConfigFile)) as {
54
- type?: string
55
- remove?: string[]
56
- patchPackageJson?: boolean
57
- rename?: Record<string, string>
58
- copy?: Record<string, string>
59
- replaceVariables?: string[]
60
- }
61
- const nodeModulesDir = join(template, 'node_modules')
62
- const skippedFiles = new Set([...(config.remove || []).map(it => join(template, it)), templateConfigFile])
63
- if (await this.fs.pathExists(targetDir)) {
64
- throw `${targetDir} already exists`
65
- }
66
- await this.fs.copy(template, targetDir, {
67
- filter: src => !src.startsWith(nodeModulesDir) && !skippedFiles.has(src),
68
- })
56
+ const templateConfigFile = join(template, 'contember.template.yaml')
57
+ if (!(await this.fs.pathExists(templateConfigFile))) {
58
+ throw new Error(`${template} is not a Contember template`)
59
+ }
60
+ const config = (await this.readYaml(templateConfigFile)) as {
61
+ type?: string
62
+ remove?: string[]
63
+ patchPackageJson?: boolean
64
+ rename?: Record<string, string>
65
+ copy?: Record<string, string>
66
+ replaceVariables?: string[]
67
+ }
68
+ const nodeModulesDir = join(template, 'node_modules')
69
+ const skippedFiles = new Set([...(config.remove || []).map(it => join(template, it)), templateConfigFile])
70
+ if (await this.fs.pathExists(targetDir)) {
71
+ throw `${targetDir} already exists`
72
+ }
73
+ await this.fs.copy(template, targetDir, {
74
+ filter: src => !src.startsWith(nodeModulesDir) && !skippedFiles.has(src),
75
+ })
69
76
 
70
- removeTemplate()
77
+ if (config.patchPackageJson) {
78
+ await this.replaceFileContent(join(targetDir, 'package.json'), content => {
79
+ const {
80
+ name,
81
+ version,
82
+ 'scripts-template': scripts,
83
+ scripts: _nullScripts,
84
+ license,
85
+ ...json
86
+ } = JSON.parse(content)
87
+ return JSON.stringify({ scripts, ...json }, null, ' ')
88
+ })
89
+ }
90
+ for (const [source, target] of Object.entries(config.rename || {})) {
91
+ await this.fs.rename(join(targetDir, source), join(targetDir, target))
92
+ }
93
+ for (const [source, target] of Object.entries(config.copy || {})) {
94
+ await this.fs.copy(join(targetDir, source), join(targetDir, target))
95
+ }
71
96
 
72
- if (config.patchPackageJson) {
73
- await this.replaceFileContent(join(targetDir, 'package.json'), content => {
74
- const {
75
- name,
76
- version,
77
- 'scripts-template': scripts,
78
- scripts: _nullScripts,
79
- license,
80
- ...json
81
- } = JSON.parse(content)
82
- return JSON.stringify({ scripts, ...json }, null, ' ')
83
- })
84
- }
85
- for (const [source, target] of Object.entries(config.rename || {})) {
86
- await this.fs.rename(join(targetDir, source), join(targetDir, target))
87
- }
88
- for (const [source, target] of Object.entries(config.copy || {})) {
89
- await this.fs.copy(join(targetDir, source), join(targetDir, target))
97
+ for (const file of config.replaceVariables || []) {
98
+ const path = join(targetDir, file)
99
+ if (!(await this.fs.pathExists(path))) {
100
+ continue
101
+ }
102
+ await this.replaceFileContent(path, content =>
103
+ Object.entries(variables).reduce(
104
+ (content, [key, value]) => content.replace(new RegExp(`{${key}}`, 'g'), value),
105
+ content,
106
+ ))
107
+ }
108
+ } finally {
109
+ if (temporaryTemplateDir !== undefined) {
110
+ await this.cleanupTemporaryTemplate(temporaryTemplateDir)
111
+ }
90
112
  }
113
+ }
91
114
 
92
- for (const file of config.replaceVariables || []) {
93
- const path = join(targetDir, file)
94
- if (!(await this.fs.pathExists(path))) {
95
- continue
96
- }
97
- await this.replaceFileContent(path, content =>
98
- Object.entries(variables).reduce(
99
- (content, [key, value]) => content.replace(new RegExp(`{${key}}`, 'g'), value),
100
- content,
101
- ))
115
+ private cleanupTemporaryTemplate = async (path: string): Promise<void> => {
116
+ try {
117
+ await this.fs.remove(path, { recursive: true, force: true })
118
+ } catch {
119
+ this.output.warn('Failed to clean up the temporary template directory.')
102
120
  }
103
121
  }
104
122
 
package/src/run.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import { Application, CommandManager } from '@contember/cli-common'
2
+ import { Application, CommandManager, exitProcess, Output, readGlobalOptionsFromArgs, renderCliError } from '@contember/cli-common'
3
3
  import { WorkspaceCreateCommand } from './commands/index.js'
4
+ import { FileSystem } from './lib/FileSystem.js'
4
5
  import { TemplateInstaller } from './lib/TemplateInstaller.js'
5
6
  import { resourcesDir } from './paths.js'
6
- import { FileSystem } from './lib/FileSystem.js'
7
+
8
+ const output = new Output()
9
+ output.applyGlobalOptions(readGlobalOptionsFromArgs(process.argv.slice(2)))
7
10
  ;(async () => {
8
11
  const commandManager = new CommandManager({
9
12
  ['workspace']: () =>
@@ -11,6 +14,7 @@ import { FileSystem } from './lib/FileSystem.js'
11
14
  new TemplateInstaller(
12
15
  resourcesDir,
13
16
  new FileSystem(),
17
+ output,
14
18
  ),
15
19
  ),
16
20
  })
@@ -19,9 +23,6 @@ import { FileSystem } from './lib/FileSystem.js'
19
23
  if (nodeVersion && Number(nodeVersion[1]) < 18) {
20
24
  throw `Node >= 18 is required`
21
25
  }
22
- const app = new Application(commandManager, `Contember installer`)
26
+ const app = new Application(commandManager, `Contember installer`, output)
23
27
  await app.runCommand('workspace', process.argv.slice(2))
24
- })().catch(e => {
25
- console.log(e)
26
- process.exit(1)
27
- })
28
+ })().catch(error => exitProcess(renderCliError(error, output)))
@@ -0,0 +1,66 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test'
2
+ import { existsSync } from 'node:fs'
3
+ import { mkdtemp, rm } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join, resolve } from 'node:path'
6
+
7
+ const repoRoot = resolve(import.meta.dir, '../../../../..')
8
+ const sourceEntrypoint = join(repoRoot, 'packages/create/src/run.ts')
9
+ const builtEntrypoint = join(repoRoot, 'packages/create/dist/production/run.js')
10
+ const testBuiltCli = process.env.CONTEMBER_TEST_BUILT_CLI === '1'
11
+ const createInvocation = testBuiltCli ? ['node', builtEntrypoint] : ['bun', '--conditions=typescript', sourceEntrypoint]
12
+ const temporaryDirectories: string[] = []
13
+
14
+ afterEach(async () => {
15
+ await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })))
16
+ })
17
+
18
+ const runCreate = async (cwd: string, args: string[]) => {
19
+ if (testBuiltCli && !existsSync(builtEntrypoint)) {
20
+ throw new Error(`Built create entrypoint is missing: ${builtEntrypoint}`)
21
+ }
22
+ const process = Bun.spawn([...createInvocation, ...args], {
23
+ cwd,
24
+ env: { ...Bun.env, NO_COLOR: '1' },
25
+ stdin: 'ignore',
26
+ stdout: 'pipe',
27
+ stderr: 'pipe',
28
+ })
29
+ const [stdout, stderr, exitCode] = await Promise.all([
30
+ new Response(process.stdout).text(),
31
+ new Response(process.stderr).text(),
32
+ process.exited,
33
+ ])
34
+ return { stdout, stderr, exitCode }
35
+ }
36
+
37
+ describe('@contember/create process output', () => {
38
+ test('writes a successful JSON result to stdout only', async () => {
39
+ const cwd = await mkdtemp(join(tmpdir(), 'contember-create-process-'))
40
+ temporaryDirectories.push(cwd)
41
+
42
+ const result = await runCreate(cwd, ['demo', '--json'])
43
+
44
+ expect(result.exitCode).toBe(0)
45
+ expect(result.stderr).toBe('')
46
+ expect(JSON.parse(result.stdout)).toMatchObject({
47
+ projectName: 'demo',
48
+ projectDirectory: join(cwd, 'demo'),
49
+ template: 'default',
50
+ })
51
+ })
52
+
53
+ test('writes a structured JSON error to stderr only', async () => {
54
+ const cwd = await mkdtemp(join(tmpdir(), 'contember-create-process-'))
55
+ temporaryDirectories.push(cwd)
56
+
57
+ const result = await runCreate(cwd, ['--json'])
58
+
59
+ expect(result.exitCode).toBe(1)
60
+ expect(result.stdout).toBe('')
61
+ expect(JSON.parse(result.stderr)).toMatchObject({
62
+ ok: false,
63
+ error: { retryable: false },
64
+ })
65
+ })
66
+ })
@@ -0,0 +1,150 @@
1
+ import { afterEach, describe, expect, test } from 'bun:test'
2
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { Output, OutputMode, OutputStream } from '@contember/cli-common'
6
+ import { FileSystem } from '../../../src/lib/FileSystem.js'
7
+ import { TemplateInstaller } from '../../../src/lib/TemplateInstaller.js'
8
+
9
+ const temporaryDirectories: string[] = []
10
+
11
+ afterEach(async () => {
12
+ await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })))
13
+ })
14
+
15
+ class CapturingStream implements OutputStream {
16
+ public chunks: string[] = []
17
+ public readonly isTty = false
18
+
19
+ public write(text: string): void {
20
+ this.chunks.push(text)
21
+ }
22
+
23
+ public get text(): string {
24
+ return this.chunks.join('')
25
+ }
26
+ }
27
+
28
+ class CleanupFileSystem extends FileSystem {
29
+ public temporaryDirectory: string | undefined
30
+ public cleanupAttempts = 0
31
+ public cleanupCompleted = false
32
+
33
+ public constructor(private readonly failCleanup: boolean) {
34
+ super()
35
+ }
36
+
37
+ public override createTempDir = async (): Promise<string> => {
38
+ this.temporaryDirectory = await mkdtemp(join(tmpdir(), 'contember-template-installer-'))
39
+ temporaryDirectories.push(this.temporaryDirectory)
40
+ return this.temporaryDirectory
41
+ }
42
+
43
+ public override remove: FileSystem['remove'] = async (path, options) => {
44
+ this.cleanupAttempts++
45
+ if (this.failCleanup) {
46
+ throw new Error('cleanup secret')
47
+ }
48
+ await rm(path, options)
49
+ await Promise.resolve()
50
+ this.cleanupCompleted = true
51
+ }
52
+ }
53
+
54
+ const createOutput = (mode: OutputMode = 'human') => {
55
+ const stdout = new CapturingStream()
56
+ const stderr = new CapturingStream()
57
+ const output = new Output({ stdout, stderr })
58
+ output.setMode(mode)
59
+ return { output, stdout, stderr }
60
+ }
61
+
62
+ const createTarget = async (): Promise<string> => {
63
+ const root = await mkdtemp(join(tmpdir(), 'contember-template-target-'))
64
+ temporaryDirectories.push(root)
65
+ return join(root, 'project')
66
+ }
67
+
68
+ const writeValidTemplate = async (directory: string): Promise<void> => {
69
+ await writeFile(join(directory, 'contember.template.yaml'), '{}')
70
+ await writeFile(join(directory, 'README.md'), 'template')
71
+ }
72
+
73
+ describe('TemplateInstaller remote cleanup', () => {
74
+ test('awaits cleanup after a successful remote installation', async () => {
75
+ const fileSystem = new CleanupFileSystem(false)
76
+ const { output, stderr } = createOutput()
77
+ const installer = new TemplateInstaller('/unused', fileSystem, output, async (_source, directory) => {
78
+ await writeValidTemplate(directory)
79
+ })
80
+
81
+ await installer.installTemplate('owner/repository', await createTarget())
82
+
83
+ expect(fileSystem.cleanupAttempts).toBe(1)
84
+ expect(fileSystem.cleanupCompleted).toBe(true)
85
+ expect(await fileSystem.pathExists(fileSystem.temporaryDirectory ?? '')).toBe(false)
86
+ expect(stderr.text).toBe('')
87
+ })
88
+
89
+ test('preserves the primary failure when cleanup also fails', async () => {
90
+ const fileSystem = new CleanupFileSystem(true)
91
+ const { output, stderr } = createOutput()
92
+ const installer = new TemplateInstaller('/unused', fileSystem, output, async () => {
93
+ throw new Error('primary clone failure')
94
+ })
95
+
96
+ await expect(installer.installTemplate('owner/repository', await createTarget())).rejects.toThrow('primary clone failure')
97
+
98
+ expect(fileSystem.cleanupAttempts).toBe(1)
99
+ expect(stderr.text).toContain('Failed to clean up the temporary template directory.')
100
+ expect(stderr.text).not.toContain('cleanup secret')
101
+ expect(stderr.text).not.toContain('owner/repository')
102
+ })
103
+
104
+ test('preserves a template validation failure when cleanup also fails', async () => {
105
+ const fileSystem = new CleanupFileSystem(true)
106
+ const { output, stderr } = createOutput()
107
+ const installer = new TemplateInstaller('/unused', fileSystem, output, async () => {})
108
+
109
+ await expect(installer.installTemplate('owner/repository', await createTarget())).rejects.toThrow('is not a Contember template')
110
+
111
+ expect(fileSystem.cleanupAttempts).toBe(1)
112
+ expect(stderr.text).toContain('Failed to clean up the temporary template directory.')
113
+ expect(stderr.text).not.toContain('cleanup secret')
114
+ })
115
+
116
+ for (const mode of ['json', 'quiet'] satisfies OutputMode[]) {
117
+ test(`suppresses cleanup warnings in ${mode} mode`, async () => {
118
+ const fileSystem = new CleanupFileSystem(true)
119
+ const { output, stdout, stderr } = createOutput(mode)
120
+ const installer = new TemplateInstaller('/unused', fileSystem, output, async (_source, directory) => {
121
+ await writeValidTemplate(directory)
122
+ })
123
+
124
+ await installer.installTemplate('owner/repository', await createTarget())
125
+
126
+ expect(fileSystem.cleanupAttempts).toBe(1)
127
+ expect(stdout.text).toBe('')
128
+ expect(stderr.text).toBe('')
129
+ })
130
+ }
131
+
132
+ test('does not clone or clean up local templates', async () => {
133
+ const resourceDirectory = await mkdtemp(join(tmpdir(), 'contember-template-resources-'))
134
+ temporaryDirectories.push(resourceDirectory)
135
+ const templateDirectory = join(resourceDirectory, 'templates/default')
136
+ await mkdir(templateDirectory, { recursive: true })
137
+ await writeValidTemplate(templateDirectory)
138
+ const fileSystem = new CleanupFileSystem(false)
139
+ const { output } = createOutput()
140
+ let cloneCalled = false
141
+ const installer = new TemplateInstaller(resourceDirectory, fileSystem, output, async () => {
142
+ cloneCalled = true
143
+ })
144
+
145
+ await installer.installTemplate('default', await createTarget())
146
+
147
+ expect(cloneCalled).toBe(false)
148
+ expect(fileSystem.cleanupAttempts).toBe(0)
149
+ })
150
+ })