Rename ProjectConfigurator, restructure Projects workspace, retire MediaCollection naming

- Rename MediaConfig -> ProjectConfigurator throughout; drop the Parameters
  tab/page; rename the Mounts tab to Projects and restructure it into three
  sections: Central services, Main services, Third-party services
- Add a self-describe contract (GET /api/info returning name/tabs/mountTypes)
  and a server-side discovery proxy (POST /api/discover-service) so adding a
  main service only requires a URL
- Add ProjectConfigurator HA: multiple instances now sync their settings with
  each other (GET /api/settings/export, POST /api/settings/sync, a periodic
  background puller), last-write-wins per key by updated_at
- Add a generic, project-agnostic file-storage API on CarrierNode
  (GET/POST/DELETE /api/mount/{project}/{type}[/*]) driven by the same
  configured_mounts data the Projects workspace already writes, usable by any
  registered project, not just the media family
- Add last_login_at tracking to the shared auth Store/User (schema, queries,
  UpdateLastLogin) and surface it through the shared web-ui ManagedUser type
  and UserManagement component
- Retire the "MediaCollection" name: Go module -> repos.gfranz.ch/Gabriel20xx/shared/media-backend,
  binary -> mediabackend, session cookie default -> "session", media-webui
  merged into webui, media-shared-assets renamed to legacy-assets and pruned
  to the one file MediaDesktop still uses

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-04 15:02:16 +02:00
1 parent 07cf3308da
commit ee59571552
126 files changed
+2880 -8542

No files matched your search

+2 -2
View File
@@ -1,8 +1,8 @@
import { readFileSync, readdirSync, existsSync } from 'fs';
import { join } from 'path';
// TODO(MediaEngine extraction): this audits legacy pre-SvelteKit `<project>/public/*.html`
// script tags. MediaEngine's webui/ is SvelteKit-based (no per-service `public/` HTML pages), and
// TODO(shared extraction): this audits legacy pre-SvelteKit `<project>/public/*.html`
// script tags. this repo's webui/ is SvelteKit-based (no per-service `public/` HTML pages), and
// none of the sibling monorepo service directories below live inside this repo anymore (they're
// now separate repos: MediaModerator, MediaTools, MediaKiosk, MediaViewer). The existsSync guard
// below means this currently no-ops safely (nothing to audit) rather than erroring. Left as-is
+89 -89
View File
@@ -1,89 +1,89 @@
import fs from 'node:fs/promises';
import path from 'node:path';
const repoRoot = process.cwd();
const strict = process.argv.includes('--strict');
const includeExt = new Set(['.js', '.ejs', '.html']);
const skipDirs = new Set(['node_modules', '.git', 'dist', 'release', 'coverage']);
const styleDisplayAssign = /style\.display\s*=\s*['"](?:flex|grid)['"]/gi;
const inlineDisplayStyle = /style\s*=\s*['"][^'"]*display\s*:\s*(?:flex|grid)[^'"]*['"]/gi;
async function walk(dir, out = []) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
await walk(full, out);
continue;
}
if (!includeExt.has(path.extname(entry.name))) continue;
out.push(full);
}
return out;
}
function lineNumberAt(content, index) {
let line = 1;
for (let i = 0; i < index; i += 1) {
if (content.charCodeAt(i) === 10) line += 1;
}
return line;
}
function collectMatches(content, regex, type) {
const rows = [];
regex.lastIndex = 0;
let match;
while ((match = regex.exec(content)) !== null) {
rows.push({
type,
line: lineNumberAt(content, match.index),
snippet: match[0],
});
}
return rows;
}
const allFiles = await walk(repoRoot);
const violations = [];
// After folding media-backend/media-webui directly into the shared repo, this filter targets
// the frontend directories where inline HTML/CSS layout violations are actually possible
// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/).
const includedTopLevelDirs = ['media-webui/', 'scripts/media/'];
for (const filePath of allFiles) {
const rel = path.relative(repoRoot, filePath).replaceAll('\\', '/');
if (!includedTopLevelDirs.some(prefix => rel.startsWith(prefix))) continue;
const content = await fs.readFile(filePath, 'utf8');
const hits = [
...collectMatches(content, styleDisplayAssign, 'js-style-display'),
...collectMatches(content, inlineDisplayStyle, 'inline-style-display'),
];
if (hits.length) {
violations.push({ file: rel, hits });
}
}
const total = violations.reduce((sum, row) => sum + row.hits.length, 0);
console.log(
JSON.stringify(
{
ok: strict ? total === 0 : true,
strict,
files: violations.length,
violations: total,
entries: violations,
},
null,
2
)
);
if (strict && total > 0) {
process.exitCode = 1;
}
import fs from 'node:fs/promises';
import path from 'node:path';
const repoRoot = process.cwd();
const strict = process.argv.includes('--strict');
const includeExt = new Set(['.js', '.ejs', '.html']);
const skipDirs = new Set(['node_modules', '.git', 'dist', 'release', 'coverage']);
const styleDisplayAssign = /style\.display\s*=\s*['"](?:flex|grid)['"]/gi;
const inlineDisplayStyle = /style\s*=\s*['"][^'"]*display\s*:\s*(?:flex|grid)[^'"]*['"]/gi;
async function walk(dir, out = []) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
await walk(full, out);
continue;
}
if (!includeExt.has(path.extname(entry.name))) continue;
out.push(full);
}
return out;
}
function lineNumberAt(content, index) {
let line = 1;
for (let i = 0; i < index; i += 1) {
if (content.charCodeAt(i) === 10) line += 1;
}
return line;
}
function collectMatches(content, regex, type) {
const rows = [];
regex.lastIndex = 0;
let match;
while ((match = regex.exec(content)) !== null) {
rows.push({
type,
line: lineNumberAt(content, match.index),
snippet: match[0],
});
}
return rows;
}
const allFiles = await walk(repoRoot);
const violations = [];
// After folding media-backend/webui directly into the shared repo, this filter targets
// the frontend directories where inline HTML/CSS layout violations are actually possible
// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/).
const includedTopLevelDirs = ['webui/', 'scripts/media/'];
for (const filePath of allFiles) {
const rel = path.relative(repoRoot, filePath).replaceAll('\\', '/');
if (!includedTopLevelDirs.some(prefix => rel.startsWith(prefix))) continue;
const content = await fs.readFile(filePath, 'utf8');
const hits = [
...collectMatches(content, styleDisplayAssign, 'js-style-display'),
...collectMatches(content, inlineDisplayStyle, 'inline-style-display'),
];
if (hits.length) {
violations.push({ file: rel, hits });
}
}
const total = violations.reduce((sum, row) => sum + row.hits.length, 0);
console.log(
JSON.stringify(
{
ok: strict ? total === 0 : true,
strict,
files: violations.length,
violations: total,
entries: violations,
},
null,
2
)
);
if (strict && total > 0) {
process.exitCode = 1;
}
+153 -153
View File
@@ -1,153 +1,153 @@
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
// After a test run we want certain scratch roots removed entirely.
// NOTE: These are repo-root directories.
const DELETE_DIRS = [
'avatars',
'thumbnails',
'downloads',
'logs',
'output',
'input',
'loras',
'copy',
'database',
];
// Some roots are expected to remain present but empty.
// Keep this list lean to avoid surprising destructive behavior.
const EMPTY_DIRS = [
// (intentionally empty)
];
function rimrafChildren(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
let removed = 0;
for (const entry of fs.readdirSync(dir)) {
const full = path.join(dir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing', full, e.message);
}
}
return { removed };
}
function rimrafDir(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
try {
fs.rmSync(dir, { recursive: true, force: true });
return { deleted: true };
} catch (e) {
console.error('[CLEAN] Failed removing dir', dir, e.message);
return { deleted: false, error: e.message };
}
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
const results = [];
for (const rel of EMPTY_DIRS) {
const abs = path.join(repoRoot, rel);
ensureDir(abs);
const res = rimrafChildren(abs);
results.push({ dir: rel, mode: 'empty', ...res });
}
const deleted = [];
for (const rel of DELETE_DIRS) {
const abs = path.join(repoRoot, rel);
const res = rimrafDir(abs);
deleted.push({ dir: rel, mode: 'delete', ...res });
}
function removeFallbackDirs(baseDir) {
let removed = 0;
if (!fs.existsSync(baseDir)) return removed;
for (const entry of fs.readdirSync(baseDir)) {
if (entry.startsWith('tmp-fallback-')) {
const full = path.join(baseDir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing fallback dir', full, e.message);
}
}
}
return removed;
}
// Remove tmp-fallback-* directories from known roots.
// Tests can create these in repo root.
let fallbackRemoved = 0;
fallbackRemoved += removeFallbackDirs(repoRoot);
// Sweep tests/ folder for orphaned ephemeral Postgres artifacts left behind by crashed runs
// or CWD-relative path.resolve('tests').
// Pattern: mediacollection-embedded-pg-* dirs, mediacollection-test-postgres-*.json state files.
// NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was
// found anywhere in this repo — this sweep is a harmless no-op today but kept for forward
// compatibility / parity with the source script. The former sweep of a nested shared/tests/
// was dropped: after folding media-backend/media-webui directly into the shared repo (no more
// vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep.
const pgSweepDirs = [path.join(repoRoot, 'tests')];
let pgArtifactsRemoved = 0;
for (const sweepDir of pgSweepDirs) {
try {
for (const name of fs.readdirSync(sweepDir)) {
if (
name.startsWith('mediacollection-embedded-pg-') ||
(name.startsWith('mediacollection-test-postgres-') &&
(name.endsWith('.json') || name.endsWith('.json.lock'))) ||
name.startsWith('media-analyzer-test-')
) {
const full = path.join(sweepDir, name);
try {
fs.rmSync(full, { recursive: true, force: true });
pgArtifactsRemoved++;
} catch (e) {
console.error('[CLEAN] Failed removing artifact', full, e.message);
}
}
}
// If sweepDir is outside the canonical tests/ dir and now empty, remove it entirely.
if (sweepDir !== path.join(repoRoot, 'tests')) {
try {
const remaining = fs.readdirSync(sweepDir);
if (remaining.length === 0) {
fs.rmdirSync(sweepDir);
}
} catch {
/* ignore */
}
}
} catch {
/* ignore scan errors */
}
}
const summary = { ok: true, cleaned: results, fallbackRemoved, pgArtifactsRemoved };
summary.deleted = deleted;
console.log(JSON.stringify(summary, null, 2));
// Windows occasionally reports a native module handle crash (exit code 3221225477) after
// synchronous fs.rmSync bursts. Yield event loop once and exit 0 explicitly to stabilize CI.
setTimeout(() => {
try {
process.exitCode = 0; // be explicit
} catch {
/* noop */
}
}, 10);
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
// After a test run we want certain scratch roots removed entirely.
// NOTE: These are repo-root directories.
const DELETE_DIRS = [
'avatars',
'thumbnails',
'downloads',
'logs',
'output',
'input',
'loras',
'copy',
'database',
];
// Some roots are expected to remain present but empty.
// Keep this list lean to avoid surprising destructive behavior.
const EMPTY_DIRS = [
// (intentionally empty)
];
function rimrafChildren(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
let removed = 0;
for (const entry of fs.readdirSync(dir)) {
const full = path.join(dir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing', full, e.message);
}
}
return { removed };
}
function rimrafDir(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
try {
fs.rmSync(dir, { recursive: true, force: true });
return { deleted: true };
} catch (e) {
console.error('[CLEAN] Failed removing dir', dir, e.message);
return { deleted: false, error: e.message };
}
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
const results = [];
for (const rel of EMPTY_DIRS) {
const abs = path.join(repoRoot, rel);
ensureDir(abs);
const res = rimrafChildren(abs);
results.push({ dir: rel, mode: 'empty', ...res });
}
const deleted = [];
for (const rel of DELETE_DIRS) {
const abs = path.join(repoRoot, rel);
const res = rimrafDir(abs);
deleted.push({ dir: rel, mode: 'delete', ...res });
}
function removeFallbackDirs(baseDir) {
let removed = 0;
if (!fs.existsSync(baseDir)) return removed;
for (const entry of fs.readdirSync(baseDir)) {
if (entry.startsWith('tmp-fallback-')) {
const full = path.join(baseDir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing fallback dir', full, e.message);
}
}
}
return removed;
}
// Remove tmp-fallback-* directories from known roots.
// Tests can create these in repo root.
let fallbackRemoved = 0;
fallbackRemoved += removeFallbackDirs(repoRoot);
// Sweep tests/ folder for orphaned ephemeral Postgres artifacts left behind by crashed runs
// or CWD-relative path.resolve('tests').
// Pattern: shared-media-embedded-pg-* dirs, shared-media-test-postgres-*.json state files.
// NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was
// found anywhere in this repo — this sweep is a harmless no-op today but kept for forward
// compatibility / parity with the source script. The former sweep of a nested shared/tests/
// was dropped: after folding media-backend/webui directly into the shared repo (no more
// vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep.
const pgSweepDirs = [path.join(repoRoot, 'tests')];
let pgArtifactsRemoved = 0;
for (const sweepDir of pgSweepDirs) {
try {
for (const name of fs.readdirSync(sweepDir)) {
if (
name.startsWith('shared-media-embedded-pg-') ||
(name.startsWith('shared-media-test-postgres-') &&
(name.endsWith('.json') || name.endsWith('.json.lock'))) ||
name.startsWith('media-analyzer-test-')
) {
const full = path.join(sweepDir, name);
try {
fs.rmSync(full, { recursive: true, force: true });
pgArtifactsRemoved++;
} catch (e) {
console.error('[CLEAN] Failed removing artifact', full, e.message);
}
}
}
// If sweepDir is outside the canonical tests/ dir and now empty, remove it entirely.
if (sweepDir !== path.join(repoRoot, 'tests')) {
try {
const remaining = fs.readdirSync(sweepDir);
if (remaining.length === 0) {
fs.rmdirSync(sweepDir);
}
} catch {
/* ignore */
}
}
} catch {
/* ignore scan errors */
}
}
const summary = { ok: true, cleaned: results, fallbackRemoved, pgArtifactsRemoved };
summary.deleted = deleted;
console.log(JSON.stringify(summary, null, 2));
// Windows occasionally reports a native module handle crash (exit code 3221225477) after
// synchronous fs.rmSync bursts. Yield event loop once and exit 0 explicitly to stabilize CI.
setTimeout(() => {
try {
process.exitCode = 0; // be explicit
} catch {
/* noop */
}
}, 10);
+9 -9
View File
@@ -6,9 +6,9 @@
* - Theme CSS must not contain project/service-coupled selector tokens.
* - Theme CSS must not contain route-coupled panel IDs in selectors.
*
* TODO(MediaEngine extraction): the original monorepo version of this script also asserted that
* TODO(shared extraction): the original monorepo version of this script also asserted that
* MediaShared/public/css/index.css and MediaDesktop/public/index.css stayed byte-for-byte synced.
* That check is no longer possible from inside MediaEngine: MediaDesktop is now a fully separate
* That check is no longer possible from inside this repo: MediaDesktop is now a fully separate
* repo (Original/MediaDesktop) and isn't checked out alongside this one, so there is nothing here
* to diff it against. The desktop-vs-shared theme sync check has been dropped rather than pointed
* at a nonexistent path; if that guarantee still matters, it belongs in MediaDesktop's own CI
@@ -21,12 +21,12 @@ import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// MediaShared/public/css/index.css became packages/media-shared-assets/public/css/index.css
// once media-backend/media-webui were folded directly into the shared repo (no more vendored copy).
// MediaShared/public/css/index.css became packages/legacy-assets/public/css/index.css once
// media-backend/webui were folded directly into the shared repo (no more vendored copy).
const sharedThemePath = path.join(
repoRoot,
'packages',
'media-shared-assets',
'legacy-assets',
'public',
'css',
'index.css'
@@ -35,22 +35,22 @@ const sharedThemePath = path.join(
const bannedSelectorRules = [
{
name: 'project-coupled service token',
regex: /\b(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|servant)-page\b/i,
regex: /\b(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|carriernode)-page\b/i,
},
{
name: 'project-coupled state class token',
regex:
/\b(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|servant)-(?:home|page|stage|mode|active|panel)\b/i,
/\b(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|carriernode)-(?:home|page|stage|mode|active|panel)\b/i,
},
{
name: 'project-prefixed keyframe name',
regex:
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|servant)/i,
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|carriernode)/i,
},
{
name: 'project-coupled data attribute',
regex:
/\[data-(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|servant)[^\]]*\]/i,
/\[data-(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|carriernode)[^\]]*\]/i,
},
{
name: 'route-coupled panel selector',
+2 -2
View File
@@ -6,8 +6,8 @@
*
* Run: node scripts/shared/enforce-js-mapping.mjs
*
* TODO(MediaEngine extraction): §7.1's 1:1 HTML/JS rule applied to the legacy pre-SvelteKit
* `<project>/public/*.html` + `*.js` pages below. MediaEngine's webui/ is SvelteKit-based (routes
* TODO(shared extraction): §7.1's 1:1 HTML/JS rule applied to the legacy pre-SvelteKit
* `<project>/public/*.html` + `*.js` pages below. this repo's webui/ is SvelteKit-based (routes
* under webui/src/routes, no public/*.html+*.js pairs), and none of the other project directories
* listed below live inside this repo anymore (they're now separate repos). The existsSync guard
* per project means this currently no-ops safely (nothing found to check). Left as-is rather than
+3 -3
View File
@@ -7,16 +7,16 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// The monorepo kept its canonical JS/TS test sources under a single repo-root tests/ dir, which
// doesn't exist in MediaEngine. Scan the real locations JS/TS test files can currently live in
// doesn't exist in this repo. Scan the real locations JS/TS test files can currently live in
// this repo instead: webui/src (SvelteKit app) and shared/packages/*/test(s) (vendored from the
// shared repo). repoRoot/tests is kept as a forward-compatible root in case one is added later.
// As of the MediaEngine extraction none of these contain vitest/mocha/jest-style test files yet
// As of this repo's extraction, none of these contain vitest/mocha/jest-style test files yet
// (shared/packages/node-backend/test/auth.test.js uses plain `node --test`, which shares the same
// describe/it/test .skip API surface these patterns already match), so this currently passes
// trivially rather than being a dead check.
const testsRoots = [
path.join(repoRoot, 'tests'),
path.join(repoRoot, 'media-webui', 'src'),
path.join(repoRoot, 'webui', 'src'),
path.join(repoRoot, 'shared', 'packages'),
];
+3 -3
View File
@@ -4,10 +4,10 @@
* Does NOT print per-file diagnostics unless a failure occurs; keeps CI logs lean while enabling
* machine parsing. Exit code is non-zero if any package reports errors or warnings (configurable).
*
* MediaEngine extraction note: the monorepo version of this script discovered the monorepo root by
* Shared extraction note: the monorepo version of this script discovered the monorepo root by
* walking up for a MediaShared/package.json marker and iterated MediaShared/MediaModerator/
* MediaViewer/MediaTools using a shared root eslint.config.mjs. None of those sibling packages or
* the root config exist in MediaEngine — webui/ is the only JS/TS package here, and it already
* the root config exist in this repo — webui/ is the only JS/TS package here, and it already
* ships its own local eslint.config.js (picked up automatically, no --config override needed).
*/
import { spawnSync } from 'node:child_process';
@@ -18,7 +18,7 @@ import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'media-webui', path: 'media-webui' }];
const packages = [{ name: 'webui', path: 'webui' }];
function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
+4 -4
View File
@@ -4,10 +4,10 @@
* format check.
* Exits non‑zero if any package fails its lint step.
*
* MediaEngine extraction note: the monorepo version of this script discovered the monorepo root
* Shared extraction note: the monorepo version of this script discovered the monorepo root
* by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages
* against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of
* MediaShared/node_modules (npm workspace hoisting). None of that exists in MediaEngine: there is
* MediaShared/node_modules (npm workspace hoisting). None of that exists in this repo: there is
* no root package.json, no shared devDependency hoisting, and webui/ is the only JS/TS package —
* it already ships its own local eslint.config.js and prettier.config.js. The Stylelint section
* has been dropped entirely rather than pointed at a nonexistent .stylelintrc.json: webui has no
@@ -23,7 +23,7 @@ import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'media-webui', path: 'media-webui' }];
const packages = [{ name: 'webui', path: 'webui' }];
function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
@@ -83,7 +83,7 @@ for (const pkg of packages) {
// ===== webui: Prettier format check =====
console.log('\n===== FORMAT CHECK (Prettier, webui) =====');
{
const webuiDir = resolve(root, 'media-webui');
const webuiDir = resolve(root, 'webui');
const prettierBin = resolve(webuiDir, 'node_modules', 'prettier', 'bin', 'prettier.cjs');
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const fmtResult = existsSync(prettierBin)
+104 -104
View File
@@ -1,104 +1,104 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
// Run vitest with JSON reporter and parse skipped tests/suites.
// Usage: node scripts/list-skipped-tests.mjs
// Exits with code 0 if none skipped, 1 if any skipped.
//
// TODO(MediaEngine extraction): as of the extraction from MediaCollection, MediaEngine has no
// vitest suite anywhere (webui/ has no vitest devDependency/config; shared/packages/node-backend
// uses plain `node --test`; backend/ is Go), so `require.resolve('vitest/package.json')` below
// will fail immediately. The hardcoded `--config ../vitest.config.mjs` below also assumed this
// script runs from a subdirectory (e.g. the old repo-root tests/ dir) one level below a
// vitest.config.mjs — that layout does not exist in MediaEngine either. Left unfixed rather than
// guessed at: revisit once/if a real vitest suite is introduced in this repo, and point the
// --config flag at wherever that config actually lives.
// Resolve local vitest binary (avoid relying on npx which can be absent in some CI / shells)
function resolveVitestBin() {
try {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('vitest/package.json');
const binDir = path.dirname(pkgPath);
// Vitest exposes a bin field pointing to dist/cli.js; require it to ensure path stability
const pkg = require('vitest/package.json');
if (pkg && pkg.bin && pkg.bin.vitest) {
return path.join(binDir, pkg.bin.vitest);
}
// Fallback: common location
return path.join(binDir, 'dist', 'cli.js');
} catch (err) {
console.error('[list-skipped-tests] Unable to resolve vitest binary:', err.message);
process.exit(2);
}
}
const vitestBin = resolveVitestBin();
const nodeExec = process.execPath; // Use current Node runtime
// Always pass explicit config to ensure identical file set as normal test run.
// Use 'run' subcommand to execute once (no watch) and JSON reporter for machine parsing.
const args = [vitestBin, 'run', '--config', '../vitest.config.mjs', '--reporter=json'];
const child = spawn(nodeExec, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let jsonBlock = '';
child.stdout.on('data', d => {
const text = d.toString();
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
jsonBlock += text;
});
// eslint-disable-next-line no-unused-vars
child.on('close', _code => {
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
if (!match) {
console.error('[list-skipped-tests] Failed to parse Vitest JSON output');
process.exit(2);
}
let report;
try {
report = JSON.parse(match[1]);
} catch (e) {
console.error('[list-skipped-tests] JSON parse error', e);
process.exit(2);
}
// Vitest JSON reporter structure (observed):
// { numTotalTests, testResults: [ { name, assertionResults: [ { title, status } ] } ] }
// Legacy / alternative structure: { testFiles: [ { file, tests:[{ state }] } ] }
const skipped = [];
let totalFiles = 0;
if (Array.isArray(report.testResults)) {
totalFiles = report.testResults.length;
for (const tr of report.testResults) {
const filePath = tr.name || tr.file || 'unknown';
(tr.assertionResults || []).forEach(ar => {
// Vitest marks skipped tests with status === 'skipped'. Support 'todo' & 'pending' for completeness.
if (ar.status === 'skipped' || ar.status === 'todo' || ar.status === 'pending') {
skipped.push({ file: filePath, test: ar.fullName || ar.title, state: ar.status });
}
});
}
} else if (Array.isArray(report.testFiles)) {
// fallback structure
totalFiles = report.testFiles.length;
for (const f of report.testFiles) {
if (!f) continue;
const filePath = f.file || f.name || 'unknown';
(f.tests || []).forEach(t => {
if (t.state === 'skip' || t.state === 'todo' || t.state === 'pending') {
skipped.push({ file: filePath, test: t.name, state: t.state });
}
});
}
} else {
console.error('[list-skipped-tests] Unrecognized Vitest JSON structure');
process.exit(2);
}
const summary = { totalFiles, skippedCount: skipped.length, skipped };
console.log(JSON.stringify(summary, null, 2));
process.exit(skipped.length > 0 ? 1 : 0);
});
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
// Run vitest with JSON reporter and parse skipped tests/suites.
// Usage: node scripts/list-skipped-tests.mjs
// Exits with code 0 if none skipped, 1 if any skipped.
//
// TODO(shared extraction): as of this repo's extraction from the old monorepo, it has no
// vitest suite anywhere (webui/ has no vitest devDependency/config; shared/packages/node-backend
// uses plain `node --test`; backend/ is Go), so `require.resolve('vitest/package.json')` below
// will fail immediately. The hardcoded `--config ../vitest.config.mjs` below also assumed this
// script runs from a subdirectory (e.g. the old repo-root tests/ dir) one level below a
// vitest.config.mjs — that layout does not exist in this repo either. Left unfixed rather than
// guessed at: revisit once/if a real vitest suite is introduced in this repo, and point the
// --config flag at wherever that config actually lives.
// Resolve local vitest binary (avoid relying on npx which can be absent in some CI / shells)
function resolveVitestBin() {
try {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('vitest/package.json');
const binDir = path.dirname(pkgPath);
// Vitest exposes a bin field pointing to dist/cli.js; require it to ensure path stability
const pkg = require('vitest/package.json');
if (pkg && pkg.bin && pkg.bin.vitest) {
return path.join(binDir, pkg.bin.vitest);
}
// Fallback: common location
return path.join(binDir, 'dist', 'cli.js');
} catch (err) {
console.error('[list-skipped-tests] Unable to resolve vitest binary:', err.message);
process.exit(2);
}
}
const vitestBin = resolveVitestBin();
const nodeExec = process.execPath; // Use current Node runtime
// Always pass explicit config to ensure identical file set as normal test run.
// Use 'run' subcommand to execute once (no watch) and JSON reporter for machine parsing.
const args = [vitestBin, 'run', '--config', '../vitest.config.mjs', '--reporter=json'];
const child = spawn(nodeExec, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let jsonBlock = '';
child.stdout.on('data', d => {
const text = d.toString();
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
jsonBlock += text;
});
// eslint-disable-next-line no-unused-vars
child.on('close', _code => {
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
if (!match) {
console.error('[list-skipped-tests] Failed to parse Vitest JSON output');
process.exit(2);
}
let report;
try {
report = JSON.parse(match[1]);
} catch (e) {
console.error('[list-skipped-tests] JSON parse error', e);
process.exit(2);
}
// Vitest JSON reporter structure (observed):
// { numTotalTests, testResults: [ { name, assertionResults: [ { title, status } ] } ] }
// Legacy / alternative structure: { testFiles: [ { file, tests:[{ state }] } ] }
const skipped = [];
let totalFiles = 0;
if (Array.isArray(report.testResults)) {
totalFiles = report.testResults.length;
for (const tr of report.testResults) {
const filePath = tr.name || tr.file || 'unknown';
(tr.assertionResults || []).forEach(ar => {
// Vitest marks skipped tests with status === 'skipped'. Support 'todo' & 'pending' for completeness.
if (ar.status === 'skipped' || ar.status === 'todo' || ar.status === 'pending') {
skipped.push({ file: filePath, test: ar.fullName || ar.title, state: ar.status });
}
});
}
} else if (Array.isArray(report.testFiles)) {
// fallback structure
totalFiles = report.testFiles.length;
for (const f of report.testFiles) {
if (!f) continue;
const filePath = f.file || f.name || 'unknown';
(f.tests || []).forEach(t => {
if (t.state === 'skip' || t.state === 'todo' || t.state === 'pending') {
skipped.push({ file: filePath, test: t.name, state: t.state });
}
});
}
} else {
console.error('[list-skipped-tests] Unrecognized Vitest JSON structure');
process.exit(2);
}
const summary = { totalFiles, skippedCount: skipped.length, skipped };
console.log(JSON.stringify(summary, null, 2));
process.exit(skipped.length > 0 ? 1 : 0);
});
+47 -47
View File
@@ -1,47 +1,47 @@
#!/usr/bin/env node
// Simple timing harness: runs vitest in JSON reporter mode and summarizes collection vs test execution time.
//
// TODO(MediaEngine extraction): this script assumes a vitest test suite is configured in whatever
// directory it's invoked from. As of the extraction from MediaCollection, MediaEngine has no vitest
// suite anywhere (webui/ has no vitest devDependency or config; shared/packages/node-backend uses
// plain `node --test`; backend/ is Go). This is a generic, path-assumption-free script (no fix
// needed for the MediaEngine layout), but it currently has nothing to run against — it will fail
// with "vitest not found" / no config until a vitest suite is introduced somewhere in this repo.
import { spawn } from 'node:child_process';
const args = ['vitest', 'run', '--reporter=json'];
const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
stdio: ['ignore', 'pipe', 'inherit'],
});
let json = '';
child.stdout.on('data', d => {
json += d.toString();
});
child.on('close', code => {
if (code !== 0) {
console.error('vitest exited with code', code);
process.exit(code);
}
// Vitest JSON reporter may output multiple JSON objects; take last complete JSON object.
const matches = json.trim().match(/\{[\s\S]*$/); // naive: last JSON-like block
let data;
try {
data = JSON.parse(matches ? matches[0] : json);
} catch {
console.error('Failed to parse vitest JSON output');
process.exit(1);
}
const summary = data?.summary || {};
const out = {
testFiles: summary.testFiles ?? summary.files ?? 'n/a',
tests: summary.tests ?? 'n/a',
durationMs: summary.duration ?? 'n/a',
failed: summary.failed ?? 0,
skipped: summary.skipped ?? 0,
passed: summary.passed ?? 0,
// Vitest does not expose collect vs run granularly in JSON; we could extend later by parsing stdout.
note: 'For deeper phase timing, run "npx vitest run --reporter basic" and inspect breakdown.',
};
console.log(JSON.stringify(out, null, 2));
});
#!/usr/bin/env node
// Simple timing harness: runs vitest in JSON reporter mode and summarizes collection vs test execution time.
//
// TODO(shared extraction): this script assumes a vitest test suite is configured in whatever
// directory it's invoked from. As of this repo's extraction from the old monorepo, it has no vitest
// suite anywhere (webui/ has no vitest devDependency or config; shared/packages/node-backend uses
// plain `node --test`; backend/ is Go). This is a generic, path-assumption-free script (no fix
// needed for this repo's layout), but it currently has nothing to run against — it will fail
// with "vitest not found" / no config until a vitest suite is introduced somewhere in this repo.
import { spawn } from 'node:child_process';
const args = ['vitest', 'run', '--reporter=json'];
const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
stdio: ['ignore', 'pipe', 'inherit'],
});
let json = '';
child.stdout.on('data', d => {
json += d.toString();
});
child.on('close', code => {
if (code !== 0) {
console.error('vitest exited with code', code);
process.exit(code);
}
// Vitest JSON reporter may output multiple JSON objects; take last complete JSON object.
const matches = json.trim().match(/\{[\s\S]*$/); // naive: last JSON-like block
let data;
try {
data = JSON.parse(matches ? matches[0] : json);
} catch {
console.error('Failed to parse vitest JSON output');
process.exit(1);
}
const summary = data?.summary || {};
const out = {
testFiles: summary.testFiles ?? summary.files ?? 'n/a',
tests: summary.tests ?? 'n/a',
durationMs: summary.duration ?? 'n/a',
failed: summary.failed ?? 0,
skipped: summary.skipped ?? 0,
passed: summary.passed ?? 0,
// Vitest does not expose collect vs run granularly in JSON; we could extend later by parsing stdout.
note: 'For deeper phase timing, run "npx vitest run --reporter basic" and inspect breakdown.',
};
console.log(JSON.stringify(out, null, 2));
});
+142 -142
View File
@@ -1,142 +1,142 @@
#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
const registryBase = 'https://registry.npmjs.org';
const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
function shouldSkipSpec(spec) {
if (!spec) return true;
const lower = spec.toLowerCase();
return (
lower.startsWith('file:') ||
lower.startsWith('workspace:') ||
lower.startsWith('link:') ||
lower.startsWith('github:') ||
lower.startsWith('git+') ||
lower.startsWith('http://') ||
lower.startsWith('https://') ||
lower.startsWith('npm:')
);
}
function isSimpleRange(spec) {
if (!spec) return false;
if (spec === '*' || spec === 'latest') return true;
if (spec.includes(' ') || spec.includes('||')) return false;
return /^[~^]?\d+(\.\d+){0,2}([-.][0-9A-Za-z-.]+)?$/.test(spec);
}
function buildNextSpec(currentSpec, latest) {
if (currentSpec === '*' || currentSpec === 'latest') {
return `^${latest}`;
}
if (currentSpec.startsWith('~')) return `~${latest}`;
if (currentSpec.startsWith('^')) return `^${latest}`;
return `^${latest}`;
}
async function fetchLatestVersion(pkgName) {
const encoded = encodeURIComponent(pkgName);
const res = await fetch(`${registryBase}/${encoded}`);
if (!res.ok) {
throw new Error(`Failed to fetch ${pkgName}: ${res.status} ${res.statusText}`);
}
const data = await res.json();
const latest = data?.['dist-tags']?.latest;
if (!latest) {
throw new Error(`Missing dist-tags.latest for ${pkgName}`);
}
return latest;
}
async function loadJson(filePath) {
const raw = await fs.readFile(filePath, 'utf8');
return JSON.parse(raw);
}
async function saveJson(filePath, data) {
const next = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(filePath, next, 'utf8');
}
async function updatePackageJson(packageJsonPath) {
const pkg = await loadJson(packageJsonPath);
let changed = false;
const changes = [];
for (const section of sections) {
const deps = pkg[section];
if (!deps) continue;
const entries = Object.entries(deps);
for (const [name, spec] of entries) {
if (shouldSkipSpec(spec) || !isSimpleRange(spec)) continue;
let latest;
try {
latest = await fetchLatestVersion(name);
} catch (err) {
console.warn(`[skip] ${name}: ${err.message}`);
continue;
}
const nextSpec = buildNextSpec(spec, latest);
if (nextSpec !== spec) {
deps[name] = nextSpec;
changed = true;
changes.push({ name, from: spec, to: nextSpec, section });
}
}
}
if (changed) {
await saveJson(packageJsonPath, pkg);
}
return { changed, changes };
}
// MediaEngine has no root package.json / npm workspaces (unlike the monorepo this was extracted
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm
// package whose dependency versions this repo owns and should bump directly. shared/package.json
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
const LOCAL_PACKAGE_DIRS = ['media-webui'];
async function main() {
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
const results = [];
for (const pkgPath of packageJsonPaths) {
try {
const result = await updatePackageJson(pkgPath);
results.push({ pkgPath, ...result });
} catch (err) {
console.error(`[error] ${pkgPath}: ${err.message}`);
}
}
const updated = results.filter(r => r.changed);
const totalChanges = updated.reduce((sum, r) => sum + r.changes.length, 0);
console.log(`Updated ${updated.length} package.json file(s).`);
console.log(`Total dependency updates: ${totalChanges}`);
for (const { pkgPath, changes } of updated) {
const rel = path.relative(repoRoot, pkgPath);
console.log(`\n${rel}`);
for (const change of changes) {
console.log(` ${change.section}: ${change.name} ${change.from} -> ${change.to}`);
}
}
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});
#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
const registryBase = 'https://registry.npmjs.org';
const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
function shouldSkipSpec(spec) {
if (!spec) return true;
const lower = spec.toLowerCase();
return (
lower.startsWith('file:') ||
lower.startsWith('workspace:') ||
lower.startsWith('link:') ||
lower.startsWith('github:') ||
lower.startsWith('git+') ||
lower.startsWith('http://') ||
lower.startsWith('https://') ||
lower.startsWith('npm:')
);
}
function isSimpleRange(spec) {
if (!spec) return false;
if (spec === '*' || spec === 'latest') return true;
if (spec.includes(' ') || spec.includes('||')) return false;
return /^[~^]?\d+(\.\d+){0,2}([-.][0-9A-Za-z-.]+)?$/.test(spec);
}
function buildNextSpec(currentSpec, latest) {
if (currentSpec === '*' || currentSpec === 'latest') {
return `^${latest}`;
}
if (currentSpec.startsWith('~')) return `~${latest}`;
if (currentSpec.startsWith('^')) return `^${latest}`;
return `^${latest}`;
}
async function fetchLatestVersion(pkgName) {
const encoded = encodeURIComponent(pkgName);
const res = await fetch(`${registryBase}/${encoded}`);
if (!res.ok) {
throw new Error(`Failed to fetch ${pkgName}: ${res.status} ${res.statusText}`);
}
const data = await res.json();
const latest = data?.['dist-tags']?.latest;
if (!latest) {
throw new Error(`Missing dist-tags.latest for ${pkgName}`);
}
return latest;
}
async function loadJson(filePath) {
const raw = await fs.readFile(filePath, 'utf8');
return JSON.parse(raw);
}
async function saveJson(filePath, data) {
const next = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(filePath, next, 'utf8');
}
async function updatePackageJson(packageJsonPath) {
const pkg = await loadJson(packageJsonPath);
let changed = false;
const changes = [];
for (const section of sections) {
const deps = pkg[section];
if (!deps) continue;
const entries = Object.entries(deps);
for (const [name, spec] of entries) {
if (shouldSkipSpec(spec) || !isSimpleRange(spec)) continue;
let latest;
try {
latest = await fetchLatestVersion(name);
} catch (err) {
console.warn(`[skip] ${name}: ${err.message}`);
continue;
}
const nextSpec = buildNextSpec(spec, latest);
if (nextSpec !== spec) {
deps[name] = nextSpec;
changed = true;
changes.push({ name, from: spec, to: nextSpec, section });
}
}
}
if (changed) {
await saveJson(packageJsonPath, pkg);
}
return { changed, changes };
}
// this repo has no root package.json / npm workspaces (unlike the monorepo this was extracted
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm
// package whose dependency versions this repo owns and should bump directly. shared/package.json
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
const LOCAL_PACKAGE_DIRS = ['webui'];
async function main() {
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
const results = [];
for (const pkgPath of packageJsonPaths) {
try {
const result = await updatePackageJson(pkgPath);
results.push({ pkgPath, ...result });
} catch (err) {
console.error(`[error] ${pkgPath}: ${err.message}`);
}
}
const updated = results.filter(r => r.changed);
const totalChanges = updated.reduce((sum, r) => sum + r.changes.length, 0);
console.log(`Updated ${updated.length} package.json file(s).`);
console.log(`Total dependency updates: ${totalChanges}`);
for (const { pkgPath, changes } of updated) {
const rel = path.relative(repoRoot, pkgPath);
console.log(`\n${rel}`);
for (const change of changes) {
console.log(` ${change.section}: ${change.name} ${change.from} -> ${change.to}`);
}
}
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});
+1 -1
View File
@@ -47,7 +47,7 @@ $consumerProjects = @(
New-ConsumerProject 'Original/MediaAnalyzer' -Destination 'engine'
New-ConsumerProject 'Original/MediaTools' -Destination 'engine'
New-ConsumerProject 'Original/MediaViewer' -Destination 'engine'
New-ConsumerProject 'Central/MediaServant' -Destination 'engine'
New-ConsumerProject 'Central/CarrierNode' -Destination 'engine'
New-ConsumerProject 'Central/ModerationHub' -Destination 'engine'
New-ConsumerProject 'Central/ProjectConfigurator' -Destination 'engine'
New-ConsumerProject 'Central/AuthGuard'