@ai-matrx/kit 0.12.1 → 0.13.1

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/index.cjs CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/index.ts
32
32
  var src_exports = {};
33
33
  __export(src_exports, {
34
+ ContentTransferError: () => ContentTransferError,
34
35
  DBStoreManager: () => DBStoreManager,
35
36
  DEFAULT_JSON_INDENT: () => DEFAULT_JSON_INDENT,
36
37
  DEFAULT_JSON_WIDTH: () => DEFAULT_JSON_WIDTH,
@@ -38,19 +39,30 @@ __export(src_exports, {
38
39
  FeatureStore: () => FeatureStore,
39
40
  PublicStoreManager: () => PublicStoreManager,
40
41
  _resetIdbStoreSingletons: () => _resetIdbStoreSingletons,
42
+ applySectionSelection: () => applySectionSelection,
43
+ applyTransferLimits: () => applyTransferLimits,
41
44
  booleanUrlCodec: () => booleanUrlCodec,
45
+ buildAgentPayload: () => buildAgentPayload,
46
+ capture: () => capture,
42
47
  captureDrafts: () => captureDrafts,
48
+ collectAllMatching: () => collectAllMatching,
43
49
  commitUrlParams: () => commitUrlParams,
44
50
  computeSearchScore: () => computeSearchScore,
51
+ createBrowserTransport: () => createBrowserTransport,
45
52
  createColorNormalizer: () => createColorNormalizer,
53
+ createDraft: () => createDraft,
46
54
  createFormatter: () => createFormatter,
47
55
  createMatrxToast: () => createMatrxToast,
56
+ createSurfaceTransferHandle: () => createSurfaceTransferHandle,
48
57
  decodeQrFromElement: () => decodeQrFromElement,
49
58
  decodeQrFromImageData: () => decodeQrFromImageData,
50
59
  decodeQrFromImageFile: () => decodeQrFromImageFile,
51
60
  detectJson: () => detectJson,
61
+ directSource: () => directSource,
52
62
  discardDraft: () => discardDraft,
63
+ editDraft: () => editDraft,
53
64
  enumUrlCodec: () => enumUrlCodec,
65
+ fenceJsonBlock: () => fenceJsonBlock,
54
66
  filterAndSortBySearch: () => filterAndSortBySearch,
55
67
  findNearestTailwindColor: () => findNearestTailwindColor,
56
68
  fireInvalidation: () => fireInvalidation,
@@ -94,23 +106,38 @@ __export(src_exports, {
94
106
  jsonUrlCodec: () => jsonUrlCodec,
95
107
  listDrafts: () => listDrafts,
96
108
  matchesSearch: () => matchesSearch,
109
+ normalizeTransferJson: () => normalizeTransferJson,
97
110
  onFlushComplete: () => onFlushComplete,
98
111
  parseHexOrRgb: () => parseHexOrRgb,
99
112
  positiveIntegerUrlCodec: () => positiveIntegerUrlCodec,
113
+ projectSnapshot: () => projectSnapshot,
114
+ readTransferCell: () => readTransferCell,
115
+ reduceJson: () => reduceJson,
116
+ refreshDraft: () => refreshDraft,
100
117
  registerDraftSource: () => registerDraftSource,
101
118
  registerIdleTask: () => registerIdleTask,
102
119
  registerInvalidationCallback: () => registerInvalidationCallback,
120
+ renderMarkdownHtml: () => renderMarkdownHtml,
103
121
  reportDelimiterViolations: () => reportDelimiterViolations,
122
+ resetDraft: () => resetDraft,
104
123
  resetScheduler: () => resetScheduler,
124
+ resolveTransferPreferences: () => resolveTransferPreferences,
125
+ resolveTransferRegistry: () => resolveTransferRegistry,
105
126
  rgbDelta: () => rgbDelta,
106
127
  rgbToLab: () => rgbToLab,
107
128
  runWithConcurrency: () => runWithConcurrency,
129
+ sealTransferArtifact: () => sealTransferArtifact,
130
+ serialize: () => serialize,
131
+ serializeMarkdownRich: () => serializeMarkdownRich,
108
132
  setUrlStateRouter: () => setUrlStateRouter,
133
+ sourceChanged: () => sourceChanged,
109
134
  stringUrlCodec: () => stringUrlCodec,
110
135
  stringifyJson: () => stringifyJson,
111
136
  subscribeDrafts: () => subscribeDrafts,
112
137
  tailwindColors: () => tailwindColors,
138
+ transformRows: () => transformRows,
113
139
  treeContainsComponent: () => treeContainsComponent,
140
+ undoDraft: () => undoDraft,
114
141
  useAutosave: () => useAutosave,
115
142
  useClipboard: () => useClipboard,
116
143
  useDurableDraft: () => useDurableDraft,
@@ -930,7 +957,7 @@ function messageText(message, data) {
930
957
  }
931
958
  function createMatrxToast({
932
959
  toast: hostToast,
933
- capture
960
+ capture: capture2
934
961
  }) {
935
962
  if (typeof hostToast !== "function") {
936
963
  throw new Error(
@@ -938,9 +965,9 @@ function createMatrxToast({
938
965
  );
939
966
  }
940
967
  function captureToast(kind, message, data) {
941
- if (!capture) return;
968
+ if (!capture2) return;
942
969
  try {
943
- capture({
970
+ capture2({
944
971
  source: "user-toast",
945
972
  message: `${kind === "warning" ? "[warning] " : ""}${messageText(message, data)}`,
946
973
  userMessage: messageText(message, data),
@@ -2838,4 +2865,1148 @@ async function decodeQrFromImageFile(file) {
2838
2865
  bitmap.close();
2839
2866
  }
2840
2867
  }
2868
+
2869
+ // src/html-escape.ts
2870
+ var HTML_ESCAPES = {
2871
+ "&": "&",
2872
+ "<": "&lt;",
2873
+ ">": "&gt;",
2874
+ '"': "&quot;",
2875
+ "'": "&#39;"
2876
+ };
2877
+ var HTML_ESCAPE_RE = /[&<>"']/g;
2878
+ function escapeHtml(value) {
2879
+ if (typeof value !== "string") return "";
2880
+ return value.replace(HTML_ESCAPE_RE, (char) => HTML_ESCAPES[char] ?? char);
2881
+ }
2882
+
2883
+ // src/content-transfer/agent-payload.ts
2884
+ var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2885
+ var xmlName = (name) => {
2886
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name)) throw new Error(`Invalid AI envelope name: ${name}`);
2887
+ return name;
2888
+ };
2889
+ var presentEntries = (values) => Object.entries(values ?? {}).filter(([, value]) => value !== null && value !== void 0 && value !== "");
2890
+ function fenceJsonBlock(json) {
2891
+ const runs = json.match(/`+/g) ?? [];
2892
+ const fence = "`".repeat(Math.max(3, ...runs.map((run) => run.length + 1)));
2893
+ return `${fence}json
2894
+ ${json.trimEnd()}
2895
+ ${fence}`;
2896
+ }
2897
+ function buildAgentPayload(input, environment = {}) {
2898
+ const kind = xmlName(input.kind);
2899
+ const url = environment.url ?? (typeof window === "undefined" ? "" : window.location.href);
2900
+ const route = environment.route ?? (typeof window === "undefined" ? "" : window.location.pathname);
2901
+ const attrs = presentEntries(input.attributes).map(([key, value]) => ` ${xmlName(key)}="${escapeXml(String(value))}"`).join("");
2902
+ const entries = [
2903
+ ["location", input.location],
2904
+ ...url ? [["url", url]] : [],
2905
+ ...route ? [["route", route]] : [],
2906
+ ["copied", input.description],
2907
+ ["copied-at", environment.capturedAt ?? (/* @__PURE__ */ new Date()).toISOString()],
2908
+ ...presentEntries(input.context).map(([key, value]) => [xmlName(key), String(value)])
2909
+ ];
2910
+ const json = JSON.stringify(input.data, null, 2);
2911
+ if (json === void 0) throw new Error("AI envelope data must be JSON serializable.");
2912
+ const safeJson = json.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
2913
+ const context = entries.map(([key, value]) => `<${key}>${escapeXml(value)}</${key}>`).join("\n");
2914
+ const summary = input.summary ? `<summary>
2915
+ ${escapeXml(input.summary)}
2916
+ </summary>
2917
+ ` : "";
2918
+ return `<${kind}${attrs}>
2919
+ <context>
2920
+ ${context}
2921
+ </context>
2922
+ ${summary}<data format="json">
2923
+ ${fenceJsonBlock(safeJson)}
2924
+ </data>
2925
+ </${kind}>`;
2926
+ }
2927
+
2928
+ // src/content-transfer.ts
2929
+ var ContentTransferError = class extends Error {
2930
+ code;
2931
+ path;
2932
+ constructor(code, message, path) {
2933
+ super(message);
2934
+ this.code = code;
2935
+ this.path = path;
2936
+ }
2937
+ };
2938
+ var bound = /* @__PURE__ */ Symbol("bound-all-matching");
2939
+ var stop = (s) => {
2940
+ if (s.aborted) throw new DOMException("Cancelled", "AbortError");
2941
+ };
2942
+ var enc = (x) => x.replace(/~/g, "~0").replace(/\//g, "~1");
2943
+ var dec = (x) => x.replace(/~1/g, "/").replace(/~0/g, "~");
2944
+ function clone(v, path = "", seen = /* @__PURE__ */ new WeakSet()) {
2945
+ if (v === null || typeof v === "string" || typeof v === "boolean") return v;
2946
+ if (typeof v === "number") {
2947
+ if (!Number.isFinite(v))
2948
+ throw new ContentTransferError(
2949
+ "unsupported-value",
2950
+ "Only finite numbers are transferable",
2951
+ path
2952
+ );
2953
+ return v;
2954
+ }
2955
+ if (typeof v !== "object")
2956
+ throw new ContentTransferError(
2957
+ "unsupported-value",
2958
+ "Unsupported value",
2959
+ path
2960
+ );
2961
+ if (seen.has(v))
2962
+ throw new ContentTransferError(
2963
+ "circular-value",
2964
+ "Circular values cannot be transferred",
2965
+ path
2966
+ );
2967
+ if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null)
2968
+ throw new ContentTransferError(
2969
+ "unsupported-value",
2970
+ "Only plain JSON objects are transferable",
2971
+ path
2972
+ );
2973
+ seen.add(v);
2974
+ if (Array.isArray(v)) {
2975
+ for (let index = 0; index < v.length; index += 1)
2976
+ if (!Object.hasOwn(v, index))
2977
+ throw new ContentTransferError(
2978
+ "unsupported-value",
2979
+ "Sparse arrays cannot be transferred",
2980
+ `${path}/${index}`
2981
+ );
2982
+ }
2983
+ const out = Array.isArray(v) ? v.map((x, i) => clone(x, `${path}/${i}`, seen)) : Object.fromEntries(
2984
+ Object.entries(v).map(([k, x]) => [
2985
+ k,
2986
+ clone(x, `${path}/${enc(k)}`, seen)
2987
+ ])
2988
+ );
2989
+ seen.delete(v);
2990
+ return out;
2991
+ }
2992
+ function normalizeTransferJson(value) {
2993
+ return clone(value);
2994
+ }
2995
+ function deepFreeze(v) {
2996
+ if (ArrayBuffer.isView(v)) return v;
2997
+ if (v && typeof v === "object" && !Object.isFrozen(v)) {
2998
+ Object.freeze(v);
2999
+ for (const x of Object.values(v)) deepFreeze(x);
3000
+ }
3001
+ return v;
3002
+ }
3003
+ function at(v, path) {
3004
+ validatePointer(path);
3005
+ if (path === "") return v;
3006
+ if (!path.startsWith("/"))
3007
+ throw new ContentTransferError(
3008
+ "invalid-path",
3009
+ "Expected RFC 6901 pointer",
3010
+ path
3011
+ );
3012
+ let cur = v;
3013
+ for (const part of path.slice(1).split("/").map(dec)) {
3014
+ if (Array.isArray(cur)) cur = cur[Number(part)];
3015
+ else if (cur && typeof cur === "object")
3016
+ cur = Object.hasOwn(cur, part) ? cur[part] : void 0;
3017
+ else return void 0;
3018
+ }
3019
+ return cur;
3020
+ }
3021
+ function validatePointer(path) {
3022
+ if (path !== "" && !path.startsWith("/") || /~(?![01])/u.test(path))
3023
+ throw new ContentTransferError(
3024
+ "invalid-path",
3025
+ "Expected an RFC 6901 JSON pointer",
3026
+ path
3027
+ );
3028
+ }
3029
+ function readTransferCell(row, column) {
3030
+ return at(row, column.path);
3031
+ }
3032
+ function without(v, paths, omit, path = "") {
3033
+ if (paths.includes(path)) {
3034
+ omit.push({ path, reason: "excluded" });
3035
+ return void 0;
3036
+ }
3037
+ if (Array.isArray(v))
3038
+ return v.map((x, i) => without(x, paths, omit, `${path}/${i}`)).filter((x) => x !== void 0);
3039
+ if (v && typeof v === "object") {
3040
+ const out = /* @__PURE__ */ Object.create(null);
3041
+ for (const [k, x] of Object.entries(v)) {
3042
+ const y = without(x, paths, omit, `${path}/${enc(k)}`);
3043
+ if (y !== void 0) out[k] = y;
3044
+ }
3045
+ return out;
3046
+ }
3047
+ return v;
3048
+ }
3049
+ function projectValue(v, rules, target, omit) {
3050
+ rules.forEach((rule) => validatePointer(rule.path));
3051
+ return without(
3052
+ clone(v),
3053
+ rules.filter(
3054
+ (r) => r.target === target && (!r.exportable || r.classification !== "ordinary")
3055
+ ).map((r) => r.path),
3056
+ omit
3057
+ ) ?? null;
3058
+ }
3059
+ function normalize(p, projection, omit) {
3060
+ if (p.kind === "text" || p.kind === "markdown") {
3061
+ if (typeof p.text !== "string")
3062
+ throw new ContentTransferError(
3063
+ "unsupported-value",
3064
+ "Text payload must contain a string",
3065
+ "/text"
3066
+ );
3067
+ const value = projectValue(p.text, projection.rules, "payload", omit);
3068
+ return { kind: p.kind, text: typeof value === "string" ? value : "" };
3069
+ }
3070
+ if (p.kind === "json")
3071
+ return {
3072
+ kind: "json",
3073
+ value: projectValue(p.value, projection.rules, "payload", omit)
3074
+ };
3075
+ if (p.kind === "registered")
3076
+ return {
3077
+ kind: "registered",
3078
+ format: p.format,
3079
+ value: projectValue(p.value, projection.rules, "payload", omit)
3080
+ };
3081
+ const rowsPayload = p;
3082
+ if (p.kind !== "rows")
3083
+ throw new ContentTransferError(
3084
+ "invalid-payload",
3085
+ "Unsupported payload kind"
3086
+ );
3087
+ const columns = rowsPayload.columns.map((c) => ({ ...c }));
3088
+ resolveTransferRegistry(columns);
3089
+ columns.forEach((column) => validatePointer(column.path));
3090
+ const rules = [
3091
+ ...projection.rules,
3092
+ ...columns.filter(
3093
+ (c) => c.exportable === false || c.classification === "secret" || c.classification === "credential"
3094
+ ).map((c) => ({
3095
+ target: "row",
3096
+ path: c.path,
3097
+ exportable: c.exportable ?? true,
3098
+ classification: c.classification ?? "ordinary"
3099
+ }))
3100
+ ];
3101
+ return {
3102
+ kind: "rows",
3103
+ columns,
3104
+ rows: rowsPayload.rows.map((row, index) => {
3105
+ if (!row || typeof row !== "object" || Array.isArray(row))
3106
+ throw new ContentTransferError(
3107
+ "invalid-row",
3108
+ "A table row must be a JSON object",
3109
+ `/rows/${index}`
3110
+ );
3111
+ const projected = projectValue(row, rules, "row", omit);
3112
+ return projected === null ? {} : projected;
3113
+ })
3114
+ };
3115
+ }
3116
+ function projectSnapshot(raw, projection) {
3117
+ const omissions = raw.omissions.map((o) => ({ ...o }));
3118
+ const normalized = normalize(raw.payload, projection, omissions);
3119
+ const payload = raw.limits ? limitPayload(normalized, raw.limits, omissions) : normalized;
3120
+ const included = payload.kind === "rows" ? payload.rows.length : raw.coverage.included;
3121
+ return deepFreeze({
3122
+ ...raw,
3123
+ payload,
3124
+ coverage: {
3125
+ ...raw.coverage,
3126
+ included,
3127
+ ...included < raw.coverage.included ? { status: "partial", reason: "Source export limit applied" } : {}
3128
+ },
3129
+ omissions,
3130
+ sections: raw.sections.filter(
3131
+ (section) => !projection.rules.some(
3132
+ (rule) => rule.target === "payload" && (!rule.exportable || rule.classification !== "ordinary") && (section.path === rule.path || section.path.startsWith(`${rule.path}/`))
3133
+ )
3134
+ ).map((x) => ({ ...x })),
3135
+ ...raw.limits ? { limits: { ...raw.limits } } : {}
3136
+ });
3137
+ }
3138
+ var uid = () => globalThis.crypto?.randomUUID?.() ?? `capture-${Date.now()}-${Math.random()}`;
3139
+ function directSource(payload, options = {}) {
3140
+ const id = options.id ?? uid();
3141
+ return {
3142
+ projection: options.projection ?? { rules: [] },
3143
+ snapshot: {
3144
+ id,
3145
+ sourceId: options.sourceId ?? id,
3146
+ revision: options.revision ?? uid(),
3147
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
3148
+ label: options.label ?? "Content",
3149
+ payload,
3150
+ coverage: options.coverage ?? {
3151
+ status: "complete",
3152
+ included: payload.kind === "rows" ? payload.rows.length : 1,
3153
+ total: payload.kind === "rows" ? payload.rows.length : 1
3154
+ },
3155
+ unsavedChanges: options.unsavedChanges ?? false,
3156
+ omissions: [],
3157
+ sections: options.sections ?? [],
3158
+ ...options.limits ? { limits: { ...options.limits } } : {}
3159
+ }
3160
+ };
3161
+ }
3162
+ async function capture(source, signal, scope = "target") {
3163
+ stop(signal);
3164
+ const captured = "kind" in source ? directSource(source) : await source.capture({ scope, signal });
3165
+ stop(signal);
3166
+ const all = captured.allMatching;
3167
+ if (all && (all.query.sourceId !== captured.snapshot.sourceId || all.query.revision !== captured.snapshot.revision || all.query.order.length === 0))
3168
+ throw new ContentTransferError(
3169
+ "query-mismatch",
3170
+ "All-matching query must be captured with stable ordering"
3171
+ );
3172
+ const snapshot = projectSnapshot(captured.snapshot, captured.projection);
3173
+ if (!all) return { snapshot };
3174
+ return {
3175
+ snapshot,
3176
+ allMatching: deepFreeze({
3177
+ [bound]: true,
3178
+ source: {
3179
+ ...all,
3180
+ query: {
3181
+ ...all.query,
3182
+ query: clone(all.query.query),
3183
+ order: all.query.order.map((x) => ({ ...x }))
3184
+ }
3185
+ },
3186
+ projection: { rules: captured.projection.rules.map((x) => ({ ...x })) },
3187
+ columns: snapshot.payload.kind === "rows" ? snapshot.payload.columns : [],
3188
+ ...snapshot.limits ? { limits: { ...snapshot.limits } } : {}
3189
+ })
3190
+ };
3191
+ }
3192
+ function createDraft(s) {
3193
+ return deepFreeze({
3194
+ snapshotId: s.id,
3195
+ sourceId: s.sourceId,
3196
+ sourceRevision: s.revision,
3197
+ revision: 0,
3198
+ payload: normalize(s.payload, { rules: [] }, []),
3199
+ omissions: [...s.omissions],
3200
+ manuallyEdited: false,
3201
+ provenance: [{ kind: "original", description: "Captured source snapshot" }]
3202
+ });
3203
+ }
3204
+ function revise(d, p, o, description, manual = d.manuallyEdited, kind = "deterministic", baseOmissions = d.omissions) {
3205
+ const { history: _history, ...previous } = d;
3206
+ return deepFreeze({
3207
+ ...d,
3208
+ revision: d.revision + 1,
3209
+ payload: normalize(p, { rules: [] }, []),
3210
+ omissions: [...baseOmissions, ...o],
3211
+ manuallyEdited: manual,
3212
+ provenance: [...d.provenance, { kind, description }],
3213
+ history: [...d.history ?? [], previous]
3214
+ });
3215
+ }
3216
+ var editDraft = (d, p) => revise(d, p, [], "Manual edit", true, "manual");
3217
+ var resetDraft = (s) => createDraft(s);
3218
+ var sourceChanged = (d, s) => d.sourceId !== s.sourceId || d.sourceRevision !== s.revision;
3219
+ function undoDraft(d) {
3220
+ const previous = d.history?.at(-1);
3221
+ if (!previous) return d;
3222
+ return deepFreeze({
3223
+ ...previous,
3224
+ revision: d.revision + 1,
3225
+ history: d.history.slice(0, -1)
3226
+ });
3227
+ }
3228
+ function refreshDraft(draft, snapshot, choice) {
3229
+ return choice === "keep" ? draft : createDraft(snapshot);
3230
+ }
3231
+ function applySectionSelection(d, s, ids) {
3232
+ if (d.snapshotId !== s.id || d.sourceId !== s.sourceId || d.sourceRevision !== s.revision)
3233
+ throw new ContentTransferError(
3234
+ "snapshot-mismatch",
3235
+ "Section selection requires the draft's captured source snapshot"
3236
+ );
3237
+ const selected = new Set(ids), omit = [], paths = s.sections.filter((x) => !selected.has(x.id)).map((x) => {
3238
+ omit.push({ path: x.path, reason: "excluded" });
3239
+ return x.path;
3240
+ }), baseOmissions = s.omissions;
3241
+ if (s.payload.kind === "json")
3242
+ return revise(
3243
+ d,
3244
+ { kind: "json", value: without(s.payload.value, paths, []) ?? null },
3245
+ omit,
3246
+ "Selected sections",
3247
+ d.manuallyEdited,
3248
+ "deterministic",
3249
+ baseOmissions
3250
+ );
3251
+ if (s.payload.kind === "registered")
3252
+ return revise(
3253
+ d,
3254
+ {
3255
+ kind: "registered",
3256
+ format: s.payload.format,
3257
+ value: without(s.payload.value, paths, []) ?? null
3258
+ },
3259
+ omit,
3260
+ "Selected sections",
3261
+ d.manuallyEdited,
3262
+ "deterministic",
3263
+ baseOmissions
3264
+ );
3265
+ return revise(
3266
+ d,
3267
+ s.payload,
3268
+ omit,
3269
+ "Selected sections",
3270
+ d.manuallyEdited,
3271
+ "deterministic",
3272
+ baseOmissions
3273
+ );
3274
+ }
3275
+ function transformRows(d, o) {
3276
+ if (d.payload.kind !== "rows") return d;
3277
+ if (o.top != null) assertLimit(o.top, "maxRows");
3278
+ const cols = o.visibleColumns ? o.visibleColumns.map(
3279
+ (id) => d.payload.kind === "rows" ? d.payload.columns.find((c) => c.id === id) : void 0
3280
+ ).filter((c) => Boolean(c)) : d.payload.columns.filter((c) => c.visible);
3281
+ const get = readTransferCell;
3282
+ let rows = [...d.payload.rows], omit = [];
3283
+ const before = rows.length;
3284
+ if (o.selectedIndices !== void 0) {
3285
+ const selected = /* @__PURE__ */ new Set();
3286
+ for (const index of o.selectedIndices) {
3287
+ if (!Number.isSafeInteger(index) || index < 0 || index >= d.payload.rows.length)
3288
+ throw new ContentTransferError(
3289
+ "invalid-selection-index",
3290
+ "Selected row indexes must be non-negative positions in the input draft rows"
3291
+ );
3292
+ selected.add(index);
3293
+ }
3294
+ rows = d.payload.rows.filter((_, index) => selected.has(index));
3295
+ }
3296
+ if (o.selectedIds && o.idColumn) {
3297
+ const set = new Set(o.selectedIds);
3298
+ const idColumn = d.payload.columns.find((c) => c.id === o.idColumn);
3299
+ rows = rows.filter(
3300
+ (r) => set.has(String(idColumn ? get(r, idColumn) : r[o.idColumn]))
3301
+ );
3302
+ }
3303
+ if (o.search) {
3304
+ const q = o.search.toLowerCase();
3305
+ rows = rows.filter(
3306
+ (r) => cols.some(
3307
+ (c) => String(get(r, c) ?? "").toLowerCase().includes(q)
3308
+ )
3309
+ );
3310
+ }
3311
+ for (const [id, q] of Object.entries(o.filters ?? {})) {
3312
+ const c = cols.find((x) => x.id === id);
3313
+ if (c)
3314
+ rows = rows.filter(
3315
+ (r) => String(get(r, c) ?? "").toLowerCase().includes(q.toLowerCase())
3316
+ );
3317
+ }
3318
+ if (rows.length !== before)
3319
+ omit.push({
3320
+ path: "/rows",
3321
+ reason: "filtered",
3322
+ count: before - rows.length
3323
+ });
3324
+ if (o.sort) {
3325
+ const c = cols.find((x) => x.id === o.sort.column);
3326
+ if (c)
3327
+ rows.sort((a, b) => {
3328
+ const left = get(a, c);
3329
+ const right = get(b, c);
3330
+ const compare = typeof left === "number" && typeof right === "number" ? left - right : String(left ?? "").localeCompare(String(right ?? ""));
3331
+ return compare * (o.sort.direction === "asc" ? 1 : -1);
3332
+ });
3333
+ }
3334
+ if (o.top != null && rows.length > o.top) {
3335
+ omit.push({
3336
+ path: "/rows",
3337
+ reason: "truncated",
3338
+ count: rows.length - o.top
3339
+ });
3340
+ rows = rows.slice(0, o.top);
3341
+ }
3342
+ if (o.structuredProjection === "visible") {
3343
+ rows = rows.map(
3344
+ (r) => Object.fromEntries(cols.map((c) => [c.id, get(r, c) ?? null]))
3345
+ );
3346
+ omit.push({
3347
+ path: "/columns",
3348
+ reason: "excluded",
3349
+ count: d.payload.columns.length - cols.length
3350
+ });
3351
+ }
3352
+ return revise(
3353
+ d,
3354
+ {
3355
+ kind: "rows",
3356
+ rows,
3357
+ columns: cols.map((c) => ({
3358
+ ...c,
3359
+ visible: true,
3360
+ ...o.structuredProjection === "visible" ? { path: `/${enc(c.id)}` } : {}
3361
+ }))
3362
+ },
3363
+ omit,
3364
+ "Prepared row subset"
3365
+ );
3366
+ }
3367
+ function reduceJson(draft, options) {
3368
+ if (draft.payload.kind !== "json" && draft.payload.kind !== "registered")
3369
+ return draft;
3370
+ const omissions = [];
3371
+ options.exclude?.forEach(validatePointer);
3372
+ const filtered = without(clone(draft.payload.value), options.exclude ?? [], omissions) ?? null;
3373
+ const payload = limitPayload(
3374
+ { ...draft.payload, value: filtered },
3375
+ options,
3376
+ omissions
3377
+ );
3378
+ return revise(draft, payload, omissions, "Reduced JSON");
3379
+ }
3380
+ async function collectAllMatching(c, signal) {
3381
+ const rows = [], omissions = [], ids = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
3382
+ let cursor = null, token, last = {
3383
+ status: "unknown",
3384
+ included: 0,
3385
+ total: null
3386
+ };
3387
+ let certifiedTotal;
3388
+ const maxRows = c.limits?.maxRows;
3389
+ if (maxRows != null) assertLimit(maxRows, "maxRows");
3390
+ const finishAtLimit = (total, knownOmitted) => ({
3391
+ rows: deepFreeze(rows),
3392
+ omissions: deepFreeze([
3393
+ ...omissions,
3394
+ {
3395
+ path: "/rows",
3396
+ reason: "truncated",
3397
+ ...knownOmitted === void 0 || knownOmitted <= 0 ? {} : { count: knownOmitted }
3398
+ }
3399
+ ]),
3400
+ coverage: deepFreeze({
3401
+ status: "partial",
3402
+ included: rows.length,
3403
+ total,
3404
+ reason: "Source export limit applied"
3405
+ })
3406
+ });
3407
+ try {
3408
+ if (maxRows === 0) return finishAtLimit(null);
3409
+ do {
3410
+ stop(signal);
3411
+ const page = await c.source.page({
3412
+ query: c.source.query,
3413
+ cursor,
3414
+ consistencyToken: token ?? null,
3415
+ signal
3416
+ });
3417
+ stop(signal);
3418
+ if (token === void 0) token = page.consistencyToken;
3419
+ else if (page.consistencyToken !== token)
3420
+ throw new ContentTransferError(
3421
+ "consistency-token-changed",
3422
+ "All-matching export changed during collection"
3423
+ );
3424
+ if (page.coverage.included !== page.rows.length)
3425
+ throw new ContentTransferError(
3426
+ "invalid-page-coverage",
3427
+ "Page count does not match returned rows"
3428
+ );
3429
+ if (page.coverage.total !== null && (!Number.isSafeInteger(page.coverage.total) || page.coverage.total < 0))
3430
+ throw new ContentTransferError(
3431
+ "invalid-page-coverage",
3432
+ "Page total must be a non-negative integer or null"
3433
+ );
3434
+ if (certifiedTotal === void 0) certifiedTotal = page.coverage.total;
3435
+ else if (page.coverage.total !== certifiedTotal)
3436
+ throw new ContentTransferError(
3437
+ "inconsistent-total",
3438
+ "All-matching source changed its reported total during collection"
3439
+ );
3440
+ const projected = normalize(
3441
+ { kind: "rows", rows: page.rows, columns: [...c.columns] },
3442
+ c.projection,
3443
+ omissions
3444
+ ).rows;
3445
+ let uniqueBeyondLimit = 0;
3446
+ for (const row of projected) {
3447
+ const id = c.source.getRowId(row);
3448
+ if (!id)
3449
+ throw new ContentTransferError(
3450
+ "invalid-row-id",
3451
+ "All-matching source returned empty projected ID"
3452
+ );
3453
+ if (!ids.has(id)) {
3454
+ ids.add(id);
3455
+ if (maxRows == null || rows.length < maxRows)
3456
+ rows.push(
3457
+ limitPayload(
3458
+ { kind: "rows", rows: [row], columns: [...c.columns] },
3459
+ { ...c.limits, maxRows: null },
3460
+ omissions
3461
+ ).rows[0]
3462
+ );
3463
+ else uniqueBeyondLimit += 1;
3464
+ } else omissions.push({ path: `/rows/${enc(id)}`, reason: "duplicate" });
3465
+ }
3466
+ if (page.coverage.total !== null && page.coverage.total < ids.size)
3467
+ throw new ContentTransferError(
3468
+ "invalid-page-coverage",
3469
+ "Page total is smaller than the accumulated unique row count"
3470
+ );
3471
+ last = page.coverage;
3472
+ if (maxRows != null && rows.length >= maxRows && (uniqueBeyondLimit > 0 || page.nextCursor !== null))
3473
+ return finishAtLimit(
3474
+ page.coverage.total,
3475
+ page.nextCursor === null ? uniqueBeyondLimit : page.coverage.total != null && page.coverage.total > rows.length ? page.coverage.total - rows.length : void 0
3476
+ );
3477
+ cursor = page.nextCursor;
3478
+ if (cursor !== null && (!cursor || cursors.has(cursor)))
3479
+ throw new ContentTransferError(
3480
+ "non-advancing-cursor",
3481
+ "All-matching source repeated a cursor"
3482
+ );
3483
+ if (cursor) cursors.add(cursor);
3484
+ } while (cursor !== null);
3485
+ const complete = c.source.stableSnapshot === true && last.status === "complete" && last.total === rows.length && token !== void 0;
3486
+ return {
3487
+ rows: deepFreeze(rows),
3488
+ omissions: deepFreeze(omissions),
3489
+ coverage: deepFreeze(
3490
+ complete ? { ...last, included: rows.length } : {
3491
+ ...last,
3492
+ status: "partial",
3493
+ included: rows.length,
3494
+ reason: last.reason ?? "Source did not certify a stable complete snapshot"
3495
+ }
3496
+ )
3497
+ };
3498
+ } catch (e) {
3499
+ const error = e instanceof ContentTransferError ? e : new ContentTransferError(
3500
+ signal.aborted ? "cancelled" : "page-failed",
3501
+ e instanceof Error ? e.message : "Page collection failed"
3502
+ );
3503
+ return {
3504
+ rows: deepFreeze(rows),
3505
+ omissions: deepFreeze(omissions),
3506
+ coverage: deepFreeze({
3507
+ status: "partial",
3508
+ included: rows.length,
3509
+ total: last.total,
3510
+ reason: error.message
3511
+ }),
3512
+ error
3513
+ };
3514
+ }
3515
+ }
3516
+ var textValue = (value) => value === void 0 ? "" : typeof value === "string" ? value : stringifyJson(value, { style: "compact" });
3517
+ function sealTransferArtifact(artifact) {
3518
+ if (!artifact.file)
3519
+ return deepFreeze({
3520
+ ...artifact,
3521
+ omissions: artifact.omissions.map((o) => ({ ...o }))
3522
+ });
3523
+ const bytes = artifact.file.bytes.slice();
3524
+ const file = {
3525
+ filename: artifact.file.filename,
3526
+ mime: artifact.file.mime,
3527
+ get bytes() {
3528
+ return bytes.slice();
3529
+ }
3530
+ };
3531
+ return deepFreeze({
3532
+ ...artifact,
3533
+ file,
3534
+ omissions: artifact.omissions.map((o) => ({ ...o }))
3535
+ });
3536
+ }
3537
+ function serialize(draft, format, options = {}) {
3538
+ const payload = draft.payload;
3539
+ const omissions = draft.omissions.map((o) => ({ ...o }));
3540
+ let plainText = "", html;
3541
+ let mime = "text/plain;charset=utf-8", extension = "txt";
3542
+ const columnCell = (row, column) => textValue(readTransferCell(row, column));
3543
+ if ((format === "csv" || format === "tsv") && payload.kind !== "rows") {
3544
+ throw new ContentTransferError(
3545
+ "unsupported-format",
3546
+ `${format.toUpperCase()} requires tabular data`
3547
+ );
3548
+ }
3549
+ if (format === "json" || format === "compact-json") {
3550
+ const value = payload.kind === "rows" ? payload.rows : payload.kind === "text" || payload.kind === "markdown" ? payload.text : payload.value;
3551
+ plainText = stringifyJson(value, {
3552
+ style: format === "json" ? "pretty" : "compact"
3553
+ });
3554
+ mime = "application/json;charset=utf-8";
3555
+ extension = "json";
3556
+ } else if (payload.kind === "rows") {
3557
+ const columns = payload.columns.filter(
3558
+ (c) => c.visible && c.exportable !== false && c.classification !== "secret" && c.classification !== "credential"
3559
+ );
3560
+ if (format === "markdown") {
3561
+ const escapeCell = (value) => escapeHtml(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
3562
+ plainText = [
3563
+ `| ${columns.map((c) => escapeCell(c.label)).join(" | ")} |`,
3564
+ `| ${columns.map(() => "---").join(" | ")} |`,
3565
+ ...payload.rows.map(
3566
+ (row) => `| ${columns.map((c) => escapeCell(columnCell(row, c))).join(" | ")} |`
3567
+ )
3568
+ ].join("\n");
3569
+ mime = "text/markdown;charset=utf-8";
3570
+ extension = "md";
3571
+ } else {
3572
+ const delimiter = format === "csv" ? "," : " ";
3573
+ const safe = options.spreadsheetSafe ?? format === "tsv";
3574
+ const encode = (value, path, isString = true) => {
3575
+ let text = value;
3576
+ if (safe && isString && /^[\t\r\n ]*[=+\-@]/.test(text)) {
3577
+ text = `'${text}`;
3578
+ omissions.push({ path, reason: "escaped", count: 1 });
3579
+ }
3580
+ return text.includes(delimiter) || /["\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
3581
+ };
3582
+ plainText = [
3583
+ columns.map((c) => encode(c.label, `/columns/${enc(c.id)}`)).join(delimiter),
3584
+ ...payload.rows.map(
3585
+ (row, index) => columns.map(
3586
+ (c) => encode(
3587
+ columnCell(row, c),
3588
+ `/rows/${index}${c.path}`,
3589
+ typeof readTransferCell(row, c) === "string"
3590
+ )
3591
+ ).join(delimiter)
3592
+ )
3593
+ ].join("\n");
3594
+ if (format === "csv") {
3595
+ mime = "text/csv;charset=utf-8";
3596
+ extension = "csv";
3597
+ }
3598
+ if (format === "tsv") {
3599
+ mime = "text/tab-separated-values;charset=utf-8";
3600
+ extension = "tsv";
3601
+ }
3602
+ }
3603
+ if (format === "html")
3604
+ html = `<table><thead><tr>${columns.map((c) => `<th>${escapeHtml(c.label)}</th>`).join("")}</tr></thead><tbody>${payload.rows.map((row) => `<tr>${columns.map((c) => `<td>${escapeHtml(columnCell(row, c)).replace(/\r\n|\r|\n/g, "<br>")}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
3605
+ } else {
3606
+ plainText = payload.kind === "text" || payload.kind === "markdown" ? payload.text : stringifyJson(payload.value, { style: "pretty" });
3607
+ if (format === "markdown") {
3608
+ mime = "text/markdown;charset=utf-8";
3609
+ extension = "md";
3610
+ }
3611
+ if (format === "html") html = `<pre>${escapeHtml(plainText)}</pre>`;
3612
+ }
3613
+ if (format === "html") {
3614
+ mime = "text/html;charset=utf-8";
3615
+ extension = "html";
3616
+ }
3617
+ return sealTransferArtifact({
3618
+ snapshotId: draft.snapshotId,
3619
+ draftRevision: draft.revision,
3620
+ format,
3621
+ plainText,
3622
+ ...html === void 0 ? {} : { html },
3623
+ file: {
3624
+ filename: options.filename ?? `export.${extension}`,
3625
+ mime,
3626
+ bytes: new TextEncoder().encode(
3627
+ format === "html" ? html ?? plainText : plainText
3628
+ )
3629
+ },
3630
+ omissions
3631
+ });
3632
+ }
3633
+ async function renderMarkdownHtml(markdown) {
3634
+ const [{ marked }, purify] = await Promise.all([
3635
+ import("marked"),
3636
+ import("dompurify")
3637
+ ]);
3638
+ const html = await marked.parse(markdown);
3639
+ const api = purify.default;
3640
+ if (typeof api === "function" && typeof window !== "undefined") {
3641
+ const purifier = api(window);
3642
+ if (typeof purifier?.sanitize === "function") return purifier.sanitize(html);
3643
+ }
3644
+ if (typeof api.sanitize === "function")
3645
+ return api.sanitize(html);
3646
+ throw new ContentTransferError(
3647
+ "rich-html-unavailable",
3648
+ "Rich Markdown HTML requires a DOMPurify DOM adapter"
3649
+ );
3650
+ }
3651
+ async function serializeMarkdownRich(d, filename = "export.html") {
3652
+ if (d.payload.kind !== "markdown")
3653
+ throw new ContentTransferError(
3654
+ "unsupported-format",
3655
+ "Rich Markdown requires Markdown payload"
3656
+ );
3657
+ const html = await renderMarkdownHtml(d.payload.text);
3658
+ return sealTransferArtifact({
3659
+ snapshotId: d.snapshotId,
3660
+ draftRevision: d.revision,
3661
+ format: "html",
3662
+ plainText: d.payload.text,
3663
+ html,
3664
+ file: {
3665
+ filename,
3666
+ mime: "text/html;charset=utf-8",
3667
+ bytes: new TextEncoder().encode(html)
3668
+ },
3669
+ omissions: [...d.omissions]
3670
+ });
3671
+ }
3672
+ function createBrowserTransport() {
3673
+ return {
3674
+ async copy(a, signal) {
3675
+ const cancelled = () => signal.aborted ? { status: "cancelled" } : void 0;
3676
+ try {
3677
+ if (cancelled()) return cancelled();
3678
+ const c = globalThis.navigator?.clipboard;
3679
+ if (!c?.write && !c?.writeText)
3680
+ return {
3681
+ status: "error",
3682
+ code: "clipboard-unavailable",
3683
+ message: "Clipboard writing is unavailable",
3684
+ retryable: false
3685
+ };
3686
+ if (a.html && c.write && typeof globalThis.ClipboardItem === "function") {
3687
+ try {
3688
+ await c.write([
3689
+ new ClipboardItem({
3690
+ "text/plain": new Blob([a.plainText], { type: "text/plain" }),
3691
+ "text/html": new Blob([a.html], { type: "text/html" })
3692
+ })
3693
+ ]);
3694
+ if (cancelled()) return cancelled();
3695
+ return {
3696
+ status: "success",
3697
+ delivered: "clipboard",
3698
+ mimeTypes: ["text/plain", "text/html"]
3699
+ };
3700
+ } catch {
3701
+ if (cancelled()) return cancelled();
3702
+ }
3703
+ }
3704
+ if (c.writeText) {
3705
+ await c.writeText(a.plainText);
3706
+ if (cancelled()) return cancelled();
3707
+ return a.html ? {
3708
+ status: "degraded",
3709
+ delivered: "plain-text",
3710
+ reason: "Rich clipboard write was unavailable or rejected"
3711
+ } : {
3712
+ status: "success",
3713
+ delivered: "clipboard",
3714
+ mimeTypes: ["text/plain"]
3715
+ };
3716
+ }
3717
+ return {
3718
+ status: "error",
3719
+ code: "clipboard-rejected",
3720
+ message: "Clipboard rejected the write",
3721
+ retryable: true
3722
+ };
3723
+ } catch (e) {
3724
+ return cancelled() ?? {
3725
+ status: "error",
3726
+ code: "clipboard-rejected",
3727
+ message: e instanceof Error ? e.message : "Clipboard rejected the write",
3728
+ retryable: true
3729
+ };
3730
+ }
3731
+ },
3732
+ async download(a, signal) {
3733
+ if (signal.aborted) return { status: "cancelled" };
3734
+ if (!a.file || typeof document === "undefined" || !URL?.createObjectURL)
3735
+ return {
3736
+ status: "error",
3737
+ code: "download-unavailable",
3738
+ message: "Download is unavailable",
3739
+ retryable: false
3740
+ };
3741
+ let url;
3742
+ try {
3743
+ url = URL.createObjectURL(
3744
+ new Blob([a.file.bytes.slice().buffer], {
3745
+ type: a.file.mime
3746
+ })
3747
+ );
3748
+ const link = document.createElement("a");
3749
+ link.href = url;
3750
+ link.download = a.file.filename;
3751
+ link.click();
3752
+ return signal.aborted ? { status: "cancelled" } : {
3753
+ status: "success",
3754
+ delivered: "download-started",
3755
+ mimeTypes: [a.file.mime]
3756
+ };
3757
+ } catch (e) {
3758
+ return signal.aborted ? { status: "cancelled" } : {
3759
+ status: "error",
3760
+ code: "download-failed",
3761
+ message: e instanceof Error ? e.message : "Download failed",
3762
+ retryable: true
3763
+ };
3764
+ } finally {
3765
+ if (url) setTimeout(() => URL.revokeObjectURL(url), 0);
3766
+ }
3767
+ }
3768
+ };
3769
+ }
3770
+ function assertLimit(value, name) {
3771
+ if (value != null && (!Number.isSafeInteger(value) || value < 0)) {
3772
+ throw new ContentTransferError(
3773
+ "invalid-limit",
3774
+ `${name} must be a non-negative safe integer or null`
3775
+ );
3776
+ }
3777
+ }
3778
+ var limitKeys = [
3779
+ "maxRows",
3780
+ "maxStringChars",
3781
+ "maxDepth",
3782
+ "maxArrayItems",
3783
+ "targetTokens"
3784
+ ];
3785
+ function resolveTransferPreferences(provider = {}, menu = {}, sourceLimits = {}) {
3786
+ const limits = {
3787
+ maxRows: null,
3788
+ maxStringChars: null,
3789
+ maxDepth: null,
3790
+ maxArrayItems: null,
3791
+ targetTokens: null
3792
+ };
3793
+ for (const key of limitKeys) {
3794
+ const candidates = [
3795
+ provider.limits?.[key],
3796
+ menu.limits?.[key],
3797
+ sourceLimits[key]
3798
+ ];
3799
+ candidates.forEach((value) => assertLimit(value, key));
3800
+ const finite = candidates.filter((value) => value != null);
3801
+ limits[key] = finite.length ? Math.min(...finite) : null;
3802
+ }
3803
+ return deepFreeze({
3804
+ initialFormat: menu.initialFormat ?? provider.initialFormat ?? "plain",
3805
+ initialPreset: menu.initialPreset ?? provider.initialPreset ?? "full",
3806
+ limits
3807
+ });
3808
+ }
3809
+ function cloneTransferRegistration(value, path = "registration", seen = /* @__PURE__ */ new WeakSet()) {
3810
+ if (value === null || typeof value !== "object" && typeof value !== "function")
3811
+ return value;
3812
+ if (typeof value === "function") return value;
3813
+ if (seen.has(value))
3814
+ throw new ContentTransferError(
3815
+ "unsupported-registration-metadata",
3816
+ "Circular transfer registration metadata is unsupported",
3817
+ path
3818
+ );
3819
+ seen.add(value);
3820
+ if (Array.isArray(value)) {
3821
+ const copy2 = value.map(
3822
+ (item, index) => cloneTransferRegistration(item, `${path}/${index}`, seen)
3823
+ );
3824
+ seen.delete(value);
3825
+ return Object.freeze(copy2);
3826
+ }
3827
+ const prototype = Object.getPrototypeOf(value);
3828
+ if (prototype !== Object.prototype && prototype !== null)
3829
+ throw new ContentTransferError(
3830
+ "unsupported-registration-metadata",
3831
+ "Transfer registration metadata must use plain objects and arrays",
3832
+ path
3833
+ );
3834
+ const copy = Object.create(prototype);
3835
+ for (const key of Reflect.ownKeys(value)) {
3836
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3837
+ if (!("value" in descriptor))
3838
+ throw new ContentTransferError(
3839
+ "unsupported-registration-metadata",
3840
+ "Transfer registration metadata cannot use accessors",
3841
+ `${path}/${String(key)}`
3842
+ );
3843
+ Object.defineProperty(copy, key, {
3844
+ value: cloneTransferRegistration(
3845
+ descriptor.value,
3846
+ `${path}/${String(key)}`,
3847
+ seen
3848
+ ),
3849
+ enumerable: descriptor.enumerable === true,
3850
+ writable: false,
3851
+ configurable: false
3852
+ });
3853
+ }
3854
+ seen.delete(value);
3855
+ return Object.freeze(copy);
3856
+ }
3857
+ function resolveTransferRegistry(...groups) {
3858
+ const ids = /* @__PURE__ */ new Set();
3859
+ const result = [];
3860
+ for (const group of groups)
3861
+ for (const item of group) {
3862
+ const copy = cloneTransferRegistration(item);
3863
+ if (!copy.id.trim() || ids.has(copy.id))
3864
+ throw new ContentTransferError(
3865
+ "duplicate-registration",
3866
+ `Transfer id ${JSON.stringify(copy.id)} is empty or registered more than once`
3867
+ );
3868
+ ids.add(copy.id);
3869
+ result.push(copy);
3870
+ }
3871
+ return Object.freeze(result);
3872
+ }
3873
+ function createSurfaceTransferHandle(options) {
3874
+ const declarations = resolveTransferRegistry(
3875
+ options.manifest.values.map((value) => ({ ...value, id: value.name }))
3876
+ );
3877
+ return {
3878
+ instanceId: options.instanceId,
3879
+ surfaceName: options.manifest.surfaceName,
3880
+ isMounted: options.isMounted,
3881
+ async capture(signal) {
3882
+ stop(signal);
3883
+ if (!options.isMounted())
3884
+ throw new ContentTransferError(
3885
+ "surface-unmounted",
3886
+ "The captured surface is no longer mounted"
3887
+ );
3888
+ const revisionBefore = options.getRevision?.();
3889
+ const scope = await options.getScope();
3890
+ stop(signal);
3891
+ if (!options.isMounted())
3892
+ throw new ContentTransferError(
3893
+ "surface-unmounted",
3894
+ "The surface closed during capture"
3895
+ );
3896
+ if (revisionBefore !== void 0 && options.getRevision?.() !== revisionBefore)
3897
+ throw new ContentTransferError(
3898
+ "surface-changed",
3899
+ "The surface changed during capture; capture again"
3900
+ );
3901
+ const value = {};
3902
+ for (const declaration of declarations) {
3903
+ if (Object.hasOwn(scope, declaration.name) && scope[declaration.name] !== void 0) {
3904
+ Object.defineProperty(value, declaration.name, {
3905
+ value: clone(
3906
+ scope[declaration.name],
3907
+ `/${enc(declaration.name)}`
3908
+ ),
3909
+ enumerable: true,
3910
+ writable: true,
3911
+ configurable: true
3912
+ });
3913
+ }
3914
+ }
3915
+ return directSource(
3916
+ { kind: "json", value },
3917
+ {
3918
+ sourceId: options.instanceId,
3919
+ revision: revisionBefore ?? uid(),
3920
+ label: options.manifest.label ?? options.manifest.surfaceName,
3921
+ unsavedChanges: options.unsavedChanges?.() ?? false,
3922
+ sections: declarations.filter((d) => Object.hasOwn(value, d.name)).map((d) => ({
3923
+ id: d.name,
3924
+ label: d.label,
3925
+ path: `/${enc(d.name)}`,
3926
+ includedByDefault: d.includedByDefault ?? true
3927
+ })),
3928
+ projection: {
3929
+ rules: [
3930
+ ...options.projection?.rules ?? [],
3931
+ ...declarations.map((d) => ({
3932
+ target: "payload",
3933
+ path: `/${enc(d.name)}`,
3934
+ exportable: d.exportable ?? true,
3935
+ classification: d.classification ?? "ordinary"
3936
+ }))
3937
+ ]
3938
+ },
3939
+ ...options.limits ? { limits: options.limits } : {}
3940
+ }
3941
+ );
3942
+ }
3943
+ };
3944
+ }
3945
+ function limitJson(value, limits, omissions, path = "", depth = 0) {
3946
+ if (limits.maxDepth != null && depth > limits.maxDepth) {
3947
+ omissions.push({ path, reason: "truncated" });
3948
+ return null;
3949
+ }
3950
+ if (typeof value === "string" && limits.maxStringChars != null && Array.from(value).length > limits.maxStringChars) {
3951
+ const chars = Array.from(value);
3952
+ omissions.push({
3953
+ path,
3954
+ reason: "truncated",
3955
+ count: chars.length - limits.maxStringChars
3956
+ });
3957
+ return chars.slice(0, limits.maxStringChars).join("");
3958
+ }
3959
+ if (Array.isArray(value)) {
3960
+ const count = Math.min(value.length, limits.maxArrayItems ?? value.length);
3961
+ if (count < value.length)
3962
+ omissions.push({
3963
+ path,
3964
+ reason: "truncated",
3965
+ count: value.length - count
3966
+ });
3967
+ return value.slice(0, count).map(
3968
+ (item, index) => limitJson(item, limits, omissions, `${path}/${index}`, depth + 1)
3969
+ );
3970
+ }
3971
+ if (value && typeof value === "object")
3972
+ return Object.fromEntries(
3973
+ Object.entries(value).map(([key, item]) => [
3974
+ key,
3975
+ limitJson(item, limits, omissions, `${path}/${enc(key)}`, depth + 1)
3976
+ ])
3977
+ );
3978
+ return value;
3979
+ }
3980
+ function limitPayload(payload, limits, omissions) {
3981
+ limitKeys.forEach((key) => assertLimit(limits[key], key));
3982
+ if (payload.kind === "rows") {
3983
+ const count = Math.min(
3984
+ payload.rows.length,
3985
+ limits.maxRows ?? payload.rows.length
3986
+ );
3987
+ if (count < payload.rows.length)
3988
+ omissions.push({
3989
+ path: "/rows",
3990
+ reason: "truncated",
3991
+ count: payload.rows.length - count
3992
+ });
3993
+ return {
3994
+ ...payload,
3995
+ rows: payload.rows.slice(0, count).map(
3996
+ (row, index) => limitJson(row, limits, omissions, `/rows/${index}`)
3997
+ )
3998
+ };
3999
+ }
4000
+ if (payload.kind === "json" || payload.kind === "registered")
4001
+ return { ...payload, value: limitJson(payload.value, limits, omissions) };
4002
+ return {
4003
+ ...payload,
4004
+ text: limitJson(payload.text, limits, omissions)
4005
+ };
4006
+ }
4007
+ function applyTransferLimits(draft, limits) {
4008
+ const omissions = [];
4009
+ const payload = limitPayload(draft.payload, limits, omissions);
4010
+ return omissions.length ? revise(draft, payload, omissions, "Applied preparation limits") : draft;
4011
+ }
2841
4012
  //# sourceMappingURL=index.cjs.map