mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Paperclip tasks and comments now store channel, key-value, claim lease, profile attribution, and structured schema fields on existing issue and comment tables (`channelId`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `createdByProfile`, `actorProfile`, and claim lease fields). > - Existing board task views (`IssueProperties`, `MarkdownBody`, `CommentThread`, `IssueChatThread`, and `IssueDetail`) do not yet display these fields, and canonical `/api/issues/:id` routes do not resolve `channelPath` or strip `claimTokenHash` at serialization time. > - Users and reviewers cannot see channel provenance, key-values, active or expired claim leases, `--as <profile>` attribution, or structured `schema=<name>@<version>` blocks when they open a task in the UI. > - This pull request synchronizes the shared `Issue` and `IssueComment` contracts, resolves `channelPath` only when channel access and actor scopes allow it, strips `claimTokenHash` from issue responses, renders channel, key-values, lease, result schema, and structured schema cards across existing task views (only when set), and adds production-component Storybooks. > - The benefit is that existing task surfaces show channel, lease, key-value, profile, and schema state cleanly in place without cluttering standard tasks or adding a separate Channels navigation item, while preserving secret isolation on claim tokens. ## Linked Issues or Issue Description Refs #23329 Refs #23330 **What existing behavior does this improve?** Existing task detail, properties, Markdown body, comment thread, chat thread, and `/api/issues` HTTP serialization for tasks that carry channel, claim lease, key-value, profile attribution, or structured schema data. **Subsystem affected** Cross-cutting (`packages/shared`, `server/`, `ui/`, `ui/storybook/`, and `docs/api/`) **Current behavior** Canonical `/api/issues` routes return raw issue columns without a resolved `channelPath` and include `claimTokenHash: null` on the response shape. In `ui/`, `IssueProperties` omits channel provenance, `Key-values` editing, claim lease status, `resultSchemaRef` verification, and `--as <profile>` creator attribution. `MarkdownBody` renders ```` ```json schema=<name>@<version> ```` blocks only as plain code blocks, and comment threads show `local-board` or generic user labels instead of `actorProfile` and omit comment-level key-values. **Proposed behavior** `Issue` and `IssueComment` expose safe coordination and schema fields in `@paperclipai/shared`. Server issue routes strip `claimTokenHash` from serialized issue objects and resolve `channelPath` in batch via `findInaccessibleChannelIds` only when actor scopes and channel membership succeed (with zero extra SQL queries when `channelId` is null). `IssueProperties` mounts cohesive task property rows (`structured-task-rows.tsx`) strictly when set: `#<channelPath>` badge on `Channel`, inline `Key-values` add/edit/remove with CAS preconditions (`PATCH /api/issues/:id/kv-labels`), active vs expired `Lease` status with inline status dot and live countdown, `Result schema` matching status, and creator `--as <profile>` attribution. `MarkdownBody` and task discussion/chat threads render token-styled `SchemaBlockCard` views (`finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and custom `<name>@<version>` schemas) with a `Structured` / `JSON` toggle, deduplicated standalone `schemaBlocks`, `--as <actorProfile>` attribution, and comment key-value pills. Four production-component Storybooks document these states under `tasks-channels-leases-and-schemas`. **Reason and benefit** Agents and CLI workflows coordinate through existing Paperclip tasks and comments. Surfacing channel provenance, claim leases, key-values, profile attribution, and typed schema blocks directly on existing task views (and hiding those rows completely when unset) lets people inspect and edit structured task state in place without introducing new top-level navigation, while guaranteeing that `claimTokenHash` never leaves the server. **Breaking changes** None for external callers. `claimTokenHash` is omitted from serialized `/api/issues` JSON responses as a security invariant, and `channelPath` (`string | null`) is added on canonical issue read and update responses. ## What Changed - `packages/shared/src/types/issue.ts` and `tests/runner-e2e/source-sdk-public-inputs.json`: expose safe fields on `Issue` (`channelId`, `channelPath`, `createdByProfile`, `kvLabels`, `schemaBlocks`, `resultSchemaRef`, `claimEpoch`, `claimHolderAgentId`, `claimHolderUserId`, `claimHolderProfile`, `claimLeasedAt`, `claimLeaseExpiresAt`, `claimAttemptCount`) and `IssueComment` (`actorProfile`, `kvLabels`, `schemaBlocks`), never `claimTokenHash`, and synchronize the SDK public input registry pin. - `server/src/services/issues.ts`, `server/src/routes/issues.ts`, and `docs/api/issues.md`: omit `claim_token_hash` from SQL issue selections and `withIssueLabels`, strip `claimTokenHash` on HTTP serialization across issue routes, clear `kvLabels` and `schemaBlocks` on tombstoned comments, resolve `channelPath` in batch via `resolveHeadlessActor` and `findInaccessibleChannelIds` (zero extra SQL queries when `channelId` is `null`), and document the API response contract. - `server/src/__tests__/fixtures/issue-detail-response.json`, `server/src/__tests__/issue-activity-events-routes.test.ts`, and `server/src/__tests__/headless-channels-schemas-batch.test.ts`: update issue detail and update response snapshots (`channelPath: null`, no `claimTokenHash`) and add route contract coverage for `channelPath` visibility, scope enforcement, comment fields, and `claimTokenHash` omission. - `ui/src/api/issues.ts` and `ui/src/api/issues.test.ts`: add `issuesApi.updateKvLabels` targeting `PATCH /api/issues/:id/kv-labels` with CAS precondition normalization (`set`, `unset`, `if`) and unit test coverage. - `ui/src/components/issue-properties/structured-task-rows.tsx` and `IssueProperties.tsx`: add `IssueChannelRow`, `IssueKvLabelsRow` (`Key-values` with inline edit, remove, `+ Add`, CAS preconditions, touch-safe 16px inputs, and complete omission when empty), `IssueClaimLeaseRow` (inline status dot, live countdown, and omission when unset or released), `IssueResultSchemaRow` (unwrapping `InfiniteData` and identifier-keyed comment query caches, plus distinguishing `"unverified"` truncated scans from `"missing"`), and `IssueProfileAttributionRow`. - `ui/src/components/SchemaBlockCard.tsx`, `ui/src/lib/schema-block-utils.ts`, and `ui/src/components/MarkdownBody.tsx`: parse ```` ```json schema=<name>@<version> ```` fences (plus `{ schema, data }` JSON envelopes) via a static remark plugin and a bounded linear $O(N)$ single-pass CommonMark fence scanner (no multi-line backtracking regexes); render semantic-token cards for `finding@1`, `test-report@1`, `git-commit@1`, `pull-request@1`, and custom `<name>@<version>` blocks with `Structured` / `JSON` toggle, `https://`-only link safety, malformed-JSON code-block fallback, and iterative stack-safe `schemaBlocks` deduplication. - `ui/src/components/CommentStructuredMeta.tsx`, `CommentThread.tsx`, `IssueChatThread.tsx`, `TaskChatBubble.tsx`, `TaskChatDescriptionBubble.tsx`, `IssueDetail.tsx`, and chat adapters: render `--as <actorProfile>` attribution, comment-level key-value chips, and unfenced `schemaBlocks` across classic and chat task threads. - `ui/storybook/stories/tasks/channels-leases-and-schemas.stories.tsx`: add `ChannelTaskPropertiesActiveLease`, `ExpiredLeaseProperties`, `BuiltInAndCustomSchemaBlocks`, and `ChannelTaskThreadEndToEnd` stories registered under `tasks-channels-leases-and-schemas`. - `ui/src/components/issue-properties/structured-task-rows.test.tsx` and `ui/src/components/SchemaBlockCard.test.tsx`: add unit tests covering unset-row omission on standard tasks, single-badge channel provenance, CAS key-value mutations and `409` conflict rollback, inline lease status dots and countdown expiry, `InfiniteData` comment unwrapping, structured schema cards, malformed JSON fallback, linear $O(N)$ scanning on 5,000 unterminated JSON fences, newline-clamped markdown bounds, and deep deduplication. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `cd server && node scripts/typecheck-layers.mjs` — passed (0 errors across all layers and test trees). - `cd server && npx vitest run src/__tests__/service-read-disconnect-retry.test.ts src/__tests__/issue-activity-events-routes.test.ts src/__tests__/issue-detail-statements.test.ts src/__tests__/headless-channels-schemas-batch.test.ts` — passed (54/54 tests). - `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors). - `cd ui && npx vitest run src/components/issue-properties/structured-task-rows.test.tsx src/components/SchemaBlockCard.test.tsx src/api/issues.test.ts src/lib/issue-chat-messages.test.ts src/components/task-chat/task-chat-adapter.test.ts` — passed (115/115 tests). - `node scripts/check-token-gates.mjs`, `node scripts/check-test-budget.mjs`, `node scripts/check-module-boundaries.mjs`, and `node scripts/check-query-error-rendering.mjs` — all passed. - `node scripts/storybook-catalog.mjs && node scripts/storybook-catalog.mjs --check` and `node --test scripts/check-maps.test.mjs scripts/storybook-catalog.test.mjs scripts/storybook-feature-index.test.mjs` — passed (30/30 tests). - `pnpm --filter @paperclipai/ui build-storybook` — passed and verified built story IDs (`tasks-channels-leases-and-schemas--channel-task-properties-active-lease`, `tasks-channels-leases-and-schemas--expired-lease-properties`, `tasks-channels-leases-and-schemas--built-in-and-custom-schema-blocks`, `tasks-channels-leases-and-schemas--channel-task-thread-end-to-end`). ## Risks - Low risk. Standard board tasks with unset `Channel`, `Key-values`, `Lease`, and `Result schema` omit all four property rows completely, preserving existing `IssueProperties` layout and SQL query count (`0` extra queries when `channelId` is `null`). - Fenced code blocks without `schema=<name>@<version>` metadata (or with invalid JSON) fall back directly to the existing `CodeBlock` renderer. ## Model Used - Google Gemini (`gemini-3.1-pro` / Antigravity agentic coding runtime with extended thinking, code search, file editing, and terminal verification tools). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
506 lines
15 KiB
TypeScript
506 lines
15 KiB
TypeScript
import {
|
|
SCHEMA_REF_REGEX,
|
|
parseSchemaRef,
|
|
type ParsedSchemaRef,
|
|
type SchemaBlock,
|
|
} from "@paperclipai/shared";
|
|
|
|
export const EMPTY_SCHEMA_BLOCKS: readonly SchemaBlock[] = [];
|
|
|
|
const MAX_SCANNED_MARKDOWN_CHARS = 512 * 1024;
|
|
const MAX_SCHEMA_FENCE_BODY_CHARS = 64 * 1024;
|
|
const MAX_SCANNED_JSON_FENCES = 64;
|
|
const MAX_FENCE_META_CHARS = 256;
|
|
|
|
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
type CanonicalStackItem =
|
|
| { kind: "token"; text: string }
|
|
| { kind: "exit"; ref: object }
|
|
| { kind: "value"; value: unknown };
|
|
|
|
/**
|
|
* Iteratively serializes arbitrary JSON-like values with sorted object keys
|
|
* using an explicit heap stack so deeply nested payloads neither overflow the
|
|
* call stack nor collide under depth truncation.
|
|
*/
|
|
function serializeCanonicalJson(root: unknown): string {
|
|
const parts: string[] = [];
|
|
const activeAncestors = new Set<object>();
|
|
const stack: CanonicalStackItem[] = [{ kind: "value", value: root }];
|
|
|
|
while (stack.length > 0) {
|
|
const current = stack.pop()!;
|
|
if (current.kind === "token") {
|
|
parts.push(current.text);
|
|
continue;
|
|
}
|
|
if (current.kind === "exit") {
|
|
activeAncestors.delete(current.ref);
|
|
continue;
|
|
}
|
|
|
|
const value = current.value;
|
|
if (value === null || value === undefined) {
|
|
parts.push("null");
|
|
continue;
|
|
}
|
|
if (typeof value === "boolean" || typeof value === "number") {
|
|
parts.push(
|
|
Number.isFinite(value as number) || typeof value === "boolean"
|
|
? String(value)
|
|
: "null",
|
|
);
|
|
continue;
|
|
}
|
|
if (typeof value === "string") {
|
|
parts.push(JSON.stringify(value));
|
|
continue;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
if (activeAncestors.has(value)) {
|
|
parts.push('"[Circular]"');
|
|
continue;
|
|
}
|
|
if (value.length === 0) {
|
|
parts.push("[]");
|
|
continue;
|
|
}
|
|
activeAncestors.add(value);
|
|
stack.push({ kind: "exit", ref: value });
|
|
stack.push({ kind: "token", text: "]" });
|
|
for (let idx = value.length - 1; idx >= 0; idx -= 1) {
|
|
stack.push({ kind: "value", value: value[idx] });
|
|
if (idx > 0) {
|
|
stack.push({ kind: "token", text: "," });
|
|
}
|
|
}
|
|
stack.push({ kind: "token", text: "[" });
|
|
continue;
|
|
}
|
|
if (isPlainRecord(value)) {
|
|
if (activeAncestors.has(value)) {
|
|
parts.push('"[Circular]"');
|
|
continue;
|
|
}
|
|
const keys = Object.keys(value)
|
|
.filter((key) => value[key] !== undefined)
|
|
.sort();
|
|
if (keys.length === 0) {
|
|
parts.push("{}");
|
|
continue;
|
|
}
|
|
activeAncestors.add(value);
|
|
stack.push({ kind: "exit", ref: value });
|
|
stack.push({ kind: "token", text: "}" });
|
|
for (let idx = keys.length - 1; idx >= 0; idx -= 1) {
|
|
const key = keys[idx]!;
|
|
stack.push({ kind: "value", value: value[key] });
|
|
stack.push({ kind: "token", text: `${JSON.stringify(key)}:` });
|
|
if (idx > 0) {
|
|
stack.push({ kind: "token", text: "," });
|
|
}
|
|
}
|
|
stack.push({ kind: "token", text: "{" });
|
|
continue;
|
|
}
|
|
parts.push(JSON.stringify(String(value)));
|
|
}
|
|
|
|
return parts.join("");
|
|
}
|
|
|
|
export function canonicalSchemaBlockKey(block: SchemaBlock): string {
|
|
return `${block.schema.toLowerCase()}@${block.version}:${serializeCanonicalJson(block.data)}`;
|
|
}
|
|
|
|
function isHorizontalSpace(code: number): boolean {
|
|
return code === 32 || code === 9;
|
|
}
|
|
|
|
export function parseSchemaFenceMeta(meta: string | null | undefined): ParsedSchemaRef | null {
|
|
if (!meta || meta.length > MAX_FENCE_META_CHARS) return null;
|
|
let idx = 0;
|
|
const len = meta.length;
|
|
while (idx < len) {
|
|
while (idx < len && isHorizontalSpace(meta.charCodeAt(idx))) {
|
|
idx += 1;
|
|
}
|
|
if (idx >= len) break;
|
|
let tokenEnd = idx;
|
|
while (tokenEnd < len && !isHorizontalSpace(meta.charCodeAt(tokenEnd))) {
|
|
tokenEnd += 1;
|
|
}
|
|
const token = meta.slice(idx, tokenEnd);
|
|
idx = tokenEnd;
|
|
if (token.length > 7 && token.slice(0, 7).toLowerCase() === "schema=") {
|
|
const candidate = token.slice(7).toLowerCase();
|
|
if (!SCHEMA_REF_REGEX.test(candidate)) return null;
|
|
try {
|
|
return parseSchemaRef(candidate);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export interface ParsedFencedSchemaBlock {
|
|
block: SchemaBlock;
|
|
rawJson: string;
|
|
}
|
|
|
|
/**
|
|
* Parses a JSON code-fence payload into a `SchemaBlock` when valid.
|
|
*
|
|
* Supports:
|
|
* 1. Explicit fence metadata (` ```json schema=<name>@<version> `) with raw `data` object
|
|
* (or `{ schema, data }` envelope).
|
|
* 2. Envelope JSON (` ```json\n{ "schema": "<name>@<version>", "data": { ... } }\n``` `)
|
|
* emitted by `formatBlocksAsFencedJson`.
|
|
*
|
|
* Returns `null` when JSON is malformed, oversized, or not a schema object so callers
|
|
* fall back cleanly to standard code block rendering.
|
|
*/
|
|
export function parseJsonSchemaBlock(
|
|
rawCode: string,
|
|
explicitRef?: string | null,
|
|
): ParsedFencedSchemaBlock | null {
|
|
if (rawCode.length > MAX_SCHEMA_FENCE_BODY_CHARS) return null;
|
|
const trimmed = rawCode.trim();
|
|
if (!trimmed.startsWith("{")) return null;
|
|
|
|
let parsedRef: ParsedSchemaRef | null = null;
|
|
if (explicitRef) {
|
|
try {
|
|
parsedRef = parseSchemaRef(explicitRef.toLowerCase());
|
|
} catch {
|
|
return null;
|
|
}
|
|
} else if (!trimmed.includes('"schema"') || !trimmed.includes('"data"')) {
|
|
return null;
|
|
}
|
|
|
|
let parsedJson: unknown;
|
|
try {
|
|
parsedJson = JSON.parse(trimmed);
|
|
} catch {
|
|
return null;
|
|
}
|
|
|
|
if (!isPlainRecord(parsedJson)) return null;
|
|
|
|
if (parsedRef) {
|
|
const keys = Object.keys(parsedJson);
|
|
const isWrappedEnvelope =
|
|
keys.length === 2 &&
|
|
typeof parsedJson.schema === "string" &&
|
|
parsedJson.schema.trim().toLowerCase() === parsedRef.ref &&
|
|
isPlainRecord(parsedJson.data);
|
|
const data = isWrappedEnvelope ? (parsedJson.data as Record<string, unknown>) : parsedJson;
|
|
return {
|
|
block: {
|
|
schema: parsedRef.name,
|
|
version: parsedRef.version,
|
|
data,
|
|
},
|
|
rawJson: JSON.stringify(data, null, 2),
|
|
};
|
|
}
|
|
|
|
const keys = Object.keys(parsedJson);
|
|
if (
|
|
keys.length !== 2 ||
|
|
typeof parsedJson.schema !== "string" ||
|
|
!SCHEMA_REF_REGEX.test(parsedJson.schema.trim().toLowerCase()) ||
|
|
!isPlainRecord(parsedJson.data)
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const envelopeRef = parseSchemaRef(parsedJson.schema.trim().toLowerCase());
|
|
return {
|
|
block: {
|
|
schema: envelopeRef.name,
|
|
version: envelopeRef.version,
|
|
data: parsedJson.data,
|
|
},
|
|
rawJson: JSON.stringify(parsedJson.data, null, 2),
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
interface OpenMarkdownFence {
|
|
markerCode: number;
|
|
markerLen: number;
|
|
isJson: boolean;
|
|
meta: string | null;
|
|
bodyStart: number;
|
|
}
|
|
|
|
function matchFenceOpening(
|
|
markdown: string,
|
|
lineStart: number,
|
|
lineEnd: number,
|
|
bodyStart: number,
|
|
): OpenMarkdownFence | null {
|
|
let pos = lineStart;
|
|
while (pos < lineEnd && pos - lineStart < 3 && markdown.charCodeAt(pos) === 32) {
|
|
pos += 1;
|
|
}
|
|
if (pos >= lineEnd) return null;
|
|
|
|
const markerCode = markdown.charCodeAt(pos);
|
|
if (markerCode !== 96 && markerCode !== 126) return null;
|
|
|
|
let markerEnd = pos;
|
|
while (markerEnd < lineEnd && markdown.charCodeAt(markerEnd) === markerCode) {
|
|
markerEnd += 1;
|
|
}
|
|
const markerLen = markerEnd - pos;
|
|
if (markerLen < 3) return null;
|
|
|
|
// CommonMark: backtick fence info strings cannot contain backticks.
|
|
if (markerCode === 96) {
|
|
for (let idx = markerEnd; idx < lineEnd; idx += 1) {
|
|
if (markdown.charCodeAt(idx) === 96) return null;
|
|
}
|
|
}
|
|
|
|
let infoStart = markerEnd;
|
|
while (infoStart < lineEnd && isHorizontalSpace(markdown.charCodeAt(infoStart))) {
|
|
infoStart += 1;
|
|
}
|
|
|
|
let langEnd = infoStart;
|
|
while (langEnd < lineEnd && !isHorizontalSpace(markdown.charCodeAt(langEnd))) {
|
|
langEnd += 1;
|
|
}
|
|
const lang = markdown.slice(infoStart, langEnd).toLowerCase();
|
|
const isJson = lang === "json";
|
|
|
|
let meta: string | null = null;
|
|
if (isJson && langEnd < lineEnd) {
|
|
const rest = markdown.slice(langEnd, lineEnd).trim();
|
|
if (rest.length > 0 && rest.length <= MAX_FENCE_META_CHARS) {
|
|
meta = rest;
|
|
}
|
|
}
|
|
|
|
return {
|
|
markerCode,
|
|
markerLen,
|
|
isJson,
|
|
meta,
|
|
bodyStart,
|
|
};
|
|
}
|
|
|
|
function isMatchingFenceClose(
|
|
markdown: string,
|
|
lineStart: number,
|
|
lineEnd: number,
|
|
openFence: OpenMarkdownFence,
|
|
): boolean {
|
|
let pos = lineStart;
|
|
while (pos < lineEnd && pos - lineStart < 3 && markdown.charCodeAt(pos) === 32) {
|
|
pos += 1;
|
|
}
|
|
if (pos >= lineEnd || markdown.charCodeAt(pos) !== openFence.markerCode) {
|
|
return false;
|
|
}
|
|
let markerEnd = pos;
|
|
while (markerEnd < lineEnd && markdown.charCodeAt(markerEnd) === openFence.markerCode) {
|
|
markerEnd += 1;
|
|
}
|
|
if (markerEnd - pos < openFence.markerLen) {
|
|
return false;
|
|
}
|
|
for (let idx = markerEnd; idx < lineEnd; idx += 1) {
|
|
if (!isHorizontalSpace(markdown.charCodeAt(idx))) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
export interface ExtractedFencedSchemaBlocksResult {
|
|
blocks: SchemaBlock[];
|
|
truncated: boolean;
|
|
}
|
|
|
|
/**
|
|
* Single-pass O(N) CommonMark fence scanner with zero multi-line regexes or
|
|
* backreferences. Unterminated fences consume to EOF once without rescanning
|
|
* inner lines, ordinary non-schema JSON blocks do not consume the schema-parse
|
|
* budget, and truncated scans are flagged explicitly so callers do not confuse
|
|
* skipped content with a missing result block.
|
|
*/
|
|
export function extractFencedSchemaBlocksWithStatus(
|
|
markdown: string | null | undefined,
|
|
): ExtractedFencedSchemaBlocksResult {
|
|
if (!markdown) {
|
|
return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated: false };
|
|
}
|
|
|
|
let truncated = false;
|
|
let source = markdown;
|
|
if (markdown.length > MAX_SCANNED_MARKDOWN_CHARS) {
|
|
truncated = true;
|
|
const lastNewline = markdown.lastIndexOf("\n", MAX_SCANNED_MARKDOWN_CHARS - 1);
|
|
if (lastNewline === -1) {
|
|
return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated: true };
|
|
}
|
|
source = markdown.slice(0, lastNewline);
|
|
}
|
|
|
|
if (!source.includes("```") && !source.includes("~~~")) {
|
|
return { blocks: EMPTY_SCHEMA_BLOCKS as SchemaBlock[], truncated };
|
|
}
|
|
|
|
const found: SchemaBlock[] = [];
|
|
let openFence: OpenMarkdownFence | null = null;
|
|
let parsedSchemaCandidates = 0;
|
|
let lineStart = 0;
|
|
const totalLen = source.length;
|
|
|
|
while (lineStart <= totalLen) {
|
|
const nlIdx = source.indexOf("\n", lineStart);
|
|
const rawLineEnd = nlIdx === -1 ? totalLen : nlIdx;
|
|
const lineEnd =
|
|
rawLineEnd > lineStart && source.charCodeAt(rawLineEnd - 1) === 13
|
|
? rawLineEnd - 1
|
|
: rawLineEnd;
|
|
const nextLineStart = nlIdx === -1 ? totalLen + 1 : nlIdx + 1;
|
|
|
|
if (openFence === null) {
|
|
openFence = matchFenceOpening(source, lineStart, lineEnd, nextLineStart);
|
|
} else if (isMatchingFenceClose(source, lineStart, lineEnd, openFence)) {
|
|
if (openFence.isJson) {
|
|
let bodyEnd = lineStart;
|
|
if (bodyEnd > openFence.bodyStart && source.charCodeAt(bodyEnd - 1) === 10) {
|
|
bodyEnd -= 1;
|
|
if (bodyEnd > openFence.bodyStart && source.charCodeAt(bodyEnd - 1) === 13) {
|
|
bodyEnd -= 1;
|
|
}
|
|
}
|
|
const bodyLen = bodyEnd - openFence.bodyStart;
|
|
const metaRef = parseSchemaFenceMeta(openFence.meta);
|
|
if (bodyLen > MAX_SCHEMA_FENCE_BODY_CHARS) {
|
|
if (metaRef) {
|
|
truncated = true;
|
|
}
|
|
} else if (bodyLen > 0) {
|
|
const rawBody = source.slice(openFence.bodyStart, bodyEnd);
|
|
const isCandidate =
|
|
Boolean(metaRef) ||
|
|
(rawBody.includes('"schema"') && rawBody.includes('"data"'));
|
|
if (isCandidate) {
|
|
if (parsedSchemaCandidates >= MAX_SCANNED_JSON_FENCES) {
|
|
truncated = true;
|
|
openFence = null;
|
|
break;
|
|
}
|
|
parsedSchemaCandidates += 1;
|
|
const parsed = parseJsonSchemaBlock(rawBody, metaRef?.ref ?? null);
|
|
if (parsed) {
|
|
found.push(parsed.block);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
openFence = null;
|
|
}
|
|
|
|
lineStart = nextLineStart;
|
|
}
|
|
|
|
return { blocks: found, truncated };
|
|
}
|
|
|
|
export function extractFencedSchemaBlocks(markdown: string | null | undefined): SchemaBlock[] {
|
|
return extractFencedSchemaBlocksWithStatus(markdown).blocks;
|
|
}
|
|
|
|
export function getUnfencedSchemaBlocks(
|
|
markdown: string | null | undefined,
|
|
blocks: readonly SchemaBlock[] | null | undefined,
|
|
): readonly SchemaBlock[] {
|
|
if (!blocks || blocks.length === 0) return EMPTY_SCHEMA_BLOCKS;
|
|
if (!markdown || (!markdown.includes("```") && !markdown.includes("~~~"))) {
|
|
return blocks;
|
|
}
|
|
const fenced = extractFencedSchemaBlocks(markdown);
|
|
if (fenced.length === 0) return blocks;
|
|
const fencedKeys = new Set(fenced.map(canonicalSchemaBlockKey));
|
|
const remaining = blocks.filter((block) => !fencedKeys.has(canonicalSchemaBlockKey(block)));
|
|
return remaining.length > 0 ? remaining : EMPTY_SCHEMA_BLOCKS;
|
|
}
|
|
|
|
export type SchemaBlockMatchStatus = "matched" | "missing" | "unverified";
|
|
|
|
export function checkMatchingSchemaBlock(
|
|
schemaRef: string | null | undefined,
|
|
sources: {
|
|
schemaBlocks?: readonly SchemaBlock[] | null;
|
|
markdownBodies?: ReadonlyArray<string | null | undefined>;
|
|
commentSchemaBlocks?: ReadonlyArray<readonly SchemaBlock[] | null | undefined>;
|
|
},
|
|
): SchemaBlockMatchStatus {
|
|
if (!schemaRef) return "missing";
|
|
let target: ParsedSchemaRef;
|
|
try {
|
|
target = parseSchemaRef(schemaRef.trim().toLowerCase());
|
|
} catch {
|
|
return "missing";
|
|
}
|
|
|
|
const matches = (block: SchemaBlock) =>
|
|
block.schema.toLowerCase() === target.name && block.version === target.version;
|
|
|
|
if (sources.schemaBlocks?.some(matches)) return "matched";
|
|
if (sources.commentSchemaBlocks?.some((list) => list?.some(matches))) return "matched";
|
|
|
|
let anyTruncated = false;
|
|
if (sources.markdownBodies) {
|
|
for (const body of sources.markdownBodies) {
|
|
if (!body) continue;
|
|
const scanned = extractFencedSchemaBlocksWithStatus(body);
|
|
if (scanned.blocks.some(matches)) return "matched";
|
|
if (scanned.truncated) {
|
|
anyTruncated = true;
|
|
}
|
|
}
|
|
}
|
|
return anyTruncated ? "unverified" : "missing";
|
|
}
|
|
|
|
export function hasMatchingSchemaBlock(
|
|
schemaRef: string | null | undefined,
|
|
sources: {
|
|
schemaBlocks?: readonly SchemaBlock[] | null;
|
|
markdownBodies?: ReadonlyArray<string | null | undefined>;
|
|
commentSchemaBlocks?: ReadonlyArray<readonly SchemaBlock[] | null | undefined>;
|
|
},
|
|
): boolean {
|
|
return checkMatchingSchemaBlock(schemaRef, sources) === "matched";
|
|
}
|
|
|
|
export function safeHttpsUrl(raw: unknown): string | null {
|
|
if (typeof raw !== "string") return null;
|
|
const trimmed = raw.trim();
|
|
if (!trimmed) return null;
|
|
try {
|
|
const parsed = new URL(trimmed);
|
|
return parsed.protocol === "https:" ? parsed.toString() : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|