Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

chore(open-knowledge): shared timing/port/tmpdir helpers (#2736)

Andrew Mikofalvye44458ca7549
diff --git a/knip.config.ts b/knip.config.ts
index 16d637b4b..9633755a0 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -119,7 +119,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts'],
diff --git a/package.json b/package.json
index ac40c2db2..204c2f36f 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,8 @@
"check:desktop": "turbo run lint typecheck test --filter=@inkeep/open-knowledge-desktop",
"check:fast": "pnpm run typecheck",
"check:doc-links": "pnpm --dir docs run validate-link",
- "check:drift": "bash scripts/check-husky-prepare-guard.sh && bash scripts/check-knip-clean.sh && bash scripts/check-notices-clean.sh && bash scripts/check-schema-snapshot-clean.sh && bash scripts/check-i18n-drift.sh && bash scripts/check-no-major-changeset.sh && vitest run --config vitest.scripts.config.ts",
+ "check:drift": "pnpm run check:drift:guards && vitest run --config vitest.scripts.config.ts",
+ "check:drift:guards": "bash scripts/check-husky-prepare-guard.sh && bash scripts/check-knip-clean.sh && bash scripts/check-notices-clean.sh && bash scripts/check-schema-snapshot-clean.sh && bash scripts/check-i18n-drift.sh && bash scripts/check-no-major-changeset.sh",
"typecheck": "turbo run typecheck",
"test": "turbo run test",
"test:vitest-selftest": "vitest run",
@@ -26,7 +27,7 @@
"lint:oxlint": "oxlint --max-warnings 0 .",
"format": "pnpm run lint:biome --write --unsafe",
"check": "pnpm run lint && pnpm exec turbo run build typecheck test",
- "check:full:parallel": "bash scripts/check-husky-prepare-guard.sh && bash scripts/check-knip-clean.sh && bash scripts/check-notices-clean.sh && bash scripts/check-schema-snapshot-clean.sh && bash scripts/check-i18n-drift.sh && bash scripts/check-no-major-changeset.sh && pnpm run lint && pnpm run check:doc-links && vitest run --config vitest.scripts.config.ts && turbo run build typecheck test test:dom test:integration test:conversion test:perf:regression:unit test:health:unit test:health test:e2e test:visual test:perf test:a11y --concurrency=100% --output-logs=errors-only",
+ "check:full:parallel": "pnpm run check:drift:guards && pnpm run lint && pnpm run check:doc-links && vitest run --config vitest.scripts.config.ts && turbo run build typecheck test test:dom test:integration test:conversion test:perf:regression:unit test:health:unit test:health test:e2e test:visual test:perf test:a11y --concurrency=100% --output-logs=errors-only",
"tier1": "pnpm run check",
"tier2": "pnpm run tier1 && turbo run test:perf:regression:unit test:health:unit test:health test:e2e",
"tier3": "STRESS_FIDELITY=1 pnpm run tier2",
diff --git a/packages/app/tests/free-port.test-helper.ts b/packages/app/tests/free-port.test-helper.ts
new file mode 100644
index 000000000..42e61e473
--- /dev/null
+++ b/packages/app/tests/free-port.test-helper.ts
@@ -0,0 +1,30 @@
+import { type AddressInfo, createServer as createNetServer } from 'node:net';
+
+/**
+ * Pre-allocate a kernel-assigned free port on an explicit loopback family.
+ *
+ * Probe AND serve on the same explicit family. A bare `listen(0)`/`listen(port)`
+ * binds dual-stack `::`, which succeeds on the v6 side even when an unrelated
+ * long-lived process (an `ok ui` proxy, a dev server, a sibling parallel test
+ * task) already holds 127.0.0.1:<same port> — and clients dialing `localhost`
+ * coin-flip the address family, intermittently landing on the foreign v4
+ * listener (observed as a collab-server-not-running 503 hijacking a test rig).
+ * Probing and binding the same explicit family removes the race; callers must
+ * dial the same loopback literal, never an ambiguous `localhost` URL.
+ *
+ * `127.0.0.1:p` and `[::1]:p` are independent kernel slots, so a port verified
+ * free on one family carries no guarantee about the other — pass the family the
+ * caller will actually bind.
+ */
+export async function getFreePort(
+ loopbackHost: '127.0.0.1' | '::1' = '127.0.0.1',
+): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const s = createNetServer();
+ s.once('error', reject);
+ s.listen(0, loopbackHost, () => {
+ const port = (s.address() as AddressInfo).port;
+ s.close(() => resolve(port));
+ });
+ });
+}
diff --git a/packages/app/tests/free-port.test.ts b/packages/app/tests/free-port.test.ts
new file mode 100644
index 000000000..c3927fde4
--- /dev/null
+++ b/packages/app/tests/free-port.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, test } from 'vitest';
+import { getFreePort } from './free-port.test-helper.ts';
+
+describe('getFreePort', () => {
+ test('resolves a port in the valid range', async () => {
+ const port = await getFreePort();
+ expect(port).toBeGreaterThan(0);
+ expect(port).toBeLessThanOrEqual(65535);
+ });
+
+ test('resolves the requested loopback family without throwing', async () => {
+ // Exercises the explicit-family binding path; 127.0.0.1 is always present
+ // (::1 can be absent in IPv6-disabled CI, so it is not asserted here).
+ const port = await getFreePort('127.0.0.1');
+ expect(port).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.ts
index 51fbe360f..b802082c5 100644
--- a/packages/app/tests/integration/test-harness.ts
+++ b/packages/app/tests/integration/test-harness.ts
@@ -19,7 +19,7 @@
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { createServer as createHttpServer } from 'node:http';
-import { type AddressInfo, createServer as createNetServer, type Socket } from 'node:net';
+import { createServer as createNetServer, type Socket } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
@@ -66,6 +66,7 @@ import {
import type { ProviderPool } from '../../src/editor/provider-pool';
import { dispatchCC1Stateless, SYSTEM_DOC_NAME } from '../../src/lib/cc1';
import { createSyncedReconnectGate, refreshServerInfo } from '../../src/lib/server-info-refresh';
+import { getFreePort } from '../free-port.test-helper.ts';
import { ControllableWebSocket } from './network-control';
// ─── Shared instances (created once, reused across all tests) ───
@@ -84,28 +85,6 @@ export const schema = getSchema(sharedExtensions);
*/
export const HARNESS_BOOT_TIMEOUT_MS = 30_000;
-// ─── Port allocation ───
-
-// Probe AND serve on explicit v4 loopback. A bare `listen(0)`/`listen(port)`
-// binds dual-stack `::`, which succeeds on the v6 side even when an
-// unrelated long-lived process (an `ok ui` proxy, a dev server, a sibling
-// parallel test task) already holds 127.0.0.1:<same port> — and clients
-// dialing `localhost` coin-flip the address family, intermittently landing
-// on the foreign v4 listener (observed as a collab-server-not-running 503
-// hijacking a test rig; the same mechanism is a candidate explanation for
-// the passes-isolated/flakes-under-parallel-load integration class in CI).
-// Probing and binding the same explicit family removes the race; harness
-// URLs use 127.0.0.1 to match.
-async function getFreePort(): Promise<number> {
- return new Promise((resolve) => {
- const s = createNetServer();
- s.listen(0, '127.0.0.1', () => {
- const port = (s.address() as AddressInfo).port;
- s.close(() => resolve(port));
- });
- });
-}
-
// ─── Server factory ───
export interface TestServer {
diff --git a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
index 31c0f2c15..5277995b0 100644
--- a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
+++ b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
@@ -10,10 +10,10 @@
*/
import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { MarkdownManager, OK_DIR, sharedExtensions } from '@inkeep/open-knowledge-core';
+import { withTempDir } from '../../temp-dir.test-helper.ts';
import { generateFixture } from './generate-view-count-fixtures.ts';
interface PmJson {
@@ -57,10 +57,9 @@ function countNodeType(node: PmJson, type: string): number {
}
describe('generateFixture — convergence', () => {
- test('produces fixture with measured count within ±5% of target across the canonical buckets', () => {
+ test('produces fixture with measured count within ±5% of target across the canonical buckets', async () => {
const mgr = new MarkdownManager({ extensions: sharedExtensions });
- const tmp = mkdtempSync(resolve(tmpdir(), 'gen-fixtures-'));
- try {
+ await withTempDir('gen-fixtures-', (tmp) => {
for (const target of [25, 50, 100, 200, 400]) {
const outDir = resolve(tmp, `views-${target}`);
const result = generateFixture(target, outDir);
@@ -74,27 +73,21 @@ describe('generateFixture — convergence', () => {
// Sanity: convergence terminated with a real result.
expect(result.iterations).toBeGreaterThan(0);
}
- } finally {
- rmSync(tmp, { recursive: true, force: true });
- }
+ });
});
- test('writes both FIXTURE.md and .ok/config.yml', () => {
- const tmp = mkdtempSync(resolve(tmpdir(), 'gen-fixtures-shape-'));
- try {
+ test('writes both FIXTURE.md and .ok/config.yml', async () => {
+ await withTempDir('gen-fixtures-shape-', (tmp) => {
const outDir = resolve(tmp, 'shape-bucket');
generateFixture(50, outDir);
expect(existsSync(resolve(outDir, 'FIXTURE.md'))).toBe(true);
expect(existsSync(resolve(outDir, OK_DIR, 'config.yml'))).toBe(true);
- } finally {
- rmSync(tmp, { recursive: true, force: true });
- }
+ });
});
- test('mark mix is ~75% link / ~25% wikiLink (D11 ratio)', () => {
+ test('mark mix is ~75% link / ~25% wikiLink (D11 ratio)', async () => {
const mgr = new MarkdownManager({ extensions: sharedExtensions });
- const tmp = mkdtempSync(resolve(tmpdir(), 'gen-fixtures-mix-'));
- try {
+ await withTempDir('gen-fixtures-mix-', (tmp) => {
const outDir = resolve(tmp, 'mix-100');
generateFixture(100, outDir);
const md = readFileSync(resolve(outDir, 'FIXTURE.md'), 'utf8');
@@ -107,8 +100,6 @@ describe('generateFixture — convergence', () => {
const linkRatio = linkCount / total;
expect(linkRatio).toBeGreaterThanOrEqual(0.65);
expect(linkRatio).toBeLessThanOrEqual(0.85);
- } finally {
- rmSync(tmp, { recursive: true, force: true });
- }
+ });
});
});
diff --git a/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts b/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts
index 35a44f3d2..0cd23daa9 100644
--- a/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts
+++ b/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts
@@ -39,10 +39,10 @@
*/
import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { dirname, join, resolve } from 'node:path';
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { withTempDir } from '../../temp-dir.test-helper.ts';
import { computeLeakRateMbPerCycle } from '../lib/cell-measurement.ts';
import {
type ProbeOptions,
@@ -255,13 +255,12 @@ describe('tiptap-destroy-leak probe CLI shape', () => {
expect(computeLeakRateMbPerCycle([42])).toBe(0);
});
- test('writeProbeResults refuses --update-baseline on a degraded run', () => {
+ test('writeProbeResults refuses --update-baseline on a degraded run', async () => {
// A run where most cycles failed produces an empty cycleHeapsMb, which
// makes computeLeakRateMbPerCycle return 0. Writing that as a baseline
// labelled 'post-fix-W14' would silently mask future regressions of
// 5+ MB/cycle. The gate refuses if observedCycles/cycles < 0.5.
- const outDir = mkdtempSync(join(tmpdir(), 'tiptap-leak-baseline-degraded-'));
- try {
+ await withTempDir('tiptap-leak-baseline-degraded-', (outDir) => {
const degraded: ProbeResult = {
schemaVersion: 1,
measuredAt: new Date().toISOString(),
@@ -280,14 +279,11 @@ describe('tiptap-destroy-leak probe CLI shape', () => {
// Refused baselines must not leave a baseline.json on disk — the
// engineer sees the error AND the absence of a stale baseline.
expect(existsSync(resolve(outDir, 'tiptap-leak-probe-baseline.json'))).toBe(false);
- } finally {
- rmSync(outDir, { recursive: true, force: true });
- }
+ });
});
- test('writeProbeResults accepts --update-baseline at >=50% success rate', () => {
- const outDir = mkdtempSync(join(tmpdir(), 'tiptap-leak-baseline-ok-'));
- try {
+ test('writeProbeResults accepts --update-baseline at >=50% success rate', async () => {
+ await withTempDir('tiptap-leak-baseline-ok-', (outDir) => {
const cycleHeaps = [100, 102, 104, 106, 108]; // 5 of 10 cycles ⇒ 50%
const ok: ProbeResult = {
schemaVersion: 1,
@@ -313,9 +309,7 @@ describe('tiptap-destroy-leak probe CLI shape', () => {
};
expect(baseline.observedCycles).toBe(5);
expect(baseline.successRate).toBe(0.5);
- } finally {
- rmSync(outDir, { recursive: true, force: true });
- }
+ });
});
test('ProbeOptions + ProbeResult types are exported (compile-time check)', () => {
diff --git a/packages/app/tests/stress/_helpers/fixtures.ts b/packages/app/tests/stress/_helpers/fixtures.ts
index 4a69bf772..d9da475b9 100644
--- a/packages/app/tests/stress/_helpers/fixtures.ts
+++ b/packages/app/tests/stress/_helpers/fixtures.ts
@@ -14,8 +14,9 @@
* fixtures using `get-port` + `cross-spawn` (no precedent for per-worker
* among Hocuspocus consumers — this migration is a new position).
* - Port allocation: kernel-assigned random port via `net.createServer(0)`
- * (collision-free; matches the Tier 1 integration harness's
- * `getFreePort()` primitive at `packages/app/tests/integration/test-harness.ts:62-70`).
+ * (collision-free; the shared `getFreePort()` primitive at
+ * `packages/app/tests/free-port.test-helper.ts`, also used by the Tier 1
+ * integration harness).
* - Content dir: `mkdtempSync` keyed by `workerInfo.workerIndex` so each
* worker gets its own filesystem; pre-seeds `test-doc.md` +
* `sidebar-folder/nested-doc.md` which `reveal-on-activate.e2e.ts`
diff --git a/packages/app/tests/stress/_helpers/server-process.ts b/packages/app/tests/stress/_helpers/server-process.ts
index 366be21fb..27ec21f33 100644
--- a/packages/app/tests/stress/_helpers/server-process.ts
+++ b/packages/app/tests/stress/_helpers/server-process.ts
@@ -25,7 +25,6 @@ import {
openSync,
readFileSync,
} from 'node:fs';
-import { type AddressInfo, createServer as createNetServer } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
@@ -169,23 +168,7 @@ export async function checkCollabSync(
}
}
-/**
- * Probe the SAME loopback family the caller will bind: `127.0.0.1:p` and
- * `[::1]:p` are independent kernel slots, so a port verified free on one
- * family carries no guarantee about the other.
- */
-export async function getFreePort(
- loopbackHost: '127.0.0.1' | '::1' = '127.0.0.1',
-): Promise<number> {
- return new Promise((resolve, reject) => {
- const s = createNetServer();
- s.once('error', reject);
- s.listen(0, loopbackHost === '::1' ? '::1' : '127.0.0.1', () => {
- const port = (s.address() as AddressInfo).port;
- s.close(() => resolve(port));
- });
- });
-}
+export { getFreePort } from '../../free-port.test-helper.ts';
export async function waitForHttpReady(baseURL: string, timeoutMs: number): Promise<void> {
const start = Date.now();
diff --git a/packages/app/tests/temp-dir.test-helper.ts b/packages/app/tests/temp-dir.test-helper.ts
new file mode 100644
index 000000000..94d715566
--- /dev/null
+++ b/packages/app/tests/temp-dir.test-helper.ts
@@ -0,0 +1,25 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+/**
+ * Run `fn` with a fresh `mkdtemp` directory under the OS tmpdir, removing it
+ * (recursive, force) when `fn` settles — including on throw, so a failing
+ * assertion never leaks the directory.
+ *
+ * Note: the returned path is NOT realpath'd — on macOS `/var` is a symlink to
+ * `/private/var`, so callers comparing against canonicalized paths should
+ * `realpath` the directory themselves (matching the existing
+ * `realpathSync(mkdtempSync(...))` idiom).
+ */
+export async function withTempDir<T>(
+ prefix: string,
+ fn: (dir: string) => T | Promise<T>,
+): Promise<T> {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ try {
+ return await fn(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
diff --git a/packages/app/tests/temp-dir.test.ts b/packages/app/tests/temp-dir.test.ts
new file mode 100644
index 000000000..93efbea85
--- /dev/null
+++ b/packages/app/tests/temp-dir.test.ts
@@ -0,0 +1,34 @@
+import { existsSync } from 'node:fs';
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { withTempDir } from './temp-dir.test-helper.ts';
+
+describe('withTempDir', () => {
+ test('provides a usable dir, returns fn result, and removes the dir after', async () => {
+ let captured = '';
+ const result = await withTempDir('temp-dir-test-', async (dir) => {
+ captured = dir;
+ expect(existsSync(dir)).toBe(true);
+ await writeFile(join(dir, 'f.txt'), 'x');
+ return 42;
+ });
+ expect(result).toBe(42);
+ expect(captured).not.toBe('');
+ expect(existsSync(captured)).toBe(false);
+ });
+
+ test('removes the directory even when fn throws', async () => {
+ // Cleanup-on-throw is the helper's entire raison d'être: a failing
+ // assertion inside the callback must not leak the tmp dir.
+ let captured = '';
+ await expect(
+ withTempDir('temp-dir-test-', (dir) => {
+ captured = dir;
+ throw new Error('boom');
+ }),
+ ).rejects.toThrow('boom');
+ expect(captured).not.toBe('');
+ expect(existsSync(captured)).toBe(false);
+ });
+});
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index c014b1413..8f9d95287 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8890f6739..c18c086d5 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 3ab9cc6ef..3c927eb47 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -38,6 +38,7 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: string
return parts.join('\n');
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 4b8890476..3f0880aa5 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 754dc5cc2..0be5203e4 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 666c3e892..8dcdcde9e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1369,6 +1369,7 @@ export {
export { type BasenameIndex, createBasenameIndex } from './utils/path-resolve.ts';
export { type ResolvedInternalHref, resolveInternalHref } from './utils/resolve-internal-href.ts';
export { sanitizeFolderName } from './utils/sanitize-folder-name.ts';
+export { sleep } from './utils/sleep.ts';
export {
disambiguateSlug,
getHeadingSlug,
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 193e286b0..47f0d07e4 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index c7518d614..fb5ac8e8a 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index f55912407..6319f264f 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 78fdfeb02..2f082e6d0 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Root as HastRoot } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -75,7 +76,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 8b36807fd..fc30bda02 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -196,6 +197,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -244,6 +246,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -263,6 +266,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -331,6 +335,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -577,6 +582,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -657,6 +663,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -935,6 +942,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1060,6 +1068,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index e78a1381d..207cd95c2 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -29,6 +29,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index d1a5ab4dc..3baacdeb7 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 1cd40ef3a..65a1b564c 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';
@@ -8,6 +9,7 @@ import {
type MarkdownlintSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 617f6e5b9..3651bd7eb 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
export const LINT_PLUGIN_IDS = ['markdownlint'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -41,6 +42,7 @@ export interface MarkdownlintSlice {
rules: Record<string, MarkdownlintRuleSetting>;
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index 679c72ef7..f84967798 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 9864b3b60..7e4a9a48b 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 7f2d5adca..e9e507469 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 5a5e4c42a..f8f5e8530 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 46cc6a074..542204403 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index be97d4d62..fe73659e6 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 8f4e9a41c..7bce04302 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index cd245c38c..c5bfd2386 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/core/src/util/file-lock.ts b/packages/core/src/util/file-lock.ts
index 30252da54..6d4835cfa 100644
--- a/packages/core/src/util/file-lock.ts
+++ b/packages/core/src/util/file-lock.ts
@@ -22,6 +22,7 @@
*/
import { closeSync, openSync, statSync, unlinkSync } from 'node:fs';
+import { sleep } from '../utils/sleep.ts';
export interface WithFileLockOptions {
/** Total acquire-retry budget. Default 5_000ms. */
@@ -48,11 +49,6 @@ export class FileLockTimeoutError extends Error {
}
}
-const sleep = (ms: number): Promise<void> =>
- new Promise((resolve) => {
- setTimeout(resolve, ms);
- });
-
/**
* Acquire `lockPath`, run `fn`, release. The lockfile is unlinked on
* release (best-effort — cleanup never throws). On acquire timeout, throws
diff --git a/packages/core/src/utils/sleep.test.ts b/packages/core/src/utils/sleep.test.ts
new file mode 100644
index 000000000..fa2ab9174
--- /dev/null
+++ b/packages/core/src/utils/sleep.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'vitest';
+import { sleep } from './sleep.ts';
+
+describe('sleep', () => {
+ test('resolves to undefined after the given delay', async () => {
+ const start = Date.now();
+ await expect(sleep(20)).resolves.toBeUndefined();
+ // Timers can fire marginally early across runtimes; assert ~80% of nominal
+ // rather than exact elapsed time to stay flakiness-safe while still catching
+ // a halved-delay regression (e.g. `setTimeout(resolve, ms / 2)`).
+ expect(Date.now() - start).toBeGreaterThanOrEqual(16);
+ });
+
+ test('sleep(0) yields asynchronously (does not resolve synchronously)', async () => {
+ let resolved = false;
+ const p = sleep(0).then(() => {
+ resolved = true;
+ });
+ expect(resolved).toBe(false);
+ await p;
+ expect(resolved).toBe(true);
+ });
+});
diff --git a/packages/core/src/utils/sleep.ts b/packages/core/src/utils/sleep.ts
new file mode 100644
index 000000000..fb2bd5a4e
--- /dev/null
+++ b/packages/core/src/utils/sleep.ts
@@ -0,0 +1,11 @@
+/**
+ * Resolve after `ms` milliseconds. Uses the global `setTimeout` (not
+ * `node:timers/promises`) so it stays importable from browser bundles —
+ * this module is exported via the core main barrel, which must remain
+ * browser-safe.
+ */
+export function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+}
diff --git a/packages/desktop/src/main/terminal-consent.ts b/packages/desktop/src/main/terminal-consent.ts
index c27ffb265..47064cd9c 100644
--- a/packages/desktop/src/main/terminal-consent.ts
+++ b/packages/desktop/src/main/terminal-consent.ts
@@ -22,6 +22,7 @@
*/
import { existsSync, readFileSync } from 'node:fs';
+import { sleep } from '@inkeep/open-knowledge-core';
import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
import { parse as parseYaml } from 'yaml';
import { getLogger } from './desktop-logger.ts';
@@ -57,8 +58,6 @@ export function isTerminalConsented(projectDir: string): boolean {
return terminal.enabled !== false;
}
-const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
-
/**
* Default grace budget for {@link isTerminalConsentedWithGrace}.
*
diff --git a/packages/server/src/embeddings/embedder.ts b/packages/server/src/embeddings/embedder.ts
index 3f500a43b..9bdf9e224 100644
--- a/packages/server/src/embeddings/embedder.ts
+++ b/packages/server/src/embeddings/embedder.ts
@@ -16,7 +16,7 @@
* zero egress. A null return means "no key → degrade to lexical search".
*/
-import { checkEmbeddingsBaseUrl } from '@inkeep/open-knowledge-core';
+import { checkEmbeddingsBaseUrl, sleep as defaultSleep } from '@inkeep/open-knowledge-core';
import {
type EmbeddingErrorReason,
recordEmbeddingProviderError,
@@ -211,10 +211,6 @@ function assertSafeEmbeddingsBaseUrl(baseUrl: string): void {
const RETRYABLE_STATUS = new Set([408, 409, 429, 500, 502, 503, 504]);
-function defaultSleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
/**
* Build the OpenAI-compatible embedder. Pure construction — makes NO network
* call, so it is safe to build at warm time (zero egress until an actual
diff --git a/packages/server/src/ensure-single-file-session.ts b/packages/server/src/ensure-single-file-session.ts
index 277342d6b..9ba8a1001 100644
--- a/packages/server/src/ensure-single-file-session.ts
+++ b/packages/server/src/ensure-single-file-session.ts
@@ -23,6 +23,7 @@ import { type SpawnOptions, spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import { realpath as fsRealpath } from 'node:fs/promises';
import { resolve } from 'node:path';
+import { sleep as defaultSleep } from '@inkeep/open-knowledge-core';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
import { isSupportedDocFile } from './doc-extensions.ts';
import { createOffCwdResolverDeps, resolveOffCwdTarget } from './off-cwd-resolver.ts';
@@ -73,7 +74,7 @@ export function ensureSingleFileSession(
absFile: string,
deps: EnsureSingleFileDeps,
): Promise<boolean> {
- const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const sleep = deps.sleep ?? defaultSleep;
const now = deps.now ?? (() => Date.now());
const pollMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
diff --git a/packages/server/src/handoff-dispatch-api.ts b/packages/server/src/handoff-dispatch-api.ts
index 2abb33653..f4e4ae799 100644
--- a/packages/server/src/handoff-dispatch-api.ts
+++ b/packages/server/src/handoff-dispatch-api.ts
@@ -55,7 +55,7 @@
*/
import type { IncomingMessage, ServerResponse } from 'node:http';
-import type { HandoffTarget } from '@inkeep/open-knowledge-core';
+import { sleep as defaultSleep, type HandoffTarget } from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { createOsProbe, type InstalledAgentScheme } from './handoff-api.ts';
import { errorResponse } from './http/error-response.ts';
@@ -203,10 +203,6 @@ export interface HandleHandoffDispatchDeps {
*/
export type { SpawnDetachedOutcome as SpawnOutcome } from './spawn-detached.ts';
-function defaultSleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
export async function handleHandoffDispatch(
req: IncomingMessage,
res: ServerResponse,