@mulmoclaude/core 1.6.0 → 1.7.0

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.
Files changed (62) hide show
  1. package/assets/helps/google-calendar-collection.md +57 -3
  2. package/assets/helps/google.md +3 -2
  3. package/dist/calendarGrid-CaS9er8i.cjs +576 -0
  4. package/dist/calendarGrid-CaS9er8i.cjs.map +1 -0
  5. package/dist/calendarGrid-CrGxeCOG.js +397 -0
  6. package/dist/calendarGrid-CrGxeCOG.js.map +1 -0
  7. package/dist/collection/index.cjs +44 -44
  8. package/dist/collection/index.cjs.map +1 -1
  9. package/dist/collection/index.js +2 -2
  10. package/dist/collection/registry/server/index.cjs +2 -2
  11. package/dist/collection/registry/server/index.js +2 -2
  12. package/dist/collection/server/index.cjs +4 -4
  13. package/dist/collection/server/index.js +3 -3
  14. package/dist/collection-watchers/index.cjs +5 -5
  15. package/dist/collection-watchers/index.cjs.map +1 -1
  16. package/dist/collection-watchers/index.js +4 -4
  17. package/dist/{discovery--kRUWed0.cjs → discovery-DYcR83qx.cjs} +64 -53
  18. package/dist/discovery-DYcR83qx.cjs.map +1 -0
  19. package/dist/{discovery-CKR4TOX3.js → discovery-_fjsluLx.js} +43 -32
  20. package/dist/discovery-_fjsluLx.js.map +1 -0
  21. package/dist/feeds/index.cjs +4 -4
  22. package/dist/feeds/index.js +2 -2
  23. package/dist/feeds/server/index.cjs +6 -6
  24. package/dist/feeds/server/index.js +4 -4
  25. package/dist/google/apiClient.d.ts +6 -0
  26. package/dist/google/calendar.d.ts +79 -8
  27. package/dist/google/calendarPushState.d.ts +17 -0
  28. package/dist/google/collectionPush.d.ts +64 -0
  29. package/dist/google/collectionSync.d.ts +10 -0
  30. package/dist/google/index.cjs +712 -36
  31. package/dist/google/index.cjs.map +1 -1
  32. package/dist/google/index.d.ts +7 -3
  33. package/dist/google/index.js +683 -37
  34. package/dist/google/index.js.map +1 -1
  35. package/dist/google/pushDateTime.d.ts +10 -0
  36. package/dist/google/pushPlan.d.ts +73 -0
  37. package/dist/{ingestTypes-xX8VpQqh.cjs → ingestTypes-D1GQdG8e.cjs} +3 -3
  38. package/dist/{ingestTypes-xX8VpQqh.cjs.map → ingestTypes-D1GQdG8e.cjs.map} +1 -1
  39. package/dist/{ingestTypes-L59cIGgX.js → ingestTypes-XReG-li7.js} +2 -2
  40. package/dist/{ingestTypes-L59cIGgX.js.map → ingestTypes-XReG-li7.js.map} +1 -1
  41. package/dist/{promptSafety-CQ5Un4wi.js → promptSafety-C--op_6a.js} +3 -269
  42. package/dist/promptSafety-C--op_6a.js.map +1 -0
  43. package/dist/{promptSafety-DfZYNtjK.cjs → promptSafety-FD8cQn3e.cjs} +8 -358
  44. package/dist/promptSafety-FD8cQn3e.cjs.map +1 -0
  45. package/dist/remote-host/index.cjs +8 -0
  46. package/dist/remote-host/index.cjs.map +1 -1
  47. package/dist/remote-host/index.d.ts +21 -0
  48. package/dist/remote-host/index.js +8 -1
  49. package/dist/remote-host/index.js.map +1 -1
  50. package/dist/{server-D_6FLygK.js → server-BlIrtGKl.js} +4 -4
  51. package/dist/{server-D_6FLygK.js.map → server-BlIrtGKl.js.map} +1 -1
  52. package/dist/{server-gEOeV_Nv.cjs → server-l4TZ5Lbf.cjs} +21 -21
  53. package/dist/{server-gEOeV_Nv.cjs.map → server-l4TZ5Lbf.cjs.map} +1 -1
  54. package/package.json +1 -1
  55. package/dist/discovery--kRUWed0.cjs.map +0 -1
  56. package/dist/discovery-CKR4TOX3.js.map +0 -1
  57. package/dist/ids-BnTh3Hl0.cjs +0 -226
  58. package/dist/ids-BnTh3Hl0.cjs.map +0 -1
  59. package/dist/ids-s4GfmE93.js +0 -131
  60. package/dist/ids-s4GfmE93.js.map +0 -1
  61. package/dist/promptSafety-CQ5Un4wi.js.map +0 -1
  62. package/dist/promptSafety-DfZYNtjK.cjs.map +0 -1
@@ -1,4 +1,4 @@
1
- const require_ids = require("./ids-BnTh3Hl0.cjs");
1
+ const require_calendarGrid = require("./calendarGrid-CaS9er8i.cjs");
2
2
  //#region src/collection/core/actionVisible.ts
3
3
  /** Core matcher:
4
4
  * - no `when` ⇒ always true (visible);
@@ -9,7 +9,7 @@ const require_ids = require("./ids-BnTh3Hl0.cjs");
9
9
  * lacks the status. */
10
10
  function whenMatches(when, record) {
11
11
  if (!when) return true;
12
- const text = require_ids.fieldTextOrNull(record[when.field]);
12
+ const text = require_calendarGrid.fieldTextOrNull(record[when.field]);
13
13
  if (text === null) return false;
14
14
  return when.in.includes(text);
15
15
  }
@@ -62,14 +62,14 @@ function fieldVisible(field, record) {
62
62
  * doesn't resolve matches nothing" contract as the flat case. Deeper nesting
63
63
  * (`a.b.c`) makes `b.c` the column name, which no row carries → no match. */
64
64
  function viaMatches(via, item, recordId) {
65
- if (Object.hasOwn(item, via)) return require_ids.fieldTextOrNull(item[via]) === recordId;
65
+ if (Object.hasOwn(item, via)) return require_calendarGrid.fieldTextOrNull(item[via]) === recordId;
66
66
  const dot = via.indexOf(".");
67
67
  if (dot === -1) return false;
68
68
  const tableField = via.slice(0, dot);
69
69
  const refColumn = via.slice(dot + 1);
70
70
  const rows = item[tableField];
71
71
  if (!Array.isArray(rows)) return false;
72
- return rows.some((row) => require_ids.fieldTextOrNull(row?.[refColumn]) === recordId);
72
+ return rows.some((row) => require_calendarGrid.fieldTextOrNull(row?.[refColumn]) === recordId);
73
73
  }
74
74
  /** The SOURCE records whose `via` field stores `recordId` (compared as
75
75
  * strings, like every ref deref), with the optional `filter` applied —
@@ -257,7 +257,7 @@ function itemIsDone(schema, item) {
257
257
  const spec = schema.fields?.[completionField];
258
258
  if (spec?.type === "flag" && spec.where) return matchesWhere(spec.where, item);
259
259
  if (!completionDoneValues) return false;
260
- const text = require_ids.fieldTextOrNull(item[completionField]);
260
+ const text = require_calendarGrid.fieldTextOrNull(item[completionField]);
261
261
  if (text === null) return false;
262
262
  return completionDoneValues.includes(text);
263
263
  }
@@ -279,7 +279,7 @@ function completionCoveredByFieldChip(schema) {
279
279
  * equals `onValue`. The toggle stores nothing of its own, so this reads the raw
280
280
  * projected value; a non-toggle field is never checked. */
281
281
  function toggleChecked(item, field) {
282
- return field.type === "toggle" && require_ids.fieldText(item[field.field]) === field.onValue;
282
+ return field.type === "toggle" && require_calendarGrid.fieldText(item[field.field]) === field.onValue;
283
283
  }
284
284
  /** A `flag` FIELD's boolean for one row, read off the already-enriched record
285
285
  * (so a flag computed from derived/rollup inputs is correct). Strict `=== true`
@@ -305,7 +305,7 @@ function chipMatches(chip, schema, item, deriveRecord) {
305
305
  /** The record with the greatest `String(record[field])` (localeCompare) —
306
306
  * ties keep the first-seen record (stable left-to-right `reduce`). */
307
307
  function latestByField(pool, field) {
308
- return pool.reduce((latest, candidate) => require_ids.fieldText(candidate[field]).localeCompare(require_ids.fieldText(latest[field])) > 0 ? candidate : latest);
308
+ return pool.reduce((latest, candidate) => require_calendarGrid.fieldText(candidate[field]).localeCompare(require_calendarGrid.fieldText(latest[field])) > 0 ? candidate : latest);
309
309
  }
310
310
  /** Reduce `records` to the one record that decides the effective icon, per
311
311
  * `source`'s `where` filter + `from` strategy:
@@ -711,272 +711,6 @@ function deriveAll(schema, base, refRecords) {
711
711
  return enriched;
712
712
  }
713
713
  //#endregion
714
- //#region src/collection/core/calendarGrid.ts
715
- var MS_PER_DAY = 864e5;
716
- var ISO_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
717
- var TWO_DIGIT_RE = /^\d{2}$/;
718
- var CLOCK_RE = /(\d{1,2}):(\d{2})/g;
719
- var RANGE_SEP_RE = /[-–—~〜~]/;
720
- /** Minutes in a full day — the timeline's vertical extent. */
721
- var MINUTES_PER_DAY = 1440;
722
- function pad2(value) {
723
- return String(value).padStart(2, "0");
724
- }
725
- /** Canonical `YYYY-MM-DD` string for a civil date. */
726
- function ymdKey(ymd) {
727
- return `${String(ymd.year).padStart(4, "0")}-${pad2(ymd.month)}-${pad2(ymd.day)}`;
728
- }
729
- /** Strictly parse a `YYYY-MM-DD` string into a civil date, rejecting
730
- * anything that isn't a real calendar day (e.g. `2026-02-30`, `2026-13-01`).
731
- * Returns null for non-strings and malformed values so callers can route
732
- * records with no usable date into the "no date" tray rather than crash. */
733
- function parseIsoDate(value) {
734
- if (typeof value !== "string") return null;
735
- const match = ISO_DATE_RE.exec(value.trim());
736
- if (!match) return null;
737
- const year = Number(match[1]);
738
- const month = Number(match[2]);
739
- const day = Number(match[3]);
740
- const probe = new Date(Date.UTC(year, month - 1, day));
741
- if (probe.getUTCFullYear() !== year || probe.getUTCMonth() !== month - 1 || probe.getUTCDate() !== day) return null;
742
- return {
743
- year,
744
- month,
745
- day
746
- };
747
- }
748
- /** Minutes-of-day for an `HH:MM` pair, or null when out of range. */
749
- function clockToMinutes(hours, minutes) {
750
- if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;
751
- return hours * 60 + minutes;
752
- }
753
- /** Strictly parse a `YYYY-MM-DDTHH:MM` (optional `:SS`) datetime into its
754
- * civil date and minutes-of-day. Returns null for anything that isn't a real
755
- * calendar day or a valid 24h clock. */
756
- function parseIsoDateTime(value) {
757
- if (typeof value !== "string") return null;
758
- const trimmed = value.trim();
759
- const tIndex = trimmed.indexOf("T");
760
- if (tIndex === -1) return null;
761
- const ymd = parseIsoDate(trimmed.slice(0, tIndex));
762
- if (!ymd) return null;
763
- const parts = trimmed.slice(tIndex + 1).split(":");
764
- if (parts.length < 2 || parts.length > 3 || !parts.every((part) => TWO_DIGIT_RE.test(part))) return null;
765
- const minutes = clockToMinutes(Number(parts[0]), Number(parts[1]));
766
- if (minutes === null) return null;
767
- return {
768
- ymd,
769
- minutes
770
- };
771
- }
772
- /** Civil date from either a `YYYY-MM-DD` or a `YYYY-MM-DDTHH:MM` value, so the
773
- * month grid buckets date-only and datetime anchors alike. */
774
- function dateOf(value) {
775
- return parseIsoDate(value) ?? parseIsoDateTime(value)?.ymd ?? null;
776
- }
777
- /** Minutes-of-day from a datetime value, or null for date-only / invalid. */
778
- function timeOf(value) {
779
- return parseIsoDateTime(value)?.minutes ?? null;
780
- }
781
- /** Parse a free-form time-string field into start/end minutes-of-day.
782
- * Handles the common shapes in user data:
783
- * "14:00-17:00" → { start: 840, end: 1020 } (range → block)
784
- * "17:00-" → { start: 1020, end: null } (open end → single line)
785
- * "16:30" → { start: 990, end: null } (point in time → single line)
786
- * "終日" / "" → null (no clock → all-day)
787
- * Returns null when no clock token is parseable. */
788
- function parseTimeRange(value) {
789
- if (typeof value !== "string") return null;
790
- const text = value.trim();
791
- if (!text) return null;
792
- const tokens = [...text.matchAll(CLOCK_RE)];
793
- if (tokens.length === 0) return null;
794
- const minutesOf = (match) => clockToMinutes(Number(match[1]), Number(match[2]));
795
- if (!RANGE_SEP_RE.test(text)) {
796
- const startMin = minutesOf(tokens[0]);
797
- return startMin === null ? null : {
798
- startMin,
799
- endMin: null
800
- };
801
- }
802
- const sepIndex = text.search(RANGE_SEP_RE);
803
- let startMin = null;
804
- let endMin = null;
805
- for (const token of tokens) if ((token.index ?? 0) < sepIndex) startMin = minutesOf(token);
806
- else endMin = minutesOf(token);
807
- if (startMin === null) return null;
808
- return {
809
- startMin,
810
- endMin
811
- };
812
- }
813
- function ymdToUtcMs(ymd) {
814
- return Date.UTC(ymd.year, ymd.month - 1, ymd.day);
815
- }
816
- function utcMsToYmd(epochMs) {
817
- const date = new Date(epochMs);
818
- return {
819
- year: date.getUTCFullYear(),
820
- month: date.getUTCMonth() + 1,
821
- day: date.getUTCDate()
822
- };
823
- }
824
- /** Chronological comparison: negative if `left` precedes `right`, 0 if the
825
- * same day, positive if after. */
826
- function compareYmd(left, right) {
827
- return ymdToUtcMs(left) - ymdToUtcMs(right);
828
- }
829
- /** True iff `day` falls within the inclusive span `[span.start, span.end]`. */
830
- function spanCoversDay(span, day) {
831
- return compareYmd(span.start, day) <= 0 && compareYmd(day, span.end) <= 0;
832
- }
833
- /** Build the 6×7 (42-cell) grid for the given month, including the
834
- * leading/trailing days of the adjacent months so every week is full.
835
- * `month` is 1-12. `weekStartsOn` is 0 (Sunday) … 6 (Saturday). */
836
- function buildMonthGrid(year, month, weekStartsOn = 0) {
837
- const lead = (new Date(Date.UTC(year, month - 1, 1)).getUTCDay() - weekStartsOn + 7) % 7;
838
- const startMs = Date.UTC(year, month - 1, 1) - lead * MS_PER_DAY;
839
- const cells = [];
840
- for (let i = 0; i < 42; i++) {
841
- const ymd = utcMsToYmd(startMs + i * MS_PER_DAY);
842
- cells.push({
843
- ymd,
844
- inMonth: ymd.year === year && ymd.month === month,
845
- key: ymdKey(ymd)
846
- });
847
- }
848
- return cells;
849
- }
850
- /** Resolve a record's calendar span from its date/datetime fields. Returns
851
- * null when the anchor date is missing/invalid (→ the caller's "no date"
852
- * tray). An end date that is missing, invalid, or earlier than the start
853
- * collapses to a single-day span — never an inverted range.
854
- *
855
- * Times for the day (time-allocation) view come from, in priority order:
856
- * 1. the clock on a `datetime` anchor/end value, else
857
- * 2. `timeField` — a separate free-form time-string column (e.g. "14:00-17:00").
858
- * A record with no resolvable clock has `startMin === endMin === null`. */
859
- function recordSpan(item, anchorField, endField, timeField) {
860
- const startRaw = item[anchorField];
861
- const start = dateOf(startRaw);
862
- if (!start) return null;
863
- let end = start;
864
- let startMin = timeOf(startRaw);
865
- let endMin = null;
866
- if (endField) {
867
- const endRaw = item[endField];
868
- const parsedEnd = dateOf(endRaw);
869
- if (parsedEnd && compareYmd(parsedEnd, start) >= 0) {
870
- end = parsedEnd;
871
- endMin = timeOf(endRaw);
872
- }
873
- }
874
- if (timeField && startMin === null && endMin === null) {
875
- const range = parseTimeRange(item[timeField]);
876
- if (range) ({startMin, endMin} = range);
877
- }
878
- return {
879
- item,
880
- start,
881
- end,
882
- startMin,
883
- endMin
884
- };
885
- }
886
- /** Split records into those that land on the calendar (with their spans)
887
- * and those with no usable anchor date (the "no date" tray). Spans are
888
- * sorted by start day so same-day stacking is stable across renders. */
889
- function bucketRecords(items, anchorField, endField, timeField) {
890
- const spans = [];
891
- const noDate = [];
892
- for (const item of items) {
893
- const span = recordSpan(item, anchorField, endField, timeField);
894
- if (span) spans.push(span);
895
- else noDate.push(item);
896
- }
897
- spans.sort((left, right) => compareYmd(left.start, right.start));
898
- return {
899
- spans,
900
- noDate
901
- };
902
- }
903
- /** Project a record's span onto a single day for the time-allocation view, or
904
- * null when the span doesn't cover that day. */
905
- function daySlice(span, day) {
906
- if (!spanCoversDay(span, day)) return null;
907
- const hasStart = span.startMin !== null;
908
- const hasEnd = span.endMin !== null;
909
- if (!hasStart && !hasEnd) return {
910
- kind: "allDay",
911
- startMin: 0,
912
- endMin: MINUTES_PER_DAY,
913
- bleedsBefore: false,
914
- bleedsAfter: false
915
- };
916
- const singleDay = compareYmd(span.start, span.end) === 0;
917
- const isStartDay = compareYmd(day, span.start) === 0;
918
- const isEndDay = compareYmd(day, span.end) === 0;
919
- if (singleDay && hasStart && !hasEnd) return {
920
- kind: "line",
921
- startMin: span.startMin,
922
- endMin: span.startMin,
923
- bleedsBefore: false,
924
- bleedsAfter: false
925
- };
926
- const startMin = isStartDay && hasStart ? span.startMin : 0;
927
- const endMin = isEndDay && hasEnd ? span.endMin : MINUTES_PER_DAY;
928
- if (singleDay && endMin <= startMin) return {
929
- kind: "line",
930
- startMin,
931
- endMin: startMin,
932
- bleedsBefore: false,
933
- bleedsAfter: false
934
- };
935
- return {
936
- kind: "block",
937
- startMin,
938
- endMin,
939
- bleedsBefore: !isStartDay,
940
- bleedsAfter: !isEndDay
941
- };
942
- }
943
- function assignLanes(blocks) {
944
- const order = [...blocks.keys()].sort((left, right) => blocks[left].startMin - blocks[right].startMin || blocks[left].endMin - blocks[right].endMin);
945
- const result = blocks.map(() => ({
946
- lane: 0,
947
- lanes: 1
948
- }));
949
- let cluster = [];
950
- let clusterEnd = Number.NEGATIVE_INFINITY;
951
- const laneEnds = [];
952
- const flush = () => {
953
- for (const index of cluster) result[index].lanes = laneEnds.length;
954
- cluster = [];
955
- laneEnds.length = 0;
956
- clusterEnd = Number.NEGATIVE_INFINITY;
957
- };
958
- for (const index of order) {
959
- const block = blocks[index];
960
- if (cluster.length > 0 && block.startMin >= clusterEnd) flush();
961
- let lane = laneEnds.findIndex((end) => end <= block.startMin);
962
- if (lane === -1) {
963
- lane = laneEnds.length;
964
- laneEnds.push(block.endMin);
965
- } else laneEnds[lane] = block.endMin;
966
- result[index].lane = lane;
967
- cluster.push(index);
968
- clusterEnd = Math.max(clusterEnd, block.endMin);
969
- }
970
- flush();
971
- return result;
972
- }
973
- /** Month label key inputs — returns the 1st of the month as a `Date` so the
974
- * component can feed it to `Intl.DateTimeFormat(locale, …)` for a localized
975
- * "April 2026" header without this module taking a locale dependency. */
976
- function monthAnchorDate(year, month) {
977
- return new Date(Date.UTC(year, month - 1, 1));
978
- }
979
- //#endregion
980
714
  //#region src/collection/core/promptSafety.ts
981
715
  /** Max chars kept — the first batch of a validation issue is enough to act on. */
982
716
  var DEFANG_MAX_LEN = 200;
@@ -984,12 +718,6 @@ function defangForPrompt(value) {
984
718
  return value.replace(/[<>]/g, "").replace(/`/g, "'").replace(/\$\{/g, "$ {").replace(/\s+/g, " ").slice(0, DEFANG_MAX_LEN);
985
719
  }
986
720
  //#endregion
987
- Object.defineProperty(exports, "MINUTES_PER_DAY", {
988
- enumerable: true,
989
- get: function() {
990
- return MINUTES_PER_DAY;
991
- }
992
- });
993
721
  Object.defineProperty(exports, "actionVisible", {
994
722
  enumerable: true,
995
723
  get: function() {
@@ -1002,30 +730,12 @@ Object.defineProperty(exports, "agentActionRunKey", {
1002
730
  return agentActionRunKey;
1003
731
  }
1004
732
  });
1005
- Object.defineProperty(exports, "assignLanes", {
1006
- enumerable: true,
1007
- get: function() {
1008
- return assignLanes;
1009
- }
1010
- });
1011
733
  Object.defineProperty(exports, "backlinkRows", {
1012
734
  enumerable: true,
1013
735
  get: function() {
1014
736
  return backlinkRows;
1015
737
  }
1016
738
  });
1017
- Object.defineProperty(exports, "bucketRecords", {
1018
- enumerable: true,
1019
- get: function() {
1020
- return bucketRecords;
1021
- }
1022
- });
1023
- Object.defineProperty(exports, "buildMonthGrid", {
1024
- enumerable: true,
1025
- get: function() {
1026
- return buildMonthGrid;
1027
- }
1028
- });
1029
739
  Object.defineProperty(exports, "chipMatches", {
1030
740
  enumerable: true,
1031
741
  get: function() {
@@ -1038,30 +748,12 @@ Object.defineProperty(exports, "coerceNumeric", {
1038
748
  return coerceNumeric;
1039
749
  }
1040
750
  });
1041
- Object.defineProperty(exports, "compareYmd", {
1042
- enumerable: true,
1043
- get: function() {
1044
- return compareYmd;
1045
- }
1046
- });
1047
751
  Object.defineProperty(exports, "completionCoveredByFieldChip", {
1048
752
  enumerable: true,
1049
753
  get: function() {
1050
754
  return completionCoveredByFieldChip;
1051
755
  }
1052
756
  });
1053
- Object.defineProperty(exports, "dateOf", {
1054
- enumerable: true,
1055
- get: function() {
1056
- return dateOf;
1057
- }
1058
- });
1059
- Object.defineProperty(exports, "daySlice", {
1060
- enumerable: true,
1061
- get: function() {
1062
- return daySlice;
1063
- }
1064
- });
1065
757
  Object.defineProperty(exports, "defangForPrompt", {
1066
758
  enumerable: true,
1067
759
  get: function() {
@@ -1110,48 +802,18 @@ Object.defineProperty(exports, "matchesWhere", {
1110
802
  return matchesWhere;
1111
803
  }
1112
804
  });
1113
- Object.defineProperty(exports, "monthAnchorDate", {
1114
- enumerable: true,
1115
- get: function() {
1116
- return monthAnchorDate;
1117
- }
1118
- });
1119
805
  Object.defineProperty(exports, "ownProp", {
1120
806
  enumerable: true,
1121
807
  get: function() {
1122
808
  return ownProp;
1123
809
  }
1124
810
  });
1125
- Object.defineProperty(exports, "parseIsoDate", {
1126
- enumerable: true,
1127
- get: function() {
1128
- return parseIsoDate;
1129
- }
1130
- });
1131
- Object.defineProperty(exports, "parseIsoDateTime", {
1132
- enumerable: true,
1133
- get: function() {
1134
- return parseIsoDateTime;
1135
- }
1136
- });
1137
- Object.defineProperty(exports, "parseTimeRange", {
1138
- enumerable: true,
1139
- get: function() {
1140
- return parseTimeRange;
1141
- }
1142
- });
1143
811
  Object.defineProperty(exports, "projectBacklinkRow", {
1144
812
  enumerable: true,
1145
813
  get: function() {
1146
814
  return projectBacklinkRow;
1147
815
  }
1148
816
  });
1149
- Object.defineProperty(exports, "recordSpan", {
1150
- enumerable: true,
1151
- get: function() {
1152
- return recordSpan;
1153
- }
1154
- });
1155
817
  Object.defineProperty(exports, "resolveIcon", {
1156
818
  enumerable: true,
1157
819
  get: function() {
@@ -1176,12 +838,6 @@ Object.defineProperty(exports, "selectDynamicRecord", {
1176
838
  return selectDynamicRecord;
1177
839
  }
1178
840
  });
1179
- Object.defineProperty(exports, "spanCoversDay", {
1180
- enumerable: true,
1181
- get: function() {
1182
- return spanCoversDay;
1183
- }
1184
- });
1185
841
  Object.defineProperty(exports, "toggleChecked", {
1186
842
  enumerable: true,
1187
843
  get: function() {
@@ -1218,11 +874,5 @@ Object.defineProperty(exports, "whenMatches", {
1218
874
  return whenMatches;
1219
875
  }
1220
876
  });
1221
- Object.defineProperty(exports, "ymdKey", {
1222
- enumerable: true,
1223
- get: function() {
1224
- return ymdKey;
1225
- }
1226
- });
1227
877
 
1228
- //# sourceMappingURL=promptSafety-DfZYNtjK.cjs.map
878
+ //# sourceMappingURL=promptSafety-FD8cQn3e.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promptSafety-FD8cQn3e.cjs","names":[],"sources":["../src/collection/core/actionVisible.ts","../src/collection/core/backlinks.ts","../src/collection/core/linkTargets.ts","../src/collection/core/where.ts","../src/collection/core/completion.ts","../src/collection/core/dynamicIcon.ts","../src/collection/core/derivedFormula.ts","../src/collection/core/ownProp.ts","../src/collection/core/deriveAll.ts","../src/collection/core/promptSafety.ts"],"sourcesContent":["// Pure `when`-predicate visibility helpers for schema-driven\n// collections — used both for action buttons and for conditionally\n// shown fields. Kept as their own module (no Vue) so CollectionView\n// can stay thin and the match semantics are pinned by unit tests.\n// Domain-free: the host compares the stringified record value against\n// the allowed set with no knowledge of what the field means.\n\nimport { fieldTextOrNull } from \"./fieldText\";\n\n/** A `when` predicate: render only when the open record's `field`\n * (stringified) is one of `in`. Shared shape for action buttons and\n * conditionally visible fields. */\nexport interface WhenPredicate {\n field: string;\n in: string[];\n}\n\n/** Core matcher:\n * - no `when` ⇒ always true (visible);\n * - otherwise true only when `record[when.field]` is present and its\n * stringified value is one of `when.in`.\n * A missing/undefined/null field is treated as \"not a match\"\n * (hidden), so a status-gated target never shows on a record that\n * lacks the status. */\nexport function whenMatches(when: WhenPredicate | undefined, record: Record<string, unknown>): boolean {\n if (!when) return true;\n // `fieldTextOrNull` rather than `String(...)`: an array/object field would\n // stringify to \"[object Object]\" and could match a `when.in` entry by\n // accident. No text ⇒ no match, same as an absent field.\n const text = fieldTextOrNull(record[when.field]);\n if (text === null) return false;\n return when.in.includes(text);\n}\n\n/** Minimal shape this helper needs from an action — the optional state\n * gate, whichever name its kind uses: `when` on the seeded kinds\n * (chat/agent), `require` on mutate. Accepts the full CollectionAction\n * union (each variant declares at most one of the two). */\nexport interface ActionWithWhen {\n when?: WhenPredicate;\n require?: WhenPredicate;\n}\n\n/** True when the action's button should render against `record` — and,\n * server-side, whether it may RUN (visibility is the authorization\n * rule, for every kind). */\nexport function actionVisible(action: ActionWithWhen, record: Record<string, unknown>): boolean {\n return whenMatches(action.when ?? action.require, record);\n}\n\n/** The run key naming one in-flight `kind: \"agent\"` action button —\n * written by the server's dispatch guard, read back by the client from\n * the detail response's `runningActions` to drive the spinner. ONE\n * builder (isomorphic) so the two sides can't drift. Collection-level\n * and per-record actions live in distinct namespaces so an id collision\n * between `actions` and `collectionActions` can't alias. */\nexport function agentActionRunKey(actionId: string, itemId?: string): string {\n return itemId === undefined ? `collection/${actionId}` : `item/${itemId}/${actionId}`;\n}\n\n/** Minimal shape this helper needs from a field spec — just its\n * optional `when` predicate. Accepts the full FieldSpec too. */\nexport interface FieldWithWhen {\n when?: WhenPredicate;\n}\n\n/** True when the field should render against `record`. A field with\n * no `when` is always shown; otherwise it's shown only when the\n * record matches (e.g. hide a rating field until `visited` is true).\n * Purely presentational — a hidden field's stored value is never\n * altered, so toggling the gate back on restores it. */\nexport function fieldVisible(field: FieldWithWhen, record: Record<string, unknown>): boolean {\n return whenMatches(field.when, record);\n}\n","// Pure resolution for `backlinks` fields (plan step ② of\n// plans/done/collection-ontology.md): the display-only reverse side of `ref`.\n// Both the server enrichment (`server/derive.ts`) and the client detail\n// view derive the row set through THESE helpers, so the LLM (getItems)\n// and the user (record panel) always see the same rows — the same\n// single-implementation rule `deriveAll` follows for formulas. No zod,\n// no I/O; safe for the browser barrel.\n\nimport { whenMatches } from \"./actionVisible\";\nimport { fieldTextOrNull } from \"./fieldText\";\nimport type { CollectionFieldSpec, CollectionItem } from \"./schema\";\n\n/** The `backlinks` member of the field-spec union. */\nexport type BacklinksFieldSpec = Extract<CollectionFieldSpec, { type: \"backlinks\" }>;\n\n/** Does `item` reference `recordId` through `via`? Three shapes, tried in\n * order so the dotted form never regresses an existing flat key:\n *\n * - Exact key (`via` is an own property of `item`): the field holds the id\n * directly — compared as text, like every ref deref. This is checked FIRST\n * because `schemaZ` accepts any field name (`z.string()`), so a field\n * literally named `\"client.id\"` keeps its pre-nesting flat-match behaviour\n * instead of being reinterpreted as a table path. A field holding an\n * array/object has no id to compare, so it matches nothing (rather than\n * testing \"[object Object]\" against the record id).\n * - Nested ref (`via: \"<tableField>.<refColumn>\"`, split on the FIRST `.`,\n * only when no exact key exists): the source stores its ref one level down,\n * inside a `table` field's rows (the ontology scanner advertises these as\n * `${key}.${subKey}`). Matches when `item[tableField]` is an array and ANY\n * row's `refColumn` derefs to `recordId`. A record referencing the target in\n * several rows still matches once — the caller filters over source records,\n * each yielded at most once.\n * - No dot and no such key: matches nothing.\n *\n * Fail-soft throughout: a dotted `via` whose table field is absent / non-array,\n * or whose rows lack the column, matches nothing — the same \"a `via` that\n * doesn't resolve matches nothing\" contract as the flat case. Deeper nesting\n * (`a.b.c`) makes `b.c` the column name, which no row carries → no match. */\nexport function viaMatches(via: string, item: CollectionItem, recordId: string): boolean {\n if (Object.hasOwn(item, via)) return fieldTextOrNull(item[via]) === recordId;\n const dot = via.indexOf(\".\");\n if (dot === -1) return false;\n const tableField = via.slice(0, dot);\n const refColumn = via.slice(dot + 1);\n const rows = item[tableField];\n if (!Array.isArray(rows)) return false;\n return rows.some((row) => fieldTextOrNull((row as CollectionItem)?.[refColumn]) === recordId);\n}\n\n/** The SOURCE records whose `via` field stores `recordId` (compared as\n * strings, like every ref deref), with the optional `filter` applied —\n * in the source items' given order. `via` may be a top-level column or a\n * `<tableField>.<refColumn>` path into a `table` field's rows (see\n * {@link viaMatches}). Fail-soft by construction: a `via` that doesn't\n * resolve on the source records simply matches nothing.\n * Callers pass DERIVED source records, so a `filter`/`display` on a\n * derived column works when its formula is SELF-CONTAINED (an invoice\n * `total` = sum over its own line items); a source column that derefs\n * yet another collection stays absent — the same each-record-derives-\n * against-itself rule ref targets follow. */\nexport function backlinkRows(spec: Pick<BacklinksFieldSpec, \"via\" | \"filter\">, recordId: string, sourceItems: CollectionItem[]): CollectionItem[] {\n if (!recordId) return [];\n return sourceItems.filter((item) => viaMatches(spec.via, item, recordId) && whenMatches(spec.filter, item));\n}\n\n/** Project one backlink row to the keys consumers surface: the source\n * collection's primaryKey (rows must stay addressable — it's the link\n * target) plus the declared `display` columns. Keys the row doesn't\n * carry are simply absent, mirroring `projectFields` in getItems. */\nexport function projectBacklinkRow(row: CollectionItem, display: readonly string[], primaryKey: string): CollectionItem {\n const keys = display.includes(primaryKey) ? display : [primaryKey, ...display];\n // Own-property only (matches `viaMatches` above): a display column named\n // `toString` must be absent, not project an inherited prototype function.\n return Object.fromEntries(keys.filter((key) => Object.hasOwn(row, key)).map((key) => [key, row[key]]));\n}\n\n/** The `rollup` member of the field-spec union. */\nexport type RollupFieldSpec = Extract<CollectionFieldSpec, { type: \"rollup\" }>;\n\n/** Numeric coercion shared by the strict record lint (`./recordZ`) and\n * rollup sums: a plain number, or a non-blank numeric string (renderers\n * coerce those via `Number(...)`, so they display fine). Anything else —\n * arrays (`[]` stringifies to `\"\"` = 0, `[42]` to `\"42\"`), booleans,\n * objects — is NaN. Lives here (zod-free) so both consumers share one\n * definition of \"numeric\". */\nexport function coerceNumeric(value: unknown): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n return NaN;\n}\n\n/** The rollup aggregate over the matching source rows (plan step ⑤):\n * `count` = how many rows match; `sum` = the total of `column` over\n * them, skipping non-numeric / absent values (a partially-filled source\n * still sums what's there). An EMPTY match set is a real 0 — the\n * fail-soft null lives at the caller, for a source collection that\n * couldn't be resolved at all. Same derived-source-records contract as\n * `backlinkRows`: pass records derived against themselves, so summing a\n * self-contained derived column (an invoice `total`) works. */\nexport function rollupValue(spec: Pick<RollupFieldSpec, \"via\" | \"filter\" | \"op\" | \"column\">, recordId: string, sourceItems: CollectionItem[]): number {\n const rows = backlinkRows(spec, recordId, sourceItems);\n if (spec.op === \"count\") return rows.length;\n let total = 0;\n for (const row of rows) {\n const value = coerceNumeric(spec.column === undefined ? undefined : row[spec.column]);\n if (Number.isFinite(value)) total += value;\n }\n return total;\n}\n","// The single implementation of \"which linked collections must be\n// preloaded\" for a schema — walked identically by the server (derive /\n// enrich, `server/derive.ts`) and the client (linked-cache fetch,\n// collection-plugin). Both sides MUST agree: the server derefs exactly the\n// collections the client caches, so a new ref-shaped field type is taught\n// here once instead of drifting between two mirrored copies. Pure schema\n// walk, no zod / I/O — safe for the browser barrel.\n\nimport type { CollectionFieldSpec, CollectionSchema } from \"./schema\";\n\n/** Slugs of every collection referenced by a `ref` field — top-level and\n * one level into `table` sub-fields (nested tables are schema-rejected,\n * so a single recursion suffices). */\nexport function uniqueRefTargets(schema: CollectionSchema): string[] {\n const targets = new Set<string>();\n const walk = (fields: Record<string, CollectionFieldSpec>): void => {\n for (const field of Object.values(fields)) {\n if (field.type === \"ref\" && typeof field.to === \"string\" && field.to.length > 0) targets.add(field.to);\n if (field.type === \"table\" && field.of) walk(field.of);\n }\n };\n walk(schema.fields);\n return [...targets];\n}\n\n/** Slugs of every collection referenced by an `embed` field. Top-level\n * only — the schema rejects `embed` inside a table's `of`, so no\n * recursion. */\nexport function uniqueEmbedTargets(schema: CollectionSchema): string[] {\n const targets = new Set<string>();\n for (const field of Object.values(schema.fields)) {\n if (field.type === \"embed\" && typeof field.to === \"string\" && field.to.length > 0) targets.add(field.to);\n }\n return [...targets];\n}\n\n/** Slugs of every SOURCE collection a `backlinks` or `rollup` field\n * reverses over — loaded once (the two field kinds share one load).\n * Top-level only, like `embed` (the schema rejects both inside a table's\n * `of`). */\nexport function uniqueBacklinkSources(schema: CollectionSchema): string[] {\n const sources = new Set<string>();\n for (const field of Object.values(schema.fields)) {\n if ((field.type === \"backlinks\" || field.type === \"rollup\") && field.from.length > 0) sources.add(field.from);\n }\n return [...sources];\n}\n","// Pure SQL-like `where` predicate for `dynamicIcon` (see\n// `DynamicIconSource.where` / `DynamicIconRule.where` in `./schema`).\n// An AND of typed conditions — richer than the single-field `CollectionWhen`\n// used elsewhere (fields/actions via `./actionVisible`), which stays as-is\n// for its existing callers. No fs, no host state. The condition SHAPES are\n// derived from the zod source of truth in `./schemaZ` (type-only imports —\n// this evaluator stays zod-free at runtime).\n\nimport type { z } from \"zod\";\nimport type { ValueRefZ, WhereCondZ, WhereZ } from \"./schemaZ\";\n\n/** Reads the comparison value from a field instead of a schema literal:\n * - `record` set → another record: `recordsById[record][field]` (e.g. a\n * `_config` singleton's `defaultCity`, following a per-user setting);\n * - `record` omitted → the SAME record being matched (field-to-field, e.g.\n * `spent > budget`). */\nexport type ValueRef = z.infer<typeof ValueRefZ>;\n\n/** One typed condition: `record[field] <op> value`. The comparison value is\n * either a literal `value` (a plain string for every op except `in`, which\n * takes the allowed set) or a `valueFrom` reference resolved against the\n * `recordsById` map passed to `matchesWhere`. Exactly one of the two is\n * expected — enforced by zod at the schema boundary (`./schemaZ`), not\n * here. */\nexport type WhereCond = z.infer<typeof WhereCondZ>;\n\n/** Comparison operators one `WhereCond` may apply to `record[field]`. */\nexport type WhereOp = WhereCond[\"op\"];\n\n/** A `where` clause is the AND of its conditions — every one must match. */\nexport type Where = z.infer<typeof WhereZ>;\n\n/** True when `record[field]` is absent (`undefined`/`null`) — the only case\n * where `ne` and every other op disagree on the result. */\nfunction isMissing(raw: unknown): boolean {\n return raw === undefined || raw === null;\n}\n\n/** Own-property read for a user/LLM-controlled key (`cond.field`,\n * `valueFrom.record`, `valueFrom.field`). A bare `obj[key]` reaches inherited\n * Object.prototype members, so `field: \"toString\"` would read a function\n * instead of an absent value (spurious match), and `record: \"constructor\"`\n * would read the `Object` function whose `.name`/`.length` are plausible\n * bogus comparands — breaking the \"unresolved ⇒ never matches\" contract\n * (#2323). A prototype key resolves to `undefined` (absent). */\nfunction ownProp<T>(obj: Record<string, T>, key: string): T | undefined {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n\n/** The effective comparison value for `cond`: its literal `value`, or — for\n * a `valueFrom` reference — the target field read out of `recordsById`.\n * `undefined` means UNRESOLVED (no such record, or the field on it is\n * missing); the caller must treat that as \"never matches\", not as a\n * literal `undefined` value to compare against. */\nfunction resolveValue(cond: WhereCond, record: Record<string, unknown>, recordsById: Record<string, Record<string, unknown>>): string | string[] | undefined {\n if (!cond.valueFrom) return cond.value;\n const { record: refRecord, field } = cond.valueFrom;\n const target = refRecord === undefined ? record : ownProp(recordsById, refRecord);\n const raw = target === undefined ? undefined : ownProp(target, field);\n return isMissing(raw) ? undefined : String(raw);\n}\n\nfunction matchesNumericOp(operator: \"gt\" | \"gte\" | \"lt\" | \"lte\", left: number, right: number): boolean {\n if (operator === \"gt\") return left > right;\n if (operator === \"gte\") return left >= right;\n if (operator === \"lt\") return left < right;\n return left <= right;\n}\n\n/** `Number(\"\")` / `Number(\" \")` are `0`, not `NaN`, so treat a blank string\n * as non-numeric explicitly — an empty field must fail a numeric compare,\n * not read as zero. */\nfunction toNumber(raw: string): number {\n return raw.trim() === \"\" ? NaN : Number(raw);\n}\n\nfunction matchesNumeric(operator: \"gt\" | \"gte\" | \"lt\" | \"lte\", raw: string, value: string | string[]): boolean {\n if (Array.isArray(value)) return false;\n const left = toNumber(raw);\n const right = toNumber(value);\n if (Number.isNaN(left) || Number.isNaN(right)) return false;\n return matchesNumericOp(operator, left, right);\n}\n\n/** True when the present string `raw` satisfies `operator` against the\n * resolved `value` (field known to exist — MISSING is handled by the\n * caller before this runs, and an UNRESOLVED `valueFrom` never reaches\n * here either). */\nfunction matchesPresent(operator: WhereOp, raw: string, value: string | string[]): boolean {\n switch (operator) {\n case \"eq\":\n return raw === String(value);\n case \"ne\":\n return raw !== String(value);\n case \"in\":\n return Array.isArray(value) && value.includes(raw);\n case \"contains\":\n return raw.includes(String(value));\n case \"gt\":\n case \"gte\":\n case \"lt\":\n case \"lte\":\n return matchesNumeric(operator, raw, value);\n default:\n return false;\n }\n}\n\n/** True when `record` satisfies one condition, given `recordsById` to\n * resolve a `valueFrom` reference. Two independent MISSING cases, checked\n * in order:\n * - `record[cond.field]` absent (`undefined`/`null`) → matches only `ne`\n * (vacuously true — \"not equal to X\" holds when there's no value at\n * all); every other op is false. Unchanged from the literal-`value`\n * behaviour, regardless of whether `valueFrom` would also resolve.\n * - the resolved comparison value is UNRESOLVED (a `valueFrom` whose\n * target record/field doesn't exist) → false for EVERY op, including\n * `ne` — a broken reference must never spuriously match. */\nfunction matchesCond(cond: WhereCond, record: Record<string, unknown>, recordsById: Record<string, Record<string, unknown>>): boolean {\n const raw = ownProp(record, cond.field);\n if (isMissing(raw)) return cond.op === \"ne\";\n const value = resolveValue(cond, record, recordsById);\n if (value === undefined) return false;\n return matchesPresent(cond.op, String(raw), value);\n}\n\n/** True when `record` satisfies every condition in `where` (AND). An empty\n * `where` matches everything. `recordsById` — the source collection's\n * records keyed by primaryKey — resolves any `valueFrom` reference;\n * omitted (default `{}`) for callers with no cross-record lookups, in\n * which case every `valueFrom` condition is UNRESOLVED and so never\n * matches. */\nexport function matchesWhere(where: Where, record: Record<string, unknown>, recordsById: Record<string, Record<string, unknown>> = {}): boolean {\n return where.every((cond) => matchesCond(cond, record, recordsById));\n}\n","// The \"is this record done?\" predicate — THE single implementation,\n// shared by the notification reconciler (bell clearing, collection-watchers),\n// spawn (successor-predicate fallback, ../server/spawn.ts), and view-side\n// completion filters. Zod-free and I/O-free like the rest of `core/`, so\n// it is browser-safe through the collection barrel.\n//\n// Two completion forms (see `CollectionSchemaZ`'s completion refine):\n// - legacy pair: `completionField` names a stored field and\n// `completionDoneValues` lists the values that mean done —\n// done ⇔ `String(item[completionField])` ∈ `completionDoneValues`.\n// - flag form: `completionField` names a `flag` field (and\n// `completionDoneValues` is absent) — done ⇔ the flag's `where`\n// matches. Evaluated directly against the raw record here (NOT read\n// from a materialized value) because callers like the reconciler and\n// spawn work on records straight off disk, before any `deriveAll`\n// enrichment. That raw evaluation is CORRECT BY CONSTRUCTION: a\n// schema-level refine rejects a completion flag whose `where`\n// references computed fields, so every condition reads stored data.\n\nimport { fieldText, fieldTextOrNull } from \"./fieldText\";\nimport { matchesWhere, type Where } from \"./where\";\nimport type { CollectionFieldSpec, CollectionItem } from \"./schema\";\n\n/** The slice of a parsed schema the done predicate reads — minimal\n * structural shape (like `DerivableSchema`) so the client and server\n * `CollectionSchema` types both satisfy it as-is. */\nexport interface CompletionSchemaView {\n /** Optional so legacy-pair callers (and their test fixtures) that\n * never consult field specs keep working; only the flag form needs\n * to look the completion field up. */\n fields?: Record<string, { type: string; where?: Where }>;\n completionField?: string;\n completionDoneValues?: readonly string[];\n}\n\n/** True iff the schema declares completion tracking AND `item` is done\n * under whichever completion form the schema uses (see module doc). */\nexport function itemIsDone(schema: CompletionSchemaView, item: Record<string, unknown>): boolean {\n const { completionField, completionDoneValues } = schema;\n if (!completionField) return false;\n const spec = schema.fields?.[completionField];\n if (spec?.type === \"flag\" && spec.where) return matchesWhere(spec.where, item);\n if (!completionDoneValues) return false;\n // An array/object field has no text form; treat it as \"not done\" rather than\n // letting \"[object Object]\" match a configured done-value.\n const text = fieldTextOrNull(item[completionField]);\n if (text === null) return false;\n return completionDoneValues.includes(text);\n}\n\n/** The schema slice `completionCoveredByFieldChip` reads: field kinds (it\n * inspects `boolean` / `toggle` variants' `field` / `onValue`) plus the\n * completion pair. Minimal structural shape so both the client and server\n * `CollectionSchema` types satisfy it as-is. */\nexport interface CompletionChipSchemaView {\n fields: Record<string, { type: string; field?: string; onValue?: string }>;\n completionField?: string;\n completionDoneValues?: readonly string[];\n}\n\n/** True when an existing FIELD chip already expresses the legacy completion\n * predicate exactly, so a synthesized \"done\" chip would be a duplicate: a\n * boolean `completionField` (done ⇔ `\"true\"` ⇔ the boolean's own chip), or a\n * `toggle` projecting the `completionField` whose `onValue` is the single\n * done value (the todos-schema shape: toggle \"Done\" on `status` +\n * `completionDoneValues: [\"done\"]`). A superset pair (extra done values)\n * still synthesizes — no field chip covers it. */\nexport function completionCoveredByFieldChip(schema: CompletionChipSchemaView): boolean {\n const { completionField, completionDoneValues } = schema;\n if (completionDoneValues?.length !== 1) return false;\n const [doneValue] = completionDoneValues;\n if (schema.fields[completionField ?? \"\"]?.type === \"boolean\") return doneValue === \"true\";\n return Object.values(schema.fields).some((field) => field.type === \"toggle\" && field.field === completionField && field.onValue === doneValue);\n}\n\n/** Whether a `toggle` field reads as checked: its projected enum field currently\n * equals `onValue`. The toggle stores nothing of its own, so this reads the raw\n * projected value; a non-toggle field is never checked. */\nexport function toggleChecked(item: CollectionItem, field: CollectionFieldSpec): boolean {\n return field.type === \"toggle\" && fieldText(item[field.field]) === field.onValue;\n}\n\n/** A `flag` FIELD's boolean for one row, read off the already-enriched record\n * (so a flag computed from derived/rollup inputs is correct). Strict `=== true`\n * on purpose: a truthy non-boolean (\"yes\", 1) is NOT a set flag, so a stray\n * value can never render as an active flag. */\nexport function flagFieldValue(record: Record<string, unknown>, key: string): boolean {\n return record[key] === true;\n}\n\n/** One entry in the table's flag-filter menu: a real `flag` / `boolean` /\n * `toggle` field, or the synthesized legacy-completion chip (`synthetic`,\n * predicate = `itemIsDone`). */\nexport interface FlagChip {\n key: string;\n label: string;\n synthetic?: boolean;\n}\n\n/** The schema slice `chipMatches` reads: full field specs (it inspects the\n * `toggle` variant's `field` / `onValue`) plus the completion pair that\n * `itemIsDone` needs for the synthesized chip. */\nexport interface ChipMatchSchema {\n fields: Record<string, CollectionFieldSpec>;\n completionField?: string;\n completionDoneValues?: readonly string[];\n}\n\n/** Whether one row satisfies a chip's predicate: `itemIsDone` for the\n * synthesized completion chip, the projected value for a `toggle`, the stored\n * boolean for a `boolean`, else the computed flag value. The flag branch reads\n * the ENRICHED record via the injected `deriveRecord` (kept a parameter so this\n * stays pure and framework-free). */\nexport function chipMatches(\n chip: FlagChip,\n schema: ChipMatchSchema,\n item: CollectionItem,\n deriveRecord: (item: CollectionItem) => Record<string, unknown>,\n): boolean {\n if (chip.synthetic) return itemIsDone(schema, item);\n const field = schema.fields[chip.key];\n if (field?.type === \"toggle\") return toggleChecked(item, field);\n if (field?.type === \"boolean\") return item[chip.key] === true;\n return flagFieldValue(deriveRecord(item), chip.key);\n}\n","// Pure resolver for a collection's dynamic launcher-shortcut icon (see\n// `CollectionSchema.dynamicIcon`). Selects one \"source\" record from a\n// (possibly cross-collection, optionally `where`-filtered) records pool,\n// then maps it through a first-match-wins rules list to an icon name.\n// No fs, no host state — the server-side compute\n// (`packages/core/src/collection/server/dynamicIcon.ts`) loads the source\n// collection's records and calls these.\n\nimport { fieldText } from \"./fieldText\";\nimport { matchesWhere } from \"./where\";\nimport type { CollectionFieldSpec, CollectionItem, CollectionSchema, DynamicIconSource, DynamicIconSpec } from \"./schema\";\n\n/** The record with the greatest `String(record[field])` (localeCompare) —\n * ties keep the first-seen record (stable left-to-right `reduce`). */\nfunction latestByField(pool: CollectionItem[], field: string): CollectionItem {\n return pool.reduce((latest, candidate) => (fieldText(candidate[field]).localeCompare(fieldText(latest[field])) > 0 ? candidate : latest));\n}\n\n/** Reduce `records` to the one record that decides the effective icon, per\n * `source`'s `where` filter + `from` strategy:\n * - pool = `source.where`-filtered records, or every record when unset;\n * - an empty pool resolves to `null` (no source record → fallback);\n * - `from: \"first\"` / `\"when\"` → the first pool record (storage order);\n * - `from: \"latest\"` (default), with `orderBy` given → the pool record\n * whose `String(record[orderBy])` sorts highest;\n * - `from: \"latest\"`, with no `orderBy` → the last pool record.\n * `recordsById` (the source collection's records keyed by primaryKey)\n * resolves any `valueFrom` reference inside `source.where`; omitted for\n * callers with no cross-record lookups. */\nexport function selectDynamicRecord(\n records: CollectionItem[],\n source: DynamicIconSource,\n orderBy: string | undefined,\n recordsById: Record<string, CollectionItem> = {},\n): CollectionItem | null {\n const { where } = source;\n const pool = where ? records.filter((record) => matchesWhere(where, record, recordsById)) : records;\n if (pool.length === 0) return null;\n if (source.from === \"first\" || source.from === \"when\") return pool[0];\n return orderBy ? latestByField(pool, orderBy) : pool[pool.length - 1];\n}\n\n/** Map a resolved source record to the effective icon: `spec.fallback`\n * (or the collection's own static `icon`) when there's no record or no\n * rule matches; otherwise the `icon` of the first rule whose `where`\n * matches the record. `recordsById` resolves any `valueFrom` reference\n * inside a rule's `where`, same as `selectDynamicRecord`. */\nexport function resolveIcon(\n record: CollectionItem | null,\n spec: DynamicIconSpec,\n staticIcon: string,\n recordsById: Record<string, CollectionItem> = {},\n): string {\n const fallback = spec.fallback ?? staticIcon;\n if (!record) return fallback;\n const matched = spec.rules.find((rule) => matchesWhere(rule.where, record, recordsById));\n return matched ? matched.icon : fallback;\n}\n\nconst isDateLikeField = (field: CollectionFieldSpec): boolean => field.type === \"date\" || field.type === \"datetime\";\n\n/** The first field key (declaration order) whose type is `date` or\n * `datetime` — the default `orderBy` for `from: \"latest\"` when a\n * `DynamicIconSource` doesn't name one. `undefined` when the schema has\n * no date-like field. */\nexport function firstDateField(schema: CollectionSchema): string | undefined {\n return Object.entries(schema.fields).find(([, field]) => isDateLikeField(field))?.[0];\n}\n","// Tiny expression evaluator for the `derived` field type on\n// schema-driven collections (see plans/done/feat-mc-invoice.md).\n//\n// Grammar (recursive-descent, no precedence climbing — six\n// non-terminals total):\n//\n// expr := term (('+' | '-') term)*\n// term := factor (('*' | '/') factor)*\n// factor := number | sumCall | refAccess | identifier | '(' expr ')'\n// sumCall:= 'sum' '(' sumArg ')'\n// sumArg := tableCol (('*' | '/') tableCol)* // e.g. lineItems[].quantity * lineItems[].rate\n// tableCol := identifier '[]' '.' identifier\n// refAccess := identifier '.' identifier // e.g. ticker.price — deref a ref field into its target record\n//\n// `identifier` accepts top-level field names (single segment).\n// Inside `sumArg`, identifiers are the `<table>[].col` form.\n// A two-segment `<field>.<col>` at factor level is a *ref deref*:\n// `<field>` must be a `ref`-typed field on this record (its stored\n// value is the target item's slug), and `<col>` is a numeric column\n// read from that target record. The caller resolves the target into\n// `ctx.refs` (it owns the schema + the loaded target collection);\n// the evaluator stays pure and never does I/O.\n//\n// What's deliberately NOT supported (and would parse-error rather\n// than silently misbehave):\n// - String literals, boolean operators, comparisons, conditionals\n// - Nested function calls beyond `sum(...)`\n// - Anything in the record that isn't a number / table-of-objects\n//\n// All evaluation is pure — no eval(), no Function constructor.\n// Returns `null` on any failure (parse error, unbound identifier,\n// non-finite arithmetic). The caller renders `null` as em-dash in\n// the table cell + form display.\n\nexport interface FormulaContext {\n /** The record being evaluated. For derived fields in the form,\n * this is the live draft (text + table both converted via the\n * same `draftToRecord` pipeline). For the main table cell,\n * this is the persisted item. */\n record: Record<string, unknown>;\n /** Resolved ref-target records for THIS row, keyed by the local\n * `ref` field name. The caller (which has the schema + the linked\n * collection's items loaded) maps each ref field's stored slug to\n * the full target record and passes it here, so a `<field>.<col>`\n * formula can read a numeric column off the referenced record\n * (e.g. `shares * ticker.price`). A missing key or `null` value\n * (unknown field / dangling slug) makes that deref evaluate to\n * NaN → the whole formula returns `null` → em-dash, consistent\n * with every other failure mode. Absent ⇒ no refs available. */\n refs?: Record<string, Record<string, unknown> | null>;\n}\n\nexport function evaluateDerived(formula: string, ctx: FormulaContext): number | null {\n let tokens: Token[];\n try {\n tokens = tokenize(formula);\n } catch {\n return null;\n }\n // eslint-disable-next-line @typescript-eslint/no-use-before-define -- Parser class is defined later in the file (grouped with its AST + evaluator); evaluateDerived runs after module init so the TDZ concern doesn't apply.\n const parser = new Parser(tokens);\n let ast: Node;\n try {\n ast = parser.parseExpr();\n if (!parser.atEnd()) return null; // trailing junk\n } catch {\n return null;\n }\n const value = evaluate(ast, ctx);\n return Number.isFinite(value) ? value : null;\n}\n\n// ─── Tokens ────────────────────────────────────────────────\n\ntype TokenKind = \"number\" | \"ident\" | \"(\" | \")\" | \"+\" | \"-\" | \"*\" | \"/\" | \"[]\" | \".\";\n\ninterface Token {\n kind: TokenKind;\n value?: string | number;\n}\n\nconst SINGLE_CHAR_PUNCT = new Set<TokenKind>([\"(\", \")\", \"+\", \"-\", \"*\", \"/\", \".\"]);\n\ninterface Cursor {\n input: string;\n index: number;\n}\n\nfunction consumeWhitespace(cur: Cursor): boolean {\n const char = cur.input[cur.index];\n if (char === \" \" || char === \"\\t\" || char === \"\\n\") {\n cur.index++;\n return true;\n }\n return false;\n}\n\nfunction consumeNumber(cur: Cursor): Token | null {\n const char = cur.input[cur.index] ?? \"\";\n const next = cur.input[cur.index + 1] ?? \"\";\n if (!isDigit(char) && !(char === \".\" && isDigit(next))) return null;\n let raw = \"\";\n while (cur.index < cur.input.length) {\n const here = cur.input[cur.index] ?? \"\";\n if (!isDigit(here) && here !== \".\") break;\n raw += here;\n cur.index++;\n }\n const num = Number(raw);\n if (!Number.isFinite(num)) throw new Error(\"bad number\");\n return { kind: \"number\", value: num };\n}\n\nfunction consumeIdent(cur: Cursor): Token | null {\n const char = cur.input[cur.index] ?? \"\";\n if (!isIdentStart(char)) return null;\n let raw = \"\";\n while (cur.index < cur.input.length && isIdentChar(cur.input[cur.index] ?? \"\")) {\n raw += cur.input[cur.index];\n cur.index++;\n }\n return { kind: \"ident\", value: raw };\n}\n\nfunction consumePunct(cur: Cursor): Token | null {\n const char = cur.input[cur.index] ?? \"\";\n if (char === \"[\" && cur.input[cur.index + 1] === \"]\") {\n cur.index += 2;\n return { kind: \"[]\" };\n }\n if (SINGLE_CHAR_PUNCT.has(char as TokenKind)) {\n cur.index++;\n return { kind: char as TokenKind };\n }\n return null;\n}\n\nfunction tokenize(input: string): Token[] {\n const tokens: Token[] = [];\n const cur: Cursor = { input, index: 0 };\n while (cur.index < input.length) {\n if (consumeWhitespace(cur)) continue;\n // Number FIRST so a leading-dot literal (`.25`) isn't split by\n // the `.` punctuation branch.\n const numTok = consumeNumber(cur);\n if (numTok) {\n tokens.push(numTok);\n continue;\n }\n const punctTok = consumePunct(cur);\n if (punctTok) {\n tokens.push(punctTok);\n continue;\n }\n const identTok = consumeIdent(cur);\n if (identTok) {\n tokens.push(identTok);\n continue;\n }\n throw new Error(`unexpected char ${input[cur.index]}`);\n }\n return tokens;\n}\n\nfunction isDigit(char: string): boolean {\n return char >= \"0\" && char <= \"9\";\n}\nfunction isIdentStart(char: string): boolean {\n return (char >= \"a\" && char <= \"z\") || (char >= \"A\" && char <= \"Z\") || char === \"_\";\n}\nfunction isIdentChar(char: string): boolean {\n return isIdentStart(char) || isDigit(char);\n}\n\n// ─── AST + Parser ───────────────────────────────────────────\n\ntype Node =\n | { kind: \"num\"; value: number }\n | { kind: \"ident\"; name: string }\n | { kind: \"ref\"; field: string; col: string }\n | { kind: \"binop\"; operator: \"+\" | \"-\" | \"*\" | \"/\"; left: Node; right: Node }\n | { kind: \"sum\"; arg: SumArg };\n\ninterface SumArg {\n // factors multiplied/divided together; each is a (tableName, colName) ref into a row.\n factors: { table: string; col: string }[];\n /** Operators between factors: length = factors.length - 1; each\n * is \"*\" or \"/\". For a single-factor sum (`sum(lineItems[].amount)`)\n * this is empty. */\n operators: (\"*\" | \"/\")[];\n}\n\nclass Parser {\n private cursor = 0;\n constructor(private readonly tokens: Token[]) {}\n\n atEnd(): boolean {\n return this.cursor >= this.tokens.length;\n }\n private peek(): Token | undefined {\n return this.tokens[this.cursor];\n }\n private consume(): Token {\n const tok = this.tokens[this.cursor++];\n if (!tok) throw new Error(\"unexpected end of input\");\n return tok;\n }\n private expect(kind: TokenKind): Token {\n const tok = this.consume();\n if (tok.kind !== kind) throw new Error(`expected ${kind}, got ${tok.kind}`);\n return tok;\n }\n\n parseExpr(): Node {\n let left = this.parseTerm();\n while (this.peek()?.kind === \"+\" || this.peek()?.kind === \"-\") {\n const operator = this.consume().kind as \"+\" | \"-\";\n const right = this.parseTerm();\n left = { kind: \"binop\", operator, left, right };\n }\n return left;\n }\n\n private parseTerm(): Node {\n let left = this.parseFactor();\n while (this.peek()?.kind === \"*\" || this.peek()?.kind === \"/\") {\n const operator = this.consume().kind as \"*\" | \"/\";\n const right = this.parseFactor();\n left = { kind: \"binop\", operator, left, right };\n }\n return left;\n }\n\n private parseFactor(): Node {\n const tok = this.peek();\n if (!tok) throw new Error(\"unexpected end in factor\");\n if (tok.kind === \"number\") {\n this.consume();\n return { kind: \"num\", value: tok.value as number };\n }\n if (tok.kind === \"(\") {\n this.consume();\n const inner = this.parseExpr();\n this.expect(\")\");\n return inner;\n }\n if (tok.kind === \"ident\") {\n const name = (tok.value as string) ?? \"\";\n // sum(...) — only function call we support\n if (name === \"sum\" && this.tokens[this.cursor + 1]?.kind === \"(\") {\n this.consume(); // ident\n this.expect(\"(\");\n const arg = this.parseSumArg();\n this.expect(\")\");\n return { kind: \"sum\", arg };\n }\n this.consume(); // ident\n // ref deref: `<field>.<col>` (e.g. ticker.price). The table-row\n // form `<table>[].col` only appears inside sum(), so a `.`\n // immediately after a top-level ident is unambiguously a ref\n // dereference here.\n if (this.peek()?.kind === \".\") {\n this.consume(); // '.'\n const col = this.expect(\"ident\");\n return { kind: \"ref\", field: name, col: col.value as string };\n }\n return { kind: \"ident\", name };\n }\n throw new Error(`unexpected token ${tok.kind} in factor`);\n }\n\n private parseSumArg(): SumArg {\n const factors: { table: string; col: string }[] = [];\n const operators: (\"*\" | \"/\")[] = [];\n factors.push(this.parseTableCol());\n while (this.peek()?.kind === \"*\" || this.peek()?.kind === \"/\") {\n const operator = this.consume().kind as \"*\" | \"/\";\n operators.push(operator);\n factors.push(this.parseTableCol());\n }\n return { factors, operators };\n }\n\n private parseTableCol(): { table: string; col: string } {\n const tableTok = this.expect(\"ident\");\n this.expect(\"[]\");\n this.expect(\".\");\n const colTok = this.expect(\"ident\");\n return { table: tableTok.value as string, col: colTok.value as string };\n }\n}\n\n// ─── Evaluator ──────────────────────────────────────────────\n\nfunction evaluate(node: Node, ctx: FormulaContext): number {\n if (node.kind === \"num\") return node.value;\n if (node.kind === \"ident\") {\n const raw = ctx.record[node.name];\n return toFiniteNumber(raw);\n }\n if (node.kind === \"ref\") {\n // `<field>.<col>`: read `col` off the resolved target record the\n // caller put in ctx.refs. Unknown field / dangling slug → null →\n // NaN, so the whole formula fails soft to an em-dash.\n const target = ctx.refs?.[node.field] ?? null;\n if (!target) return Number.NaN;\n return toFiniteNumber(target[node.col]);\n }\n if (node.kind === \"binop\") {\n const left = evaluate(node.left, ctx);\n const right = evaluate(node.right, ctx);\n return applyBinop(node.operator, left, right);\n }\n if (node.kind === \"sum\") {\n return evaluateSum(node.arg, ctx);\n }\n // Exhaustive — TS narrows above branches but throw keeps runtime honest.\n throw new Error(`unknown node`);\n}\n\nfunction applyBinop(operator: \"+\" | \"-\" | \"*\" | \"/\", left: number, right: number): number {\n if (!Number.isFinite(left) || !Number.isFinite(right)) return Number.NaN;\n if (operator === \"+\") return left + right;\n if (operator === \"-\") return left - right;\n if (operator === \"*\") return left * right;\n // operator === \"/\"\n if (right === 0) return Number.NaN;\n return left / right;\n}\n\nfunction evaluateSum(arg: SumArg, ctx: FormulaContext): number {\n if (arg.factors.length === 0) return 0;\n const tableName = arg.factors[0].table;\n // All factors must reference the SAME table (you can't multiply\n // a row from lineItems against a row from another table — the\n // semantics would be ambiguous). Reject mismatch.\n for (const factor of arg.factors) {\n if (factor.table !== tableName) return Number.NaN;\n }\n const rows = ctx.record[tableName];\n if (!Array.isArray(rows)) return 0;\n let total = 0;\n for (const row of rows) {\n if (!row || typeof row !== \"object\") continue;\n let product = toFiniteNumber((row as Record<string, unknown>)[arg.factors[0].col]);\n if (!Number.isFinite(product)) return Number.NaN;\n for (let i = 1; i < arg.factors.length; i++) {\n const value = toFiniteNumber((row as Record<string, unknown>)[arg.factors[i].col]);\n if (!Number.isFinite(value)) return Number.NaN;\n product = applyBinop(arg.operators[i - 1], product, value);\n }\n total += product;\n }\n return total;\n}\n\nfunction toFiniteNumber(value: unknown): number {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : Number.NaN;\n if (typeof value === \"string\" && value.length > 0) {\n const num = Number(value);\n return Number.isFinite(num) ? num : Number.NaN;\n }\n return Number.NaN;\n}\n","// Own-property read for a plain object indexed by a user/LLM/feed-controlled\n// key. Extracted so the ref/embed resolution in `deriveAll` and `derive`\n// share one guard (where.ts keeps its own private copy for the dynamicIcon\n// `where` evaluator — #2443).\n\n/** Read `obj[key]` only when it is an OWN property. A bare `obj[key]` reaches\n * inherited Object.prototype members, so a dangling ref/embed id like\n * `\"constructor\"` or `\"__proto__\"` resolves to a prototype value (the\n * `Object` function) instead of being absent — breaking the \"missing target\n * ⇒ null (em-dash)\" fail-soft contract and putting a non-serializable\n * function into the API response, where `JSON.stringify` drops the key\n * entirely (#2322). A prototype key resolves to `undefined`; a record whose\n * id is legitimately `\"constructor\"` (an own key) still resolves. */\nexport function ownProp<T>(obj: Record<string, T>, key: string): T | undefined {\n return Object.hasOwn(obj, key) ? obj[key] : undefined;\n}\n","// The derived-field saturation loop for schema-driven collections,\n// extracted from `composables/collections/useCollectionRendering.ts` so\n// the server (manageCollection getItems enrichment) and the client\n// (table cells, form display) evaluate formulas through ONE\n// implementation — if the two ever diverged, the UI and the LLM would\n// disagree on a number. Pure module: no Vue, no I/O.\n//\n// Like `actionVisible.ts`, the input types are minimal structural\n// shapes so both the client `FieldSpec`/`CollectionSchema`\n// (src/components/collectionTypes.ts) and the server\n// `CollectionFieldSpec`/`CollectionSchema`\n// (server/workspace/collections/types.ts) satisfy them as-is.\n\nimport { evaluateDerived, type FormulaContext } from \"./derivedFormula\";\nimport { ownProp } from \"./ownProp\";\nimport { matchesWhere, type Where } from \"./where\";\n\n/** Minimal field shape the derive loop needs — accepts both the client\n * FieldSpec and the server CollectionFieldSpec. */\nexport interface DerivableFieldSpec {\n type: string;\n /** When type === \"ref\": slug of the target collection. */\n to?: string;\n /** When type === \"derived\": formula evaluated against the record. */\n formula?: string;\n /** When type === \"flag\": predicate matched against the record. */\n where?: Where;\n}\n\n/** Minimal schema shape: just the ordered field map. */\nexport interface DerivableSchema {\n fields: Record<string, DerivableFieldSpec>;\n}\n\nexport type DerivableRecord = Record<string, unknown>;\n\n/** Per-target-collection cache of loaded referenced records:\n * target collection slug → item slug → full record. Mirrors the\n * client's `RefRecordCache` / the server's enrichment loader. */\nexport type DeriveRefRecords = Record<string, Record<string, DerivableRecord>>;\n\n/** Map each `ref` field's stored slug to its loaded target record (or\n * null when dangling / not loaded), keyed by the LOCAL field name —\n * the shape `evaluateDerived` reads for `<field>.<col>` derefs. */\nexport function resolveRowRefs(schema: DerivableSchema, record: DerivableRecord, refRecords: DeriveRefRecords): NonNullable<FormulaContext[\"refs\"]> {\n const refs: NonNullable<FormulaContext[\"refs\"]> = {};\n for (const [key, field] of Object.entries(schema.fields)) {\n if (field.type !== \"ref\" || !field.to) continue;\n const slug = record[key];\n const targets = ownProp(refRecords, field.to);\n refs[key] = typeof slug === \"string\" && targets ? (ownProp(targets, slug) ?? null) : null;\n }\n return refs;\n}\n\n/** True for the field types the saturation loop below (re)computes:\n * `derived` formulas and `flag` predicates. */\nfunction isLoopComputed(field: DerivableFieldSpec): boolean {\n return field.type === \"derived\" || field.type === \"flag\";\n}\n\n/** The value one loop-computed field takes against the current\n * `enriched` record: a `derived` formula result (`null` = failed) or a\n * `flag` predicate match (total — always a boolean). `undefined` for\n * every other field type (nothing to compute). */\nfunction computeFieldValue(\n field: DerivableFieldSpec,\n enriched: DerivableRecord,\n refs: NonNullable<FormulaContext[\"refs\"]>,\n): number | boolean | null | undefined {\n if (field.type === \"derived\" && field.formula) return evaluateDerived(field.formula, { record: enriched, refs });\n if (field.type === \"flag\" && field.where) return matchesWhere(field.where, enriched);\n return undefined;\n}\n\n/** Evaluate every `derived` and `flag` field against `base`, saturating\n * so a computed field can read another one computed in an earlier pass\n * (`subtotal → tax → total` converges in ≤ field-count passes; a flag\n * may read a derived value, or another flag via its stringified\n * boolean). Cycles can't loop forever — passes are bounded by the\n * number of computed fields and the loop breaks as soon as a pass\n * changes nothing. Failed formulas stay ABSENT (the UI renders them as\n * em-dash); flags are total (always true/false). Returns a copy;\n * `base` is never mutated.\n *\n * Computed keys already present in `base` are stripped before\n * evaluation: computed output is host-truth, never persisted-input\n * fallback. A record JSON can carry a stale (or forged) computed value\n * — raw Write/Edit, legacy data — and without the strip, a failing\n * formula would silently surface that value as if the host computed\n * it. */\nexport function deriveAll(schema: DerivableSchema, base: DerivableRecord, refRecords: DeriveRefRecords): DerivableRecord {\n const computedKeys = new Set(\n Object.entries(schema.fields)\n .filter(([, field]) => isLoopComputed(field))\n .map(([key]) => key),\n );\n const enriched: DerivableRecord = Object.fromEntries(Object.entries(base).filter(([key]) => !computedKeys.has(key)));\n const refs = resolveRowRefs(schema, base, refRecords);\n for (let pass = 0; pass < computedKeys.size; pass++) {\n let mutated = false;\n for (const [key, field] of Object.entries(schema.fields)) {\n const next = computeFieldValue(field, enriched, refs);\n if (next !== undefined && next !== null && enriched[key] !== next) {\n enriched[key] = next;\n mutated = true;\n }\n }\n if (!mutated) break;\n }\n return enriched;\n}\n","// Neutralize structural prompt-injection vectors in a short, record-derived\n// string before it rides into an LLM-facing prompt: strip angle brackets,\n// defang backticks / `${` template openings, collapse whitespace (so an\n// embedded newline can't fabricate a pseudo-instruction on its own line), and\n// clip to a small budget. Mirrors the host server's own defang so the two\n// can't drift (#1677).\n\n/** Max chars kept — the first batch of a validation issue is enough to act on. */\nconst DEFANG_MAX_LEN = 200;\n\nexport function defangForPrompt(value: string): string {\n return value.replace(/[<>]/g, \"\").replace(/`/g, \"'\").replace(/\\$\\{/g, \"$ {\").replace(/\\s+/g, \" \").slice(0, DEFANG_MAX_LEN);\n}\n"],"mappings":";;;;;;;;;AAwBA,SAAgB,YAAY,MAAiC,QAA0C;CACrG,IAAI,CAAC,MAAM,OAAO;CAIlB,MAAM,OAAO,qBAAA,gBAAgB,OAAO,KAAK,MAAM;CAC/C,IAAI,SAAS,MAAM,OAAO;CAC1B,OAAO,KAAK,GAAG,SAAS,IAAI;AAC9B;;;;AAcA,SAAgB,cAAc,QAAwB,QAA0C;CAC9F,OAAO,YAAY,OAAO,QAAQ,OAAO,SAAS,MAAM;AAC1D;;;;;;;AAQA,SAAgB,kBAAkB,UAAkB,QAAyB;CAC3E,OAAO,WAAW,KAAA,IAAY,cAAc,aAAa,QAAQ,OAAO,GAAG;AAC7E;;;;;;AAaA,SAAgB,aAAa,OAAsB,QAA0C;CAC3F,OAAO,YAAY,MAAM,MAAM,MAAM;AACvC;;;;;;;;;;;;;;;;;;;;;;;;;;ACnCA,SAAgB,WAAW,KAAa,MAAsB,UAA2B;CACvF,IAAI,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,qBAAA,gBAAgB,KAAK,IAAI,MAAM;CACpE,MAAM,MAAM,IAAI,QAAQ,GAAG;CAC3B,IAAI,QAAQ,IAAI,OAAO;CACvB,MAAM,aAAa,IAAI,MAAM,GAAG,GAAG;CACnC,MAAM,YAAY,IAAI,MAAM,MAAM,CAAC;CACnC,MAAM,OAAO,KAAK;CAClB,IAAI,CAAC,MAAM,QAAQ,IAAI,GAAG,OAAO;CACjC,OAAO,KAAK,MAAM,QAAQ,qBAAA,gBAAiB,MAAyB,UAAU,MAAM,QAAQ;AAC9F;;;;;;;;;;;;AAaA,SAAgB,aAAa,MAAkD,UAAkB,aAAiD;CAChJ,IAAI,CAAC,UAAU,OAAO,CAAC;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a,MAAM,QAAQ;EACnD,IAAI,UAAU;EACd,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,MAAM,GAAG;GACxD,MAAM,OAAO,kBAAkB,OAAO,UAAU,IAAI;GACpD,IAAI,SAAS,KAAA,KAAa,SAAS,QAAQ,SAAS,SAAS,MAAM;IACjE,SAAS,OAAO;IAChB,UAAU;GACZ;EACF;EACA,IAAI,CAAC,SAAS;CAChB;CACA,OAAO;AACT;;;;ACvGA,IAAM,iBAAiB;AAEvB,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,MAAM,QAAQ,SAAS,EAAE,CAAC,CAAC,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,MAAM,GAAG,cAAc;AAC3H"}
@@ -1,6 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let firebase_firestore = require("firebase/firestore");
3
3
  //#region src/remote-host/index.ts
4
+ /** Widen a JSON-shaped handler payload to the channel's `JsonObject`.
5
+ *
6
+ * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,
7
+ * eight remote-host handlers each carried their own `as unknown as JsonObject`
8
+ * with the justification re-argued in eight slightly different comments —
9
+ * which is how a rule stops being reviewable. */
10
+ var toJsonObject = (payload) => payload;
4
11
  var isExpired = (command, now) => typeof command.expiresAt === "number" && now >= command.expiresAt;
5
12
  var byCreatedAt = (left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0);
6
13
  var REMOTE_HOST_PROTOCOL_VERSION = 2;
@@ -19,5 +26,6 @@ exports.byCreatedAt = byCreatedAt;
19
26
  exports.commandsCollection = commandsCollection;
20
27
  exports.hostDoc = hostDoc;
21
28
  exports.isExpired = isExpired;
29
+ exports.toJsonObject = toJsonObject;
22
30
 
23
31
  //# sourceMappingURL=index.cjs.map