Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([export-isplainobject-helper-from-server-lib-objects]): export isPlainObject from server/lib/objects.js

[._.]/ Adam Eivy8628e2b2e9cc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fc567bf425..66d1070a0b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,8 @@
## Changed
+- **`isPlainObject` promoted to a named export of `server/lib/objects.js`.** The `(v && typeof v === 'object' && !Array.isArray(v))` check was previously inlined at 16 sites across `server/lib/`, `server/services/`, and `server/routes/`. The helper is now a named export of `objects.js` (surfaces through the `server/lib/index.js` barrel automatically) and all 16 sites import it. Pure refactor — no behavioral changes; the helper retains the "non-null, non-array `object`" semantics that match every existing call site (Date / Map / class instances still return true).
+
- **Universe Builder cast preview now matches Media History exactly.** Clicking a cast/canon image used to open a stripped-down modal: only Refine Prompt / Add to Collection / Download, no negative prompt, no notes, and the "prompt" field showed the character description rather than the actual prompt that produced the image. The canon section's local `<MediaPreview>` is gone — canon clicks now bubble up to the page-level lightbox, which hydrates from the gallery sidecar (real prompt, negative prompt, model, seed, resolution, …) and exposes the full action set (Refine Prompt, Remix, Send to Video, Clean, Add to Collection, Download, notes, favorite). The descriptor string is kept as a fallback label only when no sidecar exists (legacy canon renders). Character reference sheets still route through `/data/image-refs/` via a `canon-sheet:<filename>` key so a basename collision with a gallery image can't misroute the preview.
- **First-run no longer silently flips :5555 from HTTP to self-signed HTTPS.** `scripts/setup-cert.js` ran on every `npm start` and, when Tailscale was unavailable, auto-generated a self-signed cert — breaking the documented `http://localhost:5555` URL and forcing a browser click-through. It now only auto-generates a self-signed cert when (a) the user explicitly passes `--self-signed`, or (b) a self-signed cert is already present (renewal path). Fresh installs without Tailscale stay HTTP-only on :5555 so the URL in the README and in `setup.sh`'s final banner just works. `setup.sh`'s "Access at:" banner is now cert-aware — when HTTPS got provisioned it prints the loopback HTTP mirror (`http://localhost:5553`) and the Tailscale hostname instead of the broken `http://localhost:5555`.
diff --git a/DONE.md b/DONE.md
index e312706fbb..522e4885c4 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-19
+- **[export-isplainobject-helper-from-server-lib-objects] Export `isPlainObject` from `server/lib/objects.js`.** Promoted the previously-private `isPlainObject(v) = !!v && typeof v === 'object' && !Array.isArray(v)` helper to a named export of `server/lib/objects.js` (surfaces automatically through the `server/lib/index.js` barrel) and migrated 16 inline call sites onto it — every site that exactly matched the 3-part check pattern. Sites: the previously-private declarations in `server/lib/objects.js` + `server/lib/mediaModels.js` (which now imports from objects.js), the 12 sites enumerated in PLAN (`services/calendarAccounts.js`, `messageAccounts.js`, `messagePlaywrightSync.js`, `loras.js`, `mortalLoomStore.js`, `updateChecker.js`, `meatspacePost.js`, `dataSync.js`, `featureAgents.js`, `taskSchedule.js` — also dropped its single-use local `const isPlainObject`, `pipeline/issues.js`, `sharing/exporter.js`), and 2 additional matching sites that landed between when the PLAN entry was authored and now (`routes/loras.js#DELETE /auth/civitai` and `services/universeBuilderExpand.js#sanitizeCategory`). Sites with a partial-shape second predicate (`mortalLoomStore.js`'s `current[k] && typeof current[k] === 'object'` and the symmetric block in `featureAgents.js`) kept their second predicate intact — only the full 3-part check was migrated, keeping the PR a pure refactor. Helper retains the loose "non-null, non-array `object`" semantics that match every call site's behavior (Date / Map / class instances still return true — documented in the JSDoc and locked in by 3 new vitest cases). `server/lib/README.md` row updated to name both `deepMerge` and `isPlainObject`. No behavioral changes. All 5832 server tests + 154 client tests pass.
- **[med-sharing-server-services-sharing] [med-sharing-server-services-mediaannotations-js-38] [low-sharing-server-services-mediaannotations-js] [low-sharing-server-services-mediaannotations-js-2] [low-sharing-server-services-sharing] Sharing/annotation-merge hardening bundle.** Five v2.1.0 pre-release residue items shipped together because they all touch the same annotation-sync + LWW-merge surface. (1) `annotationsSync.flushAll` no longer resolves one `sourceName` for all buckets — `exportAnnotationsToBucket` now resolves its own per-bucket name, so per-bucket `displayNameOverride` is honored in outgoing annotation manifest envelopes the same way it already was for series/universe/media manifests. The bucket-effective resolver lives in `sharing/annotationIdentity.js` as a new `resolveBucketSourceName(bucket)` export consumed by both the exporter and the annotation flush (the exporter's local copy in `sharing/exporter.js` was deleted in favor of the shared helper). (2) `mediaAnnotations.mergePeerAnnotations` now pre-rejects peer payloads with missing/invalid `updatedAt` before they reach `sanitizeAuthorEntry`'s `now`-fallback — previously a malformed peer record would always win LWW. The pre-check disambiguates "empty tombstone" (still applies as a delete) from "malformed payload" (now ignored entirely, instead of silently deleting the prior peer entry through the tombstone branch). (3) `sanitizeAuthorEntry` gained an opt-in `clampUpdatedAtTo` option used by the merge path so a peer whose clock is years ahead can't ratchet every subsequent LWW round on the same key — its `updatedAt` is clamped to local-now on import without disturbing reasonable timestamps. (4) `mergePeerAnnotations` rejects `peerInstanceId === 'unknown'` (and empty/non-string) on import — the outgoing path already guarded but a hand-crafted manifest or inconsistent peer could otherwise alias every record into the same "unknown" bucket and clobber each other on every merge. (5) `exportAnnotationsToBucket` now has a cheap early-out before `listBucketAssetKeys`: if local has zero annotations AND no prior record exists on disk for this `(bucket, instance)`, skip the manifest+asset-dir scan entirely (the common fresh-install fan-out case). A late-stage skip (both filtered AND prior empty) still covers the case where the bucket has assets but none overlap local. Coverage: 11 new vitest cases across `mediaAnnotations.test.js` (refuses `'unknown'` / empty peer id, drops missing+invalid updatedAt without nuking prior, clamps future-skewed peer ts) and new sibling `sharing/annotationsSync.test.js` (per-bucket displayNameOverride honored in record, cheap early-out skips `listManifestFilenames`, late skip when no local matches + no prior, asset-less bucket short-circuit, inbox-mode short-circuit, tombstone synthesis preserved for prior keys still in bucket). `/simplify` follow-up deferred to `[promote-unknown-instance-id-constant]` — promote the existing `UNKNOWN_INSTANCE_ID` constant from `importer.js` to a shared module + replace the bare `'unknown'` literal at the four remaining sites. All 5775 server tests pass.
- **[voice-picker-on-character-cards-voiceid-binding] Voice picker on character cards + per-line override.** New reusable `client/src/components/voice/VoicePicker.jsx` — engine-grouped dropdown over the merged `/api/pipeline/tts/voices` flat namespaced list (Kokoro + Piper today; future engines slot in upstream) with an audition button that POSTs to `/api/pipeline/tts/preview` and pipes the resulting WAV through `voiceClient.playWav` so it composes with voice-mode echo gating. Module-local cache shared between mounts so the universe character editor opening N picker instances fires exactly one `listPipelineTtsVoices` request. Wired into two consumers: (1) `CharacterDetailEditor`'s Identity section binds `entry.voiceId` (canon-level default for every line spoken by that character — server-side `resolveVoiceForLine` already preferred `character.voiceId` after a per-line override); (2) `AudioStage`'s per-line row gets a `compact + hideWhenEmpty` picker driving `voiceIdOverride` through the existing per-line PATCH path (`saveLineText` generalized to `saveLinePatch` so both text edits and voice-override changes share the in-flight-promise gate that `handleRender` already awaits — preventing a synth fired before the override PATCH settles from rendering against the prior voice). New client API helpers `listPipelineTtsVoices` + `previewPipelineTtsVoice` in `apiPipeline.js` (preview uses raw fetch since the shared `request()` helper auto-parses JSON). Unavailable saved voiceIds (engine uninstalled, voice renamed) are preserved as an `(unavailable)` option so the user sees what was bound instead of silently dropping to the placeholder. Empty voices catalog hides the AudioStage row picker (`hideWhenEmpty`) so a broken TTS install doesn't print an empty picker on every line. Coverage: 9 new vitest cases in `VoicePicker.test.jsx` cover catalog fetch + engine-group rendering, namespaced onChange + null-on-clear, unavailable-voice retention, audition→preview→playWav pipe, audition disabled with no selection, load-error inline display, hideWhenEmpty no-op, and the module-cache single-fetch invariant across mounts. Server-side voiceId + voiceIdOverride support was already complete (storyBible.js sanitizer, audio.js#resolveVoiceForLine, lineEditSchema in routes/pipeline.js, audio.test.js for both resolution priorities). All 5755 server tests + 130 client tests pass.
- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.
diff --git a/PLAN.md b/PLAN.md
index fa95c25c2e..6410958c07 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -27,8 +27,6 @@ _Nothing currently parked — pick the next item from the Backlog._
### Code quality / dedup (from `/simplify` passes)
-- [ ] [export-isplainobject-helper-from-server-lib-objects] **Export `isPlainObject` from `server/lib/objects.js`.** The `(v && typeof v === 'object' && !Array.isArray(v))` plain-object check is inlined at 14 sites across the codebase: `server/lib/objects.js:27` (private), `server/lib/mediaModels.js:183` (private), `server/services/calendarAccounts.js:11`, `messageAccounts.js:13`, `messagePlaywrightSync.js:29`, `loras.js:65`, `mortalLoomStore.js`, `updateChecker.js:93`, `meatspacePost.js:75`, `dataSync.js:112`, `featureAgents.js:108`, `taskSchedule.js:1900`, `pipeline/issues.js:673`, and (newly added 2026-05-19) `server/services/sharing/exporter.js#loadAssetHashCache`. Promote the helper to a named export in `objects.js`, add a row to `server/lib/README.md`, and migrate the call sites. Surfaced by /simplify during `[sharing-exporter-cache-sourcefile-hash-by-mtime]`; deferred to keep that PR scoped.
-
- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.
- [ ] [extract-useswipenav-hook-lib-clipboard-js] **Extract `useSwipeNav` from `MediaLightbox`.** Clipboard half of the original entry already shipped (`client/src/lib/clipboard.js`); `client/src/hooks/useSwipeNav.js` also exists for the swipe pattern but `MediaLightbox` still inlines its own swipe state. Migrate `MediaLightbox` swipe to `useSwipeNav` so the lightbox + any future mobile-swipe surface share one hook.
- [ ] [route-medialightbox-settings-drawer-through] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.
diff --git a/server/lib/README.md b/server/lib/README.md
index b74ec07a43..bd338958d8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -157,7 +157,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `asyncMutex.js` | Promise-based async mutex. |
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |
-| `objects.js` | Object utilities (deep merge, etc.). |
+| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement) + `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others). |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 6744a5e676..21b93af0cf 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -19,6 +19,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { join, dirname } from 'path';
import { PATHS } from './fileUtils.js';
+import { isPlainObject } from './objects.js';
import { RUNNER_FAMILIES } from './runners.js';
// fileUtils.ensureDir is async/Promise-returning; this module needs a
// synchronous version because `loadMediaModels()` is called at import-time
@@ -180,7 +181,6 @@ const seedIfMissing = () => {
// getVideoModels / buildAppModels would throw at module import-time and
// take down server startup. If a user supplies a real array, that's their
// list, full stop — we don't deep-merge entries.
-const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
const arrayOrDefault = (v, fallback) => (Array.isArray(v) ? v : fallback);
// Pre-flux2 stored entries had `broken: 'macos'` and no `runner` field. Merge
diff --git a/server/lib/objects.js b/server/lib/objects.js
index 3ad0620902..c952b43602 100644
--- a/server/lib/objects.js
+++ b/server/lib/objects.js
@@ -1,6 +1,13 @@
/**
* Object utilities.
*
+ * `isPlainObject(v)` — `true` when `v` is a non-null, non-array `object`. The
+ * project standard for "is this a `{...}`-shaped value?" — used to gate JSON
+ * sanitizers, deep-merge recursion, and LLM-response shape guards. Note that
+ * `Date`, `Map`, class instances, etc. also return `true` (matches every
+ * inline call-site this helper replaces, which all run against `JSON.parse`
+ * output or LLM payloads that never carry exotic prototypes).
+ *
* `deepMerge` is the project's shared deep-merge — promoted from
* `services/voice/config.js` after the same pattern was reinvented in
* `services/meatspacePost.js` and `routes/loras.js#POST /auth/civitai`.
@@ -24,7 +31,7 @@
* Does NOT mutate `base`.
*/
-const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+export const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
// Prototype-pollution guard: skip keys that would mutate Object.prototype
// when assigned through normal property access. Every current call site
diff --git a/server/lib/objects.test.js b/server/lib/objects.test.js
index 64be7fb366..5d365bf3a6 100644
--- a/server/lib/objects.test.js
+++ b/server/lib/objects.test.js
@@ -1,5 +1,36 @@
import { describe, it, expect } from 'vitest';
-import { deepMerge } from './objects.js';
+import { deepMerge, isPlainObject } from './objects.js';
+
+describe('isPlainObject', () => {
+ it('returns true for plain `{}`-shaped values', () => {
+ expect(isPlainObject({})).toBe(true);
+ expect(isPlainObject({ a: 1 })).toBe(true);
+ expect(isPlainObject(Object.create(null))).toBe(true);
+ });
+
+ it('returns false for null, undefined, primitives, and arrays', () => {
+ expect(isPlainObject(null)).toBe(false);
+ expect(isPlainObject(undefined)).toBe(false);
+ expect(isPlainObject(0)).toBe(false);
+ expect(isPlainObject('')).toBe(false);
+ expect(isPlainObject('hello')).toBe(false);
+ expect(isPlainObject(true)).toBe(false);
+ expect(isPlainObject(false)).toBe(false);
+ expect(isPlainObject([])).toBe(false);
+ expect(isPlainObject([1, 2, 3])).toBe(false);
+ });
+
+ it('returns true for class instances and Date — matches inline-call-site semantics', () => {
+ // Documented contract: this is "non-null, non-array `object`", not
+ // "constructor === Object". Existing call sites run against JSON.parse
+ // output that never carries exotic prototypes, so the loose check is
+ // intentional. Lock it in.
+ expect(isPlainObject(new Date())).toBe(true);
+ expect(isPlainObject(new Map())).toBe(true);
+ class Foo { }
+ expect(isPlainObject(new Foo())).toBe(true);
+ });
+});
describe('deepMerge', () => {
it('merges nested objects recursively', () => {
diff --git a/server/routes/loras.js b/server/routes/loras.js
index 68f81d65f3..f9eaef5a86 100644
--- a/server/routes/loras.js
+++ b/server/routes/loras.js
@@ -10,7 +10,7 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../lib/errorHandler.js';
-import { deepMerge } from '../lib/objects.js';
+import { deepMerge, isPlainObject } from '../lib/objects.js';
import { validateRequest } from '../lib/validation.js';
import {
deleteLora,
@@ -69,7 +69,7 @@ router.delete('/auth/civitai', asyncHandler(async (_req, res) => {
// typeof === 'object' is true for arrays — guard explicitly so a
// legacy/malformed `civitai: ['x']` value doesn't get spread into
// `{ '0': 'x', apiKey: undefined }`.
- if (next.civitai && typeof next.civitai === 'object' && !Array.isArray(next.civitai)) {
+ if (isPlainObject(next.civitai)) {
const { apiKey: _omit, ...rest } = next.civitai;
next.civitai = rest;
}
diff --git a/server/services/calendarAccounts.js b/server/services/calendarAccounts.js
index 518d0541de..e63af46037 100644
--- a/server/services/calendarAccounts.js
+++ b/server/services/calendarAccounts.js
@@ -2,13 +2,14 @@ import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
const ACCOUNTS_FILE = join(PATHS.calendar, 'accounts.json');
async function loadAccounts() {
await ensureDir(PATHS.calendar);
const parsed = await readJSONFile(ACCOUNTS_FILE, {});
- return (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
+ return isPlainObject(parsed) ? parsed : {};
}
async function saveAccounts(accounts) {
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index a00c831cef..d674dc5234 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -10,6 +10,7 @@ import crypto from 'crypto';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
import { mergeUniversesFromSync } from './universeBuilder.js';
import { mergeSeriesFromSync } from './pipeline/series.js';
import { mergeIssuesFromSync } from './pipeline/issues.js';
@@ -109,8 +110,7 @@ function mergeDeepUnion(local, remote, timestampField = 'derivedAt') {
if (key === timestampField) continue;
// Nested objects (markers): union keys, local wins per-key conflicts
- if (remoteVal && typeof remoteVal === 'object' && !Array.isArray(remoteVal)
- && localVal && typeof localVal === 'object' && !Array.isArray(localVal)) {
+ if (isPlainObject(remoteVal) && isPlainObject(localVal)) {
const mergedObj = { ...localVal };
for (const [k, v] of Object.entries(remoteVal)) {
if (!(k in mergedObj)) {
diff --git a/server/services/featureAgents.js b/server/services/featureAgents.js
index 9b26724c69..bcf7a55299 100644
--- a/server/services/featureAgents.js
+++ b/server/services/featureAgents.js
@@ -13,6 +13,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { cosEvents } from './cosEvents.js';
import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
+import { isPlainObject } from '../lib/objects.js';
import { getAppById } from './apps.js';
const DATA_DIR = PATHS.cos;
const FA_FILE = join(DATA_DIR, 'feature-agents.json');
@@ -105,7 +106,7 @@ export async function updateFeatureAgent(id, updates) {
const merged = { ...existing };
for (const [key, value] of Object.entries(updates)) {
- if (value && typeof value === 'object' && !Array.isArray(value) && existing[key] && typeof existing[key] === 'object') {
+ if (isPlainObject(value) && existing[key] && typeof existing[key] === 'object') {
merged[key] = { ...existing[key], ...value };
} else {
merged[key] = value;
diff --git a/server/services/loras.js b/server/services/loras.js
index a019f67d79..674e794935 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -26,6 +26,7 @@ import { pipeline } from 'stream/promises';
import { basename, join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { assertSafeFilename, listDirectoryByExtension, PATHS } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
import {
applyDownloadToken,
baseModelToRunner,
@@ -62,7 +63,7 @@ export const readSidecar = async (filename) => {
console.log(`⚠️ LoRA sidecar malformed JSON [${filename}]: ${err?.message || err}`);
return null;
}
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
+ return isPlainObject(parsed) ? parsed : null;
};
// Validate a basename so it can't escape PATHS.loras. Delegates to the
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index b27b01293b..2334b0491f 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -9,7 +9,7 @@ import { writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
-import { deepMerge } from '../lib/objects.js';
+import { deepMerge, isPlainObject } from '../lib/objects.js';
import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';
const MEATSPACE_DIR = PATHS.meatspace;
@@ -72,7 +72,7 @@ export async function updatePostConfig(updates) {
async function loadSessions() {
const raw = await readJSONFile(SESSIONS_FILE, { sessions: [] }, { allowArray: false });
- const data = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : { sessions: [] };
+ const data = isPlainObject(raw) ? raw : { sessions: [] };
if (!Array.isArray(data.sessions)) data.sessions = [];
return data;
}
diff --git a/server/services/messageAccounts.js b/server/services/messageAccounts.js
index 293977d1e8..87e31ec0d0 100644
--- a/server/services/messageAccounts.js
+++ b/server/services/messageAccounts.js
@@ -2,6 +2,7 @@ import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
const ACCOUNTS_FILE = join(PATHS.messages, 'accounts.json');
@@ -10,7 +11,7 @@ async function loadAccounts() {
const content = await tryReadFile(ACCOUNTS_FILE);
if (!content) return {};
const parsed = safeJSONParse(content, {}, { context: 'messageAccounts' });
- return (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
+ return isPlainObject(parsed) ? parsed : {};
}
async function saveAccounts(accounts) {
diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.js
index b3c63b093b..475235b919 100644
--- a/server/services/messagePlaywrightSync.js
+++ b/server/services/messagePlaywrightSync.js
@@ -3,6 +3,7 @@ import { join } from 'path';
import crypto from 'crypto';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';
// Compat re-exports — older consumers and test mocks import these from here
@@ -26,7 +27,7 @@ export async function getSelectors() {
const content = await tryReadFile(SELECTORS_FILE);
if (!content) return {};
const parsed = safeJSONParse(content, {}, { context: 'messageSelectors' });
- return (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) ? parsed : {};
+ return isPlainObject(parsed) ? parsed : {};
}
export async function updateSelectors(provider, selectors) {
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 9f08400385..8bd2545fe5 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -14,6 +14,7 @@ import { readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { randomUUID } from 'crypto';
import { safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
import { getSettings } from './settings.js';
const DEFAULT_ICLOUD_PATH = join(
@@ -117,7 +118,7 @@ export async function mlPatchProfileIfEnabled(patch) {
const current = (store.profile && typeof store.profile === 'object') ? store.profile : {};
const next = { ...current };
for (const [k, v] of Object.entries(patch)) {
- if (v && typeof v === 'object' && !Array.isArray(v) && current[k] && typeof current[k] === 'object') {
+ if (isPlainObject(v) && current[k] && typeof current[k] === 'object') {
next[k] = { ...current[k], ...v };
} else {
next[k] = v;
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 2726683339..d3e2d31e53 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -22,6 +22,7 @@ import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
+import { isPlainObject } from '../../lib/objects.js';
import {
LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,
CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,
@@ -670,7 +671,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
// to write" signal (e.g. stale media-job completion against a re-rendered
// page). Skip the disk write + emitRecordUpdated so it doesn't trigger
// a re-export storm in share subscriptions for late no-op events.
- if (patch && typeof patch === 'object' && !Array.isArray(patch) && Object.keys(patch).length === 0) {
+ if (isPlainObject(patch) && Object.keys(patch).length === 0) {
return { issue: cur, stage: currentStage };
}
const merged = {
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index dac7e25b1a..9c088e23fc 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -19,6 +19,7 @@ import { join, basename } from 'path';
import { copyFile, readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { PATHS, ensureDir, atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';
+import { isPlainObject } from '../../lib/objects.js';
import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, bucketBlobIndexPath, imageSidecarName, isHexHash } from './buckets.js';
import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';
import { listSeries, getSeries } from '../pipeline/series.js';
@@ -88,7 +89,7 @@ const ASSET_SOURCE_DIRS = Object.freeze({
*/
async function loadAssetHashCache(bucketPath) {
const raw = await readJSONFile(bucketBlobIndexPath(bucketPath), {}, { logError: false });
- return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw : {};
+ return isPlainObject(raw) ? raw : {};
}
// Per-bucket cache-write tail — serializes the re-load → merge → atomicWrite
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 5ef6040e38..96a9eac216 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -18,6 +18,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
import { DAY, ensureDir, HOUR, loadSlashdoFile, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
+import { isPlainObject } from '../lib/objects.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppTaskTypeOverrides } from './apps.js';
import { loadState, isImprovementEnabled } from './cosState.js';
@@ -1927,8 +1928,7 @@ export async function loadSchedule() {
// Only spread if loadedTask.taskMetadata is a plain object to avoid corrupting config
if (defaultTask.taskMetadata && loadedTask.taskMetadata !== null) {
const storedMeta = loadedTask.taskMetadata;
- const isPlainObject = storedMeta && typeof storedMeta === 'object' && !Array.isArray(storedMeta);
- merged.taskMetadata = { ...defaultTask.taskMetadata, ...(isPlainObject ? storedMeta : {}) };
+ merged.taskMetadata = { ...defaultTask.taskMetadata, ...(isPlainObject(storedMeta) ? storedMeta : {}) };
}
mergedTasks[taskType] = merged;
}
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index e9c477dd4f..4603e08184 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -32,6 +32,7 @@ import {
import { sanitizeBibleList, stripCanonControlFields, BIBLE_KIND, BIBLE_SOURCE } from "../lib/storyBible.js";
import { ServerError } from "../lib/errorHandler.js";
import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
+import { isPlainObject } from "../lib/objects.js";
import {
assertProvider,
resolveProviderAndModel,
@@ -235,7 +236,7 @@ const normalizeCategories = (raw) => {
// sanitizeCategory falls back to default. sanitizeCategory would clamp
// again, but doing it here also defends the Zod route schema which
// rejects unknown enum values on a subsequent save round-trip.
- const llmKind = node && typeof node === 'object' && !Array.isArray(node) ? node.kind : undefined;
+ const llmKind = isPlainObject(node) ? node.kind : undefined;
const rawKind = CATEGORY_KINDS.includes(llmKind) ? llmKind : undefined;
out[key] = {
...(rawKind !== undefined ? { kind: rawKind } : {}),
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index 8b2adabb7d..fb90f36bab 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -2,6 +2,7 @@ import { join } from 'path';
import { EventEmitter } from 'events';
import { readJSONFile, PATHS, ensureDir, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
+import { isPlainObject } from '../lib/objects.js';
import { execGh } from './github.js';
const UPDATE_FILE = join(PATHS.data, 'update.json');
@@ -90,7 +91,7 @@ async function loadState() {
await ensureDir(PATHS.data);
const raw = await readJSONFile(UPDATE_FILE, defaultState(), { allowArray: false });
const defaults = defaultState();
- const stateFromFile = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const stateFromFile = isPlainObject(raw) ? raw : {};
return {
...defaults,
...stateFromFile,