@dpuse/dpuse-development 1.0.131 → 1.0.133
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dpuse-development.es.js","names":["runNpmCheckUpdates","START_MARKER","END_MARKER","determineConnectorUsageId","getConnectorActionsTable","fs","delay","START_MARKER","END_MARKER","START_MARKER","END_MARKER","fs","writeReadmeSection","readTextFileOrNull","spawnCommandForOutput","spawnCommand","Ce","De","spawnCommandToFile","readTextFile","resolveSampleDataContentType","logOperationHeader","FALLOW_DIRECTORY","migrateGovernanceSection","QUALITY_SECURITY_START_MARKER","bumpPackageVersion","clearDirectory","getStatsForPath","getModuleConfig","FALLOW_BADGE_PATH","writeJSONFile","RUST_WORKSPACE_PATH","getDirectoryEntries","CONTRIBUTING_LICENSE_START_MARKER","FALLOW_REPORT_PATH","execCommand","DEVELOPMENT_ONLY_PACKAGE_NAMES","QUALITY_SECURITY_END_MARKER","CONTRIBUTING_LICENSE_END_MARKER","buildModuleConfig","logOperationSuccess","resolveOwnerAndRepository","readJSONFile","logStepHeader","path","satisfies","os","IGNORED_ADVISORIES","\"id\"","\"reason\"","\"reviewBy\"","BLOCKING_SEVERITIES","auditDependencies","packageJSON","output","report","blockingAdvisories","checkAdvisories","listAdvisories","error","reportIgnoredAdvisories","label","ignoredCount","advisory","ignoredAdvisory","findIgnoredAdvisory","today","advisories","id","ignored","vulnerabilities","vulnerability","cause","WASM_BUILD_SCRIPT_NAME","buildProject","bundleProject","stepIcon","PRETTIER_CONFIG_REFERENCE","TEMPLATE_REPOSITORY_NAME","checkConfigFiles","configJSON","isPrivate","moduleTypeConfig","moduleDirectory","fileURLToPath","checkConfigFile","checkESLintConfig","checkTSConfig","checkTSConfigScripts","checkViteConfig","checkVitestConfig","checkPrettierConfig","hasRust","checkPrivateWorkflows","checkWorkflows","content","\"prettier\"","viteConfigTemplates","workflowPath","checkFilePath","checkFileName","templates","templateFileNames","checkFileContent","templateFileName","templatePath","templateContent","prepareTemplate","checkDependencies","rcOptions","run","pinnedPackageNames","getPinnedPackageNames","names","allowScripts","key","isAllowed","checkProject","START_MARKER$3","END_MARKER$3","SUPPORTED_ACTIONS_INTRO","CONNECTOR_USAGE_DESCRIPTIONS","SUPPORTED_ACTIONS_TABLE_LEAD_IN","documentActions","actionNames","usageId","table","block","documentContributingLicense","authorName","resolveAuthorName","copyrightYear","resolveCopyrightYear","buildContributingLicenseContent","owner","repository","author","authorString","emailStart","emailEnd","part","currentYear","firstCreatedAt","startYear","CARGO_METADATA_PATH","CARGO_TREE_PATH","CRATES_IO_REQUEST_INTERVAL","CRATES_IO_REQUEST_TIMEOUT","CRATES_IO_USER_AGENT","LICENSE_FILE_PATTERN","WASM_TARGET","documentRustCrates","cargoArguments","treeArguments","stepLabel","treeLines","parseCargoTree","metadata","promises","cratesByKey","line","crates","allowedLicenses","crate","copyLicenseFiles","addReleaseDetails","lines","text","crateText","licenseExpression","linkText","depthText","name","versionText","sourceParts","source","isOwn","link","checkCrateLicenses","allowedIdentifiers","isLicenseIdentifier","identifier","failures","isLicenseAllowed","failureList","cratePackage","candidate","crateDirectory","fileNames","fileName","a","b","licenseFiles","copiedPath","index","setTimeout","response","data","releaseDates","version","START_MARKER$2","END_MARKER$2","LICENSES_HEADING","SHIPPED_PACKAGES_RECORD_PATH","SHIPPED_PACKAGES_FILE_NAME","LICENSE_TREE_PATH","DEPENDENCY_TREE_FLAGS","DEPENDENCY_TREE_INTRO","SHIPPED_TREE_INTRO","documentDependencies","rootPackage","packageName","skipDependencyDocumentation","lockPackages","readLockPackages","shippedRecord","readShippedRecord","unshippedPackages","listUnshippedPackages","checkLicenses","insertDeclaredLicensesIntoReadme","shippedKeys","collectShippedKeys","installedKeys","listInstalledKeys","notShipped","packageKey","warnOfMissingPackages","rustCrates","readmeContext","listProductionNames","insertShippedLicensesIntoReadme","message","licenseTree","licensesByKey","readLicenses","licensesContent","buildLicensesIntro","license","formatLicenseRow","treeItems","walkTreeList","treeContent","context","crateLicensesByKey","convertCrateToLicense","hasRustCrates","tableHeader","compareLicenses","rootEntries","productionNames","javaScriptTree","rustTree","formatCrateTreeItem","item","indent","formatTreeItem","licenses","value","parseLicenseEntry","fetchNpmData","options","isProductionOnly","excludedKeys","resolve","reject","lockText","recordText","record","externalName","lockPath","resolveLockPath","shippedPath","findShippedPaths","entry","formatPackageKey","missingKeys","shippedPaths","shipped","unshipped","pendingPaths","startPath","fromPath","packages","listShippedDependencyNames","requiredPeerNames","basePath","candidatePath","parentIndex","licenseListText","formatLicenseListText","tools","buildScope","isFromBuild","lastAt","installedVersion","distributionTags","timeMap","latestVersion","publishedDate","licenseLink","licenseFile","typeLabel","depth","node","dependencies","items","walkShippedTree","entries","childEntries","isPassedOver","formatVersionDetail","published","determineLatestAge","latestAge","latestClause","momentString","dateString","input","now","months","START_MARKER$1","END_MARKER$1","documentOpening","resolveLicense","introduction","resolveIntroduction","dpuseModuleId","npmPackageName","resolvePackageName","buildOpeningContent","resolveVersionColor","repositoryURL","badgeLicense","dpuseConfigURL","description","SCORECARD_PRACTICE_LIMITS","SCORECARD_IGNORED_CHECKS","COVERAGE_FINAL_PATH","COVERAGE_SUMMARY_PATH","COVERAGE_TARGET_PERCENT","COVERAGE_WARNING_PERCENT","COVERAGE_BADGE_PATH","CODEQL_LANGUAGE_NAMES","FALLOW_GRADE_COLOURS","FALLOW_HEALTH_PATH","asyncExecFile","promisify","execFile","documentQualitySecurity","coveragePercent","measureTestCoverage","fallowHealth","measureCodeHealth","securitySettings","readSecuritySettings","bestPracticesProjectId","scorecardResult","lookUpBestPracticesProjectId","lookUpScorecardResult","buildQualitySecurityContent","summary","writeCoverageBadge","colourNames","level","\"fallow\"","coverageArguments","health","writeFallowBadge","grade","score","ciWorkflow","dependabotConfig","rustWorkspace","codeQLWorkflow","repositoryDetails","privateVulnerabilityReporting","vulnerabilityAlerts","checkRuns","readGitHubAPI","securityAndAnalysis","readSetting","checkAppSlugs","checkRun","ecosystemCount","pausedEcosystemCount","language","endpoint","stdout","project","scorecardURI","isScorecardOnlyPracticeLimited","result","formatManualNote","status","formatStatus","buildTableContent","rows","heading","row","formatEndpointBadge","badgePath","buildChecksContent","settings","ciNote","isInCI","testingRows","sonarCloudBadge","codeQualityRows","hasCodeQL","codeQLBadge","codeQLScope","codeQLLanguages","securityAnalysisRows","dependabotLink","dependencyRows","bestPracticesURL","scorecardLimitText","bestPracticesBadge","reportingText","checksResults","START_MARKER","END_MARKER","UPLOADED_MODULE_TYPE_IDS","INTERNAL_NPM_MODULE_TYPE_IDS","INTERNAL_NPM_WARNING","DEVELOPMENT_MANAGEMENT_TEXT","SHARED_MANAGEMENT_TEXT","documentUsage","cloneURL","resolveCloneURL","directoryName","resolveDirectoryName","nodeVersion","resolveVersion","npmVersion","typescriptVersion","\"typescript\"","buildIntroductionContent","packageJSONURL","buildUsageContent","url","range","match","typeId","management","API_REFERENCE_PATH","documentAPIReference","writeAPIReference","BUNDLE_REPORT_PATH","WORKER_REPORT_PATH","BUNDLE_START_MARKER","BUNDLE_END_MARKER","INDENT","BAR_WIDTH","BAR_CHARACTER","PART_BAR_CHARACTER","MIN_VISIBLE_PERCENT","SMALL_FILES_MAX_PERCENT","LABEL_MAX_LENGTH","BUNDLE_ANALYSIS_INTRO","BAR_NOTE","PART_ROW_NOTE","MORE_NOTE","UNTRACED_LABEL","WORKER_LABEL","WORKER_NOTE","WASM_LABEL_PREFIX","WASM_NOTE","UNTRACED_NOTE","documentBundleSizes","json","workerReport","workerJson","assetContents","resource","bundleTable","buildBundleTable","notes","note","assetGroups","buildAssetGroups","workerGroups","file","groups","separateEmbeddedContent","buildTotal","sum","group","assets","asset","resourceSizes","sizes","sortedGroups","compareGroups","fileTotal","buildShare","formatPercent","fitLabel","chunkSizes","renderGroupRows","isModuleLevel","workerText","findInlinedWorkerText","workerWasm","measureWasm","allWasm","separateWasm","separateWorker","variableName","declaration","quote","start","end","base64","countBase64Padding","wasm","formatBytes","untraced","untracedSizes","workerBytes","files","flattenWorkerGroups","groupName","formatGroupLabel","getSoleFileName","reportedBytes","zero","subtractBytes","bytes","groupSizes","composition","formatSeveralFilesLabel","renderFileRows","sortedFiles","smallCount","countSmallFiles","fileSizes","smallBytes","count","isTooSmallToShow","isCombinedRowStillSmall","bar","barCharacter","largestFileName","arrowIndex","prefix","pathMaxLength","dependencyPaths","buildDependencyPaths","resolveModule","addTo","dependency","dependencyPath","shortenCrateFileName","lastPathSegment","crateName","pct","whole","documentProject","isConnector","hasAPIReference","formatCode","formatTargets","existsSync","directory","lintCode","SAMPLE_DATA_BUCKET","putState","uploadDirectoryToR2","listFilesRecursively","sourceDirectory","uploadDirectory","filesByContentType","contentType","contentTypeFiles","bulkPutToR2","uploadSampleDataToR2","uploadModuleConfigToDO","stateId","uploadModuleToR2","currentDirectory","fullPath","relativePath","r2Path","uploadDirectoryPath","nonJavaScripContentType","listFolderPath","listFilePath","sourcePath","itemPath","keyPrefix","publishProject","isDeployedByScript","registerModule","moduleTypeName","releaseProject","builtConfigJSON","tagName","syncProjectWithGitHub","STEP_ICONS","TEST_TYPE_CONFIGS","testProject","stepNumber","testTypeConfig","testTypeIds","triggerGitHubRelease"],"sources":["../src/actions/auditDependencies_.json","../src/actions/auditDependencies.ts","../src/actions/buildProject.ts","../src/actions/checkConfigFiles.ts","../src/actions/checkDependencies.ts","../src/actions/checkProject.ts","../src/actions/documentActions.ts","../src/actions/documentContributingLicense.ts","../src/utilities/rustCrates.ts","../src/actions/documentDependencies.ts","../src/actions/documentOpening.ts","../src/actions/documentQualitySecurity.ts","../src/actions/documentUsage.ts","../src/actions/documentApiReference.ts","../src/actions/documentBundleSizes.ts","../src/actions/documentProject.ts","../src/actions/formatCode.ts","../src/actions/lintCode.ts","../src/utilities/cloudflare.ts","../src/actions/publishProject.ts","../src/actions/releaseProject.ts","../src/actions/syncProjectWithGitHub.ts","../src/actions/testProject.ts","../src/actions/triggerGitHubRelease.ts"],"sourcesContent":["{\n \"IGNORED_ADVISORIES\": [\n {\n \"id\": \"GHSA-fx2h-pf6j-xcff\",\n \"reason\": \"'vite', used by VitePress 1.x in dpuse-kb, which affects only the local dev server on Windows\",\n \"reviewBy\": \"2026-12-31\"\n },\n {\n \"id\": \"GHSA-vfj7-8cjw-p6xm\",\n \"reason\": \"'braces', used by ESLint's file matching in dpuse-app, which only reads glob patterns from the project's own config\",\n \"reviewBy\": \"2026-12-31\"\n },\n {\n \"id\": \"GHSA-wq5f-xc86-pv6w\",\n \"reason\": \"'sharp', pinned to 0.35.4 by miniflare, Wrangler's local Workers simulator, which runs only during development and is never deployed; remove once miniflare takes 0.35.5\",\n \"reviewBy\": \"2026-10-31\"\n }\n ]\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\n// High or critical advisories in development tools that cannot reach a release or the publish credentials, and have no\n// fix yet. Remove an entry once a fix is released. After an entry's 'reviewBy' date the audit warns, so it is checked\n// again rather than kept by habit.\nimport { IGNORED_ADVISORIES } from './auditDependencies_.json';\nimport { DEVELOPMENT_ONLY_PACKAGE_NAMES, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, spawnCommand, spawnCommandForOutput } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A flaw 'npm audit' reports against a package. The other entries in a package's 'via' list are the names of the\n// packages the flaw reaches it through.\ninterface AuditAdvisory {\n name: string;\n severity: string;\n title: string;\n url: string;\n}\n\ninterface AuditReport {\n error?: { summary: string };\n vulnerabilities?: Record<string, { via: (AuditAdvisory | string)[] }>;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst BLOCKING_SEVERITIES = new Set(['critical', 'high']);\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Audit the project's dependencies for known security vulnerabilities. */\nexport async function auditDependencies(): Promise<void> {\n try {\n logOperationHeader('Audit Dependencies');\n\n // Users install these packages, so any vulnerability at all fails the audit, and none is ever ignored. A\n // development-only package ships nothing to users, so all its dependencies are checked as dev tools below.\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n if (DEVELOPMENT_ONLY_PACKAGE_NAMES.has(packageJSON.name ?? '')) {\n logStepHeader(`1️⃣ Shipped dependencies NOT checked: ${packageJSON.name ?? ''} is a development-only tool`);\n } else {\n await spawnCommand('1️⃣ Check shipped dependencies for any vulnerability', 'npm', ['audit', '--omit=dev']);\n }\n\n // Dev tools run during publishing, where they could reach the publish credentials, so high and critical flaws\n // fail. Lesser ones often await an upstream fix, so they pass, as do the ignored advisories.\n const output = await spawnCommandForOutput('2️⃣ Check all dependencies for high or critical vulnerabilities', 'npm', ['audit', '--json']);\n const report = JSON.parse(output) as AuditReport;\n if (report.error !== undefined) throw new Error(report.error.summary);\n\n const blockingAdvisories = checkAdvisories(listAdvisories(report));\n if (blockingAdvisories.length > 0) throw new Error(`${String(blockingAdvisories.length)} high or critical vulnerabilities found`);\n\n logOperationSuccess('Dependencies audited');\n } catch (error) {\n console.error('❌ Error auditing dependencies', error);\n process.exit(1);\n }\n}\n\n/** Names the high or critical advisories 'npm audit' reports that the CI audit ignores, as npm's own report cannot. */\nexport async function reportIgnoredAdvisories(label: string): Promise<void> {\n const report = JSON.parse(await spawnCommandForOutput(label, 'npm', ['audit', '--json'])) as AuditReport;\n if (report.error !== undefined) {\n console.warn(`⚠️ Could not check the allow list: ${report.error.summary}`);\n return;\n }\n\n let ignoredCount = 0;\n for (const advisory of listAdvisories(report)) {\n const ignoredAdvisory = BLOCKING_SEVERITIES.has(advisory.severity) ? findIgnoredAdvisory(advisory) : undefined;\n if (ignoredAdvisory === undefined) continue;\n console.warn(`⚠️ ${ignoredAdvisory.id} ('${advisory.name}') is on the allow list, so the CI audit ignores it: ${ignoredAdvisory.reason}`);\n ignoredCount++;\n }\n if (ignoredCount === 0) console.info('ℹ️ None of the reported advisories are on the allow list');\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Reports each high or critical advisory, as ignored or blocking, and returns the blocking ones. */\nfunction checkAdvisories(advisories: AuditAdvisory[]): AuditAdvisory[] {\n const today = new Date().toISOString().slice(0, 10);\n const blockingAdvisories: AuditAdvisory[] = [];\n\n for (const advisory of advisories) {\n if (!BLOCKING_SEVERITIES.has(advisory.severity)) continue;\n\n const ignoredAdvisory = findIgnoredAdvisory(advisory);\n if (ignoredAdvisory === undefined) {\n console.error(`❌ ${advisory.severity} '${advisory.name}': ${advisory.title} (${advisory.url})`);\n blockingAdvisories.push(advisory);\n } else if (ignoredAdvisory.reviewBy < today) {\n console.warn(`⚠️ Ignored ${ignoredAdvisory.id}, but its review date ${ignoredAdvisory.reviewBy} has passed: ${ignoredAdvisory.reason}`);\n } else {\n console.info(`ℹ️ Ignored ${ignoredAdvisory.id}: ${ignoredAdvisory.reason}`);\n }\n }\n\n return blockingAdvisories;\n}\n\n// npm names an advisory only by its URL, which ends in the id.\nfunction findIgnoredAdvisory(advisory: AuditAdvisory): (typeof IGNORED_ADVISORIES)[number] | undefined {\n const id = advisory.url.slice(advisory.url.lastIndexOf('/') + 1);\n return IGNORED_ADVISORIES.find((ignored) => ignored.id === id);\n}\n\n/** The distinct advisories in an 'npm audit --json' report. */\nfunction listAdvisories(report: AuditReport): AuditAdvisory[] {\n const advisories = new Map<string, AuditAdvisory>();\n const vulnerabilities = Object.values(report.vulnerabilities ?? {});\n for (const vulnerability of vulnerabilities) {\n for (const cause of vulnerability.via) if (typeof cause !== 'string') advisories.set(cause.url, cause);\n }\n return advisories.values().toArray();\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A project with Rust code names its WebAssembly build in this script, as the crate and target differ by project.\nconst WASM_BUILD_SCRIPT_NAME = 'build:wasm';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Builds the package using Vite. Output to '/dist' directory. Builds bundle analysis reports. */\nexport async function buildProject(): Promise<void> {\n try {\n logOperationHeader('Build Project');\n\n await bundleProject('1️⃣ ', await readJSONFile<PackageJson>('package.json'));\n\n logOperationSuccess('Project built');\n } catch (error) {\n console.error('❌ Error building project', error);\n process.exit(1);\n }\n}\n\n/** Bundles the project with Vite, first building its WebAssembly where the project has a 'build:wasm' script. */\nexport async function bundleProject(stepIcon: string, packageJSON: PackageJson): Promise<void> {\n if (packageJSON.scripts?.[WASM_BUILD_SCRIPT_NAME] != null) {\n await spawnCommand(`${stepIcon} Build WebAssembly`, 'npm', ['run', WASM_BUILD_SCRIPT_NAME]);\n }\n await spawnCommand(`${stepIcon} Bundle project`, 'vite', ['build']);\n}\n","// ── External Dependencies & Registrations\nimport { fileURLToPath } from 'node:url';\nimport type { PackageJson } from 'type-fest';\nimport path from 'node:path';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport {\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n ModuleTypeConfig,\n readJSONFile,\n readTextFile,\n readTextFileOrNull,\n RUST_WORKSPACE_PATH\n} from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst PRETTIER_CONFIG_REFERENCE = '@dpuse/dpuse-development/prettierrc';\nconst TEMPLATE_REPOSITORY_NAME = 'dpuse-development'; // Stands in for each project's own name in the SECURITY.md template.\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function checkConfigFiles(): Promise<void> {\n try {\n logOperationHeader('Check configuration files');\n\n logStepHeader('1️⃣ Check individual files');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const isPrivate = packageJSON.private === true; // Private packages have no CodeQL, Scorecard or security policy.\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\n await checkConfigFile(moduleDirectory, '.editorconfig');\n await checkConfigFile(moduleDirectory, '.gitattributes');\n await checkConfigFile(moduleDirectory, '.gitignore', ['.gitignore_default']);\n await checkConfigFile(moduleDirectory, '.markdownlint.json');\n await checkConfigFile(moduleDirectory, '.ncurc.json');\n await checkESLintConfig(moduleTypeConfig, moduleDirectory);\n await checkConfigFile(moduleDirectory, 'LICENSE');\n await checkTSConfig(moduleTypeConfig, moduleDirectory);\n await checkTSConfigScripts(moduleTypeConfig, moduleDirectory);\n await checkViteConfig(moduleTypeConfig, moduleDirectory);\n await checkVitestConfig(moduleTypeConfig, moduleDirectory);\n checkPrettierConfig(moduleTypeConfig, packageJSON);\n // Projects with Rust code pin their Rust version, and have Dependabot watch Cargo as well.\n const hasRust = (await readTextFileOrNull(RUST_WORKSPACE_PATH)) !== null;\n if (hasRust) await checkConfigFile(moduleDirectory, 'rust-toolchain.toml');\n const dependabotTemplate = `.github/dependabot${isPrivate ? '.private' : ''}${hasRust ? '.rust' : ''}.yml`;\n await checkConfigFile(moduleDirectory, '.github/dependabot.yml', [dependabotTemplate]);\n if (isPrivate) {\n await checkPrivateWorkflows(moduleDirectory);\n } else {\n await checkWorkflows(moduleDirectory);\n await checkConfigFile(moduleDirectory, 'SECURITY.md', [], (content) => content.replaceAll(TEMPLATE_REPOSITORY_NAME, () => configJSON.id));\n }\n\n logOperationSuccess('Configuration files checked');\n } catch (error) {\n console.error('❌ Error checking configuration files', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function checkESLintConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'eslint.config.js' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'eslint', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'eslint.config.js' is UNIQUE to this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'eslint.config.js', ['eslint.config.default.js']);\n }\n}\nfunction checkPrettierConfig(moduleTypeConfig: ModuleTypeConfig, packageJSON: PackageJson) {\n if (moduleTypeConfig.typeId === 'development') {\n console.info(\"ℹ️ File '.prettierrc.json' is the template\"); // Every other project points to this file.\n } else if (moduleTypeConfig.typeId === 'app') {\n console.info(\"⚠️ File '.prettierrc.json' is UNIQUE to this project\");\n } else if (packageJSON['prettier'] === PRETTIER_CONFIG_REFERENCE) {\n console.info(`ℹ️ Prettier configuration is '${PRETTIER_CONFIG_REFERENCE}'`);\n } else {\n console.info(`❌ Prettier configuration is NOT '${PRETTIER_CONFIG_REFERENCE}'`);\n }\n}\n\nasync function checkTSConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'tsconfig.json' is NOT required by this project\");\n } else if (['connector', 'cookbook', 'development', 'engine', 'presenter', 'shared', 'tool'].includes(moduleTypeConfig.typeId)) {\n await checkConfigFile(moduleDirectory, 'tsconfig.json');\n } else {\n console.info(\"⚠️ File 'tsconfig.json' is UNIQUE to this project\");\n }\n}\n\nasync function checkTSConfigScripts(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'scripts/tsconfig.json' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'scripts/tsconfig.json'); // Type-checks the 'scripts' folder, whose files Node runs directly.\n }\n}\n\nasync function checkViteConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n // The sample data is published as files, so it has nothing to bundle.\n if (['eslint', 'github', 'kb', 'resources'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vite.config.ts' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'engine'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'vite.config.ts' is UNIQUE to this project\");\n } else {\n let viteConfigTemplates: string[];\n switch (moduleTypeConfig.typeId) {\n case 'presenter':\n viteConfigTemplates = ['vite.config.presenter.ts'];\n break;\n case 'tool':\n viteConfigTemplates = ['vite.config.tool.ts'];\n break;\n default:\n viteConfigTemplates = ['vite.config.default.ts'];\n }\n await checkConfigFile(moduleDirectory, 'vite.config.ts', viteConfigTemplates);\n }\n}\n// A private repository may still build and publish through GitHub, so the workflows it has are checked. CodeQL and\n// Scorecard only run on public repositories.\nasync function checkPrivateWorkflows(moduleDirectory: string) {\n for (const workflowPath of ['.github/workflows/ci.yml', '.github/workflows/publish.yml']) {\n if ((await readTextFileOrNull(workflowPath)) !== null) await checkConfigFile(moduleDirectory, workflowPath);\n }\n console.info(\"ℹ️ CodeQL and Scorecard workflows and file 'SECURITY.md' are NOT required by this project\");\n}\n\nasync function checkWorkflows(moduleDirectory: string) {\n await checkConfigFile(moduleDirectory, '.github/workflows/ci.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/codeql.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/publish.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/scorecard.yml');\n}\n\nasync function checkVitestConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['app', 'api', 'github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vitest.config.ts' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'vitest.config.ts');\n }\n}\n\nasync function checkConfigFile(moduleDirectory: string, checkFileName: string, templateFileNames: string[] = [], prepareTemplate = (content: string) => content): Promise<void> {\n const checkFilePath = path.resolve(process.cwd(), checkFileName);\n const templates = templateFileNames.length > 0 ? templateFileNames : [checkFileName];\n\n let checkFileContent;\n try {\n checkFileContent = await readTextFile(checkFilePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (checkFileContent === undefined) {\n console.info(`❌ File '${checkFileName}' is MISSING`);\n return;\n }\n\n for (const templateFileName of templates) {\n const templatePath = path.resolve(moduleDirectory, `../${templateFileName}`);\n const templateContent = prepareTemplate(await readTextFile(templatePath));\n if (checkFileContent === templateContent) {\n console.info(`ℹ️ File '${checkFileName}' is the same as '${templateFileName}'`);\n return;\n }\n }\n\n console.info(`❌ File '${checkFileName}' is NOT the same`);\n}\n","// ── External Dependencies & Registrations\nimport path from 'node:path';\nimport type { RcOptions } from 'npm-check-updates';\nimport { run as runNpmCheckUpdates } from 'npm-check-updates';\n\n// ── Local Framework\nimport { reportIgnoredAdvisories } from '@/actions/auditDependencies';\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identifies outdated dependencies using npm outdated and npm-check-updates with option to automatically install\n * latest versions. */\nexport async function checkDependencies(): Promise<void> {\n try {\n logOperationHeader('Check Dependencies');\n\n await spawnCommand(\"1️⃣ Check using 'npm outdated'\", 'npm', ['outdated'], true);\n\n logStepHeader(\"2️⃣ Check using 'npm-check-updates'\");\n let rcOptions: RcOptions = {};\n try {\n rcOptions = await readJSONFile<RcOptions>(path.resolve(process.cwd(), '.ncurc.json'));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n await runNpmCheckUpdates({ interactive: true, upgrade: true, dep: 'dev,prod,peer,optional', install: 'never', ...rcOptions });\n\n // Not strict here, otherwise an upgraded package with a pinned approval fails the install before step 5 can move its pin.\n // No audit summary, as step 4 reports what is left once it has fixed what it can.\n await spawnCommand('3️⃣ Install updated dependencies', 'npm', ['install', '--prefer-online', '--no-strict-allow-scripts', '--no-audit', '--no-fund']);\n\n // Only upgrades the version ranges in package.json already allow; never '--force', which makes breaking ones. Runs before\n // the pins move in step 5, so a package it upgrades has its pin moved too. npm exits with an error while vulnerabilities\n // it cannot fix remain, such as those waiting on an upstream release, so that is reported without stopping the check.\n await spawnCommand('4️⃣ Fix vulnerabilities where a compatible upgrade exists', 'npm', ['audit', 'fix', '--no-strict-allow-scripts', '--no-fund'], true);\n await reportIgnoredAdvisories('4️⃣ Name the advisories above that the CI audit ignores');\n\n // Only packages already approved are re-approved, so a newly added install script still waits for review in step 8.\n // Name-only approvals already cover every version, so only pinned ones need moving. Runs before prune, which would\n // otherwise delete a pin to an upgraded version as 'not installed' before it could be moved.\n const pinnedPackageNames = await getPinnedPackageNames();\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('5️⃣ Move install-script pins to installed versions', 'npm', ['install-scripts', 'approve', ...pinnedPackageNames]);\n } else {\n logStepHeader('5️⃣ No pinned install-script approvals to move');\n }\n\n // Runs before the rebuild in step 7. A rebuild leaves npm's record of 'node_modules' out of date, and prune then misses\n // install scripts that 'npm install' still sees, as with 'fsevents' (npm 12.0.1). Also macOS only, as elsewhere it drops\n // entries for macOS-only packages that are not installed.\n if (process.platform === 'darwin') {\n await spawnCommand('6️⃣ Remove unused install-script entries', 'npm', ['install-scripts', 'prune']);\n } else {\n logStepHeader('6️⃣ Skipped removing unused install-script entries (macOS only)');\n }\n\n // Not strict, so any install script still awaiting review is reported once, by step 8.\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('7️⃣ Run install scripts skipped in steps 3 and 4', 'npm', ['rebuild', ...pinnedPackageNames, '--no-strict-allow-scripts']);\n }\n\n // The same check a plain 'npm install' makes, which 'npm install-scripts ls' does not always agree with. Fails listing any\n // install scripts still awaiting review. Step 4 has already reported the audit.\n await spawnCommand('8️⃣ Confirm every install script is reviewed', 'npm', ['install', '--strict-allow-scripts', '--no-audit', '--no-fund']);\n\n logOperationSuccess('Dependencies checked');\n } catch (error) {\n console.error('❌ Error checking dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Keys are 'name', 'name@version' or '@scope/name@version'. An '@' after the first character marks a pin; it and the version\n// are dropped so npm matches every installed version.\nasync function getPinnedPackageNames(): Promise<string[]> {\n const { allowScripts = {} } = await readJSONFile<{ allowScripts?: Record<string, boolean> }>(path.resolve(process.cwd(), 'package.json'));\n const names = Object.entries(allowScripts)\n .filter(([key, isAllowed]) => isAllowed && key.lastIndexOf('@') > 0)\n .map(([key]) => key.slice(0, key.lastIndexOf('@')));\n return [...new Set(names)];\n}\n","// ── Local Framework\nimport { checkConfigFiles } from '@/actions/checkConfigFiles';\nimport { checkDependencies } from '@/actions/checkDependencies';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Checks the configuration files against the DPUse templates, then lists outdated dependencies. */\nexport async function checkProject(): Promise<void> {\n await checkConfigFiles();\n await checkDependencies();\n}\n","// ── DPUse Framework\nimport type { ConnectorActionName, ConnectorUsageId } from '@dpuse/dpuse-shared';\nimport { determineConnectorUsageId, getConnectorActionsTable } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- SUPPORTED_ACTIONS_START -->';\nconst END_MARKER = '<!-- SUPPORTED_ACTIONS_END -->';\n\nconst SUPPORTED_ACTIONS_INTRO =\n 'Connectors conform to a unified interface contract by implementing a specific subset of standard actions. These standardised actions allow the DPUse application to interact with any underlying data source in the same way, enabling Connectors to be built independently and loaded dynamically at runtime.';\n\nconst CONNECTOR_USAGE_DESCRIPTIONS: Record<ConnectorUsageId, string> = {\n source: 'This connector is a Source connector that supports only read actions. Connectors can also function as a Destination (write-only) or Bidirectional (read/write), depending on the actions they support.',\n destination:\n 'This connector is a Destination connector that supports only write actions. Connectors can also function as a Source (read-only) or Bidirectional (read/write), depending on the actions they support.',\n bidirectional:\n 'This connector is a Bidirectional connector that supports both read and write actions. Connectors can also function as a Source (read-only) or Destination (write-only), depending on the actions they support.',\n unknown:\n 'This connector does not yet implement any read or write actions, so its type cannot be determined. Connectors function as a Source (read-only), a Destination (write-only), or Bidirectional (read/write), depending on the actions they support.'\n};\n\nconst SUPPORTED_ACTIONS_TABLE_LEAD_IN = 'The table below lists all connector actions and highlights those supported by this connector.';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentActions(): Promise<void> {\n try {\n logOperationHeader('Document Actions');\n\n logStepHeader(\"1️⃣ Insert actions description and table into 'README.md'\");\n\n const config = await readJSONFile<{ actionNames?: string[] }>('config.json');\n const actionNames = (config.actionNames ?? []) as ConnectorActionName[];\n const usageId = determineConnectorUsageId(actionNames);\n const table = getConnectorActionsTable(actionNames);\n\n const block = `## Supported Actions\\n\\n${SUPPORTED_ACTIONS_INTRO}\\n\\n${CONNECTOR_USAGE_DESCRIPTIONS[usageId]} ${SUPPORTED_ACTIONS_TABLE_LEAD_IN}\\n\\n${table}`;\n\n await writeReadmeSection(block, START_MARKER, END_MARKER);\n\n logOperationSuccess('Actions documented');\n } catch (error) {\n console.error('❌ Error documenting actions', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport {\n CONTRIBUTING_LICENSE_END_MARKER,\n CONTRIBUTING_LICENSE_START_MARKER,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n readJSONFile,\n resolveOwnerAndRepository,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface LicenseModuleConfig {\n firstCreatedAt?: number | null;\n}\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Contributing and License sections. */\nexport async function documentContributingLicense(): Promise<void> {\n try {\n logOperationHeader('Document Contributing & License');\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<LicenseModuleConfig>('config.json')]);\n\n const { owner, repository } = resolveOwnerAndRepository(packageJSON, 'document contributing and license');\n const authorName = resolveAuthorName(packageJSON);\n const copyrightYear = resolveCopyrightYear(configJSON.firstCreatedAt);\n\n logStepHeader(\"1️⃣ Insert contributing and license content into 'README.md'\");\n\n await migrateGovernanceSection();\n await writeReadmeSection(buildContributingLicenseContent(owner, repository, authorName, copyrightYear), CONTRIBUTING_LICENSE_START_MARKER, CONTRIBUTING_LICENSE_END_MARKER);\n\n logOperationSuccess('Contributing & license documented');\n } catch (error) {\n console.error('❌ Error documenting contributing and license', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveAuthorName(packageJSON: PackageJson): string {\n const author = packageJSON.author;\n const authorString = typeof author === 'string' ? author : author?.name;\n if (authorString == null || authorString === '') throw new Error(\"package.json 'author' field is required to document contributing and license.\");\n\n // Drop the first '<email>' and the spaces around it, keeping one space between what came before and after it, as in\n // npm's 'Name <email> (url)' form. Not a regex, as '\\s*<' backtracks on long runs of spaces.\n const emailStart = authorString.indexOf('<');\n const emailEnd = emailStart === -1 ? -1 : authorString.indexOf('>', emailStart);\n return emailEnd === -1 ? authorString.trim() : [authorString.slice(0, emailStart).trim(), authorString.slice(emailEnd + 1).trim()].filter((part) => part !== '').join(' ');\n}\n\nfunction resolveCopyrightYear(firstCreatedAt: number | null | undefined): string {\n const currentYear = new Date().getFullYear();\n if (firstCreatedAt == null) return String(currentYear);\n\n const startYear = new Date(firstCreatedAt).getFullYear();\n return startYear === currentYear ? String(currentYear) : `${String(startYear)}-present`;\n}\n\nfunction buildContributingLicenseContent(owner: string, repository: string, authorName: string, copyrightYear: string): string {\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n\n return `## Contributing\n\nThis repository is maintained solely by its owner and does not, at present, accept external contributions into the canonical repo. Its source is published openly under the MIT License — every DPUse project is fully open source except DPUse Engine, which remains closed and proprietary.\n\nFor security vulnerabilities, see [Reporting Vulnerabilities](#reporting-vulnerabilities). For bugs, inconsistencies, or other feedback, [open a GitHub issue](${repositoryURL}/issues) — feedback is read, but responses and fixes are at the maintainer's discretion.\n\n## License\n\nThis project is licensed under the MIT License, permitting free use, modification, and distribution.\n\n[MIT](./LICENSE) © ${copyrightYear} ${authorName}`;\n}\n","/* eslint-disable security/detect-non-literal-fs-filename -- Paths come from Cargo's own output and this project's folders, not user input. */\n\n// ── External Dependencies & Registrations\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport satisfies from 'spdx-satisfies';\n\n// ── Local Framework\nimport { logStepHeader, readJSONFile, readTextFile, readTextFileOrNull, RUST_WORKSPACE_PATH, spawnCommandToFile } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** A crate compiled into the project's WebAssembly, with where to find its licence and its release history. */\nexport interface RustCrate {\n name: string;\n version: string;\n licenseExpression: string;\n repository: string;\n licenseFiles: { label: string; path: string }[]; // Relative to the 'licenses' folder.\n publishedDate: string;\n latestVersion: string;\n latestPublishedDate: string;\n}\n\n/** One line of Cargo's dependency tree. The project's own crates are in it too, so the tree reads from them down. */\nexport interface RustCrateTreeItem {\n name: string;\n version: string;\n depth: number;\n isOwn: boolean;\n}\n\ninterface CargoMetadata {\n packages: { name: string; version: string; manifest_path: string }[];\n}\n\ninterface CratesIOResponse {\n crate?: { max_stable_version?: string | null; max_version?: string };\n versions?: { num: string; created_at: string }[];\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst CARGO_METADATA_PATH = 'licenses/cargoMetadata.json';\nconst CARGO_TREE_PATH = 'licenses/cargoTree.txt';\nconst CRATES_IO_REQUEST_INTERVAL = 1000; // crates.io asks automated clients for no more than one request a second.\nconst CRATES_IO_REQUEST_TIMEOUT = 10_000; // Without one, a request crates.io never answers would hang the release.\nconst CRATES_IO_USER_AGENT = 'dpuse-development (https://github.com/dpuse/dpuse-development)'; // crates.io refuses requests without one.\nconst LICENSE_FILE_PATTERN = /^(?:copying|licen[cs]e|unlicense)/i;\nconst WASM_TARGET = 'wasm32-unknown-unknown';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Lists the crates compiled into the project's WebAssembly, checks each licence against those allowed, and copies\n * each licence file to 'licenses/downloads'. Returns null for a project with no Rust code. Only normal dependencies\n * built for WebAssembly are followed: development and build dependencies, and macros (which run only while compiling),\n * put none of their code in the output. */\nexport async function documentRustCrates(stepLabel: string, allowedLicenses: string): Promise<{ crates: RustCrate[]; treeItems: RustCrateTreeItem[] } | null> {\n if ((await readTextFileOrNull(RUST_WORKSPACE_PATH)) === null) return null;\n\n const cargoArguments = ['--manifest-path', RUST_WORKSPACE_PATH, '--locked'];\n const treeArguments = ['tree', ...cargoArguments, '--workspace', '--edges', 'normal,no-proc-macro', '--target', WASM_TARGET, '--prefix', 'depth', '--format', '{p}|{l}|{r}'];\n await spawnCommandToFile(stepLabel, 'cargo', treeArguments, CARGO_TREE_PATH);\n await spawnCommandToFile(stepLabel, 'cargo', ['metadata', ...cargoArguments, '--format-version', '1', '--filter-platform', WASM_TARGET], CARGO_METADATA_PATH);\n const treeLines = parseCargoTree(await readTextFile(CARGO_TREE_PATH));\n const metadata = await readJSONFile<CargoMetadata>(CARGO_METADATA_PATH);\n // Both hold paths on this machine, so are not kept.\n await fs.rm(CARGO_TREE_PATH, { force: true });\n await fs.rm(CARGO_METADATA_PATH, { force: true });\n\n const cratesByKey = new Map<string, RustCrate>();\n for (const line of treeLines) {\n if (line.isOwn || cratesByKey.has(`${line.name}@${line.version}`)) continue;\n cratesByKey.set(`${line.name}@${line.version}`, {\n name: line.name,\n version: line.version,\n licenseExpression: line.licenseExpression,\n repository: line.repository === '' ? `https://crates.io/crates/${line.name}` : line.repository,\n licenseFiles: [],\n publishedDate: '',\n latestVersion: '',\n latestPublishedDate: ''\n });\n }\n const crates = cratesByKey.values().toArray();\n\n checkCrateLicenses(crates, allowedLicenses);\n for (const crate of crates) crate.licenseFiles = await copyLicenseFiles(crate, metadata);\n await addReleaseDetails(stepLabel, crates);\n\n return { crates, treeItems: treeLines.map(({ name, version, depth, isOwn }) => ({ name, version, depth, isOwn })) };\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Each line reads '<depth><name> v<version>[ (<source>)]|<licence>|<repository>', with ' (*)' added where Cargo has\n// already listed the crate's dependencies higher up. Crate names never start with a digit, so the depth is the leading\n// digits. A crate whose source is a folder, rather than a registry or Git URL, is one of the project's own.\nfunction parseCargoTree(text: string): (RustCrateTreeItem & { licenseExpression: string; repository: string })[] {\n const lines = [];\n for (const line of text.split('\\n')) {\n const [crateText = '', licenseExpression = '', linkText = ''] = line.trim().split('|', 3);\n const depthText = /^\\d+/.exec(crateText)?.[0];\n if (depthText === undefined) continue;\n const [name = '', versionText = '', ...sourceParts] = crateText.slice(depthText.length).split(' ');\n const source = sourceParts.join(' ').replace(/^\\(/, '').replace(/\\)$/, '');\n const isOwn = source !== '' && !source.includes('://');\n const link = linkText.replace(/ \\(\\*\\)$/, '');\n lines.push({ name, version: versionText.replace(/^v/, ''), depth: Number(depthText), isOwn, licenseExpression, repository: link });\n }\n return lines;\n}\n\n// Cargo's licence field is an SPDX expression, so it is checked as one: 'MIT OR Apache-2.0' needs either, while\n// '(MIT OR Apache-2.0) AND Unicode-3.0' also needs 'Unicode-3.0'. The older 'MIT/Apache-2.0' form means 'OR'.\nfunction checkCrateLicenses(crates: RustCrate[], allowedLicenses: string): void {\n const allowedIdentifiers = allowedLicenses.split(';').filter((identifier) => isLicenseIdentifier(identifier));\n const failures = crates.filter((crate) => !isLicenseAllowed(crate.licenseExpression, allowedIdentifiers));\n if (failures.length === 0) return;\n const failureList = failures.map((crate) => `${crate.name}@${crate.version} (${crate.licenseExpression === '' ? 'no licence' : crate.licenseExpression})`).join(', ');\n throw new Error(`Rust crates with licences not allowed: ${failureList}.`);\n}\n\n// The allow list can also name licences that are not SPDX identifiers, such as a licence page, which only npm packages use.\nfunction isLicenseIdentifier(identifier: string): boolean {\n try {\n return satisfies(identifier, [identifier]);\n } catch {\n return false;\n }\n}\n\nfunction isLicenseAllowed(licenseExpression: string, allowedIdentifiers: string[]): boolean {\n try {\n return satisfies(licenseExpression.replaceAll('/', ' OR '), allowedIdentifiers);\n } catch {\n return false; // Not a licence expression at all, so it cannot be confirmed as allowed.\n }\n}\n\n// The licence files sit beside the crate's own 'Cargo.toml' in Cargo's download cache.\nasync function copyLicenseFiles(crate: RustCrate, metadata: CargoMetadata): Promise<{ label: string; path: string }[]> {\n const cratePackage = metadata.packages.find((candidate) => candidate.name === crate.name && candidate.version === crate.version);\n if (cratePackage == null) return [];\n const crateDirectory = path.dirname(cratePackage.manifest_path);\n const directoryEntries = await fs.readdir(crateDirectory);\n const fileNames = directoryEntries.filter((fileName) => LICENSE_FILE_PATTERN.test(fileName)).toSorted((a, b) => a.localeCompare(b, 'en'));\n await fs.mkdir('licenses/downloads', { recursive: true });\n const licenseFiles = [];\n for (const fileName of fileNames) {\n const copiedPath = `downloads/${crate.name}@${crate.version}-${fileName}`;\n await fs.copyFile(path.join(crateDirectory, fileName), path.join('licenses', copiedPath));\n licenseFiles.push({ label: fileName, path: copiedPath });\n }\n return licenseFiles;\n}\n\n// One request at a time, as crates.io asks. A crate it cannot answer for is shown without dates.\nasync function addReleaseDetails(stepLabel: string, crates: RustCrate[]): Promise<void> {\n logStepHeader(`${stepLabel} - fetch release dates from crates.io`);\n for (const [index, crate] of crates.entries()) {\n if (index > 0) await delay(CRATES_IO_REQUEST_INTERVAL);\n console.info(`⚙️ Fetching '${crate.name}' (${String(index + 1)} of ${String(crates.length)})...`);\n try {\n const response = await fetch(`https://crates.io/api/v1/crates/${encodeURIComponent(crate.name)}`, {\n headers: { 'User-Agent': CRATES_IO_USER_AGENT },\n signal: AbortSignal.timeout(CRATES_IO_REQUEST_TIMEOUT)\n });\n if (!response.ok) continue;\n const data = (await response.json()) as CratesIOResponse;\n const releaseDates = new Map((data.versions ?? []).map((version) => [version.num, version.created_at]));\n crate.latestVersion = data.crate?.max_stable_version ?? data.crate?.max_version ?? '';\n crate.publishedDate = releaseDates.get(crate.version) ?? '';\n crate.latestPublishedDate = crate.latestVersion === crate.version ? '' : (releaseDates.get(crate.latestVersion) ?? '');\n } catch {\n // Ignore network errors and timeouts.\n }\n }\n}\n\n/* eslint-enable security/detect-non-literal-fs-filename -- End of the Rust crate documentation's file access. */\n","// ── External Dependencies & Registrations\n// TODO: 'license-checker-rseidelsohn' is being retired in favour of '@lizenz/checker'. Switch when '@lizenz/checker'\n// reaches 1.0.0, a drop-in replacement: change these two imports and the README link text in 'buildLicensesIntro'.\n// It is BSD-3-Clause, not MIT. Longer term, 'npm sbom --omit dev' could replace it with no extra dependencies, but the\n// allowed-licence check and licence-file lookup would then need writing here.\nimport { init as initLicenseChecker } from 'license-checker-rseidelsohn';\nimport type { InitOpts } from 'license-checker-rseidelsohn';\n\n// ── Local Framework\nimport { documentRustCrates } from '@/utilities/rustCrates';\nimport { SHIPPED_PACKAGES_FILE_NAME } from '@/vite';\nimport type { ShippedPackagesRecord } from '@/vite';\nimport {\n clearDirectory,\n DEVELOPMENT_ONLY_PACKAGE_NAMES,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n readJSONFile,\n readTextFileOrNull,\n spawnCommandToFile,\n writeReadmeSection\n} from '@/utilities';\nimport type { RustCrate, RustCrateTreeItem } from '@/utilities/rustCrates';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface License {\n name: string;\n repository: string;\n licenseTypes: string;\n installedVersion: string;\n latestVersion: string;\n latestPublishedDate: string;\n author: string;\n publishedDate: string;\n licenseFiles: { label: string; path: string }[]; // Relative to the 'licenses' folder.\n}\n\ninterface ProductionPackageLicense {\n licenses: string;\n repository?: string;\n publisher?: string;\n email?: string;\n path?: string;\n licenseFile?: string;\n}\n\ninterface PackageLock {\n packages?: Record<string, PackageLockEntry>;\n}\n\ninterface PackageLockEntry {\n name?: string;\n version?: string;\n link?: boolean;\n resolved?: string;\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n peerDependenciesMeta?: Record<string, { optional?: boolean }>;\n}\n\ninterface RootPackage {\n name?: string;\n version?: string;\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n}\n\ninterface ShippedReadmeContext {\n allowedLicenses: string;\n productionNames: Set<string>;\n rustCrates: { crates: RustCrate[]; treeItems: RustCrateTreeItem[] } | null;\n shippedKeys: Set<string>;\n}\n\ninterface ShippedTreeContext {\n licensesByKey: Map<string, License>;\n shippedKeys: Set<string>;\n shownKeys: Set<string>;\n}\n\ninterface NpmPackageTree {\n version?: string;\n dependencies?: Record<string, NpmPackageTree>;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- DEPENDENCY_LICENSES_START -->';\nconst END_MARKER = '<!-- DEPENDENCY_LICENSES_END -->';\nconst LICENSES_HEADING = '## Dependency Licenses';\nconst SHIPPED_PACKAGES_RECORD_PATH = `bundle-analysis-reports/${SHIPPED_PACKAGES_FILE_NAME}`; // Written by the 'recordShippedPackages' build plugin.\nconst LICENSE_TREE_PATH = 'licenses/licenseTree.json';\n\nconst DEPENDENCY_TREE_FLAGS =\n \"Packages flagged ❗ have a newer version available; ⚠️ indicates a package that hasn't been updated in the last 6 months or longer. Neither flag necessarily indicates a problem: we let new releases stabilise before upgrading, and some packages are mature and stable (have limited or no dependencies), so they require no active development.\";\nconst DEPENDENCY_TREE_INTRO = `The dependency tree below lists every package in this project — direct and transitive — along with its installed version, release date, and update status. ${DEPENDENCY_TREE_FLAGS}`;\nconst SHIPPED_TREE_INTRO = `The dependency tree below shows how each package in the table above is reached — direct and transitive — along with its installed version, release date, and update status. A package that does not ship itself, such as one whose parts are bundled separately, is left out and what ships beneath it is shown in its place. ${DEPENDENCY_TREE_FLAGS}`;\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identify licenses of the project's production and peer dependencies. Updates the table in the Dependency Licenses\n * section of this page and summary files licenses.json and licenseTree.json in th licenses directory of this\n * repository. Also downloads a copy of dependency license to `licenses/downloads'. */\nexport async function documentDependencies(allowedLicenses = 'MIT'): Promise<void> {\n try {\n logOperationHeader('Document Dependencies');\n\n const rootPackage = await readJSONFile<RootPackage>('package.json');\n\n const packageName = rootPackage.name ?? '';\n if (DEVELOPMENT_ONLY_PACKAGE_NAMES.has(packageName)) {\n await skipDependencyDocumentation(packageName);\n logOperationSuccess('Dependencies documented');\n return;\n }\n\n await clearDirectory('1️⃣ Clear downloaded licenses', 'licenses/downloads');\n const lockPackages = await readLockPackages();\n const shippedRecord = await readShippedRecord();\n\n if (shippedRecord === null) {\n // No build record, such as for a project not built with Vite: fall back to the declared dependencies.\n const unshippedPackages = listUnshippedPackages(lockPackages);\n await checkLicenses('2️⃣ Identify production licenses', allowedLicenses, [rootPackage.name ?? '', ...unshippedPackages], true);\n await spawnCommandToFile('3️⃣ Identify transitive dependencies', 'npm', ['ls', '--all', '--json', '--omit=dev'], LICENSE_TREE_PATH);\n await insertDeclaredLicensesIntoReadme('4️⃣ ', allowedLicenses, new Set(unshippedPackages));\n } else {\n const shippedKeys = collectShippedKeys(shippedRecord, lockPackages);\n const installedKeys = listInstalledKeys(lockPackages);\n const notShipped = installedKeys.filter((packageKey) => !shippedKeys.has(packageKey));\n // Not limited to production dependencies: a package listed for development, such as an icon set, still ships\n // when the build bundles it.\n await checkLicenses('2️⃣ Identify shipped licenses', allowedLicenses, [rootPackage.name ?? '', ...notShipped], false);\n warnOfMissingPackages(shippedKeys, new Set(installedKeys));\n // The whole installed tree, as a shipped package may be listed for development. Problems npm reports in the\n // development tools' part of it do not stop the tree being written.\n await spawnCommandToFile('3️⃣ Identify transitive dependencies', 'npm', ['ls', '--all', '--json'], LICENSE_TREE_PATH, true);\n const rustCrates = await documentRustCrates('4️⃣ Identify Rust crates compiled into the WebAssembly', allowedLicenses);\n const readmeContext = { allowedLicenses, productionNames: listProductionNames(rootPackage), rustCrates, shippedKeys };\n await insertShippedLicensesIntoReadme(rustCrates === null ? '4️⃣ ' : '5️⃣ ', readmeContext);\n }\n\n logOperationSuccess('Dependencies documented');\n } catch (error) {\n console.error('❌ Error documenting dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function skipDependencyDocumentation(name: string): Promise<void> {\n logStepHeader(`1️⃣ Skip: ${name} is a development-only tool and is never part of a production release.`);\n\n const message = `> [!WARNING]\\n> Dependency licenses are not documented here: ${name} is a development-only tool and is never part of a production release.`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${message}`, START_MARKER, END_MARKER);\n}\n\nasync function insertDeclaredLicensesIntoReadme(stepIcon: string, allowedLicenses: string, unshippedPackages: Set<string>): Promise<void> {\n logStepHeader(`${stepIcon} Insert licenses into 'README.md'`);\n\n const licenseTree = await readJSONFile<NpmPackageTree>(LICENSE_TREE_PATH);\n const licensesByKey = await readLicenses();\n\n const licensesIntro = buildLicensesIntro(allowedLicenses, false);\n let licensesContent = `${licensesIntro}\\n\\n|Dependency|Version|License(s)|Document|\\n|:-|:-:|:-|:-|\\n`;\n for (const license of licensesByKey.values()) {\n licensesContent += formatLicenseRow(license);\n }\n\n const treeItems: string[] = [];\n if (licenseTree.dependencies != null) {\n walkTreeList(licenseTree.dependencies, licensesByKey, unshippedPackages, treeItems, 0);\n }\n const treeContent = `${DEPENDENCY_TREE_INTRO}\\n\\n${treeItems.join('\\n')}`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${licensesContent.trimEnd()}\\n\\n### Dependency Tree\\n\\n${treeContent}`, START_MARKER, END_MARKER);\n}\n\n// A table of exactly what the build ships, and the tree showing how each package is reached, with its release. Where\n// the project has Rust code, the table gains a Type column and lists the npm packages before the Rust crates, and the\n// tree is split in two, as neither kind of dependency can reach the other.\nasync function insertShippedLicensesIntoReadme(stepIcon: string, context: ShippedReadmeContext): Promise<void> {\n logStepHeader(`${stepIcon} Insert licenses into 'README.md'`);\n\n const { allowedLicenses, productionNames, rustCrates, shippedKeys } = context;\n const licensesByKey = await readLicenses();\n const crateLicensesByKey = new Map((rustCrates?.crates ?? []).map((crate) => [`${crate.name}@${crate.version}`, convertCrateToLicense(crate)]));\n const hasRustCrates = rustCrates !== null;\n const tableHeader = hasRustCrates ? '|Type|Dependency|Version|License(s)|Document|\\n|:-|:-|:-:|:-|:-|' : '|Dependency|Version|License(s)|Document|\\n|:-|:-:|:-|:-|';\n let licensesContent = `${buildLicensesIntro(allowedLicenses, true, hasRustCrates)}\\n\\n${tableHeader}\\n`;\n for (const license of licensesByKey.values().toArray().toSorted(compareLicenses)) {\n licensesContent += formatLicenseRow(license, hasRustCrates ? 'JavaScript' : undefined);\n }\n for (const license of crateLicensesByKey.values().toArray().toSorted(compareLicenses)) {\n licensesContent += formatLicenseRow(license, 'Rust');\n }\n\n // Production dependencies first, so a package reached both ways is placed under the one that ships it.\n const licenseTree = await readJSONFile<NpmPackageTree>(LICENSE_TREE_PATH);\n const rootEntries = Object.entries(licenseTree.dependencies ?? {}).toSorted(([a], [b]) => Number(!productionNames.has(a)) - Number(!productionNames.has(b)));\n const treeItems: string[] = [];\n walkShippedTree(rootEntries, { licensesByKey, shippedKeys, shownKeys: new Set() }, treeItems, 0, false);\n const javaScriptTree = treeItems.length === 0 ? 'None.' : treeItems.join('\\n');\n const rustTree = (rustCrates?.treeItems ?? []).map((item) => formatCrateTreeItem(item, crateLicensesByKey)).join('\\n');\n const treeContent = hasRustCrates ? `${SHIPPED_TREE_INTRO}\\n\\n#### JavaScript\\n\\n${javaScriptTree}\\n\\n#### Rust\\n\\n${rustTree}` : `${SHIPPED_TREE_INTRO}\\n\\n${javaScriptTree}`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${licensesContent.trimEnd()}\\n\\n### Dependency Tree\\n\\n${treeContent}`, START_MARKER, END_MARKER);\n}\n\nfunction compareLicenses(a: License, b: License): number {\n return a.name.localeCompare(b.name, 'en') || a.installedVersion.localeCompare(b.installedVersion, 'en');\n}\n\nfunction convertCrateToLicense(crate: RustCrate): License {\n return {\n name: crate.name,\n repository: crate.repository,\n licenseTypes: crate.licenseExpression,\n installedVersion: crate.version,\n latestVersion: crate.latestVersion,\n latestPublishedDate: crate.latestPublishedDate,\n author: '',\n publishedDate: crate.publishedDate,\n licenseFiles: crate.licenseFiles\n };\n}\n\n// The project's own crates head their part of the tree; they are this project's code, so have no licence row.\nfunction formatCrateTreeItem(item: RustCrateTreeItem, crateLicensesByKey: Map<string, License>): string {\n const indent = ' '.repeat(item.depth);\n return item.isOwn\n ? `${indent}- **${item.name}** ${item.version} — this project's Rust code, compiled into its WebAssembly`\n : formatTreeItem(item.name, item.version, crateLicensesByKey.get(`${item.name}@${item.version}`), indent);\n}\n\nfunction listProductionNames(rootPackage: RootPackage): Set<string> {\n return new Set([...Object.keys(rootPackage.dependencies ?? {}), ...Object.keys(rootPackage.optionalDependencies ?? {}), ...Object.keys(rootPackage.peerDependencies ?? {})]);\n}\n\nasync function readLicenses(): Promise<Map<string, License>> {\n const licenses = await readJSONFile<Record<string, ProductionPackageLicense>>('licenses/licenses.json');\n const licensesByKey = new Map<string, License>();\n for (const [key, value] of Object.entries(licenses)) {\n licensesByKey.set(key, parseLicenseEntry(key, value));\n }\n await Promise.all(\n licensesByKey.values().map(async (license) => {\n const data = await fetchNpmData(license.name, license.installedVersion);\n license.latestVersion = data.latestVersion;\n license.latestPublishedDate = data.latestPublishedDate;\n license.publishedDate = data.publishedDate;\n })\n );\n return licensesByKey;\n}\n\nasync function checkLicenses(stepLabel: string, allowedLicenses: string, excludedKeys: string[], isProductionOnly: boolean): Promise<void> {\n logStepHeader(stepLabel);\n await new Promise<void>((resolve, reject) => {\n const options: InitOpts & { files: string; relativeModulePath: boolean } = {\n start: process.cwd(),\n production: isProductionOnly,\n json: true,\n files: 'licenses/downloads',\n relativeModulePath: true,\n relativeLicensePath: true,\n onlyAllow: allowedLicenses,\n excludePackages: excludedKeys.join(';'),\n out: 'licenses/licenses.json'\n };\n initLicenseChecker(options, (error: Error | undefined) => {\n if (error == null) {\n resolve();\n } else {\n reject(error);\n }\n });\n });\n}\n\nasync function readLockPackages(): Promise<Record<string, PackageLockEntry>> {\n const lockText = await readTextFileOrNull('package-lock.json');\n return lockText === null ? {} : ((JSON.parse(lockText) as PackageLock).packages ?? {});\n}\n\nasync function readShippedRecord(): Promise<ShippedPackagesRecord | null> {\n const recordText = await readTextFileOrNull(SHIPPED_PACKAGES_RECORD_PATH);\n return recordText === null ? null : (JSON.parse(recordText) as ShippedPackagesRecord);\n}\n\n// The recorded packages, plus each package the build leaves to be installed by name, with whatever that one brings.\nfunction collectShippedKeys(record: ShippedPackagesRecord, lockPackages: Record<string, PackageLockEntry>): Set<string> {\n const shippedKeys = new Set(record.packages);\n for (const externalName of record.external) {\n const lockPath = resolveLockPath(lockPackages, '', externalName);\n if (lockPath === undefined) continue;\n for (const shippedPath of [lockPath, ...findShippedPaths(lockPackages, lockPath)]) {\n const entry = lockPackages[shippedPath];\n if (entry?.version !== undefined) shippedKeys.add(formatPackageKey(shippedPath, entry));\n }\n }\n return shippedKeys;\n}\n\nfunction listInstalledKeys(lockPackages: Record<string, PackageLockEntry>): string[] {\n const installedKeys = new Set<string>();\n for (const [lockPath, entry] of Object.entries(lockPackages)) {\n if (lockPath !== '' && entry.version !== undefined) installedKeys.add(formatPackageKey(lockPath, entry));\n }\n return [...installedKeys];\n}\n\n// A recorded package that is not installed means the record is from an older build, so its licence goes unchecked.\nfunction warnOfMissingPackages(shippedKeys: Set<string>, installedKeys: Set<string>): void {\n const missingKeys = [...shippedKeys.difference(installedKeys)];\n if (missingKeys.length > 0) console.warn(`⚠️ Not installed, so not checked; rebuild to refresh the record: ${missingKeys.join(', ')}`);\n}\n\nfunction formatPackageKey(lockPath: string, entry: PackageLockEntry): string {\n const name = entry.name ?? lockPath.slice(lockPath.lastIndexOf('node_modules/') + 'node_modules/'.length);\n return `${name}@${String(entry.version)}`;\n}\n\n// Packages installed but never shipped, as 'name@version'. A package ships when the project's own dependencies reach it\n// through dependencies, optional dependencies or required peers. Optional peers are not followed: TypeScript as\n// valibot's optional peer, or Vite as vue-router's, is installed only because a development tool needs it. The tree is\n// walked rather than npm's 'dev' flags trusted, as npm marks some packages under a development-only one as merely\n// 'optional', such as lightningcss's platform binary under Vite. The licence checker follows every link, so without\n// this it would count such packages as shipped. A package also installed, at the same version, for a shipped reason is kept.\nfunction listUnshippedPackages(lockPackages: Record<string, PackageLockEntry>): string[] {\n const shippedPaths = findShippedPaths(lockPackages, '');\n const shipped = new Set<string>();\n const unshipped = new Set<string>();\n for (const [lockPath, entry] of Object.entries(lockPackages)) {\n if (lockPath === '' || entry.version === undefined) continue;\n const packageKey = formatPackageKey(lockPath, entry);\n if (shippedPaths.has(lockPath)) shipped.add(packageKey);\n else unshipped.add(packageKey);\n }\n return unshipped\n .values()\n .filter((packageKey) => !shipped.has(packageKey))\n .toArray();\n}\n\n// The lock file paths reached from a starting entry, the project's own by default, following the links that ship with a package.\nfunction findShippedPaths(packages: Record<string, PackageLockEntry>, startPath: string): Set<string> {\n const shippedPaths = new Set<string>();\n const pendingPaths = [startPath];\n while (pendingPaths.length > 0) {\n const fromPath = pendingPaths.pop() ?? '';\n const entry = packages[fromPath];\n if (entry === undefined) continue;\n for (const name of listShippedDependencyNames(entry)) {\n const lockPath = resolveLockPath(packages, fromPath, name);\n if (lockPath === undefined || shippedPaths.has(lockPath)) continue;\n shippedPaths.add(lockPath);\n pendingPaths.push(lockPath);\n }\n }\n return shippedPaths;\n}\n\nfunction listShippedDependencyNames(entry: PackageLockEntry): string[] {\n const requiredPeerNames = Object.keys(entry.peerDependencies ?? {}).filter((name) => entry.peerDependenciesMeta?.[name]?.optional !== true);\n return [...Object.keys(entry.dependencies ?? {}), ...Object.keys(entry.optionalDependencies ?? {}), ...requiredPeerNames];\n}\n\n// Finds a dependency where Node would: in the package's own 'node_modules', then in each enclosing one up to the\n// project's. A linked package, such as a workspace, resolves to the folder it links to.\nfunction resolveLockPath(packages: Record<string, PackageLockEntry>, fromPath: string, name: string): string | undefined {\n let basePath = fromPath;\n for (;;) {\n const candidatePath = basePath === '' ? `node_modules/${name}` : `${basePath}/node_modules/${name}`;\n const entry = packages[candidatePath];\n if (entry !== undefined) return entry.link === true && entry.resolved !== undefined ? entry.resolved : candidatePath;\n if (basePath === '') return undefined;\n const parentIndex = basePath.lastIndexOf('/node_modules/');\n basePath = parentIndex === -1 ? '' : basePath.slice(0, parentIndex);\n }\n}\n\nfunction buildLicensesIntro(allowedLicenses: string, isFromBuild: boolean, hasRustCrates = false): string {\n const licenseListText = formatLicenseListText(allowedLicenses.split(';'));\n const tools = hasRustCrates\n ? '[license-checker](https://github.com/RSeidelsohn/license-checker-rseidelsohn) and [cargo tree](https://doc.rust-lang.org/cargo/commands/cargo-tree.html)'\n : '[license-checker](https://github.com/RSeidelsohn/license-checker-rseidelsohn)';\n const buildScope =\n \"The following table lists every package whose code, styles or assets are included in this project's build, as recorded by the build itself. Modules loaded at run time are not included; each documents its own.\";\n const rustScope =\n ' It also lists every Rust crate compiled into its WebAssembly, as resolved by Cargo; macros and other crates used only while compiling put none of their code in it, so are left out.';\n const fromBuildScope = hasRustCrates ? `${buildScope}${rustScope}` : buildScope;\n const scope = isFromBuild\n ? fromBuildScope\n : 'The following table lists all production dependencies. This project has no build record, so the list is taken from its declared dependencies.';\n return `License data is updated each time \\`npm run document\\` is run, using ${tools}. ${scope} These dependencies have been checked and confirmed to use ${licenseListText}, all of which allow commercial use. All are used unmodified, so any licence conditions that apply only to modified versions are not triggered. Developers cloning this repository should independently verify development dependencies.`;\n}\n\nfunction formatLicenseListText(licenses: string[]): string {\n if (licenses.length === 1) return licenses[0] ?? '';\n return licenses.length === 2 ? `${String(licenses[0])} or ${String(licenses[1])}` : `${licenses.slice(0, -1).join(', ')}, or ${String(licenses.at(-1))}`;\n}\n\nfunction parseLicenseEntry(key: string, value: ProductionPackageLicense): License {\n const lastAt = key.lastIndexOf('@');\n const name = lastAt > 0 ? key.slice(0, lastAt) : key;\n const installedVersion = lastAt > 0 ? key.slice(lastAt + 1) : '';\n return {\n name,\n repository: value.repository ?? `https://www.npmjs.com/package/${name}`,\n licenseTypes: value.licenses,\n installedVersion,\n author: value.publisher ?? '',\n latestVersion: '',\n latestPublishedDate: '',\n publishedDate: '',\n licenseFiles: value.licenseFile == null ? [] : [{ label: 'LICENSE', path: value.licenseFile }]\n };\n}\n\nasync function fetchNpmData(name: string, version: string): Promise<{ latestVersion: string; latestPublishedDate: string; publishedDate: string }> {\n try {\n const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`);\n if (response.ok) {\n const data = (await response.json()) as { 'dist-tags'?: Record<string, string>; time?: Record<string, string> };\n const distributionTags = new Map(Object.entries(data['dist-tags'] ?? {}));\n const timeMap = new Map(Object.entries(data.time ?? {}));\n const latestVersion = distributionTags.get('latest') ?? '';\n const publishedDate = timeMap.get(version) ?? '';\n const latestPublishedDate = latestVersion === version ? '' : (timeMap.get(latestVersion) ?? '');\n return { latestVersion, latestPublishedDate, publishedDate };\n }\n } catch {\n // Ignore network errors.\n }\n return { latestVersion: '', latestPublishedDate: '', publishedDate: '' };\n}\n\n// The type, 'JavaScript' or 'Rust', is only given where the table holds both.\nfunction formatLicenseRow(license: License, typeLabel?: string): string {\n const licenseLink =\n license.licenseFiles.length === 0 ? '⚠️ No license file' : license.licenseFiles.map((licenseFile) => `[${licenseFile.label}](licenses/${licenseFile.path})`).join(' ');\n const typeCell = typeLabel === undefined ? '' : `|${typeLabel}`;\n return `${typeCell}|[${license.name}](${license.repository})|${license.installedVersion}|${license.licenseTypes}|${licenseLink}|\\n`;\n}\n\nfunction walkTreeList(dependencies: Record<string, NpmPackageTree>, licensesByKey: Map<string, License>, unshippedPackages: Set<string>, items: string[], depth: number): void {\n const indent = ' '.repeat(depth);\n for (const [name, node] of Object.entries(dependencies)) {\n // npm lists optional peers that nothing installs, such as '@opentelemetry/api' for '@tanstack/ai', with no version.\n if (node.version === undefined) continue;\n const version = node.version;\n if (unshippedPackages.has(`${name}@${version}`)) continue;\n items.push(formatTreeItem(name, version, licensesByKey.get(`${name}@${version}`), indent));\n if (node.dependencies != null) {\n walkTreeList(node.dependencies, licensesByKey, unshippedPackages, items, depth + 1);\n }\n }\n}\n\n// Lists each shipped package where it is reached. A package that does not ship, such as 'vue' whose '@vue/*' parts are\n// bundled, or a development tool, is passed over and what ships beneath it is listed in its place. A package reached\n// that way is listed once only, as it is already listed wherever a shipped package reaches it.\nfunction walkShippedTree(entries: [string, NpmPackageTree][], context: ShippedTreeContext, items: string[], depth: number, isPassedOver: boolean): void {\n for (const [name, node] of entries) {\n if (node.version === undefined) continue;\n const packageKey = `${name}@${node.version}`;\n const childEntries = Object.entries(node.dependencies ?? {});\n if (!context.shippedKeys.has(packageKey)) {\n walkShippedTree(childEntries, context, items, depth, true);\n continue;\n }\n if (isPassedOver && context.shownKeys.has(packageKey)) continue;\n context.shownKeys.add(packageKey);\n items.push(formatTreeItem(name, node.version, context.licensesByKey.get(packageKey), ' '.repeat(depth)));\n walkShippedTree(childEntries, context, items, depth + 1, false);\n }\n}\n\nfunction formatTreeItem(name: string, version: string, license: License | undefined, indent: string): string {\n const nameLink = license == null ? name : `[${name}](${license.repository})`;\n return `${indent}- **${nameLink}** ${version}${formatVersionDetail(license)}`;\n}\n\nfunction formatVersionDetail(license: License | undefined): string {\n if (license == null) return '';\n const published = license.publishedDate ? determineLatestAge(license.publishedDate.split('T', 1)[0]) : '';\n const isOutdated = license.latestVersion !== '' && license.latestVersion !== license.installedVersion;\n if (!isOutdated) return published === '' ? '' : ` — ${published}`;\n const latestAge = license.latestPublishedDate ? determineLatestAge(license.latestPublishedDate.split('T', 1)[0]) : '';\n const latestClause = latestAge === '' ? `latest: ${license.latestVersion} ❗` : `latest: ${license.latestVersion} — ${latestAge} ❗`;\n return published === '' ? ` — → ${latestClause}` : ` — ${published} → ${latestClause}`;\n}\n\nfunction determineLatestAge(momentString?: string): string {\n if (momentString == null || momentString === '') return 'n/a';\n\n const dateString = momentString.split('T', 1)[0];\n if (dateString == null || dateString === '') return 'n/a';\n\n const input = new Date(dateString);\n const now = new Date();\n let months = (now.getFullYear() - input.getFullYear()) * 12 + (now.getMonth() - input.getMonth());\n if (now.getDate() < input.getDate()) months -= 1;\n\n if (months === 0) return `this month: ${dateString}`;\n if (months === 1) return `1 mth ago: ${dateString}`;\n return months <= 6 ? `${String(months)} mths ago: ${dateString}` : `${String(months)} mths ago: ${dateString} ⚠️`;\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, resolveOwnerAndRepository, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- OPENING_START -->';\nconst END_MARKER = '<!-- OPENING_END -->';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentOpening(): Promise<void> {\n try {\n logOperationHeader('Document Opening');\n\n logStepHeader(\"1️⃣ Insert opening content into 'README.md'\");\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n\n const { owner, repository } = resolveOwnerAndRepository(packageJSON, 'document opening');\n const license = resolveLicense(packageJSON);\n const introduction = resolveIntroduction(configJSON);\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n const dpuseModuleId = moduleTypeConfig.uploadGroupName === undefined ? undefined : configJSON.id;\n const npmPackageName = moduleTypeConfig.publishedTo === 'npm' ? resolvePackageName(packageJSON) : undefined;\n\n const content = buildOpeningContent(owner, repository, license, {\n description: packageJSON.description,\n dpuseModuleId,\n introduction,\n npmPackageName,\n version: packageJSON.version\n });\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Opening documented');\n } catch (error) {\n console.error('❌ Error documenting opening', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Shields colours the npm badge by version, but a badge reading JSON can only take a fixed colour, so the DPUse badge is\n// given the one Shields would pick, as of this release: orange before 1.0 or for a pre-release, blue otherwise.\nfunction resolveVersionColor(version: string | undefined): string {\n if (version === undefined) return 'blue';\n return /^v?0/.test(version) || /alpha|beta|snapshot|dev|pre|rc/i.test(version) ? 'orange' : 'blue';\n}\n\nfunction resolveLicense(packageJSON: PackageJson): string {\n const license = packageJSON.license;\n if (license == null || license === '') throw new Error(\"package.json 'license' field is required to document opening.\");\n return license;\n}\n\nfunction resolvePackageName(packageJSON: PackageJson): string {\n const name = packageJSON.name;\n if (name == null || name === '') throw new Error(\"package.json 'name' field is required to document opening.\");\n return name;\n}\n\n// 'description.en' holds the introduction as one string, with a blank line between paragraphs. With none, the\n// Introduction section is left out.\nfunction resolveIntroduction(configJSON: ModuleConfig): string | undefined {\n const introduction = configJSON.description.en?.trim();\n return introduction === undefined || introduction === '' ? undefined : introduction;\n}\n\n// The package description is optional, so a project without one simply has no summary between the badges and the links.\n// Only modules uploaded to DPUse get the DPUse version badge, and only projects published to npm get the npm badge. The\n// DPUse badge reads the version registered in DPUse, which is only updated once the upload succeeds, so like the npm\n// badge it shows what was actually published, and it works for private repositories too.\nfunction buildOpeningContent(\n owner: string,\n repository: string,\n license: string,\n options: {\n description: string | undefined;\n dpuseModuleId: string | undefined;\n introduction: string | undefined;\n npmPackageName: string | undefined;\n version: string | undefined;\n }\n): string {\n const { description, dpuseModuleId, introduction, npmPackageName, version } = options;\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n const badgeLicense = license.replaceAll('-', '--');\n const dpuseConfigURL = encodeURIComponent(`https://api.dpuse.app/configs/${dpuseModuleId ?? ''}`);\n const dpuseBadge =\n dpuseModuleId === undefined\n ? ''\n : `\\n[})](${repositoryURL}/releases/latest)`;\n const npmBadge =\n npmPackageName === undefined ? '' : `\\n[](https://www.npmjs.com/package/${npmPackageName})`;\n const summary = description == null || description === '' ? '' : `\\n\\n${description}`;\n const introductionSection = introduction === undefined ? '' : `\\n\\n## Introduction\\n\\n${introduction}`;\n\n return `[](./LICENSE)${dpuseBadge}${npmBadge}\n[](${repositoryURL}/actions/workflows/ci.yml)${summary}\n\n[Report a Vulnerability](${repositoryURL}/security/advisories/new) · [Open an Issue](${repositoryURL}/issues)\n\n## About DPUse\n\n[DPUse](https://www.dpuse.app) (Data Positioning & Use) is an in-browser application that positions your data for use through three core activities: sourcing, contextualising, and publishing.\n\n**Sourcing** uses a library of [Connectors](https://www.dpuse.app/connectors) to establish [Connections](https://www.dpuse.app) to applications, databases, file stores, and curated datasets; these connections are subsequently used to configure structured [Data Views](https://www.dpuse.app) from the underlying sources.\n\n**Contextualising** extracts chronological events from those [Data Views](https://www.dpuse.app) and maps them into comprehensive [Context Models](https://www.dpuse.app). This gives the DPUse Engine the structural framework needed to generate deterministic transactions, facts, or observations.\n\n**Publishing** uses a library of [Presenters](https://www.dpuse.app) to render standard [Presentations](https://www.dpuse.app) immediately using the contextualised data; additionally, [Cookbooks](https://www.dpuse.app) of [Recipes](https://www.dpuse.app) let you build Data Apps using your preferred tools.\n\nIn addition, DPUse provides [Tools](https://www.dpuse.app) used by the application, and you can use them to construct connectors and presenters.${introductionSection}`;\n}\n","// ── External Dependencies & Registrations\nimport { execFile } from 'node:child_process';\nimport type { PackageJson } from 'type-fest';\nimport { promisify } from 'node:util';\n\n// ── Local Framework\nimport {\n FALLOW_BADGE_PATH,\n FALLOW_DIRECTORY,\n FALLOW_REPORT_PATH,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n QUALITY_SECURITY_END_MARKER,\n QUALITY_SECURITY_START_MARKER,\n readJSONFile,\n readTextFileOrNull,\n resolveOwnerAndRepository,\n RUST_WORKSPACE_PATH,\n spawnCommand,\n spawnCommandToFile,\n writeJSONFile,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface BestPracticesProject {\n id: number;\n repo_url: string;\n}\n\ninterface CoverageSummary {\n total: { lines: { pct: number | 'Unknown' } }; // 'Unknown' when there is no code to measure, such as a project with no 'src'.\n}\n\ninterface FallowHealth {\n health_score: { score: number; grade: string };\n}\n\ninterface GitHubCheckRuns {\n check_runs: { app: { slug: string } | null }[];\n}\n\ninterface GitHubRepositoryDetails {\n security_and_analysis?: Record<string, { status: string } | undefined>;\n}\n\ninterface ScorecardResult {\n checks: { name: string; score: number }[];\n}\n\n// Everything the checks tables report on, gathered before the README is written.\ninterface ChecksResults {\n coveragePercent: number | undefined;\n fallowHealth: FallowHealth | undefined;\n securitySettings: SecuritySettings;\n}\n\n// On or off, or undefined where GitHub doesn't reveal the setting (some need an admin login to read).\ntype SettingStatus = boolean | undefined;\n\ninterface SecuritySettings {\n codeQLLanguages: string[];\n codeQLQueries: string | undefined; // The query suite CodeQL is told to run; without one, it runs its default suite.\n dependabotAlerts: SettingStatus;\n dependabotSecurityUpdates: SettingStatus;\n dependabotVersionUpdates: boolean;\n lintInCI: boolean;\n npmAuditInCI: boolean;\n npmAuditLevel: string | undefined; // The '--audit-level' CI passes; without one, npm audit fails on any severity.\n privateVulnerabilityReporting: SettingStatus;\n propertyTests: boolean;\n pushProtection: SettingStatus;\n secretScanning: SettingStatus;\n socket: boolean;\n sonarCloud: boolean;\n testsInCI: boolean;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Scorecard checks a solo maintainer pushing straight to 'main' can't raise, with the best score each can reach that way.\nconst SCORECARD_PRACTICE_LIMITS: Record<string, number> = { 'Branch-Protection': 3, 'Code-Review': 0, Contributors: 0 };\n// Left out when deciding whether gaps remain: the Best Practices badge shows its own progress in the same section.\nconst SCORECARD_IGNORED_CHECKS = new Set(['CII-Best-Practices']);\n\n// Coverage — only measured where the module has the Vitest coverage provider installed. 'coverage-final.json' feeds\n// Fallow's per-function scores; the summary holds the totals the Testing table reports.\nconst COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';\nconst COVERAGE_SUMMARY_PATH = 'coverage/coverage-summary.json';\nconst COVERAGE_TARGET_PERCENT = 80;\nconst COVERAGE_WARNING_PERCENT = 60; // Below the target the badge turns yellow, and below this it turns red.\nconst COVERAGE_BADGE_PATH = 'code-health-reports/vitest/badge.json'; // Not under a 'coverage' folder, which '.gitignore' leaves out.\n\nconst CODEQL_LANGUAGE_NAMES: Record<string, string> = { actions: 'GitHub Actions', 'javascript-typescript': 'JavaScript/TypeScript', rust: 'Rust' };\n\n// Fallow — only run where the module has it installed. The full report is published as its own page, linked from the\n// README; the Code Quality row and the badge are both built from the one health run, so they always agree.\nconst FALLOW_GRADE_COLOURS: Record<string, string> = { A: 'brightgreen', B: 'green', C: 'yellow', D: 'orange', F: 'red' };\nconst FALLOW_HEALTH_PATH = `${FALLOW_DIRECTORY}/health.json`;\n\n// ── Initialisation ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst asyncExecFile = promisify(execFile);\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Quality & Security section: testing, code quality, security analysis, dependencies and OpenSSF. */\nexport async function documentQualitySecurity(): Promise<void> {\n try {\n logOperationHeader('Document Quality & Security');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n\n const coveragePercent = await measureTestCoverage(packageJSON);\n const fallowHealth = await measureCodeHealth(packageJSON, coveragePercent === undefined ? [] : ['--coverage', COVERAGE_FINAL_PATH]);\n\n const { owner, repository } = resolveOwnerAndRepository(packageJSON, 'document quality and security');\n\n logStepHeader('4️⃣ Read security checks and settings');\n const securitySettings = await readSecuritySettings(owner, repository, packageJSON);\n\n logStepHeader('5️⃣ Look up OpenSSF Best Practices badge and Scorecard results');\n const [bestPracticesProjectId, scorecardResult] = await Promise.all([\n lookUpBestPracticesProjectId(`https://github.com/${owner}/${repository}`),\n lookUpScorecardResult(`github.com/${owner}/${repository}`)\n ]);\n\n logStepHeader(\"6️⃣ Insert quality and security content into 'README.md'\");\n const content = buildQualitySecurityContent(owner, repository, { coveragePercent, fallowHealth, securitySettings }, bestPracticesProjectId, scorecardResult);\n\n await migrateGovernanceSection();\n await writeReadmeSection(content, QUALITY_SECURITY_START_MARKER, QUALITY_SECURITY_END_MARKER);\n\n logOperationSuccess('Quality & security documented');\n } catch (error) {\n console.error('❌ Error documenting quality and security', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Answers undefined where the coverage provider isn't installed, the Vitest config doesn't write a coverage summary, or\n// there is no code to measure.\nasync function measureTestCoverage(packageJSON: PackageJson): Promise<number | undefined> {\n if (packageJSON.devDependencies?.['@vitest/coverage-v8'] == null) {\n logStepHeader(\"1️⃣ Test coverage NOT measured, as '@vitest/coverage-v8' is not installed\");\n return undefined;\n }\n\n await spawnCommand('1️⃣ Measure test coverage', 'vitest', ['run', '--passWithNoTests', '--coverage']);\n const summary = await readTextFileOrNull(COVERAGE_SUMMARY_PATH);\n if (summary === null) return undefined;\n\n const coveragePercent = (JSON.parse(summary) as CoverageSummary).total.lines.pct;\n if (coveragePercent === 'Unknown') return undefined;\n await writeCoverageBadge(coveragePercent);\n return coveragePercent;\n}\n\n// Written in the shields.io endpoint format, like the Fallow badge, so the README shows the latest pushed figure.\nasync function writeCoverageBadge(coveragePercent: number): Promise<void> {\n const colourNames = ['red', 'yellow', 'brightgreen'];\n const level = Number(coveragePercent >= COVERAGE_WARNING_PERCENT) + Number(coveragePercent >= COVERAGE_TARGET_PERCENT);\n await writeJSONFile(COVERAGE_BADGE_PATH, { schemaVersion: 1, label: 'coverage', message: `${coveragePercent.toFixed(1)}%`, color: colourNames[level] });\n}\n\n// Fallow exits non-zero whenever it has findings, so its exit code is ignored: the findings are what gets reported.\nasync function measureCodeHealth(packageJSON: PackageJson, coverageArguments: string[]): Promise<FallowHealth | undefined> {\n if (packageJSON.devDependencies?.['fallow'] == null) {\n logStepHeader('2️⃣ Code health NOT measured, as Fallow is not installed');\n logStepHeader('3️⃣ Code health report NOT required');\n return undefined;\n }\n\n await spawnCommandToFile('2️⃣ Measure code health', 'fallow', ['health', '--report-only', '--format', 'json', ...coverageArguments], FALLOW_HEALTH_PATH);\n await spawnCommandToFile('3️⃣ Write code health report', 'fallow', ['--format', 'markdown'], FALLOW_REPORT_PATH, true);\n const health = await readJSONFile<FallowHealth>(FALLOW_HEALTH_PATH);\n await writeFallowBadge(health);\n return health;\n}\n\n// Written in the shields.io endpoint format, so the Code Quality badge shows the latest pushed grade.\nasync function writeFallowBadge(health: FallowHealth): Promise<void> {\n const { score, grade } = health.health_score;\n await writeJSONFile(FALLOW_BADGE_PATH, {\n schemaVersion: 1,\n label: 'fallow',\n message: `${grade} (${String(Math.round(score))})`,\n color: FALLOW_GRADE_COLOURS[grade] ?? 'lightgrey'\n });\n}\n\n// Read from the repository itself each time, so the README states what is actually switched on rather than what was\n// intended. Workflow and Dependabot files are read locally; repository settings come from the GitHub API through 'gh'.\nasync function readSecuritySettings(owner: string, repository: string, packageJSON: PackageJson): Promise<SecuritySettings> {\n const [ciWorkflow, dependabotConfig, rustWorkspace] = await Promise.all([\n readTextFileOrNull('.github/workflows/ci.yml'),\n readTextFileOrNull('.github/dependabot.yml'),\n readTextFileOrNull(RUST_WORKSPACE_PATH)\n ]);\n const codeQLWorkflow = (await readTextFileOrNull('.github/workflows/codeql.yml')) ?? ''; // Empty when missing, so CodeQL reads as off.\n const [repositoryDetails, privateVulnerabilityReporting, vulnerabilityAlerts, checkRuns] = await Promise.all([\n readGitHubAPI(`repos/${owner}/${repository}`),\n readGitHubAPI(`repos/${owner}/${repository}/private-vulnerability-reporting`),\n readGitHubAPI(`repos/${owner}/${repository}/vulnerability-alerts`),\n readGitHubAPI(`repos/${owner}/${repository}/commits/main/check-runs?per_page=100`)\n ]);\n\n const securityAndAnalysis = repositoryDetails === undefined ? undefined : (JSON.parse(repositoryDetails) as GitHubRepositoryDetails).security_and_analysis;\n const readSetting = (name: string): SettingStatus => (securityAndAnalysis?.[name] === undefined ? undefined : securityAndAnalysis[name].status === 'enabled');\n const checkAppSlugs = new Set((checkRuns === undefined ? [] : (JSON.parse(checkRuns) as GitHubCheckRuns).check_runs).map((checkRun) => checkRun.app?.slug));\n\n // Version updates count as off when every ecosystem is limited to 0 pull requests, the documented way to pause them.\n const ecosystemCount = dependabotConfig?.match(/package-ecosystem:/g)?.length ?? 0;\n const pausedEcosystemCount = dependabotConfig?.match(/open-pull-requests-limit: 0\\b/g)?.length ?? 0;\n\n return {\n codeQLLanguages: codeQLWorkflow\n .matchAll(/- language: ([\\w-]+)/g)\n .filter(([, language]) => language !== 'rust' || rustWorkspace !== null) // The workflow lists Rust for every project, but skips its scan where there is none.\n .map(([, language = '']) => CODEQL_LANGUAGE_NAMES[language] ?? language)\n .toArray(),\n codeQLQueries: /queries: ([\\w-]+)/.exec(codeQLWorkflow)?.[1],\n dependabotAlerts: vulnerabilityAlerts !== undefined, // Answers '204 No Content' when on and '404' when off.\n dependabotSecurityUpdates: readSetting('dependabot_security_updates'),\n dependabotVersionUpdates: ecosystemCount > pausedEcosystemCount,\n lintInCI: (ciWorkflow ?? '').includes('npm run lint'),\n npmAuditInCI: /npm (?:run )?audit/.test(ciWorkflow ?? ''),\n npmAuditLevel: /npm audit --audit-level=(\\w+)/.exec(ciWorkflow ?? '')?.[1],\n privateVulnerabilityReporting: privateVulnerabilityReporting === undefined ? undefined : (JSON.parse(privateVulnerabilityReporting) as { enabled: boolean }).enabled,\n propertyTests: packageJSON.devDependencies?.['fast-check'] != null,\n pushProtection: readSetting('secret_scanning_push_protection'),\n secretScanning: readSetting('secret_scanning'),\n socket: checkAppSlugs.has('socket-security'),\n sonarCloud: checkAppSlugs.has('sonarqubecloud'),\n testsInCI: ciWorkflow?.includes('npm test') ?? false\n };\n}\n\n// Answers undefined for a 404, which is how some endpoints report a switched-off feature. Any other failure throws, so a\n// missing login or network blip can't be written into the README as settings being off.\nasync function readGitHubAPI(endpoint: string): Promise<string | undefined> {\n try {\n const { stdout } = await asyncExecFile('gh', ['api', endpoint]);\n return stdout;\n } catch (error) {\n if (String((error as { stderr?: unknown }).stderr).includes('HTTP 404')) return undefined;\n throw error;\n }\n}\n\n// Found by repository URL, as OpenSSF Scorecard does, so a repository shows its badge as soon as it is registered and nothing\n// needs configuring. Failures throw rather than return nothing, so a network blip can't drop the badge from the README.\nasync function lookUpBestPracticesProjectId(repositoryURL: string): Promise<number | undefined> {\n const response = await fetch(`https://www.bestpractices.dev/projects.json?url=${encodeURIComponent(repositoryURL)}`);\n if (!response.ok) throw new Error(`OpenSSF Best Practices lookup failed with status ${String(response.status)}.`);\n\n // The search also matches home page URLs, so keep only the entry registered for this repository.\n const projects = (await response.json()) as BestPracticesProject[];\n return projects.find((project) => project.repo_url === repositoryURL)?.id;\n}\n\n// Answers undefined when Scorecard has no results for the repository yet. Other failures throw, as for the badge.\nasync function lookUpScorecardResult(scorecardURI: string): Promise<ScorecardResult | undefined> {\n const response = await fetch(`https://api.scorecard.dev/projects/${scorecardURI}`);\n if (response.status === 404) return undefined;\n if (!response.ok) throw new Error(`OpenSSF Scorecard lookup failed with status ${String(response.status)}.`);\n return (await response.json()) as ScorecardResult;\n}\n\n// True when every check short of 10 is one the way the project is run caps. A score of -1 means Scorecard couldn't assess\n// the check (e.g. Signed-Releases without release assets), so it isn't counted as a gap.\nfunction isScorecardOnlyPracticeLimited(result: ScorecardResult): boolean {\n return result.checks.every(\n ({ name, score }) =>\n score === -1 || score === 10 || SCORECARD_IGNORED_CHECKS.has(name) || (SCORECARD_PRACTICE_LIMITS[name] !== undefined && score >= SCORECARD_PRACTICE_LIMITS[name])\n );\n}\n\n// Where Dependabot's pull requests are switched off, dependency updates are made by hand.\nfunction formatManualNote(status: SettingStatus): string {\n return status === false ? ' These are handled manually.' : '';\n}\n\nfunction formatStatus(status: SettingStatus): string {\n if (status === undefined) return '❔ Unknown';\n return status ? '✅ On' : '❌ Off';\n}\n\nfunction buildTableContent(heading: string, rows: string[][]): string {\n if (rows.length === 0) return '';\n return `### ${heading}\n\n|Check|Status|What it does|\n|:-|:-|:-|\n${rows.map((row) => `|${row.join('|')}|`).join('\\n')}\n\n`;\n}\n\n// A badge that shields.io draws from a JSON file this action commits, so it shows the latest pushed figure.\nfunction formatEndpointBadge(owner: string, repository: string, label: string, badgePath: string): string {\n const badgeSourceURL = encodeURIComponent(`https://raw.githubusercontent.com/${owner}/${repository}/main/${badgePath}`);\n return ``;\n}\n\n// Grouped by what each check protects against, and within a group in the order the checks act on a change: before a\n// push, on every push, then continuously, and alphabetically within each. Status is only ever on, off or unknown. What\n// it does opens with the check's badge where it has one, shown only while the check is on so a badge is never broken,\n// and names and links the product doing the check.\nfunction buildChecksContent(owner: string, repository: string, { coveragePercent, fallowHealth, securitySettings: settings }: ChecksResults): string {\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n\n const ciNote = (isInCI: boolean): string => (isInCI ? ` Part of the [CI workflow](${repositoryURL}/actions/workflows/ci.yml) on every push and pull request to \\`main\\`.` : '');\n\n const testingRows = [\n ['Unit tests', formatStatus(settings.testsInCI), `[Vitest](https://vitest.dev) runs the unit tests.${ciNote(settings.testsInCI)}`],\n [\n 'Property-based tests',\n formatStatus(settings.propertyTests),\n `[fast-check](https://fast-check.dev) runs many random inputs per test to find edge cases, alongside the unit tests.${ciNote(settings.propertyTests && settings.testsInCI)}`\n ]\n ];\n if (coveragePercent !== undefined) {\n testingRows.push([\n 'Test coverage',\n formatStatus(true),\n `${formatEndpointBadge(owner, repository, 'Coverage', COVERAGE_BADGE_PATH)} [Vitest's V8 coverage](https://vitest.dev/guide/coverage) measures the share of source lines the unit tests run. The target is ${String(COVERAGE_TARGET_PERCENT)}%.`\n ]);\n }\n\n const sonarCloudBadge = `[](https://sonarcloud.io/summary/new_code?id=${owner}_${repository}) `;\n const codeQualityRows = [\n [\n 'Code analysis',\n formatStatus(settings.sonarCloud),\n `${settings.sonarCloud ? sonarCloudBadge : ''}[SonarCloud](https://sonarcloud.io) checks every push for bugs, code smells and vulnerabilities.`\n ],\n ['Linting', formatStatus(settings.lintInCI), `[ESLint](https://eslint.org) checks the code for errors and style problems.${ciNote(settings.lintInCI)}`]\n ];\n // Measured when the README is regenerated, before the changes are pushed, so it comes first.\n if (fallowHealth !== undefined) {\n codeQualityRows.unshift([\n 'Code health',\n formatStatus(true),\n `[${formatEndpointBadge(owner, repository, 'Fallow code health', FALLOW_BADGE_PATH)}](./${FALLOW_REPORT_PATH}) [Fallow](https://github.com/fallow-rs/fallow) finds unused code, duplication, complexity and dependency problems.`\n ]);\n }\n\n const hasCodeQL = settings.codeQLLanguages.length > 0;\n const codeQLBadge = `[](${repositoryURL}/security/code-scanning) `;\n const codeQLScope = settings.codeQLQueries === 'security-extended' ? 'using the extended security queries' : 'using the default queries';\n const codeQLLanguages = hasCodeQL ? ` ${settings.codeQLLanguages.join(' and ')}` : '';\n const securityAnalysisRows = [\n [\n 'Push protection',\n formatStatus(settings.pushProtection),\n '[GitHub push protection](https://docs.github.com/en/code-security/secret-scanning/push-protection-for-repositories-and-organizations) blocks pushes that contain credentials.'\n ],\n [\n 'Static analysis',\n formatStatus(hasCodeQL),\n `${hasCodeQL ? codeQLBadge : ''}[CodeQL](https://codeql.github.com) scans${codeQLLanguages} for security vulnerabilities, ${codeQLScope}, on every push and pull request to \\`main\\` and weekly.`\n ],\n [\n 'Secret scanning',\n formatStatus(settings.secretScanning),\n '[GitHub secret scanning](https://docs.github.com/en/code-security/secret-scanning) detects credentials, such as API keys and tokens, committed to the repository.'\n ]\n ];\n\n const dependabotLink = '[Dependabot](https://docs.github.com/en/code-security/dependabot)';\n const dependencyRows = [\n [\n 'Vulnerability audit',\n formatStatus(settings.npmAuditInCI),\n settings.npmAuditLevel === undefined\n ? `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a shipped dependency has any known vulnerability, or a development dependency has a high or critical one.${ciNote(settings.npmAuditInCI)}`\n : `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a dependency has a known vulnerability of ${settings.npmAuditLevel} severity or above.${ciNote(settings.npmAuditInCI)}`\n ],\n [\n 'Supply chain risk',\n formatStatus(settings.socket), // Socket's badge service refuses requests from outside a browser, so GitHub couldn't show it.\n '[Socket](https://socket.dev) flags malicious packages, typosquatting and suspicious behaviour that may not yet have a CVE.'\n ],\n ['Security alerts', formatStatus(settings.dependabotAlerts), `${dependabotLink} alerts when a dependency has a known vulnerability, using the GitHub Advisory Database.`],\n [\n 'Security updates',\n formatStatus(settings.dependabotSecurityUpdates),\n `${dependabotLink} opens pull requests that update vulnerable dependencies.${formatManualNote(settings.dependabotSecurityUpdates)}`\n ],\n [\n 'Version updates',\n formatStatus(settings.dependabotVersionUpdates),\n `${dependabotLink} opens pull requests for new dependency versions.${formatManualNote(settings.dependabotVersionUpdates)}`\n ]\n ];\n\n return `This section is updated each time \\`npm run document\\` is run. Settings come from the repository's workflow files and GitHub. Test coverage and the Fallow score are measured at the same time.\n\n${buildTableContent('Testing', testingRows)}${buildTableContent('Code Quality', codeQualityRows)}${buildTableContent('Security Analysis', securityAnalysisRows)}${buildTableContent('Dependencies', dependencyRows)}`;\n}\n\nfunction buildQualitySecurityContent(\n owner: string,\n repository: string,\n checksResults: ChecksResults,\n bestPracticesProjectId: number | undefined,\n scorecardResult: ScorecardResult | undefined\n): string {\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n const scorecardURI = `github.com/${owner}/${repository}`;\n const bestPracticesURL = `https://www.bestpractices.dev/projects/${String(bestPracticesProjectId)}`;\n const scorecardLimitText =\n scorecardResult !== undefined && isScorecardOnlyPracticeLimited(scorecardResult)\n ? \"\\n\\n> [!NOTE]\\n> Apart from the Best Practices badge above, the remaining Scorecard gaps need multi-person review or a pull-request workflow, which this solo-maintained project doesn't use.\"\n : '';\n const bestPracticesBadge = bestPracticesProjectId === undefined ? '' : `[](${bestPracticesURL})\\n`;\n\n // Without private reporting switched on, the advisory link leads nowhere, so point only at SECURITY.md.\n const reportingText =\n checksResults.securitySettings.privateVulnerabilityReporting === true\n ? `Use [GitHub private vulnerability reporting](${repositoryURL}/security/advisories/new) instead. See [SECURITY.md](./SECURITY.md) for the full disclosure policy, contact details, and expected response times.`\n : 'See [SECURITY.md](./SECURITY.md) for how to report one privately, the full disclosure policy, and expected response times.';\n\n return `## Quality & Security\n\n${buildChecksContent(owner, repository, checksResults)}### OpenSSF 🚧\n\n${bestPracticesBadge}[](https://scorecard.dev/viewer/?uri=${scorecardURI})\n\nThis project is working towards the [OpenSSF Best Practices](https://www.bestpractices.dev) Passing badge, a self-certification covering security policy, vulnerability reporting, build processes, code quality, and more. Currently the [OpenSSF Scorecard](https://scorecard.dev) provides an independent automated assessment of the project's security practices and is an ongoing area of improvement.${scorecardLimitText}\n\n### Reporting Vulnerabilities\n\nPlease do not open public GitHub issues for security vulnerabilities. ${reportingText}`;\n}\n","// ── External Dependencies & Registrations\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport type { ModuleTypeConfig } from '@/utilities';\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- USAGE_START -->';\nconst END_MARKER = '<!-- USAGE_END -->';\n\n// Module types the DPUse Engine uploads to the cloud for the browser app to load. The engine itself is also uploaded, but\n// isn't something others build their own version of, so it gets the general wording.\nconst UPLOADED_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['connector', 'cookbook', 'presenter']);\n\n// Published to npm only so DPUse projects can install them, not for general use, so the npm wording carries a warning.\nconst INTERNAL_NPM_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['development', 'eslint']);\nconst INTERNAL_NPM_WARNING = `> [!WARNING]\n> This project is not designed for general use. It is custom built for the DPUse CI/CD process. You are welcome to clone and customise it for your own purposes, but you will need to adapt it to your own project structure and tooling.`;\n\n// How the repository is managed. dpuse-development provides the actions every other repository uses, and runs them on itself.\nconst DEVELOPMENT_MANAGEMENT_TEXT = 'This repository manages itself using the actions it implements.';\nconst SHARED_MANAGEMENT_TEXT = 'This repository is managed using the common set of actions provided by [@dpuse/dpuse-development](https://github.com/dpuse/dpuse-development).';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentUsage(): Promise<void> {\n try {\n logOperationHeader('Document Usage');\n\n logStepHeader(\"1️⃣ Insert usage content into 'README.md'\");\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<ModuleConfig>('config.json')]);\n\n const cloneURL = resolveCloneURL(packageJSON);\n const directoryName = resolveDirectoryName(cloneURL);\n const nodeVersion = resolveVersion(packageJSON.engines?.node);\n const npmVersion = resolveVersion(packageJSON.engines?.npm);\n const typescriptVersion = resolveVersion(packageJSON.devDependencies?.['typescript']);\n\n const introduction = buildIntroductionContent(getModuleConfig(configJSON.id), packageJSON.name);\n // A full link, so it still works where the README is shown away from GitHub, such as on npm.\n const packageJSONURL = `${cloneURL.replace(/\\.git$/, '')}/blob/main/package.json`;\n const managementText = packageJSON.name === '@dpuse/dpuse-development' ? DEVELOPMENT_MANAGEMENT_TEXT : SHARED_MANAGEMENT_TEXT;\n const management = `${managementText} See the \\`scripts\\` block in [package.json](${packageJSONURL}) for details.`;\n const content = buildUsageContent(introduction, cloneURL, directoryName, nodeVersion, npmVersion, typescriptVersion, management);\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Usage documented');\n } catch (error) {\n console.error('❌ Error documenting usage', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveCloneURL(packageJSON: PackageJson): string {\n const repository = packageJSON.repository;\n const url = typeof repository === 'string' ? repository : repository?.url;\n if (url == null || url === '') throw new Error(\"package.json 'repository' field is required to document usage.\");\n return url.replace(/^git\\+/, '');\n}\n\nfunction resolveDirectoryName(cloneURL: string): string {\n const lastSegment = cloneURL.split('/').at(-1) ?? '';\n return lastSegment.replace(/\\.git$/, '');\n}\n\nfunction resolveVersion(range: string | undefined): string {\n if (range == null) throw new Error('package.json version range is required to document usage.');\n // eslint-disable-next-line security/detect-unsafe-regex -- Linear: each group repeat must start with a literal '.'.\n const match = /\\d+(?:\\.\\d+)*/.exec(range);\n if (match == null) throw new Error(`Unable to parse version from '${range}'.`);\n return match[0];\n}\n\n// Worded for how the module reaches people: uploaded to DPUse, installed from npm, or neither.\nfunction buildIntroductionContent(moduleTypeConfig: ModuleTypeConfig, packageName: string | undefined): string {\n const { typeId } = moduleTypeConfig;\n\n if (UPLOADED_MODULE_TYPE_IDS.has(typeId)) {\n return `This ${typeId} is automatically uploaded to the DPUse Engine cloud once released and becomes instantly available to all new browser app instances, with existing instances notified of the update.\n\nYou may view or clone this repository for your own purposes, such as building a new, similar ${typeId}, though there is currently no process to accept third-party ${typeId}s into DPUse at this stage.`;\n }\n\n if (moduleTypeConfig.publishedTo === 'npm') {\n if (packageName == null || packageName === '') throw new Error(\"package.json 'name' field is required to document usage.\");\n const warning = INTERNAL_NPM_MODULE_TYPE_IDS.has(typeId) ? `${INTERNAL_NPM_WARNING}\\n\\n` : ''; // Its own paragraph, or the text after it joins the warning.\n return `This [package](https://www.npmjs.com/package/${packageName}) is available on [npm](https://www.npmjs.com/). Install it with:\n\n\\`\\`\\`bash\nnpm install ${packageName}\n\\`\\`\\`\n\n${warning}To work on the source instead, clone this repository.`;\n }\n\n return `You may view or clone this repository for your own purposes.`;\n}\n\nfunction buildUsageContent(\n introduction: string,\n cloneURL: string,\n directoryName: string,\n nodeVersion: string,\n npmVersion: string,\n typescriptVersion: string,\n management: string\n): string {\n return `## Usage\n\n${introduction}\n\n\\`\\`\\`bash\ngit clone ${cloneURL}\ncd ${directoryName}\nnpm install\n\\`\\`\\`\n\n_Requires [Node.js](https://nodejs.org/) ${nodeVersion} or later, [npm](https://www.npmjs.com/) ${npmVersion} or later, and [TypeScript](https://www.typescriptlang.org/) ${typescriptVersion} or later._\n\n${management}`;\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const API_REFERENCE_PATH = 'API_REFERENCE.md';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Lists every export of each import path in API_REFERENCE.md. Runs with the README's sections where the project has that file. */\nexport async function documentAPIReference(): Promise<void> {\n try {\n logOperationHeader('Document API Reference');\n\n // TypeScript is an optional peer, so the code that reads the source with it is loaded only when it's needed.\n const { writeAPIReference } = await import('@/utilities/apiReference');\n await writeAPIReference('1️⃣ ', API_REFERENCE_PATH);\n\n logOperationSuccess('API reference documented');\n } catch (error) {\n console.error('❌ Error documenting API reference', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, readTextFileOrNull, writeReadmeSection } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface Sizes {\n uncompressed: number;\n gzip: number;\n}\n\ninterface SondaResource {\n kind: 'asset' | 'chunk' | 'filesystem' | 'sourcemap';\n name: string;\n uncompressed: number;\n gzip?: number;\n parent?: string | null;\n}\n\ninterface SondaDependency {\n name: string;\n paths: string[];\n}\n\ninterface SondaJson {\n resources: SondaResource[];\n dependencies: SondaDependency[];\n}\n\ninterface GroupData {\n sizes: Sizes;\n files: Map<string, Sizes>;\n}\n\ninterface WasmSizes {\n bytes: number; // As embedded, base64 text included.\n binaryBytes: number; // The WebAssembly the text decodes to.\n}\n\ntype GroupEntry = [string, GroupData];\ntype DependencyPath = [path: string, name: string];\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const BUNDLE_REPORT_PATH = 'bundle-analysis-reports/sonda/index.json'; // Written by Sonda during the Vite build.\nconst WORKER_REPORT_PATH = 'bundle-analysis-reports/sonda/worker.json'; // Written for an inlined worker, where the project's build adds one.\n\nconst BUNDLE_START_MARKER = '<!-- BUNDLE_START -->';\nconst BUNDLE_END_MARKER = '<!-- BUNDLE_END -->';\nconst INDENT = ' ';\nconst BAR_WIDTH = 20;\nconst BAR_CHARACTER = '█';\nconst PART_BAR_CHARACTER = '▒'; // Lighter, so a '↳' row reads as part of the row above. Markdown has no colour that also shows on npm.\nconst MIN_VISIBLE_PERCENT = 100 / BAR_WIDTH / 2; // Below this a bar rounds to no characters at all.\nconst SMALL_FILES_MAX_PERCENT = 100 / BAR_WIDTH; // The combined row for small files stays within one bar character.\n\n// GitHub strips CSS from a README, so column widths are steered through the text itself: the composition column has no\n// spaces to break at, and a long label is shortened so the column it gives up stays narrow.\nconst LABEL_MAX_LENGTH = 48;\n\nconst BUNDLE_ANALYSIS_INTRO = `This report is updated with each release, from the bundle the release builds, using [Sonda](https://sonda.dev/), which analyses final source maps to reveal the actual effects of tree-shaking and minification rather than relying on pre-build estimates.\\n\\n_Note: Sonda's Vite reports currently exclude CSS files, since Vite does not generate source maps for CSS._`;\n\nconst BAR_NOTE = `Bars show each row's share of its output file.`;\nconst PART_ROW_NOTE = '↳ rows are part of the row above.'; // Only where the table has such rows, which module level leaves out.\n\nconst MORE_NOTE =\n '+ n more = the row also holds n more files from the same package or folder, each no larger than the one named. A package can appear under several output files, each holding different files, never the same file twice.';\n\nconst UNTRACED_LABEL = '(bundler output, whitespace & JSON)';\nconst WORKER_LABEL = '(inlined worker)';\nconst WORKER_NOTE = `${WORKER_LABEL} = a Web Worker built separately and embedded in its output file as text. Where the build records what it contains, its rows list that; any few bytes over are the escaping needed to embed it.`;\nconst WASM_LABEL_PREFIX = '(Rust WebAssembly as base64';\nconst WASM_NOTE = `${WASM_LABEL_PREFIX}…) = the compiled Rust code, embedded as base64 text, about a third larger than the binary it decodes to, which is the size given.`;\n\nconst UNTRACED_NOTE = `${UNTRACED_LABEL} = bytes Sonda can't trace to a source file: whitespace (indentation and line breaks), code the bundler generates (region comments, the combined import/export lines, its small runtime helper and wrappers), and imported JSON such as \\`config.json\\`, which the bundler doesn't map. The JSON and the generated code are real bytes that ship; the whitespace mostly disappears once compressed.`;\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentBundleSizes(options?: { moduleLevel?: boolean }): Promise<void> {\n try {\n logOperationHeader('Document Bundle Sizes');\n\n logStepHeader('1️⃣ Read bundle analysis report');\n const json = await readJSONFile<SondaJson>(BUNDLE_REPORT_PATH);\n const workerReport = await readTextFileOrNull(WORKER_REPORT_PATH);\n const workerJson = workerReport === null ? undefined : (JSON.parse(workerReport) as SondaJson);\n // The built files, read to find what is embedded in them as text, which Sonda cannot trace.\n const assetContents = new Map<string, string | null>();\n for (const resource of json.resources) if (resource.kind === 'asset') assetContents.set(resource.name, await readTextFileOrNull(resource.name));\n\n logStepHeader(`2️⃣ Insert table into 'README.md'`);\n const bundleTable = buildBundleTable(json, { assetContents, isModuleLevel: options?.moduleLevel ?? false, workerJson });\n const rowNote = bundleTable.includes('↳') ? `${BAR_NOTE} ${PART_ROW_NOTE}` : BAR_NOTE;\n const moreNote = / \\+ \\d+ more \\|/.test(bundleTable) ? MORE_NOTE : '';\n const notes = [rowNote, moreNote, bundleTable.includes(WORKER_LABEL) ? WORKER_NOTE : '', bundleTable.includes(WASM_LABEL_PREFIX) ? WASM_NOTE : '', UNTRACED_NOTE].filter(\n (note) => note !== ''\n );\n\n await writeReadmeSection(`## Bundle Analysis\\n\\n${BUNDLE_ANALYSIS_INTRO}\\n\\n${bundleTable}\\n\\n${notes.join('\\n\\n')}`, BUNDLE_START_MARKER, BUNDLE_END_MARKER);\n\n logOperationSuccess('Bundle sizes documented');\n } catch (error) {\n console.error('❌ Error documenting bundle sizes', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Each output file is broken down on its own, so its top-level bars add up to 100% of that file, and its heading gives its\n// share of the whole build. Rows marked '↳' are part of the row above; their bars use the same scale, so every bar in a\n// file can be compared with every other.\nfunction buildBundleTable(json: SondaJson, options: { assetContents: Map<string, string | null>; isModuleLevel: boolean; workerJson: SondaJson | undefined }): string {\n const { assetContents, isModuleLevel, workerJson } = options;\n const assetGroups = buildAssetGroups(json);\n const workerGroups = workerJson === undefined ? undefined : buildAssetGroups(workerJson).values().next().value;\n for (const [file, groups] of assetGroups) {\n const content = assetContents.get(file);\n if (content != null) separateEmbeddedContent(groups, content, workerGroups);\n }\n const buildTotal = assetGroups\n .values()\n .flatMap((groups) => groups.values().toArray())\n .reduce((sum, group) => sum + group.sizes.uncompressed, 0);\n\n const assets = json.resources\n .filter((resource) => resource.kind === 'asset')\n .map((asset): [string, Sizes] => [asset.name, resourceSizes(asset)])\n .toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n\n const lines = ['|Chunk/Module/File|Composition|', '|:------ |:-----------|'];\n\n for (const [file, sizes] of assets) {\n const groups = assetGroups.get(file) ?? new Map<string, GroupData>();\n const sortedGroups = [...groups].toSorted(compareGroups);\n const fileTotal = sortedGroups.reduce((sum, [, group]) => sum + group.sizes.uncompressed, 0);\n\n const buildShare = fileTotal > 0 && buildTotal > 0 ? ` · ${formatPercent(fileTotal, buildTotal)} of the build` : '';\n lines.push(row(`**${fitLabel(file)}**`, `${chunkSizes(sizes)}${buildShare}`), ...renderGroupRows(sortedGroups, fileTotal, isModuleLevel));\n }\n\n return lines.join('\\n');\n}\n\n// Embedded text is traced to no source, or to the one that embeds it, so it is measured in the built file and given rows\n// of its own: an inlined worker, broken down where its build was recorded, and embedded WebAssembly.\nfunction separateEmbeddedContent(groups: Map<string, GroupData>, content: string, workerGroups: Map<string, GroupData> | undefined): void {\n const workerText = findInlinedWorkerText(content);\n const workerWasm = measureWasm(workerText ?? '');\n const allWasm = measureWasm(content);\n separateWasm(groups, { bytes: allWasm.bytes - workerWasm.bytes, binaryBytes: allWasm.binaryBytes - workerWasm.binaryBytes });\n if (workerText !== undefined) separateWorker(groups, Buffer.byteLength(workerText), workerWasm, workerGroups);\n}\n\n// Vite embeds an inlined worker as a string it passes to 'new Worker(… encodeURIComponent(name))'; this finds that string.\nfunction findInlinedWorkerText(content: string): string | undefined {\n if (!content.includes('new Worker(')) return undefined;\n const variableName = /encodeURIComponent\\((\\w+)\\)/.exec(content)?.[1];\n if (variableName === undefined) return undefined;\n // eslint-disable-next-line security/detect-non-literal-regexp -- The name is a JavaScript identifier, matched by '\\w+' above.\n const declaration = new RegExp(String.raw`(?:var|let|const)\\s+${variableName}\\s*=\\s*([\"'\\`])`).exec(content);\n const quote = declaration?.[1];\n if (declaration === null || quote === undefined) return undefined;\n const start = declaration.index + declaration[0].length;\n let end = start;\n while (end < content.length && content[end] !== quote) end += content[end] === '\\\\' ? 2 : 1;\n return content.slice(start, end);\n}\n\nfunction measureWasm(text: string): WasmSizes {\n const sizes = { bytes: 0, binaryBytes: 0 };\n for (const match of text.matchAll(/data:application\\/wasm;base64,([A-Za-z\\d+/]*={0,2})/g)) {\n const base64 = match[1] ?? '';\n sizes.bytes += match[0].length;\n sizes.binaryBytes += Math.floor((base64.length * 3) / 4) - countBase64Padding(base64);\n }\n return sizes;\n}\n\nfunction countBase64Padding(base64: string): number {\n if (base64.endsWith('==')) return 2;\n return base64.endsWith('=') ? 1 : 0;\n}\n\n// The WebAssembly is taken from the wasm-bindgen file that embeds it, or failing that from the untraced bytes.\nfunction separateWasm(groups: Map<string, GroupData>, wasm: WasmSizes): void {\n if (wasm.bytes <= 0) return;\n const source = [groups.get('wasm'), groups.get(UNTRACED_LABEL)]\n .flatMap((group) =>\n group === undefined\n ? []\n : group.files\n .entries()\n .map(([fileName, sizes]) => ({ group, fileName, sizes }))\n .toArray()\n )\n .find(({ sizes }) => sizes.uncompressed >= wasm.bytes);\n if (source === undefined) return;\n subtractBytes(groups, source.group, source.fileName, source.sizes, wasm.bytes);\n const label = `${WASM_LABEL_PREFIX}, ${formatBytes(wasm.binaryBytes)} binary)`;\n groups.set(label, { sizes: { uncompressed: wasm.bytes, gzip: 0 }, files: new Map([['', { uncompressed: wasm.bytes, gzip: 0 }]]) });\n}\n\nfunction separateWorker(groups: Map<string, GroupData>, workerBytes: number, workerWasm: WasmSizes, workerGroups: Map<string, GroupData> | undefined): void {\n const untraced = groups.get(UNTRACED_LABEL);\n const untracedSizes = untraced?.files.get('');\n if (untraced === undefined || untracedSizes === undefined || untracedSizes.uncompressed < workerBytes) return;\n subtractBytes(groups, untraced, '', untracedSizes, workerBytes);\n const files = workerGroups === undefined ? new Map([['', { uncompressed: workerBytes, gzip: 0 }]]) : flattenWorkerGroups(workerGroups, workerBytes, workerWasm);\n groups.set(WORKER_LABEL, { sizes: { uncompressed: workerBytes, gzip: 0 }, files });\n}\n\n// The worker's own rows: its source files by name, and each dependency, the WebAssembly and its untraced bytes as one.\nfunction flattenWorkerGroups(workerGroups: Map<string, GroupData>, workerBytes: number, workerWasm: WasmSizes): Map<string, Sizes> {\n separateWasm(workerGroups, workerWasm);\n const files = new Map<string, Sizes>();\n for (const [groupName, group] of workerGroups) {\n if (groupName === 'src') {\n for (const [fileName, sizes] of group.files) files.set(fileName, { ...sizes });\n } else {\n const label = group.files.size === 1 ? formatGroupLabel(groupName, getSoleFileName(group.files)) : groupName;\n files.set(label, { ...group.sizes });\n }\n }\n const reportedBytes = files.values().reduce((sum, sizes) => sum + sizes.uncompressed, 0);\n const untraced = files.get(UNTRACED_LABEL) ?? zero();\n untraced.uncompressed += Math.max(0, workerBytes - reportedBytes);\n if (untraced.uncompressed > 0) files.set(UNTRACED_LABEL, untraced);\n return files;\n}\n\nfunction subtractBytes(groups: Map<string, GroupData>, group: GroupData, fileName: string, sizes: Sizes, bytes: number): void {\n sizes.uncompressed -= bytes;\n group.sizes.uncompressed -= bytes;\n if (sizes.uncompressed <= 0) group.files.delete(fileName);\n if (group.sizes.uncompressed > 0) return;\n for (const [groupName, candidate] of groups) if (candidate === group) groups.delete(groupName);\n}\n\n// Largest first, except the untraced bytes, which always come last as what is left over once the modules are listed.\nfunction compareGroups(a: GroupEntry, b: GroupEntry): number {\n if ((a[0] === UNTRACED_LABEL) !== (b[0] === UNTRACED_LABEL)) return a[0] === UNTRACED_LABEL ? 1 : -1;\n return b[1].sizes.uncompressed - a[1].sizes.uncompressed;\n}\n\n// A group of several files is labelled by its largest, with a count of the rest, so a package spread over several output\n// files reads as different parts of it rather than as a copy in each.\nfunction renderGroupRows(sortedGroups: GroupEntry[], fileTotal: number, isModuleLevel: boolean): string[] {\n const lines: string[] = [];\n\n for (const [groupName, { sizes: groupSizes, files }] of sortedGroups) {\n if (files.size === 1) {\n const fileName = getSoleFileName(files);\n lines.push(row(`${INDENT}${fitLabel(formatGroupLabel(groupName, fileName))}`, composition(groupSizes.uncompressed, fileTotal)));\n continue;\n }\n\n lines.push(row(`${INDENT}${formatSeveralFilesLabel(groupName, files)}`, composition(groupSizes.uncompressed, fileTotal)));\n if (!isModuleLevel) lines.push(...renderFileRows(files, fileTotal));\n }\n\n return lines;\n}\n\nfunction renderFileRows(files: Map<string, Sizes>, fileTotal: number): string[] {\n const sortedFiles = [...files].toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n const smallCount = countSmallFiles(sortedFiles, fileTotal);\n const namedFiles = smallCount > 0 ? sortedFiles.slice(0, -smallCount) : sortedFiles;\n\n const rows = namedFiles.map(([fileName, fileSizes]) => row(`${INDENT}${INDENT}↳ ${fitLabel(fileName)}`, composition(fileSizes.uncompressed, fileTotal, PART_BAR_CHARACTER)));\n if (smallCount > 0) {\n const smallBytes = sortedFiles.slice(-smallCount).reduce((sum, [, fileSizes]) => sum + fileSizes.uncompressed, 0);\n rows.push(row(`${INDENT}${INDENT}↳ ${String(smallCount)} smaller files`, composition(smallBytes, fileTotal, PART_BAR_CHARACTER)));\n }\n return rows;\n}\n\n// Files too small to show any bar are combined into one row, smallest first, stopping before that row would pass one bar\n// character, so it never hides much. A lone small file keeps its name, as combining one file would hide it for nothing.\nfunction countSmallFiles(sortedFiles: [string, Sizes][], fileTotal: number): number {\n if (fileTotal <= 0) return 0;\n let count = 0;\n let bytes = 0;\n for (const [, fileSizes] of sortedFiles.toReversed()) {\n const isTooSmallToShow = (fileSizes.uncompressed / fileTotal) * 100 < MIN_VISIBLE_PERCENT;\n const isCombinedRowStillSmall = ((bytes + fileSizes.uncompressed) / fileTotal) * 100 <= SMALL_FILES_MAX_PERCENT;\n if (!isTooSmallToShow || !isCombinedRowStillSmall) break;\n count++;\n bytes += fileSizes.uncompressed;\n }\n return count >= 2 ? count : 0;\n}\n\n// A bar and percentage of the output file, then the size, so the share and the bytes behind it read together.\nfunction composition(bytes: number, fileTotal: number, barCharacter = BAR_CHARACTER): string {\n return `${bar(fileTotal > 0 ? (bytes / fileTotal) * 100 : 0, barCharacter)} · ${formatBytes(bytes)}`;\n}\n\n// A group with no file name, such as the untraced bytes, is shown on its own rather than as 'group → '.\nfunction formatGroupLabel(groupName: string, fileName: string): string {\n return fileName === '' ? groupName : `${groupName} → ${fileName}`;\n}\n\n// The inlined worker's rows are its own breakdown rather than files, so it keeps its plain label. The count is left out of\n// any shortening, so it is never the part cut.\nfunction formatSeveralFilesLabel(groupName: string, files: Map<string, Sizes>): string {\n if (groupName === WORKER_LABEL) return groupName;\n const [largestFileName] = [...files].toSorted((a, b) => b[1].uncompressed - a[1].uncompressed)[0] ?? [''];\n return `${fitLabel(formatGroupLabel(groupName, largestFileName))} + ${String(files.size - 1)} more`;\n}\n\n// A 'group → ' prefix is always kept whole. The path after it loses its start, keeping the file name it ends with, and\n// shows in full on hover.\nfunction fitLabel(label: string): string {\n const arrowIndex = label.indexOf(' → ');\n const prefix = arrowIndex === -1 ? '' : label.slice(0, arrowIndex + 3);\n const path = label.slice(prefix.length);\n const pathMaxLength = Math.max(LABEL_MAX_LENGTH - prefix.length, 2);\n const isTooLong = path.length > pathMaxLength;\n return isTooLong ? `${prefix}<abbr title=\"${path.replaceAll('&', '&').replaceAll('\"', '"')}\">…${path.slice(path.length - (pathMaxLength - 1))}</abbr>` : label;\n}\n\n// The composition's spaces are made non-breaking; its bar is the only code span and holds none, so no entity lands\n// inside one, where it would show as written.\nfunction row(label: string, composition: string): string {\n return `| ${label} | ${composition.replaceAll(' ', ' ')} |`;\n}\n\nfunction getSoleFileName(files: Map<string, Sizes>): string {\n const [fileName] = files.keys();\n if (fileName === undefined) throw new Error('Expected exactly one file');\n return fileName;\n}\n\n// Builds, per output asset, the size totals grouped by dependency (or 'src'/'wasm'/'(runtime)'), and by file within each group.\nfunction buildAssetGroups(json: SondaJson): Map<string, Map<string, GroupData>> {\n const dependencyPaths = buildDependencyPaths(json.dependencies);\n const assets = new Map<string, Map<string, GroupData>>();\n\n for (const resource of json.resources) {\n if (resource.kind !== 'chunk' || !resource.parent) continue;\n const { group: groupName, file: fileName } = resolveModule(resource.name, dependencyPaths);\n const sizes = resourceSizes(resource);\n\n const groups = assets.get(resource.parent) ?? new Map<string, GroupData>();\n assets.set(resource.parent, groups);\n\n const group = groups.get(groupName) ?? { sizes: zero(), files: new Map<string, Sizes>() };\n groups.set(groupName, group);\n addTo(group.sizes, sizes);\n\n const fileSizes = group.files.get(fileName) ?? zero();\n group.files.set(fileName, fileSizes);\n addTo(fileSizes, sizes);\n }\n\n return assets;\n}\n\n// Flattens `dependencies[].paths` into `[path, dependencyName]` pairs, longest path first so scoped/nested packages match before their parents.\nfunction buildDependencyPaths(dependencies: SondaDependency[]): DependencyPath[] {\n return dependencies.flatMap((dependency): DependencyPath[] => dependency.paths.map((path) => [path, dependency.name])).toSorted((a, b) => b[0].length - a[0].length);\n}\n\nfunction resolveModule(path: string, dependencyPaths: DependencyPath[]): { group: string; file: string } {\n const match = dependencyPaths.find(([dependencyPath]) => path === dependencyPath || path.startsWith(`${dependencyPath}/`));\n if (match) {\n const [dependencyPath, name] = match;\n return { group: name, file: path.slice(dependencyPath.length + 1) };\n }\n if (path === '[unassigned]') return { group: UNTRACED_LABEL, file: '' }; // Sonda's marker for chunk bytes it can't trace back to a source module.\n if (path.startsWith('\\u{0}')) return { group: '(runtime)', file: path.slice(1) };\n return path.startsWith('rust/') ? { group: 'wasm', file: shortenCrateFileName(path) } : { group: 'src', file: lastPathSegment(path) };\n}\n\n// wasm-pack names every generated file after the crate, so the shared part is shortened to '…', leaving what differs.\nfunction shortenCrateFileName(path: string): string {\n const crateName = path.split('/', 2)[1] ?? '';\n const fileName = lastPathSegment(path);\n return crateName !== '' && fileName.startsWith(crateName) ? `…${fileName.slice(crateName.length)}` : fileName;\n}\n\nfunction lastPathSegment(path: string): string {\n return path.split('/').at(-1) ?? path;\n}\n\nfunction resourceSizes(resource: SondaResource): Sizes {\n return { uncompressed: resource.uncompressed, gzip: resource.gzip ?? 0 };\n}\n\nfunction chunkSizes(sizes: Sizes): string {\n return `${formatBytes(sizes.uncompressed)} · gzip ${formatBytes(sizes.gzip)}`;\n}\n\nfunction bar(pct: number, barCharacter = BAR_CHARACTER): string {\n const count = Math.round((pct / 100) * BAR_WIDTH);\n return `\\`${barCharacter.repeat(count)}${'░'.repeat(BAR_WIDTH - count)}\\` ${pct.toFixed(1)}%`;\n}\n\nfunction zero(): Sizes {\n return { uncompressed: 0, gzip: 0 };\n}\n\nfunction addTo(target: Sizes, source: Sizes): void {\n target.uncompressed += source.uncompressed;\n target.gzip += source.gzip;\n}\n\nfunction formatPercent(part: number, whole: number): string {\n return `${((part / whole) * 100).toFixed(1)}%`;\n}\n\nfunction formatBytes(bytes: number): string {\n return bytes < 1024 ? `${String(bytes)} B` : `${(bytes / 1024).toFixed(1)} kB`;\n}\n","// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { documentActions } from '@/actions/documentActions';\nimport { documentContributingLicense } from '@/actions/documentContributingLicense';\nimport { documentDependencies } from '@/actions/documentDependencies';\nimport { documentOpening } from '@/actions/documentOpening';\nimport { documentQualitySecurity } from '@/actions/documentQualitySecurity';\nimport { documentUsage } from '@/actions/documentUsage';\nimport { API_REFERENCE_PATH, documentAPIReference } from '@/actions/documentApiReference';\nimport { BUNDLE_REPORT_PATH, documentBundleSizes } from '@/actions/documentBundleSizes';\nimport { getModuleConfig, logStepHeader, readJSONFile, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates every generated section of the README, in the order they appear, then the API reference where the project keeps one. */\n// 'allowedLicenses' lists the licences dependencies may use, separated by ';'. 'isModuleLevel' breaks bundle sizes\n// down by module rather than by package.\nexport async function documentProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const isConnector = getModuleConfig(configJSON.id).typeId === 'connector'; // Only connectors have an actions table.\n\n await documentOpening();\n if (isConnector) await documentActions();\n await documentUsage();\n await documentDependencies(allowedLicenses);\n\n // Bundle sizes come from the report the last build wrote, so they wait until there is one, as on a fresh clone.\n if ((await readTextFileOrNull(BUNDLE_REPORT_PATH)) === null) {\n logStepHeader(`ℹ️ Bundle sizes NOT documented, as there is no '${BUNDLE_REPORT_PATH}' yet. Build the project first.`);\n } else {\n await documentBundleSizes({ moduleLevel: isModuleLevel });\n }\n\n await documentQualitySecurity();\n await documentContributingLicense();\n\n // Only where the project keeps an API reference, so projects opt in by adding the file.\n const hasAPIReference = (await readTextFileOrNull(API_REFERENCE_PATH)) !== null;\n if (hasAPIReference) {\n await documentAPIReference();\n } else {\n logStepHeader(`ℹ️ '${API_REFERENCE_PATH}' NOT required by this project`);\n }\n\n // Saved as Prettier would format them, so 'npm run format' has nothing left to change. Only the files written here\n // are formatted, so documenting never touches the source.\n await spawnCommand('ℹ️ Format generated files', 'prettier', ['--write', 'README.md', ...(hasAPIReference ? [API_REFERENCE_PATH] : [])]);\n } catch (error) {\n console.error('❌ Error documenting project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport { existsSync } from 'node:fs';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses prettier to enforce formatting style rules. */\nexport async function formatCode(): Promise<void> {\n try {\n logOperationHeader('Format Code');\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- specified directories, no user input.\n const optionalGlobs = ['app', 'src', 'tests'].filter((directory) => existsSync(directory)).map((directory) => `${directory}/**`);\n const formatTargets = ['--write', '*.json', '*.md', '*.ts', ...optionalGlobs];\n await spawnCommand('1️⃣ Format', 'prettier', formatTargets);\n\n logOperationSuccess('Code formatted');\n } catch (error) {\n console.error('❌ Error formatting code', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses eslint to check the code for potential errors and enforces coding style rules. */\nexport async function lintCode(): Promise<void> {\n try {\n logOperationHeader('Lint Code');\n\n await spawnCommand('1️⃣ Lint', 'eslint', ['.']);\n\n logOperationSuccess('Code linted');\n } catch (error) {\n console.error('❌ Error linting code', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport os from 'node:os';\nimport type { PackageJson } from 'type-fest';\nimport path from 'node:path';\nimport { promises as fs, type ObjectEncodingOptions } from 'node:fs';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { execCommand, getDirectoryEntries, getStatsForPath, readJSONFile, resolveSampleDataContentType, writeJSONFile } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A file to upload, and the key it is stored under in the bucket.\ninterface BulkPutFile {\n file: string;\n key: string;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst SAMPLE_DATA_BUCKET = 'dpuse-sample-data-eu';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// TODO: Send a release secret with these config writes once dpuse-api requires one on its '/configs' write routes,\n// which are open to anyone (found October 2026).\n//\n// TODO: Split 'CLOUDFLARE_PUBLISH_TOKEN' (found October 2026). One token, held by all 28 repos, can edit every Worker\n// and route on all accounts, so a compromised release in any repo could replace the live app. Give module repos an R2\n// only token for this account, give a Workers deploy token only to repos that run 'wrangler deploy', and remove the\n// secret from repos that never touch Cloudflare.\nexport async function putState(): Promise<void> {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${configJSON.id}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\n// Uploads a folder of sample data, and the folders inside it, under the same name in the sample data bucket. Files are\n// grouped by content type and each group goes up in one Wrangler call, which uploads its files in parallel.\nexport async function uploadDirectoryToR2(sourceDirectory: string, uploadDirectory: string): Promise<void> {\n const files = await listFilesRecursively(`${sourceDirectory}/${uploadDirectory}`, uploadDirectory);\n const filesByContentType = Map.groupBy(files, ({ key }) => resolveSampleDataContentType(key));\n for (const [contentType, contentTypeFiles] of filesByContentType) await bulkPutToR2(contentTypeFiles, ['--content-type', contentType]);\n}\n\n// Uploads the sample data: the 'application' and 'fileStore' folders, then their indexes. The indexes are always\n// checked with the server before a cached copy is reused, so a release is seen at once.\nexport async function uploadSampleDataToR2(sourceDirectory: string): Promise<void> {\n await uploadDirectoryToR2(sourceDirectory, 'application');\n await uploadDirectoryToR2(sourceDirectory, 'fileStore');\n const indexFiles = ['applicationIndex.json', 'fileStoreIndex.json'].map((name) => ({ file: `${sourceDirectory}/${name}`, key: name }));\n await bulkPutToR2(indexFiles, ['--content-type', 'application/json', '--cache-control', 'no-cache']);\n}\n\nexport async function uploadModuleConfigToDO(configJSON: ModuleConfig): Promise<void> {\n const stateId = configJSON.id;\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${stateId}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\nexport async function uploadModuleToR2(packageJSON: PackageJson, uploadDirectoryPath: string): Promise<void> {\n const version = `v${packageJSON.version ?? 'unknown'}`;\n async function uploadDirectory(currentDirectory: string, prefix = ''): Promise<void> {\n const entries = await getDirectoryEntries(currentDirectory, { withFileTypes: true } as ObjectEncodingOptions);\n for (const entry of entries) {\n if (entry.isDirectory() || entry.name.endsWith('.map')) continue;\n const fullPath = `${currentDirectory}/${entry.name}`;\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const r2Path = `${uploadDirectoryPath}_${version}/${relativePath}`.replaceAll('\\\\', '/');\n const nonJavaScripContentType = entry.name.endsWith('.css') ? 'text/css' : 'application/octet-stream';\n const contentType = entry.name.endsWith('.js') ? 'application/javascript' : nonJavaScripContentType;\n console.info(`⚙️ Uploading '${relativePath}' → '${r2Path}'...`);\n await execCommand(undefined, 'wrangler', ['r2', 'object', 'put', r2Path, `--file=${fullPath}`, '--content-type', contentType, '--jurisdiction=eu', '--remote']);\n }\n }\n await uploadDirectory('dist');\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// One 'wrangler r2 bulk put' call, which reads the files to upload from a list in a temporary file.\n//\n// TODO: Recheck this on every Wrangler upgrade, as Wrangler marks 'r2 bulk put' as experimental (\"🚧 `wrangler r2 bulk\n// put` is an experimental command\"), so it may change. As of Wrangler 4.147, the list is a JSON array of\n// '{ key, file }', each entry may carry nothing else, and options such as '--content-type' and '--cache-control' apply\n// to every file in the call, which is why files are grouped by content type. The tests pin the exact arguments, so a\n// changed command shows up there; also check the command's '--help' and the warning it prints. If it is withdrawn,\n// fall back to one 'r2 object put' per file, as before (slow: one Wrangler process per file), or upload through R2's\n// S3-compatible API.\n//\n// TODO: Report to Cloudflare (https://github.com/cloudflare/workers-sdk) that in local mode ('--local'), Wrangler 4.147\n// stores a bulk-put key containing a space with '%20', e.g. 'fileStore/Encoding%20Samples/ascii.txt', because it\n// builds a URL from the key without encoding it (`http://localhost/${entry.key}`). Found in October 2026. Remote mode,\n// which this uses, sends each file through the same function as 'r2 object put' and stores the key correctly, so this\n// only matters when trying the upload against local storage.\nasync function bulkPutToR2(files: BulkPutFile[], options: string[]): Promise<void> {\n if (files.length === 0) return;\n const listFolderPath = await fs.mkdtemp(path.join(os.tmpdir(), 'dpuse-r2-bulk-'));\n const listFilePath = path.join(listFolderPath, 'files.json');\n try {\n await writeJSONFile(listFilePath, files);\n console.info(`⚙️ Uploading ${String(files.length)} files (${options.join(' ')})...`);\n await execCommand(undefined, 'wrangler', ['r2', 'bulk', 'put', SAMPLE_DATA_BUCKET, '--filename', listFilePath, ...options, '--jurisdiction=eu', '--remote']);\n } finally {\n await fs.rm(listFolderPath, { force: true, recursive: true });\n }\n}\n\n// Skips hidden files, such as '.DS_Store', which only exist on a developer's machine.\nasync function listFilesRecursively(sourcePath: string, keyPrefix: string): Promise<BulkPutFile[]> {\n const names = await getDirectoryEntries(sourcePath);\n const files: BulkPutFile[] = [];\n for (const name of names) {\n if (name.startsWith('.')) continue;\n const itemPath = `${sourcePath}/${name}`;\n const key = `${keyPrefix}/${name}`;\n const stats = await getStatsForPath(itemPath);\n if (stats.isDirectory()) files.push(...(await listFilesRecursively(itemPath, key)));\n else files.push({ file: itemPath, key });\n }\n return files;\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, type ModuleTypeConfig, readJSONFile, spawnCommand } from '@/utilities';\nimport { putState, uploadModuleConfigToDO, uploadModuleToR2, uploadSampleDataToR2 } from '@/utilities/cloudflare';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// TODO: 'publish.yml' starts alongside CI rather than after it, and repeats CI's build, lint and test but not its audit,\n// so a release can publish while CI's audit fails. Make 'ci.yml' a reusable workflow ('workflow_call') that 'publish.yml'\n// runs as its first job, with the publish job needing it, and drop the repeated steps from 'publish.yml'.\n/** Publishes the project to npm, uploads it to DPUse, or both, as its module type requires. Run by the 'publish.yml' workflow. */\nexport async function publishProject(): Promise<void> {\n try {\n logOperationHeader('Publish Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n // Where a module goes is set by its type, so every project calls this the same way. Tools go to both places: npm\n // first, so the app is never told of a version whose npm publish failed.\n if (moduleTypeConfig.publishedTo === 'npm') {\n await spawnCommand('1️⃣ Publish to npm', 'npm', ['publish', '--provenance']);\n } else {\n logStepHeader('1️⃣ Publishing to npm NOT required');\n }\n\n // The API, the app and the knowledge base are published by their own 'deploy' scripts: the API's and the app's\n // deploy their Workers, the knowledge base's loads the docs into Cloudflare KV and deploys the site. Each deploys\n // before it is registered, so the app is never told of a version that is not live yet.\n const isDeployedByScript = ['api', 'app', 'kb'].includes(moduleTypeConfig.publishedTo);\n if (isDeployedByScript) await spawnCommand('2️⃣ Deploy', 'npm', ['run', 'deploy']);\n\n await registerModule(isDeployedByScript ? '3️⃣ ' : '2️⃣ ', packageJSON, configJSON, moduleTypeConfig);\n\n // The sample data has no module to register. Its files and indexes go to R2; the workflow has already built the\n // indexes with 'npm run build'.\n if (moduleTypeConfig.publishedTo === 'sampleData') {\n logStepHeader('3️⃣ Upload sample data');\n await uploadSampleDataToR2('public');\n }\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' published.`);\n } catch (error) {\n console.error('❌ Error publishing project', error);\n process.exit(1);\n }\n}\n\n// Also run as the last step of 'releaseProject'.\nexport async function registerModule(stepIcon: string, packageJSON: PackageJson, configJSON: ModuleConfig, moduleTypeConfig: ModuleTypeConfig): Promise<void> {\n if (moduleTypeConfig.typeId === 'app') {\n logStepHeader(`${stepIcon} Register module`);\n await putState();\n } else if (moduleTypeConfig.typeId === 'engine') {\n logStepHeader(`${stepIcon} Register module`);\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName ?? 'unknown'}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new engine is available and try to access it before it is uploaded to R2.\n } else if (moduleTypeConfig.uploadGroupName === undefined) {\n logStepHeader(`${stepIcon} Registration NOT required`);\n } else {\n logStepHeader(`${stepIcon} Register module`);\n const moduleTypeName = configJSON.id.split('-').slice(2).join('-');\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName}/${moduleTypeName}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new module is available and try to access it before it is uploaded to R2.\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { bundleProject } from '@/actions/buildProject';\nimport { documentProject } from '@/actions/documentProject';\nimport { registerModule } from '@/actions/publishProject';\nimport {\n buildModuleConfig,\n bumpPackageVersion,\n execCommand,\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n readJSONFile,\n spawnCommand\n} from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Bump version, builds config, builds project, regenerates the README, synchronise with GitHub and publish to npm or Cloudflare. */\nexport async function releaseProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n logOperationHeader('Release Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n const builtConfigJSON = await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await bundleProject('3️⃣ ', packageJSON);\n\n // After the build, so the bundle sizes are the released bundle's, and before staging, so the README is committed\n // with the release. Its governance step runs the tests, so a failing test stops the release before anything is pushed.\n logStepHeader('4️⃣ Regenerate README');\n await documentProject(allowedLicenses, isModuleLevel);\n\n await execCommand('5️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('6️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('7️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n await registerModule('8️⃣ ', packageJSON, builtConfigJSON, moduleTypeConfig);\n\n // The release triggers the 'publish.yml' workflow, which publishes to npm through trusted publishing, so no token is needed here.\n if (moduleTypeConfig.publishedTo === 'npm') {\n const tagName = `v${packageJSON.version ?? 'unknown'}`;\n await spawnCommand('9️⃣ Trigger GitHub release', 'gh', ['release', 'create', tagName, '--target', 'main', '--generate-notes', '--latest']);\n } else {\n logStepHeader(`9️⃣ Publishing NOT required for package with type identifier of '${moduleTypeConfig.typeId}'.`);\n }\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' released.`);\n } catch (error) {\n console.error('❌ Error releasing project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { buildModuleConfig, bumpPackageVersion, execCommand, getModuleConfig, logOperationHeader, logOperationSuccess, readJSONFile } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Synchronise the local repository with the main GitHub repository. */\nexport async function syncProjectWithGitHub(): Promise<void> {\n try {\n logOperationHeader('Synchronise Project with GitHub');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await execCommand('3️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('4️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('5️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' synchronised with GitHub.`);\n } catch (error) {\n console.error('❌ Error synchronising project with GitHub', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface TestTypeConfig {\n id: TestTypeId;\n label: string;\n command: string;\n arguments: string[];\n configFileName: string; // Having this file is how a project says it runs this type of test.\n}\n\nexport type TestTypeId = 'e2e' | 'unit';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst STEP_ICONS = ['1️⃣ ', '2️⃣ ', '3️⃣ ', '4️⃣ '];\n\n// In the order they run. Unit tests go first so a failure stops the run before the slow browser tests start.\n// Both runners are told to pass when they find nothing, so a project that has set up a runner but not yet written\n// any tests reports green rather than red, and a real failure stands out.\nconst TEST_TYPE_CONFIGS: TestTypeConfig[] = [\n { id: 'unit', label: 'Run unit tests', command: 'vitest', arguments: ['run', '--passWithNoTests'], configFileName: 'vitest.config.ts' },\n { id: 'e2e', label: 'Run end-to-end tests', command: 'playwright', arguments: ['test', '--pass-with-no-tests'], configFileName: 'playwright.config.ts' }\n];\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Runs the requested types of test, skipping any type this project has not configured. */\nexport async function testProject(testTypeIds: TestTypeId[] = ['unit']): Promise<void> {\n try {\n logOperationHeader('Test Project');\n\n let stepNumber = 0;\n for (const testTypeConfig of TEST_TYPE_CONFIGS) {\n // Pass quietly over a type that was not requested, or that the project does not run because it has no\n // configuration file for it.\n if (!testTypeIds.includes(testTypeConfig.id) || (await readTextFileOrNull(testTypeConfig.configFileName)) === null) continue;\n\n const stepLabel = `${STEP_ICONS[stepNumber] ?? ''} ${testTypeConfig.label}`;\n await spawnCommand(stepLabel, testTypeConfig.command, testTypeConfig.arguments);\n stepNumber += 1;\n }\n\n if (stepNumber === 0) {\n console.warn('\\n⚠️ No tests configured for this project.\\n');\n return;\n }\n\n logOperationSuccess('Project tested');\n } catch (error) {\n console.error('❌ Error testing project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Create a GitHub release for the current version, which triggers the 'publish.yml' workflow. */\nexport async function triggerGitHubRelease(): Promise<void> {\n try {\n logOperationHeader('Trigger GitHub Release');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const tagName = `v${packageJSON.version ?? 'unknown'}`;\n\n await spawnCommand('1️⃣ Trigger GitHub release', 'gh', ['release', 'create', tagName, '--target', 'main', '--generate-notes', '--latest']);\n\n logOperationSuccess(`GitHub release '${tagName}' created.`);\n } catch (error) {\n console.error('❌ Error triggering GitHub release', error);\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;A,GC4BMmD,qBAAsB,IAAI,IAAI,CAAC,YAAY,MAAM,CAAC;AAKxD,eAAsBC,KAAmC;CACrD,IAAI;EACA,EAAmB,oBAAoB;EAIvC,IAAMC,IAAc,MAAMX,EAA0B,cAAc;EAClE,AAAIN,GAA+B,IAAIiB,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D;EACJ;EAEA,EAAoB,gBAAgB;CACxC,SAAShiB,GAAO;EAEZ,AADA,QAAQ,MAAM,4BAA4BA,CAAK,GAC/C,QAAQ,KAAK,CAAC;CAClB;AACJ;;;AC9CA,eAAsBmiB,KAAsC;CACxD,IAAI;EACA,EAAmB,wBAAwB;EAG3C,IAAMR,IAAU,KAAI,MADM5iB,EAA0B,cAAc,EAAA,CAClC,WAAW;EAI3C,AAFA,MAAM3B,EAAa,+BAA+B,MAAM;GAAC;GAAW;GAAUukB;GAAS;GAAY;GAAQ;GAAoB;EAAU,CAAC,GAE1I9iB,EAAoB,mBAAmB8iB,EAAQ,WAAW;CAC9D,SAAS3hB,GAAO;EAEZ,AADA,QAAQ,MAAM,sCAAsCA,CAAK,GACzD,QAAQ,KAAK,CAAC;CAClB;AACJ"}
|
|
1
|
+
{"version":3,"file":"dpuse-development.es.js","names":["runNpmCheckUpdates","START_MARKER","END_MARKER","determineConnectorUsageId","getConnectorActionsTable","fs","delay","START_MARKER","END_MARKER","START_MARKER","END_MARKER","fs","writeReadmeSection","readTextFileOrNull","spawnCommandForOutput","spawnCommand","Ce","De","spawnCommandToFile","readTextFile","resolveSampleDataContentType","logOperationHeader","FALLOW_DIRECTORY","migrateGovernanceSection","QUALITY_SECURITY_START_MARKER","bumpPackageVersion","clearDirectory","getStatsForPath","getModuleConfig","FALLOW_BADGE_PATH","writeJSONFile","RUST_WORKSPACE_PATH","getDirectoryEntries","CONTRIBUTING_LICENSE_START_MARKER","FALLOW_REPORT_PATH","execCommand","DEVELOPMENT_ONLY_PACKAGE_NAMES","QUALITY_SECURITY_END_MARKER","CONTRIBUTING_LICENSE_END_MARKER","buildModuleConfig","logOperationSuccess","resolveOwnerAndRepository","readJSONFile","logStepHeader","path","satisfies","os","IGNORED_ADVISORIES","\"id\"","\"reason\"","\"reviewBy\"","BLOCKING_SEVERITIES","auditDependencies","packageJSON","output","report","blockingAdvisories","checkAdvisories","listAdvisories","error","reportIgnoredAdvisories","label","ignoredCount","advisory","ignoredAdvisory","findIgnoredAdvisory","today","advisories","id","ignored","vulnerabilities","vulnerability","cause","WASM_BUILD_SCRIPT_NAME","buildProject","bundleProject","stepIcon","PRETTIER_CONFIG_REFERENCE","TEMPLATE_REPOSITORY_NAME","checkConfigFiles","configJSON","isPrivate","moduleTypeConfig","moduleDirectory","fileURLToPath","checkConfigFile","checkESLintConfig","checkTSConfig","checkTSConfigScripts","checkViteConfig","checkVitestConfig","checkPrettierConfig","hasRust","checkPrivateWorkflows","checkWorkflows","content","\"prettier\"","viteConfigTemplates","workflowPath","checkFilePath","checkFileName","templates","templateFileNames","checkFileContent","templateFileName","templatePath","templateContent","prepareTemplate","checkDependencies","rcOptions","run","pinnedPackageNames","getPinnedPackageNames","names","allowScripts","key","isAllowed","checkProject","START_MARKER$3","END_MARKER$3","SUPPORTED_ACTIONS_INTRO","CONNECTOR_USAGE_DESCRIPTIONS","SUPPORTED_ACTIONS_TABLE_LEAD_IN","documentActions","actionNames","usageId","table","block","documentContributingLicense","authorName","resolveAuthorName","copyrightYear","resolveCopyrightYear","buildContributingLicenseContent","owner","repository","author","authorString","emailStart","emailEnd","part","currentYear","firstCreatedAt","startYear","CARGO_METADATA_PATH","CARGO_TREE_PATH","CRATES_IO_REQUEST_INTERVAL","CRATES_IO_REQUEST_TIMEOUT","CRATES_IO_USER_AGENT","LICENSE_FILE_PATTERN","WASM_TARGET","documentRustCrates","cargoArguments","treeArguments","stepLabel","treeLines","parseCargoTree","metadata","promises","cratesByKey","line","crates","allowedLicenses","crate","copyLicenseFiles","addReleaseDetails","lines","text","crateText","licenseExpression","linkText","depthText","name","versionText","sourceParts","source","isOwn","link","checkCrateLicenses","allowedIdentifiers","isLicenseIdentifier","identifier","failures","isLicenseAllowed","failureList","cratePackage","candidate","crateDirectory","fileNames","fileName","a","b","licenseFiles","copiedPath","index","setTimeout","response","data","releaseDates","version","START_MARKER$2","END_MARKER$2","LICENSES_HEADING","SHIPPED_PACKAGES_RECORD_PATH","SHIPPED_PACKAGES_FILE_NAME","LICENSE_TREE_PATH","DEPENDENCY_TREE_FLAGS","DEPENDENCY_TREE_INTRO","SHIPPED_TREE_INTRO","documentDependencies","rootPackage","packageName","skipDependencyDocumentation","lockPackages","readLockPackages","shippedRecord","readShippedRecord","unshippedPackages","listUnshippedPackages","checkLicenses","insertDeclaredLicensesIntoReadme","shippedKeys","collectShippedKeys","installedKeys","listInstalledKeys","notShipped","packageKey","warnOfMissingPackages","rustCrates","readmeContext","listProductionNames","insertShippedLicensesIntoReadme","message","licenseTree","licensesByKey","readLicenses","licensesContent","buildLicensesIntro","license","formatLicenseRow","treeItems","walkTreeList","treeContent","context","crateLicensesByKey","convertCrateToLicense","hasRustCrates","tableHeader","compareLicenses","rootEntries","productionNames","javaScriptTree","rustTree","formatCrateTreeItem","item","indent","formatTreeItem","licenses","value","parseLicenseEntry","fetchNpmData","options","isProductionOnly","excludedKeys","resolve","reject","lockText","recordText","record","externalName","lockPath","resolveLockPath","shippedPath","findShippedPaths","entry","formatPackageKey","missingKeys","shippedPaths","shipped","unshipped","pendingPaths","startPath","fromPath","packages","listShippedDependencyNames","requiredPeerNames","basePath","candidatePath","parentIndex","licenseListText","formatLicenseListText","tools","buildScope","isFromBuild","lastAt","installedVersion","distributionTags","timeMap","latestVersion","publishedDate","licenseLink","licenseFile","typeLabel","depth","node","dependencies","items","walkShippedTree","entries","childEntries","isPassedOver","formatVersionDetail","published","determineLatestAge","latestAge","latestClause","momentString","dateString","input","now","months","START_MARKER$1","END_MARKER$1","documentOpening","resolveLicense","introduction","resolveIntroduction","dpuseModuleId","npmPackageName","resolvePackageName","buildOpeningContent","resolveVersionColor","repositoryURL","badgeLicense","dpuseConfigURL","description","SCORECARD_PRACTICE_LIMITS","SCORECARD_IGNORED_CHECKS","COVERAGE_FINAL_PATH","COVERAGE_SUMMARY_PATH","COVERAGE_TARGET_PERCENT","COVERAGE_WARNING_PERCENT","COVERAGE_BADGE_PATH","CODEQL_LANGUAGE_NAMES","FALLOW_GRADE_COLOURS","FALLOW_HEALTH_PATH","asyncExecFile","promisify","execFile","documentQualitySecurity","coveragePercent","measureTestCoverage","fallowHealth","measureCodeHealth","securitySettings","readSecuritySettings","bestPracticesProjectId","scorecardResult","lookUpBestPracticesProjectId","lookUpScorecardResult","buildQualitySecurityContent","summary","writeCoverageBadge","colourNames","level","\"fallow\"","coverageArguments","health","writeFallowBadge","grade","score","ciWorkflow","dependabotConfig","rustWorkspace","codeQLWorkflow","repositoryDetails","privateVulnerabilityReporting","vulnerabilityAlerts","checkRuns","readGitHubAPI","securityAndAnalysis","readSetting","checkAppSlugs","checkRun","ecosystemCount","pausedEcosystemCount","language","endpoint","stdout","project","scorecardURI","isScorecardOnlyPracticeLimited","result","formatManualNote","status","formatStatus","buildTableContent","rows","heading","row","formatEndpointBadge","badgePath","buildChecksContent","settings","ciNote","isInCI","testingRows","sonarCloudBadge","codeQualityRows","hasCodeQL","codeQLBadge","codeQLScope","codeQLLanguages","securityAnalysisRows","dependabotLink","dependencyRows","bestPracticesURL","scorecardLimitText","bestPracticesBadge","reportingText","checksResults","START_MARKER","END_MARKER","UPLOADED_MODULE_TYPE_IDS","INTERNAL_NPM_MODULE_TYPE_IDS","INTERNAL_NPM_WARNING","DEVELOPMENT_MANAGEMENT_TEXT","SHARED_MANAGEMENT_TEXT","documentUsage","cloneURL","resolveCloneURL","directoryName","resolveDirectoryName","nodeVersion","resolveVersion","npmVersion","typescriptVersion","\"typescript\"","buildIntroductionContent","packageJSONURL","buildUsageContent","url","range","match","typeId","management","API_REFERENCE_PATH","documentAPIReference","writeAPIReference","BUNDLE_REPORT_PATH","WORKER_REPORT_PATH","BUNDLE_START_MARKER","BUNDLE_END_MARKER","INDENT","BAR_WIDTH","BAR_CHARACTER","PART_BAR_CHARACTER","MIN_VISIBLE_PERCENT","SMALL_FILES_MAX_PERCENT","LABEL_MAX_LENGTH","BUNDLE_ANALYSIS_INTRO","BAR_NOTE","PART_ROW_NOTE","MORE_NOTE","UNTRACED_LABEL","WORKER_LABEL","WORKER_NOTE","WASM_LABEL_PREFIX","WASM_NOTE","UNTRACED_NOTE","documentBundleSizes","json","workerReport","workerJson","assetContents","resource","bundleTable","buildBundleTable","notes","note","assetGroups","buildAssetGroups","workerGroups","file","groups","separateEmbeddedContent","buildTotal","sum","group","assets","asset","resourceSizes","sizes","sortedGroups","compareGroups","fileTotal","buildShare","formatPercent","fitLabel","chunkSizes","renderGroupRows","isModuleLevel","workerText","findInlinedWorkerText","workerWasm","measureWasm","allWasm","separateWasm","separateWorker","variableName","declaration","quote","start","end","base64","countBase64Padding","wasm","formatBytes","untraced","untracedSizes","workerBytes","files","flattenWorkerGroups","groupName","formatGroupLabel","getSoleFileName","reportedBytes","zero","subtractBytes","bytes","groupSizes","composition","formatSeveralFilesLabel","renderFileRows","sortedFiles","smallCount","countSmallFiles","fileSizes","smallBytes","count","isTooSmallToShow","isCombinedRowStillSmall","bar","barCharacter","largestFileName","arrowIndex","prefix","pathMaxLength","dependencyPaths","buildDependencyPaths","resolveModule","addTo","dependency","dependencyPath","shortenCrateFileName","lastPathSegment","crateName","pct","whole","documentProject","isConnector","hasAPIReference","formatCode","formatTargets","existsSync","directory","lintCode","SAMPLE_DATA_BUCKET","putState","uploadDirectoryToR2","listFilesRecursively","sourceDirectory","uploadDirectory","filesByContentType","contentType","contentTypeFiles","bulkPutToR2","uploadSampleDataToR2","uploadModuleConfigToDO","stateId","uploadModuleToR2","currentDirectory","fullPath","relativePath","r2Path","uploadDirectoryPath","nonJavaScripContentType","listFolderPath","listFilePath","sourcePath","itemPath","keyPrefix","publishProject","isDeployedByScript","registerModule","moduleTypeName","releaseProject","builtConfigJSON","tagName","syncProjectWithGitHub","STEP_ICONS","TEST_TYPE_CONFIGS","testProject","stepNumber","testTypeConfig","testTypeIds","triggerGitHubRelease"],"sources":["../src/actions/auditDependencies_.json","../src/actions/auditDependencies.ts","../src/actions/buildProject.ts","../src/actions/checkConfigFiles.ts","../src/actions/checkDependencies.ts","../src/actions/checkProject.ts","../src/actions/documentActions.ts","../src/actions/documentContributingLicense.ts","../src/utilities/rustCrates.ts","../src/actions/documentDependencies.ts","../src/actions/documentOpening.ts","../src/actions/documentQualitySecurity.ts","../src/actions/documentUsage.ts","../src/actions/documentApiReference.ts","../src/actions/documentBundleSizes.ts","../src/actions/documentProject.ts","../src/actions/formatCode.ts","../src/actions/lintCode.ts","../src/utilities/cloudflare.ts","../src/actions/publishProject.ts","../src/actions/releaseProject.ts","../src/actions/syncProjectWithGitHub.ts","../src/actions/testProject.ts","../src/actions/triggerGitHubRelease.ts"],"sourcesContent":["{\n \"IGNORED_ADVISORIES\": [\n {\n \"id\": \"GHSA-fx2h-pf6j-xcff\",\n \"reason\": \"'vite', used by VitePress 1.x in dpuse-kb, which affects only the local dev server on Windows\",\n \"reviewBy\": \"2026-12-31\"\n },\n {\n \"id\": \"GHSA-wq5f-xc86-pv6w\",\n \"reason\": \"'sharp', pinned to 0.35.4 by miniflare, Wrangler's local Workers simulator, which runs only during development and is never deployed; remove once miniflare takes 0.35.5\",\n \"reviewBy\": \"2026-10-31\"\n },\n {\n \"id\": \"GHSA-xjj6-f33q-929c\",\n \"reason\": \"'undici', pinned to 7.29.1 by miniflare, Wrangler's local Workers simulator, which runs only during development and is never deployed; remove once miniflare takes 7.30.1\",\n \"reviewBy\": \"2026-11-30\"\n }\n ]\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\n// High or critical advisories in development tools that cannot reach a release or the publish credentials, and have no\n// fix yet. Remove an entry once a fix is released. After an entry's 'reviewBy' date the audit warns, so it is checked\n// again rather than kept by habit.\nimport { IGNORED_ADVISORIES } from './auditDependencies_.json';\nimport { DEVELOPMENT_ONLY_PACKAGE_NAMES, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, spawnCommand, spawnCommandForOutput } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A flaw 'npm audit' reports against a package. The other entries in a package's 'via' list are the names of the\n// packages the flaw reaches it through.\ninterface AuditAdvisory {\n name: string;\n severity: string;\n title: string;\n url: string;\n}\n\ninterface AuditReport {\n error?: { summary: string };\n vulnerabilities?: Record<string, { via: (AuditAdvisory | string)[] }>;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst BLOCKING_SEVERITIES = new Set(['critical', 'high']);\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Audit the project's dependencies for known security vulnerabilities. */\nexport async function auditDependencies(): Promise<void> {\n try {\n logOperationHeader('Audit Dependencies');\n\n // Users install these packages, so any vulnerability at all fails the audit, and none is ever ignored. A\n // development-only package ships nothing to users, so all its dependencies are checked as dev tools below.\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n if (DEVELOPMENT_ONLY_PACKAGE_NAMES.has(packageJSON.name ?? '')) {\n logStepHeader(`1️⃣ Shipped dependencies NOT checked: ${packageJSON.name ?? ''} is a development-only tool`);\n } else {\n await spawnCommand('1️⃣ Check shipped dependencies for any vulnerability', 'npm', ['audit', '--omit=dev']);\n }\n\n // Dev tools run during publishing, where they could reach the publish credentials, so high and critical flaws\n // fail. Lesser ones often await an upstream fix, so they pass, as do the ignored advisories.\n const output = await spawnCommandForOutput('2️⃣ Check all dependencies for high or critical vulnerabilities', 'npm', ['audit', '--json']);\n const report = JSON.parse(output) as AuditReport;\n if (report.error !== undefined) throw new Error(report.error.summary);\n\n const blockingAdvisories = checkAdvisories(listAdvisories(report));\n if (blockingAdvisories.length > 0) throw new Error(`${String(blockingAdvisories.length)} high or critical vulnerabilities found`);\n\n logOperationSuccess('Dependencies audited');\n } catch (error) {\n console.error('❌ Error auditing dependencies', error);\n process.exit(1);\n }\n}\n\n/** Names the high or critical advisories 'npm audit' reports that the CI audit ignores, as npm's own report cannot. */\nexport async function reportIgnoredAdvisories(label: string): Promise<void> {\n const report = JSON.parse(await spawnCommandForOutput(label, 'npm', ['audit', '--json'])) as AuditReport;\n if (report.error !== undefined) {\n console.warn(`⚠️ Could not check the allow list: ${report.error.summary}`);\n return;\n }\n\n let ignoredCount = 0;\n for (const advisory of listAdvisories(report)) {\n const ignoredAdvisory = BLOCKING_SEVERITIES.has(advisory.severity) ? findIgnoredAdvisory(advisory) : undefined;\n if (ignoredAdvisory === undefined) continue;\n console.warn(`⚠️ ${ignoredAdvisory.id} ('${advisory.name}') is on the allow list, so the CI audit ignores it: ${ignoredAdvisory.reason}`);\n ignoredCount++;\n }\n if (ignoredCount === 0) console.info('ℹ️ None of the reported advisories are on the allow list');\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Reports each high or critical advisory, as ignored or blocking, and returns the blocking ones. */\nfunction checkAdvisories(advisories: AuditAdvisory[]): AuditAdvisory[] {\n const today = new Date().toISOString().slice(0, 10);\n const blockingAdvisories: AuditAdvisory[] = [];\n\n for (const advisory of advisories) {\n if (!BLOCKING_SEVERITIES.has(advisory.severity)) continue;\n\n const ignoredAdvisory = findIgnoredAdvisory(advisory);\n if (ignoredAdvisory === undefined) {\n console.error(`❌ ${advisory.severity} '${advisory.name}': ${advisory.title} (${advisory.url})`);\n blockingAdvisories.push(advisory);\n } else if (ignoredAdvisory.reviewBy < today) {\n console.warn(`⚠️ Ignored ${ignoredAdvisory.id}, but its review date ${ignoredAdvisory.reviewBy} has passed: ${ignoredAdvisory.reason}`);\n } else {\n console.info(`ℹ️ Ignored ${ignoredAdvisory.id}: ${ignoredAdvisory.reason}`);\n }\n }\n\n return blockingAdvisories;\n}\n\n// npm names an advisory only by its URL, which ends in the id.\nfunction findIgnoredAdvisory(advisory: AuditAdvisory): (typeof IGNORED_ADVISORIES)[number] | undefined {\n const id = advisory.url.slice(advisory.url.lastIndexOf('/') + 1);\n return IGNORED_ADVISORIES.find((ignored) => ignored.id === id);\n}\n\n/** The distinct advisories in an 'npm audit --json' report. */\nfunction listAdvisories(report: AuditReport): AuditAdvisory[] {\n const advisories = new Map<string, AuditAdvisory>();\n const vulnerabilities = Object.values(report.vulnerabilities ?? {});\n for (const vulnerability of vulnerabilities) {\n for (const cause of vulnerability.via) if (typeof cause !== 'string') advisories.set(cause.url, cause);\n }\n return advisories.values().toArray();\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A project with Rust code names its WebAssembly build in this script, as the crate and target differ by project.\nconst WASM_BUILD_SCRIPT_NAME = 'build:wasm';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Builds the package using Vite. Output to '/dist' directory. Builds bundle analysis reports. */\nexport async function buildProject(): Promise<void> {\n try {\n logOperationHeader('Build Project');\n\n await bundleProject('1️⃣ ', await readJSONFile<PackageJson>('package.json'));\n\n logOperationSuccess('Project built');\n } catch (error) {\n console.error('❌ Error building project', error);\n process.exit(1);\n }\n}\n\n/** Bundles the project with Vite, first building its WebAssembly where the project has a 'build:wasm' script. */\nexport async function bundleProject(stepIcon: string, packageJSON: PackageJson): Promise<void> {\n if (packageJSON.scripts?.[WASM_BUILD_SCRIPT_NAME] != null) {\n await spawnCommand(`${stepIcon} Build WebAssembly`, 'npm', ['run', WASM_BUILD_SCRIPT_NAME]);\n }\n await spawnCommand(`${stepIcon} Bundle project`, 'vite', ['build']);\n}\n","// ── External Dependencies & Registrations\nimport { fileURLToPath } from 'node:url';\nimport type { PackageJson } from 'type-fest';\nimport path from 'node:path';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport {\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n ModuleTypeConfig,\n readJSONFile,\n readTextFile,\n readTextFileOrNull,\n RUST_WORKSPACE_PATH\n} from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst PRETTIER_CONFIG_REFERENCE = '@dpuse/dpuse-development/prettierrc';\nconst TEMPLATE_REPOSITORY_NAME = 'dpuse-development'; // Stands in for each project's own name in the SECURITY.md template.\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function checkConfigFiles(): Promise<void> {\n try {\n logOperationHeader('Check configuration files');\n\n logStepHeader('1️⃣ Check individual files');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const isPrivate = packageJSON.private === true; // Private packages have no CodeQL, Scorecard or security policy.\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\n await checkConfigFile(moduleDirectory, '.editorconfig');\n await checkConfigFile(moduleDirectory, '.gitattributes');\n await checkConfigFile(moduleDirectory, '.gitignore', ['.gitignore_default']);\n await checkConfigFile(moduleDirectory, '.markdownlint.json');\n await checkConfigFile(moduleDirectory, '.ncurc.json');\n await checkESLintConfig(moduleTypeConfig, moduleDirectory);\n await checkConfigFile(moduleDirectory, 'LICENSE');\n await checkTSConfig(moduleTypeConfig, moduleDirectory);\n await checkTSConfigScripts(moduleTypeConfig, moduleDirectory);\n await checkViteConfig(moduleTypeConfig, moduleDirectory);\n await checkVitestConfig(moduleTypeConfig, moduleDirectory);\n checkPrettierConfig(moduleTypeConfig, packageJSON);\n // Projects with Rust code pin their Rust version, and have Dependabot watch Cargo as well.\n const hasRust = (await readTextFileOrNull(RUST_WORKSPACE_PATH)) !== null;\n if (hasRust) await checkConfigFile(moduleDirectory, 'rust-toolchain.toml');\n const dependabotTemplate = `.github/dependabot${isPrivate ? '.private' : ''}${hasRust ? '.rust' : ''}.yml`;\n await checkConfigFile(moduleDirectory, '.github/dependabot.yml', [dependabotTemplate]);\n if (isPrivate) {\n await checkPrivateWorkflows(moduleDirectory);\n } else {\n await checkWorkflows(moduleDirectory);\n await checkConfigFile(moduleDirectory, 'SECURITY.md', [], (content) => content.replaceAll(TEMPLATE_REPOSITORY_NAME, () => configJSON.id));\n }\n\n logOperationSuccess('Configuration files checked');\n } catch (error) {\n console.error('❌ Error checking configuration files', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function checkESLintConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'eslint.config.js' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'eslint', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'eslint.config.js' is UNIQUE to this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'eslint.config.js', ['eslint.config.default.js']);\n }\n}\nfunction checkPrettierConfig(moduleTypeConfig: ModuleTypeConfig, packageJSON: PackageJson) {\n if (moduleTypeConfig.typeId === 'development') {\n console.info(\"ℹ️ File '.prettierrc.json' is the template\"); // Every other project points to this file.\n } else if (moduleTypeConfig.typeId === 'app') {\n console.info(\"⚠️ File '.prettierrc.json' is UNIQUE to this project\");\n } else if (packageJSON['prettier'] === PRETTIER_CONFIG_REFERENCE) {\n console.info(`ℹ️ Prettier configuration is '${PRETTIER_CONFIG_REFERENCE}'`);\n } else {\n console.info(`❌ Prettier configuration is NOT '${PRETTIER_CONFIG_REFERENCE}'`);\n }\n}\n\nasync function checkTSConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'tsconfig.json' is NOT required by this project\");\n } else if (['connector', 'cookbook', 'development', 'engine', 'presenter', 'shared', 'tool'].includes(moduleTypeConfig.typeId)) {\n await checkConfigFile(moduleDirectory, 'tsconfig.json');\n } else {\n console.info(\"⚠️ File 'tsconfig.json' is UNIQUE to this project\");\n }\n}\n\nasync function checkTSConfigScripts(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['github'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'scripts/tsconfig.json' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'scripts/tsconfig.json'); // Type-checks the 'scripts' folder, whose files Node runs directly.\n }\n}\n\nasync function checkViteConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n // The sample data is published as files, so it has nothing to bundle.\n if (['eslint', 'github', 'kb', 'resources'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vite.config.ts' is NOT required by this project\");\n } else if (['app', 'api', 'development', 'engine'].includes(moduleTypeConfig.typeId)) {\n console.info(\"⚠️ File 'vite.config.ts' is UNIQUE to this project\");\n } else {\n let viteConfigTemplates: string[];\n switch (moduleTypeConfig.typeId) {\n case 'presenter':\n viteConfigTemplates = ['vite.config.presenter.ts'];\n break;\n case 'tool':\n viteConfigTemplates = ['vite.config.tool.ts'];\n break;\n default:\n viteConfigTemplates = ['vite.config.default.ts'];\n }\n await checkConfigFile(moduleDirectory, 'vite.config.ts', viteConfigTemplates);\n }\n}\n// A private repository may still build and publish through GitHub, so the workflows it has are checked. CodeQL and\n// Scorecard only run on public repositories.\nasync function checkPrivateWorkflows(moduleDirectory: string) {\n for (const workflowPath of ['.github/workflows/ci.yml', '.github/workflows/publish.yml']) {\n if ((await readTextFileOrNull(workflowPath)) !== null) await checkConfigFile(moduleDirectory, workflowPath);\n }\n console.info(\"ℹ️ CodeQL and Scorecard workflows and file 'SECURITY.md' are NOT required by this project\");\n}\n\nasync function checkWorkflows(moduleDirectory: string) {\n await checkConfigFile(moduleDirectory, '.github/workflows/ci.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/codeql.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/publish.yml');\n await checkConfigFile(moduleDirectory, '.github/workflows/scorecard.yml');\n}\n\nasync function checkVitestConfig(moduleTypeConfig: ModuleTypeConfig, moduleDirectory: string) {\n if (['app', 'api', 'github', 'kb'].includes(moduleTypeConfig.typeId)) {\n console.info(\"ℹ️ File 'vitest.config.ts' is NOT required by this project\");\n } else {\n await checkConfigFile(moduleDirectory, 'vitest.config.ts');\n }\n}\n\nasync function checkConfigFile(moduleDirectory: string, checkFileName: string, templateFileNames: string[] = [], prepareTemplate = (content: string) => content): Promise<void> {\n const checkFilePath = path.resolve(process.cwd(), checkFileName);\n const templates = templateFileNames.length > 0 ? templateFileNames : [checkFileName];\n\n let checkFileContent;\n try {\n checkFileContent = await readTextFile(checkFilePath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (checkFileContent === undefined) {\n console.info(`❌ File '${checkFileName}' is MISSING`);\n return;\n }\n\n for (const templateFileName of templates) {\n const templatePath = path.resolve(moduleDirectory, `../${templateFileName}`);\n const templateContent = prepareTemplate(await readTextFile(templatePath));\n if (checkFileContent === templateContent) {\n console.info(`ℹ️ File '${checkFileName}' is the same as '${templateFileName}'`);\n return;\n }\n }\n\n console.info(`❌ File '${checkFileName}' is NOT the same`);\n}\n","// ── External Dependencies & Registrations\nimport path from 'node:path';\nimport type { RcOptions } from 'npm-check-updates';\nimport { run as runNpmCheckUpdates } from 'npm-check-updates';\n\n// ── Local Framework\nimport { reportIgnoredAdvisories } from '@/actions/auditDependencies';\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identifies outdated dependencies using npm outdated and npm-check-updates with option to automatically install\n * latest versions. */\nexport async function checkDependencies(): Promise<void> {\n try {\n logOperationHeader('Check Dependencies');\n\n await spawnCommand(\"1️⃣ Check using 'npm outdated'\", 'npm', ['outdated'], true);\n\n logStepHeader(\"2️⃣ Check using 'npm-check-updates'\");\n let rcOptions: RcOptions = {};\n try {\n rcOptions = await readJSONFile<RcOptions>(path.resolve(process.cwd(), '.ncurc.json'));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n await runNpmCheckUpdates({ interactive: true, upgrade: true, dep: 'dev,prod,peer,optional', install: 'never', ...rcOptions });\n\n // Not strict here, otherwise an upgraded package with a pinned approval fails the install before step 5 can move its pin.\n // No audit summary, as step 4 reports what is left once it has fixed what it can.\n await spawnCommand('3️⃣ Install updated dependencies', 'npm', ['install', '--prefer-online', '--no-strict-allow-scripts', '--no-audit', '--no-fund']);\n\n // Only upgrades the version ranges in package.json already allow; never '--force', which makes breaking ones. Runs before\n // the pins move in step 5, so a package it upgrades has its pin moved too. npm exits with an error while vulnerabilities\n // it cannot fix remain, such as those waiting on an upstream release, so that is reported without stopping the check.\n await spawnCommand('4️⃣ Fix vulnerabilities where a compatible upgrade exists', 'npm', ['audit', 'fix', '--no-strict-allow-scripts', '--no-fund'], true);\n await reportIgnoredAdvisories('4️⃣ Name the advisories above that the CI audit ignores');\n\n // Only packages already approved are re-approved, so a newly added install script still waits for review in step 8.\n // Name-only approvals already cover every version, so only pinned ones need moving. Runs before prune, which would\n // otherwise delete a pin to an upgraded version as 'not installed' before it could be moved.\n const pinnedPackageNames = await getPinnedPackageNames();\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('5️⃣ Move install-script pins to installed versions', 'npm', ['install-scripts', 'approve', ...pinnedPackageNames]);\n } else {\n logStepHeader('5️⃣ No pinned install-script approvals to move');\n }\n\n // Runs before the rebuild in step 7. A rebuild leaves npm's record of 'node_modules' out of date, and prune then misses\n // install scripts that 'npm install' still sees, as with 'fsevents' (npm 12.0.1). Also macOS only, as elsewhere it drops\n // entries for macOS-only packages that are not installed.\n if (process.platform === 'darwin') {\n await spawnCommand('6️⃣ Remove unused install-script entries', 'npm', ['install-scripts', 'prune']);\n } else {\n logStepHeader('6️⃣ Skipped removing unused install-script entries (macOS only)');\n }\n\n // Not strict, so any install script still awaiting review is reported once, by step 8.\n if (pinnedPackageNames.length > 0) {\n await spawnCommand('7️⃣ Run install scripts skipped in steps 3 and 4', 'npm', ['rebuild', ...pinnedPackageNames, '--no-strict-allow-scripts']);\n }\n\n // The same check a plain 'npm install' makes, which 'npm install-scripts ls' does not always agree with. Fails listing any\n // install scripts still awaiting review. Step 4 has already reported the audit.\n await spawnCommand('8️⃣ Confirm every install script is reviewed', 'npm', ['install', '--strict-allow-scripts', '--no-audit', '--no-fund']);\n\n logOperationSuccess('Dependencies checked');\n } catch (error) {\n console.error('❌ Error checking dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Keys are 'name', 'name@version' or '@scope/name@version'. An '@' after the first character marks a pin; it and the version\n// are dropped so npm matches every installed version.\nasync function getPinnedPackageNames(): Promise<string[]> {\n const { allowScripts = {} } = await readJSONFile<{ allowScripts?: Record<string, boolean> }>(path.resolve(process.cwd(), 'package.json'));\n const names = Object.entries(allowScripts)\n .filter(([key, isAllowed]) => isAllowed && key.lastIndexOf('@') > 0)\n .map(([key]) => key.slice(0, key.lastIndexOf('@')));\n return [...new Set(names)];\n}\n","// ── Local Framework\nimport { checkConfigFiles } from '@/actions/checkConfigFiles';\nimport { checkDependencies } from '@/actions/checkDependencies';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Checks the configuration files against the DPUse templates, then lists outdated dependencies. */\nexport async function checkProject(): Promise<void> {\n await checkConfigFiles();\n await checkDependencies();\n}\n","// ── DPUse Framework\nimport type { ConnectorActionName, ConnectorUsageId } from '@dpuse/dpuse-shared';\nimport { determineConnectorUsageId, getConnectorActionsTable } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- SUPPORTED_ACTIONS_START -->';\nconst END_MARKER = '<!-- SUPPORTED_ACTIONS_END -->';\n\nconst SUPPORTED_ACTIONS_INTRO =\n 'Connectors conform to a unified interface contract by implementing a specific subset of standard actions. These standardised actions allow the DPUse application to interact with any underlying data source in the same way, enabling Connectors to be built independently and loaded dynamically at runtime.';\n\nconst CONNECTOR_USAGE_DESCRIPTIONS: Record<ConnectorUsageId, string> = {\n source: 'This connector is a Source connector that supports only read actions. Connectors can also function as a Destination (write-only) or Bidirectional (read/write), depending on the actions they support.',\n destination:\n 'This connector is a Destination connector that supports only write actions. Connectors can also function as a Source (read-only) or Bidirectional (read/write), depending on the actions they support.',\n bidirectional:\n 'This connector is a Bidirectional connector that supports both read and write actions. Connectors can also function as a Source (read-only) or Destination (write-only), depending on the actions they support.',\n unknown:\n 'This connector does not yet implement any read or write actions, so its type cannot be determined. Connectors function as a Source (read-only), a Destination (write-only), or Bidirectional (read/write), depending on the actions they support.'\n};\n\nconst SUPPORTED_ACTIONS_TABLE_LEAD_IN = 'The table below lists all connector actions and highlights those supported by this connector.';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentActions(): Promise<void> {\n try {\n logOperationHeader('Document Actions');\n\n logStepHeader(\"1️⃣ Insert actions description and table into 'README.md'\");\n\n const config = await readJSONFile<{ actionNames?: string[] }>('config.json');\n const actionNames = (config.actionNames ?? []) as ConnectorActionName[];\n const usageId = determineConnectorUsageId(actionNames);\n const table = getConnectorActionsTable(actionNames);\n\n const block = `## Supported Actions\\n\\n${SUPPORTED_ACTIONS_INTRO}\\n\\n${CONNECTOR_USAGE_DESCRIPTIONS[usageId]} ${SUPPORTED_ACTIONS_TABLE_LEAD_IN}\\n\\n${table}`;\n\n await writeReadmeSection(block, START_MARKER, END_MARKER);\n\n logOperationSuccess('Actions documented');\n } catch (error) {\n console.error('❌ Error documenting actions', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport {\n CONTRIBUTING_LICENSE_END_MARKER,\n CONTRIBUTING_LICENSE_START_MARKER,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n readJSONFile,\n resolveOwnerAndRepository,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface LicenseModuleConfig {\n firstCreatedAt?: number | null;\n}\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Contributing and License sections. */\nexport async function documentContributingLicense(): Promise<void> {\n try {\n logOperationHeader('Document Contributing & License');\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<LicenseModuleConfig>('config.json')]);\n\n const { owner, repository } = resolveOwnerAndRepository(packageJSON, 'document contributing and license');\n const authorName = resolveAuthorName(packageJSON);\n const copyrightYear = resolveCopyrightYear(configJSON.firstCreatedAt);\n\n logStepHeader(\"1️⃣ Insert contributing and license content into 'README.md'\");\n\n await migrateGovernanceSection();\n await writeReadmeSection(buildContributingLicenseContent(owner, repository, authorName, copyrightYear), CONTRIBUTING_LICENSE_START_MARKER, CONTRIBUTING_LICENSE_END_MARKER);\n\n logOperationSuccess('Contributing & license documented');\n } catch (error) {\n console.error('❌ Error documenting contributing and license', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveAuthorName(packageJSON: PackageJson): string {\n const author = packageJSON.author;\n const authorString = typeof author === 'string' ? author : author?.name;\n if (authorString == null || authorString === '') throw new Error(\"package.json 'author' field is required to document contributing and license.\");\n\n // Drop the first '<email>' and the spaces around it, keeping one space between what came before and after it, as in\n // npm's 'Name <email> (url)' form. Not a regex, as '\\s*<' backtracks on long runs of spaces.\n const emailStart = authorString.indexOf('<');\n const emailEnd = emailStart === -1 ? -1 : authorString.indexOf('>', emailStart);\n return emailEnd === -1 ? authorString.trim() : [authorString.slice(0, emailStart).trim(), authorString.slice(emailEnd + 1).trim()].filter((part) => part !== '').join(' ');\n}\n\nfunction resolveCopyrightYear(firstCreatedAt: number | null | undefined): string {\n const currentYear = new Date().getFullYear();\n if (firstCreatedAt == null) return String(currentYear);\n\n const startYear = new Date(firstCreatedAt).getFullYear();\n return startYear === currentYear ? String(currentYear) : `${String(startYear)}-present`;\n}\n\nfunction buildContributingLicenseContent(owner: string, repository: string, authorName: string, copyrightYear: string): string {\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n\n return `## Contributing\n\nThis repository is maintained solely by its owner and does not, at present, accept external contributions into the canonical repo. Its source is published openly under the MIT License — every DPUse project is fully open source except DPUse Engine, which remains closed and proprietary.\n\nFor security vulnerabilities, see [Reporting Vulnerabilities](#reporting-vulnerabilities). For bugs, inconsistencies, or other feedback, [open a GitHub issue](${repositoryURL}/issues) — feedback is read, but responses and fixes are at the maintainer's discretion.\n\n## License\n\nThis project is licensed under the MIT License, permitting free use, modification, and distribution.\n\n[MIT](./LICENSE) © ${copyrightYear} ${authorName}`;\n}\n","/* eslint-disable security/detect-non-literal-fs-filename -- Paths come from Cargo's own output and this project's folders, not user input. */\n\n// ── External Dependencies & Registrations\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport satisfies from 'spdx-satisfies';\n\n// ── Local Framework\nimport { logStepHeader, readJSONFile, readTextFile, readTextFileOrNull, RUST_WORKSPACE_PATH, spawnCommandToFile } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** A crate compiled into the project's WebAssembly, with where to find its licence and its release history. */\nexport interface RustCrate {\n name: string;\n version: string;\n licenseExpression: string;\n repository: string;\n licenseFiles: { label: string; path: string }[]; // Relative to the 'licenses' folder.\n publishedDate: string;\n latestVersion: string;\n latestPublishedDate: string;\n}\n\n/** One line of Cargo's dependency tree. The project's own crates are in it too, so the tree reads from them down. */\nexport interface RustCrateTreeItem {\n name: string;\n version: string;\n depth: number;\n isOwn: boolean;\n}\n\ninterface CargoMetadata {\n packages: { name: string; version: string; manifest_path: string }[];\n}\n\ninterface CratesIOResponse {\n crate?: { max_stable_version?: string | null; max_version?: string };\n versions?: { num: string; created_at: string }[];\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst CARGO_METADATA_PATH = 'licenses/cargoMetadata.json';\nconst CARGO_TREE_PATH = 'licenses/cargoTree.txt';\nconst CRATES_IO_REQUEST_INTERVAL = 1000; // crates.io asks automated clients for no more than one request a second.\nconst CRATES_IO_REQUEST_TIMEOUT = 10_000; // Without one, a request crates.io never answers would hang the release.\nconst CRATES_IO_USER_AGENT = 'dpuse-development (https://github.com/dpuse/dpuse-development)'; // crates.io refuses requests without one.\nconst LICENSE_FILE_PATTERN = /^(?:copying|licen[cs]e|unlicense)/i;\nconst WASM_TARGET = 'wasm32-unknown-unknown';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Lists the crates compiled into the project's WebAssembly, checks each licence against those allowed, and copies\n * each licence file to 'licenses/downloads'. Returns null for a project with no Rust code. Only normal dependencies\n * built for WebAssembly are followed: development and build dependencies, and macros (which run only while compiling),\n * put none of their code in the output. */\nexport async function documentRustCrates(stepLabel: string, allowedLicenses: string): Promise<{ crates: RustCrate[]; treeItems: RustCrateTreeItem[] } | null> {\n if ((await readTextFileOrNull(RUST_WORKSPACE_PATH)) === null) return null;\n\n const cargoArguments = ['--manifest-path', RUST_WORKSPACE_PATH, '--locked'];\n const treeArguments = ['tree', ...cargoArguments, '--workspace', '--edges', 'normal,no-proc-macro', '--target', WASM_TARGET, '--prefix', 'depth', '--format', '{p}|{l}|{r}'];\n await spawnCommandToFile(stepLabel, 'cargo', treeArguments, CARGO_TREE_PATH);\n await spawnCommandToFile(stepLabel, 'cargo', ['metadata', ...cargoArguments, '--format-version', '1', '--filter-platform', WASM_TARGET], CARGO_METADATA_PATH);\n const treeLines = parseCargoTree(await readTextFile(CARGO_TREE_PATH));\n const metadata = await readJSONFile<CargoMetadata>(CARGO_METADATA_PATH);\n // Both hold paths on this machine, so are not kept.\n await fs.rm(CARGO_TREE_PATH, { force: true });\n await fs.rm(CARGO_METADATA_PATH, { force: true });\n\n const cratesByKey = new Map<string, RustCrate>();\n for (const line of treeLines) {\n if (line.isOwn || cratesByKey.has(`${line.name}@${line.version}`)) continue;\n cratesByKey.set(`${line.name}@${line.version}`, {\n name: line.name,\n version: line.version,\n licenseExpression: line.licenseExpression,\n repository: line.repository === '' ? `https://crates.io/crates/${line.name}` : line.repository,\n licenseFiles: [],\n publishedDate: '',\n latestVersion: '',\n latestPublishedDate: ''\n });\n }\n const crates = cratesByKey.values().toArray();\n\n checkCrateLicenses(crates, allowedLicenses);\n for (const crate of crates) crate.licenseFiles = await copyLicenseFiles(crate, metadata);\n await addReleaseDetails(stepLabel, crates);\n\n return { crates, treeItems: treeLines.map(({ name, version, depth, isOwn }) => ({ name, version, depth, isOwn })) };\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Each line reads '<depth><name> v<version>[ (<source>)]|<licence>|<repository>', with ' (*)' added where Cargo has\n// already listed the crate's dependencies higher up. Crate names never start with a digit, so the depth is the leading\n// digits. A crate whose source is a folder, rather than a registry or Git URL, is one of the project's own.\nfunction parseCargoTree(text: string): (RustCrateTreeItem & { licenseExpression: string; repository: string })[] {\n const lines = [];\n for (const line of text.split('\\n')) {\n const [crateText = '', licenseExpression = '', linkText = ''] = line.trim().split('|', 3);\n const depthText = /^\\d+/.exec(crateText)?.[0];\n if (depthText === undefined) continue;\n const [name = '', versionText = '', ...sourceParts] = crateText.slice(depthText.length).split(' ');\n const source = sourceParts.join(' ').replace(/^\\(/, '').replace(/\\)$/, '');\n const isOwn = source !== '' && !source.includes('://');\n const link = linkText.replace(/ \\(\\*\\)$/, '');\n lines.push({ name, version: versionText.replace(/^v/, ''), depth: Number(depthText), isOwn, licenseExpression, repository: link });\n }\n return lines;\n}\n\n// Cargo's licence field is an SPDX expression, so it is checked as one: 'MIT OR Apache-2.0' needs either, while\n// '(MIT OR Apache-2.0) AND Unicode-3.0' also needs 'Unicode-3.0'. The older 'MIT/Apache-2.0' form means 'OR'.\nfunction checkCrateLicenses(crates: RustCrate[], allowedLicenses: string): void {\n const allowedIdentifiers = allowedLicenses.split(';').filter((identifier) => isLicenseIdentifier(identifier));\n const failures = crates.filter((crate) => !isLicenseAllowed(crate.licenseExpression, allowedIdentifiers));\n if (failures.length === 0) return;\n const failureList = failures.map((crate) => `${crate.name}@${crate.version} (${crate.licenseExpression === '' ? 'no licence' : crate.licenseExpression})`).join(', ');\n throw new Error(`Rust crates with licences not allowed: ${failureList}.`);\n}\n\n// The allow list can also name licences that are not SPDX identifiers, such as a licence page, which only npm packages use.\nfunction isLicenseIdentifier(identifier: string): boolean {\n try {\n return satisfies(identifier, [identifier]);\n } catch {\n return false;\n }\n}\n\nfunction isLicenseAllowed(licenseExpression: string, allowedIdentifiers: string[]): boolean {\n try {\n return satisfies(licenseExpression.replaceAll('/', ' OR '), allowedIdentifiers);\n } catch {\n return false; // Not a licence expression at all, so it cannot be confirmed as allowed.\n }\n}\n\n// The licence files sit beside the crate's own 'Cargo.toml' in Cargo's download cache.\nasync function copyLicenseFiles(crate: RustCrate, metadata: CargoMetadata): Promise<{ label: string; path: string }[]> {\n const cratePackage = metadata.packages.find((candidate) => candidate.name === crate.name && candidate.version === crate.version);\n if (cratePackage == null) return [];\n const crateDirectory = path.dirname(cratePackage.manifest_path);\n const directoryEntries = await fs.readdir(crateDirectory);\n const fileNames = directoryEntries.filter((fileName) => LICENSE_FILE_PATTERN.test(fileName)).toSorted((a, b) => a.localeCompare(b, 'en'));\n await fs.mkdir('licenses/downloads', { recursive: true });\n const licenseFiles = [];\n for (const fileName of fileNames) {\n const copiedPath = `downloads/${crate.name}@${crate.version}-${fileName}`;\n await fs.copyFile(path.join(crateDirectory, fileName), path.join('licenses', copiedPath));\n licenseFiles.push({ label: fileName, path: copiedPath });\n }\n return licenseFiles;\n}\n\n// One request at a time, as crates.io asks. A crate it cannot answer for is shown without dates.\nasync function addReleaseDetails(stepLabel: string, crates: RustCrate[]): Promise<void> {\n logStepHeader(`${stepLabel} - fetch release dates from crates.io`);\n for (const [index, crate] of crates.entries()) {\n if (index > 0) await delay(CRATES_IO_REQUEST_INTERVAL);\n console.info(`⚙️ Fetching '${crate.name}' (${String(index + 1)} of ${String(crates.length)})...`);\n try {\n const response = await fetch(`https://crates.io/api/v1/crates/${encodeURIComponent(crate.name)}`, {\n headers: { 'User-Agent': CRATES_IO_USER_AGENT },\n signal: AbortSignal.timeout(CRATES_IO_REQUEST_TIMEOUT)\n });\n if (!response.ok) continue;\n const data = (await response.json()) as CratesIOResponse;\n const releaseDates = new Map((data.versions ?? []).map((version) => [version.num, version.created_at]));\n crate.latestVersion = data.crate?.max_stable_version ?? data.crate?.max_version ?? '';\n crate.publishedDate = releaseDates.get(crate.version) ?? '';\n crate.latestPublishedDate = crate.latestVersion === crate.version ? '' : (releaseDates.get(crate.latestVersion) ?? '');\n } catch {\n // Ignore network errors and timeouts.\n }\n }\n}\n\n/* eslint-enable security/detect-non-literal-fs-filename -- End of the Rust crate documentation's file access. */\n","// ── External Dependencies & Registrations\n// TODO: 'license-checker-rseidelsohn' is being retired in favour of '@lizenz/checker'. Switch when '@lizenz/checker'\n// reaches 1.0.0, a drop-in replacement: change these two imports and the README link text in 'buildLicensesIntro'.\n// It is BSD-3-Clause, not MIT. Longer term, 'npm sbom --omit dev' could replace it with no extra dependencies, but the\n// allowed-licence check and licence-file lookup would then need writing here.\nimport { init as initLicenseChecker } from 'license-checker-rseidelsohn';\nimport type { InitOpts } from 'license-checker-rseidelsohn';\n\n// ── Local Framework\nimport { documentRustCrates } from '@/utilities/rustCrates';\nimport { SHIPPED_PACKAGES_FILE_NAME } from '@/vite';\nimport type { ShippedPackagesRecord } from '@/vite';\nimport {\n clearDirectory,\n DEVELOPMENT_ONLY_PACKAGE_NAMES,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n readJSONFile,\n readTextFileOrNull,\n spawnCommandToFile,\n writeReadmeSection\n} from '@/utilities';\nimport type { RustCrate, RustCrateTreeItem } from '@/utilities/rustCrates';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface License {\n name: string;\n repository: string;\n licenseTypes: string;\n installedVersion: string;\n latestVersion: string;\n latestPublishedDate: string;\n author: string;\n publishedDate: string;\n licenseFiles: { label: string; path: string }[]; // Relative to the 'licenses' folder.\n}\n\ninterface ProductionPackageLicense {\n licenses: string;\n repository?: string;\n publisher?: string;\n email?: string;\n path?: string;\n licenseFile?: string;\n}\n\ninterface PackageLock {\n packages?: Record<string, PackageLockEntry>;\n}\n\ninterface PackageLockEntry {\n name?: string;\n version?: string;\n link?: boolean;\n resolved?: string;\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n peerDependenciesMeta?: Record<string, { optional?: boolean }>;\n}\n\ninterface RootPackage {\n name?: string;\n version?: string;\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n}\n\ninterface ShippedReadmeContext {\n allowedLicenses: string;\n productionNames: Set<string>;\n rustCrates: { crates: RustCrate[]; treeItems: RustCrateTreeItem[] } | null;\n shippedKeys: Set<string>;\n}\n\ninterface ShippedTreeContext {\n licensesByKey: Map<string, License>;\n shippedKeys: Set<string>;\n shownKeys: Set<string>;\n}\n\ninterface NpmPackageTree {\n version?: string;\n dependencies?: Record<string, NpmPackageTree>;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- DEPENDENCY_LICENSES_START -->';\nconst END_MARKER = '<!-- DEPENDENCY_LICENSES_END -->';\nconst LICENSES_HEADING = '## Dependency Licenses';\nconst SHIPPED_PACKAGES_RECORD_PATH = `bundle-analysis-reports/${SHIPPED_PACKAGES_FILE_NAME}`; // Written by the 'recordShippedPackages' build plugin.\nconst LICENSE_TREE_PATH = 'licenses/licenseTree.json';\n\nconst DEPENDENCY_TREE_FLAGS =\n \"Packages flagged ❗ have a newer version available; ⚠️ indicates a package that hasn't been updated in the last 6 months or longer. Neither flag necessarily indicates a problem: we let new releases stabilise before upgrading, and some packages are mature and stable (have limited or no dependencies), so they require no active development.\";\nconst DEPENDENCY_TREE_INTRO = `The dependency tree below lists every package in this project — direct and transitive — along with its installed version, release date, and update status. ${DEPENDENCY_TREE_FLAGS}`;\nconst SHIPPED_TREE_INTRO = `The dependency tree below shows how each package in the table above is reached — direct and transitive — along with its installed version, release date, and update status. A package that does not ship itself, such as one whose parts are bundled separately, is left out and what ships beneath it is shown in its place. ${DEPENDENCY_TREE_FLAGS}`;\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Identify licenses of the project's production and peer dependencies. Updates the table in the Dependency Licenses\n * section of this page and summary files licenses.json and licenseTree.json in th licenses directory of this\n * repository. Also downloads a copy of dependency license to `licenses/downloads'. */\nexport async function documentDependencies(allowedLicenses = 'MIT'): Promise<void> {\n try {\n logOperationHeader('Document Dependencies');\n\n const rootPackage = await readJSONFile<RootPackage>('package.json');\n\n const packageName = rootPackage.name ?? '';\n if (DEVELOPMENT_ONLY_PACKAGE_NAMES.has(packageName)) {\n await skipDependencyDocumentation(packageName);\n logOperationSuccess('Dependencies documented');\n return;\n }\n\n await clearDirectory('1️⃣ Clear downloaded licenses', 'licenses/downloads');\n const lockPackages = await readLockPackages();\n const shippedRecord = await readShippedRecord();\n\n if (shippedRecord === null) {\n // No build record, such as for a project not built with Vite: fall back to the declared dependencies.\n const unshippedPackages = listUnshippedPackages(lockPackages);\n await checkLicenses('2️⃣ Identify production licenses', allowedLicenses, [rootPackage.name ?? '', ...unshippedPackages], true);\n await spawnCommandToFile('3️⃣ Identify transitive dependencies', 'npm', ['ls', '--all', '--json', '--omit=dev'], LICENSE_TREE_PATH);\n await insertDeclaredLicensesIntoReadme('4️⃣ ', allowedLicenses, new Set(unshippedPackages));\n } else {\n const shippedKeys = collectShippedKeys(shippedRecord, lockPackages);\n const installedKeys = listInstalledKeys(lockPackages);\n const notShipped = installedKeys.filter((packageKey) => !shippedKeys.has(packageKey));\n // Not limited to production dependencies: a package listed for development, such as an icon set, still ships\n // when the build bundles it.\n await checkLicenses('2️⃣ Identify shipped licenses', allowedLicenses, [rootPackage.name ?? '', ...notShipped], false);\n warnOfMissingPackages(shippedKeys, new Set(installedKeys));\n // The whole installed tree, as a shipped package may be listed for development. Problems npm reports in the\n // development tools' part of it do not stop the tree being written.\n await spawnCommandToFile('3️⃣ Identify transitive dependencies', 'npm', ['ls', '--all', '--json'], LICENSE_TREE_PATH, true);\n const rustCrates = await documentRustCrates('4️⃣ Identify Rust crates compiled into the WebAssembly', allowedLicenses);\n const readmeContext = { allowedLicenses, productionNames: listProductionNames(rootPackage), rustCrates, shippedKeys };\n await insertShippedLicensesIntoReadme(rustCrates === null ? '4️⃣ ' : '5️⃣ ', readmeContext);\n }\n\n logOperationSuccess('Dependencies documented');\n } catch (error) {\n console.error('❌ Error documenting dependencies', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nasync function skipDependencyDocumentation(name: string): Promise<void> {\n logStepHeader(`1️⃣ Skip: ${name} is a development-only tool and is never part of a production release.`);\n\n const message = `> [!WARNING]\\n> Dependency licenses are not documented here: ${name} is a development-only tool and is never part of a production release.`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${message}`, START_MARKER, END_MARKER);\n}\n\nasync function insertDeclaredLicensesIntoReadme(stepIcon: string, allowedLicenses: string, unshippedPackages: Set<string>): Promise<void> {\n logStepHeader(`${stepIcon} Insert licenses into 'README.md'`);\n\n const licenseTree = await readJSONFile<NpmPackageTree>(LICENSE_TREE_PATH);\n const licensesByKey = await readLicenses();\n\n const licensesIntro = buildLicensesIntro(allowedLicenses, false);\n let licensesContent = `${licensesIntro}\\n\\n|Dependency|Version|License(s)|Document|\\n|:-|:-:|:-|:-|\\n`;\n for (const license of licensesByKey.values()) {\n licensesContent += formatLicenseRow(license);\n }\n\n const treeItems: string[] = [];\n if (licenseTree.dependencies != null) {\n walkTreeList(licenseTree.dependencies, licensesByKey, unshippedPackages, treeItems, 0);\n }\n const treeContent = `${DEPENDENCY_TREE_INTRO}\\n\\n${treeItems.join('\\n')}`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${licensesContent.trimEnd()}\\n\\n### Dependency Tree\\n\\n${treeContent}`, START_MARKER, END_MARKER);\n}\n\n// A table of exactly what the build ships, and the tree showing how each package is reached, with its release. Where\n// the project has Rust code, the table gains a Type column and lists the npm packages before the Rust crates, and the\n// tree is split in two, as neither kind of dependency can reach the other.\nasync function insertShippedLicensesIntoReadme(stepIcon: string, context: ShippedReadmeContext): Promise<void> {\n logStepHeader(`${stepIcon} Insert licenses into 'README.md'`);\n\n const { allowedLicenses, productionNames, rustCrates, shippedKeys } = context;\n const licensesByKey = await readLicenses();\n const crateLicensesByKey = new Map((rustCrates?.crates ?? []).map((crate) => [`${crate.name}@${crate.version}`, convertCrateToLicense(crate)]));\n const hasRustCrates = rustCrates !== null;\n const tableHeader = hasRustCrates ? '|Type|Dependency|Version|License(s)|Document|\\n|:-|:-|:-:|:-|:-|' : '|Dependency|Version|License(s)|Document|\\n|:-|:-:|:-|:-|';\n let licensesContent = `${buildLicensesIntro(allowedLicenses, true, hasRustCrates)}\\n\\n${tableHeader}\\n`;\n for (const license of licensesByKey.values().toArray().toSorted(compareLicenses)) {\n licensesContent += formatLicenseRow(license, hasRustCrates ? 'JavaScript' : undefined);\n }\n for (const license of crateLicensesByKey.values().toArray().toSorted(compareLicenses)) {\n licensesContent += formatLicenseRow(license, 'Rust');\n }\n\n // Production dependencies first, so a package reached both ways is placed under the one that ships it.\n const licenseTree = await readJSONFile<NpmPackageTree>(LICENSE_TREE_PATH);\n const rootEntries = Object.entries(licenseTree.dependencies ?? {}).toSorted(([a], [b]) => Number(!productionNames.has(a)) - Number(!productionNames.has(b)));\n const treeItems: string[] = [];\n walkShippedTree(rootEntries, { licensesByKey, shippedKeys, shownKeys: new Set() }, treeItems, 0, false);\n const javaScriptTree = treeItems.length === 0 ? 'None.' : treeItems.join('\\n');\n const rustTree = (rustCrates?.treeItems ?? []).map((item) => formatCrateTreeItem(item, crateLicensesByKey)).join('\\n');\n const treeContent = hasRustCrates ? `${SHIPPED_TREE_INTRO}\\n\\n#### JavaScript\\n\\n${javaScriptTree}\\n\\n#### Rust\\n\\n${rustTree}` : `${SHIPPED_TREE_INTRO}\\n\\n${javaScriptTree}`;\n\n await writeReadmeSection(`${LICENSES_HEADING}\\n\\n${licensesContent.trimEnd()}\\n\\n### Dependency Tree\\n\\n${treeContent}`, START_MARKER, END_MARKER);\n}\n\nfunction compareLicenses(a: License, b: License): number {\n return a.name.localeCompare(b.name, 'en') || a.installedVersion.localeCompare(b.installedVersion, 'en');\n}\n\nfunction convertCrateToLicense(crate: RustCrate): License {\n return {\n name: crate.name,\n repository: crate.repository,\n licenseTypes: crate.licenseExpression,\n installedVersion: crate.version,\n latestVersion: crate.latestVersion,\n latestPublishedDate: crate.latestPublishedDate,\n author: '',\n publishedDate: crate.publishedDate,\n licenseFiles: crate.licenseFiles\n };\n}\n\n// The project's own crates head their part of the tree; they are this project's code, so have no licence row.\nfunction formatCrateTreeItem(item: RustCrateTreeItem, crateLicensesByKey: Map<string, License>): string {\n const indent = ' '.repeat(item.depth);\n return item.isOwn\n ? `${indent}- **${item.name}** ${item.version} — this project's Rust code, compiled into its WebAssembly`\n : formatTreeItem(item.name, item.version, crateLicensesByKey.get(`${item.name}@${item.version}`), indent);\n}\n\nfunction listProductionNames(rootPackage: RootPackage): Set<string> {\n return new Set([...Object.keys(rootPackage.dependencies ?? {}), ...Object.keys(rootPackage.optionalDependencies ?? {}), ...Object.keys(rootPackage.peerDependencies ?? {})]);\n}\n\nasync function readLicenses(): Promise<Map<string, License>> {\n const licenses = await readJSONFile<Record<string, ProductionPackageLicense>>('licenses/licenses.json');\n const licensesByKey = new Map<string, License>();\n for (const [key, value] of Object.entries(licenses)) {\n licensesByKey.set(key, parseLicenseEntry(key, value));\n }\n await Promise.all(\n licensesByKey.values().map(async (license) => {\n const data = await fetchNpmData(license.name, license.installedVersion);\n license.latestVersion = data.latestVersion;\n license.latestPublishedDate = data.latestPublishedDate;\n license.publishedDate = data.publishedDate;\n })\n );\n return licensesByKey;\n}\n\nasync function checkLicenses(stepLabel: string, allowedLicenses: string, excludedKeys: string[], isProductionOnly: boolean): Promise<void> {\n logStepHeader(stepLabel);\n await new Promise<void>((resolve, reject) => {\n const options: InitOpts & { files: string; relativeModulePath: boolean } = {\n start: process.cwd(),\n production: isProductionOnly,\n json: true,\n files: 'licenses/downloads',\n relativeModulePath: true,\n relativeLicensePath: true,\n onlyAllow: allowedLicenses,\n excludePackages: excludedKeys.join(';'),\n out: 'licenses/licenses.json'\n };\n initLicenseChecker(options, (error: Error | undefined) => {\n if (error == null) {\n resolve();\n } else {\n reject(error);\n }\n });\n });\n}\n\nasync function readLockPackages(): Promise<Record<string, PackageLockEntry>> {\n const lockText = await readTextFileOrNull('package-lock.json');\n return lockText === null ? {} : ((JSON.parse(lockText) as PackageLock).packages ?? {});\n}\n\nasync function readShippedRecord(): Promise<ShippedPackagesRecord | null> {\n const recordText = await readTextFileOrNull(SHIPPED_PACKAGES_RECORD_PATH);\n return recordText === null ? null : (JSON.parse(recordText) as ShippedPackagesRecord);\n}\n\n// The recorded packages, plus each package the build leaves to be installed by name, with whatever that one brings.\nfunction collectShippedKeys(record: ShippedPackagesRecord, lockPackages: Record<string, PackageLockEntry>): Set<string> {\n const shippedKeys = new Set(record.packages);\n for (const externalName of record.external) {\n const lockPath = resolveLockPath(lockPackages, '', externalName);\n if (lockPath === undefined) continue;\n for (const shippedPath of [lockPath, ...findShippedPaths(lockPackages, lockPath)]) {\n const entry = lockPackages[shippedPath];\n if (entry?.version !== undefined) shippedKeys.add(formatPackageKey(shippedPath, entry));\n }\n }\n return shippedKeys;\n}\n\nfunction listInstalledKeys(lockPackages: Record<string, PackageLockEntry>): string[] {\n const installedKeys = new Set<string>();\n for (const [lockPath, entry] of Object.entries(lockPackages)) {\n if (lockPath !== '' && entry.version !== undefined) installedKeys.add(formatPackageKey(lockPath, entry));\n }\n return [...installedKeys];\n}\n\n// A recorded package that is not installed means the record is from an older build, so its licence goes unchecked.\nfunction warnOfMissingPackages(shippedKeys: Set<string>, installedKeys: Set<string>): void {\n const missingKeys = [...shippedKeys.difference(installedKeys)];\n if (missingKeys.length > 0) console.warn(`⚠️ Not installed, so not checked; rebuild to refresh the record: ${missingKeys.join(', ')}`);\n}\n\nfunction formatPackageKey(lockPath: string, entry: PackageLockEntry): string {\n const name = entry.name ?? lockPath.slice(lockPath.lastIndexOf('node_modules/') + 'node_modules/'.length);\n return `${name}@${String(entry.version)}`;\n}\n\n// Packages installed but never shipped, as 'name@version'. A package ships when the project's own dependencies reach it\n// through dependencies, optional dependencies or required peers. Optional peers are not followed: TypeScript as\n// valibot's optional peer, or Vite as vue-router's, is installed only because a development tool needs it. The tree is\n// walked rather than npm's 'dev' flags trusted, as npm marks some packages under a development-only one as merely\n// 'optional', such as lightningcss's platform binary under Vite. The licence checker follows every link, so without\n// this it would count such packages as shipped. A package also installed, at the same version, for a shipped reason is kept.\nfunction listUnshippedPackages(lockPackages: Record<string, PackageLockEntry>): string[] {\n const shippedPaths = findShippedPaths(lockPackages, '');\n const shipped = new Set<string>();\n const unshipped = new Set<string>();\n for (const [lockPath, entry] of Object.entries(lockPackages)) {\n if (lockPath === '' || entry.version === undefined) continue;\n const packageKey = formatPackageKey(lockPath, entry);\n if (shippedPaths.has(lockPath)) shipped.add(packageKey);\n else unshipped.add(packageKey);\n }\n return unshipped\n .values()\n .filter((packageKey) => !shipped.has(packageKey))\n .toArray();\n}\n\n// The lock file paths reached from a starting entry, the project's own by default, following the links that ship with a package.\nfunction findShippedPaths(packages: Record<string, PackageLockEntry>, startPath: string): Set<string> {\n const shippedPaths = new Set<string>();\n const pendingPaths = [startPath];\n while (pendingPaths.length > 0) {\n const fromPath = pendingPaths.pop() ?? '';\n const entry = packages[fromPath];\n if (entry === undefined) continue;\n for (const name of listShippedDependencyNames(entry)) {\n const lockPath = resolveLockPath(packages, fromPath, name);\n if (lockPath === undefined || shippedPaths.has(lockPath)) continue;\n shippedPaths.add(lockPath);\n pendingPaths.push(lockPath);\n }\n }\n return shippedPaths;\n}\n\nfunction listShippedDependencyNames(entry: PackageLockEntry): string[] {\n const requiredPeerNames = Object.keys(entry.peerDependencies ?? {}).filter((name) => entry.peerDependenciesMeta?.[name]?.optional !== true);\n return [...Object.keys(entry.dependencies ?? {}), ...Object.keys(entry.optionalDependencies ?? {}), ...requiredPeerNames];\n}\n\n// Finds a dependency where Node would: in the package's own 'node_modules', then in each enclosing one up to the\n// project's. A linked package, such as a workspace, resolves to the folder it links to.\nfunction resolveLockPath(packages: Record<string, PackageLockEntry>, fromPath: string, name: string): string | undefined {\n let basePath = fromPath;\n for (;;) {\n const candidatePath = basePath === '' ? `node_modules/${name}` : `${basePath}/node_modules/${name}`;\n const entry = packages[candidatePath];\n if (entry !== undefined) return entry.link === true && entry.resolved !== undefined ? entry.resolved : candidatePath;\n if (basePath === '') return undefined;\n const parentIndex = basePath.lastIndexOf('/node_modules/');\n basePath = parentIndex === -1 ? '' : basePath.slice(0, parentIndex);\n }\n}\n\nfunction buildLicensesIntro(allowedLicenses: string, isFromBuild: boolean, hasRustCrates = false): string {\n const licenseListText = formatLicenseListText(allowedLicenses.split(';'));\n const tools = hasRustCrates\n ? '[license-checker](https://github.com/RSeidelsohn/license-checker-rseidelsohn) and [cargo tree](https://doc.rust-lang.org/cargo/commands/cargo-tree.html)'\n : '[license-checker](https://github.com/RSeidelsohn/license-checker-rseidelsohn)';\n const buildScope =\n \"The following table lists every package whose code, styles or assets are included in this project's build, as recorded by the build itself. Modules loaded at run time are not included; each documents its own.\";\n const rustScope =\n ' It also lists every Rust crate compiled into its WebAssembly, as resolved by Cargo; macros and other crates used only while compiling put none of their code in it, so are left out.';\n const fromBuildScope = hasRustCrates ? `${buildScope}${rustScope}` : buildScope;\n const scope = isFromBuild\n ? fromBuildScope\n : 'The following table lists all production dependencies. This project has no build record, so the list is taken from its declared dependencies.';\n return `License data is updated each time \\`npm run document\\` is run, using ${tools}. ${scope} These dependencies have been checked and confirmed to use ${licenseListText}, all of which allow commercial use. All are used unmodified, so any licence conditions that apply only to modified versions are not triggered. Developers cloning this repository should independently verify development dependencies.`;\n}\n\nfunction formatLicenseListText(licenses: string[]): string {\n if (licenses.length === 1) return licenses[0] ?? '';\n return licenses.length === 2 ? `${String(licenses[0])} or ${String(licenses[1])}` : `${licenses.slice(0, -1).join(', ')}, or ${String(licenses.at(-1))}`;\n}\n\nfunction parseLicenseEntry(key: string, value: ProductionPackageLicense): License {\n const lastAt = key.lastIndexOf('@');\n const name = lastAt > 0 ? key.slice(0, lastAt) : key;\n const installedVersion = lastAt > 0 ? key.slice(lastAt + 1) : '';\n return {\n name,\n repository: value.repository ?? `https://www.npmjs.com/package/${name}`,\n licenseTypes: value.licenses,\n installedVersion,\n author: value.publisher ?? '',\n latestVersion: '',\n latestPublishedDate: '',\n publishedDate: '',\n licenseFiles: value.licenseFile == null ? [] : [{ label: 'LICENSE', path: value.licenseFile }]\n };\n}\n\nasync function fetchNpmData(name: string, version: string): Promise<{ latestVersion: string; latestPublishedDate: string; publishedDate: string }> {\n try {\n const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}`);\n if (response.ok) {\n const data = (await response.json()) as { 'dist-tags'?: Record<string, string>; time?: Record<string, string> };\n const distributionTags = new Map(Object.entries(data['dist-tags'] ?? {}));\n const timeMap = new Map(Object.entries(data.time ?? {}));\n const latestVersion = distributionTags.get('latest') ?? '';\n const publishedDate = timeMap.get(version) ?? '';\n const latestPublishedDate = latestVersion === version ? '' : (timeMap.get(latestVersion) ?? '');\n return { latestVersion, latestPublishedDate, publishedDate };\n }\n } catch {\n // Ignore network errors.\n }\n return { latestVersion: '', latestPublishedDate: '', publishedDate: '' };\n}\n\n// The type, 'JavaScript' or 'Rust', is only given where the table holds both.\nfunction formatLicenseRow(license: License, typeLabel?: string): string {\n const licenseLink =\n license.licenseFiles.length === 0 ? '⚠️ No license file' : license.licenseFiles.map((licenseFile) => `[${licenseFile.label}](licenses/${licenseFile.path})`).join(' ');\n const typeCell = typeLabel === undefined ? '' : `|${typeLabel}`;\n return `${typeCell}|[${license.name}](${license.repository})|${license.installedVersion}|${license.licenseTypes}|${licenseLink}|\\n`;\n}\n\nfunction walkTreeList(dependencies: Record<string, NpmPackageTree>, licensesByKey: Map<string, License>, unshippedPackages: Set<string>, items: string[], depth: number): void {\n const indent = ' '.repeat(depth);\n for (const [name, node] of Object.entries(dependencies)) {\n // npm lists optional peers that nothing installs, such as '@opentelemetry/api' for '@tanstack/ai', with no version.\n if (node.version === undefined) continue;\n const version = node.version;\n if (unshippedPackages.has(`${name}@${version}`)) continue;\n items.push(formatTreeItem(name, version, licensesByKey.get(`${name}@${version}`), indent));\n if (node.dependencies != null) {\n walkTreeList(node.dependencies, licensesByKey, unshippedPackages, items, depth + 1);\n }\n }\n}\n\n// Lists each shipped package where it is reached. A package that does not ship, such as 'vue' whose '@vue/*' parts are\n// bundled, or a development tool, is passed over and what ships beneath it is listed in its place. A package reached\n// that way is listed once only, as it is already listed wherever a shipped package reaches it.\nfunction walkShippedTree(entries: [string, NpmPackageTree][], context: ShippedTreeContext, items: string[], depth: number, isPassedOver: boolean): void {\n for (const [name, node] of entries) {\n if (node.version === undefined) continue;\n const packageKey = `${name}@${node.version}`;\n const childEntries = Object.entries(node.dependencies ?? {});\n if (!context.shippedKeys.has(packageKey)) {\n walkShippedTree(childEntries, context, items, depth, true);\n continue;\n }\n if (isPassedOver && context.shownKeys.has(packageKey)) continue;\n context.shownKeys.add(packageKey);\n items.push(formatTreeItem(name, node.version, context.licensesByKey.get(packageKey), ' '.repeat(depth)));\n walkShippedTree(childEntries, context, items, depth + 1, false);\n }\n}\n\nfunction formatTreeItem(name: string, version: string, license: License | undefined, indent: string): string {\n const nameLink = license == null ? name : `[${name}](${license.repository})`;\n return `${indent}- **${nameLink}** ${version}${formatVersionDetail(license)}`;\n}\n\nfunction formatVersionDetail(license: License | undefined): string {\n if (license == null) return '';\n const published = license.publishedDate ? determineLatestAge(license.publishedDate.split('T', 1)[0]) : '';\n const isOutdated = license.latestVersion !== '' && license.latestVersion !== license.installedVersion;\n if (!isOutdated) return published === '' ? '' : ` — ${published}`;\n const latestAge = license.latestPublishedDate ? determineLatestAge(license.latestPublishedDate.split('T', 1)[0]) : '';\n const latestClause = latestAge === '' ? `latest: ${license.latestVersion} ❗` : `latest: ${license.latestVersion} — ${latestAge} ❗`;\n return published === '' ? ` — → ${latestClause}` : ` — ${published} → ${latestClause}`;\n}\n\nfunction determineLatestAge(momentString?: string): string {\n if (momentString == null || momentString === '') return 'n/a';\n\n const dateString = momentString.split('T', 1)[0];\n if (dateString == null || dateString === '') return 'n/a';\n\n const input = new Date(dateString);\n const now = new Date();\n let months = (now.getFullYear() - input.getFullYear()) * 12 + (now.getMonth() - input.getMonth());\n if (now.getDate() < input.getDate()) months -= 1;\n\n if (months === 0) return `this month: ${dateString}`;\n if (months === 1) return `1 mth ago: ${dateString}`;\n return months <= 6 ? `${String(months)} mths ago: ${dateString}` : `${String(months)} mths ago: ${dateString} ⚠️`;\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, resolveOwnerAndRepository, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- OPENING_START -->';\nconst END_MARKER = '<!-- OPENING_END -->';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentOpening(): Promise<void> {\n try {\n logOperationHeader('Document Opening');\n\n logStepHeader(\"1️⃣ Insert opening content into 'README.md'\");\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n\n const { owner, repository } = resolveOwnerAndRepository(packageJSON, 'document opening');\n const license = resolveLicense(packageJSON);\n const introduction = resolveIntroduction(configJSON);\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n const dpuseModuleId = moduleTypeConfig.uploadGroupName === undefined ? undefined : configJSON.id;\n const npmPackageName = moduleTypeConfig.publishedTo === 'npm' ? resolvePackageName(packageJSON) : undefined;\n\n const content = buildOpeningContent(owner, repository, license, {\n description: packageJSON.description,\n dpuseModuleId,\n introduction,\n npmPackageName,\n version: packageJSON.version\n });\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Opening documented');\n } catch (error) {\n console.error('❌ Error documenting opening', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Shields colours the npm badge by version, but a badge reading JSON can only take a fixed colour, so the DPUse badge is\n// given the one Shields would pick, as of this release: orange before 1.0 or for a pre-release, blue otherwise.\nfunction resolveVersionColor(version: string | undefined): string {\n if (version === undefined) return 'blue';\n return /^v?0/.test(version) || /alpha|beta|snapshot|dev|pre|rc/i.test(version) ? 'orange' : 'blue';\n}\n\nfunction resolveLicense(packageJSON: PackageJson): string {\n const license = packageJSON.license;\n if (license == null || license === '') throw new Error(\"package.json 'license' field is required to document opening.\");\n return license;\n}\n\nfunction resolvePackageName(packageJSON: PackageJson): string {\n const name = packageJSON.name;\n if (name == null || name === '') throw new Error(\"package.json 'name' field is required to document opening.\");\n return name;\n}\n\n// 'description.en' holds the introduction as one string, with a blank line between paragraphs. With none, the\n// Introduction section is left out.\nfunction resolveIntroduction(configJSON: ModuleConfig): string | undefined {\n const introduction = configJSON.description.en?.trim();\n return introduction === undefined || introduction === '' ? undefined : introduction;\n}\n\n// The package description is optional, so a project without one simply has no summary between the badges and the links.\n// Only modules uploaded to DPUse get the DPUse version badge, and only projects published to npm get the npm badge. The\n// DPUse badge reads the version registered in DPUse, which is only updated once the upload succeeds, so like the npm\n// badge it shows what was actually published, and it works for private repositories too.\nfunction buildOpeningContent(\n owner: string,\n repository: string,\n license: string,\n options: {\n description: string | undefined;\n dpuseModuleId: string | undefined;\n introduction: string | undefined;\n npmPackageName: string | undefined;\n version: string | undefined;\n }\n): string {\n const { description, dpuseModuleId, introduction, npmPackageName, version } = options;\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n const badgeLicense = license.replaceAll('-', '--');\n const dpuseConfigURL = encodeURIComponent(`https://api.dpuse.app/configs/${dpuseModuleId ?? ''}`);\n const dpuseBadge =\n dpuseModuleId === undefined\n ? ''\n : `\\n[})](${repositoryURL}/releases/latest)`;\n const npmBadge =\n npmPackageName === undefined ? '' : `\\n[](https://www.npmjs.com/package/${npmPackageName})`;\n const summary = description == null || description === '' ? '' : `\\n\\n${description}`;\n const introductionSection = introduction === undefined ? '' : `\\n\\n## Introduction\\n\\n${introduction}`;\n\n return `[](./LICENSE)${dpuseBadge}${npmBadge}\n[](${repositoryURL}/actions/workflows/ci.yml)${summary}\n\n[Report a Vulnerability](${repositoryURL}/security/advisories/new) · [Open an Issue](${repositoryURL}/issues)\n\n## About DPUse\n\n[DPUse](https://www.dpuse.app) (Data Positioning & Use) is an in-browser application that positions your data for use through three core activities: sourcing, contextualising, and publishing.\n\n**Sourcing** uses a library of [Connectors](https://www.dpuse.app/connectors) to establish [Connections](https://www.dpuse.app) to applications, databases, file stores, and curated datasets; these connections are subsequently used to configure structured [Data Views](https://www.dpuse.app) from the underlying sources.\n\n**Contextualising** extracts chronological events from those [Data Views](https://www.dpuse.app) and maps them into comprehensive [Context Models](https://www.dpuse.app). This gives the DPUse Engine the structural framework needed to generate deterministic transactions, facts, or observations.\n\n**Publishing** uses a library of [Presenters](https://www.dpuse.app) to render standard [Presentations](https://www.dpuse.app) immediately using the contextualised data; additionally, [Cookbooks](https://www.dpuse.app) of [Recipes](https://www.dpuse.app) let you build Data Apps using your preferred tools.\n\nIn addition, DPUse provides [Tools](https://www.dpuse.app) used by the application, and you can use them to construct connectors and presenters.${introductionSection}`;\n}\n","// ── External Dependencies & Registrations\nimport { execFile } from 'node:child_process';\nimport type { PackageJson } from 'type-fest';\nimport { promisify } from 'node:util';\n\n// ── Local Framework\nimport {\n FALLOW_BADGE_PATH,\n FALLOW_DIRECTORY,\n FALLOW_REPORT_PATH,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n migrateGovernanceSection,\n QUALITY_SECURITY_END_MARKER,\n QUALITY_SECURITY_START_MARKER,\n readJSONFile,\n readTextFileOrNull,\n resolveOwnerAndRepository,\n RUST_WORKSPACE_PATH,\n spawnCommand,\n spawnCommandToFile,\n writeJSONFile,\n writeReadmeSection\n} from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface BestPracticesProject {\n id: number;\n repo_url: string;\n}\n\ninterface CoverageSummary {\n total: { lines: { pct: number | 'Unknown' } }; // 'Unknown' when there is no code to measure, such as a project with no 'src'.\n}\n\ninterface FallowHealth {\n health_score: { score: number; grade: string };\n}\n\ninterface GitHubCheckRuns {\n check_runs: { app: { slug: string } | null }[];\n}\n\ninterface GitHubRepositoryDetails {\n security_and_analysis?: Record<string, { status: string } | undefined>;\n}\n\ninterface ScorecardResult {\n checks: { name: string; score: number }[];\n}\n\n// Everything the checks tables report on, gathered before the README is written.\ninterface ChecksResults {\n coveragePercent: number | undefined;\n fallowHealth: FallowHealth | undefined;\n securitySettings: SecuritySettings;\n}\n\n// On or off, or undefined where GitHub doesn't reveal the setting (some need an admin login to read).\ntype SettingStatus = boolean | undefined;\n\ninterface SecuritySettings {\n codeQLLanguages: string[];\n codeQLQueries: string | undefined; // The query suite CodeQL is told to run; without one, it runs its default suite.\n dependabotAlerts: SettingStatus;\n dependabotSecurityUpdates: SettingStatus;\n dependabotVersionUpdates: boolean;\n lintInCI: boolean;\n npmAuditInCI: boolean;\n npmAuditLevel: string | undefined; // The '--audit-level' CI passes; without one, npm audit fails on any severity.\n privateVulnerabilityReporting: SettingStatus;\n propertyTests: boolean;\n pushProtection: SettingStatus;\n secretScanning: SettingStatus;\n socket: boolean;\n sonarCloud: boolean;\n testsInCI: boolean;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Scorecard checks a solo maintainer pushing straight to 'main' can't raise, with the best score each can reach that way.\nconst SCORECARD_PRACTICE_LIMITS: Record<string, number> = { 'Branch-Protection': 3, 'Code-Review': 0, Contributors: 0 };\n// Left out when deciding whether gaps remain: the Best Practices badge shows its own progress in the same section.\nconst SCORECARD_IGNORED_CHECKS = new Set(['CII-Best-Practices']);\n\n// Coverage — only measured where the module has the Vitest coverage provider installed. 'coverage-final.json' feeds\n// Fallow's per-function scores; the summary holds the totals the Testing table reports.\nconst COVERAGE_FINAL_PATH = 'coverage/coverage-final.json';\nconst COVERAGE_SUMMARY_PATH = 'coverage/coverage-summary.json';\nconst COVERAGE_TARGET_PERCENT = 80;\nconst COVERAGE_WARNING_PERCENT = 60; // Below the target the badge turns yellow, and below this it turns red.\nconst COVERAGE_BADGE_PATH = 'code-health-reports/vitest/badge.json'; // Not under a 'coverage' folder, which '.gitignore' leaves out.\n\nconst CODEQL_LANGUAGE_NAMES: Record<string, string> = { actions: 'GitHub Actions', 'javascript-typescript': 'JavaScript/TypeScript', rust: 'Rust' };\n\n// Fallow — only run where the module has it installed. The full report is published as its own page, linked from the\n// README; the Code Quality row and the badge are both built from the one health run, so they always agree.\nconst FALLOW_GRADE_COLOURS: Record<string, string> = { A: 'brightgreen', B: 'green', C: 'yellow', D: 'orange', F: 'red' };\nconst FALLOW_HEALTH_PATH = `${FALLOW_DIRECTORY}/health.json`;\n\n// ── Initialisation ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst asyncExecFile = promisify(execFile);\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates the README's Quality & Security section: testing, code quality, security analysis, dependencies and OpenSSF. */\nexport async function documentQualitySecurity(): Promise<void> {\n try {\n logOperationHeader('Document Quality & Security');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n\n const coveragePercent = await measureTestCoverage(packageJSON);\n const fallowHealth = await measureCodeHealth(packageJSON, coveragePercent === undefined ? [] : ['--coverage', COVERAGE_FINAL_PATH]);\n\n const { owner, repository } = resolveOwnerAndRepository(packageJSON, 'document quality and security');\n\n logStepHeader('4️⃣ Read security checks and settings');\n const securitySettings = await readSecuritySettings(owner, repository, packageJSON);\n\n logStepHeader('5️⃣ Look up OpenSSF Best Practices badge and Scorecard results');\n const [bestPracticesProjectId, scorecardResult] = await Promise.all([\n lookUpBestPracticesProjectId(`https://github.com/${owner}/${repository}`),\n lookUpScorecardResult(`github.com/${owner}/${repository}`)\n ]);\n\n logStepHeader(\"6️⃣ Insert quality and security content into 'README.md'\");\n const content = buildQualitySecurityContent(owner, repository, { coveragePercent, fallowHealth, securitySettings }, bestPracticesProjectId, scorecardResult);\n\n await migrateGovernanceSection();\n await writeReadmeSection(content, QUALITY_SECURITY_START_MARKER, QUALITY_SECURITY_END_MARKER);\n\n logOperationSuccess('Quality & security documented');\n } catch (error) {\n console.error('❌ Error documenting quality and security', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Answers undefined where the coverage provider isn't installed, the Vitest config doesn't write a coverage summary, or\n// there is no code to measure.\nasync function measureTestCoverage(packageJSON: PackageJson): Promise<number | undefined> {\n if (packageJSON.devDependencies?.['@vitest/coverage-v8'] == null) {\n logStepHeader(\"1️⃣ Test coverage NOT measured, as '@vitest/coverage-v8' is not installed\");\n return undefined;\n }\n\n await spawnCommand('1️⃣ Measure test coverage', 'vitest', ['run', '--passWithNoTests', '--coverage']);\n const summary = await readTextFileOrNull(COVERAGE_SUMMARY_PATH);\n if (summary === null) return undefined;\n\n const coveragePercent = (JSON.parse(summary) as CoverageSummary).total.lines.pct;\n if (coveragePercent === 'Unknown') return undefined;\n await writeCoverageBadge(coveragePercent);\n return coveragePercent;\n}\n\n// Written in the shields.io endpoint format, like the Fallow badge, so the README shows the latest pushed figure.\nasync function writeCoverageBadge(coveragePercent: number): Promise<void> {\n const colourNames = ['red', 'yellow', 'brightgreen'];\n const level = Number(coveragePercent >= COVERAGE_WARNING_PERCENT) + Number(coveragePercent >= COVERAGE_TARGET_PERCENT);\n await writeJSONFile(COVERAGE_BADGE_PATH, { schemaVersion: 1, label: 'coverage', message: `${coveragePercent.toFixed(1)}%`, color: colourNames[level] });\n}\n\n// Fallow exits non-zero whenever it has findings, so its exit code is ignored: the findings are what gets reported.\nasync function measureCodeHealth(packageJSON: PackageJson, coverageArguments: string[]): Promise<FallowHealth | undefined> {\n if (packageJSON.devDependencies?.['fallow'] == null) {\n logStepHeader('2️⃣ Code health NOT measured, as Fallow is not installed');\n logStepHeader('3️⃣ Code health report NOT required');\n return undefined;\n }\n\n await spawnCommandToFile('2️⃣ Measure code health', 'fallow', ['health', '--report-only', '--format', 'json', ...coverageArguments], FALLOW_HEALTH_PATH);\n await spawnCommandToFile('3️⃣ Write code health report', 'fallow', ['--format', 'markdown'], FALLOW_REPORT_PATH, true);\n const health = await readJSONFile<FallowHealth>(FALLOW_HEALTH_PATH);\n await writeFallowBadge(health);\n return health;\n}\n\n// Written in the shields.io endpoint format, so the Code Quality badge shows the latest pushed grade.\nasync function writeFallowBadge(health: FallowHealth): Promise<void> {\n const { score, grade } = health.health_score;\n await writeJSONFile(FALLOW_BADGE_PATH, {\n schemaVersion: 1,\n label: 'fallow',\n message: `${grade} (${String(Math.round(score))})`,\n color: FALLOW_GRADE_COLOURS[grade] ?? 'lightgrey'\n });\n}\n\n// Read from the repository itself each time, so the README states what is actually switched on rather than what was\n// intended. Workflow and Dependabot files are read locally; repository settings come from the GitHub API through 'gh'.\nasync function readSecuritySettings(owner: string, repository: string, packageJSON: PackageJson): Promise<SecuritySettings> {\n const [ciWorkflow, dependabotConfig, rustWorkspace] = await Promise.all([\n readTextFileOrNull('.github/workflows/ci.yml'),\n readTextFileOrNull('.github/dependabot.yml'),\n readTextFileOrNull(RUST_WORKSPACE_PATH)\n ]);\n const codeQLWorkflow = (await readTextFileOrNull('.github/workflows/codeql.yml')) ?? ''; // Empty when missing, so CodeQL reads as off.\n const [repositoryDetails, privateVulnerabilityReporting, vulnerabilityAlerts, checkRuns] = await Promise.all([\n readGitHubAPI(`repos/${owner}/${repository}`),\n readGitHubAPI(`repos/${owner}/${repository}/private-vulnerability-reporting`),\n readGitHubAPI(`repos/${owner}/${repository}/vulnerability-alerts`),\n readGitHubAPI(`repos/${owner}/${repository}/commits/main/check-runs?per_page=100`)\n ]);\n\n const securityAndAnalysis = repositoryDetails === undefined ? undefined : (JSON.parse(repositoryDetails) as GitHubRepositoryDetails).security_and_analysis;\n const readSetting = (name: string): SettingStatus => (securityAndAnalysis?.[name] === undefined ? undefined : securityAndAnalysis[name].status === 'enabled');\n const checkAppSlugs = new Set((checkRuns === undefined ? [] : (JSON.parse(checkRuns) as GitHubCheckRuns).check_runs).map((checkRun) => checkRun.app?.slug));\n\n // Version updates count as off when every ecosystem is limited to 0 pull requests, the documented way to pause them.\n const ecosystemCount = dependabotConfig?.match(/package-ecosystem:/g)?.length ?? 0;\n const pausedEcosystemCount = dependabotConfig?.match(/open-pull-requests-limit: 0\\b/g)?.length ?? 0;\n\n return {\n codeQLLanguages: codeQLWorkflow\n .matchAll(/- language: ([\\w-]+)/g)\n .filter(([, language]) => language !== 'rust' || rustWorkspace !== null) // The workflow lists Rust for every project, but skips its scan where there is none.\n .map(([, language = '']) => CODEQL_LANGUAGE_NAMES[language] ?? language)\n .toArray(),\n codeQLQueries: /queries: ([\\w-]+)/.exec(codeQLWorkflow)?.[1],\n dependabotAlerts: vulnerabilityAlerts !== undefined, // Answers '204 No Content' when on and '404' when off.\n dependabotSecurityUpdates: readSetting('dependabot_security_updates'),\n dependabotVersionUpdates: ecosystemCount > pausedEcosystemCount,\n lintInCI: (ciWorkflow ?? '').includes('npm run lint'),\n npmAuditInCI: /npm (?:run )?audit/.test(ciWorkflow ?? ''),\n npmAuditLevel: /npm audit --audit-level=(\\w+)/.exec(ciWorkflow ?? '')?.[1],\n privateVulnerabilityReporting: privateVulnerabilityReporting === undefined ? undefined : (JSON.parse(privateVulnerabilityReporting) as { enabled: boolean }).enabled,\n propertyTests: packageJSON.devDependencies?.['fast-check'] != null,\n pushProtection: readSetting('secret_scanning_push_protection'),\n secretScanning: readSetting('secret_scanning'),\n socket: checkAppSlugs.has('socket-security'),\n sonarCloud: checkAppSlugs.has('sonarqubecloud'),\n testsInCI: ciWorkflow?.includes('npm test') ?? false\n };\n}\n\n// Answers undefined for a 404, which is how some endpoints report a switched-off feature. Any other failure throws, so a\n// missing login or network blip can't be written into the README as settings being off.\nasync function readGitHubAPI(endpoint: string): Promise<string | undefined> {\n try {\n const { stdout } = await asyncExecFile('gh', ['api', endpoint]);\n return stdout;\n } catch (error) {\n if (String((error as { stderr?: unknown }).stderr).includes('HTTP 404')) return undefined;\n throw error;\n }\n}\n\n// Found by repository URL, as OpenSSF Scorecard does, so a repository shows its badge as soon as it is registered and nothing\n// needs configuring. Failures throw rather than return nothing, so a network blip can't drop the badge from the README.\nasync function lookUpBestPracticesProjectId(repositoryURL: string): Promise<number | undefined> {\n const response = await fetch(`https://www.bestpractices.dev/projects.json?url=${encodeURIComponent(repositoryURL)}`);\n if (!response.ok) throw new Error(`OpenSSF Best Practices lookup failed with status ${String(response.status)}.`);\n\n // The search also matches home page URLs, so keep only the entry registered for this repository.\n const projects = (await response.json()) as BestPracticesProject[];\n return projects.find((project) => project.repo_url === repositoryURL)?.id;\n}\n\n// Answers undefined when Scorecard has no results for the repository yet. Other failures throw, as for the badge.\nasync function lookUpScorecardResult(scorecardURI: string): Promise<ScorecardResult | undefined> {\n const response = await fetch(`https://api.scorecard.dev/projects/${scorecardURI}`);\n if (response.status === 404) return undefined;\n if (!response.ok) throw new Error(`OpenSSF Scorecard lookup failed with status ${String(response.status)}.`);\n return (await response.json()) as ScorecardResult;\n}\n\n// True when every check short of 10 is one the way the project is run caps. A score of -1 means Scorecard couldn't assess\n// the check (e.g. Signed-Releases without release assets), so it isn't counted as a gap.\nfunction isScorecardOnlyPracticeLimited(result: ScorecardResult): boolean {\n return result.checks.every(\n ({ name, score }) =>\n score === -1 || score === 10 || SCORECARD_IGNORED_CHECKS.has(name) || (SCORECARD_PRACTICE_LIMITS[name] !== undefined && score >= SCORECARD_PRACTICE_LIMITS[name])\n );\n}\n\n// Where Dependabot's pull requests are switched off, dependency updates are made by hand.\nfunction formatManualNote(status: SettingStatus): string {\n return status === false ? ' These are handled manually.' : '';\n}\n\nfunction formatStatus(status: SettingStatus): string {\n if (status === undefined) return '❔ Unknown';\n return status ? '✅ On' : '❌ Off';\n}\n\nfunction buildTableContent(heading: string, rows: string[][]): string {\n if (rows.length === 0) return '';\n return `### ${heading}\n\n|Check|Status|What it does|\n|:-|:-|:-|\n${rows.map((row) => `|${row.join('|')}|`).join('\\n')}\n\n`;\n}\n\n// A badge that shields.io draws from a JSON file this action commits, so it shows the latest pushed figure.\nfunction formatEndpointBadge(owner: string, repository: string, label: string, badgePath: string): string {\n const badgeSourceURL = encodeURIComponent(`https://raw.githubusercontent.com/${owner}/${repository}/main/${badgePath}`);\n return ``;\n}\n\n// Grouped by what each check protects against, and within a group in the order the checks act on a change: before a\n// push, on every push, then continuously, and alphabetically within each. Status is only ever on, off or unknown. What\n// it does opens with the check's badge where it has one, shown only while the check is on so a badge is never broken,\n// and names and links the product doing the check.\nfunction buildChecksContent(owner: string, repository: string, { coveragePercent, fallowHealth, securitySettings: settings }: ChecksResults): string {\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n\n const ciNote = (isInCI: boolean): string => (isInCI ? ` Part of the [CI workflow](${repositoryURL}/actions/workflows/ci.yml) on every push and pull request to \\`main\\`.` : '');\n\n const testingRows = [\n ['Unit tests', formatStatus(settings.testsInCI), `[Vitest](https://vitest.dev) runs the unit tests.${ciNote(settings.testsInCI)}`],\n [\n 'Property-based tests',\n formatStatus(settings.propertyTests),\n `[fast-check](https://fast-check.dev) runs many random inputs per test to find edge cases, alongside the unit tests.${ciNote(settings.propertyTests && settings.testsInCI)}`\n ]\n ];\n if (coveragePercent !== undefined) {\n testingRows.push([\n 'Test coverage',\n formatStatus(true),\n `${formatEndpointBadge(owner, repository, 'Coverage', COVERAGE_BADGE_PATH)} [Vitest's V8 coverage](https://vitest.dev/guide/coverage) measures the share of source lines the unit tests run. The target is ${String(COVERAGE_TARGET_PERCENT)}%.`\n ]);\n }\n\n const sonarCloudBadge = `[](https://sonarcloud.io/summary/new_code?id=${owner}_${repository}) `;\n const codeQualityRows = [\n [\n 'Code analysis',\n formatStatus(settings.sonarCloud),\n `${settings.sonarCloud ? sonarCloudBadge : ''}[SonarCloud](https://sonarcloud.io) checks every push for bugs, code smells and vulnerabilities.`\n ],\n ['Linting', formatStatus(settings.lintInCI), `[ESLint](https://eslint.org) checks the code for errors and style problems.${ciNote(settings.lintInCI)}`]\n ];\n // Measured when the README is regenerated, before the changes are pushed, so it comes first.\n if (fallowHealth !== undefined) {\n codeQualityRows.unshift([\n 'Code health',\n formatStatus(true),\n `[${formatEndpointBadge(owner, repository, 'Fallow code health', FALLOW_BADGE_PATH)}](./${FALLOW_REPORT_PATH}) [Fallow](https://github.com/fallow-rs/fallow) finds unused code, duplication, complexity and dependency problems.`\n ]);\n }\n\n const hasCodeQL = settings.codeQLLanguages.length > 0;\n const codeQLBadge = `[](${repositoryURL}/security/code-scanning) `;\n const codeQLScope = settings.codeQLQueries === 'security-extended' ? 'using the extended security queries' : 'using the default queries';\n const codeQLLanguages = hasCodeQL ? ` ${settings.codeQLLanguages.join(' and ')}` : '';\n const securityAnalysisRows = [\n [\n 'Push protection',\n formatStatus(settings.pushProtection),\n '[GitHub push protection](https://docs.github.com/en/code-security/secret-scanning/push-protection-for-repositories-and-organizations) blocks pushes that contain credentials.'\n ],\n [\n 'Static analysis',\n formatStatus(hasCodeQL),\n `${hasCodeQL ? codeQLBadge : ''}[CodeQL](https://codeql.github.com) scans${codeQLLanguages} for security vulnerabilities, ${codeQLScope}, on every push and pull request to \\`main\\` and weekly.`\n ],\n [\n 'Secret scanning',\n formatStatus(settings.secretScanning),\n '[GitHub secret scanning](https://docs.github.com/en/code-security/secret-scanning) detects credentials, such as API keys and tokens, committed to the repository.'\n ]\n ];\n\n const dependabotLink = '[Dependabot](https://docs.github.com/en/code-security/dependabot)';\n const dependencyRows = [\n [\n 'Vulnerability audit',\n formatStatus(settings.npmAuditInCI),\n settings.npmAuditLevel === undefined\n ? `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a shipped dependency has any known vulnerability, or a development dependency has a high or critical one.${ciNote(settings.npmAuditInCI)}`\n : `[npm audit](https://docs.npmjs.com/cli/commands/npm-audit) fails when a dependency has a known vulnerability of ${settings.npmAuditLevel} severity or above.${ciNote(settings.npmAuditInCI)}`\n ],\n [\n 'Supply chain risk',\n formatStatus(settings.socket), // Socket's badge service refuses requests from outside a browser, so GitHub couldn't show it.\n '[Socket](https://socket.dev) flags malicious packages, typosquatting and suspicious behaviour that may not yet have a CVE.'\n ],\n ['Security alerts', formatStatus(settings.dependabotAlerts), `${dependabotLink} alerts when a dependency has a known vulnerability, using the GitHub Advisory Database.`],\n [\n 'Security updates',\n formatStatus(settings.dependabotSecurityUpdates),\n `${dependabotLink} opens pull requests that update vulnerable dependencies.${formatManualNote(settings.dependabotSecurityUpdates)}`\n ],\n [\n 'Version updates',\n formatStatus(settings.dependabotVersionUpdates),\n `${dependabotLink} opens pull requests for new dependency versions.${formatManualNote(settings.dependabotVersionUpdates)}`\n ]\n ];\n\n return `This section is updated each time \\`npm run document\\` is run. Settings come from the repository's workflow files and GitHub. Test coverage and the Fallow score are measured at the same time.\n\n${buildTableContent('Testing', testingRows)}${buildTableContent('Code Quality', codeQualityRows)}${buildTableContent('Security Analysis', securityAnalysisRows)}${buildTableContent('Dependencies', dependencyRows)}`;\n}\n\nfunction buildQualitySecurityContent(\n owner: string,\n repository: string,\n checksResults: ChecksResults,\n bestPracticesProjectId: number | undefined,\n scorecardResult: ScorecardResult | undefined\n): string {\n const repositoryURL = `https://github.com/${owner}/${repository}`;\n const scorecardURI = `github.com/${owner}/${repository}`;\n const bestPracticesURL = `https://www.bestpractices.dev/projects/${String(bestPracticesProjectId)}`;\n const scorecardLimitText =\n scorecardResult !== undefined && isScorecardOnlyPracticeLimited(scorecardResult)\n ? \"\\n\\n> [!NOTE]\\n> Apart from the Best Practices badge above, the remaining Scorecard gaps need multi-person review or a pull-request workflow, which this solo-maintained project doesn't use.\"\n : '';\n const bestPracticesBadge = bestPracticesProjectId === undefined ? '' : `[](${bestPracticesURL})\\n`;\n\n // Without private reporting switched on, the advisory link leads nowhere, so point only at SECURITY.md.\n const reportingText =\n checksResults.securitySettings.privateVulnerabilityReporting === true\n ? `Use [GitHub private vulnerability reporting](${repositoryURL}/security/advisories/new) instead. See [SECURITY.md](./SECURITY.md) for the full disclosure policy, contact details, and expected response times.`\n : 'See [SECURITY.md](./SECURITY.md) for how to report one privately, the full disclosure policy, and expected response times.';\n\n return `## Quality & Security\n\n${buildChecksContent(owner, repository, checksResults)}### OpenSSF 🚧\n\n${bestPracticesBadge}[](https://scorecard.dev/viewer/?uri=${scorecardURI})\n\nThis project is working towards the [OpenSSF Best Practices](https://www.bestpractices.dev) Passing badge, a self-certification covering security policy, vulnerability reporting, build processes, code quality, and more. Currently the [OpenSSF Scorecard](https://scorecard.dev) provides an independent automated assessment of the project's security practices and is an ongoing area of improvement.${scorecardLimitText}\n\n### Reporting Vulnerabilities\n\nPlease do not open public GitHub issues for security vulnerabilities. ${reportingText}`;\n}\n","// ── External Dependencies & Registrations\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport type { ModuleTypeConfig } from '@/utilities';\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, writeReadmeSection } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst START_MARKER = '<!-- USAGE_START -->';\nconst END_MARKER = '<!-- USAGE_END -->';\n\n// Module types the DPUse Engine uploads to the cloud for the browser app to load. The engine itself is also uploaded, but\n// isn't something others build their own version of, so it gets the general wording.\nconst UPLOADED_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['connector', 'cookbook', 'presenter']);\n\n// Published to npm only so DPUse projects can install them, not for general use, so the npm wording carries a warning.\nconst INTERNAL_NPM_MODULE_TYPE_IDS = new Set<ModuleTypeConfig['typeId']>(['development', 'eslint']);\nconst INTERNAL_NPM_WARNING = `> [!WARNING]\n> This project is not designed for general use. It is custom built for the DPUse CI/CD process. You are welcome to clone and customise it for your own purposes, but you will need to adapt it to your own project structure and tooling.`;\n\n// How the repository is managed. dpuse-development provides the actions every other repository uses, and runs them on itself.\nconst DEVELOPMENT_MANAGEMENT_TEXT = 'This repository manages itself using the actions it implements.';\nconst SHARED_MANAGEMENT_TEXT = 'This repository is managed using the common set of actions provided by [@dpuse/dpuse-development](https://github.com/dpuse/dpuse-development).';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentUsage(): Promise<void> {\n try {\n logOperationHeader('Document Usage');\n\n logStepHeader(\"1️⃣ Insert usage content into 'README.md'\");\n\n const [packageJSON, configJSON] = await Promise.all([readJSONFile<PackageJson>('package.json'), readJSONFile<ModuleConfig>('config.json')]);\n\n const cloneURL = resolveCloneURL(packageJSON);\n const directoryName = resolveDirectoryName(cloneURL);\n const nodeVersion = resolveVersion(packageJSON.engines?.node);\n const npmVersion = resolveVersion(packageJSON.engines?.npm);\n const typescriptVersion = resolveVersion(packageJSON.devDependencies?.['typescript']);\n\n const introduction = buildIntroductionContent(getModuleConfig(configJSON.id), packageJSON.name);\n // A full link, so it still works where the README is shown away from GitHub, such as on npm.\n const packageJSONURL = `${cloneURL.replace(/\\.git$/, '')}/blob/main/package.json`;\n const managementText = packageJSON.name === '@dpuse/dpuse-development' ? DEVELOPMENT_MANAGEMENT_TEXT : SHARED_MANAGEMENT_TEXT;\n const management = `${managementText} See the \\`scripts\\` block in [package.json](${packageJSONURL}) for details.`;\n const content = buildUsageContent(introduction, cloneURL, directoryName, nodeVersion, npmVersion, typescriptVersion, management);\n\n await writeReadmeSection(content, START_MARKER, END_MARKER);\n\n logOperationSuccess('Usage documented');\n } catch (error) {\n console.error('❌ Error documenting usage', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction resolveCloneURL(packageJSON: PackageJson): string {\n const repository = packageJSON.repository;\n const url = typeof repository === 'string' ? repository : repository?.url;\n if (url == null || url === '') throw new Error(\"package.json 'repository' field is required to document usage.\");\n return url.replace(/^git\\+/, '');\n}\n\nfunction resolveDirectoryName(cloneURL: string): string {\n const lastSegment = cloneURL.split('/').at(-1) ?? '';\n return lastSegment.replace(/\\.git$/, '');\n}\n\nfunction resolveVersion(range: string | undefined): string {\n if (range == null) throw new Error('package.json version range is required to document usage.');\n // eslint-disable-next-line security/detect-unsafe-regex -- Linear: each group repeat must start with a literal '.'.\n const match = /\\d+(?:\\.\\d+)*/.exec(range);\n if (match == null) throw new Error(`Unable to parse version from '${range}'.`);\n return match[0];\n}\n\n// Worded for how the module reaches people: uploaded to DPUse, installed from npm, or neither.\nfunction buildIntroductionContent(moduleTypeConfig: ModuleTypeConfig, packageName: string | undefined): string {\n const { typeId } = moduleTypeConfig;\n\n if (UPLOADED_MODULE_TYPE_IDS.has(typeId)) {\n return `This ${typeId} is automatically uploaded to the DPUse Engine cloud once released and becomes instantly available to all new browser app instances, with existing instances notified of the update.\n\nYou may view or clone this repository for your own purposes, such as building a new, similar ${typeId}, though there is currently no process to accept third-party ${typeId}s into DPUse at this stage.`;\n }\n\n if (moduleTypeConfig.publishedTo === 'npm') {\n if (packageName == null || packageName === '') throw new Error(\"package.json 'name' field is required to document usage.\");\n const warning = INTERNAL_NPM_MODULE_TYPE_IDS.has(typeId) ? `${INTERNAL_NPM_WARNING}\\n\\n` : ''; // Its own paragraph, or the text after it joins the warning.\n return `This [package](https://www.npmjs.com/package/${packageName}) is available on [npm](https://www.npmjs.com/). Install it with:\n\n\\`\\`\\`bash\nnpm install ${packageName}\n\\`\\`\\`\n\n${warning}To work on the source instead, clone this repository.`;\n }\n\n return `You may view or clone this repository for your own purposes.`;\n}\n\nfunction buildUsageContent(\n introduction: string,\n cloneURL: string,\n directoryName: string,\n nodeVersion: string,\n npmVersion: string,\n typescriptVersion: string,\n management: string\n): string {\n return `## Usage\n\n${introduction}\n\n\\`\\`\\`bash\ngit clone ${cloneURL}\ncd ${directoryName}\nnpm install\n\\`\\`\\`\n\n_Requires [Node.js](https://nodejs.org/) ${nodeVersion} or later, [npm](https://www.npmjs.com/) ${npmVersion} or later, and [TypeScript](https://www.typescriptlang.org/) ${typescriptVersion} or later._\n\n${management}`;\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess } from '@/utilities';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const API_REFERENCE_PATH = 'API_REFERENCE.md';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Lists every export of each import path in API_REFERENCE.md. Runs with the README's sections where the project has that file. */\nexport async function documentAPIReference(): Promise<void> {\n try {\n logOperationHeader('Document API Reference');\n\n // TypeScript is an optional peer, so the code that reads the source with it is loaded only when it's needed.\n const { writeAPIReference } = await import('@/utilities/apiReference');\n await writeAPIReference('1️⃣ ', API_REFERENCE_PATH);\n\n logOperationSuccess('API reference documented');\n } catch (error) {\n console.error('❌ Error documenting API reference', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, logStepHeader, readJSONFile, readTextFileOrNull, writeReadmeSection } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface Sizes {\n uncompressed: number;\n gzip: number;\n}\n\ninterface SondaResource {\n kind: 'asset' | 'chunk' | 'filesystem' | 'sourcemap';\n name: string;\n uncompressed: number;\n gzip?: number;\n parent?: string | null;\n}\n\ninterface SondaDependency {\n name: string;\n paths: string[];\n}\n\ninterface SondaJson {\n resources: SondaResource[];\n dependencies: SondaDependency[];\n}\n\ninterface GroupData {\n sizes: Sizes;\n files: Map<string, Sizes>;\n}\n\ninterface WasmSizes {\n bytes: number; // As embedded, base64 text included.\n binaryBytes: number; // The WebAssembly the text decodes to.\n}\n\ntype GroupEntry = [string, GroupData];\ntype DependencyPath = [path: string, name: string];\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport const BUNDLE_REPORT_PATH = 'bundle-analysis-reports/sonda/index.json'; // Written by Sonda during the Vite build.\nconst WORKER_REPORT_PATH = 'bundle-analysis-reports/sonda/worker.json'; // Written for an inlined worker, where the project's build adds one.\n\nconst BUNDLE_START_MARKER = '<!-- BUNDLE_START -->';\nconst BUNDLE_END_MARKER = '<!-- BUNDLE_END -->';\nconst INDENT = ' ';\nconst BAR_WIDTH = 20;\nconst BAR_CHARACTER = '█';\nconst PART_BAR_CHARACTER = '▒'; // Lighter, so a '↳' row reads as part of the row above. Markdown has no colour that also shows on npm.\nconst MIN_VISIBLE_PERCENT = 100 / BAR_WIDTH / 2; // Below this a bar rounds to no characters at all.\nconst SMALL_FILES_MAX_PERCENT = 100 / BAR_WIDTH; // The combined row for small files stays within one bar character.\n\n// GitHub strips CSS from a README, so column widths are steered through the text itself: the composition column has no\n// spaces to break at, and a long label is shortened so the column it gives up stays narrow.\nconst LABEL_MAX_LENGTH = 48;\n\nconst BUNDLE_ANALYSIS_INTRO = `This report is updated with each release, from the bundle the release builds, using [Sonda](https://sonda.dev/), which analyses final source maps to reveal the actual effects of tree-shaking and minification rather than relying on pre-build estimates.\\n\\n_Note: Sonda's Vite reports currently exclude CSS files, since Vite does not generate source maps for CSS._`;\n\nconst BAR_NOTE = `Bars show each row's share of its output file.`;\nconst PART_ROW_NOTE = '↳ rows are part of the row above.'; // Only where the table has such rows, which module level leaves out.\n\nconst MORE_NOTE =\n '+ n more = the row also holds n more files from the same package or folder, each no larger than the one named. A package can appear under several output files, each holding different files, never the same file twice.';\n\nconst UNTRACED_LABEL = '(bundler output, whitespace & JSON)';\nconst WORKER_LABEL = '(inlined worker)';\nconst WORKER_NOTE = `${WORKER_LABEL} = a Web Worker built separately and embedded in its output file as text. Where the build records what it contains, its rows list that; any few bytes over are the escaping needed to embed it.`;\nconst WASM_LABEL_PREFIX = '(Rust WebAssembly as base64';\nconst WASM_NOTE = `${WASM_LABEL_PREFIX}…) = the compiled Rust code, embedded as base64 text, about a third larger than the binary it decodes to, which is the size given.`;\n\nconst UNTRACED_NOTE = `${UNTRACED_LABEL} = bytes Sonda can't trace to a source file: whitespace (indentation and line breaks), code the bundler generates (region comments, the combined import/export lines, its small runtime helper and wrappers), and imported JSON such as \\`config.json\\`, which the bundler doesn't map. The JSON and the generated code are real bytes that ship; the whitespace mostly disappears once compressed.`;\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport async function documentBundleSizes(options?: { moduleLevel?: boolean }): Promise<void> {\n try {\n logOperationHeader('Document Bundle Sizes');\n\n logStepHeader('1️⃣ Read bundle analysis report');\n const json = await readJSONFile<SondaJson>(BUNDLE_REPORT_PATH);\n const workerReport = await readTextFileOrNull(WORKER_REPORT_PATH);\n const workerJson = workerReport === null ? undefined : (JSON.parse(workerReport) as SondaJson);\n // The built files, read to find what is embedded in them as text, which Sonda cannot trace.\n const assetContents = new Map<string, string | null>();\n for (const resource of json.resources) if (resource.kind === 'asset') assetContents.set(resource.name, await readTextFileOrNull(resource.name));\n\n logStepHeader(`2️⃣ Insert table into 'README.md'`);\n const bundleTable = buildBundleTable(json, { assetContents, isModuleLevel: options?.moduleLevel ?? false, workerJson });\n const rowNote = bundleTable.includes('↳') ? `${BAR_NOTE} ${PART_ROW_NOTE}` : BAR_NOTE;\n const moreNote = / \\+ \\d+ more \\|/.test(bundleTable) ? MORE_NOTE : '';\n const notes = [rowNote, moreNote, bundleTable.includes(WORKER_LABEL) ? WORKER_NOTE : '', bundleTable.includes(WASM_LABEL_PREFIX) ? WASM_NOTE : '', UNTRACED_NOTE].filter(\n (note) => note !== ''\n );\n\n await writeReadmeSection(`## Bundle Analysis\\n\\n${BUNDLE_ANALYSIS_INTRO}\\n\\n${bundleTable}\\n\\n${notes.join('\\n\\n')}`, BUNDLE_START_MARKER, BUNDLE_END_MARKER);\n\n logOperationSuccess('Bundle sizes documented');\n } catch (error) {\n console.error('❌ Error documenting bundle sizes', error);\n process.exit(1);\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// Each output file is broken down on its own, so its top-level bars add up to 100% of that file, and its heading gives its\n// share of the whole build. Rows marked '↳' are part of the row above; their bars use the same scale, so every bar in a\n// file can be compared with every other.\nfunction buildBundleTable(json: SondaJson, options: { assetContents: Map<string, string | null>; isModuleLevel: boolean; workerJson: SondaJson | undefined }): string {\n const { assetContents, isModuleLevel, workerJson } = options;\n const assetGroups = buildAssetGroups(json);\n const workerGroups = workerJson === undefined ? undefined : buildAssetGroups(workerJson).values().next().value;\n for (const [file, groups] of assetGroups) {\n const content = assetContents.get(file);\n if (content != null) separateEmbeddedContent(groups, content, workerGroups);\n }\n const buildTotal = assetGroups\n .values()\n .flatMap((groups) => groups.values().toArray())\n .reduce((sum, group) => sum + group.sizes.uncompressed, 0);\n\n const assets = json.resources\n .filter((resource) => resource.kind === 'asset')\n .map((asset): [string, Sizes] => [asset.name, resourceSizes(asset)])\n .toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n\n const lines = ['|Chunk/Module/File|Composition|', '|:------ |:-----------|'];\n\n for (const [file, sizes] of assets) {\n const groups = assetGroups.get(file) ?? new Map<string, GroupData>();\n const sortedGroups = [...groups].toSorted(compareGroups);\n const fileTotal = sortedGroups.reduce((sum, [, group]) => sum + group.sizes.uncompressed, 0);\n\n const buildShare = fileTotal > 0 && buildTotal > 0 ? ` · ${formatPercent(fileTotal, buildTotal)} of the build` : '';\n lines.push(row(`**${fitLabel(file)}**`, `${chunkSizes(sizes)}${buildShare}`), ...renderGroupRows(sortedGroups, fileTotal, isModuleLevel));\n }\n\n return lines.join('\\n');\n}\n\n// Embedded text is traced to no source, or to the one that embeds it, so it is measured in the built file and given rows\n// of its own: an inlined worker, broken down where its build was recorded, and embedded WebAssembly.\nfunction separateEmbeddedContent(groups: Map<string, GroupData>, content: string, workerGroups: Map<string, GroupData> | undefined): void {\n const workerText = findInlinedWorkerText(content);\n const workerWasm = measureWasm(workerText ?? '');\n const allWasm = measureWasm(content);\n separateWasm(groups, { bytes: allWasm.bytes - workerWasm.bytes, binaryBytes: allWasm.binaryBytes - workerWasm.binaryBytes });\n if (workerText !== undefined) separateWorker(groups, Buffer.byteLength(workerText), workerWasm, workerGroups);\n}\n\n// Vite embeds an inlined worker as a string it passes to 'new Worker(… encodeURIComponent(name))'; this finds that string.\nfunction findInlinedWorkerText(content: string): string | undefined {\n if (!content.includes('new Worker(')) return undefined;\n const variableName = /encodeURIComponent\\((\\w+)\\)/.exec(content)?.[1];\n if (variableName === undefined) return undefined;\n // eslint-disable-next-line security/detect-non-literal-regexp -- The name is a JavaScript identifier, matched by '\\w+' above.\n const declaration = new RegExp(String.raw`(?:var|let|const)\\s+${variableName}\\s*=\\s*([\"'\\`])`).exec(content);\n const quote = declaration?.[1];\n if (declaration === null || quote === undefined) return undefined;\n const start = declaration.index + declaration[0].length;\n let end = start;\n while (end < content.length && content[end] !== quote) end += content[end] === '\\\\' ? 2 : 1;\n return content.slice(start, end);\n}\n\nfunction measureWasm(text: string): WasmSizes {\n const sizes = { bytes: 0, binaryBytes: 0 };\n for (const match of text.matchAll(/data:application\\/wasm;base64,([A-Za-z\\d+/]*={0,2})/g)) {\n const base64 = match[1] ?? '';\n sizes.bytes += match[0].length;\n sizes.binaryBytes += Math.floor((base64.length * 3) / 4) - countBase64Padding(base64);\n }\n return sizes;\n}\n\nfunction countBase64Padding(base64: string): number {\n if (base64.endsWith('==')) return 2;\n return base64.endsWith('=') ? 1 : 0;\n}\n\n// The WebAssembly is taken from the wasm-bindgen file that embeds it, or failing that from the untraced bytes.\nfunction separateWasm(groups: Map<string, GroupData>, wasm: WasmSizes): void {\n if (wasm.bytes <= 0) return;\n const source = [groups.get('wasm'), groups.get(UNTRACED_LABEL)]\n .flatMap((group) =>\n group === undefined\n ? []\n : group.files\n .entries()\n .map(([fileName, sizes]) => ({ group, fileName, sizes }))\n .toArray()\n )\n .find(({ sizes }) => sizes.uncompressed >= wasm.bytes);\n if (source === undefined) return;\n subtractBytes(groups, source.group, source.fileName, source.sizes, wasm.bytes);\n const label = `${WASM_LABEL_PREFIX}, ${formatBytes(wasm.binaryBytes)} binary)`;\n groups.set(label, { sizes: { uncompressed: wasm.bytes, gzip: 0 }, files: new Map([['', { uncompressed: wasm.bytes, gzip: 0 }]]) });\n}\n\nfunction separateWorker(groups: Map<string, GroupData>, workerBytes: number, workerWasm: WasmSizes, workerGroups: Map<string, GroupData> | undefined): void {\n const untraced = groups.get(UNTRACED_LABEL);\n const untracedSizes = untraced?.files.get('');\n if (untraced === undefined || untracedSizes === undefined || untracedSizes.uncompressed < workerBytes) return;\n subtractBytes(groups, untraced, '', untracedSizes, workerBytes);\n const files = workerGroups === undefined ? new Map([['', { uncompressed: workerBytes, gzip: 0 }]]) : flattenWorkerGroups(workerGroups, workerBytes, workerWasm);\n groups.set(WORKER_LABEL, { sizes: { uncompressed: workerBytes, gzip: 0 }, files });\n}\n\n// The worker's own rows: its source files by name, and each dependency, the WebAssembly and its untraced bytes as one.\nfunction flattenWorkerGroups(workerGroups: Map<string, GroupData>, workerBytes: number, workerWasm: WasmSizes): Map<string, Sizes> {\n separateWasm(workerGroups, workerWasm);\n const files = new Map<string, Sizes>();\n for (const [groupName, group] of workerGroups) {\n if (groupName === 'src') {\n for (const [fileName, sizes] of group.files) files.set(fileName, { ...sizes });\n } else {\n const label = group.files.size === 1 ? formatGroupLabel(groupName, getSoleFileName(group.files)) : groupName;\n files.set(label, { ...group.sizes });\n }\n }\n const reportedBytes = files.values().reduce((sum, sizes) => sum + sizes.uncompressed, 0);\n const untraced = files.get(UNTRACED_LABEL) ?? zero();\n untraced.uncompressed += Math.max(0, workerBytes - reportedBytes);\n if (untraced.uncompressed > 0) files.set(UNTRACED_LABEL, untraced);\n return files;\n}\n\nfunction subtractBytes(groups: Map<string, GroupData>, group: GroupData, fileName: string, sizes: Sizes, bytes: number): void {\n sizes.uncompressed -= bytes;\n group.sizes.uncompressed -= bytes;\n if (sizes.uncompressed <= 0) group.files.delete(fileName);\n if (group.sizes.uncompressed > 0) return;\n for (const [groupName, candidate] of groups) if (candidate === group) groups.delete(groupName);\n}\n\n// Largest first, except the untraced bytes, which always come last as what is left over once the modules are listed.\nfunction compareGroups(a: GroupEntry, b: GroupEntry): number {\n if ((a[0] === UNTRACED_LABEL) !== (b[0] === UNTRACED_LABEL)) return a[0] === UNTRACED_LABEL ? 1 : -1;\n return b[1].sizes.uncompressed - a[1].sizes.uncompressed;\n}\n\n// A group of several files is labelled by its largest, with a count of the rest, so a package spread over several output\n// files reads as different parts of it rather than as a copy in each.\nfunction renderGroupRows(sortedGroups: GroupEntry[], fileTotal: number, isModuleLevel: boolean): string[] {\n const lines: string[] = [];\n\n for (const [groupName, { sizes: groupSizes, files }] of sortedGroups) {\n if (files.size === 1) {\n const fileName = getSoleFileName(files);\n lines.push(row(`${INDENT}${fitLabel(formatGroupLabel(groupName, fileName))}`, composition(groupSizes.uncompressed, fileTotal)));\n continue;\n }\n\n lines.push(row(`${INDENT}${formatSeveralFilesLabel(groupName, files)}`, composition(groupSizes.uncompressed, fileTotal)));\n if (!isModuleLevel) lines.push(...renderFileRows(files, fileTotal));\n }\n\n return lines;\n}\n\nfunction renderFileRows(files: Map<string, Sizes>, fileTotal: number): string[] {\n const sortedFiles = [...files].toSorted((a, b) => b[1].uncompressed - a[1].uncompressed);\n const smallCount = countSmallFiles(sortedFiles, fileTotal);\n const namedFiles = smallCount > 0 ? sortedFiles.slice(0, -smallCount) : sortedFiles;\n\n const rows = namedFiles.map(([fileName, fileSizes]) => row(`${INDENT}${INDENT}↳ ${fitLabel(fileName)}`, composition(fileSizes.uncompressed, fileTotal, PART_BAR_CHARACTER)));\n if (smallCount > 0) {\n const smallBytes = sortedFiles.slice(-smallCount).reduce((sum, [, fileSizes]) => sum + fileSizes.uncompressed, 0);\n rows.push(row(`${INDENT}${INDENT}↳ ${String(smallCount)} smaller files`, composition(smallBytes, fileTotal, PART_BAR_CHARACTER)));\n }\n return rows;\n}\n\n// Files too small to show any bar are combined into one row, smallest first, stopping before that row would pass one bar\n// character, so it never hides much. A lone small file keeps its name, as combining one file would hide it for nothing.\nfunction countSmallFiles(sortedFiles: [string, Sizes][], fileTotal: number): number {\n if (fileTotal <= 0) return 0;\n let count = 0;\n let bytes = 0;\n for (const [, fileSizes] of sortedFiles.toReversed()) {\n const isTooSmallToShow = (fileSizes.uncompressed / fileTotal) * 100 < MIN_VISIBLE_PERCENT;\n const isCombinedRowStillSmall = ((bytes + fileSizes.uncompressed) / fileTotal) * 100 <= SMALL_FILES_MAX_PERCENT;\n if (!isTooSmallToShow || !isCombinedRowStillSmall) break;\n count++;\n bytes += fileSizes.uncompressed;\n }\n return count >= 2 ? count : 0;\n}\n\n// A bar and percentage of the output file, then the size, so the share and the bytes behind it read together.\nfunction composition(bytes: number, fileTotal: number, barCharacter = BAR_CHARACTER): string {\n return `${bar(fileTotal > 0 ? (bytes / fileTotal) * 100 : 0, barCharacter)} · ${formatBytes(bytes)}`;\n}\n\n// A group with no file name, such as the untraced bytes, is shown on its own rather than as 'group → '.\nfunction formatGroupLabel(groupName: string, fileName: string): string {\n return fileName === '' ? groupName : `${groupName} → ${fileName}`;\n}\n\n// The inlined worker's rows are its own breakdown rather than files, so it keeps its plain label. The count is left out of\n// any shortening, so it is never the part cut.\nfunction formatSeveralFilesLabel(groupName: string, files: Map<string, Sizes>): string {\n if (groupName === WORKER_LABEL) return groupName;\n const [largestFileName] = [...files].toSorted((a, b) => b[1].uncompressed - a[1].uncompressed)[0] ?? [''];\n return `${fitLabel(formatGroupLabel(groupName, largestFileName))} + ${String(files.size - 1)} more`;\n}\n\n// A 'group → ' prefix is always kept whole. The path after it loses its start, keeping the file name it ends with, and\n// shows in full on hover.\nfunction fitLabel(label: string): string {\n const arrowIndex = label.indexOf(' → ');\n const prefix = arrowIndex === -1 ? '' : label.slice(0, arrowIndex + 3);\n const path = label.slice(prefix.length);\n const pathMaxLength = Math.max(LABEL_MAX_LENGTH - prefix.length, 2);\n const isTooLong = path.length > pathMaxLength;\n return isTooLong ? `${prefix}<abbr title=\"${path.replaceAll('&', '&').replaceAll('\"', '"')}\">…${path.slice(path.length - (pathMaxLength - 1))}</abbr>` : label;\n}\n\n// The composition's spaces are made non-breaking; its bar is the only code span and holds none, so no entity lands\n// inside one, where it would show as written.\nfunction row(label: string, composition: string): string {\n return `| ${label} | ${composition.replaceAll(' ', ' ')} |`;\n}\n\nfunction getSoleFileName(files: Map<string, Sizes>): string {\n const [fileName] = files.keys();\n if (fileName === undefined) throw new Error('Expected exactly one file');\n return fileName;\n}\n\n// Builds, per output asset, the size totals grouped by dependency (or 'src'/'wasm'/'(runtime)'), and by file within each group.\nfunction buildAssetGroups(json: SondaJson): Map<string, Map<string, GroupData>> {\n const dependencyPaths = buildDependencyPaths(json.dependencies);\n const assets = new Map<string, Map<string, GroupData>>();\n\n for (const resource of json.resources) {\n if (resource.kind !== 'chunk' || !resource.parent) continue;\n const { group: groupName, file: fileName } = resolveModule(resource.name, dependencyPaths);\n const sizes = resourceSizes(resource);\n\n const groups = assets.get(resource.parent) ?? new Map<string, GroupData>();\n assets.set(resource.parent, groups);\n\n const group = groups.get(groupName) ?? { sizes: zero(), files: new Map<string, Sizes>() };\n groups.set(groupName, group);\n addTo(group.sizes, sizes);\n\n const fileSizes = group.files.get(fileName) ?? zero();\n group.files.set(fileName, fileSizes);\n addTo(fileSizes, sizes);\n }\n\n return assets;\n}\n\n// Flattens `dependencies[].paths` into `[path, dependencyName]` pairs, longest path first so scoped/nested packages match before their parents.\nfunction buildDependencyPaths(dependencies: SondaDependency[]): DependencyPath[] {\n return dependencies.flatMap((dependency): DependencyPath[] => dependency.paths.map((path) => [path, dependency.name])).toSorted((a, b) => b[0].length - a[0].length);\n}\n\nfunction resolveModule(path: string, dependencyPaths: DependencyPath[]): { group: string; file: string } {\n const match = dependencyPaths.find(([dependencyPath]) => path === dependencyPath || path.startsWith(`${dependencyPath}/`));\n if (match) {\n const [dependencyPath, name] = match;\n return { group: name, file: path.slice(dependencyPath.length + 1) };\n }\n if (path === '[unassigned]') return { group: UNTRACED_LABEL, file: '' }; // Sonda's marker for chunk bytes it can't trace back to a source module.\n if (path.startsWith('\\u{0}')) return { group: '(runtime)', file: path.slice(1) };\n return path.startsWith('rust/') ? { group: 'wasm', file: shortenCrateFileName(path) } : { group: 'src', file: lastPathSegment(path) };\n}\n\n// wasm-pack names every generated file after the crate, so the shared part is shortened to '…', leaving what differs.\nfunction shortenCrateFileName(path: string): string {\n const crateName = path.split('/', 2)[1] ?? '';\n const fileName = lastPathSegment(path);\n return crateName !== '' && fileName.startsWith(crateName) ? `…${fileName.slice(crateName.length)}` : fileName;\n}\n\nfunction lastPathSegment(path: string): string {\n return path.split('/').at(-1) ?? path;\n}\n\nfunction resourceSizes(resource: SondaResource): Sizes {\n return { uncompressed: resource.uncompressed, gzip: resource.gzip ?? 0 };\n}\n\nfunction chunkSizes(sizes: Sizes): string {\n return `${formatBytes(sizes.uncompressed)} · gzip ${formatBytes(sizes.gzip)}`;\n}\n\nfunction bar(pct: number, barCharacter = BAR_CHARACTER): string {\n const count = Math.round((pct / 100) * BAR_WIDTH);\n return `\\`${barCharacter.repeat(count)}${'░'.repeat(BAR_WIDTH - count)}\\` ${pct.toFixed(1)}%`;\n}\n\nfunction zero(): Sizes {\n return { uncompressed: 0, gzip: 0 };\n}\n\nfunction addTo(target: Sizes, source: Sizes): void {\n target.uncompressed += source.uncompressed;\n target.gzip += source.gzip;\n}\n\nfunction formatPercent(part: number, whole: number): string {\n return `${((part / whole) * 100).toFixed(1)}%`;\n}\n\nfunction formatBytes(bytes: number): string {\n return bytes < 1024 ? `${String(bytes)} B` : `${(bytes / 1024).toFixed(1)} kB`;\n}\n","// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { documentActions } from '@/actions/documentActions';\nimport { documentContributingLicense } from '@/actions/documentContributingLicense';\nimport { documentDependencies } from '@/actions/documentDependencies';\nimport { documentOpening } from '@/actions/documentOpening';\nimport { documentQualitySecurity } from '@/actions/documentQualitySecurity';\nimport { documentUsage } from '@/actions/documentUsage';\nimport { API_REFERENCE_PATH, documentAPIReference } from '@/actions/documentApiReference';\nimport { BUNDLE_REPORT_PATH, documentBundleSizes } from '@/actions/documentBundleSizes';\nimport { getModuleConfig, logStepHeader, readJSONFile, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Regenerates every generated section of the README, in the order they appear, then the API reference where the project keeps one. */\n// 'allowedLicenses' lists the licences dependencies may use, separated by ';'. 'isModuleLevel' breaks bundle sizes\n// down by module rather than by package.\nexport async function documentProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const isConnector = getModuleConfig(configJSON.id).typeId === 'connector'; // Only connectors have an actions table.\n\n await documentOpening();\n if (isConnector) await documentActions();\n await documentUsage();\n await documentDependencies(allowedLicenses);\n\n // Bundle sizes come from the report the last build wrote, so they wait until there is one, as on a fresh clone.\n if ((await readTextFileOrNull(BUNDLE_REPORT_PATH)) === null) {\n logStepHeader(`ℹ️ Bundle sizes NOT documented, as there is no '${BUNDLE_REPORT_PATH}' yet. Build the project first.`);\n } else {\n await documentBundleSizes({ moduleLevel: isModuleLevel });\n }\n\n await documentQualitySecurity();\n await documentContributingLicense();\n\n // Only where the project keeps an API reference, so projects opt in by adding the file.\n const hasAPIReference = (await readTextFileOrNull(API_REFERENCE_PATH)) !== null;\n if (hasAPIReference) {\n await documentAPIReference();\n } else {\n logStepHeader(`ℹ️ '${API_REFERENCE_PATH}' NOT required by this project`);\n }\n\n // Saved as Prettier would format them, so 'npm run format' has nothing left to change. Only the files written here\n // are formatted, so documenting never touches the source.\n await spawnCommand('ℹ️ Format generated files', 'prettier', ['--write', 'README.md', ...(hasAPIReference ? [API_REFERENCE_PATH] : [])]);\n } catch (error) {\n console.error('❌ Error documenting project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport { existsSync } from 'node:fs';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses prettier to enforce formatting style rules. */\nexport async function formatCode(): Promise<void> {\n try {\n logOperationHeader('Format Code');\n\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- specified directories, no user input.\n const optionalGlobs = ['app', 'src', 'tests'].filter((directory) => existsSync(directory)).map((directory) => `${directory}/**`);\n const formatTargets = ['--write', '*.json', '*.md', '*.ts', ...optionalGlobs];\n await spawnCommand('1️⃣ Format', 'prettier', formatTargets);\n\n logOperationSuccess('Code formatted');\n } catch (error) {\n console.error('❌ Error formatting code', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Uses eslint to check the code for potential errors and enforces coding style rules. */\nexport async function lintCode(): Promise<void> {\n try {\n logOperationHeader('Lint Code');\n\n await spawnCommand('1️⃣ Lint', 'eslint', ['.']);\n\n logOperationSuccess('Code linted');\n } catch (error) {\n console.error('❌ Error linting code', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport os from 'node:os';\nimport type { PackageJson } from 'type-fest';\nimport path from 'node:path';\nimport { promises as fs, type ObjectEncodingOptions } from 'node:fs';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { execCommand, getDirectoryEntries, getStatsForPath, readJSONFile, resolveSampleDataContentType, writeJSONFile } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// A file to upload, and the key it is stored under in the bucket.\ninterface BulkPutFile {\n file: string;\n key: string;\n}\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst SAMPLE_DATA_BUCKET = 'dpuse-sample-data-eu';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// TODO: Send a release secret with these config writes once dpuse-api requires one on its '/configs' write routes,\n// which are open to anyone (found October 2026).\n//\n// TODO: Split 'CLOUDFLARE_PUBLISH_TOKEN' (found October 2026). One token, held by all 28 repos, can edit every Worker\n// and route on all accounts, so a compromised release in any repo could replace the live app. Give module repos an R2\n// only token for this account, give a Workers deploy token only to repos that run 'wrangler deploy', and remove the\n// secret from repos that never touch Cloudflare.\nexport async function putState(): Promise<void> {\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${configJSON.id}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\n// Uploads a folder of sample data, and the folders inside it, under the same name in the sample data bucket. Files are\n// grouped by content type and each group goes up in one Wrangler call, which uploads its files in parallel.\nexport async function uploadDirectoryToR2(sourceDirectory: string, uploadDirectory: string): Promise<void> {\n const files = await listFilesRecursively(`${sourceDirectory}/${uploadDirectory}`, uploadDirectory);\n const filesByContentType = Map.groupBy(files, ({ key }) => resolveSampleDataContentType(key));\n for (const [contentType, contentTypeFiles] of filesByContentType) await bulkPutToR2(contentTypeFiles, ['--content-type', contentType]);\n}\n\n// Uploads the sample data: the 'application' and 'fileStore' folders, then their indexes. The indexes are always\n// checked with the server before a cached copy is reused, so a release is seen at once.\nexport async function uploadSampleDataToR2(sourceDirectory: string): Promise<void> {\n await uploadDirectoryToR2(sourceDirectory, 'application');\n await uploadDirectoryToR2(sourceDirectory, 'fileStore');\n const indexFiles = ['applicationIndex.json', 'fileStoreIndex.json'].map((name) => ({ file: `${sourceDirectory}/${name}`, key: name }));\n await bulkPutToR2(indexFiles, ['--content-type', 'application/json', '--cache-control', 'no-cache']);\n}\n\nexport async function uploadModuleConfigToDO(configJSON: ModuleConfig): Promise<void> {\n const stateId = configJSON.id;\n const options = {\n body: JSON.stringify(configJSON),\n headers: { 'Content-Type': 'application/json' },\n method: 'PUT'\n };\n const response = await fetch(`https://api.dpuse.app/configs/${stateId}`, options);\n if (!response.ok) throw new Error(await response.text());\n}\n\nexport async function uploadModuleToR2(packageJSON: PackageJson, uploadDirectoryPath: string): Promise<void> {\n const version = `v${packageJSON.version ?? 'unknown'}`;\n async function uploadDirectory(currentDirectory: string, prefix = ''): Promise<void> {\n const entries = await getDirectoryEntries(currentDirectory, { withFileTypes: true } as ObjectEncodingOptions);\n for (const entry of entries) {\n if (entry.isDirectory() || entry.name.endsWith('.map')) continue;\n const fullPath = `${currentDirectory}/${entry.name}`;\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const r2Path = `${uploadDirectoryPath}_${version}/${relativePath}`.replaceAll('\\\\', '/');\n const nonJavaScripContentType = entry.name.endsWith('.css') ? 'text/css' : 'application/octet-stream';\n const contentType = entry.name.endsWith('.js') ? 'application/javascript' : nonJavaScripContentType;\n console.info(`⚙️ Uploading '${relativePath}' → '${r2Path}'...`);\n await execCommand(undefined, 'wrangler', ['r2', 'object', 'put', r2Path, `--file=${fullPath}`, '--content-type', contentType, '--jurisdiction=eu', '--remote']);\n }\n }\n await uploadDirectory('dist');\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// One 'wrangler r2 bulk put' call, which reads the files to upload from a list in a temporary file.\n//\n// TODO: Recheck this on every Wrangler upgrade, as Wrangler marks 'r2 bulk put' as experimental (\"🚧 `wrangler r2 bulk\n// put` is an experimental command\"), so it may change. As of Wrangler 4.147, the list is a JSON array of\n// '{ key, file }', each entry may carry nothing else, and options such as '--content-type' and '--cache-control' apply\n// to every file in the call, which is why files are grouped by content type. The tests pin the exact arguments, so a\n// changed command shows up there; also check the command's '--help' and the warning it prints. If it is withdrawn,\n// fall back to one 'r2 object put' per file, as before (slow: one Wrangler process per file), or upload through R2's\n// S3-compatible API.\n//\n// TODO: Report to Cloudflare (https://github.com/cloudflare/workers-sdk) that in local mode ('--local'), Wrangler 4.147\n// stores a bulk-put key containing a space with '%20', e.g. 'fileStore/Encoding%20Samples/ascii.txt', because it\n// builds a URL from the key without encoding it (`http://localhost/${entry.key}`). Found in October 2026. Remote mode,\n// which this uses, sends each file through the same function as 'r2 object put' and stores the key correctly, so this\n// only matters when trying the upload against local storage.\nasync function bulkPutToR2(files: BulkPutFile[], options: string[]): Promise<void> {\n if (files.length === 0) return;\n const listFolderPath = await fs.mkdtemp(path.join(os.tmpdir(), 'dpuse-r2-bulk-'));\n const listFilePath = path.join(listFolderPath, 'files.json');\n try {\n await writeJSONFile(listFilePath, files);\n console.info(`⚙️ Uploading ${String(files.length)} files (${options.join(' ')})...`);\n await execCommand(undefined, 'wrangler', ['r2', 'bulk', 'put', SAMPLE_DATA_BUCKET, '--filename', listFilePath, ...options, '--jurisdiction=eu', '--remote']);\n } finally {\n await fs.rm(listFolderPath, { force: true, recursive: true });\n }\n}\n\n// Skips hidden files, such as '.DS_Store', which only exist on a developer's machine.\nasync function listFilesRecursively(sourcePath: string, keyPrefix: string): Promise<BulkPutFile[]> {\n const names = await getDirectoryEntries(sourcePath);\n const files: BulkPutFile[] = [];\n for (const name of names) {\n if (name.startsWith('.')) continue;\n const itemPath = `${sourcePath}/${name}`;\n const key = `${keyPrefix}/${name}`;\n const stats = await getStatsForPath(itemPath);\n if (stats.isDirectory()) files.push(...(await listFilesRecursively(itemPath, key)));\n else files.push({ file: itemPath, key });\n }\n return files;\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { getModuleConfig, logOperationHeader, logOperationSuccess, logStepHeader, type ModuleTypeConfig, readJSONFile, spawnCommand } from '@/utilities';\nimport { putState, uploadModuleConfigToDO, uploadModuleToR2, uploadSampleDataToR2 } from '@/utilities/cloudflare';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n// TODO: 'publish.yml' starts alongside CI rather than after it, and repeats CI's build, lint and test but not its audit,\n// so a release can publish while CI's audit fails. Make 'ci.yml' a reusable workflow ('workflow_call') that 'publish.yml'\n// runs as its first job, with the publish job needing it, and drop the repeated steps from 'publish.yml'.\n/** Publishes the project to npm, uploads it to DPUse, or both, as its module type requires. Run by the 'publish.yml' workflow. */\nexport async function publishProject(): Promise<void> {\n try {\n logOperationHeader('Publish Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n // Where a module goes is set by its type, so every project calls this the same way. Tools go to both places: npm\n // first, so the app is never told of a version whose npm publish failed.\n if (moduleTypeConfig.publishedTo === 'npm') {\n await spawnCommand('1️⃣ Publish to npm', 'npm', ['publish', '--provenance']);\n } else {\n logStepHeader('1️⃣ Publishing to npm NOT required');\n }\n\n // The API, the app and the knowledge base are published by their own 'deploy' scripts: the API's and the app's\n // deploy their Workers, the knowledge base's loads the docs into Cloudflare KV and deploys the site. Each deploys\n // before it is registered, so the app is never told of a version that is not live yet.\n const isDeployedByScript = ['api', 'app', 'kb'].includes(moduleTypeConfig.publishedTo);\n if (isDeployedByScript) await spawnCommand('2️⃣ Deploy', 'npm', ['run', 'deploy']);\n\n await registerModule(isDeployedByScript ? '3️⃣ ' : '2️⃣ ', packageJSON, configJSON, moduleTypeConfig);\n\n // The sample data has no module to register. Its files and indexes go to R2; the workflow has already built the\n // indexes with 'npm run build'.\n if (moduleTypeConfig.publishedTo === 'sampleData') {\n logStepHeader('3️⃣ Upload sample data');\n await uploadSampleDataToR2('public');\n }\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' published.`);\n } catch (error) {\n console.error('❌ Error publishing project', error);\n process.exit(1);\n }\n}\n\n// Also run as the last step of 'releaseProject'.\nexport async function registerModule(stepIcon: string, packageJSON: PackageJson, configJSON: ModuleConfig, moduleTypeConfig: ModuleTypeConfig): Promise<void> {\n if (moduleTypeConfig.typeId === 'app') {\n logStepHeader(`${stepIcon} Register module`);\n await putState();\n } else if (moduleTypeConfig.typeId === 'engine') {\n logStepHeader(`${stepIcon} Register module`);\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName ?? 'unknown'}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new engine is available and try to access it before it is uploaded to R2.\n } else if (moduleTypeConfig.uploadGroupName === undefined) {\n logStepHeader(`${stepIcon} Registration NOT required`);\n } else {\n logStepHeader(`${stepIcon} Register module`);\n const moduleTypeName = configJSON.id.split('-').slice(2).join('-');\n await uploadModuleToR2(packageJSON, `dpuse-engine-eu/${moduleTypeConfig.uploadGroupName}/${moduleTypeName}`);\n await uploadModuleConfigToDO(configJSON); // This MUST follow 'uploadModuleToR2', otherwise the app will receive a message a new module is available and try to access it before it is uploaded to R2.\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { bundleProject } from '@/actions/buildProject';\nimport { documentProject } from '@/actions/documentProject';\nimport { registerModule } from '@/actions/publishProject';\nimport {\n buildModuleConfig,\n bumpPackageVersion,\n execCommand,\n getModuleConfig,\n logOperationHeader,\n logOperationSuccess,\n logStepHeader,\n readJSONFile,\n spawnCommand\n} from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Bump version, builds config, builds project, regenerates the README, synchronise with GitHub and publish to npm or Cloudflare. */\nexport async function releaseProject(allowedLicenses = 'MIT', isModuleLevel = false): Promise<void> {\n try {\n logOperationHeader('Release Project');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n const builtConfigJSON = await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await bundleProject('3️⃣ ', packageJSON);\n\n // After the build, so the bundle sizes are the released bundle's, and before staging, so the README is committed\n // with the release. Its governance step runs the tests, so a failing test stops the release before anything is pushed.\n logStepHeader('4️⃣ Regenerate README');\n await documentProject(allowedLicenses, isModuleLevel);\n\n await execCommand('5️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('6️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('7️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n await registerModule('8️⃣ ', packageJSON, builtConfigJSON, moduleTypeConfig);\n\n // The release triggers the 'publish.yml' workflow, which publishes to npm through trusted publishing, so no token is needed here.\n if (moduleTypeConfig.publishedTo === 'npm') {\n const tagName = `v${packageJSON.version ?? 'unknown'}`;\n await spawnCommand('9️⃣ Trigger GitHub release', 'gh', ['release', 'create', tagName, '--target', 'main', '--generate-notes', '--latest']);\n } else {\n logStepHeader(`9️⃣ Publishing NOT required for package with type identifier of '${moduleTypeConfig.typeId}'.`);\n }\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' released.`);\n } catch (error) {\n console.error('❌ Error releasing project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── DPUse Framework\nimport type { ModuleConfig } from '@dpuse/dpuse-shared';\n\n// ── Local Framework\nimport { buildModuleConfig, bumpPackageVersion, execCommand, getModuleConfig, logOperationHeader, logOperationSuccess, readJSONFile } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Synchronise the local repository with the main GitHub repository. */\nexport async function syncProjectWithGitHub(): Promise<void> {\n try {\n logOperationHeader('Synchronise Project with GitHub');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const configJSON = await readJSONFile<ModuleConfig>('config.json');\n const moduleTypeConfig = getModuleConfig(configJSON.id);\n\n await bumpPackageVersion('1️⃣ ', packageJSON);\n\n await buildModuleConfig('2️⃣ ', packageJSON, moduleTypeConfig);\n\n await execCommand('3️⃣ Stage changes', 'git', ['add', '.']);\n\n await execCommand('4️⃣ Commit changes', 'git', ['commit', '-m', `v${packageJSON.version ?? 'unknown'}`]);\n\n await execCommand('5️⃣ Push changes', 'git', ['push', 'origin', 'main:main']);\n\n logOperationSuccess(`Project version '${packageJSON.version ?? 'unknown'}' synchronised with GitHub.`);\n } catch (error) {\n console.error('❌ Error synchronising project with GitHub', error);\n process.exit(1);\n }\n}\n","// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readTextFileOrNull, spawnCommand } from '@/utilities';\n\n// ── Types ────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\ninterface TestTypeConfig {\n id: TestTypeId;\n label: string;\n command: string;\n arguments: string[];\n configFileName: string; // Having this file is how a project says it runs this type of test.\n}\n\nexport type TestTypeId = 'e2e' | 'unit';\n\n// ── Constants ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nconst STEP_ICONS = ['1️⃣ ', '2️⃣ ', '3️⃣ ', '4️⃣ '];\n\n// In the order they run. Unit tests go first so a failure stops the run before the slow browser tests start.\n// Both runners are told to pass when they find nothing, so a project that has set up a runner but not yet written\n// any tests reports green rather than red, and a real failure stands out.\nconst TEST_TYPE_CONFIGS: TestTypeConfig[] = [\n { id: 'unit', label: 'Run unit tests', command: 'vitest', arguments: ['run', '--passWithNoTests'], configFileName: 'vitest.config.ts' },\n { id: 'e2e', label: 'Run end-to-end tests', command: 'playwright', arguments: ['test', '--pass-with-no-tests'], configFileName: 'playwright.config.ts' }\n];\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Runs the requested types of test, skipping any type this project has not configured. */\nexport async function testProject(testTypeIds: TestTypeId[] = ['unit']): Promise<void> {\n try {\n logOperationHeader('Test Project');\n\n let stepNumber = 0;\n for (const testTypeConfig of TEST_TYPE_CONFIGS) {\n // Pass quietly over a type that was not requested, or that the project does not run because it has no\n // configuration file for it.\n if (!testTypeIds.includes(testTypeConfig.id) || (await readTextFileOrNull(testTypeConfig.configFileName)) === null) continue;\n\n const stepLabel = `${STEP_ICONS[stepNumber] ?? ''} ${testTypeConfig.label}`;\n await spawnCommand(stepLabel, testTypeConfig.command, testTypeConfig.arguments);\n stepNumber += 1;\n }\n\n if (stepNumber === 0) {\n console.warn('\\n⚠️ No tests configured for this project.\\n');\n return;\n }\n\n logOperationSuccess('Project tested');\n } catch (error) {\n console.error('❌ Error testing project', error);\n process.exit(1);\n }\n}\n","// ── External Dependencies & Registrations\nimport type { PackageJson } from 'type-fest';\n\n// ── Local Framework\nimport { logOperationHeader, logOperationSuccess, readJSONFile, spawnCommand } from '@/utilities';\n\n// ── Actions ──────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Create a GitHub release for the current version, which triggers the 'publish.yml' workflow. */\nexport async function triggerGitHubRelease(): Promise<void> {\n try {\n logOperationHeader('Trigger GitHub Release');\n\n const packageJSON = await readJSONFile<PackageJson>('package.json');\n const tagName = `v${packageJSON.version ?? 'unknown'}`;\n\n await spawnCommand('1️⃣ Trigger GitHub release', 'gh', ['release', 'create', tagName, '--target', 'main', '--generate-notes', '--latest']);\n\n logOperationSuccess(`GitHub release '${tagName}' created.`);\n } catch (error) {\n console.error('❌ Error triggering GitHub release', error);\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;A,GC4BMmD,qBAAsB,IAAI,IAAI,CAAC,YAAY,MAAM,CAAC;AAKxD,eAAsBC,KAAmC;CACrD,IAAI;EACA,EAAmB,oBAAoB;EAIvC,IAAMC,IAAc,MAAMX,EAA0B,cAAc;EAClE,AAAIN,GAA+B,IAAIiB,EAAY,QAAQ,EAAE,IACzDV,EAAc,0CAA0CU,EAAY,QAAQ,GAAG,4BAA4B,IAE3G,MAAMtC,EAAa,yDAAyD,OAAO,CAAC,SAAS,YAAY,CAAC;EAK9G,IAAMuC,IAAS,MAAMxC,EAAsB,oEAAoE,OAAO,CAAC,SAAS,QAAQ,CAAC,GACnIyC,IAAS,KAAK,MAAMD,CAAM;EAChC,IAAIC,EAAO,UAAU,KAAA,GAAW,MAAU,MAAMA,EAAO,MAAM,OAAO;EAEpE,IAAMC,IAAqBC,GAAgBC,GAAeH,CAAM,CAAC;EACjE,IAAIC,EAAmB,SAAS,GAAG,MAAU,MAAM,GAAG,OAAOA,EAAmB,MAAM,EAAE,wCAAwC;EAEhI,EAAoB,sBAAsB;CAC9C,SAASG,GAAO;EAEZ,AADA,QAAQ,MAAM,kCAAkCA,CAAK,GACrD,QAAQ,KAAK,CAAC;CAClB;AACJ;AAGA,eAAsBC,GAAwB,GAA8B;CACxE,IAAML,IAAS,KAAK,MAAM,MAAMzC,EAAsB+C,GAAO,OAAO,CAAC,SAAS,QAAQ,CAAC,CAAC;CACxF,IAAIN,EAAO,UAAU,KAAA,GAAW;EAC5B,QAAQ,KAAK,uCAAuCA,EAAO,MAAM,SAAS;EAC1E;CACJ;CAEA,IAAIO,IAAe;CACnB,KAAK,IAAMC,KAAYL,GAAe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