@xrystal/core 3.53.1 → 3.53.3

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.53.1",
4
+ "version": "3.53.3",
5
5
  "description": "microservice runtime library",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -6,8 +6,8 @@ import { CLI_PRIMARY_NAME } from '../helpers/cli-identity.mjs'
6
6
  import { readCliPackageJson } from '../helpers/project-root.mjs'
7
7
  import { ensureTmpFile } from '../helpers/tmp-layout.mjs'
8
8
  import { ensureTmpSchemaVersion } from '../helpers/tmp-schema-version.mjs'
9
- import { syncRegistryFromPath } from '../helpers/xrystal-registry.mjs'
10
9
  import { resolveSyncScope } from '../helpers/sync-scope.mjs'
10
+ import { runWorkspaceSelfHeal } from '../helpers/workspace-heal.mjs'
11
11
  import { printSyncProjectResult, syncOneProject } from '../helpers/sync-project.mjs'
12
12
  import { formatSyncHelp } from '../helpers/cli-help.mjs'
13
13
 
@@ -25,6 +25,19 @@ export function registerSyncCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
25
25
  }
26
26
 
27
27
  printCommandHeader({ cliName, command: 'sync', version: coreVersion })
28
+
29
+ let workspaceHeal = null
30
+ if (scope.workspaceRoot && !options.dryRun) {
31
+ workspaceHeal = runWorkspaceSelfHeal(scope.workspaceRoot, {
32
+ forceRegistry: scope.mode === 'workspace-all',
33
+ })
34
+ if (workspaceHeal.slotDirsCreated.length) {
35
+ console.log(chalk.green(` layout: created ${workspaceHeal.slotDirsCreated.join(', ')}/`))
36
+ }
37
+ if (workspaceHeal.tmpOptionsPatched) {
38
+ console.log(chalk.green(' outer tmp: added global.options.fileWatchIntervalMs'))
39
+ }
40
+ }
28
41
  if (scope.warnAllIgnored) {
29
42
  console.log(chalk.yellow(' note: not in a workspace — --all ignored, syncing this repo only'))
30
43
  }
@@ -71,13 +84,8 @@ export function registerSyncCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
71
84
  if (result.failed) failed += 1
72
85
  }
73
86
 
74
- if (scope.mode === 'workspace-all' && scope.workspaceRoot && !options.dryRun) {
75
- try {
76
- syncRegistryFromPath(scope.workspaceRoot)
77
- console.log(chalk.gray('\n registry updated (~/.xrystal)'))
78
- } catch (error) {
79
- console.log(chalk.yellow(`\n registry skipped: ${error.message}`))
80
- }
87
+ if (workspaceHeal?.registryChanged) {
88
+ console.log(chalk.gray('\n registry healed (~/.xrystal)'))
81
89
  }
82
90
 
83
91
  if (scope.hintAll) {
@@ -0,0 +1,91 @@
1
+ import chalk from 'chalk'
2
+
3
+ import { printCommandFooter, printCommandHeader } from '../helpers/banner.mjs'
4
+ import { CLI_PRIMARY_NAME } from '../helpers/cli-identity.mjs'
5
+ import { readCliPackageJson } from '../helpers/project-root.mjs'
6
+ import { collectWatchTargets } from '../helpers/xrystal-watch-daemon.mjs'
7
+ import { readRegistry, resolveXrystalHome } from '../helpers/xrystal-registry.mjs'
8
+ import {
9
+ ensureWatchDaemon,
10
+ startWatchDaemon,
11
+ stopWatchDaemon,
12
+ watchDaemonStatus,
13
+ watchLogPath,
14
+ } from '../helpers/xrystal-watch-spawn.mjs'
15
+
16
+ export function registerWatchCommand(cli, { cliName = CLI_PRIMARY_NAME } = {}) {
17
+ const watch = cli
18
+ .command('watch')
19
+ .description('~/.xrystal background tmp watcher — auto self-heal for registered workspaces')
20
+
21
+ watch
22
+ .command('start', { isDefault: true })
23
+ .description('Start background daemon (also auto-starts on workspace sync/project)')
24
+ .option('--foreground', 'Run in foreground (debug)')
25
+ .action((options) => {
26
+ const version = readCliPackageJson().version
27
+ printCommandHeader({ cliName, command: 'watch start', version })
28
+
29
+ const result = startWatchDaemon({ detached: !options.foreground, quiet: false })
30
+ if (result.started) {
31
+ console.log(chalk.green(` daemon started (pid ${result.pid})`))
32
+ console.log(chalk.gray(` log: ${watchLogPath()}`))
33
+ } else if (result.running) {
34
+ console.log(chalk.gray(` already running (pid ${result.pid})`))
35
+ }
36
+
37
+ printCommandFooter({ version })
38
+ })
39
+
40
+ watch
41
+ .command('stop')
42
+ .description('Stop background daemon')
43
+ .action(() => {
44
+ const version = readCliPackageJson().version
45
+ printCommandHeader({ cliName, command: 'watch stop', version })
46
+
47
+ const result = stopWatchDaemon()
48
+ if (result.stopped) {
49
+ console.log(chalk.green(` stopped pid ${result.pid}`))
50
+ } else {
51
+ console.log(chalk.gray(' not running'))
52
+ }
53
+
54
+ printCommandFooter({ version })
55
+ })
56
+
57
+ watch
58
+ .command('status')
59
+ .description('Show daemon state and watched tmp paths')
60
+ .action(() => {
61
+ const version = readCliPackageJson().version
62
+ printCommandHeader({ cliName, command: 'watch status', version })
63
+
64
+ const status = watchDaemonStatus()
65
+ console.log(chalk.gray(` home: ${resolveXrystalHome()}`))
66
+ console.log(status.running
67
+ ? chalk.green(` running pid ${status.pid}`)
68
+ : chalk.yellow(' not running'))
69
+
70
+ const targets = collectWatchTargets(readRegistry())
71
+ console.log(chalk.gray(` watching ${targets.length} tmp file(s)`))
72
+ for (const target of targets) {
73
+ console.log(` • [${target.kind}] ${target.file}`)
74
+ }
75
+
76
+ if (status.running) {
77
+ console.log(chalk.gray(`\n log: ${watchLogPath()}`))
78
+ } else {
79
+ console.log(chalk.dim('\n tip: auto-starts on xry sync / xry project inside a workspace'))
80
+ }
81
+
82
+ printCommandFooter({ version })
83
+ })
84
+
85
+ watch
86
+ .command('ensure')
87
+ .description('Start daemon only if not running (internal / CI)')
88
+ .action(() => {
89
+ ensureWatchDaemon({ quiet: false })
90
+ })
91
+ }
@@ -1,6 +1,6 @@
1
1
  // source/utils/helpers/workspace/index.ts
2
2
  import fs2 from "node:fs";
3
- import path2 from "node:path";
3
+ import path4 from "node:path";
4
4
 
5
5
  // source/utils/models/enums/index.ts
6
6
  var GlobalTypeEnum;
@@ -9,6 +9,16 @@ var GlobalTypeEnum;
9
9
  GlobalTypeEnum2["API_SERVICE"] = "api-service";
10
10
  GlobalTypeEnum2["FRONTEND"] = "frontend";
11
11
  })(GlobalTypeEnum ||= {});
12
+
13
+ // source/utils/constants/index.ts
14
+ import path3 from "node:path";
15
+
16
+ // source/utils/constants/package-root.ts
17
+ import path from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+ var constantsDir = path.dirname(fileURLToPath(import.meta.url));
20
+ var sourceDir = path.resolve(constantsDir, "..", "..");
21
+ var packageRootDir = path.resolve(constantsDir, "..", "..", "..");
12
22
  // source/utils/constants/defaults.json
13
23
  var defaults_default = {
14
24
  packageName: "@xrystal/core",
@@ -81,8 +91,8 @@ var defaults_default = {
81
91
 
82
92
  // source/utils/helpers/tmp/seed-from-tmp.ts
83
93
  import fs from "node:fs";
84
- import path from "node:path";
85
- import { fileURLToPath } from "node:url";
94
+ import path2 from "node:path";
95
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
86
96
  import yaml from "yaml";
87
97
 
88
98
  // source/utils/helpers/tmp/path-normalize.ts
@@ -101,7 +111,7 @@ function normalizeSourceFolder(value, fallback) {
101
111
  }
102
112
 
103
113
  // source/utils/helpers/tmp/seed-from-tmp.ts
104
- var here = path.dirname(fileURLToPath(import.meta.url));
114
+ var here = path2.dirname(fileURLToPath2(import.meta.url));
105
115
  var templateRel = defaults_default.apiServiceTemplateRel ?? "x/templates/api-service/tmp.yml";
106
116
  function requireString(value, label) {
107
117
  if (typeof value !== "string" || !value.trim()) {
@@ -118,14 +128,14 @@ function readLayoutFromSpecial(special) {
118
128
  };
119
129
  }
120
130
  function findApiTemplate() {
121
- const starts = [here, process.cwd()].map((value) => path.resolve(value));
131
+ const starts = [here, process.cwd()].map((value) => path2.resolve(value));
122
132
  for (const start of starts) {
123
133
  let dir = start;
124
134
  for (;; ) {
125
- const candidate = path.join(dir, templateRel);
135
+ const candidate = path2.join(dir, templateRel);
126
136
  if (fs.existsSync(candidate))
127
137
  return candidate;
128
- const parent = path.dirname(dir);
138
+ const parent = path2.dirname(dir);
129
139
  if (parent === dir)
130
140
  break;
131
141
  dir = parent;
@@ -154,6 +164,42 @@ function loadSeedFromBundledTmp(tmpFilePath) {
154
164
  }
155
165
  var seedFromTmp = loadSeedFromBundledTmp();
156
166
 
167
+ // source/utils/constants/index.ts
168
+ var packageDefaults = Object.freeze({
169
+ ...defaults_default,
170
+ mainSourceFolder: seedFromTmp.sourceFolder,
171
+ framework: seedFromTmp.framework,
172
+ layoutPaths: Object.freeze({ ...seedFromTmp.layout }),
173
+ brand: Object.freeze({ ...defaults_default.brand }),
174
+ runtimes: Object.freeze(Object.fromEntries(Object.entries(defaults_default.runtimes).map(([key, value]) => [key, Object.freeze({ ...value })]))),
175
+ bundlers: Object.freeze([...defaults_default.bundlers]),
176
+ buildDefaults: Object.freeze({ ...defaults_default.buildDefaults }),
177
+ tmpWatchDefaults: Object.freeze({ ...defaults_default.tmpWatchDefaults }),
178
+ cliBinNames: Object.freeze([...defaults_default.cliBinNames ?? [defaults_default.cliName]])
179
+ });
180
+ var tmpFileName = `${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;
181
+
182
+ class Constants {
183
+ static packageName = packageDefaults.packageName;
184
+ static packageRootFolder = packageDefaults.packageRootFolder;
185
+ static tmpBaseName = packageDefaults.tmpBaseName;
186
+ static tmpExtension = packageDefaults.tmpExtension;
187
+ static publicFolderName = packageDefaults.publicFolderName;
188
+ static kafkaLogsTopic = packageDefaults.kafkaLogsTopic;
189
+ static templateRepoUri = packageDefaults.templateRepoUri;
190
+ static cliName = packageDefaults.cliName;
191
+ static cliBinNames = packageDefaults.cliBinNames;
192
+ static pathAliasKey = packageDefaults.pathAliasKey;
193
+ static brand = packageDefaults.brand;
194
+ static mainSourceFolder = packageDefaults.mainSourceFolder;
195
+ static framework = packageDefaults.framework;
196
+ static layoutPaths = packageDefaults.layoutPaths;
197
+ static cliBinFile = packageDefaults.cliBinFile;
198
+ static logTag = packageDefaults.packageName;
199
+ static bundledApiServiceTmpPath = path3.join(packageRootDir, packageDefaults.apiServiceTemplateRel ?? `${packageDefaults.packageRootFolder}/templates/api-service/${tmpFileName}`);
200
+ static bundledCoreTmpPath = path3.join(packageRootDir, packageDefaults.packageRootFolder, tmpFileName);
201
+ }
202
+
157
203
  // source/utils/helpers/tmp/tmp-interpolate.ts
158
204
  import Handlebars from "handlebars";
159
205
 
@@ -251,15 +297,15 @@ function entryType(meta, slot) {
251
297
  return null;
252
298
  }
253
299
  function findWorkspaceRoot(startDir = process.cwd()) {
254
- let cur = path2.resolve(startDir);
300
+ let cur = path4.resolve(startDir);
255
301
  for (;; ) {
256
- const candidate = path2.join(cur, TMP_FILE);
302
+ const candidate = path4.join(cur, TMP_FILE);
257
303
  if (fs2.existsSync(candidate)) {
258
304
  const meta = readTmpFile(candidate);
259
305
  if (meta.globalType === "workspace" /* WORKSPACE */)
260
306
  return cur;
261
307
  }
262
- const parent = path2.dirname(cur);
308
+ const parent = path4.dirname(cur);
263
309
  if (parent === cur)
264
310
  break;
265
311
  cur = parent;
@@ -292,7 +338,7 @@ function walkTmpUnder(rootDir) {
292
338
  continue;
293
339
  }
294
340
  for (const entry of entries) {
295
- const full = path2.join(dir, entry.name);
341
+ const full = path4.join(dir, entry.name);
296
342
  if (isTraversableDir(entry, full)) {
297
343
  if (SKIP_DIRS.has(entry.name) || entry.name.startsWith("."))
298
344
  continue;
@@ -319,14 +365,14 @@ function repoRootFromTmp(tmpPath, meta) {
319
365
  throw new Error(`tmp path mismatch: expected */${rel}, got ${abs}`);
320
366
  }
321
367
  function findEntries(workspaceRoot) {
322
- const wsMeta = readTmpFile(path2.join(workspaceRoot, TMP_FILE));
368
+ const wsMeta = readTmpFile(path4.join(workspaceRoot, TMP_FILE));
323
369
  const fsMap = wsMeta.folderStructure;
324
370
  const entries = [];
325
371
  const seen = new Set;
326
372
  for (const { slot, folder: folderRel, frontendOnly } of workspaceDiscoverySlots(fsMap)) {
327
- const folder = path2.join(workspaceRoot, folderRel);
373
+ const folder = path4.join(workspaceRoot, folderRel);
328
374
  for (const tmpPath of walkTmpUnder(folder)) {
329
- if (path2.resolve(tmpPath) === path2.join(workspaceRoot, TMP_FILE))
375
+ if (path4.resolve(tmpPath) === path4.join(workspaceRoot, TMP_FILE))
330
376
  continue;
331
377
  const meta = readTmpFile(tmpPath);
332
378
  const kind = entryType(meta, slot);
@@ -363,14 +409,46 @@ function resolveEntryPath(workspaceRoot, name) {
363
409
  return hit?.path ?? null;
364
410
  }
365
411
  function workspaceProjectName(workspaceRoot) {
366
- const meta = readTmpFile(path2.join(workspaceRoot, TMP_FILE));
367
- return meta.projectName?.trim() || path2.basename(workspaceRoot);
412
+ const meta = readTmpFile(path4.join(workspaceRoot, TMP_FILE));
413
+ return meta.projectName?.trim() || path4.basename(workspaceRoot);
368
414
  }
369
415
  function readWorkspaceGlobalTmp(workspaceRoot) {
370
- const text = fs2.readFileSync(path2.join(workspaceRoot, TMP_FILE), "utf8");
416
+ const text = fs2.readFileSync(path4.join(workspaceRoot, TMP_FILE), "utf8");
371
417
  const match = text.match(/options:\s*\n(?:[ \t]+[^\n]+\n)*?[ \t]+fileWatchIntervalMs:\s*(\d+)/m) ?? text.match(/fileWatchIntervalMs:\s*(\d+)/);
372
418
  return match ? { fileWatchIntervalMs: Number(match[1]) } : {};
373
419
  }
420
+ function ensureWorkspaceSlotDirs(workspaceRoot) {
421
+ const tmpPath = path4.join(workspaceRoot, TMP_FILE);
422
+ if (!fs2.existsSync(tmpPath))
423
+ return [];
424
+ const meta = readTmpFile(tmpPath);
425
+ const created = [];
426
+ for (const folder of Object.values(meta.folderStructure)) {
427
+ const dir = path4.join(workspaceRoot, folder);
428
+ if (!fs2.existsSync(dir)) {
429
+ fs2.mkdirSync(dir, { recursive: true });
430
+ created.push(folder);
431
+ }
432
+ }
433
+ return created;
434
+ }
435
+ function healWorkspaceOuterTmpOptions(workspaceRoot) {
436
+ const tmpPath = path4.join(workspaceRoot, TMP_FILE);
437
+ if (!fs2.existsSync(tmpPath))
438
+ return false;
439
+ const text = fs2.readFileSync(tmpPath, "utf8");
440
+ if (/fileWatchIntervalMs:\s*\d+/m.test(text))
441
+ return false;
442
+ const defaultMs = packageDefaults.tmpWatchDefaults.intervalMs;
443
+ const insertBlock = ` options:
444
+ fileWatchIntervalMs: ${defaultMs}
445
+ `;
446
+ const patched = text.replace(/(configs:\s*\n\s+global:\s*\n\s+type:\s*workspace\s*\n)/m, `$1${insertBlock}`);
447
+ if (patched === text)
448
+ return false;
449
+ fs2.writeFileSync(tmpPath, patched);
450
+ return true;
451
+ }
374
452
  var readWorkspaceCoreTmp = readWorkspaceGlobalTmp;
375
453
  function workspaceTmpTemplate(projectName) {
376
454
  return `project:
@@ -379,6 +457,8 @@ function workspaceTmpTemplate(projectName) {
379
457
  configs:
380
458
  global:
381
459
  type: workspace
460
+ options:
461
+ fileWatchIntervalMs: 500
382
462
  folder-structure:
383
463
  api: api
384
464
  web: web
@@ -400,11 +480,13 @@ export {
400
480
  readTmpFile,
401
481
  parseFolderStructure,
402
482
  normalizeGlobalType,
483
+ healWorkspaceOuterTmpOptions,
403
484
  findWorkspaceRoot,
404
485
  findEntries,
405
486
  findApiServices,
406
487
  entryType,
407
488
  entryName,
489
+ ensureWorkspaceSlotDirs,
408
490
  TMP_FILE,
409
491
  SKIP_DIRS,
410
492
  DEFAULT_FOLDER_STRUCTURE
@@ -1,11 +1,11 @@
1
1
  // source/utils/helpers/xrystal-home/registry.ts
2
2
  import fs3 from "node:fs";
3
3
  import os from "node:os";
4
- import path3 from "node:path";
4
+ import path5 from "node:path";
5
5
 
6
6
  // source/utils/helpers/workspace/index.ts
7
7
  import fs2 from "node:fs";
8
- import path2 from "node:path";
8
+ import path4 from "node:path";
9
9
 
10
10
  // source/utils/models/enums/index.ts
11
11
  var GlobalTypeEnum;
@@ -14,6 +14,16 @@ var GlobalTypeEnum;
14
14
  GlobalTypeEnum2["API_SERVICE"] = "api-service";
15
15
  GlobalTypeEnum2["FRONTEND"] = "frontend";
16
16
  })(GlobalTypeEnum ||= {});
17
+
18
+ // source/utils/constants/index.ts
19
+ import path3 from "node:path";
20
+
21
+ // source/utils/constants/package-root.ts
22
+ import path from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ var constantsDir = path.dirname(fileURLToPath(import.meta.url));
25
+ var sourceDir = path.resolve(constantsDir, "..", "..");
26
+ var packageRootDir = path.resolve(constantsDir, "..", "..", "..");
17
27
  // source/utils/constants/defaults.json
18
28
  var defaults_default = {
19
29
  packageName: "@xrystal/core",
@@ -86,8 +96,8 @@ var defaults_default = {
86
96
 
87
97
  // source/utils/helpers/tmp/seed-from-tmp.ts
88
98
  import fs from "node:fs";
89
- import path from "node:path";
90
- import { fileURLToPath } from "node:url";
99
+ import path2 from "node:path";
100
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
91
101
  import yaml from "yaml";
92
102
 
93
103
  // source/utils/helpers/tmp/path-normalize.ts
@@ -106,7 +116,7 @@ function normalizeSourceFolder(value, fallback) {
106
116
  }
107
117
 
108
118
  // source/utils/helpers/tmp/seed-from-tmp.ts
109
- var here = path.dirname(fileURLToPath(import.meta.url));
119
+ var here = path2.dirname(fileURLToPath2(import.meta.url));
110
120
  var templateRel = defaults_default.apiServiceTemplateRel ?? "x/templates/api-service/tmp.yml";
111
121
  function requireString(value, label) {
112
122
  if (typeof value !== "string" || !value.trim()) {
@@ -123,14 +133,14 @@ function readLayoutFromSpecial(special) {
123
133
  };
124
134
  }
125
135
  function findApiTemplate() {
126
- const starts = [here, process.cwd()].map((value) => path.resolve(value));
136
+ const starts = [here, process.cwd()].map((value) => path2.resolve(value));
127
137
  for (const start of starts) {
128
138
  let dir = start;
129
139
  for (;; ) {
130
- const candidate = path.join(dir, templateRel);
140
+ const candidate = path2.join(dir, templateRel);
131
141
  if (fs.existsSync(candidate))
132
142
  return candidate;
133
- const parent = path.dirname(dir);
143
+ const parent = path2.dirname(dir);
134
144
  if (parent === dir)
135
145
  break;
136
146
  dir = parent;
@@ -159,6 +169,42 @@ function loadSeedFromBundledTmp(tmpFilePath) {
159
169
  }
160
170
  var seedFromTmp = loadSeedFromBundledTmp();
161
171
 
172
+ // source/utils/constants/index.ts
173
+ var packageDefaults = Object.freeze({
174
+ ...defaults_default,
175
+ mainSourceFolder: seedFromTmp.sourceFolder,
176
+ framework: seedFromTmp.framework,
177
+ layoutPaths: Object.freeze({ ...seedFromTmp.layout }),
178
+ brand: Object.freeze({ ...defaults_default.brand }),
179
+ runtimes: Object.freeze(Object.fromEntries(Object.entries(defaults_default.runtimes).map(([key, value]) => [key, Object.freeze({ ...value })]))),
180
+ bundlers: Object.freeze([...defaults_default.bundlers]),
181
+ buildDefaults: Object.freeze({ ...defaults_default.buildDefaults }),
182
+ tmpWatchDefaults: Object.freeze({ ...defaults_default.tmpWatchDefaults }),
183
+ cliBinNames: Object.freeze([...defaults_default.cliBinNames ?? [defaults_default.cliName]])
184
+ });
185
+ var tmpFileName = `${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;
186
+
187
+ class Constants {
188
+ static packageName = packageDefaults.packageName;
189
+ static packageRootFolder = packageDefaults.packageRootFolder;
190
+ static tmpBaseName = packageDefaults.tmpBaseName;
191
+ static tmpExtension = packageDefaults.tmpExtension;
192
+ static publicFolderName = packageDefaults.publicFolderName;
193
+ static kafkaLogsTopic = packageDefaults.kafkaLogsTopic;
194
+ static templateRepoUri = packageDefaults.templateRepoUri;
195
+ static cliName = packageDefaults.cliName;
196
+ static cliBinNames = packageDefaults.cliBinNames;
197
+ static pathAliasKey = packageDefaults.pathAliasKey;
198
+ static brand = packageDefaults.brand;
199
+ static mainSourceFolder = packageDefaults.mainSourceFolder;
200
+ static framework = packageDefaults.framework;
201
+ static layoutPaths = packageDefaults.layoutPaths;
202
+ static cliBinFile = packageDefaults.cliBinFile;
203
+ static logTag = packageDefaults.packageName;
204
+ static bundledApiServiceTmpPath = path3.join(packageRootDir, packageDefaults.apiServiceTemplateRel ?? `${packageDefaults.packageRootFolder}/templates/api-service/${tmpFileName}`);
205
+ static bundledCoreTmpPath = path3.join(packageRootDir, packageDefaults.packageRootFolder, tmpFileName);
206
+ }
207
+
162
208
  // source/utils/helpers/tmp/tmp-interpolate.ts
163
209
  import Handlebars from "handlebars";
164
210
 
@@ -180,9 +226,9 @@ function normalizeGlobalType(value) {
180
226
  var TMP_FILE = "tmp.yml";
181
227
  var SKIP_DIRS = new Set(["node_modules", ".git", "dist", ".turbo", "coverage"]);
182
228
  var DEFAULT_FOLDER_STRUCTURE = {
183
- api: "api",
184
- admin: "admin",
185
- web: "web"
229
+ ["api" /* API */]: "api",
230
+ ["web" /* WEB */]: "web",
231
+ ["mobile" /* MOBILE */]: "mobile"
186
232
  };
187
233
  function parseScalar(raw) {
188
234
  const trimmed = raw.trim();
@@ -216,18 +262,28 @@ function readTmpFile(filePath) {
216
262
  }
217
263
  function parseFolderStructure(text) {
218
264
  const fsBlock = text.match(/folder-structure:\s*\n((?:[ \t]+[^\n]+\n?)*)/)?.[1] ?? "";
265
+ if (/^[ \t]+admin:/m.test(fsBlock)) {
266
+ throw new Error("configs.folder-structure.admin removed — put admin panels under web/ (e.g. web/admin-ui)");
267
+ }
219
268
  const readSlot = (key) => {
220
- const scalar = fsBlock.match(new RegExp(`^[ ]+${key}:s*(.+?)(?:s+#.*)?$`, "m"));
269
+ const scalar = fsBlock.match(new RegExp(`^[ \\t]+${key}:\\s*(.+?)(?:\\s+#.*)?$`, "m"));
221
270
  if (scalar)
222
271
  return parseScalar(scalar[1]);
223
272
  return DEFAULT_FOLDER_STRUCTURE[key];
224
273
  };
225
274
  return {
226
- api: readSlot("api"),
227
- admin: readSlot("admin"),
228
- web: readSlot("web")
275
+ ["api" /* API */]: readSlot("api" /* API */),
276
+ ["web" /* WEB */]: readSlot("web" /* WEB */),
277
+ ["mobile" /* MOBILE */]: readSlot("mobile" /* MOBILE */)
229
278
  };
230
279
  }
280
+ function workspaceDiscoverySlots(fsMap) {
281
+ return [
282
+ { slot: "api" /* API */, folder: fsMap["api" /* API */], frontendOnly: false },
283
+ { slot: "web" /* WEB */, folder: fsMap["web" /* WEB */], frontendOnly: true },
284
+ { slot: "mobile" /* MOBILE */, folder: fsMap["mobile" /* MOBILE */], frontendOnly: true }
285
+ ];
286
+ }
231
287
  function entryName(meta) {
232
288
  const project = (meta.projectName ?? "").trim();
233
289
  return project || null;
@@ -241,20 +297,20 @@ function entryType(meta, slot) {
241
297
  return null;
242
298
  }
243
299
  }
244
- if (slot === "api")
300
+ if (slot === "api" /* API */)
245
301
  return "api-service" /* API_SERVICE */;
246
302
  return null;
247
303
  }
248
304
  function findWorkspaceRoot(startDir = process.cwd()) {
249
- let cur = path2.resolve(startDir);
305
+ let cur = path4.resolve(startDir);
250
306
  for (;; ) {
251
- const candidate = path2.join(cur, TMP_FILE);
307
+ const candidate = path4.join(cur, TMP_FILE);
252
308
  if (fs2.existsSync(candidate)) {
253
309
  const meta = readTmpFile(candidate);
254
310
  if (meta.globalType === "workspace" /* WORKSPACE */)
255
311
  return cur;
256
312
  }
257
- const parent = path2.dirname(cur);
313
+ const parent = path4.dirname(cur);
258
314
  if (parent === cur)
259
315
  break;
260
316
  cur = parent;
@@ -287,7 +343,7 @@ function walkTmpUnder(rootDir) {
287
343
  continue;
288
344
  }
289
345
  for (const entry of entries) {
290
- const full = path2.join(dir, entry.name);
346
+ const full = path4.join(dir, entry.name);
291
347
  if (isTraversableDir(entry, full)) {
292
348
  if (SKIP_DIRS.has(entry.name) || entry.name.startsWith("."))
293
349
  continue;
@@ -314,21 +370,20 @@ function repoRootFromTmp(tmpPath, meta) {
314
370
  throw new Error(`tmp path mismatch: expected */${rel}, got ${abs}`);
315
371
  }
316
372
  function findEntries(workspaceRoot) {
317
- const wsMeta = readTmpFile(path2.join(workspaceRoot, TMP_FILE));
373
+ const wsMeta = readTmpFile(path4.join(workspaceRoot, TMP_FILE));
318
374
  const fsMap = wsMeta.folderStructure;
319
375
  const entries = [];
320
376
  const seen = new Set;
321
- const slots = ["api", "admin", "web"];
322
- for (const slot of slots) {
323
- const folder = path2.join(workspaceRoot, fsMap[slot]);
377
+ for (const { slot, folder: folderRel, frontendOnly } of workspaceDiscoverySlots(fsMap)) {
378
+ const folder = path4.join(workspaceRoot, folderRel);
324
379
  for (const tmpPath of walkTmpUnder(folder)) {
325
- if (path2.resolve(tmpPath) === path2.join(workspaceRoot, TMP_FILE))
380
+ if (path4.resolve(tmpPath) === path4.join(workspaceRoot, TMP_FILE))
326
381
  continue;
327
382
  const meta = readTmpFile(tmpPath);
328
383
  const kind = entryType(meta, slot);
329
384
  if (kind === "workspace" /* WORKSPACE */)
330
385
  continue;
331
- if (slot !== "api" && kind !== "frontend" /* FRONTEND */)
386
+ if (frontendOnly && kind !== "frontend" /* FRONTEND */)
332
387
  continue;
333
388
  if (kind !== "api-service" /* API_SERVICE */ && kind !== "frontend" /* FRONTEND */)
334
389
  continue;
@@ -355,14 +410,14 @@ function findEntries(workspaceRoot) {
355
410
  // source/utils/helpers/xrystal-home/registry.ts
356
411
  var XRYSTAL_HOME_DIR = ".xrystal";
357
412
  function resolveXrystalHome() {
358
- return path3.join(os.homedir(), XRYSTAL_HOME_DIR);
413
+ return path5.join(os.homedir(), XRYSTAL_HOME_DIR);
359
414
  }
360
415
  function registryFilePath() {
361
- return path3.join(resolveXrystalHome(), "registry.json");
416
+ return path5.join(resolveXrystalHome(), "registry.json");
362
417
  }
363
418
  function ensureXrystalHome() {
364
419
  const home = resolveXrystalHome();
365
- fs3.mkdirSync(path3.join(home, "workspaces"), { recursive: true });
420
+ fs3.mkdirSync(path5.join(home, "workspaces"), { recursive: true });
366
421
  return home;
367
422
  }
368
423
  function entryToRegistryProject(entry) {
@@ -375,7 +430,7 @@ function entryToRegistryProject(entry) {
375
430
  };
376
431
  }
377
432
  function normalizeRegistryPath(input) {
378
- const resolved = path3.resolve(input);
433
+ const resolved = path5.resolve(input);
379
434
  try {
380
435
  return fs3.realpathSync.native(resolved);
381
436
  } catch {
@@ -385,7 +440,7 @@ function normalizeRegistryPath(input) {
385
440
  function scanWorkspace(workspacePath, workspaceName) {
386
441
  const root = normalizeRegistryPath(workspacePath);
387
442
  const entries = findEntries(root);
388
- const name = workspaceName ?? path3.basename(root);
443
+ const name = workspaceName ?? path5.basename(root);
389
444
  return {
390
445
  name,
391
446
  path: root,
@@ -407,12 +462,12 @@ function writeRegistry(registry) {
407
462
  fs3.writeFileSync(registryFilePath(), `${JSON.stringify(registry, null, 2)}
408
463
  `);
409
464
  for (const ws of registry.workspaces) {
410
- const wsDir = path3.join(resolveXrystalHome(), "workspaces", ws.name);
465
+ const wsDir = path5.join(resolveXrystalHome(), "workspaces", ws.name);
411
466
  fs3.mkdirSync(wsDir, { recursive: true });
412
- fs3.writeFileSync(path3.join(wsDir, "workspace.json"), `${JSON.stringify(ws, null, 2)}
467
+ fs3.writeFileSync(path5.join(wsDir, "workspace.json"), `${JSON.stringify(ws, null, 2)}
413
468
  `);
414
469
  for (const project of ws.projects) {
415
- fs3.writeFileSync(path3.join(wsDir, `${project.name}.json`), `${JSON.stringify(project, null, 2)}
470
+ fs3.writeFileSync(path5.join(wsDir, `${project.name}.json`), `${JSON.stringify(project, null, 2)}
416
471
  `);
417
472
  }
418
473
  }
@@ -429,11 +484,37 @@ function syncRegistryFromPath(startDir = process.cwd()) {
429
484
  if (!workspaceRoot) {
430
485
  throw new Error("No workspace tmp.yml found — run xry create demo --workspace first");
431
486
  }
432
- const scanned = scanWorkspace(workspaceRoot);
433
- const registry = upsertWorkspace(readRegistry(), scanned);
434
- writeRegistry(registry);
487
+ const { registry } = healRegistryAtPath(workspaceRoot, { force: true });
435
488
  return registry;
436
489
  }
490
+ function projectsFingerprint(projects) {
491
+ return JSON.stringify([...projects].sort((a, b) => a.path.localeCompare(b.path) || a.name.localeCompare(b.name)));
492
+ }
493
+ function healRegistryAtPath(workspaceRoot, { force = false } = {}) {
494
+ const root = normalizeRegistryPath(workspaceRoot);
495
+ let registry = readRegistry();
496
+ const beforeLen = registry.workspaces.length;
497
+ registry = {
498
+ ...registry,
499
+ workspaces: registry.workspaces.filter((ws) => {
500
+ try {
501
+ return fs3.existsSync(normalizeRegistryPath(ws.path));
502
+ } catch {
503
+ return false;
504
+ }
505
+ })
506
+ };
507
+ const pruned = registry.workspaces.length !== beforeLen;
508
+ const scanned = scanWorkspace(root);
509
+ const existing = registry.workspaces.find((ws) => normalizeRegistryPath(ws.path) === root);
510
+ const projectsChanged = !existing || projectsFingerprint(existing.projects) !== projectsFingerprint(scanned.projects);
511
+ if (force || pruned || projectsChanged) {
512
+ registry = upsertWorkspace(registry, scanned);
513
+ writeRegistry(registry);
514
+ return { changed: true, registry };
515
+ }
516
+ return { changed: false, registry };
517
+ }
437
518
  function listRegistryProjects(registry = readRegistry()) {
438
519
  const rows = [];
439
520
  for (const ws of registry.workspaces) {
@@ -452,6 +533,7 @@ export {
452
533
  registryFilePath,
453
534
  readRegistry,
454
535
  listRegistryProjects,
536
+ healRegistryAtPath,
455
537
  entryToRegistryProject,
456
538
  ensureXrystalHome,
457
539
  XRYSTAL_HOME_DIR
@@ -13,6 +13,7 @@ const QUICK_COMMANDS = [
13
13
  { cmd: 'tmp', desc: 'Ensure tmp.yml for current scope (inner x/ or outer ./)' },
14
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
+ { cmd: 'watch status', desc: 'Background tmp watcher for registered workspaces (~/.xrystal)' },
16
17
  { cmd: 'dev / build / doctor', desc: 'Develop & diagnostics' },
17
18
  ]
18
19
 
@@ -8,6 +8,7 @@ import { findEntries, findWorkspaceRoot, workspaceProjectName } from './workspac
8
8
  import { getInstalledCoreVersion, readCliPackageJson, readProjectPackageJson, resolveProjectRoot } from './project-root.mjs'
9
9
  import { readTmpSchemaVersion, TMP_SCHEMA_VERSION } from './tmp-schema-version.mjs'
10
10
  import { GlobalTypeEnum, ProjectScopeKindEnum } from './cli-enums.mjs'
11
+ import { runWorkspaceSelfHeal } from './workspace-heal.mjs'
11
12
 
12
13
  function readTmpMeta(tmpFilePath) {
13
14
  if (!tmpFilePath || !fs.existsSync(tmpFilePath)) return null
@@ -101,6 +102,14 @@ export function resolveProjectContext(startDir = process.cwd()) {
101
102
  label = 'Workspace linked service (inner x/tmp.yml)'
102
103
  }
103
104
 
105
+ if (workspaceRoot && outerMeta?.globalType === GlobalTypeEnum.WORKSPACE) {
106
+ try {
107
+ runWorkspaceSelfHeal(workspaceRoot, { ensureTmp: false })
108
+ } catch {
109
+ // layout/registry heal is best-effort during context resolution
110
+ }
111
+ }
112
+
104
113
  const workspaceEntries = workspaceRoot ? findEntries(workspaceRoot) : []
105
114
  const selfEntry = workspaceEntries.find((e) => path.resolve(e.path) === path.resolve(projectRoot))
106
115
 
@@ -0,0 +1,36 @@
1
+ import {
2
+ ensureWorkspaceSlotDirs,
3
+ healWorkspaceOuterTmpOptions,
4
+ } from './workspace-resolve.mjs'
5
+ import { healRegistryAtPath } from './xrystal-registry.mjs'
6
+ import { ensureOuterWorkspaceTmp } from './workspace-tmp.mjs'
7
+ import { ensureWatchDaemon } from './xrystal-watch-spawn.mjs'
8
+
9
+ /**
10
+ * Workspace self-heal: slot dirs, outer tmp options, ~/.xrystal registry.
11
+ * Runs automatically on sync / project context — no explicit CLI flag required.
12
+ */
13
+ export function runWorkspaceSelfHeal(workspaceRoot, {
14
+ ensureTmp = true,
15
+ healRegistry = true,
16
+ forceRegistry = false,
17
+ ensureDaemon = true,
18
+ } = {}) {
19
+ if (ensureTmp) {
20
+ ensureOuterWorkspaceTmp(workspaceRoot)
21
+ }
22
+
23
+ const slotDirsCreated = ensureWorkspaceSlotDirs(workspaceRoot)
24
+ const tmpOptionsPatched = healWorkspaceOuterTmpOptions(workspaceRoot)
25
+
26
+ let registryChanged = false
27
+ if (healRegistry) {
28
+ registryChanged = healRegistryAtPath(workspaceRoot, { force: forceRegistry }).changed
29
+ }
30
+
31
+ if (ensureDaemon && healRegistry) {
32
+ ensureWatchDaemon({ quiet: true })
33
+ }
34
+
35
+ return { slotDirsCreated, tmpOptionsPatched, registryChanged }
36
+ }
@@ -1,8 +1,10 @@
1
1
  export {
2
2
  DEFAULT_FOLDER_STRUCTURE,
3
+ ensureWorkspaceSlotDirs,
3
4
  findApiServices,
4
5
  findEntries,
5
6
  findWorkspaceRoot,
7
+ healWorkspaceOuterTmpOptions,
6
8
  normalizeGlobalType,
7
9
  parseFolderStructure,
8
10
  readTmpFile,
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
 
4
- import { DEFAULT_FOLDER_STRUCTURE, workspaceTmpTemplate } from './workspace-resolve.mjs'
4
+ import { readTmpFile, workspaceTmpTemplate } from './workspace-resolve.mjs'
5
5
  import { scaffoldServiceFromTemplate } from './scaffold-service.mjs'
6
6
  import { ensureServiceTelepresenceEnv, writeWorkspaceTelepresenceFiles } from './telepresence-layout.mjs'
7
7
  import { ensureTmpSchemaVersion } from './tmp-schema-version.mjs'
@@ -28,13 +28,14 @@ export function scaffoldWorkspace(targetPath, projectName, {
28
28
 
29
29
  writeWorkspaceTelepresenceFiles(resolved)
30
30
 
31
- for (const dir of Object.values(DEFAULT_FOLDER_STRUCTURE)) {
31
+ const fsMap = readTmpFile(tmpPath).folderStructure
32
+ for (const dir of Object.values(fsMap)) {
32
33
  fs.mkdirSync(path.join(resolved, dir), { recursive: true })
33
34
  }
34
35
 
35
36
  let general = null
36
37
  if (scaffoldGeneral) {
37
- const generalPath = path.join(resolved, DEFAULT_FOLDER_STRUCTURE.api, 'general')
38
+ const generalPath = path.join(resolved, fsMap.api, 'general')
38
39
  general = scaffoldServiceFromTemplate(generalPath, {
39
40
  projectName: 'general',
40
41
  templateRepoUri,
@@ -3,6 +3,7 @@ import path from 'node:path'
3
3
 
4
4
  import { ensureTmpSchemaVersion } from './tmp-schema-version.mjs'
5
5
  import { workspaceProjectName, workspaceTmpTemplate } from './workspace-resolve.mjs'
6
+ import { runWorkspaceSelfHeal } from './workspace-heal.mjs'
6
7
 
7
8
  export function ensureOuterWorkspaceTmp(workspaceRoot, { projectName } = {}) {
8
9
  const resolved = path.resolve(workspaceRoot)
@@ -16,5 +17,6 @@ export function ensureOuterWorkspaceTmp(workspaceRoot, { projectName } = {}) {
16
17
  }
17
18
 
18
19
  const schema = ensureTmpSchemaVersion(tmpPath)
20
+ runWorkspaceSelfHeal(resolved, { ensureTmp: false })
19
21
  return { tmpFilePath: tmpPath, created, schema, workspaceRoot: resolved }
20
22
  }
@@ -1,6 +1,7 @@
1
1
  export {
2
2
  ensureXrystalHome,
3
3
  entryToRegistryProject,
4
+ healRegistryAtPath,
4
5
  listRegistryProjects,
5
6
  readRegistry,
6
7
  registryFilePath,
@@ -0,0 +1,174 @@
1
+ import fs, { unwatchFile, watchFile } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ import { packageDefaults } from './package-defaults.mjs'
5
+ import { findEntries, readWorkspaceCoreTmp } from './workspace-resolve.mjs'
6
+ import { readRegistry, registryFilePath, resolveXrystalHome } from './xrystal-registry.mjs'
7
+ import { runWorkspaceSelfHeal } from './workspace-heal.mjs'
8
+ import { watchPidPath } from './xrystal-watch-spawn.mjs'
9
+
10
+ const DEBOUNCE_MS = 200
11
+ const REGISTRY_RESCAN_MS = 30_000
12
+
13
+ function defaultWatchIntervalMs() {
14
+ return packageDefaults.tmpWatchDefaults?.intervalMs ?? 500
15
+ }
16
+
17
+ function resolveWorkspaceWatchIntervalMs(workspaceRoot) {
18
+ try {
19
+ return readWorkspaceCoreTmp(workspaceRoot).fileWatchIntervalMs ?? defaultWatchIntervalMs()
20
+ } catch {
21
+ return defaultWatchIntervalMs()
22
+ }
23
+ }
24
+
25
+ /** Collect outer + inner tmp.yml paths for all registered workspaces. */
26
+ export function collectWatchTargets(registry = readRegistry()) {
27
+ const targets = []
28
+ const seen = new Set()
29
+
30
+ for (const ws of registry.workspaces ?? []) {
31
+ if (!ws?.path || !fs.existsSync(ws.path)) continue
32
+
33
+ const outer = path.join(ws.path, 'tmp.yml')
34
+ if (fs.existsSync(outer)) {
35
+ const key = path.resolve(outer)
36
+ if (!seen.has(key)) {
37
+ seen.add(key)
38
+ targets.push({ file: key, workspaceRoot: ws.path, kind: 'outer' })
39
+ }
40
+ }
41
+
42
+ try {
43
+ for (const entry of findEntries(ws.path)) {
44
+ if (!entry.tmp || !fs.existsSync(entry.tmp)) continue
45
+ const key = path.resolve(entry.tmp)
46
+ if (seen.has(key)) continue
47
+ seen.add(key)
48
+ targets.push({ file: key, workspaceRoot: ws.path, kind: 'inner' })
49
+ }
50
+ } catch {
51
+ // workspace may be mid-edit — skip until next rescan
52
+ }
53
+ }
54
+
55
+ return targets
56
+ }
57
+
58
+ function appendWatchLog(line) {
59
+ try {
60
+ fs.appendFileSync(path.join(resolveXrystalHome(), 'watch.log'), `${new Date().toISOString()} ${line}\n`)
61
+ } catch {
62
+ // ignore log failures
63
+ }
64
+ }
65
+
66
+ export function runWatchDaemonMain() {
67
+ const pidFile = watchPidPath()
68
+ fs.mkdirSync(resolveXrystalHome(), { recursive: true })
69
+ fs.writeFileSync(pidFile, `${process.pid}\n`)
70
+
71
+ const active = new Map()
72
+ const debounceTimers = new Map()
73
+ let registryWatcher = null
74
+ let rescanTimer = null
75
+
76
+ const scheduleHeal = (workspaceRoot, reason) => {
77
+ const key = path.resolve(workspaceRoot)
78
+ if (debounceTimers.has(key)) {
79
+ clearTimeout(debounceTimers.get(key))
80
+ }
81
+
82
+ debounceTimers.set(key, setTimeout(() => {
83
+ debounceTimers.delete(key)
84
+ try {
85
+ const result = runWorkspaceSelfHeal(workspaceRoot, {
86
+ ensureTmp: false,
87
+ healRegistry: true,
88
+ forceRegistry: true,
89
+ })
90
+ appendWatchLog(
91
+ `heal ${path.basename(workspaceRoot)} reason=${reason}`
92
+ + ` dirs=${result.slotDirsCreated.join(',') || '-'}`
93
+ + ` tmp=${result.tmpOptionsPatched ? 'patched' : 'ok'}`
94
+ + ` registry=${result.registryChanged ? 'updated' : 'ok'}`,
95
+ )
96
+ } catch (error) {
97
+ appendWatchLog(`heal error ${workspaceRoot}: ${error.message}`)
98
+ }
99
+ rebuildWatchers()
100
+ }, DEBOUNCE_MS))
101
+ }
102
+
103
+ const rebuildWatchers = () => {
104
+ const registry = readRegistry()
105
+ const targets = collectWatchTargets(registry)
106
+ const nextPaths = new Set(targets.map((t) => t.file))
107
+
108
+ for (const [file] of active) {
109
+ if (!nextPaths.has(file)) {
110
+ unwatchFile(file)
111
+ active.delete(file)
112
+ }
113
+ }
114
+
115
+ for (const target of targets) {
116
+ const interval = resolveWorkspaceWatchIntervalMs(target.workspaceRoot)
117
+ const existing = active.get(target.file)
118
+ if (existing && existing.interval === interval) continue
119
+
120
+ if (existing) {
121
+ unwatchFile(target.file)
122
+ }
123
+
124
+ watchFile(target.file, { interval }, (curr, prev) => {
125
+ if (curr.mtimeMs !== prev.mtimeMs) {
126
+ scheduleHeal(target.workspaceRoot, target.kind)
127
+ }
128
+ })
129
+ active.set(target.file, { interval, workspaceRoot: target.workspaceRoot, kind: target.kind })
130
+ }
131
+
132
+ const registryPath = registryFilePath()
133
+ if (registryWatcher) {
134
+ unwatchFile(registryWatcher.path)
135
+ registryWatcher = null
136
+ }
137
+ if (fs.existsSync(registryPath)) {
138
+ watchFile(registryPath, { interval: defaultWatchIntervalMs() }, (curr, prev) => {
139
+ if (curr.mtimeMs !== prev.mtimeMs) rebuildWatchers()
140
+ })
141
+ registryWatcher = { path: registryPath }
142
+ }
143
+ }
144
+
145
+ const shutdown = (signal) => {
146
+ appendWatchLog(`shutdown ${signal}`)
147
+ if (rescanTimer) clearInterval(rescanTimer)
148
+ for (const [file] of active) unwatchFile(file)
149
+ active.clear()
150
+ if (registryWatcher) unwatchFile(registryWatcher.path)
151
+ for (const timer of debounceTimers.values()) clearTimeout(timer)
152
+ debounceTimers.clear()
153
+ try { fs.unlinkSync(pidFile) } catch { /* ignore */ }
154
+ process.exit(0)
155
+ }
156
+
157
+ process.on('SIGTERM', () => shutdown('SIGTERM'))
158
+ process.on('SIGINT', () => shutdown('SIGINT'))
159
+
160
+ appendWatchLog(`started pid=${process.pid}`)
161
+ rebuildWatchers()
162
+
163
+ // Safety rescan — picks up new inner tmp without file event on registry
164
+ rescanTimer = setInterval(() => {
165
+ rebuildWatchers()
166
+ }, REGISTRY_RESCAN_MS)
167
+
168
+ // Initial heal pass for all registered workspaces
169
+ for (const ws of readRegistry().workspaces ?? []) {
170
+ if (ws?.path && fs.existsSync(ws.path)) {
171
+ scheduleHeal(ws.path, 'boot')
172
+ }
173
+ }
174
+ }
@@ -0,0 +1,92 @@
1
+ import { spawn } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ import { resolveXrystalHome } from './xrystal-registry.mjs'
7
+
8
+ const HELPERS_DIR = path.dirname(fileURLToPath(import.meta.url))
9
+
10
+ export function watchDaemonScriptPath() {
11
+ return path.join(HELPERS_DIR, '../scripts/xrystal-watch-daemon.mjs')
12
+ }
13
+
14
+ export function watchPidPath() {
15
+ return path.join(resolveXrystalHome(), 'watch.pid')
16
+ }
17
+
18
+ export function watchLogPath() {
19
+ return path.join(resolveXrystalHome(), 'watch.log')
20
+ }
21
+
22
+ export function watchDaemonStatus() {
23
+ const pidFile = watchPidPath()
24
+ if (!fs.existsSync(pidFile)) {
25
+ return { running: false, pid: null }
26
+ }
27
+
28
+ const pid = Number(fs.readFileSync(pidFile, 'utf8').trim())
29
+ if (!Number.isFinite(pid) || pid <= 0) {
30
+ try { fs.unlinkSync(pidFile) } catch { /* ignore */ }
31
+ return { running: false, pid: null, stale: true }
32
+ }
33
+
34
+ try {
35
+ process.kill(pid, 0)
36
+ return { running: true, pid }
37
+ } catch {
38
+ try { fs.unlinkSync(pidFile) } catch { /* ignore */ }
39
+ return { running: false, pid: null, stale: true }
40
+ }
41
+ }
42
+
43
+ export function startWatchDaemon({ detached = true, quiet = true } = {}) {
44
+ const status = watchDaemonStatus()
45
+ if (status.running) {
46
+ return { ...status, started: false }
47
+ }
48
+
49
+ const script = watchDaemonScriptPath()
50
+ if (!fs.existsSync(script)) {
51
+ throw new Error(`watch daemon script missing: ${script}`)
52
+ }
53
+
54
+ const logFd = fs.openSync(watchLogPath(), 'a')
55
+ const child = spawn(process.execPath, [script], {
56
+ detached,
57
+ stdio: detached ? ['ignore', logFd, logFd] : 'inherit',
58
+ env: { ...process.env, XRY_WATCH_DAEMON: '1' },
59
+ })
60
+ fs.closeSync(logFd)
61
+
62
+ if (detached) {
63
+ child.unref()
64
+ }
65
+
66
+ return { running: true, pid: child.pid, started: true, quiet }
67
+ }
68
+
69
+ export function stopWatchDaemon() {
70
+ const status = watchDaemonStatus()
71
+ if (!status.running || !status.pid) {
72
+ return { stopped: false, ...status }
73
+ }
74
+
75
+ try {
76
+ process.kill(status.pid, 'SIGTERM')
77
+ } catch {
78
+ try { fs.unlinkSync(watchPidPath()) } catch { /* ignore */ }
79
+ return { stopped: false, running: false, pid: null }
80
+ }
81
+
82
+ return { stopped: true, pid: status.pid }
83
+ }
84
+
85
+ /** Start background ~/.xrystal tmp watcher when not already running. */
86
+ export function ensureWatchDaemon({ quiet = true } = {}) {
87
+ try {
88
+ return startWatchDaemon({ detached: true, quiet })
89
+ } catch {
90
+ return { running: false, started: false, quiet }
91
+ }
92
+ }
package/x/bin/main-cli.js CHANGED
@@ -13,6 +13,7 @@ import { registerProjectsCommand, registerWorkspacesCommand } from './commands/p
13
13
  import { registerTagCommand, registerVersionCommand } from './commands/release.mjs'
14
14
  import { registerTelepresenceCommand } from './commands/telepresence.mjs'
15
15
  import { registerHooksCommand } from './commands/hooks.mjs'
16
+ import { registerWatchCommand } from './commands/watch.mjs'
16
17
  import { printBanner, shouldShowBanner } from './helpers/banner.mjs'
17
18
  import { formatRootHelp, formatCreateCommandHelp, isCreateHelpRequest, isRootHelpRequest, printQuickStartGuide } from './helpers/cli-help.mjs'
18
19
  import {
@@ -79,6 +80,7 @@ registerProjectInfoCommand(cli, cliContext)
79
80
  registerSyncCommand(cli, cliContext)
80
81
  registerWorkspacesCommand(cli, cliContext)
81
82
  registerProjectsCommand(cli, cliContext)
83
+ registerWatchCommand(cli, cliContext)
82
84
  registerHooksCommand(cli, cliContext)
83
85
  registerTelepresenceCommand(cli, cliContext)
84
86
  registerProjectCommands(cli, cliContext)
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { runWatchDaemonMain } from '../helpers/xrystal-watch-daemon.mjs'
4
+
5
+ runWatchDaemonMain()
@@ -41,5 +41,9 @@ export declare function workspaceProjectName(workspaceRoot: string): string;
41
41
  export declare function readWorkspaceGlobalTmp(workspaceRoot: string): {
42
42
  fileWatchIntervalMs?: number;
43
43
  };
44
+ /** Ensure api/web/mobile (or custom folder-structure paths) exist on disk. */
45
+ export declare function ensureWorkspaceSlotDirs(workspaceRoot: string): string[];
46
+ /** Patch outer workspace tmp when global.options.fileWatchIntervalMs is missing. */
47
+ export declare function healWorkspaceOuterTmpOptions(workspaceRoot: string): boolean;
44
48
  /** @deprecated */ export declare const readWorkspaceCoreTmp: typeof readWorkspaceGlobalTmp;
45
49
  export declare function workspaceTmpTemplate(projectName: string): string;
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { GlobalTypeEnum, WorkspaceSlotEnum } from '../../../utils/models/enums/index.js';
4
+ import { packageDefaults } from '../../../utils/constants/index.js';
4
5
  import { normalizeGlobalType } from '../../../utils/helpers/tmp/tmp-schema.js';
5
6
  export const TMP_FILE = 'tmp.yml';
6
7
  export const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.turbo', 'coverage']);
@@ -208,6 +209,38 @@ export function readWorkspaceGlobalTmp(workspaceRoot) {
208
209
  ?? text.match(/fileWatchIntervalMs:\s*(\d+)/);
209
210
  return match ? { fileWatchIntervalMs: Number(match[1]) } : {};
210
211
  }
212
+ /** Ensure api/web/mobile (or custom folder-structure paths) exist on disk. */
213
+ export function ensureWorkspaceSlotDirs(workspaceRoot) {
214
+ const tmpPath = path.join(workspaceRoot, TMP_FILE);
215
+ if (!fs.existsSync(tmpPath))
216
+ return [];
217
+ const meta = readTmpFile(tmpPath);
218
+ const created = [];
219
+ for (const folder of Object.values(meta.folderStructure)) {
220
+ const dir = path.join(workspaceRoot, folder);
221
+ if (!fs.existsSync(dir)) {
222
+ fs.mkdirSync(dir, { recursive: true });
223
+ created.push(folder);
224
+ }
225
+ }
226
+ return created;
227
+ }
228
+ /** Patch outer workspace tmp when global.options.fileWatchIntervalMs is missing. */
229
+ export function healWorkspaceOuterTmpOptions(workspaceRoot) {
230
+ const tmpPath = path.join(workspaceRoot, TMP_FILE);
231
+ if (!fs.existsSync(tmpPath))
232
+ return false;
233
+ const text = fs.readFileSync(tmpPath, 'utf8');
234
+ if (/fileWatchIntervalMs:\s*\d+/m.test(text))
235
+ return false;
236
+ const defaultMs = packageDefaults.tmpWatchDefaults.intervalMs;
237
+ const insertBlock = ` options:\n fileWatchIntervalMs: ${defaultMs}\n`;
238
+ const patched = text.replace(/(configs:\s*\n\s+global:\s*\n\s+type:\s*workspace\s*\n)/m, `$1${insertBlock}`);
239
+ if (patched === text)
240
+ return false;
241
+ fs.writeFileSync(tmpPath, patched);
242
+ return true;
243
+ }
211
244
  /** @deprecated */ export const readWorkspaceCoreTmp = readWorkspaceGlobalTmp;
212
245
  export function workspaceTmpTemplate(projectName) {
213
246
  return `project:
@@ -216,6 +249,8 @@ export function workspaceTmpTemplate(projectName) {
216
249
  configs:
217
250
  global:
218
251
  type: workspace
252
+ options:
253
+ fileWatchIntervalMs: 500
219
254
  folder-structure:
220
255
  api: api
221
256
  web: web
@@ -27,6 +27,13 @@ export declare function readRegistry(): XrystalRegistry;
27
27
  export declare function writeRegistry(registry: XrystalRegistry): void;
28
28
  export declare function upsertWorkspace(registry: XrystalRegistry, workspace: RegistryWorkspace): XrystalRegistry;
29
29
  export declare function syncRegistryFromPath(startDir?: string): XrystalRegistry;
30
+ /** Rescan workspace, prune dead registry rows, write when drift detected. */
31
+ export declare function healRegistryAtPath(workspaceRoot: string, { force }?: {
32
+ force?: boolean;
33
+ }): {
34
+ changed: boolean;
35
+ registry: XrystalRegistry;
36
+ };
30
37
  export declare function listRegistryProjects(registry?: XrystalRegistry): Array<RegistryProject & {
31
38
  workspace: string;
32
39
  }>;
@@ -76,11 +76,40 @@ export function syncRegistryFromPath(startDir = process.cwd()) {
76
76
  if (!workspaceRoot) {
77
77
  throw new Error('No workspace tmp.yml found — run xry create demo --workspace first');
78
78
  }
79
- const scanned = scanWorkspace(workspaceRoot);
80
- const registry = upsertWorkspace(readRegistry(), scanned);
81
- writeRegistry(registry);
79
+ const { registry } = healRegistryAtPath(workspaceRoot, { force: true });
82
80
  return registry;
83
81
  }
82
+ function projectsFingerprint(projects) {
83
+ return JSON.stringify([...projects].sort((a, b) => a.path.localeCompare(b.path) || a.name.localeCompare(b.name)));
84
+ }
85
+ /** Rescan workspace, prune dead registry rows, write when drift detected. */
86
+ export function healRegistryAtPath(workspaceRoot, { force = false } = {}) {
87
+ const root = normalizeRegistryPath(workspaceRoot);
88
+ let registry = readRegistry();
89
+ const beforeLen = registry.workspaces.length;
90
+ registry = {
91
+ ...registry,
92
+ workspaces: registry.workspaces.filter((ws) => {
93
+ try {
94
+ return fs.existsSync(normalizeRegistryPath(ws.path));
95
+ }
96
+ catch {
97
+ return false;
98
+ }
99
+ }),
100
+ };
101
+ const pruned = registry.workspaces.length !== beforeLen;
102
+ const scanned = scanWorkspace(root);
103
+ const existing = registry.workspaces.find((ws) => normalizeRegistryPath(ws.path) === root);
104
+ const projectsChanged = !existing
105
+ || projectsFingerprint(existing.projects) !== projectsFingerprint(scanned.projects);
106
+ if (force || pruned || projectsChanged) {
107
+ registry = upsertWorkspace(registry, scanned);
108
+ writeRegistry(registry);
109
+ return { changed: true, registry };
110
+ }
111
+ return { changed: false, registry };
112
+ }
84
113
  export function listRegistryProjects(registry = readRegistry()) {
85
114
  const rows = [];
86
115
  for (const ws of registry.workspaces) {