import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import { createRequire, isBuiltin, registerHooks } from 'node:module'
import path from 'node:path'
import { pathToFileURL, fileURLToPath } from 'node:url'
assert.equal(process.argv.length, 4, 'Usage: node profile-load-order.mjs <checkout> <empty temporary directory>')
const repo = path.resolve(process.argv[2])
const scratch = path.resolve(process.argv[3])
assert.deepEqual(fs.readdirSync(scratch), [], 'The temporary directory must be empty')
const base = pathToFileURL(repo + path.sep).href
const store = path.join(repo, 'node_modules', '.pnpm')
const require = createRequire(import.meta.url)
const ts = require(path.join(store, 'typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const cachedPackages = fs.readdirSync(store)
const pinned = new Map([['ajv', 'ajv@8.20.0']])
// The local checkout lacks this dependency of the unrelated runtime import resolver.
const missingResolver = !fs.existsSync(path.join(store, 'resolve.exports@2.0.3/node_modules/resolve.exports/package.json'))
const unusedPackageImports = 'data:text/javascript,' + encodeURIComponent(
'export function imports() { throw new Error("Missing optional test-path dependency resolve.exports was invoked") }'
)
const packageRoots = new Map()
const sourceHashes = {}
const digest = (text) => createHash('sha256').update(text).digest('hex')
const fileUrl = (name) => pathToFileURL(name).href
const directories = (folder) => fs.readdirSync(folder, { withFileTypes: true })
.filter((entry) => entry.isDirectory()).map((entry) => path.join(folder, entry.name))
const read = (name) => JSON.parse(fs.readFileSync(name, 'utf8'))
const write = (name, body) => fs.writeFileSync(name, body, 'utf8')
const writeJson = (name, value) => write(name, JSON.stringify(value, null, 2))
for (const folder of [
...directories(path.join(repo, 'vendor')),
...directories(path.join(repo, 'packages')).flatMap(directories),
...directories(path.join(repo, 'apps')),
]) {
const manifest = path.join(folder, 'package.json')
if (fs.existsSync(manifest)) packageRoots.set(read(manifest).name, folder)
}
registerHooks({
resolve(specifier, context, nextResolve) {
if (isBuiltin(specifier) || /^(?:[./]|[a-z]+:)/i.test(specifier)) {
return nextResolve(specifier, context)
}
if (missingResolver && specifier === 'resolve.exports') return nextResolve(unusedPackageImports, context)
const segments = specifier.split('/')
const name = segments.splice(0, specifier.startsWith('@') ? 2 : 1).join('/')
const subpath = segments.join('/')
const root = packageRoots.get(name)
if (root) {
return nextResolve(fileUrl(path.join(root, subpath || 'src/index.ts')), context)
}
try {
return nextResolve(specifier, context)
} catch (error) {
if (error.code !== 'ERR_MODULE_NOT_FOUND' && error.code !== 'MODULE_NOT_FOUND') throw error
if (!context.parentURL?.startsWith(base)) throw error
const matches = cachedPackages.filter((entry) => entry.startsWith(name.replace('/', '+') + '@'))
const cached = pinned.get(name) ?? (matches.length === 1 ? matches[0] : undefined)
if (!cached) throw error
return nextResolve(specifier, { ...context, parentURL: fileUrl(path.join(store, cached, 'loader.mjs')) })
}
},
load(url, context, nextLoad) {
if (!url.startsWith(base) || !url.endsWith('.ts')) return nextLoad(url, context)
const filename = fileURLToPath(url)
const input = fs.readFileSync(filename, 'utf8')
sourceHashes[path.relative(repo, filename).split(path.sep).join('/')] = digest(input)
const output = ts.transpileModule(input, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } })
return { format: 'module', source: output.outputText, shortCircuit: true }
},
})
const app = await import(base + 'packages/boot/app-boot/src/index.ts')
const { initProfile, loadProfile, composeEntries, resolveProfileDir, readProfileManifest } =
await import(base + 'packages/boot/app-boot/src/profile.ts')
const { readProfilePatches } = await import(base + 'packages/boot/app-boot/src/profile-context.ts')
const name = 'lesson-colors'
const home = path.join(scratch, 'home')
const profile = resolveProfileDir(name, home)
const install = path.join(scratch, 'install')
fs.mkdirSync(install, { recursive: true })
const installAnchor = path.join(install, 'package.json')
writeJson(installAnchor, { name: 'lesson-install', private: true })
const packaged = '@deepseek-ai/dsh-base'
const local = 'lesson-colors-bundle'
const inert = 'lesson-palette-library'
const bundleNames = [packaged, local, inert]
initProfile(profile, bundleNames)
const cases = []
function check(name, input, expected, actual) {
assert.deepEqual(actual, expected, name)
cases.push({ name, input, expected, actual, passed: true })
}
const initial = readProfileManifest('lesson', profile)
check('profile_directory_and_manifest', { name, bundleNames },
{ dir: 'home/profiles/lesson-colors', manifest: { name: 'dsh-profile-lesson-colors', private: true, dependencies: {},
dsh: { profile: { bundles: bundleNames } } }, userPatch: true, workspace: true },
{ dir: path.relative(scratch, profile).split(path.sep).join('/'), manifest: initial,
userPatch: fs.existsSync(path.join(profile, 'cordis.patch.yml')),
workspace: fs.existsSync(path.join(profile, 'pnpm-workspace.yaml')) })
initProfile(profile, ['new-ignored'])
check('reinitialization_preserves_bundles', ['new-ignored'], bundleNames, readProfileManifest('lesson', profile).dsh.profile.bundles)
function fixture(anchor, packageName, patches) {
const folder = path.join(anchor, 'node_modules', packageName)
fs.mkdirSync(folder, { recursive: true })
writeJson(path.join(folder, 'package.json'), {
name: packageName, version: '0.1.0',
...(patches.length ? { dsh: { bundle: { patch: patches.length === 1 ? patches[0][0] : patches.map(([file]) => file) } } } : {}),
})
for (const [file, text] of patches) write(path.join(folder, file), text)
}
const row = 'palette'
const color = (value) => '- id: palette\n config: { color: ' + value + ' }\n'
fixture(install, packaged, [['first.yml', '- insert:\n - id: palette\n name: lesson-colors\n config: { color: navy, border: true }\n'],
['second.yml', '- id: palette\n config: { color: blue, border: true }\n']])
fixture(profile, packaged, [['wrong-anchor.yml', color('red')]])
fixture(profile, local, [['bundle.yml', color('green')]])
fixture(profile, inert, [])
const patchPath = path.join(profile, 'cordis.patch.yml')
const homePatch = path.join(home, 'cordis.patch.yml')
const overlayPaths = ['overlay-first.yml', 'overlay-last.yml'].map((file) => path.join(scratch, file))
write(patchPath, color('yellow'))
write(homePatch, color('orange'))
write(overlayPaths[0], color('silver'))
write(overlayPaths[1], color('purple'))
const loaded = loadProfile('lesson', name, installAnchor, home)
check('bundle_order_and_no_bundle_declaration', bundleNames, { layers: [packaged, local], skipped: [inert], reason: true },
{ layers: loaded.layers.map((layer) => layer.packageName), skipped: loaded.skippedBundles.map((layer) => layer.packageName),
reason: loaded.skippedBundles[0].reason.includes('declares no dsh.bundle') })
check('installation_anchor_and_ordered_bundle_files', packaged,
{ installed: true, files: ['first.yml', 'second.yml'], config: { color: 'blue', border: true } },
{ installed: loaded.layers[0].packageDir.startsWith(install + path.sep),
files: loaded.layers[0].patchPaths.map((name) => path.basename(name)), config: composeEntries([loaded.layers[0].patches])[0].config })
check('profile_anchor_used_for_external_bundle', local, true, loaded.layers[1].packageDir.startsWith(profile + path.sep))
const bundlePatches = loaded.layers.map((layer) => layer.patches)
check('whole_config_replaced_in_real_profile', { row, lastBundle: local }, { color: 'green' }, composeEntries(bundlePatches)[0].config)
const context = { name, dir: profile, patchPath, installAnchor, cwd: scratch, home, startedBundles: [packaged, local],
overlayPaths, telemetryDisabledEnv: undefined }
const layers = readProfilePatches('lesson', context, loaded)
check('file_backed_layers_through_official_reader', 'bundle -> profile -> home -> argv overlays',
['navy', 'blue', 'green', 'yellow', 'orange', 'silver', 'purple'],
layers.map((layer) => layer.insert?.[0].config.color ?? layer.config.color))
check('argv_final_overlay_wins', ['overlay-first.yml', 'overlay-last.yml'], { color: 'purple' }, composeEntries([layers])[0].config)
const labels = [...loaded.layers.map((layer) => ({ label: layer.packageName, patches: layer.patches })),
{ label: 'profile' , patches: loaded.patches },
{ label: 'home', patches: app.loadOptionalPatches('lesson', homePatch) },
...overlayPaths.map((file) => ({ label: path.basename(file), patches: app.loadOverlayPatches('lesson', file) }))]
const rootConfig = path.join(profile, 'cordis.yml')
write(rootConfig, '[]\n')
const dump = app.renderConfigDump('lesson', rootConfig, labels)
check('config_dump_labels_preserve_layer_order', labels.map((layer) => layer.label),
['# == @deepseek-ai/dsh-base, patched by lesson-colors-bundle, profile, home, overlay-first.yml, overlay-last.yml'],
dump.split(/\r?\n/).filter((line) => line.startsWith('# == ')))
check('config_dump_marks_effective_row', row, true, /color: purple/.test(dump))
write(patchPath, 'not-a-list: true\n')
const bundlesOnly = loadProfile('lesson', name, installAnchor, home, { userLayer: false })
check('bundles_only_read_skips_invalid_user_layer', 'options.userLayer = false', [packaged, local],
bundlesOnly.layers.map((layer) => layer.packageName))
let rejected = false
try {
loadProfile('lesson', name, installAnchor, home)
} catch (error) {
rejected = /must be a top-level YAML array/.test(error.message)
}
check('invalid_user_layer_rejected_on_normal_read', 'mapping instead of patch array', true, rejected)
console.log(JSON.stringify({
cases, node: process.version, typescript: ts.version, code_sha256: digest(fs.readFileSync(fileURLToPath(import.meta.url))),
source_hashes: Object.fromEntries(Object.entries(sourceHashes).sort(([a], [b]) => a.localeCompare(b))),
isolated_missing_dependency: missingResolver ? 'resolve.exports@2.0.3' : null,
actual_profile_api_tested: true, product_cli_tested: false, pnpm_install_tested: false, config_js_evaluated: false,
}, null, 2))
本例需在 Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、本地空临时目录。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、本地空临时目录。
入口文件:projects/deepseek-harness-install-load-order/profile-load-order.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
profile-load-order.mjs,或下载右侧课程工程包。 - 确认本地已准备 Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、本地空临时目录。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a140.zip
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip