@xrystal/core 3.52.7 → 3.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.52.7",
4
+ "version": "3.53.0",
5
5
  "description": "microservice runtime library",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -26,7 +26,9 @@ export function registerCreateCommand(cli, { cliName = CLI_PRIMARY_NAME, runtime
26
26
  .command('create <project-name> [target-path]')
27
27
  .description('Scaffold new service from GitHub template')
28
28
  .option('-f, --force', 'Allow creating in a non-empty directory')
29
- .option('--workspace', 'Scaffold multi-repo workspace (root tmp.yml + api/admin/web folders)')
29
+ .option('--workspace', 'Scaffold multi-repo workspace (root tmp.yml + api/web/mobile folders)')
30
+ .option('--web', 'Inside a workspace: create under web/ (frontend slot)')
31
+ .option('--mobile', 'Inside a workspace: create under mobile/')
30
32
  .action(async (projectName, targetDir, options) => {
31
33
  const name = projectName?.trim()
32
34
  if (!name) {
@@ -66,12 +68,12 @@ export function registerCreateCommand(cli, { cliName = CLI_PRIMARY_NAME, runtime
66
68
  })
67
69
  console.log(chalk.green('\n✓ Workspace ready\n'))
68
70
  console.log(chalk.gray(` tmp: ${path.relative(process.cwd(), result.tmpPath) || result.tmpPath}`))
69
- console.log(chalk.gray(' outer tmp: ./tmp.yml (workspace) · inner: each api|admin|web project'))
71
+ console.log(chalk.gray(' outer tmp: ./tmp.yml (workspace) · inner: each api|web|mobile project'))
70
72
  if (result.general) {
71
73
  console.log(chalk.green(' api/general: monolith scaffold (gpt template)'))
72
74
  console.log(chalk.gray(` tmp: ${path.relative(process.cwd(), result.general.tmpFilePath) || result.general.tmpFilePath}`))
73
75
  }
74
- console.log(chalk.gray(' link more services into api/ or admin|web (frontend)'))
76
+ console.log(chalk.gray(' link frontends under web/ (incl. admin) or mobile/'))
75
77
  console.log(chalk.gray(' telepresence: .env.telepresence.example + x/environments/.env.telepresence'))
76
78
  console.log(chalk.cyan(`\n cd ${path.relative(process.cwd(), result.root) || result.root}`))
77
79
  try {
@@ -88,15 +90,40 @@ export function registerCreateCommand(cli, { cliName = CLI_PRIMARY_NAME, runtime
88
90
  return
89
91
  }
90
92
 
93
+ const slot = options.mobile ? 'mobile' : options.web ? 'web' : 'api'
94
+
91
95
  let targetPath
92
96
  let isCurrentDir
97
+ let workspaceRoot
98
+ let inWorkspace
93
99
  try {
94
- ;({ targetPath, isCurrentDir } = resolveCreateTarget(name, targetDir))
100
+ ;({
101
+ targetPath,
102
+ isCurrentDir,
103
+ workspaceRoot,
104
+ inWorkspace,
105
+ slot: resolvedSlot,
106
+ } = resolveCreateTarget(name, targetDir, { slot }))
95
107
  } catch (error) {
96
108
  console.error(chalk.red(`\n✗ ${error.message}\n`))
97
109
  process.exit(1)
98
110
  }
99
111
 
112
+ if (isCurrentDir && inWorkspace && workspaceRoot) {
113
+ console.error(chalk.red('\n✗ Cannot init workspace root as a service (create .)\n'))
114
+ console.error(chalk.gray(' Use xry create <name> to add api/web/mobile project'))
115
+ console.error(chalk.gray(' Or xry create <name> --workspace to scaffold a new workspace\n'))
116
+ process.exit(1)
117
+ }
118
+
119
+ if (inWorkspace) {
120
+ const version = readCliPackageJson().version
121
+ printCommandHeader({ cliName, command: 'create (workspace link)', version })
122
+ console.log(chalk.gray(` workspace: ${workspaceRoot}`))
123
+ console.log(chalk.gray(` slot: ${resolvedSlot}/`))
124
+ console.log(chalk.gray(` target: ${targetPath}`))
125
+ }
126
+
100
127
  if (fs.existsSync(targetPath)) {
101
128
  const entries = fs.readdirSync(targetPath)
102
129
  if (entries.length > 0 && !options.force) {
@@ -174,6 +201,16 @@ export function registerCreateCommand(cli, { cliName = CLI_PRIMARY_NAME, runtime
174
201
  console.log('')
175
202
  }
176
203
 
204
+ if (inWorkspace) {
205
+ try {
206
+ syncRegistryFromPath(workspaceRoot)
207
+ console.log(chalk.gray(' registered in ~/.xrystal'))
208
+ } catch {
209
+ }
210
+ console.log(chalk.gray(` next: ${cliName} sync --all (from workspace root)`))
211
+ printCommandFooter({ version: readCliPackageJson().version })
212
+ }
213
+
177
214
  const relativePath = path.relative(process.cwd(), targetPath)
178
215
  if (relativePath && relativePath !== '.') console.log(chalk.cyan(` cd ${relativePath}`))
179
216
  console.log(chalk.cyan(` ${devCommand}\n`))
@@ -5,10 +5,10 @@ import { resolveDistLayout } from '../helpers/project-artifacts.mjs'
5
5
  import { CLI_PRIMARY_NAME } from '../helpers/cli-identity.mjs'
6
6
  import {
7
7
  getInstalledCoreVersion,
8
- getProjectRoot,
9
8
  readCliPackageJson,
10
9
  readProjectPackageJson,
11
10
  } from '../helpers/project-root.mjs'
11
+ import { requireServiceRoot, exitOnCliContextError } from '../helpers/cli-context-guard.mjs'
12
12
  import { listRuntimeInventory, resolveRuntimeInfo } from '../helpers/runtime-info.mjs'
13
13
  import { evaluateVersionBump, getVersionState, resolveCommitVersionHint, resolveVersionBaseline, VERSION_PATTERN } from '../scripts/version-check.mjs'
14
14
  import { auditTsconfigAlignment, resolveToolchainPathsFromProject } from '../helpers/toolchain-config.mjs'
@@ -30,7 +30,13 @@ export function registerDoctorCommand(cli, { cliName = CLI_PRIMARY_NAME } = {})
30
30
  .command('doctor')
31
31
  .description(`Check runtime, git, and ${packageDefaults.packageName} alignment`)
32
32
  .action(async () => {
33
- const root = getProjectRoot()
33
+ let root
34
+ try {
35
+ ;({ root } = requireServiceRoot(process.cwd(), { cliName, command: 'doctor' }))
36
+ } catch (error) {
37
+ exitOnCliContextError(error)
38
+ }
39
+
34
40
  const cliPkg = readCliPackageJson()
35
41
  const projectPkg = readProjectPackageJson(root)
36
42
  const core = getInstalledCoreVersion(root)
@@ -3,7 +3,7 @@ import chalk from 'chalk'
3
3
  import { printCommandHeader } from '../helpers/banner.mjs'
4
4
  import { readCliPackageJson } from '../helpers/project-root.mjs'
5
5
  import { installGitHooks, isGitHookInstalled } from '../scripts/install-git-hooks.mjs'
6
- import { getProjectRoot } from '../helpers/project-root.mjs'
6
+ import { requireServiceRoot, exitOnCliContextError } from '../helpers/cli-context-guard.mjs'
7
7
  import { CLI_PRIMARY_NAME } from '../helpers/cli-identity.mjs'
8
8
  import { packageDefaults } from '../helpers/package-defaults.mjs'
9
9
 
@@ -25,7 +25,7 @@ export function registerHooksCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
25
25
  .description('Write pre-commit hook to .git/hooks (core repo + services)')
26
26
  .action(() => {
27
27
  try {
28
- const root = getProjectRoot()
28
+ const { root } = requireServiceRoot(process.cwd(), { cliName, command: 'hooks install' })
29
29
  printCommandHeader({ cliName, command: 'hooks install', version: readCliPackageJson().version })
30
30
 
31
31
  if (isGitHookInstalled(root)) {
@@ -39,6 +39,7 @@ export function registerHooksCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
39
39
  console.log(chalk.gray(` checker: ${result.scriptPath}`))
40
40
  console.log(chalk.dim('\n Runs on git commit when package.json version changes.\n'))
41
41
  } catch (error) {
42
+ exitOnCliContextError(error)
42
43
  console.error(chalk.red(`\n✗ ${error.message}\n`))
43
44
  process.exit(1)
44
45
  }
@@ -48,7 +49,12 @@ export function registerHooksCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
48
49
  .command('status')
49
50
  .description(`Show whether ${packageDefaults.packageName} pre-commit hook is installed`)
50
51
  .action(() => {
51
- const root = getProjectRoot()
52
+ let root
53
+ try {
54
+ ;({ root } = requireServiceRoot(process.cwd(), { cliName, command: 'hooks status' }))
55
+ } catch (error) {
56
+ exitOnCliContextError(error)
57
+ }
52
58
  printCommandHeader({ cliName, command: 'hooks status', version: readCliPackageJson().version })
53
59
  const installed = isGitHookInstalled(root)
54
60
  console.log(` pre-commit: ${installed ? chalk.green('installed') : chalk.yellow('not installed')}`)
@@ -18,7 +18,7 @@ import {
18
18
  shouldDelegatePackageBuild,
19
19
  summarizeBuildPlan,
20
20
  } from '../helpers/build-config.mjs'
21
- import { getProjectRoot } from '../helpers/project-root.mjs'
21
+ import { runWithServiceRoot } from '../helpers/cli-context-guard.mjs'
22
22
  import { printCommandHeader } from '../helpers/banner.mjs'
23
23
  import { readCliPackageJson } from '../helpers/project-root.mjs'
24
24
  import { ensureTmpFile, relativeFromRoot } from '../helpers/tmp-layout.mjs'
@@ -41,100 +41,104 @@ function resolveTestTarget(root) {
41
41
  export function registerProjectCommands(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
42
42
  cli
43
43
  .command('dev')
44
- .description('Watch TypeScript entry with dev env files')
44
+ .description('Watch TypeScript entry with dev env files (service repo only — not workspace root)')
45
45
  .action(() => {
46
- const root = getProjectRoot()
47
- const { layout, runtime } = readTmpBuildContext(root)
48
- const entry = resolveDevEntry(root, layout)
49
- const envFiles = resolveEnvFiles(layout.pathsAbs.environments, ['.global.env', '.dev.env'])
50
- const envArgs = envFiles.map((file) => `--env-file=${file}`).join(' ')
51
- const runner = resolveRuntimeRunner(runtime)
52
-
53
- printCommandHeader({ cliName, command: 'dev', version: readCliPackageJson().version })
54
- console.log(chalk.gray(` root: ${root}`))
55
- console.log(chalk.gray(` runtime: ${runtime}`))
56
- console.log(chalk.gray(` entry: ${entry} (.ts)\n`))
57
- runInProject(root, `${runner} --watch ${envArgs} ${entry}`.trim())
46
+ runWithServiceRoot((root) => {
47
+ const { layout, runtime } = readTmpBuildContext(root)
48
+ const entry = resolveDevEntry(root, layout)
49
+ const envFiles = resolveEnvFiles(layout.pathsAbs.environments, ['.global.env', '.dev.env'])
50
+ const envArgs = envFiles.map((file) => `--env-file=${file}`).join(' ')
51
+ const runner = resolveRuntimeRunner(runtime)
52
+
53
+ printCommandHeader({ cliName, command: 'dev', version: readCliPackageJson().version })
54
+ console.log(chalk.gray(` root: ${root}`))
55
+ console.log(chalk.gray(` runtime: ${runtime}`))
56
+ console.log(chalk.gray(` entry: ${entry} (.ts)\n`))
57
+ runInProject(root, `${runner} --watch ${envArgs} ${entry}`.trim())
58
+ }, { cliName, command: 'dev' })
58
59
  })
59
60
 
60
61
  cli
61
62
  .command('build')
62
- .description('Bundle to dist/ (bundler from tmp.yml)')
63
+ .description('Bundle to dist/ (service repo only — not workspace root)')
63
64
  .action(() => {
64
- const root = getProjectRoot()
65
- ensureProjectArtifacts(root, { writeToolchain: true, writeManifest: true })
66
- const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
67
- const { layout, build, runtime, bundler } = readTmpBuildContext(root)
68
-
69
- printCommandHeader({ cliName, command: 'build', version: readCliPackageJson().version })
70
- console.log(chalk.gray(` root: ${root}`))
71
-
72
- if (shouldDelegatePackageBuild(pkg)) {
73
- runInProject(root, `${resolvePackageScriptRunner(runtime)} build`)
74
- return
75
- }
76
-
77
- const plan = summarizeBuildPlan(root, layout, build, runtime)
78
- const steps = isCorePackageName(pkg.name)
79
- ? resolveCoreBuildSteps(root, plan.distRel, build)
80
- : resolveServiceBuildSteps(root, layout, build, runtime)
81
- console.log(chalk.gray(` mode: ${isCorePackageName(pkg.name) ? 'core entries' : 'service tsconfig + tmp overrides'}`))
82
- console.log(chalk.gray(` runtime: ${runtime}`))
83
- if (!isCorePackageName(pkg.name)) {
84
- console.log(chalk.gray(` bundler: ${plan.bundler || bundler}`))
85
- }
86
- if (plan.tsconfigRel) {
87
- console.log(chalk.gray(` tsconfig: ${plan.tsconfigRel}`))
88
- }
89
- console.log(chalk.gray(` dist: ${plan.distRel}/ (${plan.distSource})`))
90
- console.log(chalk.gray(` glob: ${plan.entryGlobs.join(', ')} (${plan.globSource})`))
91
- if (plan.typecheck) console.log(chalk.gray(' typecheck: tsc --noEmit'))
92
- if (plan.declarations) console.log(chalk.gray(' declarations: tsc --emitDeclarationOnly'))
93
- if (plan.sourcemap !== 'false') console.log(chalk.gray(` sourcemap: ${plan.sourcemap}`))
94
- if (plan.minify && plan.minify !== 'off') console.log(chalk.gray(` minify: ${plan.minify}`))
95
- console.log('')
96
-
97
- runInProject(root, steps.join(' && '))
65
+ runWithServiceRoot((root) => {
66
+ ensureProjectArtifacts(root, { writeToolchain: true, writeManifest: true })
67
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
68
+ const { layout, build, runtime, bundler } = readTmpBuildContext(root)
69
+
70
+ printCommandHeader({ cliName, command: 'build', version: readCliPackageJson().version })
71
+ console.log(chalk.gray(` root: ${root}`))
72
+
73
+ if (shouldDelegatePackageBuild(pkg)) {
74
+ runInProject(root, `${resolvePackageScriptRunner(runtime)} build`)
75
+ return
76
+ }
77
+
78
+ const plan = summarizeBuildPlan(root, layout, build, runtime)
79
+ const steps = isCorePackageName(pkg.name)
80
+ ? resolveCoreBuildSteps(root, plan.distRel, build)
81
+ : resolveServiceBuildSteps(root, layout, build, runtime)
82
+ console.log(chalk.gray(` mode: ${isCorePackageName(pkg.name) ? 'core entries' : 'service tsconfig + tmp overrides'}`))
83
+ console.log(chalk.gray(` runtime: ${runtime}`))
84
+ if (!isCorePackageName(pkg.name)) {
85
+ console.log(chalk.gray(` bundler: ${plan.bundler || bundler}`))
86
+ }
87
+ if (plan.tsconfigRel) {
88
+ console.log(chalk.gray(` tsconfig: ${plan.tsconfigRel}`))
89
+ }
90
+ console.log(chalk.gray(` dist: ${plan.distRel}/ (${plan.distSource})`))
91
+ console.log(chalk.gray(` glob: ${plan.entryGlobs.join(', ')} (${plan.globSource})`))
92
+ if (plan.typecheck) console.log(chalk.gray(' typecheck: tsc --noEmit'))
93
+ if (plan.declarations) console.log(chalk.gray(' declarations: tsc --emitDeclarationOnly'))
94
+ if (plan.sourcemap !== 'false') console.log(chalk.gray(` sourcemap: ${plan.sourcemap}`))
95
+ if (plan.minify && plan.minify !== 'off') console.log(chalk.gray(` minify: ${plan.minify}`))
96
+ console.log('')
97
+
98
+ runInProject(root, steps.join(' && '))
99
+ }, { cliName, command: 'build' })
98
100
  })
99
101
 
100
102
  cli
101
103
  .command('start')
102
104
  .alias('start:dist')
103
- .description('Run dist/index.js with prod env files')
105
+ .description('Run dist/index.js with prod env files (service repo only)')
104
106
  .action(() => {
105
- const root = getProjectRoot()
106
- const { layout, build, runtime } = readTmpBuildContext(root)
107
- const entryAbs = resolveDistEntryAbs(root, layout, build)
108
-
109
- if (!fs.existsSync(entryAbs)) {
110
- throw new Error(
111
- `Build output not found: ${path.relative(root, entryAbs)}. Run ${cliName} build first.`,
112
- )
113
- }
114
-
115
- const entry = relativeFromRoot(root, entryAbs)
116
- const envFiles = resolveEnvFiles(layout.pathsAbs.environments, ['.global.env', '.prod.env'])
117
- const envArgs = envFiles.map((file) => `--env-file=${file}`).join(' ')
118
- const runner = resolveRuntimeRunner(runtime)
119
-
120
- printCommandHeader({ cliName, command: 'start', version: readCliPackageJson().version })
121
- console.log(chalk.gray(` root: ${root}`))
122
- console.log(chalk.gray(` runtime: ${runtime}`))
123
- console.log(chalk.gray(` entry: ${entry} (.js)\n`))
124
- runInProject(root, `${runner} ${envArgs} ${entry}`.trim())
107
+ runWithServiceRoot((root) => {
108
+ const { layout, build, runtime } = readTmpBuildContext(root)
109
+ const entryAbs = resolveDistEntryAbs(root, layout, build)
110
+
111
+ if (!fs.existsSync(entryAbs)) {
112
+ throw new Error(
113
+ `Build output not found: ${path.relative(root, entryAbs)}. Run ${cliName} build first.`,
114
+ )
115
+ }
116
+
117
+ const entry = relativeFromRoot(root, entryAbs)
118
+ const envFiles = resolveEnvFiles(layout.pathsAbs.environments, ['.global.env', '.prod.env'])
119
+ const envArgs = envFiles.map((file) => `--env-file=${file}`).join(' ')
120
+ const runner = resolveRuntimeRunner(runtime)
121
+
122
+ printCommandHeader({ cliName, command: 'start', version: readCliPackageJson().version })
123
+ console.log(chalk.gray(` root: ${root}`))
124
+ console.log(chalk.gray(` runtime: ${runtime}`))
125
+ console.log(chalk.gray(` entry: ${entry} (.js)\n`))
126
+ runInProject(root, `${runner} ${envArgs} ${entry}`.trim())
127
+ }, { cliName, command: 'start' })
125
128
  })
126
129
 
127
130
  cli
128
131
  .command('test')
129
- .description('Run tests from tmp.yml paths')
132
+ .description('Run tests from tmp.yml paths (service repo only)')
130
133
  .action(() => {
131
- const root = getProjectRoot()
132
- const { runtime } = readTmpBuildContext(root)
133
- const target = resolveTestTarget(root)
134
-
135
- printCommandHeader({ cliName, command: 'test', version: readCliPackageJson().version })
136
- console.log(chalk.gray(` runtime: ${runtime}`))
137
- console.log(chalk.gray(` target: ${target}\n`))
138
- runInProject(root, resolveTestCommand(runtime, target))
134
+ runWithServiceRoot((root) => {
135
+ const { runtime } = readTmpBuildContext(root)
136
+ const target = resolveTestTarget(root)
137
+
138
+ printCommandHeader({ cliName, command: 'test', version: readCliPackageJson().version })
139
+ console.log(chalk.gray(` runtime: ${runtime}`))
140
+ console.log(chalk.gray(` target: ${target}\n`))
141
+ runInProject(root, resolveTestCommand(runtime, target))
142
+ }, { cliName, command: 'test' })
139
143
  })
140
144
  }
@@ -1,5 +1,6 @@
1
1
  import chalk from 'chalk'
2
- import { readCliPackageJson, readProjectPackageJson, getProjectRoot } from '../helpers/project-root.mjs'
2
+ import { readCliPackageJson, readProjectPackageJson } from '../helpers/project-root.mjs'
3
+ import { requireServiceRoot, exitOnCliContextError } from '../helpers/cli-context-guard.mjs'
3
4
  import { compareSemver, getVersionState, resolveVersionBaseline, runTagRelease } from '../scripts/version-check.mjs'
4
5
  import { CLI_PRIMARY_NAME, PACKAGE_NAME } from '../helpers/cli-identity.mjs'
5
6
  import { packageDefaults } from '../helpers/package-defaults.mjs'
@@ -13,16 +14,18 @@ export function registerTagCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
13
14
  .option('--skip-prepare', 'Skip lint, test, and build:prod (core only)')
14
15
  .action(async (options) => {
15
16
  try {
17
+ const { root } = requireServiceRoot(process.cwd(), { cliName, command: 'tag' })
16
18
  await runTagRelease({
17
19
  dryRun: options.dryRun,
18
20
  requireClean: options.strictClean,
19
21
  skipPrepare: options.skipPrepare,
20
- root: getProjectRoot(),
22
+ root,
21
23
  })
22
24
  if (!options.dryRun) {
23
25
  console.log(chalk.green('\n✓ Tag pushed.\n'))
24
26
  }
25
27
  } catch (error) {
28
+ if (error?.name === 'CliContextError') exitOnCliContextError(error)
26
29
  console.error(chalk.red(`\n✗ ${error.message}\n`))
27
30
  process.exit(1)
28
31
  }
@@ -35,7 +38,7 @@ export function registerVersionCommand(cli, { cliName = CLI_PRIMARY_NAME } = {})
35
38
  .description('Show CLI and project package versions')
36
39
  .action(() => {
37
40
  try {
38
- const root = getProjectRoot()
41
+ const { root } = requireServiceRoot(process.cwd(), { cliName, command: 'version' })
39
42
  const cliPkg = readCliPackageJson()
40
43
  const projectPkg = readProjectPackageJson(root)
41
44
  const state = getVersionState('HEAD', root)
@@ -61,6 +64,7 @@ export function registerVersionCommand(cli, { cliName = CLI_PRIMARY_NAME } = {})
61
64
  console.log(` working tree: ${state.isClean ? chalk.green('clean') : chalk.yellow('dirty')}`)
62
65
  console.log('')
63
66
  } catch (error) {
67
+ if (error?.name === 'CliContextError') exitOnCliContextError(error)
64
68
  console.error(chalk.red(`\n✗ ${error.message}\n`))
65
69
  process.exit(1)
66
70
  }
@@ -25,6 +25,9 @@ export function registerSyncCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
25
25
  }
26
26
 
27
27
  printCommandHeader({ cliName, command: 'sync', version: coreVersion })
28
+ if (scope.warnAllIgnored) {
29
+ console.log(chalk.yellow(' note: not in a workspace — --all ignored, syncing this repo only'))
30
+ }
28
31
  console.log(chalk.gray(` scope: ${scope.label} (${scope.mode})`))
29
32
  if (scope.workspaceRoot) {
30
33
  console.log(chalk.gray(` workspace: ${scope.workspaceRoot}`))
@@ -44,7 +47,7 @@ export function registerSyncCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
44
47
  if (scope.entries.length === 0) {
45
48
  console.log(chalk.yellow('\n no projects to sync'))
46
49
  if (scope.mode === 'workspace-all') {
47
- console.log(chalk.gray(' link services under api/ admin/ web/ then re-run'))
50
+ console.log(chalk.gray(' link services under api/ web/ mobile/ then re-run'))
48
51
  }
49
52
  printCommandFooter({ version: coreVersion })
50
53
  return
@@ -97,7 +100,7 @@ export function registerSyncCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
97
100
  .description('Sync tsconfig + @xrystal/core for current project (use --all inside a workspace for every link)')
98
101
  .option('--dry-run', 'Preview without writing')
99
102
  .option('--self', 'Inside a workspace: sync only the current linked project')
100
- .option('--all', 'Inside a workspace: sync all api/admin/web linked projects + registry')
103
+ .option('--all', 'Inside a workspace: sync all api/web/mobile linked projects + registry')
101
104
  .option('--workspace', 'Alias for --all')
102
105
  .addHelpText('after', () => formatSyncHelp({ cliName }))
103
106
  .action(run)
@@ -4,7 +4,7 @@ import yaml from 'yaml'
4
4
 
5
5
  import { printCommandFooter, printCommandHeader } from '../helpers/banner.mjs'
6
6
  import { resolveObjWithHandlebars } from '../helpers/index.mjs'
7
- import { getProjectRoot, readCliPackageJson } from '../helpers/project-root.mjs'
7
+ import { readCliPackageJson } from '../helpers/project-root.mjs'
8
8
  import { CLI_PRIMARY_NAME } from '../helpers/cli-identity.mjs'
9
9
  import {
10
10
  ensureTmpFile,
@@ -15,55 +15,75 @@ import {
15
15
  import { formatLoaderSummary, summarizeLoaders } from '../helpers/tmp-config.mjs'
16
16
  import { packageDefaults } from '../helpers/package-defaults.mjs'
17
17
  import { ensureTmpSchemaVersion, readTmpSchemaVersion } from '../helpers/tmp-schema-version.mjs'
18
- import { resolveProjectContext } from '../helpers/project-context.mjs'
18
+ import { getCliContext } from '../helpers/cli-context-guard.mjs'
19
+ import { ensureOuterWorkspaceTmp } from '../helpers/workspace-tmp.mjs'
20
+
21
+ function ensureTmpForContext(ctx) {
22
+ if (ctx.kind === 'workspace-root') {
23
+ const outer = ensureOuterWorkspaceTmp(ctx.workspaceRoot)
24
+ return {
25
+ tmpFilePath: outer.tmpFilePath,
26
+ created: outer.created,
27
+ layout: null,
28
+ schema: outer.schema,
29
+ }
30
+ }
31
+ const result = ensureTmpFile(ctx.projectRoot)
32
+ return { ...result, schema: ensureTmpSchemaVersion(result.tmpFilePath) }
33
+ }
19
34
 
20
35
  export function registerTmpCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
21
36
  cli
22
37
  .command('tmp')
23
- .description(`Ensure inner/outer tmp.yml exists (seed from ${packageDefaults.packageName})`)
38
+ .description('Ensure tmp.yml for current scope (outer workspace or inner service)')
24
39
  .option('--dry-run', 'Show target path without writing')
25
40
  .action((options) => {
26
- const root = getProjectRoot()
41
+ const ctx = getCliContext()
27
42
  const version = readCliPackageJson().version
43
+ const root = ctx.kind === 'workspace-root' ? ctx.workspaceRoot : ctx.projectRoot
28
44
 
29
45
  if (options.dryRun) {
30
- const layout = resolveTmpLayoutOrDefaults(root)
31
- const target = layout.tmpFilePath ?? ownerTmpFilePath(root, layout)
32
- const exists = fs.existsSync(target)
46
+ const target = ctx.kind === 'workspace-root'
47
+ ? `${ctx.workspaceRoot}/tmp.yml`
48
+ : (resolveTmpLayoutOrDefaults(root).tmpFilePath ?? ownerTmpFilePath(root))
33
49
 
34
50
  printCommandHeader({ cliName, command: 'tmp (dry-run)', version })
51
+ console.log(chalk.gray(` scope: ${ctx.label}`))
35
52
  console.log(chalk.gray(` root: ${root}`))
36
- console.log(` ${exists ? 'exists' : 'would create'}: ${target}`)
53
+ console.log(` ${fs.existsSync(target) ? 'exists' : 'would create'}: ${target}`)
37
54
  printCommandFooter({ version })
38
55
  return
39
56
  }
40
57
 
41
- const result = ensureTmpFile(root)
58
+ const result = ensureTmpForContext(ctx)
42
59
  const rel = relativeFromRoot(root, result.tmpFilePath)
43
- const schema = ensureTmpSchemaVersion(result.tmpFilePath)
44
60
 
45
- const ctx = resolveProjectContext()
46
61
  printCommandHeader({ cliName, command: 'tmp', version })
47
62
  console.log(chalk.gray(` scope: ${ctx.label}`))
48
63
  console.log(chalk.gray(` root: ${root}`))
49
64
  console.log(result.created ? chalk.green(` created ${rel}`) : chalk.gray(` ok ${rel}`))
65
+
50
66
  const schemaVersion = readTmpSchemaVersion(result.tmpFilePath)
51
67
  if (schemaVersion) {
52
- const schemaLabel = schema.patched
68
+ const schemaLabel = result.schema?.patched
53
69
  ? chalk.green(` end.version → ${schemaVersion} (schema)`)
54
70
  : chalk.gray(` end.version: ${schemaVersion} (schema)`)
55
71
  console.log(schemaLabel)
56
72
  }
57
73
 
58
- try {
59
- const tmp = yaml.parse(fs.readFileSync(result.tmpFilePath, 'utf8'))
60
- const summary = summarizeLoaders(resolveObjWithHandlebars(tmp, tmp))
61
- console.log(chalk.gray(` root: ${result.layout.rootFolderPath} · project: ${summary.project ?? '-'}`))
62
- if (summary.items?.length) {
63
- console.log(chalk.gray(` loaders: ${formatLoaderSummary(summary)}`))
74
+ if (ctx.kind !== 'workspace-root') {
75
+ try {
76
+ const tmp = yaml.parse(fs.readFileSync(result.tmpFilePath, 'utf8'))
77
+ const summary = summarizeLoaders(resolveObjWithHandlebars(tmp, tmp))
78
+ console.log(chalk.gray(` root: ${result.layout?.rootFolderPath ?? 'x'} · project: ${summary.project ?? '-'}`))
79
+ if (summary.items?.length) {
80
+ console.log(chalk.gray(` loaders: ${formatLoaderSummary(summary)}`))
81
+ }
82
+ } catch {
83
+ // summary optional
64
84
  }
65
- } catch {
66
- // summary optional
85
+ } else {
86
+ console.log(chalk.gray(' outer workspace tmp — layout only (no loaders)'))
67
87
  }
68
88
 
69
89
  printCommandFooter({ version })
@@ -291,16 +291,36 @@ function resolveMergedPaths(configs) {
291
291
  tmpRelPath: `${root}/${tmpName}`.replace(/\/+/g, "/")
292
292
  };
293
293
  }
294
+ function readWorkspaceGlobalBlock(global) {
295
+ const pathsRaw = isRecord2(global.paths) ? global.paths : {};
296
+ const root = typeof pathsRaw.root === "string" && pathsRaw.root.trim() ? pathsRaw.root.trim() : ".";
297
+ const optionsRaw = isRecord2(global.options) ? global.options : undefined;
298
+ return {
299
+ type: "workspace" /* WORKSPACE */,
300
+ runtime: "bun" /* BUN */,
301
+ framework: "",
302
+ paths: {
303
+ root,
304
+ tmp: typeof pathsRaw.tmp === "string" ? pathsRaw.tmp : "tmp.yml"
305
+ },
306
+ vars: isRecord2(global.vars) ? { ...global.vars } : {},
307
+ options: optionsRaw ? { fileWatchIntervalMs: readWatchIntervalValue(optionsRaw.fileWatchIntervalMs) } : undefined
308
+ };
309
+ }
294
310
  function readTmpGlobalBlock(configs) {
295
311
  const global = isRecord2(configs?.global) ? configs.global : {};
296
312
  const varsRaw = isRecord2(global.vars) ? global.vars : {};
297
313
  const typeRaw = global.type;
314
+ const type = typeRaw !== undefined ? normalizeGlobalType(typeRaw) : undefined;
315
+ if (type === "workspace" /* WORKSPACE */) {
316
+ return readWorkspaceGlobalBlock(global);
317
+ }
298
318
  if (typeof global.framework !== "string" || !global.framework.trim()) {
299
319
  throw new Error(`${defaults_default.packageName}: configs.global.framework is required`);
300
320
  }
301
321
  return {
302
322
  runtime: normalizeRuntime(global.runtime),
303
- type: typeRaw !== undefined ? normalizeGlobalType(typeRaw) : undefined,
323
+ type,
304
324
  framework: global.framework.trim(),
305
325
  paths: readTmpGlobalPathsBlock(configs),
306
326
  vars: { ...varsRaw },
@@ -370,6 +390,15 @@ function resolveTmpRuntimeConfigs(tmp) {
370
390
  assertNoLegacyTmpKeys(configs);
371
391
  const global = readTmpGlobalBlock(configs);
372
392
  const depends = readTmpDependsBlock(configs);
393
+ if (global.type === "workspace" /* WORKSPACE */) {
394
+ return {
395
+ global: { ...global, build: {} },
396
+ depends: buildNormalizedDepends(depends),
397
+ deploymentName: resolveTmpDeploymentName(tmp),
398
+ rootFolderPath: ".",
399
+ tmpRelPath: global.paths.tmp ?? "tmp.yml"
400
+ };
401
+ }
373
402
  const merged = resolveMergedPaths(configs);
374
403
  return {
375
404
  global: {
@@ -176,8 +176,8 @@ var TMP_FILE = "tmp.yml";
176
176
  var SKIP_DIRS = new Set(["node_modules", ".git", "dist", ".turbo", "coverage"]);
177
177
  var DEFAULT_FOLDER_STRUCTURE = {
178
178
  api: "api",
179
- admin: "admin",
180
- web: "web"
179
+ web: "web",
180
+ mobile: "mobile"
181
181
  };
182
182
  function parseScalar(raw) {
183
183
  const trimmed = raw.trim();
@@ -211,18 +211,28 @@ function readTmpFile(filePath) {
211
211
  }
212
212
  function parseFolderStructure(text) {
213
213
  const fsBlock = text.match(/folder-structure:\s*\n((?:[ \t]+[^\n]+\n?)*)/)?.[1] ?? "";
214
+ if (/^[ \t]+admin:/m.test(fsBlock)) {
215
+ throw new Error("configs.folder-structure.admin removed — put admin panels under web/ (e.g. web/admin-ui)");
216
+ }
214
217
  const readSlot = (key) => {
215
- const scalar = fsBlock.match(new RegExp(`^[ ]+${key}:s*(.+?)(?:s+#.*)?$`, "m"));
218
+ const scalar = fsBlock.match(new RegExp(`^[ ]+${key}:\\s*(.+?)(?:\\s+#.*)?$`, "m"));
216
219
  if (scalar)
217
220
  return parseScalar(scalar[1]);
218
221
  return DEFAULT_FOLDER_STRUCTURE[key];
219
222
  };
220
223
  return {
221
224
  api: readSlot("api"),
222
- admin: readSlot("admin"),
223
- web: readSlot("web")
225
+ web: readSlot("web"),
226
+ mobile: readSlot("mobile")
224
227
  };
225
228
  }
229
+ function workspaceDiscoverySlots(fsMap) {
230
+ return [
231
+ { slot: "api", folder: fsMap.api, frontendOnly: false },
232
+ { slot: "web", folder: fsMap.web, frontendOnly: true },
233
+ { slot: "mobile", folder: fsMap.mobile, frontendOnly: true }
234
+ ];
235
+ }
226
236
  function entryName(meta) {
227
237
  const project = (meta.projectName ?? "").trim();
228
238
  return project || null;
@@ -313,9 +323,8 @@ function findEntries(workspaceRoot) {
313
323
  const fsMap = wsMeta.folderStructure;
314
324
  const entries = [];
315
325
  const seen = new Set;
316
- const slots = ["api", "admin", "web"];
317
- for (const slot of slots) {
318
- const folder = path2.join(workspaceRoot, fsMap[slot]);
326
+ for (const { slot, folder: folderRel, frontendOnly } of workspaceDiscoverySlots(fsMap)) {
327
+ const folder = path2.join(workspaceRoot, folderRel);
319
328
  for (const tmpPath of walkTmpUnder(folder)) {
320
329
  if (path2.resolve(tmpPath) === path2.join(workspaceRoot, TMP_FILE))
321
330
  continue;
@@ -323,7 +332,7 @@ function findEntries(workspaceRoot) {
323
332
  const kind = entryType(meta, slot);
324
333
  if (kind === "workspace" /* WORKSPACE */)
325
334
  continue;
326
- if (slot !== "api" && kind !== "frontend" /* FRONTEND */)
335
+ if (frontendOnly && kind !== "frontend" /* FRONTEND */)
327
336
  continue;
328
337
  if (kind !== "api-service" /* API_SERVICE */ && kind !== "frontend" /* FRONTEND */)
329
338
  continue;
@@ -370,17 +379,10 @@ function workspaceTmpTemplate(projectName) {
370
379
  configs:
371
380
  global:
372
381
  type: workspace
373
- runtime: bun
374
- framework: bun
375
- paths:
376
- root: .
377
- tmp: tmp.yml
378
- options:
379
- fileWatchIntervalMs: 500
380
382
  folder-structure:
381
383
  api: api
382
- admin: admin
383
384
  web: web
385
+ mobile: mobile
384
386
 
385
387
  kubeconfig: ~/.kube/config
386
388
 
@@ -391,6 +393,7 @@ end:
391
393
  export {
392
394
  workspaceTmpTemplate,
393
395
  workspaceProjectName,
396
+ workspaceDiscoverySlots,
394
397
  resolveEntryPath,
395
398
  readWorkspaceGlobalTmp,
396
399
  readWorkspaceCoreTmp,
@@ -0,0 +1,76 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ import chalk from 'chalk'
5
+
6
+ import { resolveProjectContext } from './project-context.mjs'
7
+
8
+ export class CliContextError extends Error {
9
+ constructor(message, { hints = [] } = {}) {
10
+ super(message)
11
+ this.name = 'CliContextError'
12
+ this.hints = hints
13
+ }
14
+ }
15
+
16
+ export function getCliContext(startDir = process.cwd()) {
17
+ return resolveProjectContext(startDir)
18
+ }
19
+
20
+ export function requireServiceRoot(startDir = process.cwd(), { cliName = 'xry', command = 'dev' } = {}) {
21
+ const ctx = getCliContext(startDir)
22
+
23
+ if (ctx.kind === 'workspace-root') {
24
+ const examples = (ctx.workspaceEntries ?? [])
25
+ .slice(0, 3)
26
+ .map((entry) => {
27
+ const rel = path.relative(ctx.cwd, entry.path) || entry.path
28
+ return `cd ${rel} && ${cliName} ${command}`
29
+ })
30
+
31
+ throw new CliContextError(
32
+ 'Workspace root is layout-only (outer tmp.yml) — not a runnable service.',
33
+ {
34
+ hints: [
35
+ 'Use a linked project under api/, web/, or mobile/',
36
+ ...examples,
37
+ `${cliName} project — list linked services`,
38
+ ],
39
+ },
40
+ )
41
+ }
42
+
43
+ const pkgPath = path.join(ctx.projectRoot, 'package.json')
44
+ if (!fs.existsSync(pkgPath)) {
45
+ throw new CliContextError(
46
+ `No service package.json here (${ctx.projectRoot}).`,
47
+ {
48
+ hints: [
49
+ `${cliName} project — see current scope`,
50
+ 'cd into api/<service>, web/<app>, or mobile/<app>',
51
+ ],
52
+ },
53
+ )
54
+ }
55
+
56
+ return { ctx, root: ctx.projectRoot }
57
+ }
58
+
59
+ export function exitOnCliContextError(error) {
60
+ if (error?.name !== 'CliContextError') throw error
61
+ console.error(chalk.red(`\n✗ ${error.message}\n`))
62
+ for (const hint of error.hints ?? []) {
63
+ console.error(chalk.gray(` → ${hint}`))
64
+ }
65
+ console.error('')
66
+ process.exit(1)
67
+ }
68
+
69
+ export function runWithServiceRoot(fn, { cliName = 'xry', command = 'dev' } = {}) {
70
+ try {
71
+ const { root, ctx } = requireServiceRoot(process.cwd(), { cliName, command })
72
+ return fn(root, ctx)
73
+ } catch (error) {
74
+ exitOnCliContextError(error)
75
+ }
76
+ }
@@ -9,9 +9,9 @@ import { packageDefaults } from './package-defaults.mjs'
9
9
  const QUICK_COMMANDS = [
10
10
  { cmd: 'project', desc: 'Where am I? workspace root · linked service · standalone' },
11
11
  { cmd: 'sync', desc: 'This project: tsconfig + @xrystal/core pin' },
12
- { cmd: 'sync --all', desc: 'Inside workspace: every linked api/admin/web project' },
12
+ { cmd: 'sync --all', desc: 'Inside workspace: every linked api/web/mobile project' },
13
13
  { cmd: 'tmp', desc: 'Ensure tmp.yml for current scope (inner x/ or outer ./)' },
14
- { cmd: 'create <name> --workspace', desc: 'Outer tmp + api/general + admin/web slots' },
14
+ { cmd: 'create <name> --workspace', desc: 'Outer tmp + api/general + web/mobile slots' },
15
15
  { cmd: 'workspaces', desc: 'Global registry ~/.xrystal (not repo tmp.yml)' },
16
16
  { cmd: 'dev / build / doctor', desc: 'Develop & diagnostics' },
17
17
  ]
@@ -36,8 +36,8 @@ const COMMAND_GROUPS = [
36
36
  {
37
37
  title: 'Workspace',
38
38
  items: [
39
- { cmd: 'create <name> --workspace', desc: 'Outer ./tmp.yml + api/general inner monolith + admin/web' },
40
- { cmd: 'sync --all', desc: 'From root or any link: all api/admin/web + ~/.xrystal registry' },
39
+ { cmd: 'create <name> --workspace', desc: 'Outer ./tmp.yml + api/general + web/mobile (admin under web/)' },
40
+ { cmd: 'sync --all', desc: 'From root or any link: all api/web/mobile + ~/.xrystal registry' },
41
41
  { cmd: 'workspaces [list|sync]', desc: 'Inspect/rescan global registry (separate from xry sync)' },
42
42
  { cmd: 'telepresence dev <deploy>', aliases: 'tp dev', desc: 'Intercept cluster pod → local dev' },
43
43
  { cmd: 'telepresence connect', aliases: 'tp connect', desc: 'Connect Telepresence to dev/test namespace' },
@@ -100,8 +100,8 @@ export function formatSyncHelp({ cliName = CLI_PRIMARY_NAME } = {}) {
100
100
  const rows = [
101
101
  { ctx: 'Standalone service', cmd: `${cliName} sync`, effect: 'tsconfig + pin @xrystal/core + tmp schema' },
102
102
  { ctx: 'Workspace root', cmd: `${cliName} sync`, effect: 'all linked projects + registry (same as --all)' },
103
- { ctx: 'Inside api/admin/web', cmd: `${cliName} sync`, effect: 'current project only (default)' },
104
- { ctx: 'Inside api/admin/web', cmd: `${cliName} sync --all`, effect: 'every linked project + registry' },
103
+ { ctx: 'Inside api/web/mobile', cmd: `${cliName} sync`, effect: 'current project only (default)' },
104
+ { ctx: 'Inside api/web/mobile', cmd: `${cliName} sync --all`, effect: 'every linked project + registry' },
105
105
  { ctx: 'Global registry only', cmd: `${cliName} workspaces sync`, effect: 'rescan ~/.xrystal from cwd' },
106
106
  ]
107
107
  const lines = rows.map((row) => ` ${chalk.gray(row.ctx.padEnd(22))} ${chalk.cyan(row.cmd)}\n${' '.repeat(26)}${chalk.gray(row.effect)}`)
@@ -162,10 +162,11 @@ export function formatRootHelp({ cliName = CLI_PRIMARY_NAME } = {}) {
162
162
 
163
163
  export function formatCreateHelp({ cliName = CLI_PRIMARY_NAME } = {}) {
164
164
  const examples = [
165
- { cmd: `${cliName} create demo --workspace`, desc: '→ workspace + api/general + admin/web' },
166
- { cmd: `${cliName} create my-api`, desc: '→ ./my-api (current folder)' },
167
- { cmd: `${cliName} create my-api ..`, desc: '→ ../my-api' },
168
- { cmd: `${cliName} create my-api ~/services`, desc: '→ ~/services/my-api' },
165
+ { cmd: `${cliName} create demo --workspace`, desc: '→ workspace + api/general + web/mobile' },
166
+ { cmd: `${cliName} create my-api`, desc: '→ ./my-api (or workspace/api/my-api if inside ws)' },
167
+ { cmd: `${cliName} create my-api ..`, desc: '→ ../my-api (standalone parent folder)' },
168
+ { cmd: `${cliName} create my-api ~/ws`, desc: '→ ~/ws/api/my-api when ~/ws is a workspace' },
169
+ { cmd: `${cliName} create ui --web`, desc: '→ workspace/web/ui when inside a workspace' },
169
170
  { cmd: `${cliName} create .`, desc: '→ init in current directory' },
170
171
  ]
171
172
  return [
@@ -1,12 +1,32 @@
1
+ import fs from 'node:fs'
1
2
  import path from 'node:path'
2
3
 
4
+ import {
5
+ DEFAULT_FOLDER_STRUCTURE,
6
+ findWorkspaceRoot,
7
+ readTmpFile,
8
+ } from './workspace-resolve.mjs'
9
+
10
+ function resolveReal(input) {
11
+ const resolved = path.resolve(input)
12
+ try {
13
+ return fs.realpathSync.native(resolved)
14
+ } catch {
15
+ return resolved
16
+ }
17
+ }
18
+
3
19
  /**
4
20
  * Resolve scaffold target directory.
5
21
  *
22
+ * When cwd or target-path sits inside a workspace, services land under
23
+ * api|web|mobile automatically (default slot: api).
24
+ *
6
25
  * @param {string} projectName Folder name or `.` for current directory
7
26
  * @param {string | undefined} targetDir Optional parent path (default: cwd)
27
+ * @param {{ slot?: 'api' | 'web' | 'mobile' }} options
8
28
  */
9
- export function resolveCreateTarget(projectName, targetDir) {
29
+ export function resolveCreateTarget(projectName, targetDir, { slot = 'api' } = {}) {
10
30
  const cwd = process.cwd()
11
31
  const name = String(projectName ?? '').trim()
12
32
 
@@ -19,17 +39,41 @@ export function resolveCreateTarget(projectName, targetDir) {
19
39
  return {
20
40
  targetPath: parent,
21
41
  isCurrentDir: true,
42
+ workspaceRoot: findWorkspaceRoot(parent),
43
+ slot: null,
44
+ inWorkspace: Boolean(findWorkspaceRoot(parent)),
22
45
  }
23
46
  }
24
47
 
25
48
  const base = targetDir ? path.resolve(cwd, targetDir) : cwd
49
+ const workspaceRoot = findWorkspaceRoot(base)
50
+
51
+ if (workspaceRoot) {
52
+ const wsRoot = resolveReal(workspaceRoot)
53
+ const wsTmp = path.join(wsRoot, 'tmp.yml')
54
+ const fsMap = readTmpFile(wsTmp).folderStructure
55
+ const slotFolder = fsMap[slot] ?? DEFAULT_FOLDER_STRUCTURE[slot]
56
+ const slotRoot = path.join(wsRoot, slotFolder)
57
+ const targetPath = resolveReal(path.join(slotRoot, name))
58
+
59
+ return {
60
+ targetPath,
61
+ isCurrentDir: false,
62
+ workspaceRoot: wsRoot,
63
+ slot,
64
+ inWorkspace: true,
65
+ }
66
+ }
67
+
26
68
  return {
27
- targetPath: path.join(base, name),
69
+ targetPath: resolveReal(path.join(base, name)),
28
70
  isCurrentDir: false,
71
+ workspaceRoot: null,
72
+ slot: null,
73
+ inWorkspace: false,
29
74
  }
30
75
  }
31
76
 
32
- export function formatCreateTargetPreview(projectName, targetDir) {
33
- const { targetPath, isCurrentDir } = resolveCreateTarget(projectName, targetDir)
34
- return { targetPath, isCurrentDir, label: isCurrentDir ? targetPath : targetPath }
77
+ export function formatCreateTargetPreview(projectName, targetDir, options = {}) {
78
+ return resolveCreateTarget(projectName, targetDir, options)
35
79
  }
@@ -107,14 +107,15 @@ export function resolveProjectContext(startDir = process.cwd()) {
107
107
 
108
108
  const hints = []
109
109
  if (kind === 'workspace-root') {
110
- hints.push('Outer tmp: ./tmp.yml · inner tmp: each api|admin|web project')
110
+ hints.push('Outer tmp: ./tmp.yml · inner tmp: each api|web|mobile project (admin → web/)')
111
111
  hints.push('xry sync — all linked projects + ~/.xrystal registry')
112
- hints.push('xry sync --all — same from any folder under this workspace')
112
+ hints.push('xry create <name> — adds api/<name> (or --web / --mobile)')
113
+ hints.push('dev/build/start — run inside a linked service, not here')
113
114
  hints.push('xry workspaces — global registry (~/.xrystal), not repo tmp files')
114
115
  } else if (kind === 'workspace-service') {
115
116
  hints.push(`Outer workspace: ${workspaceRoot}`)
116
117
  hints.push('xry sync — this service only (tsconfig + @xrystal/core pin)')
117
- hints.push('xry sync --all — every linked api/admin/web project + registry')
118
+ hints.push('xry sync --all — every linked api/web/mobile project + registry')
118
119
  hints.push('xry tmp — inner x/tmp.yml · configs.global.type drives loader profile')
119
120
  } else {
120
121
  hints.push('xry sync — tsconfig + @xrystal/core pin for this repo')
@@ -2,24 +2,37 @@ import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
 
4
4
  import { packageDefaults, packageRoot } from '../paths.mjs'
5
+ import { findWorkspaceRoot } from './workspace-resolve.mjs'
5
6
 
6
7
  export function getProjectRoot(startDir = process.cwd()) {
7
8
  return resolveProjectRoot(startDir)
8
9
  }
9
10
 
11
+ /** Nearest package.json with @xrystal/core — never walks above workspace root. */
10
12
  export function resolveProjectRoot(startDir = process.cwd()) {
11
13
  let dir = path.resolve(startDir)
14
+ const workspaceRoot = findWorkspaceRoot(dir)
15
+ const floor = workspaceRoot ? path.resolve(workspaceRoot) : null
12
16
 
13
- while (dir !== path.dirname(dir)) {
17
+ while (true) {
14
18
  const pkgPath = path.join(dir, 'package.json')
15
19
  if (fs.existsSync(pkgPath)) {
16
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
17
- if (pkg.name === packageDefaults.packageName) return dir
20
+ try {
21
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
22
+ if (pkg.name === packageDefaults.packageName) return dir
18
23
 
19
- const deps = { ...pkg.dependencies, ...pkg.devDependencies }
20
- if (deps[packageDefaults.packageName]) return dir
24
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies }
25
+ if (deps[packageDefaults.packageName]) return dir
26
+ } catch {
27
+ // ignore malformed package.json
28
+ }
21
29
  }
22
- dir = path.dirname(dir)
30
+
31
+ if (floor && path.resolve(dir) === floor) break
32
+
33
+ const parent = path.dirname(dir)
34
+ if (parent === dir) break
35
+ dir = parent
23
36
  }
24
37
 
25
38
  return path.resolve(startDir)
@@ -32,9 +32,14 @@ export function resolveSyncScope(cwd = process.cwd(), options = {}) {
32
32
  targetRoot: projectRoot,
33
33
  workspaceRoot: null,
34
34
  entries: [{ path: projectRoot, name: path.basename(projectRoot), type: 'project' }],
35
+ warnAllIgnored: wantAll,
35
36
  }
36
37
  }
37
38
 
39
+ if (atWorkspaceRoot && wantSelf) {
40
+ throw new Error('At workspace root use plain sync (all linked projects). --self is for inner api/web/mobile folders.')
41
+ }
42
+
38
43
  const entries = findEntries(workspaceRoot)
39
44
 
40
45
  if (atWorkspaceRoot || wantAll) {
@@ -66,6 +71,6 @@ export function resolveSyncScope(cwd = process.cwd(), options = {}) {
66
71
  targetRoot: projectRoot,
67
72
  workspaceRoot,
68
73
  entries: self ? [self] : [{ path: projectRoot, name: path.basename(projectRoot), type: 'project' }],
69
- hintAll: `Run ${options.cliName ?? 'xry'} sync --all from here to sync every linked api/admin/web project`,
74
+ hintAll: `Run ${options.cliName ?? 'xry'} sync --all from here to sync every linked api/web/mobile project`,
70
75
  }
71
76
  }
@@ -4,6 +4,8 @@ export {
4
4
  findEntries,
5
5
  findWorkspaceRoot,
6
6
  normalizeGlobalType,
7
+ parseFolderStructure,
8
+ readTmpFile,
7
9
  readWorkspaceCoreTmp,
8
10
  resolveEntryPath,
9
11
  workspaceProjectName,
@@ -0,0 +1,20 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ import { ensureTmpSchemaVersion } from './tmp-schema-version.mjs'
5
+ import { workspaceProjectName, workspaceTmpTemplate } from './workspace-resolve.mjs'
6
+
7
+ export function ensureOuterWorkspaceTmp(workspaceRoot, { projectName } = {}) {
8
+ const resolved = path.resolve(workspaceRoot)
9
+ const tmpPath = path.join(resolved, 'tmp.yml')
10
+ let created = false
11
+
12
+ if (!fs.existsSync(tmpPath)) {
13
+ const name = projectName ?? workspaceProjectName(resolved)
14
+ fs.writeFileSync(tmpPath, workspaceTmpTemplate(name))
15
+ created = true
16
+ }
17
+
18
+ const schema = ensureTmpSchemaVersion(tmpPath)
19
+ return { tmpFilePath: tmpPath, created, schema, workspaceRoot: resolved }
20
+ }
@@ -94,16 +94,38 @@ export function resolveMergedPaths(configs) {
94
94
  tmpRelPath: `${root}/${tmpName}`.replace(/\/+/g, '/'),
95
95
  };
96
96
  }
97
+ function readWorkspaceGlobalBlock(global) {
98
+ const pathsRaw = isRecord(global.paths) ? global.paths : {};
99
+ const root = typeof pathsRaw.root === 'string' && pathsRaw.root.trim() ? pathsRaw.root.trim() : '.';
100
+ const optionsRaw = isRecord(global.options) ? global.options : undefined;
101
+ return {
102
+ type: GlobalTypeEnum.WORKSPACE,
103
+ runtime: RuntimeEnum.BUN,
104
+ framework: '',
105
+ paths: {
106
+ root,
107
+ tmp: typeof pathsRaw.tmp === 'string' ? pathsRaw.tmp : 'tmp.yml',
108
+ },
109
+ vars: isRecord(global.vars) ? { ...global.vars } : {},
110
+ options: optionsRaw
111
+ ? { fileWatchIntervalMs: readWatchIntervalValue(optionsRaw.fileWatchIntervalMs) }
112
+ : undefined,
113
+ };
114
+ }
97
115
  export function readTmpGlobalBlock(configs) {
98
116
  const global = isRecord(configs?.global) ? configs.global : {};
99
117
  const varsRaw = isRecord(global.vars) ? global.vars : {};
100
118
  const typeRaw = global.type;
119
+ const type = typeRaw !== undefined ? normalizeGlobalType(typeRaw) : undefined;
120
+ if (type === GlobalTypeEnum.WORKSPACE) {
121
+ return readWorkspaceGlobalBlock(global);
122
+ }
101
123
  if (typeof global.framework !== 'string' || !global.framework.trim()) {
102
124
  throw new Error(`${defaults.packageName}: configs.global.framework is required`);
103
125
  }
104
126
  return {
105
127
  runtime: normalizeRuntime(global.runtime),
106
- type: typeRaw !== undefined ? normalizeGlobalType(typeRaw) : undefined,
128
+ type,
107
129
  framework: global.framework.trim(),
108
130
  paths: readTmpGlobalPathsBlock(configs),
109
131
  vars: { ...varsRaw },
@@ -177,6 +199,15 @@ export function resolveTmpRuntimeConfigs(tmp) {
177
199
  assertNoLegacyTmpKeys(configs);
178
200
  const global = readTmpGlobalBlock(configs);
179
201
  const depends = readTmpDependsBlock(configs);
202
+ if (global.type === GlobalTypeEnum.WORKSPACE) {
203
+ return {
204
+ global: { ...global, build: {} },
205
+ depends: buildNormalizedDepends(depends),
206
+ deploymentName: resolveTmpDeploymentName(tmp),
207
+ rootFolderPath: '.',
208
+ tmpRelPath: global.paths.tmp ?? 'tmp.yml',
209
+ };
210
+ }
180
211
  const merged = resolveMergedPaths(configs);
181
212
  return {
182
213
  global: {
@@ -3,8 +3,8 @@ export declare const TMP_FILE = "tmp.yml";
3
3
  export declare const SKIP_DIRS: Set<string>;
4
4
  export type FolderStructure = {
5
5
  api: string;
6
- admin: string;
7
6
  web: string;
7
+ mobile: string;
8
8
  };
9
9
  export declare const DEFAULT_FOLDER_STRUCTURE: FolderStructure;
10
10
  export type TmpMeta = {
@@ -17,19 +17,26 @@ export type TmpMeta = {
17
17
  pathsRoot?: string;
18
18
  folderStructure: FolderStructure;
19
19
  };
20
+ export type WorkspaceSlot = keyof FolderStructure;
20
21
  export type WorkspaceEntry = {
21
22
  name: string;
22
23
  type: GlobalTypeEnum.API_SERVICE | GlobalTypeEnum.FRONTEND;
23
24
  path: string;
24
25
  tmp: string;
25
- slot: keyof FolderStructure;
26
+ slot: WorkspaceSlot;
26
27
  cluster?: string;
27
28
  };
28
29
  export declare function readTmpFile(filePath: string): TmpMeta;
29
30
  export declare function parseFolderStructure(text: string): FolderStructure;
31
+ type DiscoverySlot = {
32
+ slot: WorkspaceSlot;
33
+ folder: string;
34
+ frontendOnly: boolean;
35
+ };
36
+ export declare function workspaceDiscoverySlots(fsMap: FolderStructure): DiscoverySlot[];
30
37
  export { normalizeGlobalType } from '../../../utils/helpers/tmp/tmp-schema';
31
38
  export declare function entryName(meta: TmpMeta): string | null;
32
- export declare function entryType(meta: TmpMeta, slot: keyof FolderStructure): GlobalTypeEnum | null;
39
+ export declare function entryType(meta: TmpMeta, slot: WorkspaceSlot): GlobalTypeEnum | null;
33
40
  export declare function findWorkspaceRoot(startDir?: string): string | null;
34
41
  export declare function findEntries(workspaceRoot: string): WorkspaceEntry[];
35
42
  export declare function findApiServices(workspaceRoot: string): WorkspaceEntry[];
@@ -6,8 +6,8 @@ export const TMP_FILE = 'tmp.yml';
6
6
  export const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.turbo', 'coverage']);
7
7
  export const DEFAULT_FOLDER_STRUCTURE = {
8
8
  api: 'api',
9
- admin: 'admin',
10
9
  web: 'web',
10
+ mobile: 'mobile',
11
11
  };
12
12
  function parseScalar(raw) {
13
13
  const trimmed = raw.trim();
@@ -43,18 +43,28 @@ export function readTmpFile(filePath) {
43
43
  }
44
44
  export function parseFolderStructure(text) {
45
45
  const fsBlock = text.match(/folder-structure:\s*\n((?:[ \t]+[^\n]+\n?)*)/)?.[1] ?? '';
46
+ if (/^[ \t]+admin:/m.test(fsBlock)) {
47
+ throw new Error('configs.folder-structure.admin removed — put admin panels under web/ (e.g. web/admin-ui)');
48
+ }
46
49
  const readSlot = (key) => {
47
- const scalar = fsBlock.match(new RegExp(`^[ \t]+${key}:\s*(.+?)(?:\s+#.*)?$`, 'm'));
50
+ const scalar = fsBlock.match(new RegExp(`^[ \t]+${key}:\\s*(.+?)(?:\\s+#.*)?$`, 'm'));
48
51
  if (scalar)
49
52
  return parseScalar(scalar[1]);
50
53
  return DEFAULT_FOLDER_STRUCTURE[key];
51
54
  };
52
55
  return {
53
56
  api: readSlot('api'),
54
- admin: readSlot('admin'),
55
57
  web: readSlot('web'),
58
+ mobile: readSlot('mobile'),
56
59
  };
57
60
  }
61
+ export function workspaceDiscoverySlots(fsMap) {
62
+ return [
63
+ { slot: 'api', folder: fsMap.api, frontendOnly: false },
64
+ { slot: 'web', folder: fsMap.web, frontendOnly: true },
65
+ { slot: 'mobile', folder: fsMap.mobile, frontendOnly: true },
66
+ ];
67
+ }
58
68
  export { normalizeGlobalType } from '../../../utils/helpers/tmp/tmp-schema.js';
59
69
  export function entryName(meta) {
60
70
  const project = (meta.projectName ?? '').trim();
@@ -149,9 +159,8 @@ export function findEntries(workspaceRoot) {
149
159
  const fsMap = wsMeta.folderStructure;
150
160
  const entries = [];
151
161
  const seen = new Set();
152
- const slots = ['api', 'admin', 'web'];
153
- for (const slot of slots) {
154
- const folder = path.join(workspaceRoot, fsMap[slot]);
162
+ for (const { slot, folder: folderRel, frontendOnly } of workspaceDiscoverySlots(fsMap)) {
163
+ const folder = path.join(workspaceRoot, folderRel);
155
164
  for (const tmpPath of walkTmpUnder(folder)) {
156
165
  if (path.resolve(tmpPath) === path.join(workspaceRoot, TMP_FILE))
157
166
  continue;
@@ -159,7 +168,7 @@ export function findEntries(workspaceRoot) {
159
168
  const kind = entryType(meta, slot);
160
169
  if (kind === GlobalTypeEnum.WORKSPACE)
161
170
  continue;
162
- if (slot !== 'api' && kind !== GlobalTypeEnum.FRONTEND)
171
+ if (frontendOnly && kind !== GlobalTypeEnum.FRONTEND)
163
172
  continue;
164
173
  if (kind !== GlobalTypeEnum.API_SERVICE && kind !== GlobalTypeEnum.FRONTEND)
165
174
  continue;
@@ -207,17 +216,10 @@ export function workspaceTmpTemplate(projectName) {
207
216
  configs:
208
217
  global:
209
218
  type: workspace
210
- runtime: bun
211
- framework: bun
212
- paths:
213
- root: .
214
- tmp: tmp.yml
215
- options:
216
- fileWatchIntervalMs: 500
217
219
  folder-structure:
218
220
  api: api
219
- admin: admin
220
221
  web: web
222
+ mobile: mobile
221
223
 
222
224
  kubeconfig: ~/.kube/config
223
225