@bendyline/gezel-sdk 1.1.7 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/checks.d.ts CHANGED
@@ -45,6 +45,60 @@ interface CheckResult {
45
45
  type StepSniffName = 'html-complete' | 'html-game' | 'nonempty' | 'json-valid' | 'data-table';
46
46
  declare function runSniff(name: StepSniffName, content: string): boolean;
47
47
 
48
+ /**
49
+ * `claimsGrounded`: the facts in a document appear in the sources it cites.
50
+ *
51
+ * `citationsResolve` proves a cited file exists; it says nothing about
52
+ * whether the cited file says what the sentence claims. A research deck could
53
+ * cite the brief and still invent its numbers, which is exactly the "cited and
54
+ * verified" bar a research book promises. This check reads each cited source
55
+ * and requires every number, date, month and quotation in a citing sentence to
56
+ * appear in it, using the same engine (`groundText`) and the same counting rule
57
+ * (`isBlockingGroundingProblem`) that refuse an unsupported document write in a
58
+ * factual chat. It catches invention, not a wrong source copied faithfully.
59
+ *
60
+ * Citations it reads: `[n]` markers resolved through a Sources / References
61
+ * list, and inline `(source: path)` notes. Cited URLs, `knowledge://`
62
+ * references and PDF or Office files cannot be read here as text, so a
63
+ * sentence citing only those counts as cited but unverified, never as
64
+ * invented. `sources` adds material the facts
65
+ * may come from without being cited (a contract's supplied brief), so a true
66
+ * but uncited detail reads as a citation slip rather than an invention.
67
+ */
68
+ interface ClaimsGroundedOptions {
69
+ /** Files or folders the facts may come from, cited or not. */
70
+ sources?: readonly string[];
71
+ /** Citing sentences whose details no evidence shows. Default 0. */
72
+ maxUnsupported?: number;
73
+ /** Citations that resolve to nothing. Default 0. */
74
+ maxBadCitations?: number;
75
+ /** Uncited sentences whose details no evidence shows. Default 0. */
76
+ maxUncited?: number;
77
+ /**
78
+ * What the task was handed: its request, its parameters, today's date. A
79
+ * detail found here needs no citation, as in chat, where the person's own
80
+ * words are never an invention.
81
+ */
82
+ given?: string;
83
+ }
84
+ interface ClaimsGroundedResult extends CheckResult {
85
+ counts: {
86
+ supported: number;
87
+ unattributed: number;
88
+ unverified: number;
89
+ unsupported: number;
90
+ uncited: number;
91
+ badCitations: number;
92
+ };
93
+ sources: {
94
+ read: string[];
95
+ missing: string[];
96
+ unverifiable: string[];
97
+ };
98
+ problems: string[];
99
+ }
100
+ declare function claimsGrounded(ws: WorkspaceLike, file: string, opts?: ClaimsGroundedOptions): Promise<ClaimsGroundedResult>;
101
+
48
102
  /**
49
103
  * Existence oracle for cited workspace paths — the shared spine of the
50
104
  * anti-fabrication checks (`citationsResolve`, `securityReport`,
@@ -909,4 +963,4 @@ declare function workspaceFromGezel(g: {
909
963
  };
910
964
  }): WorkspaceLike;
911
965
 
912
- export { type CellType, type CheckResult, type CitationsResult, type CodebaseReviewReportOptions, type CodebaseReviewReportResult, type CorpusCoverageLedger, type CorpusCoverageMergeResult, type CorpusCoverageShardInput, type CsvShapeResult, type CsvShapeSpec, type EntitiesResult, type EntitySpec, type ExplainableSniff, type FigureCheckOptions, type FigureCheckResult, type FigureFinding, type FigureFindingKind, GateScriptResult, type GroundingFact, type GroundingResult, IMG_EXT, type ImageRefsReport, type InlineScript, type JsonPathEqualsResult, type JsonScalar, type JudgeVerdict, MIN_INLINE_JS_BYTES, MIN_JUDGE_EVIDENCE_SUBSTRING, type MarkdownHeadingsMatchResult, type ParsedTable, type PlanRow, type PlanStructureResult, type PlanStructureSpec, type ReadingLevelResult, type RecordFieldSpec, type RecordSchemaResult, type RecordSchemaSpec, type ScriptValidation, type SecurityReportOptions, type SecurityReportResult, type StepSniffName, type TableShapeResult, type TableShapeSpec, type UnsupportedClaimPattern, type UnsupportedClaimViolation, type UnsupportedClaimsResult, type ValuesSubsetResult, type ValuesSubsetSpec, type WordBandResult, type WorkspaceLike, buildJudgePrompt, checkFigures, citationsResolve, citedPathKey, cleanCitedPath, codebaseReviewReport, containsPattern, countDistinctMatches, createCitedPathChecker, cssMinBytes, csvShape, dataTableSniff, detectTypeScriptOnlySyntax, detectUnclosedScript, esmImports, explainSniff, extractInlineScripts, extractMoneyAmounts, fileCountByExt, fileMinBytes, fileMinLines, findImageRefs, frontmatterList, gateResult, grepMatches, htmlCompleteSniff, htmlGameSniff, imageRefsResolve, inlineJsBytes, isRealIsoDate, jsonPathEquals, jsonValid, listedFiles, markdownHeadingsMatch, mergeCorpusCoverageShards, namedEntitiesConsistent, normalizeDigitGroups, normalizeInlineEmphasis, normalizeTypography, notContainsPattern, parseCsv, parseJudgeVerdict, parseMarkdownTable, planStructure, readingLevel, recordSchema, requireOrderedSections, resolveRelative, runSniff, securityReport, standaloneJsParses, tableShape, totalMinBytes, unsupportedClaims, validateJudgeEvidence, validateScriptSyntax, valueGrounding, valuesSubsetOf, wordBand, workspaceFromGezel, wrapperReturnHint };
966
+ export { type CellType, type CheckResult, type CitationsResult, type ClaimsGroundedOptions, type ClaimsGroundedResult, type CodebaseReviewReportOptions, type CodebaseReviewReportResult, type CorpusCoverageLedger, type CorpusCoverageMergeResult, type CorpusCoverageShardInput, type CsvShapeResult, type CsvShapeSpec, type EntitiesResult, type EntitySpec, type ExplainableSniff, type FigureCheckOptions, type FigureCheckResult, type FigureFinding, type FigureFindingKind, GateScriptResult, type GroundingFact, type GroundingResult, IMG_EXT, type ImageRefsReport, type InlineScript, type JsonPathEqualsResult, type JsonScalar, type JudgeVerdict, MIN_INLINE_JS_BYTES, MIN_JUDGE_EVIDENCE_SUBSTRING, type MarkdownHeadingsMatchResult, type ParsedTable, type PlanRow, type PlanStructureResult, type PlanStructureSpec, type ReadingLevelResult, type RecordFieldSpec, type RecordSchemaResult, type RecordSchemaSpec, type ScriptValidation, type SecurityReportOptions, type SecurityReportResult, type StepSniffName, type TableShapeResult, type TableShapeSpec, type UnsupportedClaimPattern, type UnsupportedClaimViolation, type UnsupportedClaimsResult, type ValuesSubsetResult, type ValuesSubsetSpec, type WordBandResult, type WorkspaceLike, buildJudgePrompt, checkFigures, citationsResolve, citedPathKey, claimsGrounded, cleanCitedPath, codebaseReviewReport, containsPattern, countDistinctMatches, createCitedPathChecker, cssMinBytes, csvShape, dataTableSniff, detectTypeScriptOnlySyntax, detectUnclosedScript, esmImports, explainSniff, extractInlineScripts, extractMoneyAmounts, fileCountByExt, fileMinBytes, fileMinLines, findImageRefs, frontmatterList, gateResult, grepMatches, htmlCompleteSniff, htmlGameSniff, imageRefsResolve, inlineJsBytes, isRealIsoDate, jsonPathEquals, jsonValid, listedFiles, markdownHeadingsMatch, mergeCorpusCoverageShards, namedEntitiesConsistent, normalizeDigitGroups, normalizeInlineEmphasis, normalizeTypography, notContainsPattern, parseCsv, parseJudgeVerdict, parseMarkdownTable, planStructure, readingLevel, recordSchema, requireOrderedSections, resolveRelative, runSniff, securityReport, standaloneJsParses, tableShape, totalMinBytes, unsupportedClaims, validateJudgeEvidence, validateScriptSyntax, valueGrounding, valuesSubsetOf, wordBand, workspaceFromGezel, wrapperReturnHint };
package/dist/checks.js CHANGED
@@ -628,6 +628,461 @@ function runSniff(name, content) {
628
628
  }
629
629
  }
630
630
 
631
+ // ../core/src/grounding/citations.ts
632
+ var MARKER = /\[(\d{1,3}(?:\s*(?:[-–]|,)\s*\d{1,3})*)\]/g;
633
+ function parseCitationNumbers(inner) {
634
+ const out = [];
635
+ for (const part of inner.split(",")) {
636
+ const range = /^\s*(\d{1,3})\s*[-–]\s*(\d{1,3})\s*$/.exec(part);
637
+ if (range) {
638
+ const a = Number(range[1]);
639
+ const b = Number(range[2]);
640
+ for (let n = Math.min(a, b); n <= Math.max(a, b) && n - Math.min(a, b) < 50; n++) out.push(n);
641
+ } else if (/^\s*\d{1,3}\s*$/.test(part)) out.push(Number(part));
642
+ }
643
+ return [...new Set(out)];
644
+ }
645
+ function stripCitations(text) {
646
+ return text.replace(MARKER, "").replace(/[ \t]+([.,;:!?])/g, "$1").replace(/[ \t]{2,}/g, " ").trim();
647
+ }
648
+ var ABBREVIATION = /(?:^|\s)(?:Mr|Mrs|Ms|Dr|St|Mt|Jr|Sr|Gen|Col|Lt|Capt|Rev|Gov|Sen|Rep|Pres|Prof|Fr|Sgt|Maj|Adm|Cpl|Hon|vs|etc|No|Vol|ca|approx|e\.g|i\.e|U\.S|U\.K)\.$|(?:^|\s)[A-Z]\.$/;
649
+ function citedSentences(markdown) {
650
+ const units = [];
651
+ let inFence = false;
652
+ for (const line of markdown.split("\n")) {
653
+ if (/^\s*(?:```|~~~)/.test(line)) {
654
+ inFence = !inFence;
655
+ continue;
656
+ }
657
+ if (inFence || /^\s*(?:#{1,6}\s|\||<!--|---\s*$|\*\*\*\s*$)/.test(line) || /^\s*(?:[-*+]\s+)?\*\*[^*]+\*\*:?\s*$/.test(line))
658
+ continue;
659
+ const body = line.replace(/^\s*(?:[-*+]|\d+[.)]|>)\s+/, "").trim();
660
+ if (body) units.push(body);
661
+ }
662
+ const out = [];
663
+ for (const unit of units) {
664
+ const normalized = unit.replace(/([.!?])((?:\s*\[\d[\d,\s–-]*\])+)/g, "$2$1");
665
+ const pieces = normalized.split(
666
+ /(?<=[.!?](?:\*\*|__|\*|_)?["”’)]?)\s+(?=(?:\*\*|__|\*|_|["“‘(])?[A-Z0-9])/
667
+ );
668
+ const sentences = [];
669
+ for (const piece of pieces) {
670
+ const previous = sentences.at(-1);
671
+ if (previous !== void 0 && ABBREVIATION.test(previous))
672
+ sentences[sentences.length - 1] = `${previous} ${piece}`;
673
+ else sentences.push(piece);
674
+ }
675
+ for (const sentence of sentences) {
676
+ const cites = [];
677
+ for (const m of sentence.matchAll(MARKER)) cites.push(...parseCitationNumbers(m[1] ?? ""));
678
+ const text = stripCitations(sentence);
679
+ if (text) out.push({ text, cites: [...new Set(cites)] });
680
+ }
681
+ }
682
+ return out;
683
+ }
684
+ var MONTHS = [
685
+ "january",
686
+ "february",
687
+ "march",
688
+ "april",
689
+ "may",
690
+ "june",
691
+ "july",
692
+ "august",
693
+ "september",
694
+ "october",
695
+ "november",
696
+ "december"
697
+ ];
698
+ var SMALL_NUMBERS = [
699
+ "zero",
700
+ "one",
701
+ "two",
702
+ "three",
703
+ "four",
704
+ "five",
705
+ "six",
706
+ "seven",
707
+ "eight",
708
+ "nine",
709
+ "ten",
710
+ "eleven",
711
+ "twelve"
712
+ ];
713
+ var COMMON_CAPITALIZED = new Set(
714
+ "a an the and but or nor so yet for if when while after before during although though because since until unless as at by from in into of on onto to with without within he she it they we you i his her its their our your my this that these those there here then today tonight yesterday tomorrow later earlier meanwhile however instead still also each every both either neither many most some few all one two three no not yes later once soon now who what where which why how do does did is are was were be been being am has have had will would can could should shall may might must".split(
715
+ " "
716
+ )
717
+ );
718
+ var WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
719
+ function weekdayOfIsoDate(evidence, weekday) {
720
+ for (const m of evidence.matchAll(/(?<!\d)(\d{4})-(\d{2})-(\d{2})(?!\d)/g)) {
721
+ const date = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
722
+ if (!Number.isNaN(date.getTime()) && date.getUTCDay() === weekday) return true;
723
+ }
724
+ return false;
725
+ }
726
+ var TECHNICAL_ACRONYMS = new Set(
727
+ "http https api url uri utc gmt json csv xml html css sql cpu gpu ram ssd dns tls ssl sdk cli ci cd pr id ui ux os vm qa sla slo sli rps qps eur usd gbp kb mb gb tb ms pdf faq".split(
728
+ " "
729
+ )
730
+ );
731
+ var NAME_JOINERS = /* @__PURE__ */ new Set([
732
+ "of",
733
+ "de",
734
+ "da",
735
+ "del",
736
+ "van",
737
+ "von",
738
+ "der",
739
+ "la",
740
+ "le",
741
+ "du",
742
+ "the",
743
+ "and"
744
+ ]);
745
+ var CLOCK_TIME = /(?<![\d:.])((?:[01]?\d|2[0-3]):[0-5]\d(?::[0-5]\d)?)(?![\d:])/g;
746
+ var APPROXIMATE = /(?:[~≈]\s*|\b(?:about|around|roughly|approximately|approx\.|nearly|almost|circa|some)\s+)(?:\d[\d,.]*\s*(?:[-–—]|to)\s*)?$/i;
747
+ var ENUMERATOR_LABEL = /(?:\b(?:step|phase|slide|part|stage|round|option|item|section|chapter|no\.)\s*|[#§]\s*)$/i;
748
+ function isEnumerator(before, after, value) {
749
+ if (ENUMERATOR_LABEL.test(before)) return true;
750
+ return value < 100 && /^[\s*_#>-]*$/.test(before) && /^[.)](?:\s|\*|$)/.test(after);
751
+ }
752
+ function extractClaims(text) {
753
+ const sentence = text.replace(/`[^`]*`/g, " ").replace(/\]\([^)]*\)/g, "]").replace(/\bhttps?:\/\/\S+/g, " ").replace(ATTRIBUTION_PARENTHETICAL, " ").replace(FILE_REFERENCE, " ");
754
+ const claims = [];
755
+ const seen = /* @__PURE__ */ new Set();
756
+ const add = (kind, value, flags = {}) => {
757
+ const key = `${kind}:${value.toLowerCase()}`;
758
+ if (!seen.has(key)) {
759
+ seen.add(key);
760
+ claims.push({
761
+ kind,
762
+ value,
763
+ ...flags.approx ? { approx: true } : {},
764
+ ...flags.percent ? { percent: true } : {},
765
+ ...flags.clock ? { clock: true } : {}
766
+ });
767
+ }
768
+ };
769
+ for (const m of sentence.matchAll(/["“]([^"”]{8,}?)["”]/g)) {
770
+ if ((m[1] ?? "").trim().split(/\s+/).length >= 3) add("quote", (m[1] ?? "").trim());
771
+ }
772
+ const unquoted = sentence.replace(/["“][^"”]*["”]/g, " ");
773
+ for (const m of unquoted.matchAll(CLOCK_TIME)) add("number", m[1] ?? "", { clock: true });
774
+ const numeric = unquoted.replace(CLOCK_TIME, (time) => " ".repeat(time.length));
775
+ for (const m of numeric.matchAll(
776
+ /(?<![\w.])(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?:st|nd|rd|th|s)?(?![\w.]*\d)/g
777
+ )) {
778
+ const digits = (m[1] ?? "").replace(/,/g, "");
779
+ const value = Number(digits);
780
+ const at = m.index ?? 0;
781
+ if (isEnumerator(numeric.slice(0, at), numeric.slice(at + m[0].length), value)) continue;
782
+ if (/^(1[0-9]{3}|20[0-9]{2})$/.test(digits) && !(m[1] ?? "").includes(",")) add("year", digits);
783
+ else if (Number.isFinite(value))
784
+ add("number", digits, {
785
+ approx: APPROXIMATE.test(unquoted.slice(Math.max(0, at - 24), at)),
786
+ percent: /^\s*(?:%|percent\b)/i.test(unquoted.slice(at + m[0].length))
787
+ });
788
+ }
789
+ for (const m of unquoted.matchAll(
790
+ /\b(January|February|March|April|May|June|July|August|September|October|November|December)\b/g
791
+ )) {
792
+ if (m.index !== 0 || m[1] !== "May") add("month", m[1] ?? "");
793
+ }
794
+ const raw = unquoted.split(/\s+/);
795
+ const tokens = raw.map((t) => t.replace(/^[^\p{L}]+|[^\p{L}'’-]+$/gu, ""));
796
+ const opensClause = (i) => i === 0 || raw[i + 1] === "/" || /[:;—–·|•/\]]\**$/.test(raw[i - 1] ?? "") || /^(?:[-*+>•·|/]|\d{1,3}[.)])$/.test(raw[i - 1] ?? "");
797
+ const isFormula = (i) => /\p{Lu}\p{L}*[0-9₀-₉]/u.test(raw[i] ?? "");
798
+ let run = [];
799
+ let runStart = -1;
800
+ const flush = () => {
801
+ const words = run.filter((w) => !NAME_JOINERS.has(w.toLowerCase()));
802
+ const startsSentence = runStart >= 0 && opensClause(runStart);
803
+ const named = startsSentence && words.filter((w) => isEntityName(w)).length < 2 ? words.slice(1) : words;
804
+ const parts = named.flatMap(
805
+ (word) => word.includes("-") ? word.split("-").filter((part) => /^\p{Lu}/u.test(part) && !/^\p{Lu}{2,}$/u.test(part)) : [word]
806
+ );
807
+ for (const word of parts) {
808
+ const bare = word.replace(/['’]s$/, "");
809
+ if (bare.length > 1 && !COMMON_CAPITALIZED.has(bare.toLowerCase()) && !TECHNICAL_ACRONYMS.has(bare.toLowerCase()) && !MONTHS.includes(bare.toLowerCase()))
810
+ add("name", bare);
811
+ }
812
+ run = [];
813
+ runStart = -1;
814
+ };
815
+ tokens.forEach((token, i) => {
816
+ if (/^\p{Lu}[\p{L}'’-]*$/u.test(token) && // All capitals is emphasis or an acronym ("NOT APPLICABLE", "PASS"),
817
+ // not a name a source has to state.
818
+ !/^\p{Lu}{2,}$/u.test(token) && !isFormula(i) && !(opensClause(i) && COMMON_CAPITALIZED.has(token.toLowerCase()))) {
819
+ if (run.length === 0) runStart = i;
820
+ run.push(token);
821
+ if (/[:;,.!?)\]—–]\**$/.test(raw[i] ?? "")) flush();
822
+ } else if (run.length > 0 && NAME_JOINERS.has(token.toLowerCase())) run.push(token);
823
+ else flush();
824
+ });
825
+ flush();
826
+ return claims;
827
+ }
828
+ var THOUSANDS = /(?<![\d.,])\d{1,3}(?:,\d{3})+(?:\.\d+)?(?!\d|,\d)/g;
829
+ var normalizeEvidence = (text) => ` ${text.replace(/^[ \t]*\d+→ ?/gm, "").toLowerCase().replace(THOUSANDS, (n) => n.replace(/,/g, "")).replace(/[“”]/g, '"').replace(/[‘’]/g, "'").replace(/\s+/g, " ")} `;
830
+ function claimPattern(kind, value) {
831
+ const v = value.toLowerCase();
832
+ if (kind === "year" || kind === "number") {
833
+ const n = Number(v);
834
+ const digits = `(?<![\\d.])${v.replace(".", "\\.")}(?![\\d]|\\.\\d)`;
835
+ return new RegExp(
836
+ Number.isInteger(n) && n <= 12 ? `${digits}|\\b${SMALL_NUMBERS[n]}\\b` : digits,
837
+ "g"
838
+ );
839
+ }
840
+ return new RegExp(
841
+ `(?<![\\p{L}])${v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:['\u2019]?s)?(?![\\p{L}])`,
842
+ "gu"
843
+ );
844
+ }
845
+ var QUOTE_EDGE_PUNCTUATION = /^[\s,.;:!?…]+|[\s,.;:!?…]+$/g;
846
+ function quoteFound(value, evidence) {
847
+ const pieces = normalizeEvidence(value).split(/…|\.\.\./).map((piece) => piece.replace(QUOTE_EDGE_PUNCTUATION, "")).filter(Boolean);
848
+ return pieces.length > 0 && pieces.every((piece) => evidence.includes(piece));
849
+ }
850
+ var EVIDENCE_NUMBER = /(?<![\d.])\d+(?:\.\d+)?(?![\d]|\.\d)/g;
851
+ function claimFound(claim, evidence) {
852
+ const { kind, value } = claim;
853
+ if (kind === "quote") return quoteFound(value, evidence);
854
+ if (claimPattern(kind, value).test(evidence)) return true;
855
+ if (kind === "name") {
856
+ const weekday = WEEKDAYS.indexOf(value.toLowerCase());
857
+ return weekday >= 0 && weekdayOfIsoDate(evidence, weekday);
858
+ }
859
+ if (kind === "month") {
860
+ const month = String(MONTHS.indexOf(value.toLowerCase()) + 1).padStart(2, "0");
861
+ return new RegExp(`\\b\\d{4}-${month}\\b`).test(evidence);
862
+ }
863
+ if (kind !== "number") return false;
864
+ if (claim.clock) {
865
+ const other = /^0\d:/.test(value) ? value.slice(1) : /^\d:/.test(value) ? `0${value}` : "";
866
+ return other !== "" && claimPattern(kind, other).test(evidence);
867
+ }
868
+ if (claim.percent && value === "100") return /\b(?:all|every|entire|whole)\b/.test(evidence);
869
+ if (claim.percent && value === "0") return /\b(?:none|zero|no)\b/.test(evidence);
870
+ const target = Number(value);
871
+ const evidenceNumbers = () => [...evidence.matchAll(EVIDENCE_NUMBER)].map((m) => Number(m[0]));
872
+ if (claim.percent) {
873
+ const places = value.split(".")[1]?.length ?? 0;
874
+ const tolerance = 0.5 * 10 ** -places + 1e-9;
875
+ if (evidenceNumbers().some((n) => n < 1 && Math.abs(n * 100 - target) <= tolerance))
876
+ return true;
877
+ }
878
+ if (value.includes(".")) {
879
+ const tolerance = 0.5 * 10 ** -(value.split(".")[1]?.length ?? 0) + 1e-9;
880
+ if (evidenceNumbers().some((n) => Math.abs(n / 1e3 - target) <= tolerance)) return true;
881
+ if (claim.approx && evidenceNumbers().some((n) => Math.abs(n - target) <= tolerance))
882
+ return true;
883
+ return false;
884
+ }
885
+ const zeros = /0*$/.exec(value)?.[0].length ?? 0;
886
+ if (claim.approx && zeros > 0 && zeros < value.length) {
887
+ const tolerance = 0.5 * 10 ** zeros;
888
+ return evidenceNumbers().some((n) => Math.abs(n - target) <= tolerance);
889
+ }
890
+ return false;
891
+ }
892
+ function isEntityName(word) {
893
+ return !/^\p{Lu}[\p{Lu}\d]+$/u.test(word) && !/\p{Ll}\p{Lu}/u.test(word);
894
+ }
895
+ var ATTRIBUTION_PARENTHETICAL = /\([^()]*\b[\w.-]+\.(?:md|csv|txt|log|json|diff|ya?ml|tsv|html?)\b[^()]*\)/gi;
896
+ var FILE_REFERENCE = /\b[\w./-]+\.(?:md|csv|txt|log|json|diff|ya?ml|tsv|html?)\b(?::[\d:,–-]+)?/gi;
897
+ var NEAR_CHARS = 160;
898
+ function detachedNumbers(claims, sources, sentence = "") {
899
+ const occurrences = (kind, value, text) => [
900
+ ...text.matchAll(claimPattern(kind, value))
901
+ ];
902
+ const count = (value) => sources.reduce((sum, text) => sum + occurrences("name", value, text).length, 0);
903
+ const subject = sentence.replace(ATTRIBUTION_PARENTHETICAL, " ");
904
+ const names = claims.filter(
905
+ (c) => c.kind === "name" && isEntityName(c.value) && count(c.value) > 0 && (!sentence || claimPattern("name", c.value).test(normalizeEvidence(subject)))
906
+ );
907
+ if (names.length === 0) return [];
908
+ const rarest = (values) => values.reduce((best, v) => count(v) < count(best) ? v : best);
909
+ const runs = nameRuns(
910
+ names.map((c) => c.value),
911
+ subject
912
+ );
913
+ const out = [];
914
+ for (const claim of claims) {
915
+ if (claim.kind !== "year" && claim.kind !== "number" || claim.clock) continue;
916
+ const run = nearestRun(runs, claim, subject);
917
+ const anchor = rarest(run ?? names.map((c) => c.value));
918
+ const near = new RegExp(claimPattern("name", anchor).source, "u");
919
+ const stated = sources.filter((text) => near.test(text)).map((text) => ({ text, at: occurrences(claim.kind, claim.value, text) })).filter((source) => source.at.length > 0);
920
+ if (stated.length === 0) continue;
921
+ const placed = stated.some(
922
+ ({ text, at }) => at.some((m) => {
923
+ const i = m.index ?? 0;
924
+ return near.test(text.slice(Math.max(0, i - NEAR_CHARS), i + NEAR_CHARS));
925
+ })
926
+ );
927
+ if (!placed) out.push(`${claim.value} next to ${anchor}`);
928
+ }
929
+ return out;
930
+ }
931
+ function nameRuns(values, sentence) {
932
+ const text = normalizeEvidence(sentence);
933
+ const spots = values.flatMap(
934
+ (value) => [...text.matchAll(claimPattern("name", value))].map((m) => ({
935
+ value,
936
+ start: m.index ?? 0,
937
+ end: (m.index ?? 0) + m[0].length
938
+ }))
939
+ ).sort((a, b) => a.start - b.start);
940
+ const runs = [];
941
+ for (const spot of spots) {
942
+ const last = runs.at(-1);
943
+ if (last && /^[\s'’.-]*$/.test(text.slice(last.end, spot.start))) {
944
+ if (!last.words.includes(spot.value)) last.words.push(spot.value);
945
+ last.end = spot.end;
946
+ } else runs.push({ words: [spot.value], start: spot.start, end: spot.end });
947
+ }
948
+ return runs;
949
+ }
950
+ function nearestRun(runs, claim, sentence) {
951
+ if (runs.length === 0) return void 0;
952
+ const at = claimPattern(claim.kind, claim.value).exec(normalizeEvidence(sentence))?.index;
953
+ if (at === void 0) return void 0;
954
+ const distance = (run) => at < run.start ? run.start - at : at > run.end ? at - run.end : 0;
955
+ return runs.reduce((best, run) => distance(run) < distance(best) ? run : best).words;
956
+ }
957
+ function groundContext(evidence, options) {
958
+ const given = options.given ? normalizeEvidence(options.given) : "";
959
+ const normalized = new Map([...evidence].map(([n, item]) => [n, normalizeEvidence(item.text)]));
960
+ return {
961
+ evidence,
962
+ normalized,
963
+ everything: [...normalized.values()].join("\n") + given,
964
+ sources: [...normalized.values(), ...given ? [given] : []],
965
+ given,
966
+ ...options.opaque ? { opaque: options.opaque } : {}
967
+ };
968
+ }
969
+ function checkAgainst(claims, text) {
970
+ return withShownArithmetic(
971
+ claims.map((claim) => ({
972
+ kind: claim.kind,
973
+ value: claim.value,
974
+ found: claimFound(claim, text)
975
+ }))
976
+ );
977
+ }
978
+ function withShownArithmetic(checks) {
979
+ const sourced = checks.filter((c) => c.kind === "number" && c.found).map((c) => Number(c.value)).filter(Number.isFinite);
980
+ if (sourced.length < 2) return checks;
981
+ return checks.map(
982
+ (c) => c.kind === "number" && !c.found && isDerivedNumber(c.value, sourced) ? { ...c, found: true } : c
983
+ );
984
+ }
985
+ function isDerivedNumber(value, sourced) {
986
+ const v = Number(value);
987
+ if (!Number.isFinite(v)) return false;
988
+ const decimals = value.includes(".") ? value.split(".")[1].length : 0;
989
+ const scale = 10 ** decimals;
990
+ const writtenAs = (x) => Math.abs(Math.round(x * scale) - v * scale) < 1e-6 || Math.abs(Math.trunc(x * scale + 1e-9) - v * scale) < 1e-6;
991
+ for (let i = 0; i < sourced.length; i++) {
992
+ for (let j = 0; j < sourced.length; j++) {
993
+ if (i === j) continue;
994
+ const a = sourced[i];
995
+ const b = sourced[j];
996
+ if (a === b) continue;
997
+ if (j > i && (writtenAs(a + b) || writtenAs(Math.abs(a - b)))) return true;
998
+ if (a !== 0 && writtenAs(Math.abs(a - b) / Math.abs(a) * 100)) return true;
999
+ if (b !== 0 && (writtenAs(a / b) || writtenAs(a / b * 100))) return true;
1000
+ }
1001
+ }
1002
+ return false;
1003
+ }
1004
+ var DISCLAIMS = /\b(?:could ?n[o']t|cannot|can't|was unable to|unable to|did ?n[o']t)\s+(?:be\s+)?(?:verif|confirm|find|locate)|\b(?:unverified|unconfirmed|not (?:been )?(?:verified|confirmed))\b|\bno (?:source|record)s?\b/i;
1005
+ function groundWith(ctx, sentence) {
1006
+ if (sentence.cites.length === 0 && DISCLAIMS.test(sentence.text)) {
1007
+ return { ...sentence, status: "non-factual", checks: [], missing: [] };
1008
+ }
1009
+ const claims = extractClaims(sentence.text);
1010
+ const opaque = sentence.cites.filter((n) => !ctx.evidence.has(n) && ctx.opaque?.(n));
1011
+ const badCites = sentence.cites.filter((n) => !ctx.evidence.has(n) && !opaque.includes(n));
1012
+ if (badCites.length > 0) {
1013
+ return {
1014
+ ...sentence,
1015
+ status: "bad-citation",
1016
+ checks: [],
1017
+ missing: badCites.map((n) => `[${n}]`)
1018
+ };
1019
+ }
1020
+ if (claims.length === 0) {
1021
+ return {
1022
+ ...sentence,
1023
+ status: sentence.cites.length > 0 ? "cited" : "non-factual",
1024
+ checks: [],
1025
+ missing: []
1026
+ };
1027
+ }
1028
+ if (opaque.length > 0) return { ...sentence, status: "cited", checks: [], missing: [] };
1029
+ const holds = (sources) => {
1030
+ const checks2 = checkAgainst(claims, sources.join("\n"));
1031
+ return checks2.every((c) => c.found) && detachedNumbers(claims, sources, sentence.text).length === 0 ? checks2 : null;
1032
+ };
1033
+ const given = ctx.given ? [ctx.given] : [];
1034
+ if (sentence.cites.length > 0) {
1035
+ const checks2 = holds([...sentence.cites.map((n) => ctx.normalized.get(n) ?? ""), ...given]);
1036
+ if (checks2) return { ...sentence, status: "supported", checks: checks2, missing: [] };
1037
+ } else if (ctx.given) {
1038
+ const checks2 = holds(given);
1039
+ if (checks2) return { ...sentence, status: "supported", checks: checks2, missing: [] };
1040
+ }
1041
+ const checks = checkAgainst(claims, ctx.everything);
1042
+ const absent = checks.filter((c) => !c.found).map((c) => c.value);
1043
+ const missing = absent.length > 0 ? absent : detachedNumbers(claims, ctx.sources, sentence.text);
1044
+ if (missing.length === 0) return { ...sentence, status: "unattributed", checks, missing };
1045
+ return {
1046
+ ...sentence,
1047
+ status: sentence.cites.length > 0 ? "unsupported" : "uncited",
1048
+ checks,
1049
+ missing
1050
+ };
1051
+ }
1052
+ function groundText(markdown, evidence, options = {}) {
1053
+ const ctx = groundContext(new Map(evidence.map((item) => [item.n, item])), options);
1054
+ const sentences = citedSentences(markdown).map((s) => groundWith(ctx, s));
1055
+ const counts = {
1056
+ "non-factual": 0,
1057
+ cited: 0,
1058
+ supported: 0,
1059
+ unattributed: 0,
1060
+ uncited: 0,
1061
+ "bad-citation": 0,
1062
+ unsupported: 0
1063
+ };
1064
+ for (const s of sentences) counts[s.status]++;
1065
+ return { sentences, counts };
1066
+ }
1067
+ function isBlockingGroundingProblem(sentence) {
1068
+ if (sentence.status === "bad-citation") return true;
1069
+ if (sentence.checks.some((check) => !check.found && check.kind !== "name")) return true;
1070
+ return sentence.missing.some((detail) => /^(?:1\d{3}|20\d{2}) next to /.test(detail));
1071
+ }
1072
+ function describeGroundingProblems(problems, max = 8) {
1073
+ const lines = problems.slice(0, max).map((s) => {
1074
+ const quoted = `"${s.text.length > 160 ? `${s.text.slice(0, 157)}\u2026` : s.text}"`;
1075
+ if (s.status === "bad-citation")
1076
+ return `- ${quoted} cites ${s.missing.join(", ")}, which is not in the evidence list.`;
1077
+ const details = s.missing.map((m) => `"${m}"`).join(", ");
1078
+ if (s.status === "uncited")
1079
+ return `- ${quoted} cites nothing, and no evidence shows ${details}.`;
1080
+ return `- ${quoted}: ${details} not found in ${s.cites.map((n) => `[${n}]`).join(", ")} or any other evidence.`;
1081
+ });
1082
+ if (problems.length > max) lines.push(`- \u2026and ${problems.length - max} more.`);
1083
+ return lines.join("\n");
1084
+ }
1085
+
631
1086
  // ../core/src/checks/workspace-exists.ts
632
1087
  function createCitedPathChecker(ws) {
633
1088
  let listing = null;
@@ -658,6 +1113,204 @@ function citedPathKey(p) {
658
1113
  return cleanCitedPath(p).toLowerCase();
659
1114
  }
660
1115
 
1116
+ // ../core/src/checks/claims.ts
1117
+ var REFERENCES_HEADING = /^(#{1,6})\s*(?:sources|references|citations|bibliography|works cited|sources cited)\b/i;
1118
+ var REFERENCE_LINE = /^\s*(?:[-*+]\s*)?(?:\[(\d{1,3})\]|(\d{1,3})[.)])\s*:?\s*(.+)$/;
1119
+ var INLINE_SOURCE = /\((?:source|sources|src)\s*:\s*([^)]+)\)/gi;
1120
+ var HAS_INLINE_SOURCE = /\((?:source|sources|src)\s*:/i;
1121
+ var BRACKETED_PATH = /\[((?:[\w.-]+\/)*[\w.-]+\.[a-z][a-z0-9]{0,5})\](?!\()/gi;
1122
+ var URL_LIKE = /^(?:[a-z][\w+.-]*:\/\/|mailto:)/i;
1123
+ var MAX_FOLDER_FILES = 50;
1124
+ var TEXT_FILE = /\.(?:md|markdown|txt|csv|tsv|json|ya?ml|html?|xml|log|rst)$/i;
1125
+ var BINARY_DOCUMENT = /\.(?:pdf|docx?|pptx?|xlsx?|odt|odp|ods|rtf|epub)$/i;
1126
+ function refFromLine(text) {
1127
+ const link = /\]\(([^)\s]+)\)/.exec(text)?.[1];
1128
+ if (link) return link;
1129
+ const ticked = /`([^`\n]+)`/.exec(text)?.[1];
1130
+ if (ticked) return ticked;
1131
+ const url = /\b(?:https?:\/\/|knowledge:\/\/)[^\s)>\]]+/i.exec(text)?.[0];
1132
+ if (url) return url;
1133
+ const path = /(?:^|\s)((?:[\w.-]+\/)*[\w.-]+\.[a-z][a-z0-9]{0,5})\b/i.exec(text)?.[1];
1134
+ return path ?? null;
1135
+ }
1136
+ function splitReferences(markdown) {
1137
+ const lines = markdown.split("\n");
1138
+ const refs = /* @__PURE__ */ new Map();
1139
+ const body = [];
1140
+ let level = 0;
1141
+ for (const line of lines) {
1142
+ const heading = /^(#{1,6})\s/.exec(line);
1143
+ if (level > 0 && heading && heading[1].length <= level) level = 0;
1144
+ const references = REFERENCES_HEADING.exec(line);
1145
+ if (references) {
1146
+ level = references[1].length;
1147
+ continue;
1148
+ }
1149
+ if (level > 0) {
1150
+ const inline = [...line.matchAll(/\[(\d{1,3})\]\s*:?\s*/g)];
1151
+ if (inline.length > 1) {
1152
+ inline.forEach((m2, i) => {
1153
+ const end = inline[i + 1]?.index ?? line.length;
1154
+ const ref = refFromLine(line.slice(m2.index + m2[0].length, end));
1155
+ const n = Number(m2[1]);
1156
+ if (ref && !refs.has(n)) refs.set(n, ref);
1157
+ });
1158
+ continue;
1159
+ }
1160
+ const m = REFERENCE_LINE.exec(line);
1161
+ if (m) {
1162
+ const n = Number(m[1] ?? m[2]);
1163
+ const ref = refFromLine(m[3]);
1164
+ if (ref && !refs.has(n)) refs.set(n, ref);
1165
+ }
1166
+ continue;
1167
+ }
1168
+ body.push(line);
1169
+ }
1170
+ return { body: body.join("\n"), refs };
1171
+ }
1172
+ function numberInlineSources(body, refs) {
1173
+ const byRef = new Map([...refs].map(([n, ref]) => [ref.toLowerCase(), n]));
1174
+ let next = Math.max(0, ...refs.keys()) + 1;
1175
+ const bracketed = body.replace(BRACKETED_PATH, (_whole, path) => `(source: ${path})`);
1176
+ return bracketed.replace(INLINE_SOURCE, (_whole, list) => {
1177
+ const numbers = [];
1178
+ for (const raw of list.split(/[,;]/)) {
1179
+ const ref = refFromLine(raw) ?? raw.trim().replace(/^`+|`+$/g, "");
1180
+ if (!ref) continue;
1181
+ const key = ref.toLowerCase();
1182
+ let n = byRef.get(key);
1183
+ if (n === void 0) {
1184
+ n = next++;
1185
+ refs.set(n, ref);
1186
+ byRef.set(key, n);
1187
+ }
1188
+ numbers.push(n);
1189
+ }
1190
+ return numbers.length > 0 ? `[${numbers.join(", ")}]` : "";
1191
+ });
1192
+ }
1193
+ function declaredSources(body) {
1194
+ const out = [];
1195
+ for (const line of body.split("\n")) {
1196
+ const declared = /\b(?:sources?|data sourced from|based on)\s*:?\**\s*(.+)$/i.exec(line);
1197
+ if (!declared || HAS_INLINE_SOURCE.test(line)) continue;
1198
+ for (const m of declared[1].matchAll(/`([^`\n]+)`|\]\(([^)\s]+)\)/g)) {
1199
+ const ref = (m[1] ?? m[2] ?? "").trim();
1200
+ if (ref && !URL_LIKE.test(ref)) out.push(ref);
1201
+ }
1202
+ }
1203
+ return [...new Set(out)];
1204
+ }
1205
+ var DERIVATION_WINDOW = 3;
1206
+ function derivedFromNeighbors(sentences, i) {
1207
+ const sentence = sentences[i];
1208
+ if (sentence.status === "bad-citation") return false;
1209
+ const unfound = sentence.checks.filter((c) => !c.found && c.kind !== "name");
1210
+ if (unfound.length === 0 || unfound.some((c) => c.kind !== "number")) return false;
1211
+ const sourced = sentences.slice(Math.max(0, i - DERIVATION_WINDOW), i + DERIVATION_WINDOW + 1).flatMap((s) => s.checks.filter((c) => c.kind === "number" && c.found)).map((c) => Number(c.value)).filter(Number.isFinite);
1212
+ return unfound.every((c) => isDerivedNumber(c.value, sourced));
1213
+ }
1214
+ async function readSource(ws, ref) {
1215
+ const path = cleanCitedPath(ref);
1216
+ if (!path) return null;
1217
+ const text = await ws.read(path).catch(() => null);
1218
+ if (text !== null) return text;
1219
+ const prefix = `${path.replace(/\/+$/, "")}/`;
1220
+ const files = (await ws.list().catch(() => [])).filter((f) => cleanCitedPath(f).startsWith(prefix) && TEXT_FILE.test(f)).slice(0, MAX_FOLDER_FILES);
1221
+ if (files.length === 0) return null;
1222
+ const parts = await Promise.all(files.map((f) => ws.read(f).catch(() => null)));
1223
+ const joined = parts.filter((p) => p !== null).join("\n\n");
1224
+ return joined.length > 0 ? joined : null;
1225
+ }
1226
+ async function claimsGrounded(ws, file, opts = {}) {
1227
+ const empty = {
1228
+ counts: {
1229
+ supported: 0,
1230
+ unattributed: 0,
1231
+ unverified: 0,
1232
+ unsupported: 0,
1233
+ uncited: 0,
1234
+ badCitations: 0
1235
+ },
1236
+ sources: { read: [], missing: [], unverifiable: [] },
1237
+ problems: []
1238
+ };
1239
+ const content = await ws.read(file);
1240
+ if (content === null) {
1241
+ return { ...empty, ok: false, detail: `${file} not found \u2014 write the deliverable first.` };
1242
+ }
1243
+ const { body, refs } = splitReferences(content);
1244
+ const text = numberInlineSources(body, refs);
1245
+ const evidence = [];
1246
+ const opaque = /* @__PURE__ */ new Set();
1247
+ const read = [];
1248
+ const missing = [];
1249
+ const unverifiable = [];
1250
+ for (const [n, ref] of refs) {
1251
+ if (URL_LIKE.test(ref) || BINARY_DOCUMENT.test(ref)) {
1252
+ opaque.add(n);
1253
+ unverifiable.push(ref);
1254
+ continue;
1255
+ }
1256
+ const source = await readSource(ws, ref);
1257
+ if (source === null) {
1258
+ missing.push(ref);
1259
+ continue;
1260
+ }
1261
+ evidence.push({ n, text: source, ref });
1262
+ read.push(ref);
1263
+ }
1264
+ let extra = Math.max(0, ...refs.keys()) + 1;
1265
+ for (const ref of [...opts.sources ?? [], ...declaredSources(body)]) {
1266
+ if (refs.size > 0 && [...refs.values()].some((r) => r.toLowerCase() === ref.toLowerCase())) {
1267
+ continue;
1268
+ }
1269
+ const source = await readSource(ws, ref);
1270
+ if (source === null) continue;
1271
+ evidence.push({ n: extra++, text: source, ref });
1272
+ read.push(ref);
1273
+ }
1274
+ const grounding = groundText(text, evidence, {
1275
+ opaque: (n) => opaque.has(n),
1276
+ ...opts.given ? { given: opts.given } : {}
1277
+ });
1278
+ const blocking = grounding.sentences.filter(
1279
+ (s, i) => (s.status === "unsupported" || s.status === "uncited" || s.status === "bad-citation") && isBlockingGroundingProblem(s) && !derivedFromNeighbors(grounding.sentences, i)
1280
+ );
1281
+ const count = (status) => blocking.filter((s) => s.status === status).length;
1282
+ const counts = {
1283
+ supported: grounding.counts.supported,
1284
+ unattributed: grounding.counts.unattributed,
1285
+ unverified: grounding.counts.cited,
1286
+ unsupported: count("unsupported"),
1287
+ uncited: count("uncited"),
1288
+ badCitations: count("bad-citation")
1289
+ };
1290
+ const ok = counts.unsupported <= (opts.maxUnsupported ?? 0) && counts.badCitations <= (opts.maxBadCitations ?? 0) && counts.uncited <= (opts.maxUncited ?? 0);
1291
+ const problems = describeGroundingProblems(blocking).split("\n").filter(Boolean);
1292
+ const sources = { read, missing, unverifiable };
1293
+ if (ok) {
1294
+ const unchecked = unverifiable.length > 0 ? ` (+${unverifiable.length} URL source(s) not checked offline)` : "";
1295
+ return {
1296
+ ok,
1297
+ detail: `${file}: ${counts.supported} sentence(s) with checkable facts are supported by their sources${unchecked}.`,
1298
+ counts,
1299
+ sources,
1300
+ problems
1301
+ };
1302
+ }
1303
+ const missingNote = missing.length > 0 ? ` Cited sources that do not exist: ${missing.slice(0, 5).map((m) => `\`${m}\``).join(", ")}.` : "";
1304
+ return {
1305
+ ok,
1306
+ detail: `${file} states facts its sources do not show \u2014 look each one up in the cited source, correct it, or remove it:
1307
+ ${problems.join("\n")}${missingNote}`,
1308
+ counts,
1309
+ sources,
1310
+ problems
1311
+ };
1312
+ }
1313
+
661
1314
  // ../core/src/checks/files.ts
662
1315
  async function fileMinBytes(ws, file, bytes, trim = false) {
663
1316
  const content = await ws.read(file);
@@ -1930,7 +2583,7 @@ function candidateSums(run, breaks) {
1930
2583
  }
1931
2584
  return sums.length > 0 ? sums : null;
1932
2585
  }
1933
- var MONTHS = {
2586
+ var MONTHS2 = {
1934
2587
  january: 1,
1935
2588
  jan: 1,
1936
2589
  february: 2,
@@ -1956,7 +2609,7 @@ var MONTHS = {
1956
2609
  december: 12,
1957
2610
  dec: 12
1958
2611
  };
1959
- var WEEKDAYS = {
2612
+ var WEEKDAYS2 = {
1960
2613
  sunday: 0,
1961
2614
  sun: 0,
1962
2615
  monday: 1,
@@ -2023,13 +2676,13 @@ function utcDay(year, month, day) {
2023
2676
  function dateHits(text) {
2024
2677
  const hits = [];
2025
2678
  const seen = /* @__PURE__ */ new Set();
2026
- const weekdayOf = (w) => w ? WEEKDAYS[w.toLowerCase().replace(/\.$/, "")] ?? null : null;
2679
+ const weekdayOf = (w) => w ? WEEKDAYS2[w.toLowerCase().replace(/\.$/, "")] ?? null : null;
2027
2680
  for (const m of text.matchAll(US_DATE_RE)) {
2028
2681
  seen.add(m.index);
2029
2682
  hits.push({
2030
2683
  raw: m[0],
2031
2684
  weekday: weekdayOf(m[1]),
2032
- month: MONTHS[m[2].toLowerCase()],
2685
+ month: MONTHS2[m[2].toLowerCase()],
2033
2686
  day: Number(m[3]),
2034
2687
  year: m[4] ? Number(m[4]) : null
2035
2688
  });
@@ -2040,7 +2693,7 @@ function dateHits(text) {
2040
2693
  raw: m[0],
2041
2694
  weekday: weekdayOf(m[1]),
2042
2695
  day: Number(m[2]),
2043
- month: MONTHS[m[3].toLowerCase()],
2696
+ month: MONTHS2[m[3].toLowerCase()],
2044
2697
  year: m[4] ? Number(m[4]) : null
2045
2698
  });
2046
2699
  }
@@ -2764,6 +3417,7 @@ export {
2764
3417
  checkFigures,
2765
3418
  citationsResolve,
2766
3419
  citedPathKey,
3420
+ claimsGrounded,
2767
3421
  cleanCitedPath,
2768
3422
  codebaseReviewReport,
2769
3423
  containsPattern,
package/dist/page.d.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  * The runtime object is injected server-side by the daemon
6
6
  * (`packages/service/src/http/routes/page-api-shim.ts` splices the shim
7
7
  * into every `text/html` response served from the `type` preview source),
8
- * so pages never bundle an implementation — this module exists so gilde
8
+ * so hosted pages need no bundled implementation (the demo publisher/exporter supplies the same
9
+ * components and fonts) — this module exists so gilde
9
10
  * page authors and the host UI relay share one contract. The postMessage
10
11
  * envelope behind it is validated by the zod schemas in
11
12
  * `@bendyline/gezel` (`packages/core/src/schemas/page-bridge.ts`); the
@@ -24,8 +25,8 @@
24
25
  * and `data.*` travel as same-origin fetches against the head API under
25
26
  * the visitor's cookie; `data.watch` polls; `refresh()` reloads. The
26
27
  * page still never sees a credential.
27
- * - `demo` — a raw file opened outside gezel entirely. The real shim is
28
- * never present there; gilde ships a paste-in stub that defines
28
+ * - `demo` — a published preview or exported offline page. The shared demo
29
+ * bootstrap defines
29
30
  * `window.gezel` only when the real one is absent.
30
31
  *
31
32
  * Guard accordingly: `if (window.gezel) { ... }`.
@@ -157,11 +158,33 @@ interface GezelPageWatchOptions {
157
158
  intervalMs?: number;
158
159
  }
159
160
  /**
160
- * Read-only access to the project's files, scoped to what the page's
161
+ * Read access to the project's files, scoped to what the page's
161
162
  * manifest declared readable. Out-of-scope paths reject with code
162
- * `'not-allowed'`; writes happen through {@link GezelPageToolsApi} only.
163
+ * `'not-allowed'`. Uploads use separately declared import destinations;
164
+ * other writes happen through {@link GezelPageToolsApi}.
163
165
  */
164
166
  interface GezelPageDataApi {
167
+ /** Explicit manifest destinations and current workspace write availability. */
168
+ importTargets(): Promise<GezelImportTarget[]>;
169
+ /** Copies selected files, keeping both on name conflicts. Results include partial failures.
170
+ * Embedded desktop only; demo adapters keep files in memory. Maximum 100 files/batch,
171
+ * 256 MiB/file (destinations can lower this). Cancellation does not undo completed files. */
172
+ importFiles(files: Iterable<File>, opts: {
173
+ target: string;
174
+ signal?: AbortSignal;
175
+ onProgress?: (progress: {
176
+ completed: number;
177
+ total: number;
178
+ name: string;
179
+ }) => void;
180
+ }): Promise<GezelImportResult[]>;
181
+ /**
182
+ * Open a declared file in Gezel's existing file viewer (CSV table,
183
+ * spreadsheet, document, etc.). Checks the manifest's read scope and
184
+ * file existence before navigating. Embedded mode only; rejects with
185
+ * 'unavailable' in standalone browser and serve modes.
186
+ */
187
+ open(path: string, opts?: GezelPageSourceOptions): Promise<void>;
165
188
  /**
166
189
  * Read one file. Resolves to a string for `'text'`, a parsed value for
167
190
  * `'json'`, or a `Uint8Array` for `'bytes'` (see
@@ -187,12 +210,61 @@ interface GezelPageDataApi {
187
210
  */
188
211
  url(path: string, opts?: GezelPageSourceOptions): string;
189
212
  }
213
+ /** A queryable table backed by a file/directory in the page's declared reads. */
214
+ interface GezelPageTable {
215
+ /** Stable SQL identifier issued by the host. Do not derive this from a filename. */
216
+ name: string;
217
+ title: string;
218
+ source: GezelPageReadSource;
219
+ /** Original workspace file, or the connector's artifact table directory. */
220
+ path: string;
221
+ rows: number;
222
+ columnCount: number;
223
+ updatedAt?: string;
224
+ schemaInferred: boolean;
225
+ }
226
+ interface GezelPageTableSchema {
227
+ op: 'describe';
228
+ table: GezelPageTable;
229
+ columns: Array<{
230
+ name: string;
231
+ type: 'BOOLEAN' | 'BIGINT' | 'DOUBLE' | 'VARCHAR' | 'DATE' | 'TIMESTAMP' | 'JSON';
232
+ role: 'time' | 'dimension' | 'measure' | 'identifier' | 'attribute';
233
+ description?: string;
234
+ unit?: string;
235
+ cardinalityHint?: string;
236
+ examples?: string[];
237
+ }>;
238
+ description?: string;
239
+ grain?: string;
240
+ }
241
+ interface GezelPageTableQuery {
242
+ op: 'query';
243
+ rows: Record<string, unknown>[];
244
+ columns: string[];
245
+ truncated: boolean;
246
+ limit: number;
247
+ tablesInScope: string[];
248
+ }
249
+ /** Read-only DuckDB access in embedded/serve mode on hosts with a query engine.
250
+ * Permissions are checked again on every call; no table names grant authority. */
251
+ interface GezelPageTablesApi {
252
+ list(): Promise<GezelPageTable[]>;
253
+ describe(table: string): Promise<GezelPageTableSchema>;
254
+ /** One read-only statement. Default limit 100, max 1000 rows and 1 MiB.
255
+ * `tables` can narrow the readable scope, never expand it. */
256
+ query(sql: string, opts?: {
257
+ tables?: string[];
258
+ limit?: number;
259
+ }): Promise<GezelPageTableQuery>;
260
+ }
190
261
  /** The host UI theme as seen by the page. */
191
262
  interface GezelPageTheme {
192
263
  mode: 'light' | 'dark';
193
264
  }
194
265
  /** Host UI state the page can mirror. */
195
266
  interface GezelPageUiApi {
267
+ components: GezelPageComponents;
196
268
  /** The current theme. Live — reflects the host's latest pushed value. */
197
269
  theme: GezelPageTheme;
198
270
  /**
@@ -202,6 +274,58 @@ interface GezelPageUiApi {
202
274
  */
203
275
  onTheme(cb: (t: GezelPageTheme) => void): () => void;
204
276
  }
277
+ interface GezelPageFile {
278
+ source?: GezelPageReadSource;
279
+ path: string;
280
+ name?: string;
281
+ size?: number;
282
+ mtime?: number;
283
+ }
284
+ interface GezelImportTarget {
285
+ id: string;
286
+ source: 'workspace';
287
+ path: string;
288
+ accept?: string[];
289
+ maxFileBytes?: number;
290
+ writable: boolean;
291
+ reason?: string;
292
+ }
293
+ type GezelImportResult = {
294
+ ok: true;
295
+ name: string;
296
+ file: GezelPageFile;
297
+ } | {
298
+ ok: false;
299
+ name: string;
300
+ error: string;
301
+ };
302
+ interface GezelFileCardOptions {
303
+ file: GezelPageFile;
304
+ variant?: 'tile' | 'row';
305
+ thumbnail?: string | false;
306
+ onActivate?: (file: GezelPageFile) => void | Promise<void>;
307
+ }
308
+ interface GezelFileAdderOptions {
309
+ target: string;
310
+ onAdded?: (files: GezelPageFile[]) => void | Promise<void>;
311
+ }
312
+ interface GezelPageComponent<T> {
313
+ element: HTMLElement;
314
+ update(options: Partial<T>): void;
315
+ destroy(): void;
316
+ }
317
+ interface GezelPageComponents {
318
+ version: 1;
319
+ fileCard(target: string | HTMLElement, options: GezelFileCardOptions): GezelPageComponent<GezelFileCardOptions>;
320
+ fileAdder(target: string | HTMLElement, options: GezelFileAdderOptions): GezelPageComponent<GezelFileAdderOptions> & {
321
+ refresh(): Promise<void>;
322
+ };
323
+ /** Present only in standalone demo mode; releases imported object URLs on reset. */
324
+ demo?: {
325
+ files(): GezelPageFile[];
326
+ reset(): void;
327
+ };
328
+ }
205
329
  /**
206
330
  * The `window.gezel` object a served project-type page codes against.
207
331
  * Installed non-writable before any page script runs; absent entirely in
@@ -214,6 +338,7 @@ interface GezelPageApi {
214
338
  tools: GezelPageToolsApi;
215
339
  /** Read and watch project files within the page's declared scope. */
216
340
  data: GezelPageDataApi;
341
+ tables: GezelPageTablesApi;
217
342
  /** Mirror host UI state (theme). */
218
343
  ui: GezelPageUiApi;
219
344
  /** Ask the host to re-serve the page (embedded); reloads the tab in browser mode. */
@@ -226,4 +351,4 @@ declare global {
226
351
  }
227
352
  }
228
353
 
229
- export { GEZEL_PAGE_API_VERSION, type GezelPageApi, type GezelPageDataApi, type GezelPageDirEntry, type GezelPageError, type GezelPageErrorCode, type GezelPageInfo, type GezelPageMode, type GezelPageReadOptions, type GezelPageReadSource, type GezelPageSourceOptions, type GezelPageTheme, type GezelPageToolReaction, type GezelPageToolResult, type GezelPageToolsApi, type GezelPageUiApi, type GezelPageWatchEvent, type GezelPageWatchOptions };
354
+ export { GEZEL_PAGE_API_VERSION, type GezelFileAdderOptions, type GezelFileCardOptions, type GezelImportResult, type GezelImportTarget, type GezelPageApi, type GezelPageComponent, type GezelPageComponents, type GezelPageDataApi, type GezelPageDirEntry, type GezelPageError, type GezelPageErrorCode, type GezelPageFile, type GezelPageInfo, type GezelPageMode, type GezelPageReadOptions, type GezelPageReadSource, type GezelPageSourceOptions, type GezelPageTable, type GezelPageTableQuery, type GezelPageTableSchema, type GezelPageTablesApi, type GezelPageTheme, type GezelPageToolReaction, type GezelPageToolResult, type GezelPageToolsApi, type GezelPageUiApi, type GezelPageWatchEvent, type GezelPageWatchOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/gezel-sdk",
3
- "version": "1.1.7",
3
+ "version": "1.1.9",
4
4
  "description": "SDK for scripts that run in the Gezel sandbox: the gezel object and the defineScript helper.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -63,7 +63,7 @@
63
63
  "!dist/**/*.map"
64
64
  ],
65
65
  "devDependencies": {
66
- "@bendyline/gezel": "1.2.7",
66
+ "@bendyline/gezel": "1.2.9",
67
67
  "tsup": "^8.5.1",
68
68
  "typescript": "^6.0.3",
69
69
  "vitest": "^4.1.10"
@@ -72,7 +72,7 @@
72
72
  "build": "tsup",
73
73
  "dev": "tsup --watch",
74
74
  "typecheck": "tsc --noEmit",
75
- "clean": "rm -rf dist .turbo",
75
+ "clean": "node ../../scripts/clean-dirs.mjs dist .turbo",
76
76
  "test": "vitest run"
77
77
  }
78
78
  }