@intlayer/engine 9.5.10 → 9.5.12
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/dist/assets/installSkills/skills/bundle-optimization.md +123 -0
- package/dist/assets/installSkills/skills/compat.md +0 -4
- package/dist/assets/installSkills/skills/content.md +8 -2
- package/dist/assets/installSkills/skills/next-js.md +2 -2
- package/dist/assets/installSkills/skills/usage.md +1 -1
- package/dist/cjs/build.cjs +5 -0
- package/dist/cjs/cli.cjs +1 -0
- package/dist/cjs/docReview/alignBlocks.cjs +53 -36
- package/dist/cjs/docReview/alignBlocks.cjs.map +1 -1
- package/dist/cjs/docReview/rebuildDocument.cjs +3 -1
- package/dist/cjs/docReview/rebuildDocument.cjs.map +1 -1
- package/dist/cjs/docReview/segmentDocument.cjs +8 -5
- package/dist/cjs/docReview/segmentDocument.cjs.map +1 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/transforms.cjs +4 -1
- package/dist/cjs/init/frameworkSetup/nextAppRouter/transforms.cjs.map +1 -1
- package/dist/cjs/init/index.cjs +2 -12
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/backendPackages.cjs +15 -0
- package/dist/cjs/init/utils/backendPackages.cjs.map +1 -0
- package/dist/cjs/init/utils/index.cjs +2 -3
- package/dist/cjs/installMCP/installMCP.cjs +1 -1
- package/dist/cjs/installMCP/installMCP.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs +2 -0
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +9 -8
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs +3 -1
- package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs +4 -6
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/log.cjs +1 -1
- package/dist/cjs/loadDictionaries/log.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs +19 -12
- package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/remoteDictionaryClient.cjs +18 -0
- package/dist/cjs/loadDictionaries/remoteDictionaryClient.cjs.map +1 -0
- package/dist/cjs/prepareIntlayerServer.cjs +132 -0
- package/dist/cjs/prepareIntlayerServer.cjs.map +1 -0
- package/dist/cjs/scan/analyzeBundleContent.cjs +26 -12
- package/dist/cjs/scan/analyzeBundleContent.cjs.map +1 -1
- package/dist/cjs/scan/calculateScore.cjs +4 -1
- package/dist/cjs/scan/calculateScore.cjs.map +1 -1
- package/dist/cjs/scan/checks.cjs +394 -221
- package/dist/cjs/scan/checks.cjs.map +1 -1
- package/dist/cjs/scan/detection/checkDetails.cjs +56 -0
- package/dist/cjs/scan/detection/checkDetails.cjs.map +1 -0
- package/dist/cjs/scan/detection/classifyInternalLinks.cjs +47 -0
- package/dist/cjs/scan/detection/classifyInternalLinks.cjs.map +1 -0
- package/dist/cjs/scan/detection/detectRoutingStrategy.cjs +143 -0
- package/dist/cjs/scan/detection/detectRoutingStrategy.cjs.map +1 -0
- package/dist/cjs/scan/detection/detectTechnologies.cjs +89 -0
- package/dist/cjs/scan/detection/detectTechnologies.cjs.map +1 -0
- package/dist/cjs/scan/detection/index.cjs +36 -0
- package/dist/cjs/scan/detection/localeCode.cjs +118 -0
- package/dist/cjs/scan/detection/localeCode.cjs.map +1 -0
- package/dist/cjs/scan/detection/localizedPages.cjs +48 -0
- package/dist/cjs/scan/detection/localizedPages.cjs.map +1 -0
- package/dist/cjs/scan/detection/technologySignatures.cjs +564 -0
- package/dist/cjs/scan/detection/technologySignatures.cjs.map +1 -0
- package/dist/cjs/scan/detection/url.cjs +53 -0
- package/dist/cjs/scan/detection/url.cjs.map +1 -0
- package/dist/cjs/scan/fetchText.cjs +56 -0
- package/dist/cjs/scan/fetchText.cjs.map +1 -0
- package/dist/cjs/scan/index.cjs +59 -3
- package/dist/cjs/scan/parseHtml.cjs +55 -10
- package/dist/cjs/scan/parseHtml.cjs.map +1 -1
- package/dist/cjs/scan/robots.cjs +65 -0
- package/dist/cjs/scan/robots.cjs.map +1 -0
- package/dist/cjs/scan/runScanChecks.cjs +89 -0
- package/dist/cjs/scan/runScanChecks.cjs.map +1 -0
- package/dist/cjs/scan/scanWebsite.cjs +58 -52
- package/dist/cjs/scan/scanWebsite.cjs.map +1 -1
- package/dist/cjs/scan/sitemap.cjs +109 -0
- package/dist/cjs/scan/sitemap.cjs.map +1 -0
- package/dist/cjs/utils/chunkJSON.cjs +24 -9
- package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
- package/dist/cjs/utils/getChunk.cjs +2 -2
- package/dist/cjs/utils/getChunk.cjs.map +1 -1
- package/dist/cjs/utils/getProcessChainCommands.cjs +117 -0
- package/dist/cjs/utils/getProcessChainCommands.cjs.map +1 -0
- package/dist/cjs/utils/index.cjs +2 -0
- package/dist/cjs/utils/runParallel/index.cjs +1 -1
- package/dist/cjs/utils/runParallel/index.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/pidTree.cjs +23 -11
- package/dist/cjs/utils/runParallel/pidTree.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/ps.cjs +8 -3
- package/dist/cjs/utils/runParallel/ps.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/runTask.cjs +2 -1
- package/dist/cjs/utils/runParallel/runTask.cjs.map +1 -1
- package/dist/cjs/utils/runParallel/wmic.cjs +8 -3
- package/dist/cjs/utils/runParallel/wmic.cjs.map +1 -1
- package/dist/cjs/utils/startContentWatcher.cjs +99 -0
- package/dist/cjs/utils/startContentWatcher.cjs.map +1 -0
- package/dist/cjs/watcher.cjs +2 -2
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs +7 -4
- package/dist/cjs/writeContentDeclaration/detectExportedComponentName.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs +2 -2
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs.map +1 -1
- package/dist/cjs/writeJsonIfChanged.cjs.map +1 -1
- package/dist/esm/build.mjs +2 -1
- package/dist/esm/cli.mjs +2 -2
- package/dist/esm/docReview/alignBlocks.mjs +53 -36
- package/dist/esm/docReview/alignBlocks.mjs.map +1 -1
- package/dist/esm/docReview/rebuildDocument.mjs +3 -1
- package/dist/esm/docReview/rebuildDocument.mjs.map +1 -1
- package/dist/esm/docReview/segmentDocument.mjs +8 -5
- package/dist/esm/docReview/segmentDocument.mjs.map +1 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/transforms.mjs +4 -1
- package/dist/esm/init/frameworkSetup/nextAppRouter/transforms.mjs.map +1 -1
- package/dist/esm/init/index.mjs +1 -11
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/backendPackages.mjs +14 -0
- package/dist/esm/init/utils/backendPackages.mjs.map +1 -0
- package/dist/esm/init/utils/index.mjs +2 -2
- package/dist/esm/installMCP/installMCP.mjs +1 -1
- package/dist/esm/installMCP/installMCP.mjs.map +1 -1
- package/dist/esm/installSkills/index.mjs +2 -0
- package/dist/esm/installSkills/index.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs +9 -8
- package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs +3 -1
- package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs +3 -5
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
- package/dist/esm/loadDictionaries/log.mjs +1 -1
- package/dist/esm/loadDictionaries/log.mjs.map +1 -1
- package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs +19 -12
- package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
- package/dist/esm/loadDictionaries/remoteDictionaryClient.mjs +16 -0
- package/dist/esm/loadDictionaries/remoteDictionaryClient.mjs.map +1 -0
- package/dist/esm/prepareIntlayerServer.mjs +128 -0
- package/dist/esm/prepareIntlayerServer.mjs.map +1 -0
- package/dist/esm/scan/analyzeBundleContent.mjs +26 -12
- package/dist/esm/scan/analyzeBundleContent.mjs.map +1 -1
- package/dist/esm/scan/calculateScore.mjs +4 -1
- package/dist/esm/scan/calculateScore.mjs.map +1 -1
- package/dist/esm/scan/checks.mjs +387 -220
- package/dist/esm/scan/checks.mjs.map +1 -1
- package/dist/esm/scan/detection/checkDetails.mjs +54 -0
- package/dist/esm/scan/detection/checkDetails.mjs.map +1 -0
- package/dist/esm/scan/detection/classifyInternalLinks.mjs +46 -0
- package/dist/esm/scan/detection/classifyInternalLinks.mjs.map +1 -0
- package/dist/esm/scan/detection/detectRoutingStrategy.mjs +141 -0
- package/dist/esm/scan/detection/detectRoutingStrategy.mjs.map +1 -0
- package/dist/esm/scan/detection/detectTechnologies.mjs +87 -0
- package/dist/esm/scan/detection/detectTechnologies.mjs.map +1 -0
- package/dist/esm/scan/detection/index.mjs +10 -0
- package/dist/esm/scan/detection/localeCode.mjs +108 -0
- package/dist/esm/scan/detection/localeCode.mjs.map +1 -0
- package/dist/esm/scan/detection/localizedPages.mjs +46 -0
- package/dist/esm/scan/detection/localizedPages.mjs.map +1 -0
- package/dist/esm/scan/detection/technologySignatures.mjs +563 -0
- package/dist/esm/scan/detection/technologySignatures.mjs.map +1 -0
- package/dist/esm/scan/detection/url.mjs +47 -0
- package/dist/esm/scan/detection/url.mjs.map +1 -0
- package/dist/esm/scan/fetchText.mjs +55 -0
- package/dist/esm/scan/fetchText.mjs.map +1 -0
- package/dist/esm/scan/index.mjs +15 -3
- package/dist/esm/scan/parseHtml.mjs +52 -11
- package/dist/esm/scan/parseHtml.mjs.map +1 -1
- package/dist/esm/scan/robots.mjs +63 -0
- package/dist/esm/scan/robots.mjs.map +1 -0
- package/dist/esm/scan/runScanChecks.mjs +88 -0
- package/dist/esm/scan/runScanChecks.mjs.map +1 -0
- package/dist/esm/scan/scanWebsite.mjs +59 -53
- package/dist/esm/scan/scanWebsite.mjs.map +1 -1
- package/dist/esm/scan/sitemap.mjs +105 -0
- package/dist/esm/scan/sitemap.mjs.map +1 -0
- package/dist/esm/utils/chunkJSON.mjs +24 -9
- package/dist/esm/utils/chunkJSON.mjs.map +1 -1
- package/dist/esm/utils/getChunk.mjs +2 -2
- package/dist/esm/utils/getChunk.mjs.map +1 -1
- package/dist/esm/utils/getProcessChainCommands.mjs +115 -0
- package/dist/esm/utils/getProcessChainCommands.mjs.map +1 -0
- package/dist/esm/utils/index.mjs +2 -1
- package/dist/esm/utils/runParallel/index.mjs +1 -1
- package/dist/esm/utils/runParallel/index.mjs.map +1 -1
- package/dist/esm/utils/runParallel/pidTree.mjs +23 -11
- package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
- package/dist/esm/utils/runParallel/ps.mjs +8 -3
- package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
- package/dist/esm/utils/runParallel/runTask.mjs +2 -1
- package/dist/esm/utils/runParallel/runTask.mjs.map +1 -1
- package/dist/esm/utils/runParallel/wmic.mjs +8 -3
- package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
- package/dist/esm/utils/startContentWatcher.mjs +98 -0
- package/dist/esm/utils/startContentWatcher.mjs.map +1 -0
- package/dist/esm/watcher.mjs +1 -1
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/detectExportedComponentName.mjs +7 -4
- package/dist/esm/writeContentDeclaration/detectExportedComponentName.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs +2 -2
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs.map +1 -1
- package/dist/esm/writeJsonIfChanged.mjs +1 -1
- package/dist/esm/writeJsonIfChanged.mjs.map +1 -1
- package/dist/types/build.d.ts +2 -1
- package/dist/types/cli.d.ts +2 -2
- package/dist/types/docReview/rebuildDocument.d.ts.map +1 -1
- package/dist/types/docReview/segmentDocument.d.ts.map +1 -1
- package/dist/types/init/frameworkSetup/nextAppRouter/transforms.d.ts.map +1 -1
- package/dist/types/init/index.d.ts +1 -1
- package/dist/types/init/index.d.ts.map +1 -1
- package/dist/types/init/utils/backendPackages.d.ts +5 -0
- package/dist/types/init/utils/backendPackages.d.ts.map +1 -0
- package/dist/types/init/utils/index.d.ts +2 -2
- package/dist/types/installSkills/index.d.ts +1 -0
- package/dist/types/installSkills/index.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +1 -1
- package/dist/types/loadDictionaries/logTypeScriptErrors.d.ts.map +1 -1
- package/dist/types/loadDictionaries/remoteDictionaryClient.d.ts +14 -0
- package/dist/types/loadDictionaries/remoteDictionaryClient.d.ts.map +1 -0
- package/dist/types/prepareIntlayerServer.d.ts +67 -0
- package/dist/types/prepareIntlayerServer.d.ts.map +1 -0
- package/dist/types/scan/analyzeBundleContent.d.ts.map +1 -1
- package/dist/types/scan/calculateScore.d.ts +4 -1
- package/dist/types/scan/calculateScore.d.ts.map +1 -1
- package/dist/types/scan/checks.d.ts +114 -21
- package/dist/types/scan/checks.d.ts.map +1 -1
- package/dist/types/scan/detection/checkDetails.d.ts +29 -0
- package/dist/types/scan/detection/checkDetails.d.ts.map +1 -0
- package/dist/types/scan/detection/classifyInternalLinks.d.ts +44 -0
- package/dist/types/scan/detection/classifyInternalLinks.d.ts.map +1 -0
- package/dist/types/scan/detection/detectRoutingStrategy.d.ts +60 -0
- package/dist/types/scan/detection/detectRoutingStrategy.d.ts.map +1 -0
- package/dist/types/scan/detection/detectTechnologies.d.ts +60 -0
- package/dist/types/scan/detection/detectTechnologies.d.ts.map +1 -0
- package/dist/types/scan/detection/index.d.ts +9 -0
- package/dist/types/scan/detection/localeCode.d.ts +49 -0
- package/dist/types/scan/detection/localeCode.d.ts.map +1 -0
- package/dist/types/scan/detection/localizedPages.d.ts +40 -0
- package/dist/types/scan/detection/localizedPages.d.ts.map +1 -0
- package/dist/types/scan/detection/technologySignatures.d.ts +48 -0
- package/dist/types/scan/detection/technologySignatures.d.ts.map +1 -0
- package/dist/types/scan/detection/url.d.ts +27 -0
- package/dist/types/scan/detection/url.d.ts.map +1 -0
- package/dist/types/scan/fetchText.d.ts +30 -0
- package/dist/types/scan/fetchText.d.ts.map +1 -0
- package/dist/types/scan/index.d.ts +16 -4
- package/dist/types/scan/parseHtml.d.ts +17 -0
- package/dist/types/scan/parseHtml.d.ts.map +1 -1
- package/dist/types/scan/robots.d.ts +23 -0
- package/dist/types/scan/robots.d.ts.map +1 -0
- package/dist/types/scan/runScanChecks.d.ts +43 -0
- package/dist/types/scan/runScanChecks.d.ts.map +1 -0
- package/dist/types/scan/scanWebsite.d.ts.map +1 -1
- package/dist/types/scan/sitemap.d.ts +49 -0
- package/dist/types/scan/sitemap.d.ts.map +1 -0
- package/dist/types/scan/types.d.ts +15 -0
- package/dist/types/scan/types.d.ts.map +1 -1
- package/dist/types/utils/chunkJSON.d.ts.map +1 -1
- package/dist/types/utils/getProcessChainCommands.d.ts +35 -0
- package/dist/types/utils/getProcessChainCommands.d.ts.map +1 -0
- package/dist/types/utils/index.d.ts +2 -1
- package/dist/types/utils/runParallel/pidTree.d.ts.map +1 -1
- package/dist/types/utils/startContentWatcher.d.ts +40 -0
- package/dist/types/utils/startContentWatcher.d.ts.map +1 -0
- package/dist/types/watcher.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/writeMarkdownFile.d.ts.map +1 -1
- package/package.json +15 -7
- package/dist/cjs/init/utils/devScript.cjs +0 -57
- package/dist/cjs/init/utils/devScript.cjs.map +0 -1
- package/dist/esm/init/utils/devScript.mjs +0 -55
- package/dist/esm/init/utils/devScript.mjs.map +0 -1
- package/dist/types/init/utils/devScript.d.ts +0 -48
- package/dist/types/init/utils/devScript.d.ts.map +0 -1
|
@@ -70,14 +70,17 @@ const pidtree = (PID, options, callback) => {
|
|
|
70
70
|
}
|
|
71
71
|
let root;
|
|
72
72
|
for (let l = 0; l < processList.length; l++) {
|
|
73
|
-
|
|
73
|
+
const proc = processList[l];
|
|
74
|
+
if (!proc) continue;
|
|
75
|
+
const [ppid, pid] = proc;
|
|
76
|
+
if (pid === parsedPID) {
|
|
74
77
|
root = normalizedOptions.advanced ? {
|
|
75
|
-
ppid
|
|
78
|
+
ppid,
|
|
76
79
|
pid: parsedPID
|
|
77
80
|
} : parsedPID;
|
|
78
81
|
break;
|
|
79
82
|
}
|
|
80
|
-
if (
|
|
83
|
+
if (ppid === parsedPID) root = normalizedOptions.advanced ? { pid: parsedPID } : parsedPID;
|
|
81
84
|
}
|
|
82
85
|
if (root === void 0) {
|
|
83
86
|
normalizedCallback(/* @__PURE__ */ new Error("No matching pid found"), void 0);
|
|
@@ -87,19 +90,28 @@ const pidtree = (PID, options, callback) => {
|
|
|
87
90
|
const listCopy = [...processList];
|
|
88
91
|
while (listCopy.length > 0) {
|
|
89
92
|
const element = listCopy.pop();
|
|
90
|
-
if (
|
|
91
|
-
|
|
93
|
+
if (!element) continue;
|
|
94
|
+
const ppid = element[0];
|
|
95
|
+
const pid = element[1];
|
|
96
|
+
const children = tree[ppid];
|
|
97
|
+
if (children) children.push(pid);
|
|
98
|
+
else tree[ppid] = [pid];
|
|
92
99
|
}
|
|
93
100
|
let idx = 0;
|
|
94
101
|
const pids = [root];
|
|
95
102
|
while (idx < pids.length) {
|
|
96
103
|
const curpid = normalizedOptions.advanced ? pids[idx++].pid : pids[idx++];
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
104
|
+
const children = tree[curpid];
|
|
105
|
+
if (!children) continue;
|
|
106
|
+
const length = children.length;
|
|
107
|
+
for (let j = 0; j < length; j++) {
|
|
108
|
+
const childPid = children[j];
|
|
109
|
+
if (childPid === void 0) continue;
|
|
110
|
+
pids.push(normalizedOptions.advanced ? {
|
|
111
|
+
ppid: curpid,
|
|
112
|
+
pid: childPid
|
|
113
|
+
} : childPid);
|
|
114
|
+
}
|
|
103
115
|
delete tree[curpid];
|
|
104
116
|
}
|
|
105
117
|
if (!normalizedOptions.root) pids.shift();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pidTree.mjs","names":["os"],"sources":["../../../../src/utils/runParallel/pidTree.ts"],"sourcesContent":["import * as os from 'node:os';\nimport { ps } from './ps';\nimport { wmic } from './wmic';\n\ntype Platform =\n | 'darwin'\n | 'sunos'\n | 'freebsd'\n | 'netbsd'\n | 'win'\n | 'linux'\n | 'aix';\ntype Method = 'ps' | 'wmic';\n\ntype ProcessList = [number, number][]; // [PPID, PID][]\n\ninterface ListOptions {\n root?: boolean;\n advanced?: boolean;\n}\n\ntype ProcessInfo = { pid: number; ppid?: number };\ntype ResultType<T extends ListOptions | undefined> = T extends {\n advanced: true;\n}\n ? ProcessInfo[]\n : number[];\n\ntype ProcessListCallback = (err: Error | null, list?: ProcessList) => void;\ntype ListCallback<T extends ListOptions | undefined> = (\n err: Error | null,\n list?: ResultType<T>\n) => void;\n\ntype ProcessListFn = (callback: ProcessListCallback) => void;\n\nconst platformToMethod: Record<Platform, Method> = {\n darwin: 'ps',\n sunos: 'ps',\n freebsd: 'ps',\n netbsd: 'ps',\n win: 'wmic',\n linux: 'ps',\n aix: 'ps',\n};\n\nconst methodToFn: Record<Method, ProcessListFn> = {\n ps,\n wmic,\n};\n\nlet platform: string = os.platform();\nif (platform.startsWith('win')) {\n platform = 'win';\n}\n\nconst method: Method | undefined = platformToMethod[platform as Platform];\n\n/**\n * Gets the list of all the pids of the system.\n */\nconst getAll = (callback: ProcessListCallback): void => {\n if (method === undefined) {\n callback(\n new Error(\n os.platform() +\n ' is not supported yet, please open an issue (https://github.com/simonepri/pidtree)'\n ),\n undefined\n );\n return;\n }\n\n const listFn = methodToFn[method];\n listFn(callback);\n};\n\n/**\n * Get the list of children and grandchildren pids of the given PID.\n * @param PID A PID. If -1 will return all the pids.\n * @param options Optional options object.\n * @param callback Called when the list is ready.\n */\nconst pidtree = <T extends ListOptions | undefined>(\n PID: number | string,\n options: T | ListCallback<T> | undefined,\n callback?: ListCallback<T>\n): void => {\n let normalizedOptions: ListOptions;\n let normalizedCallback: ListCallback<T>;\n\n if (typeof options === 'function') {\n normalizedCallback = options;\n normalizedOptions = {};\n } else {\n normalizedCallback = callback!;\n normalizedOptions = typeof options === 'object' ? options : {};\n }\n\n const parsedPID = parseInt(String(PID), 10);\n if (Number.isNaN(parsedPID) || parsedPID < -1) {\n normalizedCallback(\n new TypeError('The pid provided is invalid') as Error,\n undefined\n );\n return;\n }\n\n getAll((err, processList) => {\n if (err) {\n normalizedCallback(err, undefined);\n return;\n }\n\n if (!processList) {\n normalizedCallback(new Error('Failed to get process list'), undefined);\n return;\n }\n\n // If the user wants the whole list just return it\n if (parsedPID === -1) {\n const result = processList.map(([ppid, pid]) =>\n normalizedOptions.advanced ? { ppid, pid } : pid\n ) as ResultType<T>;\n\n normalizedCallback(null, result);\n return;\n }\n\n let root: ProcessInfo | number | undefined;\n for (let l = 0; l < processList.length; l++) {\n
|
|
1
|
+
{"version":3,"file":"pidTree.mjs","names":["os"],"sources":["../../../../src/utils/runParallel/pidTree.ts"],"sourcesContent":["import * as os from 'node:os';\nimport { ps } from './ps';\nimport { wmic } from './wmic';\n\ntype Platform =\n | 'darwin'\n | 'sunos'\n | 'freebsd'\n | 'netbsd'\n | 'win'\n | 'linux'\n | 'aix';\ntype Method = 'ps' | 'wmic';\n\ntype ProcessList = [number, number][]; // [PPID, PID][]\n\ninterface ListOptions {\n root?: boolean;\n advanced?: boolean;\n}\n\ntype ProcessInfo = { pid: number; ppid?: number };\ntype ResultType<T extends ListOptions | undefined> = T extends {\n advanced: true;\n}\n ? ProcessInfo[]\n : number[];\n\ntype ProcessListCallback = (err: Error | null, list?: ProcessList) => void;\ntype ListCallback<T extends ListOptions | undefined> = (\n err: Error | null,\n list?: ResultType<T>\n) => void;\n\ntype ProcessListFn = (callback: ProcessListCallback) => void;\n\nconst platformToMethod: Record<Platform, Method> = {\n darwin: 'ps',\n sunos: 'ps',\n freebsd: 'ps',\n netbsd: 'ps',\n win: 'wmic',\n linux: 'ps',\n aix: 'ps',\n};\n\nconst methodToFn: Record<Method, ProcessListFn> = {\n ps,\n wmic,\n};\n\nlet platform: string = os.platform();\nif (platform.startsWith('win')) {\n platform = 'win';\n}\n\nconst method: Method | undefined = platformToMethod[platform as Platform];\n\n/**\n * Gets the list of all the pids of the system.\n */\nconst getAll = (callback: ProcessListCallback): void => {\n if (method === undefined) {\n callback(\n new Error(\n os.platform() +\n ' is not supported yet, please open an issue (https://github.com/simonepri/pidtree)'\n ),\n undefined\n );\n return;\n }\n\n const listFn = methodToFn[method];\n listFn(callback);\n};\n\n/**\n * Get the list of children and grandchildren pids of the given PID.\n * @param PID A PID. If -1 will return all the pids.\n * @param options Optional options object.\n * @param callback Called when the list is ready.\n */\nconst pidtree = <T extends ListOptions | undefined>(\n PID: number | string,\n options: T | ListCallback<T> | undefined,\n callback?: ListCallback<T>\n): void => {\n let normalizedOptions: ListOptions;\n let normalizedCallback: ListCallback<T>;\n\n if (typeof options === 'function') {\n normalizedCallback = options;\n normalizedOptions = {};\n } else {\n normalizedCallback = callback!;\n normalizedOptions = typeof options === 'object' ? options : {};\n }\n\n const parsedPID = parseInt(String(PID), 10);\n if (Number.isNaN(parsedPID) || parsedPID < -1) {\n normalizedCallback(\n new TypeError('The pid provided is invalid') as Error,\n undefined\n );\n return;\n }\n\n getAll((err, processList) => {\n if (err) {\n normalizedCallback(err, undefined);\n return;\n }\n\n if (!processList) {\n normalizedCallback(new Error('Failed to get process list'), undefined);\n return;\n }\n\n // If the user wants the whole list just return it\n if (parsedPID === -1) {\n const result = processList.map(([ppid, pid]) =>\n normalizedOptions.advanced ? { ppid, pid } : pid\n ) as ResultType<T>;\n\n normalizedCallback(null, result);\n return;\n }\n\n let root: ProcessInfo | number | undefined;\n for (let l = 0; l < processList.length; l++) {\n const proc = processList[l];\n\n if (!proc) continue;\n const [ppid, pid] = proc;\n\n if (pid === parsedPID) {\n root = normalizedOptions.advanced\n ? { ppid, pid: parsedPID }\n : parsedPID;\n break;\n }\n\n if (ppid === parsedPID) {\n root = normalizedOptions.advanced ? { pid: parsedPID } : parsedPID; // Special pids like 0 on *nix\n }\n }\n\n if (root === undefined) {\n normalizedCallback(new Error('No matching pid found'), undefined);\n return;\n }\n\n // Build the adjacency Hash Map (pid -> [children of pid])\n const tree: Record<number, number[]> = {};\n const listCopy = [...processList];\n while (listCopy.length > 0) {\n const element = listCopy.pop();\n\n if (!element) continue;\n const ppid = element[0];\n const pid = element[1];\n const children = tree[ppid];\n\n if (children) {\n children.push(pid);\n } else {\n tree[ppid] = [pid];\n }\n }\n\n // Starting by the PID provided by the user, traverse the tree using the\n // adjacency Hash Map until the whole subtree is visited.\n // Each pid encountered while visiting is added to the pids array.\n let idx = 0;\n const pids: (ProcessInfo | number)[] = [root];\n while (idx < pids.length) {\n const curpid = normalizedOptions.advanced\n ? (pids[idx++] as ProcessInfo).pid\n : (pids[idx++] as number);\n const children = tree[curpid];\n\n if (!children) continue;\n const length = children.length;\n for (let j = 0; j < length; j++) {\n const childPid = children[j];\n\n if (childPid === undefined) continue;\n\n pids.push(\n normalizedOptions.advanced\n ? { ppid: curpid, pid: childPid }\n : childPid\n );\n }\n\n delete tree[curpid];\n }\n\n if (!normalizedOptions.root) {\n pids.shift(); // Remove root\n }\n\n normalizedCallback(null, pids as ResultType<T>);\n });\n};\n\nconst pify = <T extends ListOptions | undefined>(\n fn: typeof pidtree,\n arg1: number | string,\n arg2: T | undefined\n): Promise<ResultType<T>> => {\n return new Promise((resolve, reject) => {\n fn(arg1, arg2, (err, data) => {\n if (err) return reject(err);\n if (data === undefined) {\n return reject(new Error('No data returned'));\n }\n resolve(data);\n });\n });\n};\n\n// Node versions prior to 4.0.0 do not define have `startsWith`.\n/* istanbul ignore if */\nif (!String.prototype.startsWith) {\n String.prototype.startsWith = function (suffix: string): boolean {\n return this.substring(0, suffix.length) === suffix;\n };\n}\n\n/**\n * Get the list of children pids of the given pid.\n * @param pid A PID. If -1 will return all the pids.\n * @param options Optional options object.\n * @param callback Called when the list is ready. If not provided a promise is returned instead.\n * @returns Only when the callback is not provided.\n */\nexport const list = <T extends ListOptions | undefined>(\n pid: number | string,\n options?: T | ListCallback<T>,\n callback?: ListCallback<T>\n): Promise<ResultType<T>> | undefined => {\n if (typeof options === 'function') {\n pidtree(pid, undefined, options);\n return;\n }\n\n if (typeof callback === 'function') {\n pidtree(pid, options, callback);\n return;\n }\n\n return pify(pidtree, pid, options);\n};\n"],"mappings":";;;;;AAoCA,MAAM,mBAA6C;CACjD,QAAQ;CACR,OAAO;CACP,SAAS;CACT,QAAQ;CACR,KAAK;CACL,OAAO;CACP,KAAK;AACP;AAEA,MAAM,aAA4C;CAChD;CACA;AACF;AAEA,IAAI,WAAmBA,KAAG,SAAS;AACnC,IAAI,SAAS,WAAW,KAAK,GAC3B,WAAW;AAGb,MAAM,SAA6B,iBAAiB;;;;AAKpD,MAAM,UAAU,aAAwC;CACtD,IAAI,WAAW,QAAW;EACxB,yBACE,IAAI,MACFA,KAAG,SAAS,IACV,oFACJ,GACA,MACF;EACA;CACF;CAEA,MAAM,SAAS,WAAW;CAC1B,OAAO,QAAQ;AACjB;;;;;;;AAQA,MAAM,WACJ,KACA,SACA,aACS;CACT,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO,YAAY,YAAY;EACjC,qBAAqB;EACrB,oBAAoB,CAAC;CACvB,OAAO;EACL,qBAAqB;EACrB,oBAAoB,OAAO,YAAY,WAAW,UAAU,CAAC;CAC/D;CAEA,MAAM,YAAY,SAAS,OAAO,GAAG,GAAG,EAAE;CAC1C,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,IAAI;EAC7C,mCACE,IAAI,UAAU,6BAA6B,GAC3C,MACF;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AS,SAAS;GACxB,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK;IAC/B,MAAM,WAAW,SAAS;IAE1B,IAAI,aAAa,QAAW;IAE5B,KAAK,KACH,kBAAkB,WACd;KAAE,MAAM;KAAQ,KAAK;IAAS,IAC9B,QACN;GACF;GAEA,OAAO,KAAK;EACd;EAEA,IAAI,CAAC,kBAAkB,MACrB,KAAK,MAAM;EAGb,mBAAmB,MAAM,IAAqB;CAChD,CAAC;AACH;AAEA,MAAM,QACJ,IACA,MACA,SAC2B;CAC3B,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,GAAG,MAAM,OAAO,KAAK,SAAS;GAC5B,IAAI,KAAK,OAAO,OAAO,GAAG;GAC1B,IAAI,SAAS,QACX,OAAO,uBAAO,IAAI,MAAM,kBAAkB,CAAC;GAE7C,QAAQ,IAAI;EACd,CAAC;CACH,CAAC;AACH;;AAIA,IAAI,CAAC,OAAO,UAAU,YACpB,OAAO,UAAU,aAAa,SAAU,QAAyB;CAC/D,OAAO,KAAK,UAAU,GAAG,OAAO,MAAM,MAAM;AAC9C;;;;;;;;AAUF,MAAa,QACX,KACA,SACA,aACuC;CACvC,IAAI,OAAO,YAAY,YAAY;EACjC,QAAQ,KAAK,QAAW,OAAO;EAC/B;CACF;CAEA,IAAI,OAAO,aAAa,YAAY;EAClC,QAAQ,KAAK,SAAS,QAAQ;EAC9B;CACF;CAEA,OAAO,KAAK,SAAS,KAAK,OAAO;AACnC"}
|
|
@@ -28,11 +28,16 @@ const ps = (callback) => {
|
|
|
28
28
|
const lines = stdout.split(os$1.EOL);
|
|
29
29
|
const list = [];
|
|
30
30
|
for (let i = 1; i < lines.length; i++) {
|
|
31
|
-
const
|
|
31
|
+
const line = lines[i];
|
|
32
|
+
if (!line) continue;
|
|
33
|
+
const trimmed = line.trim();
|
|
32
34
|
if (!trimmed) continue;
|
|
33
35
|
const parts = trimmed.split(/\s+/);
|
|
34
|
-
const
|
|
35
|
-
const
|
|
36
|
+
const p0 = parts[0];
|
|
37
|
+
const p1 = parts[1];
|
|
38
|
+
if (!p0 || !p1) continue;
|
|
39
|
+
const ppid = parseInt(p0, 10);
|
|
40
|
+
const pid = parseInt(p1, 10);
|
|
36
41
|
if (!Number.isNaN(ppid) && !Number.isNaN(pid)) list.push([ppid, pid]);
|
|
37
42
|
}
|
|
38
43
|
callback(null, list);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ps.mjs","names":["os"],"sources":["../../../../src/utils/runParallel/ps.ts"],"sourcesContent":["import * as os from 'node:os';\nimport { run } from './bin';\n\ntype ProcessList = [number, number][]; // [PPID, PID][]\ntype ProcessListCallback = (err: Error | null, list?: ProcessList) => void;\n\n/**\n * Gets the list of all the pids of the system through the ps command.\n * @param callback Callback function with error and process list.\n */\nexport const ps = (callback: ProcessListCallback): void => {\n const args = ['-A', '-o', 'ppid,pid'];\n\n run('ps', args, (err, stdout, code) => {\n if (err) {\n callback(err);\n return;\n }\n if (code !== 0) {\n callback(new Error(`pidtree ps command exited with code ${code}`));\n return;\n }\n\n // Example of stdout\n //\n // PPID PID\n // 1 430\n // 430 432\n // 1 727\n // 1 7166\n\n if (!stdout) {\n callback(new Error('No stdout received from ps command'));\n return;\n }\n\n try {\n const lines = stdout.split(os.EOL);\n\n const list: ProcessList = [];\n for (let i = 1; i < lines.length; i++) {\n const
|
|
1
|
+
{"version":3,"file":"ps.mjs","names":["os"],"sources":["../../../../src/utils/runParallel/ps.ts"],"sourcesContent":["import * as os from 'node:os';\nimport { run } from './bin';\n\ntype ProcessList = [number, number][]; // [PPID, PID][]\ntype ProcessListCallback = (err: Error | null, list?: ProcessList) => void;\n\n/**\n * Gets the list of all the pids of the system through the ps command.\n * @param callback Callback function with error and process list.\n */\nexport const ps = (callback: ProcessListCallback): void => {\n const args = ['-A', '-o', 'ppid,pid'];\n\n run('ps', args, (err, stdout, code) => {\n if (err) {\n callback(err);\n return;\n }\n if (code !== 0) {\n callback(new Error(`pidtree ps command exited with code ${code}`));\n return;\n }\n\n // Example of stdout\n //\n // PPID PID\n // 1 430\n // 430 432\n // 1 727\n // 1 7166\n\n if (!stdout) {\n callback(new Error('No stdout received from ps command'));\n return;\n }\n\n try {\n const lines = stdout.split(os.EOL);\n\n const list: ProcessList = [];\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n\n if (!line) continue;\n\n const trimmed = line.trim();\n\n if (!trimmed) continue;\n\n const parts = trimmed.split(/\\s+/);\n const p0 = parts[0];\n const p1 = parts[1];\n\n if (!p0 || !p1) continue;\n\n const ppid = parseInt(p0, 10); // PPID\n const pid = parseInt(p1, 10); // PID\n\n if (!Number.isNaN(ppid) && !Number.isNaN(pid)) {\n list.push([ppid, pid]);\n }\n }\n\n callback(null, list);\n } catch (error) {\n callback(error instanceof Error ? error : new Error(String(error)));\n }\n });\n};\n"],"mappings":";;;;;;;;AAUA,MAAa,MAAM,aAAwC;CAGzD,IAAI,MAAM;EAFI;EAAM;EAAM;CAEb,IAAI,KAAK,QAAQ,SAAS;EACrC,IAAI,KAAK;GACP,SAAS,GAAG;GACZ;EACF;EACA,IAAI,SAAS,GAAG;GACd,yBAAS,IAAI,MAAM,uCAAuC,MAAM,CAAC;GACjE;EACF;EAUA,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,MAAM,oCAAoC,CAAC;GACxD;EACF;EAEA,IAAI;GACF,MAAM,QAAQ,OAAO,MAAMA,KAAG,GAAG;GAEjC,MAAM,OAAoB,CAAC;GAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;IACrC,MAAM,OAAO,MAAM;IAEnB,IAAI,CAAC,MAAM;IAEX,MAAM,UAAU,KAAK,KAAK;IAE1B,IAAI,CAAC,SAAS;IAEd,MAAM,QAAQ,QAAQ,MAAM,KAAK;IACjC,MAAM,KAAK,MAAM;IACjB,MAAM,KAAK,MAAM;IAEjB,IAAI,CAAC,MAAM,CAAC,IAAI;IAEhB,MAAM,OAAO,SAAS,IAAI,EAAE;IAC5B,MAAM,MAAM,SAAS,IAAI,EAAE;IAE3B,IAAI,CAAC,OAAO,MAAM,IAAI,KAAK,CAAC,OAAO,MAAM,GAAG,GAC1C,KAAK,KAAK,CAAC,MAAM,GAAG,CAAC;GAEzB;GAEA,SAAS,MAAM,IAAI;EACrB,SAAS,OAAO;GACd,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;EACpE;CACF,CAAC;AACH"}
|
|
@@ -119,7 +119,8 @@ const runTasks = (tasks, options) => {
|
|
|
119
119
|
if (aborted) return;
|
|
120
120
|
if (options.aggregateOutput) originalOutputStream.write(writer.toString());
|
|
121
121
|
if (result.code === null && result.signal !== null && result.signal !== void 0) result.code = 128 + convert(result.signal);
|
|
122
|
-
results[task.index]
|
|
122
|
+
const taskResult = results[task.index];
|
|
123
|
+
if (taskResult) taskResult.code = result.code;
|
|
123
124
|
if (result.code) {
|
|
124
125
|
error = /* @__PURE__ */ new Error(`Task ${result.name} failed with code ${result.code}`);
|
|
125
126
|
if (!options.continueOnError) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runTask.mjs","names":[],"sources":["../../../../src/utils/runParallel/runTask.ts"],"sourcesContent":["//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport { Writable } from 'node:stream';\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Remove the given value from the array.\n */\nconst remove = <T>(array: T[], x: T): void => {\n const index = array.indexOf(x);\n if (index !== -1) {\n array.splice(index, 1);\n }\n};\n\nconst signals: Record<string, number> = {\n // Signal name mappings to their respective standard numeric codes.\n // See: https://man7.org/linux/man-pages/man7/signal.7.html\n\n SIGABRT: 6, // Abort signal from abort(3)\n SIGALRM: 14, // Timer signal from alarm(2)\n SIGBUS: 10, // Bus error (bad memory access)\n SIGCHLD: 20, // Child stopped or terminated\n SIGCONT: 19, // Continue if stopped\n SIGFPE: 8, // Floating point exception\n SIGHUP: 1, // Hangup detected on controlling terminal or death of controlling process\n SIGILL: 4, // Illegal Instruction\n SIGINT: 2, // Interrupt from keyboard (Ctrl+C)\n SIGKILL: 9, // Kill signal (cannot be caught or ignored)\n SIGPIPE: 13, // Broken pipe: write to pipe with no readers\n SIGQUIT: 3, // Quit from keyboard (Ctrl+\\)\n SIGSEGV: 11, // Invalid memory reference (segmentation fault)\n SIGSTOP: 17, // Stop process (cannot be caught or ignored)\n SIGTERM: 15, // Termination signal\n SIGTRAP: 5, // Trace/breakpoint trap\n SIGTSTP: 18, // Stop typed at tty (Ctrl+Z)\n SIGTTIN: 21, // tty input for background process\n SIGTTOU: 22, // tty output for background process\n SIGUSR1: 30, // User-defined signal 1\n SIGUSR2: 31, // User-defined signal 2\n};\n\n/**\n * Converts a signal name to a number.\n */\nconst convert = (signal: string): number => {\n return signals[signal] || 0;\n};\n\n/**\n * Simple in-memory writable stream\n */\nclass MemoryStream extends Writable {\n private chunks: Buffer[] = [];\n\n _write(\n chunk: Buffer,\n _encoding: string,\n callback: (error?: Error | null) => void\n ): void {\n this.chunks.push(chunk);\n callback();\n }\n\n toString(): string {\n return Buffer.concat(this.chunks).toString('utf8');\n }\n}\n\n//------------------------------------------------------------------------------\n// Types\n//------------------------------------------------------------------------------\n\ninterface TaskResult {\n name: string;\n code: number | null;\n signal?: string | null;\n}\n\ninterface TaskQueueItem {\n name: string;\n index: number;\n}\n\ninterface RunTaskOptions {\n stdout: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n aggregateOutput?: boolean;\n continueOnError?: boolean;\n race?: boolean;\n maxParallel?: number;\n}\n\ninterface TaskPromise extends Promise<TaskResult> {\n abort?: () => void;\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * Run npm-scripts of given names in parallel.\n *\n * If a npm-script exited with a non-zero code, this aborts other all npm-scripts.\n *\n * Note: This is a simplified version for our use case.\n * The full implementation would require the actual runTask function from npm-run-all.\n */\nexport const runTasks = (\n tasks: string[],\n options: RunTaskOptions\n): Promise<TaskResult[]> => {\n return new Promise((resolve, reject) => {\n if (tasks.length === 0) {\n resolve([]);\n return;\n }\n\n const results: TaskResult[] = tasks.map((task) => ({\n name: task,\n code: undefined as any,\n }));\n const queue: TaskQueueItem[] = tasks.map((task, index) => ({\n name: task,\n index,\n }));\n const promises: TaskPromise[] = [];\n let error: Error | null = null;\n let aborted = false;\n\n /**\n * Done.\n */\n const done = (): void => {\n if (error == null) {\n resolve(results);\n } else {\n reject(error);\n }\n };\n\n /**\n * Aborts all tasks.\n */\n const abort = (): void => {\n if (aborted) {\n return;\n }\n aborted = true;\n\n if (promises.length === 0) {\n done();\n } else {\n for (const p of promises) {\n p.abort?.();\n }\n Promise.all(promises).then(done, reject);\n }\n };\n\n /**\n * Runs a next task.\n */\n const next = (): void => {\n if (aborted) {\n return;\n }\n if (queue.length === 0) {\n if (promises.length === 0) {\n done();\n }\n return;\n }\n\n const originalOutputStream = options.stdout;\n const optionsClone = { ...options };\n const writer = new MemoryStream();\n\n if (options.aggregateOutput) {\n optionsClone.stdout = writer as any;\n }\n\n const task = queue.shift()!;\n\n // Note: This requires the actual runTask implementation from npm-run-all\n // For now, this is a placeholder that would need to be implemented\n const promise = Promise.resolve({\n name: task.name,\n code: 0,\n signal: null,\n }) as TaskPromise;\n\n promises.push(promise);\n promise.then(\n (result) => {\n remove(promises, promise);\n if (aborted) {\n return;\n }\n\n if (options.aggregateOutput) {\n originalOutputStream.write(writer.toString());\n }\n\n // Check if the task failed as a result of a signal, and\n // amend the exit code as a result.\n if (\n result.code === null &&\n result.signal !== null &&\n result.signal !== undefined\n ) {\n // An exit caused by a signal must return a status code\n // of 128 plus the value of the signal code.\n // Ref: https://nodejs.org/api/process.html#process_exit_codes\n result.code = 128 + convert(result.signal);\n }\n\n // Save the result.\n results[task.index].code = result.code;\n\n // Aborts all tasks if it's an error.\n if (result.code) {\n error = new Error(\n `Task ${result.name} failed with code ${result.code}`\n );\n if (!options.continueOnError) {\n abort();\n return;\n }\n }\n\n // Aborts all tasks if options.race is true.\n if (options.race && !result.code) {\n abort();\n return;\n }\n\n // Call the next task.\n next();\n },\n (thisError: Error) => {\n remove(promises, promise);\n if (!options.continueOnError || options.race) {\n error = thisError;\n abort();\n return;\n }\n next();\n }\n );\n };\n\n const max = options.maxParallel;\n const end =\n typeof max === 'number' && max > 0\n ? Math.min(tasks.length, max)\n : tasks.length;\n for (let i = 0; i < end; ++i) {\n next();\n }\n });\n};\n"],"mappings":";;;;;;AAaA,MAAM,UAAa,OAAY,MAAe;CAC5C,MAAM,QAAQ,MAAM,QAAQ,CAAC;CAC7B,IAAI,UAAU,IACZ,MAAM,OAAO,OAAO,CAAC;AAEzB;AAEA,MAAM,UAAkC;CAItC,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;AACX;;;;AAKA,MAAM,WAAW,WAA2B;CAC1C,OAAO,QAAQ,WAAW;AAC5B;;;;AAKA,IAAM,eAAN,cAA2B,SAAS;CAClC,AAAQ,SAAmB,CAAC;CAE5B,OACE,OACA,WACA,UACM;EACN,KAAK,OAAO,KAAK,KAAK;EACtB,SAAS;CACX;CAEA,WAAmB;EACjB,OAAO,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM;CACnD;AACF;;;;;;;;;AA0CA,MAAa,YACX,OACA,YAC0B;CAC1B,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,MAAM,WAAW,GAAG;GACtB,QAAQ,CAAC,CAAC;GACV;EACF;EAEA,MAAM,UAAwB,MAAM,KAAK,UAAU;GACjD,MAAM;GACN,MAAM;EACR,EAAE;EACF,MAAM,QAAyB,MAAM,KAAK,MAAM,WAAW;GACzD,MAAM;GACN;EACF,EAAE;EACF,MAAM,WAA0B,CAAC;EACjC,IAAI,QAAsB;EAC1B,IAAI,UAAU;;;;EAKd,MAAM,aAAmB;GACvB,IAAI,SAAS,MACX,QAAQ,OAAO;QAEf,OAAO,KAAK;EAEhB;;;;EAKA,MAAM,cAAoB;GACxB,IAAI,SACF;GAEF,UAAU;GAEV,IAAI,SAAS,WAAW,GACtB,KAAK;QACA;IACL,KAAK,MAAM,KAAK,UACd,EAAE,QAAQ;IAEZ,QAAQ,IAAI,QAAQ,CAAC,CAAC,KAAK,MAAM,MAAM;GACzC;EACF;;;;EAKA,MAAM,aAAmB;GACvB,IAAI,SACF;GAEF,IAAI,MAAM,WAAW,GAAG;IACtB,IAAI,SAAS,WAAW,GACtB,KAAK;IAEP;GACF;GAEA,MAAM,uBAAuB,QAAQ;GACrC,MAAM,eAAe,EAAE,GAAG,QAAQ;GAClC,MAAM,SAAS,IAAI,aAAa;GAEhC,IAAI,QAAQ,iBACV,aAAa,SAAS;GAGxB,MAAM,OAAO,MAAM,MAAM;GAIzB,MAAM,UAAU,QAAQ,QAAQ;IAC9B,MAAM,KAAK;IACX,MAAM;IACN,QAAQ;GACV,CAAC;GAED,SAAS,KAAK,OAAO;GACrB,QAAQ,MACL,WAAW;IACV,OAAO,UAAU,OAAO;IACxB,IAAI,SACF;IAGF,IAAI,QAAQ,iBACV,qBAAqB,MAAM,OAAO,SAAS,CAAC;IAK9C,IACE,OAAO,SAAS,QAChB,OAAO,WAAW,QAClB,OAAO,WAAW,QAKlB,OAAO,OAAO,MAAM,QAAQ,OAAO,MAAM;IAI3C,QAAQ,KAAK,
|
|
1
|
+
{"version":3,"file":"runTask.mjs","names":[],"sources":["../../../../src/utils/runParallel/runTask.ts"],"sourcesContent":["//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport { Writable } from 'node:stream';\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Remove the given value from the array.\n */\nconst remove = <T>(array: T[], x: T): void => {\n const index = array.indexOf(x);\n if (index !== -1) {\n array.splice(index, 1);\n }\n};\n\nconst signals: Record<string, number> = {\n // Signal name mappings to their respective standard numeric codes.\n // See: https://man7.org/linux/man-pages/man7/signal.7.html\n\n SIGABRT: 6, // Abort signal from abort(3)\n SIGALRM: 14, // Timer signal from alarm(2)\n SIGBUS: 10, // Bus error (bad memory access)\n SIGCHLD: 20, // Child stopped or terminated\n SIGCONT: 19, // Continue if stopped\n SIGFPE: 8, // Floating point exception\n SIGHUP: 1, // Hangup detected on controlling terminal or death of controlling process\n SIGILL: 4, // Illegal Instruction\n SIGINT: 2, // Interrupt from keyboard (Ctrl+C)\n SIGKILL: 9, // Kill signal (cannot be caught or ignored)\n SIGPIPE: 13, // Broken pipe: write to pipe with no readers\n SIGQUIT: 3, // Quit from keyboard (Ctrl+\\)\n SIGSEGV: 11, // Invalid memory reference (segmentation fault)\n SIGSTOP: 17, // Stop process (cannot be caught or ignored)\n SIGTERM: 15, // Termination signal\n SIGTRAP: 5, // Trace/breakpoint trap\n SIGTSTP: 18, // Stop typed at tty (Ctrl+Z)\n SIGTTIN: 21, // tty input for background process\n SIGTTOU: 22, // tty output for background process\n SIGUSR1: 30, // User-defined signal 1\n SIGUSR2: 31, // User-defined signal 2\n};\n\n/**\n * Converts a signal name to a number.\n */\nconst convert = (signal: string): number => {\n return signals[signal] || 0;\n};\n\n/**\n * Simple in-memory writable stream\n */\nclass MemoryStream extends Writable {\n private chunks: Buffer[] = [];\n\n _write(\n chunk: Buffer,\n _encoding: string,\n callback: (error?: Error | null) => void\n ): void {\n this.chunks.push(chunk);\n callback();\n }\n\n toString(): string {\n return Buffer.concat(this.chunks).toString('utf8');\n }\n}\n\n//------------------------------------------------------------------------------\n// Types\n//------------------------------------------------------------------------------\n\ninterface TaskResult {\n name: string;\n code: number | null;\n signal?: string | null;\n}\n\ninterface TaskQueueItem {\n name: string;\n index: number;\n}\n\ninterface RunTaskOptions {\n stdout: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n aggregateOutput?: boolean;\n continueOnError?: boolean;\n race?: boolean;\n maxParallel?: number;\n}\n\ninterface TaskPromise extends Promise<TaskResult> {\n abort?: () => void;\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * Run npm-scripts of given names in parallel.\n *\n * If a npm-script exited with a non-zero code, this aborts other all npm-scripts.\n *\n * Note: This is a simplified version for our use case.\n * The full implementation would require the actual runTask function from npm-run-all.\n */\nexport const runTasks = (\n tasks: string[],\n options: RunTaskOptions\n): Promise<TaskResult[]> => {\n return new Promise((resolve, reject) => {\n if (tasks.length === 0) {\n resolve([]);\n return;\n }\n\n const results: TaskResult[] = tasks.map((task) => ({\n name: task,\n code: undefined as any,\n }));\n const queue: TaskQueueItem[] = tasks.map((task, index) => ({\n name: task,\n index,\n }));\n const promises: TaskPromise[] = [];\n let error: Error | null = null;\n let aborted = false;\n\n /**\n * Done.\n */\n const done = (): void => {\n if (error == null) {\n resolve(results);\n } else {\n reject(error);\n }\n };\n\n /**\n * Aborts all tasks.\n */\n const abort = (): void => {\n if (aborted) {\n return;\n }\n aborted = true;\n\n if (promises.length === 0) {\n done();\n } else {\n for (const p of promises) {\n p.abort?.();\n }\n Promise.all(promises).then(done, reject);\n }\n };\n\n /**\n * Runs a next task.\n */\n const next = (): void => {\n if (aborted) {\n return;\n }\n if (queue.length === 0) {\n if (promises.length === 0) {\n done();\n }\n return;\n }\n\n const originalOutputStream = options.stdout;\n const optionsClone = { ...options };\n const writer = new MemoryStream();\n\n if (options.aggregateOutput) {\n optionsClone.stdout = writer as any;\n }\n\n const task = queue.shift()!;\n\n // Note: This requires the actual runTask implementation from npm-run-all\n // For now, this is a placeholder that would need to be implemented\n const promise = Promise.resolve({\n name: task.name,\n code: 0,\n signal: null,\n }) as TaskPromise;\n\n promises.push(promise);\n promise.then(\n (result) => {\n remove(promises, promise);\n if (aborted) {\n return;\n }\n\n if (options.aggregateOutput) {\n originalOutputStream.write(writer.toString());\n }\n\n // Check if the task failed as a result of a signal, and\n // amend the exit code as a result.\n if (\n result.code === null &&\n result.signal !== null &&\n result.signal !== undefined\n ) {\n // An exit caused by a signal must return a status code\n // of 128 plus the value of the signal code.\n // Ref: https://nodejs.org/api/process.html#process_exit_codes\n result.code = 128 + convert(result.signal);\n }\n\n // Save the result.\n const taskResult = results[task.index];\n\n if (taskResult) {\n taskResult.code = result.code;\n }\n\n // Aborts all tasks if it's an error.\n if (result.code) {\n error = new Error(\n `Task ${result.name} failed with code ${result.code}`\n );\n if (!options.continueOnError) {\n abort();\n return;\n }\n }\n\n // Aborts all tasks if options.race is true.\n if (options.race && !result.code) {\n abort();\n return;\n }\n\n // Call the next task.\n next();\n },\n (thisError: Error) => {\n remove(promises, promise);\n if (!options.continueOnError || options.race) {\n error = thisError;\n abort();\n return;\n }\n next();\n }\n );\n };\n\n const max = options.maxParallel;\n const end =\n typeof max === 'number' && max > 0\n ? Math.min(tasks.length, max)\n : tasks.length;\n for (let i = 0; i < end; ++i) {\n next();\n }\n });\n};\n"],"mappings":";;;;;;AAaA,MAAM,UAAa,OAAY,MAAe;CAC5C,MAAM,QAAQ,MAAM,QAAQ,CAAC;CAC7B,IAAI,UAAU,IACZ,MAAM,OAAO,OAAO,CAAC;AAEzB;AAEA,MAAM,UAAkC;CAItC,SAAS;CACT,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;AACX;;;;AAKA,MAAM,WAAW,WAA2B;CAC1C,OAAO,QAAQ,WAAW;AAC5B;;;;AAKA,IAAM,eAAN,cAA2B,SAAS;CAClC,AAAQ,SAAmB,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IACxB,IAAI,SACF;IAGF,IAAI,QAAQ,iBACV,qBAAqB,MAAM,OAAO,SAAS,CAAC;IAK9C,IACE,OAAO,SAAS,QAChB,OAAO,WAAW,QAClB,OAAO,WAAW,QAKlB,OAAO,OAAO,MAAM,QAAQ,OAAO,MAAM;IAI3C,MAAM,aAAa,QAAQ,KAAK;IAEhC,IAAI,YACF,WAAW,OAAO,OAAO;IAI3B,IAAI,OAAO,MAAM;KACf,wBAAQ,IAAI,MACV,QAAQ,OAAO,KAAK,oBAAoB,OAAO,MACjD;KACA,IAAI,CAAC,QAAQ,iBAAiB;MAC5B,MAAM;MACN;KACF;IACF;IAGA,IAAI,QAAQ,QAAQ,CAAC,OAAO,MAAM;KAChC,MAAM;KACN;IACF;IAGA,KAAK;GACP,IACC,cAAqB;IACpB,OAAO,UAAU,OAAO;IACxB,IAAI,CAAC,QAAQ,mBAAmB,QAAQ,MAAM;KAC5C,QAAQ;KACR,MAAM;KACN;IACF;IACA,KAAK;GACP,CACF;EACF;EAEA,MAAM,MAAM,QAAQ;EACpB,MAAM,MACJ,OAAO,QAAQ,YAAY,MAAM,IAC7B,KAAK,IAAI,MAAM,QAAQ,GAAG,IAC1B,MAAM;EACZ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,EAAE,GACzB,KAAK;CAET,CAAC;AACH"}
|
|
@@ -31,11 +31,16 @@ const wmic = (callback) => {
|
|
|
31
31
|
const lines = stdout.split(os$1.EOL);
|
|
32
32
|
const list = [];
|
|
33
33
|
for (let i = 1; i < lines.length; i++) {
|
|
34
|
-
const
|
|
34
|
+
const line = lines[i];
|
|
35
|
+
if (!line) continue;
|
|
36
|
+
const trimmed = line.trim();
|
|
35
37
|
if (!trimmed) continue;
|
|
36
38
|
const parts = trimmed.split(/\s+/);
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
+
const p0 = parts[0];
|
|
40
|
+
const p1 = parts[1];
|
|
41
|
+
if (!p0 || !p1) continue;
|
|
42
|
+
const ppid = parseInt(p0, 10);
|
|
43
|
+
const pid = parseInt(p1, 10);
|
|
39
44
|
if (!Number.isNaN(ppid) && !Number.isNaN(pid)) list.push([ppid, pid]);
|
|
40
45
|
}
|
|
41
46
|
callback(null, list);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wmic.mjs","names":["os"],"sources":["../../../../src/utils/runParallel/wmic.ts"],"sourcesContent":["import type { SpawnOptions } from 'node:child_process';\nimport * as os from 'node:os';\nimport { run } from './bin';\n\ntype ProcessList = [number, number][]; // [PPID, PID][]\ntype ProcessListCallback = (err: Error | null, list?: ProcessList) => void;\n\n/**\n * Gets the list of all the pids of the system through the wmic command.\n * @param callback Callback function with error and process list.\n */\nexport const wmic = (callback: ProcessListCallback): void => {\n const args = ['PROCESS', 'get', 'ParentProcessId,ProcessId'];\n const options: SpawnOptions = {\n windowsHide: true,\n windowsVerbatimArguments: true,\n };\n run('wmic', args, options, (err, stdout, code) => {\n if (err) {\n callback(err);\n return;\n }\n\n if (code !== 0) {\n callback(new Error(`pidtree wmic command exited with code ${code}`));\n return;\n }\n\n // Example of stdout\n //\n // ParentProcessId ProcessId\n // 0 777\n\n if (!stdout) {\n callback(new Error('No stdout received from wmic command'));\n return;\n }\n\n try {\n const lines = stdout.split(os.EOL);\n\n const list: ProcessList = [];\n for (let i = 1; i < lines.length; i++) {\n const
|
|
1
|
+
{"version":3,"file":"wmic.mjs","names":["os"],"sources":["../../../../src/utils/runParallel/wmic.ts"],"sourcesContent":["import type { SpawnOptions } from 'node:child_process';\nimport * as os from 'node:os';\nimport { run } from './bin';\n\ntype ProcessList = [number, number][]; // [PPID, PID][]\ntype ProcessListCallback = (err: Error | null, list?: ProcessList) => void;\n\n/**\n * Gets the list of all the pids of the system through the wmic command.\n * @param callback Callback function with error and process list.\n */\nexport const wmic = (callback: ProcessListCallback): void => {\n const args = ['PROCESS', 'get', 'ParentProcessId,ProcessId'];\n const options: SpawnOptions = {\n windowsHide: true,\n windowsVerbatimArguments: true,\n };\n run('wmic', args, options, (err, stdout, code) => {\n if (err) {\n callback(err);\n return;\n }\n\n if (code !== 0) {\n callback(new Error(`pidtree wmic command exited with code ${code}`));\n return;\n }\n\n // Example of stdout\n //\n // ParentProcessId ProcessId\n // 0 777\n\n if (!stdout) {\n callback(new Error('No stdout received from wmic command'));\n return;\n }\n\n try {\n const lines = stdout.split(os.EOL);\n\n const list: ProcessList = [];\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i];\n\n if (!line) continue;\n const trimmed = line.trim();\n\n if (!trimmed) continue;\n\n const parts = trimmed.split(/\\s+/);\n const p0 = parts[0];\n const p1 = parts[1];\n\n if (!p0 || !p1) continue;\n\n const ppid = parseInt(p0, 10); // PPID\n const pid = parseInt(p1, 10); // PID\n\n if (!Number.isNaN(ppid) && !Number.isNaN(pid)) {\n list.push([ppid, pid]);\n }\n }\n\n callback(null, list);\n } catch (error) {\n callback(error instanceof Error ? error : new Error(String(error)));\n }\n });\n};\n"],"mappings":";;;;;;;;AAWA,MAAa,QAAQ,aAAwC;CAM3D,IAAI,QAAQ;EALE;EAAW;EAAO;CAKjB,GAAG;EAHhB,aAAa;EACb,0BAA0B;CAEJ,IAAI,KAAK,QAAQ,SAAS;EAChD,IAAI,KAAK;GACP,SAAS,GAAG;GACZ;EACF;EAEA,IAAI,SAAS,GAAG;GACd,yBAAS,IAAI,MAAM,yCAAyC,MAAM,CAAC;GACnE;EACF;EAOA,IAAI,CAAC,QAAQ;GACX,yBAAS,IAAI,MAAM,sCAAsC,CAAC;GAC1D;EACF;EAEA,IAAI;GACF,MAAM,QAAQ,OAAO,MAAMA,KAAG,GAAG;GAEjC,MAAM,OAAoB,CAAC;GAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;IACrC,MAAM,OAAO,MAAM;IAEnB,IAAI,CAAC,MAAM;IACX,MAAM,UAAU,KAAK,KAAK;IAE1B,IAAI,CAAC,SAAS;IAEd,MAAM,QAAQ,QAAQ,MAAM,KAAK;IACjC,MAAM,KAAK,MAAM;IACjB,MAAM,KAAK,MAAM;IAEjB,IAAI,CAAC,MAAM,CAAC,IAAI;IAEhB,MAAM,OAAO,SAAS,IAAI,EAAE;IAC5B,MAAM,MAAM,SAAS,IAAI,EAAE;IAE3B,IAAI,CAAC,OAAO,MAAM,IAAI,KAAK,CAAC,OAAO,MAAM,GAAG,GAC1C,KAAK,KAAK,CAAC,MAAM,GAAG,CAAC;GAEzB;GAEA,SAAS,MAAM,IAAI;EACrB,SAAS,OAAO;GACd,SAAS,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;EACpE;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { acquireContentWatcherLock, getCliContentWatcherLabel, getContentWatcherOwner, reportRedundantContentWatcher } from "./contentWatcherLock.mjs";
|
|
2
|
+
import { getAppLogger } from "@intlayer/config/logger";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/startContentWatcher.ts
|
|
5
|
+
/**
|
|
6
|
+
* How often a process that lost the ownership race checks whether the owner is
|
|
7
|
+
* gone, so it can take over once that process stops (e.g. a short-lived config
|
|
8
|
+
* process, or a second dev server).
|
|
9
|
+
*/
|
|
10
|
+
const TAKEOVER_POLL_INTERVAL_MS = 5e3;
|
|
11
|
+
/**
|
|
12
|
+
* Per-process state, kept on `globalThis` rather than in module scope: a process
|
|
13
|
+
* can load both the CJS and ESM builds of this package, and hot-reloading
|
|
14
|
+
* servers (`bun --hot`, Vite SSR) re-evaluate modules without restarting — each
|
|
15
|
+
* copy must still see the watcher the first one started.
|
|
16
|
+
*/
|
|
17
|
+
const getContentWatcherState = () => {
|
|
18
|
+
const stateKey = Symbol.for("intlayer.contentWatcher");
|
|
19
|
+
const globalScope = globalThis;
|
|
20
|
+
globalScope[stateKey] ??= {
|
|
21
|
+
isWatching: false,
|
|
22
|
+
isClaimInFlight: false
|
|
23
|
+
};
|
|
24
|
+
return globalScope[stateKey];
|
|
25
|
+
};
|
|
26
|
+
const claimAndWatch = async (configuration, options) => {
|
|
27
|
+
const state = getContentWatcherState();
|
|
28
|
+
if (!await acquireContentWatcherLock(configuration, {
|
|
29
|
+
source: "bundler",
|
|
30
|
+
label: options.label
|
|
31
|
+
})) {
|
|
32
|
+
const owner = await getContentWatcherOwner(configuration);
|
|
33
|
+
if (owner?.source === "cli") {
|
|
34
|
+
reportRedundantContentWatcher(configuration, {
|
|
35
|
+
cliLabel: owner.label,
|
|
36
|
+
bundlerLabel: options.label
|
|
37
|
+
});
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
setTimeout(() => {
|
|
41
|
+
startContentWatcher(configuration, options);
|
|
42
|
+
}, TAKEOVER_POLL_INTERVAL_MS).unref?.();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
state.isWatching = true;
|
|
46
|
+
try {
|
|
47
|
+
const { watch } = await import("../watcher.mjs");
|
|
48
|
+
await watch({ configuration });
|
|
49
|
+
} catch (error) {
|
|
50
|
+
state.isWatching = false;
|
|
51
|
+
getAppLogger(configuration)(["Failed to watch Intlayer content declarations:", error], { level: "error" });
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Starts the content declaration watcher from an integration (bundler plugin or
|
|
56
|
+
* server middleware), making sure only one watcher rebuilds a project's
|
|
57
|
+
* dictionaries.
|
|
58
|
+
*
|
|
59
|
+
* - Idempotent within a process, across module copies and hot reloads.
|
|
60
|
+
* - Stands down, with an explanation, when `intlayer watch` already covers the
|
|
61
|
+
* project, whether it spawned this process (`--with`) or runs elsewhere.
|
|
62
|
+
* - Otherwise the first process to take the project lock watches; the others
|
|
63
|
+
* retry in the background to take over once it stops.
|
|
64
|
+
*
|
|
65
|
+
* Not awaitable on purpose: a dev server must not wait on the watcher to serve.
|
|
66
|
+
*
|
|
67
|
+
* @param configuration - The resolved Intlayer configuration.
|
|
68
|
+
* @param options - How the integration identifies itself.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* configureServer() {
|
|
73
|
+
* startContentWatcher(configuration, { label: 'vite-intlayer' });
|
|
74
|
+
* }
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
const startContentWatcher = (configuration, options) => {
|
|
78
|
+
const state = getContentWatcherState();
|
|
79
|
+
if (state.isWatching || state.isClaimInFlight) return;
|
|
80
|
+
if (!configuration.content.watch) return;
|
|
81
|
+
if (options.getShouldSkip?.()) return;
|
|
82
|
+
const cliWatcherLabel = getCliContentWatcherLabel();
|
|
83
|
+
if (cliWatcherLabel) {
|
|
84
|
+
reportRedundantContentWatcher(configuration, {
|
|
85
|
+
cliLabel: cliWatcherLabel,
|
|
86
|
+
bundlerLabel: options.label
|
|
87
|
+
});
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
state.isClaimInFlight = true;
|
|
91
|
+
claimAndWatch(configuration, options).finally(() => {
|
|
92
|
+
state.isClaimInFlight = false;
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
//#endregion
|
|
97
|
+
export { startContentWatcher };
|
|
98
|
+
//# sourceMappingURL=startContentWatcher.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"startContentWatcher.mjs","names":[],"sources":["../../../src/utils/startContentWatcher.ts"],"sourcesContent":["import { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport {\n acquireContentWatcherLock,\n getCliContentWatcherLabel,\n getContentWatcherOwner,\n reportRedundantContentWatcher,\n} from './contentWatcherLock';\n\n/**\n * How often a process that lost the ownership race checks whether the owner is\n * gone, so it can take over once that process stops (e.g. a short-lived config\n * process, or a second dev server).\n */\nconst TAKEOVER_POLL_INTERVAL_MS = 5000;\n\nexport type StartContentWatcherOptions = {\n /**\n * How the integration names itself in the lock and in messages, e.g.\n * `vite-intlayer`.\n */\n label: string;\n /**\n * Whether this process must never own the watcher, re-checked on every\n * attempt (e.g. a helper process that outlives the dev server).\n */\n getShouldSkip?: () => boolean;\n};\n\ntype ContentWatcherState = {\n /** Set once the watcher is running in this process. */\n isWatching: boolean;\n /**\n * Set while an ownership attempt is in flight: taking the lock is\n * asynchronous, and integrations re-enter on config reloads or server\n * restarts.\n */\n isClaimInFlight: boolean;\n};\n\n/**\n * Per-process state, kept on `globalThis` rather than in module scope: a process\n * can load both the CJS and ESM builds of this package, and hot-reloading\n * servers (`bun --hot`, Vite SSR) re-evaluate modules without restarting — each\n * copy must still see the watcher the first one started.\n */\nconst getContentWatcherState = (): ContentWatcherState => {\n const stateKey = Symbol.for('intlayer.contentWatcher');\n const globalScope = globalThis as typeof globalThis & {\n [key: symbol]: ContentWatcherState | undefined;\n };\n\n globalScope[stateKey] ??= { isWatching: false, isClaimInFlight: false };\n\n return globalScope[stateKey];\n};\n\nconst claimAndWatch = async (\n configuration: IntlayerConfig,\n options: StartContentWatcherOptions\n): Promise<void> => {\n const state = getContentWatcherState();\n\n const hasAcquiredLock = await acquireContentWatcherLock(configuration, {\n source: 'bundler',\n label: options.label,\n });\n\n if (!hasAcquiredLock) {\n const owner = await getContentWatcherOwner(configuration);\n\n // A CLI watcher started from another terminal is just as redundant as one\n // wrapping this command, and worth the same explanation.\n if (owner?.source === 'cli') {\n reportRedundantContentWatcher(configuration, {\n cliLabel: owner.label,\n bundlerLabel: options.label,\n });\n return;\n }\n\n // Another integration owns the watcher: retry in the background so this\n // process picks it up if that one stops first.\n const retryTimer = setTimeout(() => {\n startContentWatcher(configuration, options);\n }, TAKEOVER_POLL_INTERVAL_MS);\n\n // Unreferenced so a process whose only remaining work is this retry can\n // still exit.\n retryTimer.unref?.();\n\n return;\n }\n\n state.isWatching = true;\n\n try {\n // Imported lazily: the watcher pulls in `@parcel/watcher`, a native module\n // with no business being loaded during a production build.\n const { watch } = await import('../watcher');\n\n await watch({ configuration });\n } catch (error) {\n state.isWatching = false;\n\n getAppLogger(configuration)(\n ['Failed to watch Intlayer content declarations:', error],\n { level: 'error' }\n );\n }\n};\n\n/**\n * Starts the content declaration watcher from an integration (bundler plugin or\n * server middleware), making sure only one watcher rebuilds a project's\n * dictionaries.\n *\n * - Idempotent within a process, across module copies and hot reloads.\n * - Stands down, with an explanation, when `intlayer watch` already covers the\n * project, whether it spawned this process (`--with`) or runs elsewhere.\n * - Otherwise the first process to take the project lock watches; the others\n * retry in the background to take over once it stops.\n *\n * Not awaitable on purpose: a dev server must not wait on the watcher to serve.\n *\n * @param configuration - The resolved Intlayer configuration.\n * @param options - How the integration identifies itself.\n *\n * @example\n * ```ts\n * configureServer() {\n * startContentWatcher(configuration, { label: 'vite-intlayer' });\n * }\n * ```\n */\nexport const startContentWatcher = (\n configuration: IntlayerConfig,\n options: StartContentWatcherOptions\n): void => {\n const state = getContentWatcherState();\n\n if (state.isWatching || state.isClaimInFlight) return;\n if (!configuration.content.watch) return;\n if (options.getShouldSkip?.()) return;\n\n // Spawned by `intlayer watch --with`: the CLI watcher covers the project, and\n // this is known from the environment alone — no need to touch the lock.\n const cliWatcherLabel = getCliContentWatcherLabel();\n\n if (cliWatcherLabel) {\n reportRedundantContentWatcher(configuration, {\n cliLabel: cliWatcherLabel,\n bundlerLabel: options.label,\n });\n return;\n }\n\n state.isClaimInFlight = true;\n\n claimAndWatch(configuration, options).finally(() => {\n state.isClaimInFlight = false;\n });\n};\n"],"mappings":";;;;;;;;;AAcA,MAAM,4BAA4B;;;;;;;AAgClC,MAAM,+BAAoD;CACxD,MAAM,WAAW,OAAO,IAAI,yBAAyB;CACrD,MAAM,cAAc;CAIpB,YAAY,cAAc;EAAE,YAAY;EAAO,iBAAiB;CAAM;CAEtE,OAAO,YAAY;AACrB;AAEA,MAAM,gBAAgB,OACpB,eACA,YACkB;CAClB,MAAM,QAAQ,uBAAuB;CAOrC,IAAI,CAAC,MALyB,0BAA0B,eAAe;EACrE,QAAQ;EACR,OAAO,QAAQ;CACjB,CAAC,GAEqB;EACpB,MAAM,QAAQ,MAAM,uBAAuB,aAAa;EAIxD,IAAI,OAAO,WAAW,OAAO;GAC3B,8BAA8B,eAAe;IAC3C,UAAU,MAAM;IAChB,cAAc,QAAQ;GACxB,CAAC;GACD;EACF;EAUA,AANmB,iBAAiB;GAClC,oBAAoB,eAAe,OAAO;EAC5C,GAAG,yBAIM,CAAC,CAAC,QAAQ;EAEnB;CACF;CAEA,MAAM,aAAa;CAEnB,IAAI;EAGF,MAAM,EAAE,UAAU,MAAM,OAAO;EAE/B,MAAM,MAAM,EAAE,cAAc,CAAC;CAC/B,SAAS,OAAO;EACd,MAAM,aAAa;EAEnB,aAAa,aAAa,CAAC,CACzB,CAAC,kDAAkD,KAAK,GACxD,EAAE,OAAO,QAAQ,CACnB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,uBACX,eACA,YACS;CACT,MAAM,QAAQ,uBAAuB;CAErC,IAAI,MAAM,cAAc,MAAM,iBAAiB;CAC/C,IAAI,CAAC,cAAc,QAAQ,OAAO;CAClC,IAAI,QAAQ,gBAAgB,GAAG;CAI/B,MAAM,kBAAkB,0BAA0B;CAElD,IAAI,iBAAiB;EACnB,8BAA8B,eAAe;GAC3C,UAAU;GACV,cAAc,QAAQ;EACxB,CAAC;EACD;CACF;CAEA,MAAM,kBAAkB;CAExB,cAAc,eAAe,OAAO,CAAC,CAAC,cAAc;EAClD,MAAM,kBAAkB;CAC1B,CAAC;AACH"}
|
package/dist/esm/watcher.mjs
CHANGED
|
@@ -2,7 +2,6 @@ import { formatPath } from "./utils/formatter.mjs";
|
|
|
2
2
|
import { getFormatFromExtension } from "./utils/getFormatFromExtension.mjs";
|
|
3
3
|
import { parseContentDeclarationFileName } from "./utils/parseContentDeclarationFileName.mjs";
|
|
4
4
|
import { prepareIntlayer } from "./prepareIntlayer.mjs";
|
|
5
|
-
import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.mjs";
|
|
6
5
|
import { handleContentDeclarationFileChange } from "./handleContentDeclarationFileChange.mjs";
|
|
7
6
|
import { handleAdditionalContentDeclarationFile } from "./handleAdditionalContentDeclarationFile.mjs";
|
|
8
7
|
import { handleContentDeclarationFileMoved } from "./handleContentDeclarationFileMoved.mjs";
|
|
@@ -171,6 +170,7 @@ const watch = async (options) => {
|
|
|
171
170
|
const { key, locale } = parseContentDeclarationFileName(filePath, configuration);
|
|
172
171
|
const isMarkdown = getFormatFromExtension(extname(filePath)) === "md";
|
|
173
172
|
const declaredLocale = locale ?? (isMarkdown ? configuration.internationalization.defaultLocale : void 0);
|
|
173
|
+
const { writeContentDeclaration } = await import("./writeContentDeclaration/index.mjs");
|
|
174
174
|
await writeContentDeclaration({
|
|
175
175
|
key,
|
|
176
176
|
...declaredLocale && { locale: declaredLocale },
|
package/dist/esm/watcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watcher.mjs","names":["fsWatch"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { existsSync, watch as fsWatch } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { basename, dirname, extname, resolve } from 'node:path';\nimport * as ANSIColor from '@intlayer/config/colors';\nimport { transpileTSToCJS } from '@intlayer/config/file';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n getConfigurationAndFilePath,\n} from '@intlayer/config/node';\nimport {\n clearAllCache,\n clearDiskCacheMemory,\n clearModuleCache,\n normalizePath,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleContentDeclarationFileMoved } from './handleContentDeclarationFileMoved';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport {\n formatPath,\n getFormatFromExtension,\n parseContentDeclarationFileName,\n} from './utils';\nimport { writeContentDeclaration } from './writeContentDeclaration';\n\n// Map to track files that were recently unlinked: oldPath -> { timer, timestamp }\nconst pendingUnlinks = new Map<\n string,\n { timer: NodeJS.Timeout; oldPath: string }\n>();\n\n// Array-based sequential task queue — no Promise chain accumulation, no race conditions\nconst taskQueue: (() => Promise<void>)[] = [];\nlet isProcessing = false;\n\nconst processQueue = async () => {\n if (isProcessing) return;\n isProcessing = true;\n while (taskQueue.length > 0) {\n const task = taskQueue.shift()!;\n try {\n await task();\n } catch (error) {\n console.error(error);\n }\n }\n isProcessing = false;\n};\n\nconst processEvent = (task: () => Promise<void>) => {\n taskQueue.push(task);\n processQueue();\n};\n\ntype WatchOptions = {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n persistent?: boolean;\n};\n\n// awaitWriteFinish equivalent: debounce per path until the file is stable\nconst STABILITY_THRESHOLD = 1000;\n\nconst createStabilityDebounce = () => {\n const pending = new Map<string, NodeJS.Timeout>();\n return (path: string, handler: () => void) => {\n const existing = pending.get(path);\n if (existing) clearTimeout(existing);\n pending.set(\n path,\n setTimeout(() => {\n pending.delete(path);\n handler();\n }, STABILITY_THRESHOLD)\n );\n };\n};\n\n// Initialize @parcel/watcher (non-persistent until subscribed)\nexport const watch = async (options?: WatchOptions) => {\n const { subscribe } = await import('@parcel/watcher');\n\n const configResult = getConfigurationAndFilePath(options?.configOptions);\n const configurationFilePath = configResult.configurationFilePath;\n let configuration: IntlayerConfig =\n options?.configuration ?? configResult.configuration;\n const appLogger = getAppLogger(configuration);\n\n const {\n watch: isWatchMode,\n fileExtensions,\n contentDir,\n excludedPath,\n } = configuration.content;\n\n if (!configuration.content.watch) return;\n\n appLogger('Watching Intlayer content declarations');\n\n if (configuration.build.optimize === true) {\n appLogger(\n [\n `Build optimization is forced to ${colorize('true', ANSIColor.GREY)}, but watching is enabled too.`,\n 'It may lead to dev mode performance degradation as well as import errors.',\n 'Its recommended to keep the',\n colorize('`build.optimized`', ANSIColor.BLUE),\n 'option',\n colorize('undefined', ANSIColor.GREY),\n 'to get the best dev mode experience',\n ],\n {\n level: 'warn',\n }\n );\n }\n\n // Strip glob markers from excludedPath entries to get plain segments (e.g. 'node_modules')\n const excludedSegments = excludedPath.map((segment) =>\n segment.replace(/^\\*\\*\\//, '').replace(/\\/\\*\\*$/, '')\n );\n\n const normalizedConfigPath = configurationFilePath\n ? normalizePath(configurationFilePath)\n : null;\n\n const { mainDir, baseDir } = configuration.system;\n const normalizedMainDir = normalizePath(mainDir);\n const normalizedIntlayerDir = normalizePath(dirname(mainDir));\n\n const subscriptions: { unsubscribe: () => Promise<void> }[] = [];\n\n const scheduleStable = createStabilityDebounce();\n\n // ── mainDir watcher (depth 0) ──────────────────────────────────────────────\n // Detects broken or missing entry-point files inside .intlayer/main\n if (existsSync(mainDir)) {\n const mainDirSub = await subscribe(normalizedMainDir, (err, events) => {\n if (err || isProcessing) return;\n\n for (const event of events) {\n const eventPath = normalizePath(event.path);\n // depth-0 filter: only files directly inside mainDir\n const rel = eventPath.slice(normalizedMainDir.length + 1);\n if (!rel || rel.includes('/')) continue;\n // Temp files written by the bundler (write-then-rename) are build-internal;\n // their deletion must not trigger a clean rebuild.\n if (rel.endsWith('.tmp')) continue;\n\n if (event.type === 'update') {\n processEvent(async () => {\n try {\n // Validate that the regenerated entry point — and the relative\n // dictionary graph it imports — still resolves, by bundling it\n // in-memory with esbuild (via the shared, freshness-checked\n // transpile cache). This replaces a cache-busting dynamic\n // `import()`, which leaked a permanent record into Node's ESM\n // registry on every rebuild since that registry is never evicted.\n const entryCode = await readFile(event.path, 'utf-8');\n await transpileTSToCJS(entryCode, event.path);\n } catch {\n appLogger(\n `Entry point ${basename(event.path)} failed to load, running clean rebuild...`,\n { level: 'warn' }\n );\n await prepareIntlayer(configuration, {\n clean: true,\n forceRun: true,\n });\n }\n });\n } else if (event.type === 'delete') {\n processEvent(async () => {\n appLogger(\n [\n 'Entry point',\n formatPath(basename(event.path)),\n 'was removed, running clean rebuild...',\n ],\n { level: 'warn' }\n );\n await prepareIntlayer(configuration, {\n clean: true,\n forceRun: true,\n });\n });\n }\n }\n });\n subscriptions.push(mainDirSub);\n }\n\n // ── baseDir watcher (depth 0) — detect .intlayer directory removal ─────────\n // Native fs.watch is non-recursive and ideal for single-directory depth-0 detection.\n const intlayerDirName = basename(normalizedIntlayerDir);\n const fsDirWatcher = fsWatch(\n baseDir,\n { persistent: isWatchMode },\n (eventType, filename) => {\n if (isProcessing || !filename) return;\n if (filename !== intlayerDirName) return;\n\n const fullPath = normalizePath(resolve(baseDir, filename));\n if (fullPath !== normalizedIntlayerDir) return;\n\n if (eventType === 'rename' && !existsSync(normalizedIntlayerDir)) {\n appLogger([\n formatPath('.intlayer'),\n 'directory removed, running clean rebuild...',\n ]);\n processEvent(() =>\n prepareIntlayer(configuration, { clean: true, forceRun: true })\n );\n }\n }\n );\n subscriptions.push({\n unsubscribe: async () => {\n fsDirWatcher.close();\n },\n });\n\n // ── main content watcher ───────────────────────────────────────────────────\n // Ignore patterns for @parcel/watcher (micromatch globs)\n const ignorePatterns = excludedSegments.map((s) => `**/${s}/**`);\n\n // Strip trailing slashes so directory matching stays exact. A user-supplied\n const contentDirs = contentDir\n .map((dir) => normalizePath(dir).replace(/\\/+$/, ''))\n .filter(existsSync);\n\n // Collect unique directories to subscribe to (dirs only, not file paths)\n const dirsToWatch = new Set<string>(contentDirs);\n if (normalizedConfigPath) {\n dirsToWatch.add(normalizePath(dirname(normalizedConfigPath)));\n }\n\n const contentHandler = (\n err: Error | null,\n events: Array<{ type: string; path: string }>\n ) => {\n if (err) {\n appLogger(`Watcher error: ${err}`, { level: 'error' });\n appLogger('Restarting watcher');\n prepareIntlayer(configuration);\n return;\n }\n\n for (const event of events) {\n const filePath = event.path;\n const path = normalizePath(filePath);\n\n const isConfigFile =\n normalizedConfigPath && path === normalizedConfigPath;\n\n if (!isConfigFile) {\n // Must originate from a watched content directory\n const isInContentDir = contentDirs.some(\n (d) => path.startsWith(`${d}/`) || path === d\n );\n if (!isInContentDir) continue;\n\n if (excludedSegments.some((segment) => path.includes(`/${segment}`)))\n continue;\n\n if (!fileExtensions.some((extension) => path.endsWith(extension)))\n continue;\n }\n\n if (event.type === 'create') {\n const fileName = basename(filePath);\n\n // Move detection must happen synchronously before any debounce\n let isMove = false;\n let matchedOldPath: string | undefined;\n\n for (const [oldPath] of pendingUnlinks) {\n if (basename(oldPath) === fileName) {\n matchedOldPath = oldPath;\n break;\n }\n }\n\n if (!matchedOldPath && pendingUnlinks.size === 1) {\n matchedOldPath = pendingUnlinks.keys().next().value;\n }\n\n if (matchedOldPath) {\n const pending = pendingUnlinks.get(matchedOldPath);\n if (pending) {\n clearTimeout(pending.timer);\n pendingUnlinks.delete(matchedOldPath);\n }\n isMove = true;\n appLogger(`File moved from ${matchedOldPath} to ${filePath}`);\n }\n\n if (isMove && matchedOldPath) {\n processEvent(async () => {\n await handleContentDeclarationFileMoved(\n matchedOldPath!,\n filePath,\n configuration\n );\n });\n } else {\n // Debounce: wait for write to finish before reading the file\n scheduleStable(path, () => {\n processEvent(async () => {\n const fileContent = await readFile(filePath, 'utf-8');\n const isEmpty = fileContent === '';\n\n if (isEmpty) {\n const { key, locale } = parseContentDeclarationFileName(\n filePath,\n configuration\n );\n\n // A markdown declaration carries a single locale body, so it\n // must always state which locale it holds.\n const isMarkdown =\n getFormatFromExtension(extname(filePath)) === 'md';\n const declaredLocale =\n locale ??\n (isMarkdown\n ? configuration.internationalization.defaultLocale\n : undefined);\n\n await writeContentDeclaration(\n {\n key,\n ...(declaredLocale && { locale: declaredLocale }),\n content: {},\n filePath,\n },\n configuration\n );\n }\n\n await handleAdditionalContentDeclarationFile(\n filePath,\n configuration\n );\n });\n });\n }\n } else if (event.type === 'update') {\n scheduleStable(path, () => {\n processEvent(async () => {\n if (isConfigFile) {\n appLogger('Configuration file changed, repreparing Intlayer');\n\n clearModuleCache(filePath);\n clearAllCache();\n\n const { configuration: newConfiguration } =\n getConfigurationAndFilePath(options?.configOptions);\n\n configuration = options?.configuration ?? newConfiguration;\n\n await prepareIntlayer(configuration, { clean: false });\n } else {\n // Clear module cache for the changed file to avoid stale require() results\n clearModuleCache(filePath);\n // Evict in-memory caches so loadContentDeclaration picks up fresh content\n clearAllCache();\n clearDiskCacheMemory();\n await handleContentDeclarationFileChange(filePath, configuration);\n }\n });\n });\n } else if (event.type === 'delete') {\n // Delay unlink processing to see if an 'add' event occurs (indicating a move)\n const timer = setTimeout(async () => {\n // If timer fires, the file was genuinely removed\n pendingUnlinks.delete(filePath);\n processEvent(async () =>\n handleUnlinkedContentDeclarationFile(filePath, configuration)\n );\n }, 200); // 200ms window to catch the 'create' event\n\n pendingUnlinks.set(filePath, { timer, oldPath: filePath });\n }\n }\n };\n\n for (const dir of dirsToWatch) {\n const sub = await subscribe(dir, contentHandler, {\n ignore: ignorePatterns,\n });\n\n subscriptions.push(sub);\n }\n\n return subscriptions;\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n // Only enter watch mode when the caller explicitly opts in via `persistent`.\n // `configuration.content.watch` is the dev-mode signal consumed by bundler\n // plugins (e.g. vite-intlayer's `configureServer`); it must not coerce\n // `intlayer build` (which passes `persistent: false`) into a persistent\n // watcher, since that prevents the build command from ever exiting.\n if (options?.persistent) {\n await watch({ ...rest, configuration });\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,MAAM,iCAAiB,IAAI,IAGzB;AAGF,MAAM,YAAqC,CAAC;AAC5C,IAAI,eAAe;AAEnB,MAAM,eAAe,YAAY;CAC/B,IAAI,cAAc;CAClB,eAAe;CACf,OAAO,UAAU,SAAS,GAAG;EAC3B,MAAM,OAAO,UAAU,MAAM;EAC7B,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,QAAQ,MA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,OAAO,aAAa;EAC7B,MAAM,MAAM,MAAM,UAAU,KAAK,gBAAgB,EAC/C,QAAQ,eACV,CAAC;EAED,cAAc,KAAK,GAAG;CACxB;CAEA,OAAO;AACT;AAEA,MAAa,wBAAwB,OAAO,YAA2B;CACrE,MAAM,EAAE,aAAa,GAAG,SAAS,WAAW,CAAC;CAC7C,MAAM,gBACJ,SAAS,iBAAiB,iBAAiB,SAAS,aAAa;CAEnE,IAAI,CAAC,aACH,MAAM,gBAAgB,eAAe,EAAE,UAAU,KAAK,CAAC;CAQzD,IAAI,SAAS,YACX,MAAM,MAAM;EAAE,GAAG;EAAM;CAAc,CAAC;AAE1C"}
|
|
1
|
+
{"version":3,"file":"watcher.mjs","names":["fsWatch"],"sources":["../../src/watcher.ts"],"sourcesContent":["import { existsSync, watch as fsWatch } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { basename, dirname, extname, resolve } from 'node:path';\nimport * as ANSIColor from '@intlayer/config/colors';\nimport { transpileTSToCJS } from '@intlayer/config/file';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n getConfigurationAndFilePath,\n} from '@intlayer/config/node';\nimport {\n clearAllCache,\n clearDiskCacheMemory,\n clearModuleCache,\n normalizePath,\n} from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { handleAdditionalContentDeclarationFile } from './handleAdditionalContentDeclarationFile';\nimport { handleContentDeclarationFileChange } from './handleContentDeclarationFileChange';\nimport { handleContentDeclarationFileMoved } from './handleContentDeclarationFileMoved';\nimport { handleUnlinkedContentDeclarationFile } from './handleUnlinkedContentDeclarationFile';\nimport { prepareIntlayer } from './prepareIntlayer';\nimport {\n formatPath,\n getFormatFromExtension,\n parseContentDeclarationFileName,\n} from './utils';\n\n// Map to track files that were recently unlinked: oldPath -> { timer, timestamp }\nconst pendingUnlinks = new Map<\n string,\n { timer: NodeJS.Timeout; oldPath: string }\n>();\n\n// Array-based sequential task queue — no Promise chain accumulation, no race conditions\nconst taskQueue: (() => Promise<void>)[] = [];\nlet isProcessing = false;\n\nconst processQueue = async () => {\n if (isProcessing) return;\n isProcessing = true;\n while (taskQueue.length > 0) {\n const task = taskQueue.shift()!;\n try {\n await task();\n } catch (error) {\n console.error(error);\n }\n }\n isProcessing = false;\n};\n\nconst processEvent = (task: () => Promise<void>) => {\n taskQueue.push(task);\n processQueue();\n};\n\ntype WatchOptions = {\n configuration?: IntlayerConfig;\n configOptions?: GetConfigurationOptions;\n skipPrepare?: boolean;\n persistent?: boolean;\n};\n\n// awaitWriteFinish equivalent: debounce per path until the file is stable\nconst STABILITY_THRESHOLD = 1000;\n\nconst createStabilityDebounce = () => {\n const pending = new Map<string, NodeJS.Timeout>();\n return (path: string, handler: () => void) => {\n const existing = pending.get(path);\n if (existing) clearTimeout(existing);\n pending.set(\n path,\n setTimeout(() => {\n pending.delete(path);\n handler();\n }, STABILITY_THRESHOLD)\n );\n };\n};\n\n// Initialize @parcel/watcher (non-persistent until subscribed)\nexport const watch = async (options?: WatchOptions) => {\n const { subscribe } = await import('@parcel/watcher');\n\n const configResult = getConfigurationAndFilePath(options?.configOptions);\n const configurationFilePath = configResult.configurationFilePath;\n let configuration: IntlayerConfig =\n options?.configuration ?? configResult.configuration;\n const appLogger = getAppLogger(configuration);\n\n const {\n watch: isWatchMode,\n fileExtensions,\n contentDir,\n excludedPath,\n } = configuration.content;\n\n if (!configuration.content.watch) return;\n\n appLogger('Watching Intlayer content declarations');\n\n if (configuration.build.optimize === true) {\n appLogger(\n [\n `Build optimization is forced to ${colorize('true', ANSIColor.GREY)}, but watching is enabled too.`,\n 'It may lead to dev mode performance degradation as well as import errors.',\n 'Its recommended to keep the',\n colorize('`build.optimized`', ANSIColor.BLUE),\n 'option',\n colorize('undefined', ANSIColor.GREY),\n 'to get the best dev mode experience',\n ],\n {\n level: 'warn',\n }\n );\n }\n\n // Strip glob markers from excludedPath entries to get plain segments (e.g. 'node_modules')\n const excludedSegments = excludedPath.map((segment) =>\n segment.replace(/^\\*\\*\\//, '').replace(/\\/\\*\\*$/, '')\n );\n\n const normalizedConfigPath = configurationFilePath\n ? normalizePath(configurationFilePath)\n : null;\n\n const { mainDir, baseDir } = configuration.system;\n const normalizedMainDir = normalizePath(mainDir);\n const normalizedIntlayerDir = normalizePath(dirname(mainDir));\n\n const subscriptions: { unsubscribe: () => Promise<void> }[] = [];\n\n const scheduleStable = createStabilityDebounce();\n\n // ── mainDir watcher (depth 0) ──────────────────────────────────────────────\n // Detects broken or missing entry-point files inside .intlayer/main\n if (existsSync(mainDir)) {\n const mainDirSub = await subscribe(normalizedMainDir, (err, events) => {\n if (err || isProcessing) return;\n\n for (const event of events) {\n const eventPath = normalizePath(event.path);\n // depth-0 filter: only files directly inside mainDir\n const rel = eventPath.slice(normalizedMainDir.length + 1);\n if (!rel || rel.includes('/')) continue;\n // Temp files written by the bundler (write-then-rename) are build-internal;\n // their deletion must not trigger a clean rebuild.\n if (rel.endsWith('.tmp')) continue;\n\n if (event.type === 'update') {\n processEvent(async () => {\n try {\n // Validate that the regenerated entry point — and the relative\n // dictionary graph it imports — still resolves, by bundling it\n // in-memory with esbuild (via the shared, freshness-checked\n // transpile cache). This replaces a cache-busting dynamic\n // `import()`, which leaked a permanent record into Node's ESM\n // registry on every rebuild since that registry is never evicted.\n const entryCode = await readFile(event.path, 'utf-8');\n await transpileTSToCJS(entryCode, event.path);\n } catch {\n appLogger(\n `Entry point ${basename(event.path)} failed to load, running clean rebuild...`,\n { level: 'warn' }\n );\n await prepareIntlayer(configuration, {\n clean: true,\n forceRun: true,\n });\n }\n });\n } else if (event.type === 'delete') {\n processEvent(async () => {\n appLogger(\n [\n 'Entry point',\n formatPath(basename(event.path)),\n 'was removed, running clean rebuild...',\n ],\n { level: 'warn' }\n );\n await prepareIntlayer(configuration, {\n clean: true,\n forceRun: true,\n });\n });\n }\n }\n });\n subscriptions.push(mainDirSub);\n }\n\n // ── baseDir watcher (depth 0) — detect .intlayer directory removal ─────────\n // Native fs.watch is non-recursive and ideal for single-directory depth-0 detection.\n const intlayerDirName = basename(normalizedIntlayerDir);\n const fsDirWatcher = fsWatch(\n baseDir,\n { persistent: isWatchMode },\n (eventType, filename) => {\n if (isProcessing || !filename) return;\n if (filename !== intlayerDirName) return;\n\n const fullPath = normalizePath(resolve(baseDir, filename));\n if (fullPath !== normalizedIntlayerDir) return;\n\n if (eventType === 'rename' && !existsSync(normalizedIntlayerDir)) {\n appLogger([\n formatPath('.intlayer'),\n 'directory removed, running clean rebuild...',\n ]);\n processEvent(() =>\n prepareIntlayer(configuration, { clean: true, forceRun: true })\n );\n }\n }\n );\n subscriptions.push({\n unsubscribe: async () => {\n fsDirWatcher.close();\n },\n });\n\n // ── main content watcher ───────────────────────────────────────────────────\n // Ignore patterns for @parcel/watcher (micromatch globs)\n const ignorePatterns = excludedSegments.map((s) => `**/${s}/**`);\n\n // Strip trailing slashes so directory matching stays exact. A user-supplied\n const contentDirs = contentDir\n .map((dir) => normalizePath(dir).replace(/\\/+$/, ''))\n .filter(existsSync);\n\n // Collect unique directories to subscribe to (dirs only, not file paths)\n const dirsToWatch = new Set<string>(contentDirs);\n if (normalizedConfigPath) {\n dirsToWatch.add(normalizePath(dirname(normalizedConfigPath)));\n }\n\n const contentHandler = (\n err: Error | null,\n events: Array<{ type: string; path: string }>\n ) => {\n if (err) {\n appLogger(`Watcher error: ${err}`, { level: 'error' });\n appLogger('Restarting watcher');\n prepareIntlayer(configuration);\n return;\n }\n\n for (const event of events) {\n const filePath = event.path;\n const path = normalizePath(filePath);\n\n const isConfigFile =\n normalizedConfigPath && path === normalizedConfigPath;\n\n if (!isConfigFile) {\n // Must originate from a watched content directory\n const isInContentDir = contentDirs.some(\n (d) => path.startsWith(`${d}/`) || path === d\n );\n if (!isInContentDir) continue;\n\n if (excludedSegments.some((segment) => path.includes(`/${segment}`)))\n continue;\n\n if (!fileExtensions.some((extension) => path.endsWith(extension)))\n continue;\n }\n\n if (event.type === 'create') {\n const fileName = basename(filePath);\n\n // Move detection must happen synchronously before any debounce\n let isMove = false;\n let matchedOldPath: string | undefined;\n\n for (const [oldPath] of pendingUnlinks) {\n if (basename(oldPath) === fileName) {\n matchedOldPath = oldPath;\n break;\n }\n }\n\n if (!matchedOldPath && pendingUnlinks.size === 1) {\n matchedOldPath = pendingUnlinks.keys().next().value;\n }\n\n if (matchedOldPath) {\n const pending = pendingUnlinks.get(matchedOldPath);\n if (pending) {\n clearTimeout(pending.timer);\n pendingUnlinks.delete(matchedOldPath);\n }\n isMove = true;\n appLogger(`File moved from ${matchedOldPath} to ${filePath}`);\n }\n\n if (isMove && matchedOldPath) {\n processEvent(async () => {\n await handleContentDeclarationFileMoved(\n matchedOldPath!,\n filePath,\n configuration\n );\n });\n } else {\n // Debounce: wait for write to finish before reading the file\n scheduleStable(path, () => {\n processEvent(async () => {\n const fileContent = await readFile(filePath, 'utf-8');\n const isEmpty = fileContent === '';\n\n if (isEmpty) {\n const { key, locale } = parseContentDeclarationFileName(\n filePath,\n configuration\n );\n\n // A markdown declaration carries a single locale body, so it\n // must always state which locale it holds.\n const isMarkdown =\n getFormatFromExtension(extname(filePath)) === 'md';\n const declaredLocale =\n locale ??\n (isMarkdown\n ? configuration.internationalization.defaultLocale\n : undefined);\n\n // Lazy: pulls recast/ast-types, only needed for new empty files\n const { writeContentDeclaration } = await import(\n './writeContentDeclaration'\n );\n\n await writeContentDeclaration(\n {\n key,\n ...(declaredLocale && { locale: declaredLocale }),\n content: {},\n filePath,\n },\n configuration\n );\n }\n\n await handleAdditionalContentDeclarationFile(\n filePath,\n configuration\n );\n });\n });\n }\n } else if (event.type === 'update') {\n scheduleStable(path, () => {\n processEvent(async () => {\n if (isConfigFile) {\n appLogger('Configuration file changed, repreparing Intlayer');\n\n clearModuleCache(filePath);\n clearAllCache();\n\n const { configuration: newConfiguration } =\n getConfigurationAndFilePath(options?.configOptions);\n\n configuration = options?.configuration ?? newConfiguration;\n\n await prepareIntlayer(configuration, { clean: false });\n } else {\n // Clear module cache for the changed file to avoid stale require() results\n clearModuleCache(filePath);\n // Evict in-memory caches so loadContentDeclaration picks up fresh content\n clearAllCache();\n clearDiskCacheMemory();\n await handleContentDeclarationFileChange(filePath, configuration);\n }\n });\n });\n } else if (event.type === 'delete') {\n // Delay unlink processing to see if an 'add' event occurs (indicating a move)\n const timer = setTimeout(async () => {\n // If timer fires, the file was genuinely removed\n pendingUnlinks.delete(filePath);\n processEvent(async () =>\n handleUnlinkedContentDeclarationFile(filePath, configuration)\n );\n }, 200); // 200ms window to catch the 'create' event\n\n pendingUnlinks.set(filePath, { timer, oldPath: filePath });\n }\n }\n };\n\n for (const dir of dirsToWatch) {\n const sub = await subscribe(dir, contentHandler, {\n ignore: ignorePatterns,\n });\n\n subscriptions.push(sub);\n }\n\n return subscriptions;\n};\n\nexport const buildAndWatchIntlayer = async (options?: WatchOptions) => {\n const { skipPrepare, ...rest } = options ?? {};\n const configuration =\n options?.configuration ?? getConfiguration(options?.configOptions);\n\n if (!skipPrepare) {\n await prepareIntlayer(configuration, { forceRun: true });\n }\n\n // Only enter watch mode when the caller explicitly opts in via `persistent`.\n // `configuration.content.watch` is the dev-mode signal consumed by bundler\n // plugins (e.g. vite-intlayer's `configureServer`); it must not coerce\n // `intlayer build` (which passes `persistent: false`) into a persistent\n // watcher, since that prevents the build command from ever exiting.\n if (options?.persistent) {\n await watch({ ...rest, configuration });\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,MAAM,iCAAiB,IAAI,IAGzB;AAGF,MAAM,YAAqC,CAAC;AAC5C,IAAI,eAAe;AAEnB,MAAM,eAAe,YAAY;CAC/B,IAAI,cAAc;CAClB,eAAe;CACf,OAAO,UAAU,SAAS,GAAG;EAC3B,MAAM,OAAO,UAAU,MAAM;EAC7B,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,QAAQ,MAAM,KAAK;EACrB;CACF;CACA,eAAe;AACjB;AAEA,MAAM,gBAAgB,S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MAAM,MAAM,MAAM,UAAU,KAAK,gBAAgB,EAC/C,QAAQ,eACV,CAAC;EAED,cAAc,KAAK,GAAG;CACxB;CAEA,OAAO;AACT;AAEA,MAAa,wBAAwB,OAAO,YAA2B;CACrE,MAAM,EAAE,aAAa,GAAG,SAAS,WAAW,CAAC;CAC7C,MAAM,gBACJ,SAAS,iBAAiB,iBAAiB,SAAS,aAAa;CAEnE,IAAI,CAAC,aACH,MAAM,gBAAgB,eAAe,EAAE,UAAU,KAAK,CAAC;CAQzD,IAAI,SAAS,YACX,MAAM,MAAM;EAAE,GAAG;EAAM;CAAc,CAAC;AAE1C"}
|
|
@@ -13,12 +13,15 @@ const detectExportedComponentName = (fileText) => {
|
|
|
13
13
|
const cjsDefaultVarRegex = /exports\.default\s*=\s*(\w+)/;
|
|
14
14
|
const namedExportRegex = /export\s+(?:const|function)\s+(\w+)/g;
|
|
15
15
|
const defaultEsmFnMatch = fileText.match(defaultEsmFnRegex);
|
|
16
|
-
if (defaultEsmFnMatch) return defaultEsmFnMatch[1];
|
|
16
|
+
if (defaultEsmFnMatch?.[1]) return defaultEsmFnMatch[1];
|
|
17
17
|
const defaultEsmVarMatch = fileText.match(defaultEsmVarRegex);
|
|
18
|
-
if (defaultEsmVarMatch) return defaultEsmVarMatch[1];
|
|
18
|
+
if (defaultEsmVarMatch?.[1]) return defaultEsmVarMatch[1];
|
|
19
19
|
const cjsDefaultMatch = fileText.match(cjsDefaultRegex) || fileText.match(cjsDefaultVarRegex);
|
|
20
|
-
if (cjsDefaultMatch) return cjsDefaultMatch[1];
|
|
21
|
-
for (const match of fileText.matchAll(namedExportRegex))
|
|
20
|
+
if (cjsDefaultMatch?.[1]) return cjsDefaultMatch[1];
|
|
21
|
+
for (const match of fileText.matchAll(namedExportRegex)) {
|
|
22
|
+
const name = match[1];
|
|
23
|
+
if (name && /^[A-Z]/.test(name)) return name;
|
|
24
|
+
}
|
|
22
25
|
return null;
|
|
23
26
|
};
|
|
24
27
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detectExportedComponentName.mjs","names":[],"sources":["../../../src/writeContentDeclaration/detectExportedComponentName.ts"],"sourcesContent":["/**\n * Attempt to detect an exported React component name in the file text.\n * Looks for patterns like:\n * - export const MyComponent = ...\n * - export function MyComponent(...)\n * - export default function MyComponent(...)\n */\nexport const detectExportedComponentName = (\n fileText: string\n): string | null => {\n // Added regexes for default ESM, default CJS, and named exports\n const defaultEsmFnRegex = /export\\s+default\\s+function\\s+(\\w+)/;\n const defaultEsmVarRegex = /export\\s+default\\s+(\\w+)/;\n const cjsDefaultRegex = /module\\.exports\\s*=\\s*(\\w+)/;\n const cjsDefaultVarRegex = /exports\\.default\\s*=\\s*(\\w+)/;\n const namedExportRegex = /export\\s+(?:const|function)\\s+(\\w+)/g;\n\n // Check for default ESM function or variable\n const defaultEsmFnMatch = fileText.match(defaultEsmFnRegex);\n if (defaultEsmFnMatch) {\n return defaultEsmFnMatch[1];\n }\n\n const defaultEsmVarMatch = fileText.match(defaultEsmVarRegex);\n if (defaultEsmVarMatch) {\n return defaultEsmVarMatch[1];\n }\n\n // Check for default CJS\n const cjsDefaultMatch =\n fileText.match(cjsDefaultRegex) || fileText.match(cjsDefaultVarRegex);\n\n if (cjsDefaultMatch) return cjsDefaultMatch[1];\n\n // Otherwise, look for capitalized named exports\n for (const match of fileText.matchAll(namedExportRegex)) {\n if (/^[A-Z]/.test(
|
|
1
|
+
{"version":3,"file":"detectExportedComponentName.mjs","names":[],"sources":["../../../src/writeContentDeclaration/detectExportedComponentName.ts"],"sourcesContent":["/**\n * Attempt to detect an exported React component name in the file text.\n * Looks for patterns like:\n * - export const MyComponent = ...\n * - export function MyComponent(...)\n * - export default function MyComponent(...)\n */\nexport const detectExportedComponentName = (\n fileText: string\n): string | null => {\n // Added regexes for default ESM, default CJS, and named exports\n const defaultEsmFnRegex = /export\\s+default\\s+function\\s+(\\w+)/;\n const defaultEsmVarRegex = /export\\s+default\\s+(\\w+)/;\n const cjsDefaultRegex = /module\\.exports\\s*=\\s*(\\w+)/;\n const cjsDefaultVarRegex = /exports\\.default\\s*=\\s*(\\w+)/;\n const namedExportRegex = /export\\s+(?:const|function)\\s+(\\w+)/g;\n\n // Check for default ESM function or variable\n const defaultEsmFnMatch = fileText.match(defaultEsmFnRegex);\n\n if (defaultEsmFnMatch?.[1]) {\n return defaultEsmFnMatch[1];\n }\n\n const defaultEsmVarMatch = fileText.match(defaultEsmVarRegex);\n if (defaultEsmVarMatch?.[1]) {\n return defaultEsmVarMatch[1];\n }\n\n // Check for default CJS\n const cjsDefaultMatch =\n fileText.match(cjsDefaultRegex) || fileText.match(cjsDefaultVarRegex);\n\n if (cjsDefaultMatch?.[1]) return cjsDefaultMatch[1];\n\n // Otherwise, look for capitalized named exports\n for (const match of fileText.matchAll(namedExportRegex)) {\n const name = match[1];\n if (name && /^[A-Z]/.test(name)) return name;\n }\n\n // If we can’t find it, return null\n return null;\n};\n"],"mappings":";;;;;;;;AAOA,MAAa,+BACX,aACkB;CAElB,MAAM,oBAAoB;CAC1B,MAAM,qBAAqB;CAC3B,MAAM,kBAAkB;CACxB,MAAM,qBAAqB;CAC3B,MAAM,mBAAmB;CAGzB,MAAM,oBAAoB,SAAS,MAAM,iBAAiB;CAE1D,IAAI,oBAAoB,IACtB,OAAO,kBAAkB;CAG3B,MAAM,qBAAqB,SAAS,MAAM,kBAAkB;CAC5D,IAAI,qBAAqB,IACvB,OAAO,mBAAmB;CAI5B,MAAM,kBACJ,SAAS,MAAM,eAAe,KAAK,SAAS,MAAM,kBAAkB;CAEtE,IAAI,kBAAkB,IAAI,OAAO,gBAAgB;CAGjD,KAAK,MAAM,SAAS,SAAS,SAAS,gBAAgB,GAAG;EACvD,MAAM,OAAO,MAAM;EACnB,IAAI,QAAQ,SAAS,KAAK,IAAI,GAAG,OAAO;CAC1C;CAGA,OAAO;AACT"}
|
|
@@ -13,9 +13,9 @@ const stringifyYamlFrontmatter = (fields) => Object.entries(fields).filter(([, v
|
|
|
13
13
|
const getMarkdownBody = (content) => {
|
|
14
14
|
const lines = content.split(/\r?\n/);
|
|
15
15
|
const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== "");
|
|
16
|
-
if (firstNonEmptyIndex === -1 || lines[firstNonEmptyIndex]
|
|
16
|
+
if (firstNonEmptyIndex === -1 || lines[firstNonEmptyIndex]?.trim() !== "---") return content;
|
|
17
17
|
let endIndex = -1;
|
|
18
|
-
for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) if (lines[i]
|
|
18
|
+
for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) if (lines[i]?.trim() === "---") {
|
|
19
19
|
endIndex = i;
|
|
20
20
|
break;
|
|
21
21
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeMarkdownFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/writeMarkdownFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { MARKDOWN } from '@intlayer/types/nodeType';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\nconst stringifyYamlFrontmatter = (fields: Record<string, any>): string =>\n Object.entries(fields)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return `${key}:\\n${value.map((item) => ` - ${JSON.stringify(item)}`).join('\\n')}`;\n }\n if (\n typeof value === 'string' &&\n (value.includes(':') || value.includes('\\n') || value.includes('#'))\n ) {\n return `${key}: ${JSON.stringify(value)}`;\n }\n return `${key}: ${value}`;\n })\n .join('\\n');\n\n// Strips YAML frontmatter from a markdown string, returning only the body\nconst getMarkdownBody = (content: string): string => {\n const lines = content.split(/\\r?\\n/);\n const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== '');\n\n if (firstNonEmptyIndex === -1
|
|
1
|
+
{"version":3,"file":"writeMarkdownFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/writeMarkdownFile.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { MARKDOWN } from '@intlayer/types/nodeType';\nimport { detectFormatCommand } from '../detectFormatCommand';\n\nconst stringifyYamlFrontmatter = (fields: Record<string, any>): string =>\n Object.entries(fields)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]) => {\n if (Array.isArray(value)) {\n return `${key}:\\n${value.map((item) => ` - ${JSON.stringify(item)}`).join('\\n')}`;\n }\n if (\n typeof value === 'string' &&\n (value.includes(':') || value.includes('\\n') || value.includes('#'))\n ) {\n return `${key}: ${JSON.stringify(value)}`;\n }\n return `${key}: ${value}`;\n })\n .join('\\n');\n\n// Strips YAML frontmatter from a markdown string, returning only the body\nconst getMarkdownBody = (content: string): string => {\n const lines = content.split(/\\r?\\n/);\n const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== '');\n\n if (\n firstNonEmptyIndex === -1 ||\n lines[firstNonEmptyIndex]?.trim() !== '---'\n ) {\n return content;\n }\n\n let endIndex = -1;\n for (let i = firstNonEmptyIndex + 1; i < lines.length; i++) {\n if (lines[i]?.trim() === '---') {\n endIndex = i;\n break;\n }\n }\n\n if (endIndex === -1) return content;\n\n return lines\n .slice(endIndex + 1)\n .join('\\n')\n .trimStart();\n};\n\n// Fields that are auto-generated / internal and must not appear in frontmatter\nconst EXCLUDED_FRONTMATTER_KEYS = new Set<string>([\n 'content',\n '$schema',\n 'filePath',\n 'localId',\n 'localIds',\n 'projectIds',\n]);\n\nexport const writeMarkdownFile = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Promise<void> => {\n const content = dictionary.content as any;\n const markdownRaw =\n typeof content === 'object' && content?.nodeType === MARKDOWN\n ? (content[MARKDOWN] ?? '')\n : '';\n // content.markdown now stores the full file (frontmatter + body); extract only the body\n const markdownBody = getMarkdownBody(markdownRaw);\n\n const frontmatterFields = Object.fromEntries(\n Object.entries(dictionary).filter(\n ([k, v]) => !EXCLUDED_FRONTMATTER_KEYS.has(k) && v !== undefined\n )\n );\n\n const frontmatterStr = stringifyYamlFrontmatter(frontmatterFields);\n const fileContent = `---\\n${frontmatterStr}\\n---\\n\\n${markdownBody}`;\n\n const dir = dirname(absoluteFilePath);\n await mkdir(dir, { recursive: true });\n\n const tempDir = configuration.system?.tempDir;\n if (tempDir) await mkdir(tempDir, { recursive: true });\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n\n try {\n await writeFile(tempPath, fileContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n};\n"],"mappings":";;;;;;;AAQA,MAAM,4BAA4B,WAChC,OAAO,QAAQ,MAAM,CAAC,CACnB,QAAQ,GAAG,WAAW,UAAU,UAAa,UAAU,IAAI,CAAC,CAC5D,KAAK,CAAC,KAAK,WAAW;CACrB,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,GAAG,IAAI,KAAK,MAAM,KAAK,SAAS,OAAO,KAAK,UAAU,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAEjF,IACE,OAAO,UAAU,aAChB,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,IAAI,KAAK,MAAM,SAAS,GAAG,IAElE,OAAO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IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,EAAE;CACxG,MAAM,WAAW,UACb,KAAK,SAAS,YAAY,IAC1B,GAAG,iBAAiB,GAAG;CAE3B,IAAI;EACF,MAAM,UAAU,UAAU,aAAa,OAAO;EAC9C,MAAM,OAAO,UAAU,gBAAgB;CACzC,SAAS,OAAO;EACd,IAAI;GACF,MAAM,GAAG,UAAU,EAAE,OAAO,KAAK,CAAC;EACpC,QAAQ,CAER;EACA,MAAM;CACR;CAEA,MAAM,gBAAgB,oBAAoB,aAAa;CACvD,IAAI,eACF,IAAI;EACF,SAAS,cAAc,QAAQ,YAAY,gBAAgB,GAAG;GAC5D,OAAO;GACP,KAAK,cAAc,OAAO;EAC5B,CAAC;CACH,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;CACrB;AAEJ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { writeFileIfChanged } from "./writeFileIfChanged.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/writeJsonIfChanged.ts
|
|
4
|
-
const writeJsonIfChanged = async (path, data, { pretty =
|
|
4
|
+
const writeJsonIfChanged = async (path, data, { pretty = process.env.NODE_ENV === "development" } = {}) => {
|
|
5
5
|
const space = pretty ? 2 : void 0;
|
|
6
6
|
let json = "{}";
|
|
7
7
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"writeJsonIfChanged.mjs","names":[],"sources":["../../src/writeJsonIfChanged.ts"],"sourcesContent":["import { writeFileIfChanged } from './writeFileIfChanged';\n\nexport const writeJsonIfChanged = async <T>(\n path: string,\n data: T,\n { pretty = process.env.NODE_ENV === 'development' } = {}\n): Promise<boolean> => {\n const space = pretty ? 2 : undefined;\n\n let json = '{}';\n\n try {\n json = JSON.stringify(data, null, space);\n } catch (error) {\n console.error(`Error while parsing data to JSON for ${path}:`, error);\n }\n\n return await writeFileIfChanged(path, json);\n};\n"],"mappings":";;;AAEA,MAAa,qBAAqB,OAChC,MACA,MACA,EAAE,
|
|
1
|
+
{"version":3,"file":"writeJsonIfChanged.mjs","names":[],"sources":["../../src/writeJsonIfChanged.ts"],"sourcesContent":["import { writeFileIfChanged } from './writeFileIfChanged';\n\nexport const writeJsonIfChanged = async <T>(\n path: string,\n data: T,\n { pretty = process.env.NODE_ENV === 'development' } = {}\n): Promise<boolean> => {\n const space = pretty ? 2 : undefined;\n\n let json = '{}';\n\n try {\n json = JSON.stringify(data, null, space);\n } catch (error) {\n console.error(`Error while parsing data to JSON for ${path}:`, error);\n }\n\n return await writeFileIfChanged(path, json);\n};\n"],"mappings":";;;AAEA,MAAa,qBAAqB,OAChC,MACA,MACA,EAAE,kCAAkC,kBAAkB,CAAC,MAClC;CACrB,MAAM,QAAQ,SAAS,IAAI;CAE3B,IAAI,OAAO;CAEX,IAAI;EACF,OAAO,KAAK,UAAU,MAAM,MAAM,KAAK;CACzC,SAAS,OAAO;EACd,QAAQ,MAAM,wCAAwC,KAAK,IAAI,KAAK;CACtE;CAEA,OAAO,MAAM,mBAAmB,MAAM,IAAI;AAC5C"}
|
package/dist/types/build.d.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { loadLocalDictionaries } from "./loadDictionaries/loadLocalDictionaries.
|
|
|
20
20
|
import { formatDistantDictionaries, loadRemoteDictionaries } from "./loadDictionaries/loadRemoteDictionaries.js";
|
|
21
21
|
import "./loadDictionaries/index.js";
|
|
22
22
|
import { prepareIntlayer } from "./prepareIntlayer.js";
|
|
23
|
+
import { INTLAYER_WATCH_ENV_VAR, PrepareIntlayerServerOptions, getIsDevWatcherCommand, getIsServerDevelopment, prepareIntlayerServer } from "./prepareIntlayerServer.js";
|
|
23
24
|
import { readDictionariesFromDisk } from "./utils/readDictionariesFromDisk.js";
|
|
24
25
|
import { isCachedConfigurationUpToDate, writeConfiguration } from "./writeConfiguration/index.js";
|
|
25
26
|
import { detectExportedComponentName } from "./writeContentDeclaration/detectExportedComponentName.js";
|
|
@@ -28,4 +29,4 @@ import { transformJSFile } from "./writeContentDeclaration/transformJSFile.js";
|
|
|
28
29
|
import { writeContentDeclaration } from "./writeContentDeclaration/writeContentDeclaration.js";
|
|
29
30
|
import { writeJSFile } from "./writeContentDeclaration/writeJSFile.js";
|
|
30
31
|
import "./writeContentDeclaration/index.js";
|
|
31
|
-
export { BuildDictionariesOptions, CreateDictionaryEntryPointOptions, DictionariesStatus, DictionaryStatus, buildDictionary, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, ensureIntlayerBundle, formatDictionaries, formatDictionariesOutput, formatDictionary, formatDictionaryOutput, formatDistantDictionaries, formatDomains, formatLocalDictionaries, formatRewriteRules, generateDictionaryListContent, generateTypeScriptType, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getTypeName, isCachedConfigurationUpToDate, loadContentDeclaration, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, prepareIntlayer, processContentDeclaration, readDictionariesFromDisk, transformJSFile, writeConfiguration, writeContentDeclaration, writeJSFile };
|
|
32
|
+
export { BuildDictionariesOptions, CreateDictionaryEntryPointOptions, DictionariesStatus, DictionaryStatus, INTLAYER_WATCH_ENV_VAR, PrepareIntlayerServerOptions, buildDictionary, cleanOutputDir, createDictionaryEntryPoint, createModuleAugmentation, createTypes, detectExportedComponentName, ensureIntlayerBundle, formatDictionaries, formatDictionariesOutput, formatDictionary, formatDictionaryOutput, formatDistantDictionaries, formatDomains, formatLocalDictionaries, formatRewriteRules, generateDictionaryListContent, generateTypeScriptType, getBuiltDictionariesPath, getBuiltDynamicDictionariesPath, getBuiltFetchDictionariesPath, getBuiltRemoteDictionariesPath, getBuiltUnmergedDictionariesPath, getIsDevWatcherCommand, getIsServerDevelopment, getTypeName, isCachedConfigurationUpToDate, loadContentDeclaration, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries, prepareIntlayer, prepareIntlayerServer, processContentDeclaration, readDictionariesFromDisk, transformJSFile, writeConfiguration, writeContentDeclaration, writeJSFile };
|