@intlayer/engine 9.5.12 → 9.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/installSkills/skills/cli.md +28 -1
- package/dist/assets/installSkills/skills/compat.md +1 -1
- package/dist/assets/installSkills/skills/dev-tools.md +8 -6
- package/dist/cjs/build.cjs +12 -2
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs +12 -11
- package/dist/cjs/buildIntlayerDictionary/buildIntlayerDictionary.cjs.map +1 -1
- package/dist/cjs/buildIntlayerDictionary/index.cjs +4 -1
- package/dist/cjs/buildIntlayerDictionary/rebuildUnmergedDictionaries.cjs +23 -0
- package/dist/cjs/buildIntlayerDictionary/rebuildUnmergedDictionaries.cjs.map +1 -0
- package/dist/cjs/cli.cjs +12 -0
- package/dist/cjs/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/handleAdditionalContentDeclarationFile.cjs +1 -1
- package/dist/cjs/handleContentDeclarationFileChange.cjs +1 -1
- package/dist/cjs/handleUnlinkedContentDeclarationFile.cjs +1 -1
- package/dist/cjs/init/cms.cjs +18 -0
- package/dist/cjs/init/cms.cjs.map +1 -1
- package/dist/cjs/init/index.cjs +23 -10
- package/dist/cjs/init/index.cjs.map +1 -1
- package/dist/cjs/init/utils/configManipulation.cjs +28 -0
- package/dist/cjs/init/utils/configManipulation.cjs.map +1 -1
- package/dist/cjs/init/utils/contentLayout.cjs +61 -0
- package/dist/cjs/init/utils/contentLayout.cjs.map +1 -0
- package/dist/cjs/init/utils/index.cjs +1 -0
- package/dist/cjs/init/utils/packageManager.cjs +1 -1
- package/dist/cjs/init/utils/packageManager.cjs.map +1 -1
- package/dist/cjs/installMCP/installMCP.cjs +35 -25
- package/dist/cjs/installMCP/installMCP.cjs.map +1 -1
- package/dist/cjs/installSkills/index.cjs +26 -1
- package/dist/cjs/installSkills/index.cjs.map +1 -1
- package/dist/cjs/listDictionariesPath.cjs +2 -5
- package/dist/cjs/listDictionariesPath.cjs.map +1 -1
- package/dist/cjs/listGitFiles.cjs +3 -5
- package/dist/cjs/listGitFiles.cjs.map +1 -1
- package/dist/cjs/listProjects.cjs +1 -2
- package/dist/cjs/listProjects.cjs.map +1 -1
- package/dist/cjs/loadDictionaries/index.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadDictionaries.cjs +1 -1
- package/dist/cjs/loadDictionaries/loadRemoteDictionaries.cjs.map +1 -1
- package/dist/cjs/utils/buildComponentFilesList.cjs +18 -30
- package/dist/cjs/utils/buildComponentFilesList.cjs.map +1 -1
- package/dist/cjs/utils/chunkJSON.cjs +1 -1
- package/dist/cjs/utils/chunkJSON.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +2 -0
- package/dist/cjs/utils/isDirectoryExcluded.cjs +36 -0
- package/dist/cjs/utils/isDirectoryExcluded.cjs.map +1 -0
- package/dist/cjs/watcher.cjs +5 -2
- package/dist/cjs/watcher.cjs.map +1 -1
- package/dist/cjs/writeConfiguration/index.cjs +23 -0
- package/dist/cjs/writeConfiguration/index.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/index.cjs +6 -0
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs +20 -13
- package/dist/cjs/writeContentDeclaration/processContentDeclarationContent.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/renderContentDeclaration.cjs +213 -0
- package/dist/cjs/writeContentDeclaration/renderContentDeclaration.cjs.map +1 -0
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +5 -51
- package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs +2 -31
- package/dist/cjs/writeContentDeclaration/writeMarkdownFile.cjs.map +1 -1
- package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs +2 -8
- package/dist/cjs/writeContentDeclaration/writeYamlFile.cjs.map +1 -1
- package/dist/esm/build.mjs +7 -5
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs +12 -12
- package/dist/esm/buildIntlayerDictionary/buildIntlayerDictionary.mjs.map +1 -1
- package/dist/esm/buildIntlayerDictionary/index.mjs +3 -2
- package/dist/esm/buildIntlayerDictionary/rebuildUnmergedDictionaries.mjs +22 -0
- package/dist/esm/buildIntlayerDictionary/rebuildUnmergedDictionaries.mjs.map +1 -0
- package/dist/esm/cli.mjs +5 -3
- package/dist/esm/fetchDistantDictionaries.mjs.map +1 -1
- package/dist/esm/handleAdditionalContentDeclarationFile.mjs +1 -1
- package/dist/esm/handleContentDeclarationFileChange.mjs +1 -1
- package/dist/esm/handleUnlinkedContentDeclarationFile.mjs +1 -1
- package/dist/esm/init/cms.mjs +19 -2
- package/dist/esm/init/cms.mjs.map +1 -1
- package/dist/esm/init/index.mjs +24 -11
- package/dist/esm/init/index.mjs.map +1 -1
- package/dist/esm/init/utils/configManipulation.mjs +28 -1
- package/dist/esm/init/utils/configManipulation.mjs.map +1 -1
- package/dist/esm/init/utils/contentLayout.mjs +58 -0
- package/dist/esm/init/utils/contentLayout.mjs.map +1 -0
- package/dist/esm/init/utils/index.mjs +2 -2
- package/dist/esm/init/utils/packageManager.mjs +1 -1
- package/dist/esm/init/utils/packageManager.mjs.map +1 -1
- package/dist/esm/installMCP/installMCP.mjs +35 -25
- package/dist/esm/installMCP/installMCP.mjs.map +1 -1
- package/dist/esm/installSkills/index.mjs +27 -3
- package/dist/esm/installSkills/index.mjs.map +1 -1
- package/dist/esm/listDictionariesPath.mjs +2 -5
- package/dist/esm/listDictionariesPath.mjs.map +1 -1
- package/dist/esm/listGitFiles.mjs +1 -1
- package/dist/esm/listGitFiles.mjs.map +1 -1
- package/dist/esm/listProjects.mjs +1 -1
- package/dist/esm/listProjects.mjs.map +1 -1
- package/dist/esm/loadDictionaries/index.mjs +1 -1
- package/dist/esm/loadDictionaries/loadDictionaries.mjs +1 -1
- package/dist/esm/loadDictionaries/loadRemoteDictionaries.mjs.map +1 -1
- package/dist/esm/utils/buildComponentFilesList.mjs +19 -31
- package/dist/esm/utils/buildComponentFilesList.mjs.map +1 -1
- package/dist/esm/utils/chunkJSON.mjs +1 -1
- package/dist/esm/utils/chunkJSON.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +2 -1
- package/dist/esm/utils/isDirectoryExcluded.mjs +35 -0
- package/dist/esm/utils/isDirectoryExcluded.mjs.map +1 -0
- package/dist/esm/utils/runParallel/pidTree.mjs +3 -3
- package/dist/esm/utils/runParallel/pidTree.mjs.map +1 -1
- package/dist/esm/utils/runParallel/ps.mjs +2 -2
- package/dist/esm/utils/runParallel/ps.mjs.map +1 -1
- package/dist/esm/utils/runParallel/wmic.mjs +2 -2
- package/dist/esm/utils/runParallel/wmic.mjs.map +1 -1
- package/dist/esm/watcher.mjs +5 -2
- package/dist/esm/watcher.mjs.map +1 -1
- package/dist/esm/writeConfiguration/index.mjs +23 -1
- package/dist/esm/writeConfiguration/index.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/index.mjs +2 -1
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs +20 -13
- package/dist/esm/writeContentDeclaration/processContentDeclarationContent.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/renderContentDeclaration.mjs +208 -0
- package/dist/esm/writeContentDeclaration/renderContentDeclaration.mjs.map +1 -0
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +5 -51
- package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs +2 -31
- package/dist/esm/writeContentDeclaration/writeMarkdownFile.mjs.map +1 -1
- package/dist/esm/writeContentDeclaration/writeYamlFile.mjs +2 -8
- package/dist/esm/writeContentDeclaration/writeYamlFile.mjs.map +1 -1
- package/dist/types/build.d.ts +5 -3
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts +6 -0
- package/dist/types/buildIntlayerDictionary/buildIntlayerDictionary.d.ts.map +1 -1
- package/dist/types/buildIntlayerDictionary/index.d.ts +3 -2
- package/dist/types/buildIntlayerDictionary/rebuildUnmergedDictionaries.d.ts +14 -0
- package/dist/types/buildIntlayerDictionary/rebuildUnmergedDictionaries.d.ts.map +1 -0
- package/dist/types/cli.d.ts +6 -4
- package/dist/types/fetchDistantDictionaries.d.ts +1 -1
- package/dist/types/fetchDistantDictionaries.d.ts.map +1 -1
- package/dist/types/init/cms.d.ts +6 -0
- package/dist/types/init/cms.d.ts.map +1 -1
- package/dist/types/init/index.d.ts +15 -14
- package/dist/types/init/index.d.ts.map +1 -1
- package/dist/types/init/utils/configManipulation.d.ts +8 -0
- package/dist/types/init/utils/configManipulation.d.ts.map +1 -1
- package/dist/types/init/utils/contentLayout.d.ts +42 -0
- package/dist/types/init/utils/contentLayout.d.ts.map +1 -0
- package/dist/types/init/utils/index.d.ts +2 -2
- package/dist/types/init/utils/packageManager.d.ts +9 -3
- package/dist/types/init/utils/packageManager.d.ts.map +1 -1
- package/dist/types/installMCP/installMCP.d.ts +4 -0
- package/dist/types/installMCP/installMCP.d.ts.map +1 -1
- package/dist/types/installSkills/index.d.ts +6 -0
- package/dist/types/installSkills/index.d.ts.map +1 -1
- package/dist/types/listDictionariesPath.d.ts +1 -1
- package/dist/types/listDictionariesPath.d.ts.map +1 -1
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts +1 -1
- package/dist/types/loadDictionaries/loadRemoteDictionaries.d.ts.map +1 -1
- package/dist/types/utils/buildComponentFilesList.d.ts +6 -6
- package/dist/types/utils/buildComponentFilesList.d.ts.map +1 -1
- package/dist/types/utils/chunkJSON.d.ts.map +1 -1
- package/dist/types/utils/index.d.ts +2 -1
- package/dist/types/utils/isDirectoryExcluded.d.ts +15 -0
- package/dist/types/utils/isDirectoryExcluded.d.ts.map +1 -0
- package/dist/types/watcher.d.ts.map +1 -1
- package/dist/types/writeConfiguration/index.d.ts +13 -0
- package/dist/types/writeConfiguration/index.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/index.d.ts +2 -1
- package/dist/types/writeContentDeclaration/processContentDeclarationContent.d.ts +8 -2
- package/dist/types/writeContentDeclaration/processContentDeclarationContent.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/renderContentDeclaration.d.ts +61 -0
- package/dist/types/writeContentDeclaration/renderContentDeclaration.d.ts.map +1 -0
- package/dist/types/writeContentDeclaration/writeContentDeclaration.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/writeMarkdownFile.d.ts.map +1 -1
- package/dist/types/writeContentDeclaration/writeYamlFile.d.ts.map +1 -1
- package/package.json +18 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"listProjects.mjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport simpleGit from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Returns the git repository root directory, or `null` when the given\n * directory is not inside a git repository.\n */\nexport const getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;;AAsBA,MAAa,gBAAgB,OAAO,QAAyC;CAC3E,IAAI;EAGF,QAAO,OAFK,MAAM,UAAU,GAAG,IAAI,UAAU,EACpB,CAAC,SAAS,CAAC,iBAAiB,CAAC,EACxC,CAAC,KAAK;CACtB,SAAS,QAAQ;EACf,OAAO;CACT;AACF;;;;;;;AAQA,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,IAAI;CAGhD,IAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,SAAS;EAChD,IAAI,YACF,YAAY;CAEhB;CAGA,MAAM,iBAAiB,6BAA6B,KACjD,aAAa,MAAM,UACtB;CAGA,MAAM,cAAc,MAAM,GAAG,gBAAgB;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,YAAY;EAC3C,KAAK;CACP,CAAC;CAGD,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,SAAS,QAAQ,IAAI,CAAC,CAAC,CAAC;CAGzE,OAAO;EAAE;EAAW,cAAc,YAAY,KAAK;CAAE;AACvD"}
|
|
1
|
+
{"version":3,"file":"listProjects.mjs","names":[],"sources":["../../src/listProjects.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport { configurationFilesCandidates } from '@intlayer/config/node';\nimport fg from 'fast-glob';\nimport { simpleGit } from 'simple-git';\n\nexport type ListProjectsOptions = {\n /**\n * Base directory to search from\n * @default process.cwd()\n */\n baseDir?: string;\n /**\n * If true, search from the git root directory instead of baseDir\n * @default false\n */\n gitRoot?: boolean;\n};\n\n/**\n * Returns the git repository root directory, or `null` when the given\n * directory is not inside a git repository.\n */\nexport const getGitRootDir = async (cwd?: string): Promise<string | null> => {\n try {\n const git = cwd ? simpleGit(cwd) : simpleGit();\n const rootDir = await git.revparse(['--show-toplevel']);\n return rootDir.trim();\n } catch (_error) {\n return null;\n }\n};\n\n/**\n * List all Intlayer projects by searching for configuration files\n *\n * @param options - Options for listing projects\n * @returns Array of absolute paths to project directories containing Intlayer config\n */\nexport const listProjects = async (\n options?: ListProjectsOptions\n): Promise<{ searchDir: string; projectsPath: string[] }> => {\n let searchDir = options?.baseDir ?? process.cwd();\n\n // If gitRoot option is enabled, try to get the git root directory\n if (options?.gitRoot) {\n const gitRootDir = await getGitRootDir(searchDir);\n if (gitRootDir) {\n searchDir = gitRootDir;\n }\n }\n\n // Build glob patterns for all config file candidates\n const configPatterns = configurationFilesCandidates.map(\n (fileName) => `**/${fileName}`\n );\n\n // Search for all config files\n const configFiles = await fg(configPatterns, {\n cwd: searchDir,\n absolute: true,\n ignore: ['**/node_modules/**', '**/.git/**'],\n dot: true, // Include dot files like .intlayerrc\n });\n\n // Extract unique directory paths from config files\n const projectDirs = [...new Set(configFiles.map((file) => dirname(file)))];\n\n // Sort alphabetically for consistent output\n return { searchDir, projectsPath: projectDirs.sort() };\n};\n"],"mappings":";;;;;;;;;;AAsBA,MAAa,gBAAgB,OAAO,QAAyC;CAC3E,IAAI;EAGF,QAAO,OAFK,MAAM,UAAU,GAAG,IAAI,UAAU,EACpB,CAAC,SAAS,CAAC,iBAAiB,CAAC,EACxC,CAAC,KAAK;CACtB,SAAS,QAAQ;EACf,OAAO;CACT;AACF;;;;;;;AAQA,MAAa,eAAe,OAC1B,YAC2D;CAC3D,IAAI,YAAY,SAAS,WAAW,QAAQ,IAAI;CAGhD,IAAI,SAAS,SAAS;EACpB,MAAM,aAAa,MAAM,cAAc,SAAS;EAChD,IAAI,YACF,YAAY;CAEhB;CAGA,MAAM,iBAAiB,6BAA6B,KACjD,aAAa,MAAM,UACtB;CAGA,MAAM,cAAc,MAAM,GAAG,gBAAgB;EAC3C,KAAK;EACL,UAAU;EACV,QAAQ,CAAC,sBAAsB,YAAY;EAC3C,KAAK;CACP,CAAC;CAGD,MAAM,cAAc,CAAC,GAAG,IAAI,IAAI,YAAY,KAAK,SAAS,QAAQ,IAAI,CAAC,CAAC,CAAC;CAGzE,OAAO;EAAE;EAAW,cAAc,YAAY,KAAK;CAAE;AACvD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ensureIntlayerBundle, formatLocalDictionaries, loadContentDeclaration, loadContentDeclarations } from "./loadContentDeclaration.mjs";
|
|
2
|
+
import { loadLocalDictionaries } from "./loadLocalDictionaries.mjs";
|
|
2
3
|
import { formatDistantDictionaries, loadRemoteDictionaries } from "./loadRemoteDictionaries.mjs";
|
|
3
4
|
import { loadDictionaries } from "./loadDictionaries.mjs";
|
|
4
|
-
import { loadLocalDictionaries } from "./loadLocalDictionaries.mjs";
|
|
5
5
|
|
|
6
6
|
export { ensureIntlayerBundle, formatDistantDictionaries, formatLocalDictionaries, loadContentDeclaration, loadContentDeclarations, loadDictionaries, loadLocalDictionaries, loadRemoteDictionaries };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { filterInvalidDictionaries } from "../filterInvalidDictionaries.mjs";
|
|
2
|
-
import { formatDictionaries } from "../formatDictionary.mjs";
|
|
3
2
|
import { loadContentDeclarations } from "./loadContentDeclaration.mjs";
|
|
3
|
+
import { formatDictionaries } from "../formatDictionary.mjs";
|
|
4
4
|
import { loadRemoteDictionaries } from "./loadRemoteDictionaries.mjs";
|
|
5
5
|
import { DictionariesLogger } from "./log.mjs";
|
|
6
6
|
import * as ANSIColors from "@intlayer/config/colors";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadRemoteDictionaries.mjs","names":[],"sources":["../../../src/loadDictionaries/loadRemoteDictionaries.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"loadRemoteDictionaries.mjs","names":[],"sources":["../../../src/loadDictionaries/loadRemoteDictionaries.ts"],"sourcesContent":["import type { DictionaryAPI } from '@intlayer/api';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getRemoteDictionaries } from '@intlayer/dictionaries-entry/remote';\nimport type {\n Dictionary,\n DictionaryId,\n DictionaryKey,\n} from '@intlayer/types/dictionary';\nimport { sortAlphabetically } from '../utils/sortAlphabetically';\nimport type { DictionariesStatus } from './loadDictionaries';\n\nexport const formatDistantDictionaries = (\n dictionaries: (DictionaryAPI | Dictionary)[]\n): Dictionary[] =>\n dictionaries.map((dict) => ({\n ...dict,\n localId: `${dict.key}::remote::${dict.id}`,\n location: 'remote' as const,\n }));\n\nexport const loadRemoteDictionaries = async (\n configuration = getConfiguration(),\n onStatusUpdate?: (status: DictionariesStatus[]) => void,\n options?: {\n onStartRemoteCheck?: () => void;\n onStopRemoteCheck?: () => void;\n onError?: (error: Error) => void;\n }\n): Promise<Dictionary[]> => {\n const { editor } = configuration;\n const remoteDictionariesRecord = getRemoteDictionaries(configuration);\n\n const hasRemoteDictionaries = Boolean(editor.clientId && editor.clientSecret);\n\n if (!hasRemoteDictionaries) return [];\n\n try {\n options?.onStartRemoteCheck?.();\n\n // Lazy: the CMS client is only needed when remote credentials are set\n const { createRemoteDictionaryClient, fetchDistantDictionaries } =\n await import('./remoteDictionaryClient');\n\n const dictionary = createRemoteDictionaryClient(configuration);\n\n // Get the list of dictionary keys\n const getDictionariesKeysResult =\n await dictionary.getDictionariesUpdateTimestamp();\n\n const distantDictionaryUpdateTimeStamp: Record<\n DictionaryId,\n { key: DictionaryKey; updatedAt: number }\n > | null = getDictionariesKeysResult.data;\n\n if (!distantDictionaryUpdateTimeStamp) {\n throw new Error('No distant dictionaries found');\n }\n\n const dictionariesIdToFetch = Object.entries(\n distantDictionaryUpdateTimeStamp\n ).filter(([dictionaryId, data]) => {\n // If remote doesn't provide updatedAt, fetch to be safe\n if (!data.updatedAt) return true;\n\n // If no local cache exists, fetch\n const local: Dictionary | undefined = remoteDictionariesRecord[\n data.key\n ]?.find((dictionary) => dictionary.id === dictionaryId);\n if (!local) return true;\n\n const localUpdatedAtRaw = (local as any)?.updatedAt as\n | number\n | string\n | undefined;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // If local timestamp missing or older than remote, fetch\n if (typeof localUpdatedAt !== 'number') return true;\n\n return data.updatedAt > localUpdatedAt;\n });\n\n const flatRemoteDictionariesRecord: DictionaryAPI[] = Object.values(\n remoteDictionariesRecord\n ).flat();\n\n const cachedDictionaries: Dictionary[] =\n flatRemoteDictionariesRecord.filter((dictionary) => {\n const remoteUpdatedAt = dictionary.id\n ? distantDictionaryUpdateTimeStamp[dictionary.id]?.updatedAt\n : undefined;\n\n const localUpdatedAtRaw = dictionary.updatedAt;\n\n const localUpdatedAt =\n typeof localUpdatedAtRaw === 'number'\n ? localUpdatedAtRaw\n : localUpdatedAtRaw\n ? new Date(localUpdatedAtRaw).getTime()\n : undefined;\n\n // Consider as cached/imported when local exists and is up-to-date or newer\n return (\n typeof localUpdatedAt === 'number' &&\n typeof remoteUpdatedAt === 'number' &&\n localUpdatedAt >= remoteUpdatedAt\n );\n });\n\n // Report cached as already imported\n if (cachedDictionaries.length > 0) {\n onStatusUpdate?.(\n cachedDictionaries.map((dictionary) => ({\n dictionaryKey: dictionary.key,\n type: 'remote',\n status: 'imported',\n }))\n );\n }\n\n // Several qualified dictionaries can share a key, so keys are deduplicated:\n // one request per key already returns all of its siblings.\n const orderedDistantDictionaryKeys = [\n ...new Set(dictionariesIdToFetch.map(([, data]) => data.key)),\n ].sort(sortAlphabetically);\n\n // Report pending for keys to be fetched so totals are visible immediately\n if (orderedDistantDictionaryKeys.length > 0) {\n onStatusUpdate?.(\n orderedDistantDictionaryKeys.map((key) => ({\n dictionaryKey: key,\n type: 'remote',\n status: 'pending',\n }))\n );\n }\n\n const distantDictionariesData = await fetchDistantDictionaries(\n {\n dictionaryKeys: orderedDistantDictionaryKeys,\n },\n onStatusUpdate\n );\n\n const distantDictionaries: Dictionary[] = formatDistantDictionaries(\n distantDictionariesData\n );\n\n // Fetching by key also returns the up-to-date siblings of a stale\n // dictionary, so drop the cached copies the remote just sent back.\n const fetchedDictionaryIds = new Set(\n distantDictionaries.map((dictionary) => dictionary.id)\n );\n\n const notRefetchedCachedDictionaries = cachedDictionaries.filter(\n (dictionary) => !fetchedDictionaryIds.has(dictionary.id)\n );\n\n return [...notRefetchedCachedDictionaries, ...distantDictionaries];\n } catch (error) {\n options?.onError?.(error as Error);\n return [];\n } finally {\n options?.onStopRemoteCheck?.();\n }\n};\n"],"mappings":";;;;;AAWA,MAAa,6BACX,iBAEA,aAAa,KAAK,UAAU;CAC1B,GAAG;CACH,SAAS,GAAG,KAAK,IAAI,YAAY,KAAK;CACtC,UAAU;AACZ,EAAE;AAEJ,MAAa,yBAAyB,OACpC,gBAAgB,iBAAiB,GACjC,gBACA,YAK0B;CAC1B,MAAM,EAAE,WAAW;CACnB,MAAM,2BAA2B,sBAAsB,aAAa;CAIpE,IAAI,CAF0B,QAAQ,OAAO,YAAY,OAAO,YAEvC,GAAG,OAAO,CAAC;CAEpC,IAAI;EACF,SAAS,qBAAqB;EAG9B,MAAM,EAAE,8BAA8B,6BACpC,MAAM,OAAO;EAQf,MAAM,oCAGK,MATQ,6BAA6B,aAI/B,CAAC,CAAC,+BAA+B,EAKd,CAAC;EAErC,IAAI,CAAC,kCACH,MAAM,IAAI,MAAM,+BAA+B;EAGjD,MAAM,wBAAwB,OAAO,QACnC,gCACF,CAAC,CAAC,QAAQ,CAAC,cAAc,UAAU;GAEjC,IAAI,CAAC,KAAK,WAAW,OAAO;GAG5B,MAAM,QAAgC,yBACpC,KAAK,IACN,EAAE,MAAM,eAAe,WAAW,OAAO,YAAY;GACtD,IAAI,CAAC,OAAO,OAAO;GAEnB,M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,CAAC;CACV,UAAU;EACR,SAAS,oBAAoB;CAC/B;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isDirectoryExcluded } from "./isDirectoryExcluded.mjs";
|
|
2
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
2
3
|
import { TRAVERSE_PATTERN } from "@intlayer/config/defaultValues";
|
|
3
4
|
import { normalizePath } from "@intlayer/config/utils";
|
|
4
5
|
import fg from "fast-glob";
|
|
@@ -9,27 +10,24 @@ import fg from "fast-glob";
|
|
|
9
10
|
*/
|
|
10
11
|
const normalizeToArray = (value) => Array.isArray(value) ? value : [value];
|
|
11
12
|
/**
|
|
12
|
-
* Remove directories
|
|
13
|
-
*
|
|
14
|
-
*
|
|
13
|
+
* Remove directories nested in others so files are never scanned twice.
|
|
14
|
+
* A nested directory is kept as its own root when the exclude patterns would
|
|
15
|
+
* drop it from its parent's scan (e.g. `<root>/dist` under `**\/dist/**`).
|
|
16
|
+
*
|
|
17
|
+
* Example: ['/root', '/root/src', '/root/dist'] → ['/root', '/root/dist']
|
|
15
18
|
*/
|
|
16
|
-
const getDistinctRootDirs = (dirs) => {
|
|
19
|
+
const getDistinctRootDirs = (dirs, excludePatterns) => {
|
|
17
20
|
const uniqueDirs = Array.from(new Set(dirs.map((dir) => resolve(dir))));
|
|
18
21
|
uniqueDirs.sort((a, b) => a.length - b.length);
|
|
19
22
|
return uniqueDirs.reduce((acc, dir) => {
|
|
20
23
|
if (!acc.some((parent) => {
|
|
21
|
-
const
|
|
22
|
-
return !
|
|
24
|
+
const relativePath = relative(parent, dir);
|
|
25
|
+
return relativePath !== "" && !relativePath.startsWith("..") && !isAbsolute(relativePath) && !isDirectoryExcluded(relativePath, excludePatterns);
|
|
23
26
|
})) acc.push(dir);
|
|
24
27
|
return acc;
|
|
25
28
|
}, []);
|
|
26
29
|
};
|
|
27
30
|
/**
|
|
28
|
-
* Returns true when the resolved path passes through a `node_modules` segment.
|
|
29
|
-
* Works on both POSIX and Windows paths.
|
|
30
|
-
*/
|
|
31
|
-
const isInsideNodeModules = (dir) => resolve(dir).split(sep).includes("node_modules");
|
|
32
|
-
/**
|
|
33
31
|
* Default exclude patterns derived from TRAVERSE_PATTERN.
|
|
34
32
|
* Extracted once so the function body can reference them without re-computing.
|
|
35
33
|
*/
|
|
@@ -41,18 +39,18 @@ const DEFAULT_EXCLUDE_PATTERNS = TRAVERSE_PATTERN.filter((p) => typeof p === "st
|
|
|
41
39
|
* patterns, negation patterns embedded in `traversePattern`, and optional
|
|
42
40
|
* dot-file inclusion.
|
|
43
41
|
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
42
|
+
* `codeDir` entries are more precise than the exclude patterns: a `codeDir`
|
|
43
|
+
* inside an excluded directory (e.g. a design-system `dist` or a package in
|
|
44
|
+
* `node_modules`) is scanned as its own root, so the exclusion only applies
|
|
45
|
+
* below it.
|
|
48
46
|
*
|
|
49
47
|
* @example
|
|
50
48
|
* // Single root with excludes
|
|
51
49
|
* const files = buildComponentFilesList(config);
|
|
52
50
|
*
|
|
53
51
|
* @example
|
|
54
|
-
* // Design-system
|
|
55
|
-
* // intlayer.config.ts: { content: { codeDir: ['node_modules/my-ds/
|
|
52
|
+
* // Design-system build output is still scanned
|
|
53
|
+
* // intlayer.config.ts: { content: { codeDir: ['node_modules/my-ds/dist'] } }
|
|
56
54
|
* const files = buildComponentFilesList(config);
|
|
57
55
|
*/
|
|
58
56
|
const buildComponentFilesList = (config, excludePattern) => {
|
|
@@ -67,23 +65,13 @@ const buildComponentFilesList = (config, excludePattern) => {
|
|
|
67
65
|
...excludePattern ?? [],
|
|
68
66
|
...contentDeclarationPattern
|
|
69
67
|
])).filter((pattern) => typeof pattern === "string").map(normalizePath);
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
const normalCodeDirs = resolvedCodeDirs.filter((dir) => !isInsideNodeModules(dir));
|
|
73
|
-
const normalFiles = getDistinctRootDirs([config.system.baseDir, ...normalCodeDirs]).flatMap((root) => fg.sync(patterns, {
|
|
68
|
+
const roots = getDistinctRootDirs([config.system.baseDir, ...config.content.codeDir ?? []], baseExcludePatterns);
|
|
69
|
+
return Array.from(new Set(roots.flatMap((root) => fg.sync(patterns, {
|
|
74
70
|
cwd: root,
|
|
75
71
|
ignore: baseExcludePatterns,
|
|
76
72
|
absolute: true,
|
|
77
73
|
dot: true
|
|
78
|
-
}));
|
|
79
|
-
const nodeModulesExcludePatterns = baseExcludePatterns.filter((pattern) => !pattern.includes("node_modules"));
|
|
80
|
-
const nodeModulesFiles = inNodeModulesCodeDirs.flatMap((dir) => fg.sync(patterns, {
|
|
81
|
-
cwd: dir,
|
|
82
|
-
ignore: nodeModulesExcludePatterns,
|
|
83
|
-
absolute: true,
|
|
84
|
-
dot: false
|
|
85
|
-
}));
|
|
86
|
-
return Array.from(/* @__PURE__ */ new Set([...normalFiles, ...nodeModulesFiles]));
|
|
74
|
+
}))));
|
|
87
75
|
};
|
|
88
76
|
|
|
89
77
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildComponentFilesList.mjs","names":[],"sources":["../../../src/utils/buildComponentFilesList.ts"],"sourcesContent":["import { isAbsolute, relative, resolve
|
|
1
|
+
{"version":3,"file":"buildComponentFilesList.mjs","names":[],"sources":["../../../src/utils/buildComponentFilesList.ts"],"sourcesContent":["import { isAbsolute, relative, resolve } from 'node:path';\nimport { TRAVERSE_PATTERN } from '@intlayer/config/defaultValues';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport fg from 'fast-glob';\nimport { isDirectoryExcluded } from './isDirectoryExcluded';\n\n/**\n * Normalizes a pattern value to an array\n */\nconst normalizeToArray = <T>(value: T | T[]): T[] =>\n Array.isArray(value) ? value : [value];\n\n/**\n * Remove directories nested in others so files are never scanned twice.\n * A nested directory is kept as its own root when the exclude patterns would\n * drop it from its parent's scan (e.g. `<root>/dist` under `**\\/dist/**`).\n *\n * Example: ['/root', '/root/src', '/root/dist'] → ['/root', '/root/dist']\n */\nconst getDistinctRootDirs = (\n dirs: string[],\n excludePatterns: string[]\n): string[] => {\n const uniqueDirs = Array.from(new Set(dirs.map((dir) => resolve(dir))));\n uniqueDirs.sort((a, b) => a.length - b.length);\n\n return uniqueDirs.reduce((acc: string[], dir) => {\n const isCoveredByParent = acc.some((parent) => {\n const relativePath = relative(parent, dir);\n const isNested =\n relativePath !== '' &&\n !relativePath.startsWith('..') &&\n !isAbsolute(relativePath);\n\n return isNested && !isDirectoryExcluded(relativePath, excludePatterns);\n });\n if (!isCoveredByParent) acc.push(dir);\n\n return acc;\n }, []);\n};\n\n/**\n * Default exclude patterns derived from TRAVERSE_PATTERN.\n * Extracted once so the function body can reference them without re-computing.\n */\nconst DEFAULT_EXCLUDE_PATTERNS: string[] = TRAVERSE_PATTERN.filter(\n (p): p is string => typeof p === 'string' && p.startsWith('!')\n).map((p) => p.slice(1));\n\n/**\n * Builds a deduplicated list of absolute file paths matching the given patterns.\n *\n * Handles multiple root directories (deduplicates overlapping roots), exclude\n * patterns, negation patterns embedded in `traversePattern`, and optional\n * dot-file inclusion.\n *\n * `codeDir` entries are more precise than the exclude patterns: a `codeDir`\n * inside an excluded directory (e.g. a design-system `dist` or a package in\n * `node_modules`) is scanned as its own root, so the exclusion only applies\n * below it.\n *\n * @example\n * // Single root with excludes\n * const files = buildComponentFilesList(config);\n *\n * @example\n * // Design-system build output is still scanned\n * // intlayer.config.ts: { content: { codeDir: ['node_modules/my-ds/dist'] } }\n * const files = buildComponentFilesList(config);\n */\nexport const buildComponentFilesList = (\n config: IntlayerConfig,\n excludePattern?: string[]\n): string[] => {\n const traversePattern = config.build.traversePattern;\n const compilerTransformPattern = config.compiler.transformPattern;\n const contentDeclarationPattern = config.content.fileExtensions.map(\n (ext) => `/**/*${ext}`\n );\n\n const patterns = [\n ...traversePattern,\n ...normalizeToArray(compilerTransformPattern),\n ]\n .filter((pattern) => typeof pattern === 'string')\n .filter((pattern) => !pattern.startsWith('!'))\n .map(normalizePath);\n\n // User-supplied negations from traversePattern\n const userExcludes = traversePattern\n .filter(\n (pattern): pattern is string =>\n typeof pattern === 'string' && pattern.startsWith('!')\n )\n .map((pattern) => pattern.slice(1));\n\n // Full exclude list: defaults (from TRAVERSE_PATTERN) + user overrides + caller extras + content files.\n // DEFAULT_EXCLUDE_PATTERNS acts as a safety floor — if the user provides a\n // partial traversePattern that omits some defaults, they are still applied.\n const baseExcludePatterns = Array.from(\n new Set([\n ...DEFAULT_EXCLUDE_PATTERNS,\n ...userExcludes,\n ...(excludePattern ?? []),\n ...contentDeclarationPattern,\n ])\n )\n .filter((pattern): pattern is string => typeof pattern === 'string')\n .map(normalizePath);\n\n const roots = getDistinctRootDirs(\n [config.system.baseDir, ...(config.content.codeDir ?? [])],\n baseExcludePatterns\n );\n\n return Array.from(\n new Set(\n roots.flatMap((root) =>\n fg.sync(patterns, {\n cwd: root,\n ignore: baseExcludePatterns,\n absolute: true,\n dot: true, // needed for .intlayer and similar\n })\n )\n )\n );\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAM,oBAAuB,UAC3B,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;;;;;;;;AASvC,MAAM,uBACJ,MACA,oBACa;CACb,MAAM,aAAa,MAAM,KAAK,IAAI,IAAI,KAAK,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,CAAC;CACtE,WAAW,MAAM,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM;CAE7C,OAAO,WAAW,QAAQ,KAAe,QAAQ;EAU/C,IAAI,CATsB,IAAI,MAAM,WAAW;GAC7C,MAAM,eAAe,SAAS,QAAQ,GAAG;GAMzC,OAJE,iBAAiB,MACjB,CAAC,aAAa,WAAW,IAAI,KAC7B,CAAC,WAAW,YAAY,KAEP,CAAC,oBAAoB,cAAc,eAAe;EACvE,CACqB,GAAG,IAAI,KAAK,GAAG;EAEpC,OAA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(key === void 0) continue;
|
|
24
|
-
const isNextIndex = typeof
|
|
24
|
+
const isNextIndex = typeof path[i + 1] === "number";
|
|
25
25
|
if (typeof key === "number") {
|
|
26
26
|
if (!Array.isArray(current)) throw new Error(`Expected array at path segment ${i}`);
|
|
27
27
|
if (current[key] === void 0) current[key] = isNextIndex ? [] : {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunkJSON.mjs","names":[],"sources":["../../../src/utils/chunkJSON.ts"],"sourcesContent":["/**\n * Split & reassemble JSON by character budget.\n * - Measures serialized size using JSON.stringify(..).length (characters).\n * - Ensures each chunk is itself valid JSON.\n * - Very large strings are split into safe pieces using getChunk and re-concatenated on assemble.\n * - Protects against circular structures (JSON can't serialize those anyway).\n */\n\nimport { getChunk } from './getChunk';\n\ntype JSONPrimitive = string | number | boolean | null;\ntype JSONValue = JSONPrimitive | JSONObject | JSONArray;\n\nexport type JSONObject = {\n [k: string]: JSONValue;\n};\n\ntype JSONArray = JSONValue[];\n\ntype Path = Array<string | number>;\n\ntype SetPatch = { op: 'set'; path: Path; value: JSONValue };\ntype StrAppendPatch = {\n op: 'str-append';\n path: Path;\n value: string; // part of a longer string\n index: number;\n total: number;\n};\ntype Patch = SetPatch | StrAppendPatch;\n\ntype RootType = 'object' | 'array';\n\nexport type JsonChunk = {\n schemaVersion: 1;\n index: number;\n total: number;\n rootType: RootType;\n checksum: string; // hash of the full original JSON string\n entries: Patch[];\n};\n\nconst isObject = (val: unknown): val is Record<string, unknown> => {\n return typeof val === 'object' && val !== null && !Array.isArray(val);\n};\n\nconst computeDjb2 = (str: string): string => {\n // Simple 32-bit hash; deterministic & fast\n let hash = 5381;\n\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n\n // convert to unsigned hex\n return (hash >>> 0).toString(16).padStart(8, '0');\n};\n\nconst setAtPath = (root: any, path: Path, value: JSONValue) => {\n let current = root;\n\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (key === undefined) continue;\n\n const isNextIndex = typeof nextKey === 'number';\n\n if (typeof key === 'number') {\n if (!Array.isArray(current)) {\n throw new Error(`Expected array at path segment ${i}`);\n }\n\n if (current[key] === undefined) {\n current[key] = isNextIndex ? [] : {};\n }\n\n current = current[key];\n } else {\n if (!isObject(current)) {\n throw new Error(`Expected object at path segment ${i}`);\n }\n\n if (!(key in current)) {\n (current as Record<string, any>)[key] = isNextIndex ? [] : {};\n }\n\n current = (current as Record<string, any>)[key];\n }\n }\n\n const last = path[path.length - 1];\n\n if (last === undefined) return;\n\n if (typeof last === 'number') {\n if (!Array.isArray(current)) {\n throw new Error(`Expected array at final segment`);\n }\n\n current[last] = value as any;\n } else {\n if (!isObject(current)) {\n throw new Error(`Expected object at final segment`);\n }\n\n (current as Record<string, any>)[last] = value as any;\n }\n};\n\nconst pathKey = (path: Path): string => {\n // stable key for grouping string parts\n return JSON.stringify(path);\n};\n\n/**\n * Split a string into parts using getChunk with a charLength budget per part.\n */\nconst splitStringByBudget = (\n str: string,\n maxCharsPerPart: number\n): string[] => {\n if (maxCharsPerPart <= 0) {\n throw new Error('maxChars must be > 0');\n }\n\n const output: string[] = [];\n let offset = 0;\n\n while (offset < str.length) {\n const part = getChunk(str, {\n charStart: offset,\n charLength: maxCharsPerPart,\n });\n\n if (!part) break;\n\n output.push(part);\n offset += part.length;\n }\n\n return output;\n};\n\n/**\n * Flatten JSON into patches (leaf writes). Strings too large to fit in a single\n * chunk are yielded as multiple str-append patches.\n */\nconst flattenToPatches = (\n value: JSONValue,\n maxCharsPerChunk: number,\n path: Path = [],\n seen = new WeakSet<object>()\n): Patch[] => {\n // Conservative per-entry cap so a single entry fits into an empty chunk with envelope overhead.\n // (Envelope ~ a few hundred chars; we keep a comfortable margin.)\n const maxStringPiece = Math.max(\n 1,\n Math.floor((maxCharsPerChunk - 400) * 0.8)\n );\n\n const patches: Patch[] = [];\n\n const walk = (currentValue: JSONValue, currentPath: Path) => {\n if (typeof currentValue === 'string') {\n // If the serialized patch wouldn't fit, split the string into multiple parts\n // and encode as a split-node sentinel with numbered keys.\n const testPatch: SetPatch = {\n op: 'set',\n path: currentPath,\n value: currentValue,\n };\n const testLen = JSON.stringify(testPatch).length + 150; // margin\n\n if (testLen <= maxCharsPerChunk) {\n patches.push(testPatch);\n return;\n }\n\n // Use getChunk-based splitting to produce stable parts\n const parts = splitStringByBudget(currentValue, maxStringPiece);\n\n // Emit split-node metadata and parts as individual leaf writes\n patches.push({\n op: 'set',\n path: [...currentPath, '__splittedType'],\n value: 'string',\n });\n patches.push({\n op: 'set',\n path: [...currentPath, '__total'],\n value: parts.length,\n });\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n\n if (part !== undefined) {\n patches.push({\n op: 'set',\n path: [...currentPath, String(i + 1)],\n value: part,\n });\n }\n }\n\n return;\n }\n\n if (currentValue === null || typeof currentValue !== 'object') {\n patches.push({ op: 'set', path: currentPath, value: currentValue });\n return;\n }\n\n if (seen.has(currentValue as object)) {\n throw new Error('Cannot serialize circular structures to JSON.');\n }\n\n seen.add(currentValue as object);\n\n if (Array.isArray(currentValue)) {\n for (let i = 0; i < currentValue.length; i++) {\n const item = currentValue[i];\n if (item !== undefined) {\n walk(item as JSONValue, [...currentPath, i]);\n }\n }\n } else {\n for (const key of Object.keys(currentValue)) {\n const childVal = (currentValue as JSONObject)[key];\n\n if (childVal !== undefined) {\n walk(childVal, [...currentPath, key]);\n }\n }\n }\n\n seen.delete(currentValue as object);\n };\n\n walk(value, path);\n return patches;\n};\n\n/**\n * Split JSON into chunks constrained by character count of serialized chunk.\n */\nexport const chunkJSON = (\n value: JSONObject | JSONArray,\n maxChars: number\n): JsonChunk[] => {\n if (!isObject(value) && !Array.isArray(value)) {\n throw new Error('Root must be an object or array.');\n }\n\n if (maxChars < 500) {\n // You can lower this if you truly need; recommended to keep some envelope headroom.\n throw new Error('maxChars is too small. Use at least 500 characters.');\n }\n\n const rootType: RootType = Array.isArray(value) ? 'array' : 'object';\n let sourceString: string;\n\n try {\n sourceString = JSON.stringify(value);\n } catch {\n // Provide a deterministic error message for circular refs\n throw new Error('Cannot serialize circular structures to JSON.');\n }\n\n const checksum = computeDjb2(sourceString);\n const allPatches = flattenToPatches(value as JSONValue, maxChars);\n\n const chunks: JsonChunk[] = [];\n let currentChunk: JsonChunk = {\n schemaVersion: 1,\n index: 0, // provisional\n total: 0, // provisional\n rootType,\n checksum,\n entries: [],\n };\n\n const emptyEnvelopeSize = JSON.stringify({\n ...currentChunk,\n entries: [],\n }).length;\n\n const tryFlush = () => {\n if (currentChunk.entries.length > 0) {\n chunks.push(currentChunk);\n currentChunk = {\n schemaVersion: 1,\n index: 0,\n total: 0,\n rootType,\n checksum,\n entries: [],\n };\n }\n };\n\n for (const patch of allPatches) {\n // Would adding this patch exceed maxChars?\n const withPatchSize =\n emptyEnvelopeSize +\n JSON.stringify(currentChunk.entries).length + // current entries array\n (currentChunk.entries.length ? 1 : 0) + // possible comma\n JSON.stringify(patch).length;\n\n if (withPatchSize <= maxChars) {\n currentChunk.entries.push(patch);\n } else {\n // Start a new chunk if current has items\n if (currentChunk.entries.length > 0) {\n tryFlush();\n }\n\n // Ensure single patch fits into an empty chunk\n const singleSize = emptyEnvelopeSize + JSON.stringify([patch]).length;\n\n if (singleSize > maxChars) {\n // This should only happen for massive strings, which we pre-split;\n // if it happens for a non-string, we cannot split further.\n throw new Error(\n 'A single entry exceeds maxChars and cannot be split. Reduce entry size or increase maxChars.'\n );\n }\n\n currentChunk.entries.push(patch);\n }\n }\n\n tryFlush();\n\n // Ensure at least one chunk exists (even for empty root)\n if (chunks.length === 0) {\n chunks.push({\n schemaVersion: 1,\n index: 0,\n total: 0, // provisional\n rootType,\n checksum,\n entries: [],\n });\n }\n\n // Finalize indices & totals\n const totalChunks = chunks.length;\n\n chunks.forEach((chunk, index) => {\n chunk.index = index;\n chunk.total = totalChunks;\n });\n\n return chunks;\n};\n\n/**\n * Reassemble JSON from chunks.\n * - Validates checksums and indices.\n * - Applies 'set' patches and merges string pieces from 'str-append'.\n */\n/**\n * Reconstruct content from a single chunk without validation.\n * Useful for processing individual chunks in a pipeline where you don't have all chunks yet.\n * Note: This will only reconstruct the partial content contained in this chunk.\n */\nexport const reconstructFromSingleChunk = (\n chunk: JsonChunk\n): JSONObject | JSONArray => {\n const root: any = chunk.rootType === 'array' ? [] : {};\n\n // Apply all 'set' patches from this chunk\n for (const entry of chunk.entries) {\n if (entry.op === 'set') {\n setAtPath(root, entry.path, entry.value);\n }\n }\n\n // Reconcile split-node sentinels for strings/arrays\n // When reconstructing from a single chunk, we may have incomplete split nodes\n const reconcileSplitNodes = (node: any): any => {\n if (node === null || typeof node !== 'object') return node;\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n node[i] = reconcileSplitNodes(node[i]);\n }\n return node;\n }\n\n // string split-node\n if ((node as any)['__splittedType'] === 'string') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total <= 0) {\n // Invalid split node, return as-is\n return node;\n }\n\n const parts: string[] = [];\n let hasAllParts = true;\n\n for (let i = 1; i <= total; i++) {\n const piece = (node as any)[String(i)];\n\n if (typeof piece !== 'string') {\n hasAllParts = false;\n break;\n }\n\n parts.push(piece);\n }\n\n // Only reconstruct if we have all parts, otherwise return the node as-is\n if (hasAllParts) {\n return parts.join('');\n }\n\n return node;\n }\n\n // array split-node (optional support)\n if ((node as any)['__splittedType'] === 'array') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total < 0) {\n // Invalid split node, return as-is\n return node;\n }\n\n const output: any[] = [];\n let hasAllParts = true;\n\n for (let i = 1; i <= total; i++) {\n const slice = (node as any)[String(i)];\n\n if (!Array.isArray(slice)) {\n hasAllParts = false;\n break;\n }\n\n for (let j = 0; j < slice.length; j++) {\n output.push(reconcileSplitNodes(slice[j]));\n }\n }\n\n // Only reconstruct if we have all parts\n if (hasAllParts) {\n return output;\n }\n\n return node;\n }\n\n // walk normal object\n for (const key of Object.keys(node)) {\n node[key] = reconcileSplitNodes(node[key]);\n }\n\n return node;\n };\n\n return reconcileSplitNodes(root);\n};\n\nexport const assembleJSON = (chunks: JsonChunk[]): JSONObject | JSONArray => {\n if (!chunks || chunks.length === 0) {\n throw new Error('No chunks provided.');\n }\n\n // Basic validation & sort\n const sorted = [...chunks].sort((a, b) => a.index - b.index);\n const firstChunk = sorted[0];\n\n if (!firstChunk) {\n throw new Error('No chunks provided.');\n }\n\n const { checksum, rootType } = firstChunk;\n const schemaVersion = 1;\n\n for (let i = 0; i < sorted.length; i++) {\n const chunk = sorted[i];\n\n if (!chunk) continue;\n\n if (chunk.schemaVersion !== schemaVersion) {\n console.error('Unsupported schemaVersion.', {\n cause: chunk,\n schemaVersion,\n });\n throw new Error('Unsupported schemaVersion.');\n }\n\n if (chunk.rootType !== rootType) {\n console.error('Chunks rootType mismatch.', {\n cause: chunk,\n rootType,\n });\n throw new Error('Chunks rootType mismatch.');\n }\n\n if (chunk.checksum !== checksum) {\n console.error('Chunks checksum mismatch (different source objects?).', {\n cause: chunk,\n checksum,\n });\n throw new Error('Chunks checksum mismatch (different source objects?).');\n }\n\n if (chunk.index !== i) {\n console.error('Chunk indices are not contiguous or sorted.', {\n cause: chunk,\n index: chunk.index,\n i,\n });\n throw new Error('Chunk indices are not contiguous or sorted.');\n }\n\n // Defer total check until after reconstruction to prefer more specific errors\n }\n\n const root: any = rootType === 'array' ? [] : {};\n\n // Collect string parts by path\n const stringParts = new Map<\n string,\n { path: Path; total: number; received: StrAppendPatch[] }\n >();\n\n const applySet = (patch: SetPatch) =>\n setAtPath(root, patch.path, patch.value);\n\n for (const chunk of sorted) {\n for (const entry of chunk.entries) {\n if (entry.op === 'set') {\n applySet(entry);\n } else {\n const key = pathKey(entry.path);\n const record = stringParts.get(key) ?? {\n path: entry.path,\n total: entry.total,\n received: [],\n };\n\n if (record.total !== entry.total) {\n throw new Error('Inconsistent string part totals for a path.');\n }\n\n record.received.push(entry);\n stringParts.set(key, record);\n }\n }\n }\n\n // Stitch strings\n for (const { path, total, received } of stringParts.values()) {\n if (received.length !== total) {\n throw new Error('Missing string parts for a path; incomplete chunk set.');\n }\n\n received.sort((a, b) => a.index - b.index);\n const fullString = received.map((part) => part.value).join('');\n setAtPath(root, path, fullString);\n }\n\n // Reconcile split-node sentinels for strings/arrays after all patches applied\n const reconcileSplitNodes = (node: any): any => {\n if (node === null || typeof node !== 'object') return node;\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n node[i] = reconcileSplitNodes(node[i]);\n }\n return node;\n }\n\n // string split-node\n if ((node as any)['__splittedType'] === 'string') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total <= 0) {\n throw new Error('Invalid split-node total for a path.');\n }\n\n const parts: string[] = [];\n\n for (let i = 1; i <= total; i++) {\n const piece = (node as any)[String(i)];\n\n if (typeof piece !== 'string') {\n throw new Error(\n 'Missing string parts for a path; incomplete chunk set.'\n );\n }\n\n parts.push(piece);\n }\n\n return parts.join('');\n }\n\n // array split-node (optional support)\n if ((node as any)['__splittedType'] === 'array') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total < 0) {\n throw new Error('Invalid split-node total for a path.');\n }\n\n const output: any[] = [];\n\n for (let i = 1; i <= total; i++) {\n const slice = (node as any)[String(i)];\n\n if (!Array.isArray(slice)) {\n throw new Error(\n 'Missing string parts for a path; incomplete chunk set.'\n );\n }\n\n for (let j = 0; j < slice.length; j++) {\n output.push(reconcileSplitNodes(slice[j]));\n }\n }\n\n return output;\n }\n\n // walk normal object\n for (const key of Object.keys(node)) {\n node[key] = reconcileSplitNodes(node[key]);\n }\n\n return node;\n };\n\n const reconciled = reconcileSplitNodes(root);\n\n // Now validate totals match provided count\n for (let i = 0; i < sorted.length; i++) {\n const chunk = sorted[i];\n\n if (!chunk) continue;\n\n if (chunk.total !== sorted.length) {\n throw new Error(\n `Chunk total does not match provided count. Expected ${sorted.length}, but chunk ${i} has total=${chunk.total}`\n );\n }\n }\n\n return reconciled;\n};\n\n/* -------------------------------------------\n * Example usage\n * -------------------------------------------\nconst big: JSONObject = {\n title: \"Document\",\n content: \"…a very very long text…\",\n items: Array.from({ length: 2000 }, (_, i) => ({ id: i, label: `Item ${i}` }))\n};\n\n// Split to ~16k-char chunks\nconst chunks = chunkJSON(big, 16_000);\n\n// Send each `chunks[i]` as JSON to your backend.\n// Later, reassemble:\nconst restored = assembleJSON(chunks);\nconsole.log(JSON.stringify(restored) === JSON.stringify(big)); // true\n*/\n"],"mappings":";;;;;;;;;;AA0CA,MAAM,YAAY,QAAiD;CACjE,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,GAAG;AACtE;AAEA,MAAM,eAAe,QAAwB;CAE3C,IAAI,OAAO;CAEX,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAC9B,QAAS,QAAQ,KAAK,OAAQ,IAAI,WAAW,CAAC;CAIhD,QAAQ,SAAS,EAAC,CAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAClD;AAEA,MAAM,aAAa,MAAW,MAAY,UAAqB;CAC7D,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS,GAAG,KAAK;EACxC,MAAM,MAAM,KAAK;EACjB,IAAI,QAAQ,QAAW;EAEvB,MAAM,cAAc,OAAO,YAAY;EAEvC,IAAI,OAAO,QAAQ,UAAU;GAC3B,IAAI,CAAC,MAAM,QAAQ,OAAO,GACxB,MAAM,IAAI,MAAM,kCAAkC,GAAG;GAGvD,IAAI,QAAQ,SAAS,QACnB,QAAQ,OAAO,cAAc,CAAC,IAAI,CAAC;GAGrC,UAAU,QAAQ;EACpB,OAAO;GACL,IAAI,CAAC,SAAS,OAAO,GACnB,MAAM,IAAI,MAAM,mCAAmC,GAAG;GAGxD,IAAI,EAAE,OAAO,UACX,AAAC,QAAgC,OAAO,cAAc,CAAC,IAAI,CAAC;GAG9D,UAAW,QAAgC;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AAsC;GAGxD,MAAM,SAAgB,CAAC;GAEvB,KAAK,IAAI,IAAI,GAAG,KAAK,OAAO,KAAK;IAC/B,MAAM,QAAS,KAAa,OAAO,CAAC;IAEpC,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,MAAM,IAAI,MACR,wDACF;IAGF,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,OAAO,KAAK,oBAAoB,MAAM,EAAE,CAAC;GAE7C;GAEA,OAAO;EACT;EAGA,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAChC,KAAK,OAAO,oBAAoB,KAAK,IAAI;EAG3C,OAAO;CACT;CAEA,MAAM,aAAa,oBAAoB,IAAI;CAG3C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACtC,MAAM,QAAQ,OAAO;EAErB,IAAI,CAAC,OAAO;EAEZ,IAAI,MAAM,UAAU,OAAO,QACzB,MAAM,IAAI,MACR,uDAAuD,OAAO,OAAO,cAAc,EAAE,aAAa,MAAM,OAC1G;CAEJ;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"chunkJSON.mjs","names":[],"sources":["../../../src/utils/chunkJSON.ts"],"sourcesContent":["/**\n * Split & reassemble JSON by character budget.\n * - Measures serialized size using JSON.stringify(..).length (characters).\n * - Ensures each chunk is itself valid JSON.\n * - Very large strings are split into safe pieces using getChunk and re-concatenated on assemble.\n * - Protects against circular structures (JSON can't serialize those anyway).\n */\n\nimport { getChunk } from './getChunk';\n\ntype JSONPrimitive = string | number | boolean | null;\ntype JSONValue = JSONPrimitive | JSONObject | JSONArray;\n\nexport type JSONObject = {\n [k: string]: JSONValue;\n};\n\ntype JSONArray = JSONValue[];\n\ntype Path = Array<string | number>;\n\ntype SetPatch = { op: 'set'; path: Path; value: JSONValue };\ntype StrAppendPatch = {\n op: 'str-append';\n path: Path;\n value: string; // part of a longer string\n index: number;\n total: number;\n};\ntype Patch = SetPatch | StrAppendPatch;\n\ntype RootType = 'object' | 'array';\n\nexport type JsonChunk = {\n schemaVersion: 1;\n index: number;\n total: number;\n rootType: RootType;\n checksum: string; // hash of the full original JSON string\n entries: Patch[];\n};\n\nconst isObject = (val: unknown): val is Record<string, unknown> => {\n return typeof val === 'object' && val !== null && !Array.isArray(val);\n};\n\nconst computeDjb2 = (str: string): string => {\n // Simple 32-bit hash; deterministic & fast\n let hash = 5381;\n\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n\n // convert to unsigned hex\n return (hash >>> 0).toString(16).padStart(8, '0');\n};\n\nconst setAtPath = (root: any, path: Path, value: JSONValue) => {\n let current = root;\n\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (key === undefined) continue;\n\n const nextKey = path[i + 1];\n const isNextIndex = typeof nextKey === 'number';\n\n if (typeof key === 'number') {\n if (!Array.isArray(current)) {\n throw new Error(`Expected array at path segment ${i}`);\n }\n\n if (current[key] === undefined) {\n current[key] = isNextIndex ? [] : {};\n }\n\n current = current[key];\n } else {\n if (!isObject(current)) {\n throw new Error(`Expected object at path segment ${i}`);\n }\n\n if (!(key in current)) {\n (current as Record<string, any>)[key] = isNextIndex ? [] : {};\n }\n\n current = (current as Record<string, any>)[key];\n }\n }\n\n const last = path[path.length - 1];\n\n if (last === undefined) return;\n\n if (typeof last === 'number') {\n if (!Array.isArray(current)) {\n throw new Error(`Expected array at final segment`);\n }\n\n current[last] = value as any;\n } else {\n if (!isObject(current)) {\n throw new Error(`Expected object at final segment`);\n }\n\n (current as Record<string, any>)[last] = value as any;\n }\n};\n\nconst pathKey = (path: Path): string => {\n // stable key for grouping string parts\n return JSON.stringify(path);\n};\n\n/**\n * Split a string into parts using getChunk with a charLength budget per part.\n */\nconst splitStringByBudget = (\n str: string,\n maxCharsPerPart: number\n): string[] => {\n if (maxCharsPerPart <= 0) {\n throw new Error('maxChars must be > 0');\n }\n\n const output: string[] = [];\n let offset = 0;\n\n while (offset < str.length) {\n const part = getChunk(str, {\n charStart: offset,\n charLength: maxCharsPerPart,\n });\n\n if (!part) break;\n\n output.push(part);\n offset += part.length;\n }\n\n return output;\n};\n\n/**\n * Flatten JSON into patches (leaf writes). Strings too large to fit in a single\n * chunk are yielded as multiple str-append patches.\n */\nconst flattenToPatches = (\n value: JSONValue,\n maxCharsPerChunk: number,\n path: Path = [],\n seen = new WeakSet<object>()\n): Patch[] => {\n // Conservative per-entry cap so a single entry fits into an empty chunk with envelope overhead.\n // (Envelope ~ a few hundred chars; we keep a comfortable margin.)\n const maxStringPiece = Math.max(\n 1,\n Math.floor((maxCharsPerChunk - 400) * 0.8)\n );\n\n const patches: Patch[] = [];\n\n const walk = (currentValue: JSONValue, currentPath: Path) => {\n if (typeof currentValue === 'string') {\n // If the serialized patch wouldn't fit, split the string into multiple parts\n // and encode as a split-node sentinel with numbered keys.\n const testPatch: SetPatch = {\n op: 'set',\n path: currentPath,\n value: currentValue,\n };\n const testLen = JSON.stringify(testPatch).length + 150; // margin\n\n if (testLen <= maxCharsPerChunk) {\n patches.push(testPatch);\n return;\n }\n\n // Use getChunk-based splitting to produce stable parts\n const parts = splitStringByBudget(currentValue, maxStringPiece);\n\n // Emit split-node metadata and parts as individual leaf writes\n patches.push({\n op: 'set',\n path: [...currentPath, '__splittedType'],\n value: 'string',\n });\n patches.push({\n op: 'set',\n path: [...currentPath, '__total'],\n value: parts.length,\n });\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n\n if (part !== undefined) {\n patches.push({\n op: 'set',\n path: [...currentPath, String(i + 1)],\n value: part,\n });\n }\n }\n\n return;\n }\n\n if (currentValue === null || typeof currentValue !== 'object') {\n patches.push({ op: 'set', path: currentPath, value: currentValue });\n return;\n }\n\n if (seen.has(currentValue as object)) {\n throw new Error('Cannot serialize circular structures to JSON.');\n }\n\n seen.add(currentValue as object);\n\n if (Array.isArray(currentValue)) {\n for (let i = 0; i < currentValue.length; i++) {\n const item = currentValue[i];\n if (item !== undefined) {\n walk(item as JSONValue, [...currentPath, i]);\n }\n }\n } else {\n for (const key of Object.keys(currentValue)) {\n const childVal = (currentValue as JSONObject)[key];\n\n if (childVal !== undefined) {\n walk(childVal, [...currentPath, key]);\n }\n }\n }\n\n seen.delete(currentValue as object);\n };\n\n walk(value, path);\n return patches;\n};\n\n/**\n * Split JSON into chunks constrained by character count of serialized chunk.\n */\nexport const chunkJSON = (\n value: JSONObject | JSONArray,\n maxChars: number\n): JsonChunk[] => {\n if (!isObject(value) && !Array.isArray(value)) {\n throw new Error('Root must be an object or array.');\n }\n\n if (maxChars < 500) {\n // You can lower this if you truly need; recommended to keep some envelope headroom.\n throw new Error('maxChars is too small. Use at least 500 characters.');\n }\n\n const rootType: RootType = Array.isArray(value) ? 'array' : 'object';\n let sourceString: string;\n\n try {\n sourceString = JSON.stringify(value);\n } catch {\n // Provide a deterministic error message for circular refs\n throw new Error('Cannot serialize circular structures to JSON.');\n }\n\n const checksum = computeDjb2(sourceString);\n const allPatches = flattenToPatches(value as JSONValue, maxChars);\n\n const chunks: JsonChunk[] = [];\n let currentChunk: JsonChunk = {\n schemaVersion: 1,\n index: 0, // provisional\n total: 0, // provisional\n rootType,\n checksum,\n entries: [],\n };\n\n const emptyEnvelopeSize = JSON.stringify({\n ...currentChunk,\n entries: [],\n }).length;\n\n const tryFlush = () => {\n if (currentChunk.entries.length > 0) {\n chunks.push(currentChunk);\n currentChunk = {\n schemaVersion: 1,\n index: 0,\n total: 0,\n rootType,\n checksum,\n entries: [],\n };\n }\n };\n\n for (const patch of allPatches) {\n // Would adding this patch exceed maxChars?\n const withPatchSize =\n emptyEnvelopeSize +\n JSON.stringify(currentChunk.entries).length + // current entries array\n (currentChunk.entries.length ? 1 : 0) + // possible comma\n JSON.stringify(patch).length;\n\n if (withPatchSize <= maxChars) {\n currentChunk.entries.push(patch);\n } else {\n // Start a new chunk if current has items\n if (currentChunk.entries.length > 0) {\n tryFlush();\n }\n\n // Ensure single patch fits into an empty chunk\n const singleSize = emptyEnvelopeSize + JSON.stringify([patch]).length;\n\n if (singleSize > maxChars) {\n // This should only happen for massive strings, which we pre-split;\n // if it happens for a non-string, we cannot split further.\n throw new Error(\n 'A single entry exceeds maxChars and cannot be split. Reduce entry size or increase maxChars.'\n );\n }\n\n currentChunk.entries.push(patch);\n }\n }\n\n tryFlush();\n\n // Ensure at least one chunk exists (even for empty root)\n if (chunks.length === 0) {\n chunks.push({\n schemaVersion: 1,\n index: 0,\n total: 0, // provisional\n rootType,\n checksum,\n entries: [],\n });\n }\n\n // Finalize indices & totals\n const totalChunks = chunks.length;\n\n chunks.forEach((chunk, index) => {\n chunk.index = index;\n chunk.total = totalChunks;\n });\n\n return chunks;\n};\n\n/**\n * Reassemble JSON from chunks.\n * - Validates checksums and indices.\n * - Applies 'set' patches and merges string pieces from 'str-append'.\n */\n/**\n * Reconstruct content from a single chunk without validation.\n * Useful for processing individual chunks in a pipeline where you don't have all chunks yet.\n * Note: This will only reconstruct the partial content contained in this chunk.\n */\nexport const reconstructFromSingleChunk = (\n chunk: JsonChunk\n): JSONObject | JSONArray => {\n const root: any = chunk.rootType === 'array' ? [] : {};\n\n // Apply all 'set' patches from this chunk\n for (const entry of chunk.entries) {\n if (entry.op === 'set') {\n setAtPath(root, entry.path, entry.value);\n }\n }\n\n // Reconcile split-node sentinels for strings/arrays\n // When reconstructing from a single chunk, we may have incomplete split nodes\n const reconcileSplitNodes = (node: any): any => {\n if (node === null || typeof node !== 'object') return node;\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n node[i] = reconcileSplitNodes(node[i]);\n }\n return node;\n }\n\n // string split-node\n if ((node as any)['__splittedType'] === 'string') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total <= 0) {\n // Invalid split node, return as-is\n return node;\n }\n\n const parts: string[] = [];\n let hasAllParts = true;\n\n for (let i = 1; i <= total; i++) {\n const piece = (node as any)[String(i)];\n\n if (typeof piece !== 'string') {\n hasAllParts = false;\n break;\n }\n\n parts.push(piece);\n }\n\n // Only reconstruct if we have all parts, otherwise return the node as-is\n if (hasAllParts) {\n return parts.join('');\n }\n\n return node;\n }\n\n // array split-node (optional support)\n if ((node as any)['__splittedType'] === 'array') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total < 0) {\n // Invalid split node, return as-is\n return node;\n }\n\n const output: any[] = [];\n let hasAllParts = true;\n\n for (let i = 1; i <= total; i++) {\n const slice = (node as any)[String(i)];\n\n if (!Array.isArray(slice)) {\n hasAllParts = false;\n break;\n }\n\n for (let j = 0; j < slice.length; j++) {\n output.push(reconcileSplitNodes(slice[j]));\n }\n }\n\n // Only reconstruct if we have all parts\n if (hasAllParts) {\n return output;\n }\n\n return node;\n }\n\n // walk normal object\n for (const key of Object.keys(node)) {\n node[key] = reconcileSplitNodes(node[key]);\n }\n\n return node;\n };\n\n return reconcileSplitNodes(root);\n};\n\nexport const assembleJSON = (chunks: JsonChunk[]): JSONObject | JSONArray => {\n if (!chunks || chunks.length === 0) {\n throw new Error('No chunks provided.');\n }\n\n // Basic validation & sort\n const sorted = [...chunks].sort((a, b) => a.index - b.index);\n const firstChunk = sorted[0];\n\n if (!firstChunk) {\n throw new Error('No chunks provided.');\n }\n\n const { checksum, rootType } = firstChunk;\n const schemaVersion = 1;\n\n for (let i = 0; i < sorted.length; i++) {\n const chunk = sorted[i];\n\n if (!chunk) continue;\n\n if (chunk.schemaVersion !== schemaVersion) {\n console.error('Unsupported schemaVersion.', {\n cause: chunk,\n schemaVersion,\n });\n throw new Error('Unsupported schemaVersion.');\n }\n\n if (chunk.rootType !== rootType) {\n console.error('Chunks rootType mismatch.', {\n cause: chunk,\n rootType,\n });\n throw new Error('Chunks rootType mismatch.');\n }\n\n if (chunk.checksum !== checksum) {\n console.error('Chunks checksum mismatch (different source objects?).', {\n cause: chunk,\n checksum,\n });\n throw new Error('Chunks checksum mismatch (different source objects?).');\n }\n\n if (chunk.index !== i) {\n console.error('Chunk indices are not contiguous or sorted.', {\n cause: chunk,\n index: chunk.index,\n i,\n });\n throw new Error('Chunk indices are not contiguous or sorted.');\n }\n\n // Defer total check until after reconstruction to prefer more specific errors\n }\n\n const root: any = rootType === 'array' ? [] : {};\n\n // Collect string parts by path\n const stringParts = new Map<\n string,\n { path: Path; total: number; received: StrAppendPatch[] }\n >();\n\n const applySet = (patch: SetPatch) =>\n setAtPath(root, patch.path, patch.value);\n\n for (const chunk of sorted) {\n for (const entry of chunk.entries) {\n if (entry.op === 'set') {\n applySet(entry);\n } else {\n const key = pathKey(entry.path);\n const record = stringParts.get(key) ?? {\n path: entry.path,\n total: entry.total,\n received: [],\n };\n\n if (record.total !== entry.total) {\n throw new Error('Inconsistent string part totals for a path.');\n }\n\n record.received.push(entry);\n stringParts.set(key, record);\n }\n }\n }\n\n // Stitch strings\n for (const { path, total, received } of stringParts.values()) {\n if (received.length !== total) {\n throw new Error('Missing string parts for a path; incomplete chunk set.');\n }\n\n received.sort((a, b) => a.index - b.index);\n const fullString = received.map((part) => part.value).join('');\n setAtPath(root, path, fullString);\n }\n\n // Reconcile split-node sentinels for strings/arrays after all patches applied\n const reconcileSplitNodes = (node: any): any => {\n if (node === null || typeof node !== 'object') return node;\n\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n node[i] = reconcileSplitNodes(node[i]);\n }\n return node;\n }\n\n // string split-node\n if ((node as any)['__splittedType'] === 'string') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total <= 0) {\n throw new Error('Invalid split-node total for a path.');\n }\n\n const parts: string[] = [];\n\n for (let i = 1; i <= total; i++) {\n const piece = (node as any)[String(i)];\n\n if (typeof piece !== 'string') {\n throw new Error(\n 'Missing string parts for a path; incomplete chunk set.'\n );\n }\n\n parts.push(piece);\n }\n\n return parts.join('');\n }\n\n // array split-node (optional support)\n if ((node as any)['__splittedType'] === 'array') {\n const total = (node as any)['__total'];\n\n if (typeof total !== 'number' || total < 0) {\n throw new Error('Invalid split-node total for a path.');\n }\n\n const output: any[] = [];\n\n for (let i = 1; i <= total; i++) {\n const slice = (node as any)[String(i)];\n\n if (!Array.isArray(slice)) {\n throw new Error(\n 'Missing string parts for a path; incomplete chunk set.'\n );\n }\n\n for (let j = 0; j < slice.length; j++) {\n output.push(reconcileSplitNodes(slice[j]));\n }\n }\n\n return output;\n }\n\n // walk normal object\n for (const key of Object.keys(node)) {\n node[key] = reconcileSplitNodes(node[key]);\n }\n\n return node;\n };\n\n const reconciled = reconcileSplitNodes(root);\n\n // Now validate totals match provided count\n for (let i = 0; i < sorted.length; i++) {\n const chunk = sorted[i];\n\n if (!chunk) continue;\n\n if (chunk.total !== sorted.length) {\n throw new Error(\n `Chunk total does not match provided count. Expected ${sorted.length}, but chunk ${i} has total=${chunk.total}`\n );\n }\n }\n\n return reconciled;\n};\n\n/* -------------------------------------------\n * Example usage\n * -------------------------------------------\nconst big: JSONObject = {\n title: \"Document\",\n content: \"…a very very long text…\",\n items: Array.from({ length: 2000 }, (_, i) => ({ id: i, label: `Item ${i}` }))\n};\n\n// Split to ~16k-char chunks\nconst chunks = chunkJSON(big, 16_000);\n\n// Send each `chunks[i]` as JSON to your backend.\n// Later, reassemble:\nconst restored = assembleJSON(chunks);\nconsole.log(JSON.stringify(restored) === JSON.stringify(big)); // true\n*/\n"],"mappings":";;;;;;;;;;AA0CA,MAAM,YAAY,QAAiD;CACjE,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,GAAG;AACtE;AAEA,MAAM,eAAe,QAAwB;CAE3C,IAAI,OAAO;CAEX,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAC9B,QAAS,QAAQ,KAAK,OAAQ,IAAI,WAAW,CAAC;CAIhD,QAAQ,SAAS,EAAC,CAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAClD;AAEA,MAAM,aAAa,MAAW,MAAY,UAAqB;CAC7D,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS,GAA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DecorateContent.mjs";
|
|
2
|
+
import { isDirectoryExcluded } from "./isDirectoryExcluded.mjs";
|
|
2
3
|
import { buildComponentFilesList } from "./buildComponentFilesList.mjs";
|
|
3
4
|
import { chunkArray } from "./chunkArray.mjs";
|
|
4
5
|
import { splitTextByLines } from "./splitTextByLine.mjs";
|
|
@@ -24,4 +25,4 @@ import { startContentWatcher } from "./startContentWatcher.mjs";
|
|
|
24
25
|
import { verifyIdenticObjectFormat } from "./verifyIdenticObjectFormat.mjs";
|
|
25
26
|
import { withFileLock } from "./withFileLock.mjs";
|
|
26
27
|
|
|
27
|
-
export { CLI_CONTENT_WATCHER_ENV_VAR, Queue, acquireContentWatcherLock, assembleJSON, autoDecorateContent, buildComponentFilesList, chunkArray, chunkJSON, claimCliContentWatcher, excludeObjectFormat, formatLocale, formatPath, getChunk, getCliContentWatcherLabel, getContentExtension, getContentWatcherLockFilePath, getContentWatcherOwner, getExtensionFromFormat, getFormatFromExtension, getGlobalLimiter, getPathHash, getTaskLimiter, mergeChunks, pLimit, parallelize, parallelizeGlobal, parseContentDeclarationFileName, reconstructFromSingleChunk, reduceObjectFormat, reportRedundantContentWatcher, resolveObjectPromises, resolveRelativePath, runOnce, runParallel, sortAlphabetically, splitTextByLines, startContentWatcher, verifyIdenticObjectFormat, withFileLock };
|
|
28
|
+
export { CLI_CONTENT_WATCHER_ENV_VAR, Queue, acquireContentWatcherLock, assembleJSON, autoDecorateContent, buildComponentFilesList, chunkArray, chunkJSON, claimCliContentWatcher, excludeObjectFormat, formatLocale, formatPath, getChunk, getCliContentWatcherLabel, getContentExtension, getContentWatcherLockFilePath, getContentWatcherOwner, getExtensionFromFormat, getFormatFromExtension, getGlobalLimiter, getPathHash, getTaskLimiter, isDirectoryExcluded, mergeChunks, pLimit, parallelize, parallelizeGlobal, parseContentDeclarationFileName, reconstructFromSingleChunk, reduceObjectFormat, reportRedundantContentWatcher, resolveObjectPromises, resolveRelativePath, runOnce, runParallel, sortAlphabetically, splitTextByLines, startContentWatcher, verifyIdenticObjectFormat, withFileLock };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { normalizePath } from "@intlayer/config/utils";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/isDirectoryExcluded.ts
|
|
4
|
+
/**
|
|
5
|
+
* Extracts the literal directory segments of a directory-shaped exclude
|
|
6
|
+
* pattern (`**\/dist/**` → `dist`, `!**\/.next/**` → `.next`).
|
|
7
|
+
* Returns `undefined` for file-shaped or wildcard patterns (`**\/*.config.*`),
|
|
8
|
+
* which can never exclude a whole directory.
|
|
9
|
+
*/
|
|
10
|
+
const getExcludedDirectorySegments = (excludePattern) => {
|
|
11
|
+
const segments = normalizePath(excludePattern).replace(/^!/, "").replace(/^(\*\*\/)+/, "").replace(/(\/\*\*)+\/?$/, "");
|
|
12
|
+
return segments !== "" && !/[*?[\]{}()!]/.test(segments) ? segments : void 0;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Whether a directory path lies inside a directory matched by one of the
|
|
16
|
+
* exclude patterns (e.g. `packages/ds/dist/esm` against `**\/dist/**`).
|
|
17
|
+
*
|
|
18
|
+
* Used to keep explicitly configured directories (`codeDir`, `contentDir`)
|
|
19
|
+
* from being dropped by an exclusion that only matches their ancestors.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* isDirectoryExcluded('ds/dist/esm', ['**\/dist/**']); // true
|
|
23
|
+
* isDirectoryExcluded('src/distance', ['**\/dist/**']); // false
|
|
24
|
+
*/
|
|
25
|
+
const isDirectoryExcluded = (directoryPath, excludePatterns) => {
|
|
26
|
+
const wrappedPath = `/${normalizePath(directoryPath).replace(/^\/+|\/+$/g, "")}/`;
|
|
27
|
+
return excludePatterns.some((excludePattern) => {
|
|
28
|
+
const excludedSegments = getExcludedDirectorySegments(excludePattern);
|
|
29
|
+
return excludedSegments !== void 0 && wrappedPath.includes(`/${excludedSegments}/`);
|
|
30
|
+
});
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
export { isDirectoryExcluded };
|
|
35
|
+
//# sourceMappingURL=isDirectoryExcluded.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isDirectoryExcluded.mjs","names":[],"sources":["../../../src/utils/isDirectoryExcluded.ts"],"sourcesContent":["import { normalizePath } from '@intlayer/config/utils';\n\n/**\n * Extracts the literal directory segments of a directory-shaped exclude\n * pattern (`**\\/dist/**` → `dist`, `!**\\/.next/**` → `.next`).\n * Returns `undefined` for file-shaped or wildcard patterns (`**\\/*.config.*`),\n * which can never exclude a whole directory.\n */\nconst getExcludedDirectorySegments = (\n excludePattern: string\n): string | undefined => {\n const segments = normalizePath(excludePattern)\n .replace(/^!/, '')\n .replace(/^(\\*\\*\\/)+/, '')\n .replace(/(\\/\\*\\*)+\\/?$/, '');\n\n const isLiteral = segments !== '' && !/[*?[\\]{}()!]/.test(segments);\n\n return isLiteral ? segments : undefined;\n};\n\n/**\n * Whether a directory path lies inside a directory matched by one of the\n * exclude patterns (e.g. `packages/ds/dist/esm` against `**\\/dist/**`).\n *\n * Used to keep explicitly configured directories (`codeDir`, `contentDir`)\n * from being dropped by an exclusion that only matches their ancestors.\n *\n * @example\n * isDirectoryExcluded('ds/dist/esm', ['**\\/dist/**']); // true\n * isDirectoryExcluded('src/distance', ['**\\/dist/**']); // false\n */\nexport const isDirectoryExcluded = (\n directoryPath: string,\n excludePatterns: string[]\n): boolean => {\n const wrappedPath = `/${normalizePath(directoryPath).replace(/^\\/+|\\/+$/g, '')}/`;\n\n return excludePatterns.some((excludePattern) => {\n const excludedSegments = getExcludedDirectorySegments(excludePattern);\n\n return (\n excludedSegments !== undefined &&\n wrappedPath.includes(`/${excludedSegments}/`)\n );\n });\n};\n"],"mappings":";;;;;;;;;AAQA,MAAM,gCACJ,mBACuB;CACvB,MAAM,WAAW,cAAc,cAAc,CAAC,CAC3C,QAAQ,MAAM,EAAE,CAAC,CACjB,QAAQ,cAAc,EAAE,CAAC,CACzB,QAAQ,iBAAiB,EAAE;CAI9B,OAFkB,aAAa,MAAM,CAAC,eAAe,KAAK,QAAQ,IAE/C,WAAW;AAChC;;;;;;;;;;;;AAaA,MAAa,uBACX,eACA,oBACY;CACZ,MAAM,cAAc,IAAI,cAAc,aAAa,CAAC,CAAC,QAAQ,cAAc,EAAE,EAAE;CAE/E,OAAO,gBAAgB,MAAM,mBAAmB;EAC9C,MAAM,mBAAmB,6BAA6B,cAAc;EAEpE,OACE,qBAAqB,UACrB,YAAY,SAAS,IAAI,iBAAiB,EAAE;CAEhD,CAAC;AACH"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ps } from "./ps.mjs";
|
|
2
2
|
import { wmic } from "./wmic.mjs";
|
|
3
|
-
import * as os
|
|
3
|
+
import * as os from "node:os";
|
|
4
4
|
|
|
5
5
|
//#region src/utils/runParallel/pidTree.ts
|
|
6
6
|
const platformToMethod = {
|
|
@@ -16,7 +16,7 @@ const methodToFn = {
|
|
|
16
16
|
ps,
|
|
17
17
|
wmic
|
|
18
18
|
};
|
|
19
|
-
let platform = os
|
|
19
|
+
let platform = os.platform();
|
|
20
20
|
if (platform.startsWith("win")) platform = "win";
|
|
21
21
|
const method = platformToMethod[platform];
|
|
22
22
|
/**
|
|
@@ -24,7 +24,7 @@ const method = platformToMethod[platform];
|
|
|
24
24
|
*/
|
|
25
25
|
const getAll = (callback) => {
|
|
26
26
|
if (method === void 0) {
|
|
27
|
-
callback(/* @__PURE__ */ new Error(os
|
|
27
|
+
callback(/* @__PURE__ */ new Error(os.platform() + " is not supported yet, please open an issue (https://github.com/simonepri/pidtree)"), void 0);
|
|
28
28
|
return;
|
|
29
29
|
}
|
|
30
30
|
const listFn = methodToFn[method];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pidTree.mjs","names":[
|
|
1
|
+
{"version":3,"file":"pidTree.mjs","names":[],"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,WAAmB,GAAG,SAAS;AACnC,IAAI,SAAS,WAAW,KAAK,GAC3B,WAAW;AAGb,MAAM,SAA6B,iBAAiB;;;;AAKpD,MAAM,UAAU,aAAwC;CACtD,IAAI,WAAW,QAAW;EACxB,yBACE,IAAI,MACF,GAAG,SAAS,IACV,oFACJ,GACA,MACF;EACA;CACF;CAEA,MAAM,SAAS,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,QAAQ;EAC9B;CACF;CAEA,OAAO,KAAK,SAAS,KAAK,OAAO;AACnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { run } from "./bin.mjs";
|
|
2
|
-
import * as os
|
|
2
|
+
import * as os from "node:os";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/runParallel/ps.ts
|
|
5
5
|
/**
|
|
@@ -25,7 +25,7 @@ const ps = (callback) => {
|
|
|
25
25
|
return;
|
|
26
26
|
}
|
|
27
27
|
try {
|
|
28
|
-
const lines = stdout.split(os
|
|
28
|
+
const lines = stdout.split(os.EOL);
|
|
29
29
|
const list = [];
|
|
30
30
|
for (let i = 1; i < lines.length; i++) {
|
|
31
31
|
const line = lines[i];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ps.mjs","names":[
|
|
1
|
+
{"version":3,"file":"ps.mjs","names":[],"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,MAAM,GAAG,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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { run } from "./bin.mjs";
|
|
2
|
-
import * as os
|
|
2
|
+
import * as os from "node:os";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/runParallel/wmic.ts
|
|
5
5
|
/**
|
|
@@ -28,7 +28,7 @@ const wmic = (callback) => {
|
|
|
28
28
|
return;
|
|
29
29
|
}
|
|
30
30
|
try {
|
|
31
|
-
const lines = stdout.split(os
|
|
31
|
+
const lines = stdout.split(os.EOL);
|
|
32
32
|
const list = [];
|
|
33
33
|
for (let i = 1; i < lines.length; i++) {
|
|
34
34
|
const line = lines[i];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wmic.mjs","names":[
|
|
1
|
+
{"version":3,"file":"wmic.mjs","names":[],"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,MAAM,GAAG,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"}
|
package/dist/esm/watcher.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isDirectoryExcluded } from "./utils/isDirectoryExcluded.mjs";
|
|
1
2
|
import { formatPath } from "./utils/formatter.mjs";
|
|
2
3
|
import { getFormatFromExtension } from "./utils/getFormatFromExtension.mjs";
|
|
3
4
|
import { parseContentDeclarationFileName } from "./utils/parseContentDeclarationFileName.mjs";
|
|
@@ -139,8 +140,10 @@ const watch = async (options) => {
|
|
|
139
140
|
const path = normalizePath(filePath);
|
|
140
141
|
const isConfigFile = normalizedConfigPath && path === normalizedConfigPath;
|
|
141
142
|
if (!isConfigFile) {
|
|
142
|
-
|
|
143
|
-
if (
|
|
143
|
+
const matchingContentDir = contentDirs.filter((dictionary) => path.startsWith(`${dictionary}/`) || path === dictionary).reduce((longest, dictionary) => longest === void 0 || dictionary.length > longest.length ? dictionary : longest, void 0);
|
|
144
|
+
if (matchingContentDir === void 0) continue;
|
|
145
|
+
const relativeDirectory = dirname(path.slice(matchingContentDir.length));
|
|
146
|
+
if (isDirectoryExcluded(relativeDirectory, excludedPath)) continue;
|
|
144
147
|
if (!fileExtensions.some((extension) => path.endsWith(extension))) continue;
|
|
145
148
|
}
|
|
146
149
|
if (event.type === "create") {
|