@ai-matrx/alchemy 0.6.2 → 0.8.2
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/CHANGELOG.md +58 -0
- package/dist/actions.cjs +374 -0
- package/dist/actions.cjs.map +1 -0
- package/dist/actions.d.cts +773 -0
- package/dist/actions.d.ts +773 -0
- package/dist/actions.js +351 -0
- package/dist/actions.js.map +1 -0
- package/dist/checks.cjs +31 -2
- package/dist/checks.cjs.map +1 -1
- package/dist/checks.d.cts +24 -1
- package/dist/checks.d.ts +24 -1
- package/dist/checks.js +31 -2
- package/dist/checks.js.map +1 -1
- package/dist/core.cjs +1757 -2
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +595 -1
- package/dist/core.d.ts +595 -1
- package/dist/core.js +1749 -2
- package/dist/core.js.map +1 -1
- package/dist/declare.cjs +12 -10
- package/dist/declare.cjs.map +1 -1
- package/dist/declare.d.cts +18 -2
- package/dist/declare.d.ts +18 -2
- package/dist/declare.js +12 -10
- package/dist/declare.js.map +1 -1
- package/dist/index.cjs +1757 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +595 -1
- package/dist/index.d.ts +595 -1
- package/dist/index.js +1749 -2
- package/dist/index.js.map +1 -1
- package/dist/menu.cjs +436 -0
- package/dist/menu.cjs.map +1 -0
- package/dist/menu.d.cts +834 -0
- package/dist/menu.d.ts +834 -0
- package/dist/menu.js +413 -0
- package/dist/menu.js.map +1 -0
- package/dist/operate-document.cjs +163 -0
- package/dist/operate-document.cjs.map +1 -0
- package/dist/operate-document.d.cts +132 -0
- package/dist/operate-document.d.ts +132 -0
- package/dist/operate-document.js +130 -0
- package/dist/operate-document.js.map +1 -0
- package/dist/operate-rich-html.cjs +129 -0
- package/dist/operate-rich-html.cjs.map +1 -0
- package/dist/operate-rich-html.d.cts +136 -0
- package/dist/operate-rich-html.d.ts +136 -0
- package/dist/operate-rich-html.js +96 -0
- package/dist/operate-rich-html.js.map +1 -0
- package/dist/operate-server.cjs +157 -0
- package/dist/operate-server.cjs.map +1 -0
- package/dist/operate-server.d.cts +183 -0
- package/dist/operate-server.d.ts +183 -0
- package/dist/operate-server.js +134 -0
- package/dist/operate-server.js.map +1 -0
- package/dist/operate-xlsx.cjs +248 -0
- package/dist/operate-xlsx.cjs.map +1 -0
- package/dist/operate-xlsx.d.cts +129 -0
- package/dist/operate-xlsx.d.ts +129 -0
- package/dist/operate-xlsx.js +215 -0
- package/dist/operate-xlsx.js.map +1 -0
- package/dist/operate.cjs +1774 -0
- package/dist/operate.cjs.map +1 -0
- package/dist/operate.d.cts +595 -0
- package/dist/operate.d.ts +595 -0
- package/dist/operate.js +1750 -0
- package/dist/operate.js.map +1 -0
- package/dist/ports.cjs.map +1 -1
- package/dist/ports.d.cts +361 -3
- package/dist/ports.d.ts +361 -3
- package/dist/react-bar.cjs +686 -0
- package/dist/react-bar.cjs.map +1 -0
- package/dist/react-bar.d.cts +379 -0
- package/dist/react-bar.d.ts +379 -0
- package/dist/react-bar.js +665 -0
- package/dist/react-bar.js.map +1 -0
- package/dist/react-host.cjs +301 -0
- package/dist/react-host.cjs.map +1 -0
- package/dist/react-host.d.cts +820 -0
- package/dist/react-host.d.ts +820 -0
- package/dist/react-host.js +269 -0
- package/dist/react-host.js.map +1 -0
- package/dist/react-menu.cjs +735 -0
- package/dist/react-menu.cjs.map +1 -0
- package/dist/react-menu.d.cts +370 -0
- package/dist/react-menu.d.ts +370 -0
- package/dist/react-menu.js +722 -0
- package/dist/react-menu.js.map +1 -0
- package/dist/react-overflow.cjs +592 -0
- package/dist/react-overflow.cjs.map +1 -0
- package/dist/react-overflow.d.cts +817 -0
- package/dist/react-overflow.d.ts +817 -0
- package/dist/react-overflow.js +571 -0
- package/dist/react-overflow.js.map +1 -0
- package/dist/react-palette.cjs +489 -0
- package/dist/react-palette.cjs.map +1 -0
- package/dist/react-palette.d.cts +359 -0
- package/dist/react-palette.d.ts +359 -0
- package/dist/react-palette.js +457 -0
- package/dist/react-palette.js.map +1 -0
- package/dist/react-selection.cjs +617 -0
- package/dist/react-selection.cjs.map +1 -0
- package/dist/react-selection.d.cts +357 -0
- package/dist/react-selection.d.ts +357 -0
- package/dist/react-selection.js +596 -0
- package/dist/react-selection.js.map +1 -0
- package/dist/react-sheet.cjs +616 -0
- package/dist/react-sheet.cjs.map +1 -0
- package/dist/react-sheet.d.cts +361 -0
- package/dist/react-sheet.d.ts +361 -0
- package/dist/react-sheet.js +595 -0
- package/dist/react-sheet.js.map +1 -0
- package/package.json +148 -5
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
6
15
|
var __copyProps = (to, from, except, desc) => {
|
|
7
16
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
17
|
for (let key of __getOwnPropNames(from))
|
|
@@ -11,11 +20,1757 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
11
20
|
}
|
|
12
21
|
return to;
|
|
13
22
|
};
|
|
14
|
-
var
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
|
+
));
|
|
15
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
16
32
|
|
|
33
|
+
// src/operate/types.ts
|
|
34
|
+
var init_types = __esm({
|
|
35
|
+
"src/operate/types.ts"() {
|
|
36
|
+
"use strict";
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// src/operate/fenced-code.ts
|
|
41
|
+
function fencedCodeBlock(text, language) {
|
|
42
|
+
const runs = text.match(/`+/g) ?? [];
|
|
43
|
+
const fence = "`".repeat(Math.max(3, ...runs.map((run) => run.length + 1)));
|
|
44
|
+
return `${fence}${language}
|
|
45
|
+
${text}${text.endsWith("\n") ? "" : "\n"}${fence}`;
|
|
46
|
+
}
|
|
47
|
+
var init_fenced_code = __esm({
|
|
48
|
+
"src/operate/fenced-code.ts"() {
|
|
49
|
+
"use strict";
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// src/operate/agent-payload.ts
|
|
54
|
+
function fenceJsonBlock(json) {
|
|
55
|
+
return fencedCodeBlock(json.trimEnd(), "json");
|
|
56
|
+
}
|
|
57
|
+
function buildAgentPayload(input, environment = {}) {
|
|
58
|
+
const kind = xmlName(input.kind);
|
|
59
|
+
const url = environment.url ?? (typeof window === "undefined" ? "" : window.location.href);
|
|
60
|
+
const route = environment.route ?? (typeof window === "undefined" ? "" : window.location.pathname);
|
|
61
|
+
const attrs = presentEntries(input.attributes).map(([key, value]) => ` ${xmlName(key)}="${escapeXml(String(value))}"`).join("");
|
|
62
|
+
const entries = [
|
|
63
|
+
["location", input.location],
|
|
64
|
+
...url ? [["url", url]] : [],
|
|
65
|
+
...route ? [["route", route]] : [],
|
|
66
|
+
["copied", input.description],
|
|
67
|
+
["copied-at", environment.capturedAt ?? (/* @__PURE__ */ new Date()).toISOString()],
|
|
68
|
+
...presentEntries(input.context).map(([key, value]) => [xmlName(key), String(value)])
|
|
69
|
+
];
|
|
70
|
+
const json = JSON.stringify(input.data, null, 2);
|
|
71
|
+
if (json === void 0) throw new Error("AI envelope data must be JSON serializable.");
|
|
72
|
+
const safeJson = json.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
|
|
73
|
+
const context = entries.map(([key, value]) => `<${key}>${escapeXml(value)}</${key}>`).join("\n");
|
|
74
|
+
const summary = input.summary ? `<summary>
|
|
75
|
+
${escapeXml(input.summary)}
|
|
76
|
+
</summary>
|
|
77
|
+
` : "";
|
|
78
|
+
return `<${kind}${attrs}>
|
|
79
|
+
<context>
|
|
80
|
+
${context}
|
|
81
|
+
</context>
|
|
82
|
+
${summary}<data format="json">
|
|
83
|
+
${fenceJsonBlock(safeJson)}
|
|
84
|
+
</data>
|
|
85
|
+
</${kind}>`;
|
|
86
|
+
}
|
|
87
|
+
var escapeXml, xmlName, presentEntries;
|
|
88
|
+
var init_agent_payload = __esm({
|
|
89
|
+
"src/operate/agent-payload.ts"() {
|
|
90
|
+
"use strict";
|
|
91
|
+
init_fenced_code();
|
|
92
|
+
escapeXml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
93
|
+
xmlName = (name) => {
|
|
94
|
+
if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name)) throw new Error(`Invalid AI envelope name: ${name}`);
|
|
95
|
+
return name;
|
|
96
|
+
};
|
|
97
|
+
presentEntries = (values) => Object.entries(values ?? {}).filter(([, value]) => value !== null && value !== void 0 && value !== "");
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// src/operate/core.ts
|
|
102
|
+
function clone(v, path = "", seen = /* @__PURE__ */ new WeakSet(), policy = {}) {
|
|
103
|
+
if (v === null || typeof v === "string" || typeof v === "boolean") return v;
|
|
104
|
+
if (typeof v === "number") {
|
|
105
|
+
if (!Number.isFinite(v))
|
|
106
|
+
throw new ContentTransferError(
|
|
107
|
+
"unsupported-value",
|
|
108
|
+
"Only finite numbers are transferable",
|
|
109
|
+
path
|
|
110
|
+
);
|
|
111
|
+
return v;
|
|
112
|
+
}
|
|
113
|
+
if (typeof v !== "object")
|
|
114
|
+
throw new ContentTransferError(
|
|
115
|
+
"unsupported-value",
|
|
116
|
+
"Unsupported value",
|
|
117
|
+
path
|
|
118
|
+
);
|
|
119
|
+
if (seen.has(v))
|
|
120
|
+
throw new ContentTransferError(
|
|
121
|
+
"circular-value",
|
|
122
|
+
"Circular values cannot be transferred",
|
|
123
|
+
path
|
|
124
|
+
);
|
|
125
|
+
if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null)
|
|
126
|
+
throw new ContentTransferError(
|
|
127
|
+
"unsupported-value",
|
|
128
|
+
"Only plain JSON objects are transferable",
|
|
129
|
+
path
|
|
130
|
+
);
|
|
131
|
+
seen.add(v);
|
|
132
|
+
if (Array.isArray(v)) {
|
|
133
|
+
for (let index = 0; index < v.length; index += 1)
|
|
134
|
+
if (!Object.hasOwn(v, index))
|
|
135
|
+
throw new ContentTransferError(
|
|
136
|
+
"unsupported-value",
|
|
137
|
+
"Sparse arrays cannot be transferred",
|
|
138
|
+
`${path}/${index}`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
const out = Array.isArray(v) ? v.map((x, i) => clone(x, `${path}/${i}`, seen, policy)) : Object.fromEntries(
|
|
142
|
+
Object.entries(v).filter(([, x]) => !policy.omitUndefinedObjectProperties || x !== void 0).map(([k, x]) => [
|
|
143
|
+
k,
|
|
144
|
+
clone(x, `${path}/${enc(k)}`, seen, policy)
|
|
145
|
+
])
|
|
146
|
+
);
|
|
147
|
+
seen.delete(v);
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
function displaySurfacePointer(path) {
|
|
151
|
+
if (!path) return "/";
|
|
152
|
+
const safe = path.split("/").slice(1).map((segment) => {
|
|
153
|
+
const controlSafe = segment.replace(
|
|
154
|
+
/[\u0000-\u001F\u007F-\u009F]/g,
|
|
155
|
+
(character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
|
|
156
|
+
);
|
|
157
|
+
return truncateSurfacePointer(controlSafe, maxSurfacePointerSegmentLength);
|
|
158
|
+
}).join("/");
|
|
159
|
+
const pointer = `/${safe}`;
|
|
160
|
+
return truncateSurfacePointer(pointer, maxSurfacePointerLength);
|
|
161
|
+
}
|
|
162
|
+
function cloneSurfaceValue(value, path) {
|
|
163
|
+
try {
|
|
164
|
+
return normalizeTransferJsonAtPath(value, path, {
|
|
165
|
+
omitUndefinedObjectProperties: true
|
|
166
|
+
});
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (error instanceof ContentTransferError)
|
|
169
|
+
throw new ContentTransferError(
|
|
170
|
+
error.code,
|
|
171
|
+
`Surface capture rejected value at ${displaySurfacePointer(error.path)}: ${error.message}`,
|
|
172
|
+
error.path
|
|
173
|
+
);
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function normalizeTransferJsonAtPath(value, path, options = {}) {
|
|
178
|
+
return clone(value, path, /* @__PURE__ */ new WeakSet(), options);
|
|
179
|
+
}
|
|
180
|
+
function normalizeTransferJson(value, options = {}) {
|
|
181
|
+
return normalizeTransferJsonAtPath(value, "", options);
|
|
182
|
+
}
|
|
183
|
+
function deepFreeze(v) {
|
|
184
|
+
if (ArrayBuffer.isView(v)) return v;
|
|
185
|
+
if (v && typeof v === "object" && !Object.isFrozen(v)) {
|
|
186
|
+
Object.freeze(v);
|
|
187
|
+
for (const x of Object.values(v)) deepFreeze(x);
|
|
188
|
+
}
|
|
189
|
+
return v;
|
|
190
|
+
}
|
|
191
|
+
function at(v, path) {
|
|
192
|
+
validatePointer(path);
|
|
193
|
+
if (path === "") return v;
|
|
194
|
+
if (!path.startsWith("/"))
|
|
195
|
+
throw new ContentTransferError(
|
|
196
|
+
"invalid-path",
|
|
197
|
+
"Expected RFC 6901 pointer",
|
|
198
|
+
path
|
|
199
|
+
);
|
|
200
|
+
let cur = v;
|
|
201
|
+
for (const part of path.slice(1).split("/").map(dec)) {
|
|
202
|
+
if (Array.isArray(cur)) cur = cur[Number(part)];
|
|
203
|
+
else if (cur && typeof cur === "object")
|
|
204
|
+
cur = Object.hasOwn(cur, part) ? cur[part] : void 0;
|
|
205
|
+
else return void 0;
|
|
206
|
+
}
|
|
207
|
+
return cur;
|
|
208
|
+
}
|
|
209
|
+
function validatePointer(path) {
|
|
210
|
+
if (path !== "" && !path.startsWith("/") || /~(?![01])/u.test(path))
|
|
211
|
+
throw new ContentTransferError(
|
|
212
|
+
"invalid-path",
|
|
213
|
+
"Expected an RFC 6901 JSON pointer",
|
|
214
|
+
path
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
function readTransferCell(row, column) {
|
|
218
|
+
return at(row, column.path);
|
|
219
|
+
}
|
|
220
|
+
function without(v, paths, omit, path = "") {
|
|
221
|
+
if (paths.includes(path)) {
|
|
222
|
+
omit.push({ path, reason: "excluded" });
|
|
223
|
+
return void 0;
|
|
224
|
+
}
|
|
225
|
+
if (Array.isArray(v))
|
|
226
|
+
return v.map((x, i) => without(x, paths, omit, `${path}/${i}`)).filter((x) => x !== void 0);
|
|
227
|
+
if (v && typeof v === "object") {
|
|
228
|
+
const out = /* @__PURE__ */ Object.create(null);
|
|
229
|
+
for (const [k, x] of Object.entries(v)) {
|
|
230
|
+
const y = without(x, paths, omit, `${path}/${enc(k)}`);
|
|
231
|
+
if (y !== void 0) out[k] = y;
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
return v;
|
|
236
|
+
}
|
|
237
|
+
function projectValue(v, rules, target, omit) {
|
|
238
|
+
rules.forEach((rule) => validatePointer(rule.path));
|
|
239
|
+
return without(
|
|
240
|
+
clone(v),
|
|
241
|
+
rules.filter(
|
|
242
|
+
(r) => r.target === target && (!r.exportable || r.classification !== "ordinary")
|
|
243
|
+
).map((r) => r.path),
|
|
244
|
+
omit
|
|
245
|
+
) ?? null;
|
|
246
|
+
}
|
|
247
|
+
function excludedColumn(column) {
|
|
248
|
+
return column.exportable === false || column.classification === "secret" || column.classification === "credential";
|
|
249
|
+
}
|
|
250
|
+
function rowProjectionExcludesColumnSchema(column, rules) {
|
|
251
|
+
return rules.some(
|
|
252
|
+
(rule) => rule.target === "row" && (!rule.exportable || rule.classification !== "ordinary") && (rule.path === column.path || column.path.startsWith(`${rule.path}/`))
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
function projectColumnSchema(column, rules, omit) {
|
|
256
|
+
if (column.schema === void 0) return void 0;
|
|
257
|
+
const root = `/columns/${enc(column.id)}/schema`;
|
|
258
|
+
const schemaRules = rules.filter((rule) => rule.target === "payload" && (rule.path === root || rule.path.startsWith(`${root}/`))).map((rule) => ({ ...rule, path: rule.path.slice(root.length) }));
|
|
259
|
+
const projected = projectValue(column.schema, schemaRules, "payload", omit);
|
|
260
|
+
if (schemaRules.some((rule) => rule.path === "" && (!rule.exportable || rule.classification !== "ordinary")))
|
|
261
|
+
return void 0;
|
|
262
|
+
return projected;
|
|
263
|
+
}
|
|
264
|
+
function normalize(p, projection, omit) {
|
|
265
|
+
if (p.kind === "text" || p.kind === "markdown") {
|
|
266
|
+
if (typeof p.text !== "string")
|
|
267
|
+
throw new ContentTransferError(
|
|
268
|
+
"unsupported-value",
|
|
269
|
+
"Text payload must contain a string",
|
|
270
|
+
"/text"
|
|
271
|
+
);
|
|
272
|
+
const value = projectValue(p.text, projection.rules, "payload", omit);
|
|
273
|
+
const text = typeof value === "string" ? value : "";
|
|
274
|
+
return p.kind === "text" && typeof p.language === "string" && p.language.trim() ? { kind: "text", text, language: p.language.trim() } : { kind: p.kind, text };
|
|
275
|
+
}
|
|
276
|
+
if (p.kind === "json")
|
|
277
|
+
return {
|
|
278
|
+
kind: "json",
|
|
279
|
+
value: projectValue(p.value, projection.rules, "payload", omit)
|
|
280
|
+
};
|
|
281
|
+
if (p.kind === "registered")
|
|
282
|
+
return {
|
|
283
|
+
kind: "registered",
|
|
284
|
+
format: p.format,
|
|
285
|
+
value: projectValue(p.value, projection.rules, "payload", omit)
|
|
286
|
+
};
|
|
287
|
+
const rowsPayload = p;
|
|
288
|
+
if (p.kind !== "rows")
|
|
289
|
+
throw new ContentTransferError(
|
|
290
|
+
"invalid-payload",
|
|
291
|
+
"Unsupported payload kind"
|
|
292
|
+
);
|
|
293
|
+
const sourceColumns = rowsPayload.columns.map((column) => ({ ...column }));
|
|
294
|
+
const columns = sourceColumns.filter((column) => !excludedColumn(column)).map((column) => {
|
|
295
|
+
const { schema: _sourceSchema, ...withoutSchema } = column;
|
|
296
|
+
const schema = rowProjectionExcludesColumnSchema(column, projection.rules) ? void 0 : projectColumnSchema(column, projection.rules, omit);
|
|
297
|
+
return {
|
|
298
|
+
...withoutSchema,
|
|
299
|
+
...schema === void 0 ? {} : { schema }
|
|
300
|
+
};
|
|
301
|
+
});
|
|
302
|
+
resolveTransferRegistry(columns);
|
|
303
|
+
columns.forEach((column) => validatePointer(column.path));
|
|
304
|
+
const rules = [
|
|
305
|
+
...projection.rules,
|
|
306
|
+
...sourceColumns.filter(excludedColumn).map((c) => ({
|
|
307
|
+
target: "row",
|
|
308
|
+
path: c.path,
|
|
309
|
+
exportable: c.exportable ?? true,
|
|
310
|
+
classification: c.classification ?? "ordinary"
|
|
311
|
+
}))
|
|
312
|
+
];
|
|
313
|
+
return {
|
|
314
|
+
kind: "rows",
|
|
315
|
+
columns,
|
|
316
|
+
rows: rowsPayload.rows.map((row, index) => {
|
|
317
|
+
if (!row || typeof row !== "object" || Array.isArray(row))
|
|
318
|
+
throw new ContentTransferError(
|
|
319
|
+
"invalid-row",
|
|
320
|
+
"A table row must be a JSON object",
|
|
321
|
+
`/rows/${index}`
|
|
322
|
+
);
|
|
323
|
+
const projected = projectValue(row, rules, "row", omit);
|
|
324
|
+
return projected === null ? {} : projected;
|
|
325
|
+
})
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function projectSnapshot(raw, projection) {
|
|
329
|
+
const omissions = raw.omissions.map((o) => ({ ...o }));
|
|
330
|
+
const normalized = normalize(raw.payload, projection, omissions);
|
|
331
|
+
const payload = raw.limits ? limitPayload(normalized, raw.limits, omissions) : normalized;
|
|
332
|
+
const included = payload.kind === "rows" ? payload.rows.length : raw.coverage.included;
|
|
333
|
+
return deepFreeze({
|
|
334
|
+
...raw,
|
|
335
|
+
payload,
|
|
336
|
+
coverage: {
|
|
337
|
+
...raw.coverage,
|
|
338
|
+
included,
|
|
339
|
+
...included < raw.coverage.included ? { status: "partial", reason: "Source export limit applied" } : {}
|
|
340
|
+
},
|
|
341
|
+
omissions,
|
|
342
|
+
sections: raw.sections.filter(
|
|
343
|
+
(section) => !projection.rules.some(
|
|
344
|
+
(rule) => rule.target === "payload" && (!rule.exportable || rule.classification !== "ordinary") && (section.path === rule.path || section.path.startsWith(`${rule.path}/`))
|
|
345
|
+
)
|
|
346
|
+
).map((x) => ({ ...x })),
|
|
347
|
+
...raw.limits ? { limits: { ...raw.limits } } : {}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function directSource(payload, options = {}) {
|
|
351
|
+
const id = options.id ?? uid();
|
|
352
|
+
return {
|
|
353
|
+
projection: options.projection ?? { rules: [] },
|
|
354
|
+
snapshot: {
|
|
355
|
+
id,
|
|
356
|
+
sourceId: options.sourceId ?? id,
|
|
357
|
+
revision: options.revision ?? uid(),
|
|
358
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
359
|
+
label: options.label ?? "Content",
|
|
360
|
+
payload,
|
|
361
|
+
coverage: options.coverage ?? {
|
|
362
|
+
status: "complete",
|
|
363
|
+
included: payload.kind === "rows" ? payload.rows.length : 1,
|
|
364
|
+
total: payload.kind === "rows" ? payload.rows.length : 1
|
|
365
|
+
},
|
|
366
|
+
unsavedChanges: options.unsavedChanges ?? false,
|
|
367
|
+
omissions: [],
|
|
368
|
+
sections: options.sections ?? [],
|
|
369
|
+
...options.limits ? { limits: { ...options.limits } } : {}
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
async function capture(source, signal, scope = "target") {
|
|
374
|
+
stop(signal);
|
|
375
|
+
const captured = "kind" in source ? directSource(source) : await source.capture({ scope, signal });
|
|
376
|
+
stop(signal);
|
|
377
|
+
const all = captured.allMatching;
|
|
378
|
+
if (all && (all.query.sourceId !== captured.snapshot.sourceId || all.query.revision !== captured.snapshot.revision || all.query.order.length === 0))
|
|
379
|
+
throw new ContentTransferError(
|
|
380
|
+
"query-mismatch",
|
|
381
|
+
"All-matching query must be captured with stable ordering"
|
|
382
|
+
);
|
|
383
|
+
const snapshot = projectSnapshot(captured.snapshot, captured.projection);
|
|
384
|
+
if (!all) return { snapshot };
|
|
385
|
+
return {
|
|
386
|
+
snapshot,
|
|
387
|
+
allMatching: deepFreeze({
|
|
388
|
+
[bound]: true,
|
|
389
|
+
source: {
|
|
390
|
+
...all,
|
|
391
|
+
query: {
|
|
392
|
+
...all.query,
|
|
393
|
+
query: clone(all.query.query),
|
|
394
|
+
order: all.query.order.map((x) => ({ ...x }))
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
projection: { rules: captured.projection.rules.map((x) => ({ ...x })) },
|
|
398
|
+
// Page rows must be normalized against the original declaration so excluded
|
|
399
|
+
// column values are removed before stable IDs or any caller can observe them.
|
|
400
|
+
columns: captured.snapshot.payload.kind === "rows" ? captured.snapshot.payload.columns.map((column) => ({ ...column })) : [],
|
|
401
|
+
...snapshot.limits ? { limits: { ...snapshot.limits } } : {}
|
|
402
|
+
})
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
function createDraft(s) {
|
|
406
|
+
return deepFreeze({
|
|
407
|
+
snapshotId: s.id,
|
|
408
|
+
sourceId: s.sourceId,
|
|
409
|
+
sourceRevision: s.revision,
|
|
410
|
+
revision: 0,
|
|
411
|
+
payload: normalize(s.payload, { rules: [] }, []),
|
|
412
|
+
omissions: [...s.omissions],
|
|
413
|
+
manuallyEdited: false,
|
|
414
|
+
provenance: [{ kind: "original", description: "Captured source snapshot" }]
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
function revise(d, p, o, description, manual = d.manuallyEdited, kind = "deterministic", baseOmissions = d.omissions) {
|
|
418
|
+
const { history: _history, ...previous } = d;
|
|
419
|
+
return deepFreeze({
|
|
420
|
+
...d,
|
|
421
|
+
revision: d.revision + 1,
|
|
422
|
+
payload: normalize(p, { rules: [] }, []),
|
|
423
|
+
omissions: [...baseOmissions, ...o],
|
|
424
|
+
manuallyEdited: manual,
|
|
425
|
+
provenance: [...d.provenance, { kind, description }],
|
|
426
|
+
history: [...d.history ?? [], previous]
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
function undoDraft(d) {
|
|
430
|
+
const previous = d.history?.at(-1);
|
|
431
|
+
if (!previous) return d;
|
|
432
|
+
return deepFreeze({
|
|
433
|
+
...previous,
|
|
434
|
+
revision: d.revision + 1,
|
|
435
|
+
history: d.history.slice(0, -1)
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
function refreshDraft(draft, snapshot, choice) {
|
|
439
|
+
return choice === "keep" ? draft : createDraft(snapshot);
|
|
440
|
+
}
|
|
441
|
+
function applySectionSelection(d, s, ids) {
|
|
442
|
+
if (d.snapshotId !== s.id || d.sourceId !== s.sourceId || d.sourceRevision !== s.revision)
|
|
443
|
+
throw new ContentTransferError(
|
|
444
|
+
"snapshot-mismatch",
|
|
445
|
+
"Section selection requires the draft's captured source snapshot"
|
|
446
|
+
);
|
|
447
|
+
const selected = new Set(ids), omit = [], paths = s.sections.filter((x) => !selected.has(x.id)).map((x) => {
|
|
448
|
+
omit.push({ path: x.path, reason: "excluded" });
|
|
449
|
+
return x.path;
|
|
450
|
+
}), baseOmissions = s.omissions;
|
|
451
|
+
if (s.payload.kind === "json")
|
|
452
|
+
return revise(
|
|
453
|
+
d,
|
|
454
|
+
{ kind: "json", value: without(s.payload.value, paths, []) ?? null },
|
|
455
|
+
omit,
|
|
456
|
+
"Selected sections",
|
|
457
|
+
d.manuallyEdited,
|
|
458
|
+
"deterministic",
|
|
459
|
+
baseOmissions
|
|
460
|
+
);
|
|
461
|
+
if (s.payload.kind === "registered")
|
|
462
|
+
return revise(
|
|
463
|
+
d,
|
|
464
|
+
{
|
|
465
|
+
kind: "registered",
|
|
466
|
+
format: s.payload.format,
|
|
467
|
+
value: without(s.payload.value, paths, []) ?? null
|
|
468
|
+
},
|
|
469
|
+
omit,
|
|
470
|
+
"Selected sections",
|
|
471
|
+
d.manuallyEdited,
|
|
472
|
+
"deterministic",
|
|
473
|
+
baseOmissions
|
|
474
|
+
);
|
|
475
|
+
return revise(
|
|
476
|
+
d,
|
|
477
|
+
s.payload,
|
|
478
|
+
omit,
|
|
479
|
+
"Selected sections",
|
|
480
|
+
d.manuallyEdited,
|
|
481
|
+
"deterministic",
|
|
482
|
+
baseOmissions
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
function transformRows(d, o) {
|
|
486
|
+
if (d.payload.kind !== "rows") return d;
|
|
487
|
+
if (o.top != null) assertLimit(o.top, "maxRows");
|
|
488
|
+
const cols = o.visibleColumns ? o.visibleColumns.map(
|
|
489
|
+
(id) => d.payload.kind === "rows" ? d.payload.columns.find((c) => c.id === id) : void 0
|
|
490
|
+
).filter((c) => Boolean(c)) : d.payload.columns.filter((c) => c.visible);
|
|
491
|
+
const get = readTransferCell;
|
|
492
|
+
let rows = [...d.payload.rows], omit = [];
|
|
493
|
+
const before = rows.length;
|
|
494
|
+
if (o.selectedIndices !== void 0) {
|
|
495
|
+
const selected = /* @__PURE__ */ new Set();
|
|
496
|
+
for (const index of o.selectedIndices) {
|
|
497
|
+
if (!Number.isSafeInteger(index) || index < 0 || index >= d.payload.rows.length)
|
|
498
|
+
throw new ContentTransferError(
|
|
499
|
+
"invalid-selection-index",
|
|
500
|
+
"Selected row indexes must be non-negative positions in the input draft rows"
|
|
501
|
+
);
|
|
502
|
+
selected.add(index);
|
|
503
|
+
}
|
|
504
|
+
rows = d.payload.rows.filter((_, index) => selected.has(index));
|
|
505
|
+
}
|
|
506
|
+
if (o.selectedIds && o.idColumn) {
|
|
507
|
+
const set = new Set(o.selectedIds);
|
|
508
|
+
const idColumn = d.payload.columns.find((c) => c.id === o.idColumn);
|
|
509
|
+
rows = rows.filter(
|
|
510
|
+
(r) => set.has(String(idColumn ? get(r, idColumn) : r[o.idColumn]))
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
if (o.search) {
|
|
514
|
+
const q = o.search.toLowerCase();
|
|
515
|
+
rows = rows.filter(
|
|
516
|
+
(r) => cols.some(
|
|
517
|
+
(c) => String(get(r, c) ?? "").toLowerCase().includes(q)
|
|
518
|
+
)
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
for (const [id, q] of Object.entries(o.filters ?? {})) {
|
|
522
|
+
const c = cols.find((x) => x.id === id);
|
|
523
|
+
if (c)
|
|
524
|
+
rows = rows.filter(
|
|
525
|
+
(r) => String(get(r, c) ?? "").toLowerCase().includes(q.toLowerCase())
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
if (rows.length !== before)
|
|
529
|
+
omit.push({
|
|
530
|
+
path: "/rows",
|
|
531
|
+
reason: "filtered",
|
|
532
|
+
count: before - rows.length
|
|
533
|
+
});
|
|
534
|
+
if (o.sort) {
|
|
535
|
+
const c = cols.find((x) => x.id === o.sort.column);
|
|
536
|
+
if (c)
|
|
537
|
+
rows.sort((a, b) => {
|
|
538
|
+
const left = get(a, c);
|
|
539
|
+
const right = get(b, c);
|
|
540
|
+
const compare = typeof left === "number" && typeof right === "number" ? left - right : String(left ?? "").localeCompare(String(right ?? ""));
|
|
541
|
+
return compare * (o.sort.direction === "asc" ? 1 : -1);
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
if (o.top != null && rows.length > o.top) {
|
|
545
|
+
omit.push({
|
|
546
|
+
path: "/rows",
|
|
547
|
+
reason: "truncated",
|
|
548
|
+
count: rows.length - o.top
|
|
549
|
+
});
|
|
550
|
+
rows = rows.slice(0, o.top);
|
|
551
|
+
}
|
|
552
|
+
if (o.structuredProjection === "visible") {
|
|
553
|
+
rows = rows.map(
|
|
554
|
+
(r) => Object.fromEntries(cols.map((c) => [c.id, get(r, c) ?? null]))
|
|
555
|
+
);
|
|
556
|
+
const excludedColumns = d.payload.columns.length - cols.length;
|
|
557
|
+
if (excludedColumns > 0)
|
|
558
|
+
omit.push({
|
|
559
|
+
path: "/columns",
|
|
560
|
+
reason: "excluded",
|
|
561
|
+
count: excludedColumns
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
return revise(
|
|
565
|
+
d,
|
|
566
|
+
{
|
|
567
|
+
kind: "rows",
|
|
568
|
+
rows,
|
|
569
|
+
columns: cols.map((c) => ({
|
|
570
|
+
...c,
|
|
571
|
+
visible: true,
|
|
572
|
+
...o.structuredProjection === "visible" ? { path: `/${enc(c.id)}` } : {}
|
|
573
|
+
}))
|
|
574
|
+
},
|
|
575
|
+
omit,
|
|
576
|
+
"Prepared row subset"
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
function reduceJson(draft, options) {
|
|
580
|
+
if (draft.payload.kind !== "json" && draft.payload.kind !== "registered")
|
|
581
|
+
return draft;
|
|
582
|
+
const omissions = [];
|
|
583
|
+
options.exclude?.forEach(validatePointer);
|
|
584
|
+
const filtered = without(clone(draft.payload.value), options.exclude ?? [], omissions) ?? null;
|
|
585
|
+
const payload = limitPayload(
|
|
586
|
+
{ ...draft.payload, value: filtered },
|
|
587
|
+
options,
|
|
588
|
+
omissions
|
|
589
|
+
);
|
|
590
|
+
return revise(draft, payload, omissions, "Reduced JSON");
|
|
591
|
+
}
|
|
592
|
+
async function collectAllMatching(c, signal) {
|
|
593
|
+
const rows = [], omissions = [], ids = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
|
|
594
|
+
let cursor = null, token, last = {
|
|
595
|
+
status: "unknown",
|
|
596
|
+
included: 0,
|
|
597
|
+
total: null
|
|
598
|
+
};
|
|
599
|
+
let certifiedTotal;
|
|
600
|
+
const maxRows = c.limits?.maxRows;
|
|
601
|
+
if (maxRows != null) assertLimit(maxRows, "maxRows");
|
|
602
|
+
const finishAtLimit = (total, knownOmitted) => ({
|
|
603
|
+
rows: deepFreeze(rows),
|
|
604
|
+
omissions: deepFreeze([
|
|
605
|
+
...omissions,
|
|
606
|
+
{
|
|
607
|
+
path: "/rows",
|
|
608
|
+
reason: "truncated",
|
|
609
|
+
...knownOmitted === void 0 || knownOmitted <= 0 ? {} : { count: knownOmitted }
|
|
610
|
+
}
|
|
611
|
+
]),
|
|
612
|
+
coverage: deepFreeze({
|
|
613
|
+
status: "partial",
|
|
614
|
+
included: rows.length,
|
|
615
|
+
total,
|
|
616
|
+
reason: "Source export limit applied"
|
|
617
|
+
})
|
|
618
|
+
});
|
|
619
|
+
try {
|
|
620
|
+
if (maxRows === 0) return finishAtLimit(null);
|
|
621
|
+
do {
|
|
622
|
+
stop(signal);
|
|
623
|
+
const page = await c.source.page({
|
|
624
|
+
query: c.source.query,
|
|
625
|
+
cursor,
|
|
626
|
+
consistencyToken: token ?? null,
|
|
627
|
+
signal
|
|
628
|
+
});
|
|
629
|
+
stop(signal);
|
|
630
|
+
if (token === void 0) token = page.consistencyToken;
|
|
631
|
+
else if (page.consistencyToken !== token)
|
|
632
|
+
throw new ContentTransferError(
|
|
633
|
+
"consistency-token-changed",
|
|
634
|
+
"All-matching export changed during collection"
|
|
635
|
+
);
|
|
636
|
+
if (page.coverage.included !== page.rows.length)
|
|
637
|
+
throw new ContentTransferError(
|
|
638
|
+
"invalid-page-coverage",
|
|
639
|
+
"Page count does not match returned rows"
|
|
640
|
+
);
|
|
641
|
+
if (page.coverage.total !== null && (!Number.isSafeInteger(page.coverage.total) || page.coverage.total < 0))
|
|
642
|
+
throw new ContentTransferError(
|
|
643
|
+
"invalid-page-coverage",
|
|
644
|
+
"Page total must be a non-negative integer or null"
|
|
645
|
+
);
|
|
646
|
+
if (certifiedTotal === void 0) certifiedTotal = page.coverage.total;
|
|
647
|
+
else if (page.coverage.total !== certifiedTotal)
|
|
648
|
+
throw new ContentTransferError(
|
|
649
|
+
"inconsistent-total",
|
|
650
|
+
"All-matching source changed its reported total during collection"
|
|
651
|
+
);
|
|
652
|
+
const projected = normalize(
|
|
653
|
+
{ kind: "rows", rows: page.rows, columns: [...c.columns] },
|
|
654
|
+
c.projection,
|
|
655
|
+
omissions
|
|
656
|
+
).rows;
|
|
657
|
+
let uniqueBeyondLimit = 0;
|
|
658
|
+
for (const row of projected) {
|
|
659
|
+
const id = c.source.getRowId(row);
|
|
660
|
+
if (!id)
|
|
661
|
+
throw new ContentTransferError(
|
|
662
|
+
"invalid-row-id",
|
|
663
|
+
"All-matching source returned empty projected ID"
|
|
664
|
+
);
|
|
665
|
+
if (!ids.has(id)) {
|
|
666
|
+
ids.add(id);
|
|
667
|
+
if (maxRows == null || rows.length < maxRows)
|
|
668
|
+
rows.push(
|
|
669
|
+
limitPayload(
|
|
670
|
+
{ kind: "rows", rows: [row], columns: [...c.columns] },
|
|
671
|
+
{ ...c.limits, maxRows: null },
|
|
672
|
+
omissions
|
|
673
|
+
).rows[0]
|
|
674
|
+
);
|
|
675
|
+
else uniqueBeyondLimit += 1;
|
|
676
|
+
} else omissions.push({ path: `/rows/${enc(id)}`, reason: "duplicate" });
|
|
677
|
+
}
|
|
678
|
+
if (page.coverage.total !== null && page.coverage.total < ids.size)
|
|
679
|
+
throw new ContentTransferError(
|
|
680
|
+
"invalid-page-coverage",
|
|
681
|
+
"Page total is smaller than the accumulated unique row count"
|
|
682
|
+
);
|
|
683
|
+
last = page.coverage;
|
|
684
|
+
if (maxRows != null && rows.length >= maxRows && (uniqueBeyondLimit > 0 || page.nextCursor !== null))
|
|
685
|
+
return finishAtLimit(
|
|
686
|
+
page.coverage.total,
|
|
687
|
+
page.nextCursor === null ? uniqueBeyondLimit : page.coverage.total != null && page.coverage.total > rows.length ? page.coverage.total - rows.length : void 0
|
|
688
|
+
);
|
|
689
|
+
cursor = page.nextCursor;
|
|
690
|
+
if (cursor !== null && (!cursor || cursors.has(cursor)))
|
|
691
|
+
throw new ContentTransferError(
|
|
692
|
+
"non-advancing-cursor",
|
|
693
|
+
"All-matching source repeated a cursor"
|
|
694
|
+
);
|
|
695
|
+
if (cursor) cursors.add(cursor);
|
|
696
|
+
} while (cursor !== null);
|
|
697
|
+
const complete = c.source.stableSnapshot === true && last.status === "complete" && last.total === rows.length && token !== void 0;
|
|
698
|
+
return {
|
|
699
|
+
rows: deepFreeze(rows),
|
|
700
|
+
omissions: deepFreeze(omissions),
|
|
701
|
+
coverage: deepFreeze(
|
|
702
|
+
complete ? { ...last, included: rows.length } : {
|
|
703
|
+
...last,
|
|
704
|
+
status: "partial",
|
|
705
|
+
included: rows.length,
|
|
706
|
+
reason: last.reason ?? "Source did not certify a stable complete snapshot"
|
|
707
|
+
}
|
|
708
|
+
)
|
|
709
|
+
};
|
|
710
|
+
} catch (e) {
|
|
711
|
+
const error = e instanceof ContentTransferError ? e : new ContentTransferError(
|
|
712
|
+
signal.aborted ? "cancelled" : "page-failed",
|
|
713
|
+
e instanceof Error ? e.message : "Page collection failed"
|
|
714
|
+
);
|
|
715
|
+
return {
|
|
716
|
+
rows: deepFreeze(rows),
|
|
717
|
+
omissions: deepFreeze(omissions),
|
|
718
|
+
coverage: deepFreeze({
|
|
719
|
+
status: "partial",
|
|
720
|
+
included: rows.length,
|
|
721
|
+
total: last.total,
|
|
722
|
+
reason: error.message
|
|
723
|
+
}),
|
|
724
|
+
error
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
function sealTransferArtifact(artifact) {
|
|
729
|
+
if (!artifact.file)
|
|
730
|
+
return deepFreeze({
|
|
731
|
+
...artifact,
|
|
732
|
+
omissions: artifact.omissions.map((o) => ({ ...o }))
|
|
733
|
+
});
|
|
734
|
+
const bytes = artifact.file.bytes.slice();
|
|
735
|
+
const file = {
|
|
736
|
+
filename: artifact.file.filename,
|
|
737
|
+
mime: artifact.file.mime,
|
|
738
|
+
get bytes() {
|
|
739
|
+
return bytes.slice();
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
return deepFreeze({
|
|
743
|
+
...artifact,
|
|
744
|
+
file,
|
|
745
|
+
omissions: artifact.omissions.map((o) => ({ ...o }))
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
function serialize(draft, format, options = {}) {
|
|
749
|
+
const payload = draft.payload;
|
|
750
|
+
const omissions = draft.omissions.map((o) => ({ ...o }));
|
|
751
|
+
let plainText = "", html;
|
|
752
|
+
let mime = "text/plain;charset=utf-8", extension = "txt";
|
|
753
|
+
const columnCell = (row, column) => textValue(readTransferCell(row, column));
|
|
754
|
+
if ((format === "csv" || format === "tsv") && payload.kind !== "rows") {
|
|
755
|
+
throw new ContentTransferError(
|
|
756
|
+
"unsupported-format",
|
|
757
|
+
`${format.toUpperCase()} requires tabular data`
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
if (format === "json" || format === "compact-json") {
|
|
761
|
+
const value = payload.kind === "rows" ? payload.rows : payload.kind === "text" || payload.kind === "markdown" ? payload.text : payload.value;
|
|
762
|
+
plainText = (0, import_json_format.stringifyJson)(value, {
|
|
763
|
+
style: format === "json" ? "pretty" : "compact"
|
|
764
|
+
});
|
|
765
|
+
mime = "application/json;charset=utf-8";
|
|
766
|
+
extension = "json";
|
|
767
|
+
} else if (payload.kind === "rows") {
|
|
768
|
+
const columns = payload.columns.filter(
|
|
769
|
+
(c) => c.visible && c.exportable !== false && c.classification !== "secret" && c.classification !== "credential"
|
|
770
|
+
);
|
|
771
|
+
if (format === "markdown") {
|
|
772
|
+
const escapeCell = (value) => (0, import_html_escape.escapeHtml)(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
|
|
773
|
+
plainText = [
|
|
774
|
+
`| ${columns.map((c) => escapeCell(c.label)).join(" | ")} |`,
|
|
775
|
+
`| ${columns.map(() => "---").join(" | ")} |`,
|
|
776
|
+
...payload.rows.map(
|
|
777
|
+
(row) => `| ${columns.map((c) => escapeCell(columnCell(row, c))).join(" | ")} |`
|
|
778
|
+
)
|
|
779
|
+
].join("\n");
|
|
780
|
+
mime = "text/markdown;charset=utf-8";
|
|
781
|
+
extension = "md";
|
|
782
|
+
} else {
|
|
783
|
+
const delimiter = format === "csv" ? "," : " ";
|
|
784
|
+
const safe = options.spreadsheetSafe ?? format === "tsv";
|
|
785
|
+
const encode = (value, path, isString = true) => {
|
|
786
|
+
let text = value;
|
|
787
|
+
if (safe && isString && /^[\t\r\n ]*[=+\-@]/.test(text)) {
|
|
788
|
+
text = `'${text}`;
|
|
789
|
+
omissions.push({ path, reason: "escaped", count: 1 });
|
|
790
|
+
}
|
|
791
|
+
return text.includes(delimiter) || /["\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
|
792
|
+
};
|
|
793
|
+
plainText = [
|
|
794
|
+
columns.map((c) => encode(c.label, `/columns/${enc(c.id)}`)).join(delimiter),
|
|
795
|
+
...payload.rows.map(
|
|
796
|
+
(row, index) => columns.map(
|
|
797
|
+
(c) => encode(
|
|
798
|
+
columnCell(row, c),
|
|
799
|
+
`/rows/${index}${c.path}`,
|
|
800
|
+
typeof readTransferCell(row, c) === "string"
|
|
801
|
+
)
|
|
802
|
+
).join(delimiter)
|
|
803
|
+
)
|
|
804
|
+
].join("\n");
|
|
805
|
+
if (format === "csv") {
|
|
806
|
+
mime = "text/csv;charset=utf-8";
|
|
807
|
+
extension = "csv";
|
|
808
|
+
}
|
|
809
|
+
if (format === "tsv") {
|
|
810
|
+
mime = "text/tab-separated-values;charset=utf-8";
|
|
811
|
+
extension = "tsv";
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
if (format === "html")
|
|
815
|
+
html = `<table><thead><tr>${columns.map((c) => `<th>${(0, import_html_escape.escapeHtml)(c.label)}</th>`).join("")}</tr></thead><tbody>${payload.rows.map((row) => `<tr>${columns.map((c) => `<td>${(0, import_html_escape.escapeHtml)(columnCell(row, c)).replace(/\r\n|\r|\n/g, "<br>")}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
816
|
+
} else {
|
|
817
|
+
plainText = payload.kind === "text" || payload.kind === "markdown" ? payload.text : (0, import_json_format.stringifyJson)(payload.value, { style: "pretty" });
|
|
818
|
+
if (format === "markdown") {
|
|
819
|
+
mime = "text/markdown;charset=utf-8";
|
|
820
|
+
extension = "md";
|
|
821
|
+
}
|
|
822
|
+
if (format === "html") html = `<pre>${(0, import_html_escape.escapeHtml)(plainText)}</pre>`;
|
|
823
|
+
}
|
|
824
|
+
if (format === "html") {
|
|
825
|
+
mime = "text/html;charset=utf-8";
|
|
826
|
+
extension = "html";
|
|
827
|
+
}
|
|
828
|
+
return sealTransferArtifact({
|
|
829
|
+
snapshotId: draft.snapshotId,
|
|
830
|
+
draftRevision: draft.revision,
|
|
831
|
+
format,
|
|
832
|
+
plainText,
|
|
833
|
+
...html === void 0 ? {} : { html },
|
|
834
|
+
file: {
|
|
835
|
+
filename: options.filename ?? `export.${extension}`,
|
|
836
|
+
mime,
|
|
837
|
+
bytes: new TextEncoder().encode(
|
|
838
|
+
format === "html" ? html ?? plainText : plainText
|
|
839
|
+
)
|
|
840
|
+
},
|
|
841
|
+
omissions
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
function createBrowserTransport() {
|
|
845
|
+
return {
|
|
846
|
+
async copy(a, signal) {
|
|
847
|
+
const cancelled = () => signal.aborted ? { status: "cancelled" } : void 0;
|
|
848
|
+
try {
|
|
849
|
+
if (cancelled()) return cancelled();
|
|
850
|
+
const c = globalThis.navigator?.clipboard;
|
|
851
|
+
if (!c?.write && !c?.writeText)
|
|
852
|
+
return {
|
|
853
|
+
status: "error",
|
|
854
|
+
code: "clipboard-unavailable",
|
|
855
|
+
message: "Clipboard writing is unavailable",
|
|
856
|
+
retryable: false
|
|
857
|
+
};
|
|
858
|
+
if (a.html && c.write && typeof globalThis.ClipboardItem === "function") {
|
|
859
|
+
try {
|
|
860
|
+
await c.write([
|
|
861
|
+
new ClipboardItem({
|
|
862
|
+
"text/plain": new Blob([a.plainText], { type: "text/plain" }),
|
|
863
|
+
"text/html": new Blob([a.html], { type: "text/html" })
|
|
864
|
+
})
|
|
865
|
+
]);
|
|
866
|
+
if (cancelled()) return cancelled();
|
|
867
|
+
return {
|
|
868
|
+
status: "success",
|
|
869
|
+
delivered: "clipboard",
|
|
870
|
+
mimeTypes: ["text/plain", "text/html"]
|
|
871
|
+
};
|
|
872
|
+
} catch {
|
|
873
|
+
if (cancelled()) return cancelled();
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
if (c.writeText) {
|
|
877
|
+
await c.writeText(a.plainText);
|
|
878
|
+
if (cancelled()) return cancelled();
|
|
879
|
+
return a.html ? {
|
|
880
|
+
status: "degraded",
|
|
881
|
+
delivered: "plain-text",
|
|
882
|
+
reason: "Rich clipboard write was unavailable or rejected"
|
|
883
|
+
} : {
|
|
884
|
+
status: "success",
|
|
885
|
+
delivered: "clipboard",
|
|
886
|
+
mimeTypes: ["text/plain"]
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
return {
|
|
890
|
+
status: "error",
|
|
891
|
+
code: "clipboard-rejected",
|
|
892
|
+
message: "Clipboard rejected the write",
|
|
893
|
+
retryable: true
|
|
894
|
+
};
|
|
895
|
+
} catch (e) {
|
|
896
|
+
return cancelled() ?? {
|
|
897
|
+
status: "error",
|
|
898
|
+
code: "clipboard-rejected",
|
|
899
|
+
message: e instanceof Error ? e.message : "Clipboard rejected the write",
|
|
900
|
+
retryable: true
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
},
|
|
904
|
+
async download(a, signal) {
|
|
905
|
+
if (signal.aborted) return { status: "cancelled" };
|
|
906
|
+
if (!a.file || typeof document === "undefined" || !URL?.createObjectURL)
|
|
907
|
+
return {
|
|
908
|
+
status: "error",
|
|
909
|
+
code: "download-unavailable",
|
|
910
|
+
message: "Download is unavailable",
|
|
911
|
+
retryable: false
|
|
912
|
+
};
|
|
913
|
+
let url;
|
|
914
|
+
try {
|
|
915
|
+
url = URL.createObjectURL(
|
|
916
|
+
new Blob([a.file.bytes.slice().buffer], {
|
|
917
|
+
type: a.file.mime
|
|
918
|
+
})
|
|
919
|
+
);
|
|
920
|
+
const link = document.createElement("a");
|
|
921
|
+
link.href = url;
|
|
922
|
+
link.download = a.file.filename;
|
|
923
|
+
link.click();
|
|
924
|
+
return signal.aborted ? { status: "cancelled" } : {
|
|
925
|
+
status: "success",
|
|
926
|
+
delivered: "download-started",
|
|
927
|
+
mimeTypes: [a.file.mime]
|
|
928
|
+
};
|
|
929
|
+
} catch (e) {
|
|
930
|
+
return signal.aborted ? { status: "cancelled" } : {
|
|
931
|
+
status: "error",
|
|
932
|
+
code: "download-failed",
|
|
933
|
+
message: e instanceof Error ? e.message : "Download failed",
|
|
934
|
+
retryable: true
|
|
935
|
+
};
|
|
936
|
+
} finally {
|
|
937
|
+
if (url) setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
function assertLimit(value, name) {
|
|
943
|
+
if (value != null && (!Number.isSafeInteger(value) || value < 0)) {
|
|
944
|
+
throw new ContentTransferError(
|
|
945
|
+
"invalid-limit",
|
|
946
|
+
`${name} must be a non-negative safe integer or null`
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
function resolveTransferPreferences(provider = {}, menu = {}, sourceLimits = {}) {
|
|
951
|
+
const limits = {
|
|
952
|
+
maxRows: null,
|
|
953
|
+
maxStringChars: null,
|
|
954
|
+
maxDepth: null,
|
|
955
|
+
maxArrayItems: null,
|
|
956
|
+
targetTokens: null
|
|
957
|
+
};
|
|
958
|
+
for (const key of limitKeys) {
|
|
959
|
+
const candidates = [
|
|
960
|
+
provider.limits?.[key],
|
|
961
|
+
menu.limits?.[key],
|
|
962
|
+
sourceLimits[key]
|
|
963
|
+
];
|
|
964
|
+
candidates.forEach((value) => assertLimit(value, key));
|
|
965
|
+
const finite = candidates.filter((value) => value != null);
|
|
966
|
+
limits[key] = finite.length ? Math.min(...finite) : null;
|
|
967
|
+
}
|
|
968
|
+
return deepFreeze({
|
|
969
|
+
initialFormat: menu.initialFormat ?? provider.initialFormat ?? "plain",
|
|
970
|
+
initialPreset: menu.initialPreset ?? provider.initialPreset ?? "full",
|
|
971
|
+
limits
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
function isReactElementType(value) {
|
|
975
|
+
const tag = value.$$typeof;
|
|
976
|
+
return typeof tag === "symbol";
|
|
977
|
+
}
|
|
978
|
+
function cloneTransferRegistration(value, path = "registration", seen = /* @__PURE__ */ new WeakSet()) {
|
|
979
|
+
if (value === null || typeof value !== "object" && typeof value !== "function")
|
|
980
|
+
return value;
|
|
981
|
+
if (typeof value === "function") return value;
|
|
982
|
+
if (isReactElementType(value)) return value;
|
|
983
|
+
if (seen.has(value))
|
|
984
|
+
throw new ContentTransferError(
|
|
985
|
+
"unsupported-registration-metadata",
|
|
986
|
+
"Circular transfer registration metadata is unsupported",
|
|
987
|
+
path
|
|
988
|
+
);
|
|
989
|
+
seen.add(value);
|
|
990
|
+
if (Array.isArray(value)) {
|
|
991
|
+
const copy2 = value.map(
|
|
992
|
+
(item, index) => cloneTransferRegistration(item, `${path}/${index}`, seen)
|
|
993
|
+
);
|
|
994
|
+
seen.delete(value);
|
|
995
|
+
return Object.freeze(copy2);
|
|
996
|
+
}
|
|
997
|
+
const prototype = Object.getPrototypeOf(value);
|
|
998
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
999
|
+
throw new ContentTransferError(
|
|
1000
|
+
"unsupported-registration-metadata",
|
|
1001
|
+
"Transfer registration metadata must use plain objects and arrays",
|
|
1002
|
+
path
|
|
1003
|
+
);
|
|
1004
|
+
const copy = Object.create(prototype);
|
|
1005
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
1006
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
1007
|
+
if (!("value" in descriptor))
|
|
1008
|
+
throw new ContentTransferError(
|
|
1009
|
+
"unsupported-registration-metadata",
|
|
1010
|
+
"Transfer registration metadata cannot use accessors",
|
|
1011
|
+
`${path}/${String(key)}`
|
|
1012
|
+
);
|
|
1013
|
+
Object.defineProperty(copy, key, {
|
|
1014
|
+
value: cloneTransferRegistration(
|
|
1015
|
+
descriptor.value,
|
|
1016
|
+
`${path}/${String(key)}`,
|
|
1017
|
+
seen
|
|
1018
|
+
),
|
|
1019
|
+
enumerable: descriptor.enumerable === true,
|
|
1020
|
+
writable: false,
|
|
1021
|
+
configurable: false
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
seen.delete(value);
|
|
1025
|
+
return Object.freeze(copy);
|
|
1026
|
+
}
|
|
1027
|
+
function resolveTransferRegistry(...groups) {
|
|
1028
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1029
|
+
const result = [];
|
|
1030
|
+
for (const group of groups)
|
|
1031
|
+
for (const item of group) {
|
|
1032
|
+
const copy = cloneTransferRegistration(item);
|
|
1033
|
+
if (!copy.id.trim() || ids.has(copy.id))
|
|
1034
|
+
throw new ContentTransferError(
|
|
1035
|
+
"duplicate-registration",
|
|
1036
|
+
`Transfer id ${JSON.stringify(copy.id)} is empty or registered more than once`
|
|
1037
|
+
);
|
|
1038
|
+
ids.add(copy.id);
|
|
1039
|
+
result.push(copy);
|
|
1040
|
+
}
|
|
1041
|
+
return Object.freeze(result);
|
|
1042
|
+
}
|
|
1043
|
+
function createSurfaceTransferHandle(options) {
|
|
1044
|
+
const declarations = resolveTransferRegistry(
|
|
1045
|
+
options.manifest.values.map((value) => ({ ...value, id: value.name }))
|
|
1046
|
+
);
|
|
1047
|
+
return {
|
|
1048
|
+
instanceId: options.instanceId,
|
|
1049
|
+
surfaceName: options.manifest.surfaceName,
|
|
1050
|
+
isMounted: options.isMounted,
|
|
1051
|
+
async capture(signal) {
|
|
1052
|
+
stop(signal);
|
|
1053
|
+
if (!options.isMounted())
|
|
1054
|
+
throw new ContentTransferError(
|
|
1055
|
+
"surface-unmounted",
|
|
1056
|
+
"The captured surface is no longer mounted"
|
|
1057
|
+
);
|
|
1058
|
+
const revisionBefore = options.getRevision?.();
|
|
1059
|
+
const scope = await options.getScope();
|
|
1060
|
+
stop(signal);
|
|
1061
|
+
if (!options.isMounted())
|
|
1062
|
+
throw new ContentTransferError(
|
|
1063
|
+
"surface-unmounted",
|
|
1064
|
+
"The surface closed during capture"
|
|
1065
|
+
);
|
|
1066
|
+
if (revisionBefore !== void 0 && options.getRevision?.() !== revisionBefore)
|
|
1067
|
+
throw new ContentTransferError(
|
|
1068
|
+
"surface-changed",
|
|
1069
|
+
"The surface changed during capture; capture again"
|
|
1070
|
+
);
|
|
1071
|
+
const value = {};
|
|
1072
|
+
for (const declaration of declarations) {
|
|
1073
|
+
if (Object.hasOwn(scope, declaration.name) && scope[declaration.name] !== void 0) {
|
|
1074
|
+
Object.defineProperty(value, declaration.name, {
|
|
1075
|
+
value: cloneSurfaceValue(
|
|
1076
|
+
scope[declaration.name],
|
|
1077
|
+
`/${enc(declaration.name)}`
|
|
1078
|
+
),
|
|
1079
|
+
enumerable: true,
|
|
1080
|
+
writable: true,
|
|
1081
|
+
configurable: true
|
|
1082
|
+
});
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
return directSource(
|
|
1086
|
+
{ kind: "json", value },
|
|
1087
|
+
{
|
|
1088
|
+
sourceId: options.instanceId,
|
|
1089
|
+
revision: revisionBefore ?? uid(),
|
|
1090
|
+
label: options.manifest.label ?? options.manifest.surfaceName,
|
|
1091
|
+
unsavedChanges: options.unsavedChanges?.() ?? false,
|
|
1092
|
+
sections: declarations.filter((d) => Object.hasOwn(value, d.name)).map((d) => ({
|
|
1093
|
+
id: d.name,
|
|
1094
|
+
label: d.label,
|
|
1095
|
+
path: `/${enc(d.name)}`,
|
|
1096
|
+
includedByDefault: d.includedByDefault ?? true
|
|
1097
|
+
})),
|
|
1098
|
+
projection: {
|
|
1099
|
+
rules: [
|
|
1100
|
+
...options.projection?.rules ?? [],
|
|
1101
|
+
...declarations.map((d) => ({
|
|
1102
|
+
target: "payload",
|
|
1103
|
+
path: `/${enc(d.name)}`,
|
|
1104
|
+
exportable: d.exportable ?? true,
|
|
1105
|
+
classification: d.classification ?? "ordinary"
|
|
1106
|
+
}))
|
|
1107
|
+
]
|
|
1108
|
+
},
|
|
1109
|
+
...options.limits ? { limits: options.limits } : {}
|
|
1110
|
+
}
|
|
1111
|
+
);
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
function limitJson(value, limits, omissions, path = "", depth = 0) {
|
|
1116
|
+
if (limits.maxDepth != null && depth > limits.maxDepth) {
|
|
1117
|
+
omissions.push({ path, reason: "truncated" });
|
|
1118
|
+
return null;
|
|
1119
|
+
}
|
|
1120
|
+
if (typeof value === "string" && limits.maxStringChars != null && Array.from(value).length > limits.maxStringChars) {
|
|
1121
|
+
const chars = Array.from(value);
|
|
1122
|
+
omissions.push({
|
|
1123
|
+
path,
|
|
1124
|
+
reason: "truncated",
|
|
1125
|
+
count: chars.length - limits.maxStringChars
|
|
1126
|
+
});
|
|
1127
|
+
return chars.slice(0, limits.maxStringChars).join("");
|
|
1128
|
+
}
|
|
1129
|
+
if (Array.isArray(value)) {
|
|
1130
|
+
const count = Math.min(value.length, limits.maxArrayItems ?? value.length);
|
|
1131
|
+
if (count < value.length)
|
|
1132
|
+
omissions.push({
|
|
1133
|
+
path,
|
|
1134
|
+
reason: "truncated",
|
|
1135
|
+
count: value.length - count
|
|
1136
|
+
});
|
|
1137
|
+
return value.slice(0, count).map(
|
|
1138
|
+
(item, index) => limitJson(item, limits, omissions, `${path}/${index}`, depth + 1)
|
|
1139
|
+
);
|
|
1140
|
+
}
|
|
1141
|
+
if (value && typeof value === "object")
|
|
1142
|
+
return Object.fromEntries(
|
|
1143
|
+
Object.entries(value).map(([key, item]) => [
|
|
1144
|
+
key,
|
|
1145
|
+
limitJson(item, limits, omissions, `${path}/${enc(key)}`, depth + 1)
|
|
1146
|
+
])
|
|
1147
|
+
);
|
|
1148
|
+
return value;
|
|
1149
|
+
}
|
|
1150
|
+
function limitPayload(payload, limits, omissions) {
|
|
1151
|
+
limitKeys.forEach((key) => assertLimit(limits[key], key));
|
|
1152
|
+
if (payload.kind === "rows") {
|
|
1153
|
+
const count = Math.min(
|
|
1154
|
+
payload.rows.length,
|
|
1155
|
+
limits.maxRows ?? payload.rows.length
|
|
1156
|
+
);
|
|
1157
|
+
if (count < payload.rows.length)
|
|
1158
|
+
omissions.push({
|
|
1159
|
+
path: "/rows",
|
|
1160
|
+
reason: "truncated",
|
|
1161
|
+
count: payload.rows.length - count
|
|
1162
|
+
});
|
|
1163
|
+
return {
|
|
1164
|
+
...payload,
|
|
1165
|
+
rows: payload.rows.slice(0, count).map(
|
|
1166
|
+
(row, index) => limitJson(row, limits, omissions, `/rows/${index}`)
|
|
1167
|
+
)
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
if (payload.kind === "json" || payload.kind === "registered")
|
|
1171
|
+
return { ...payload, value: limitJson(payload.value, limits, omissions) };
|
|
1172
|
+
return {
|
|
1173
|
+
...payload,
|
|
1174
|
+
text: limitJson(payload.text, limits, omissions)
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
function applyTransferLimits(draft, limits) {
|
|
1178
|
+
const omissions = [];
|
|
1179
|
+
const payload = limitPayload(draft.payload, limits, omissions);
|
|
1180
|
+
return omissions.length ? revise(draft, payload, omissions, "Applied preparation limits") : draft;
|
|
1181
|
+
}
|
|
1182
|
+
var import_json_format, import_html_escape, TRANSFER_ERROR, ContentTransferError, bound, stop, enc, dec, maxSurfacePointerSegmentLength, maxSurfacePointerLength, truncateSurfacePointer, uid, editDraft, resetDraft, sourceChanged, textValue, limitKeys;
|
|
1183
|
+
var init_core = __esm({
|
|
1184
|
+
"src/operate/core.ts"() {
|
|
1185
|
+
"use strict";
|
|
1186
|
+
import_json_format = require("@ai-matrx/kit/json-format");
|
|
1187
|
+
import_html_escape = require("@ai-matrx/kit/html-escape");
|
|
1188
|
+
init_types();
|
|
1189
|
+
init_agent_payload();
|
|
1190
|
+
TRANSFER_ERROR = /* @__PURE__ */ Symbol.for("ai-matrx.alchemy.operate.transfer-error");
|
|
1191
|
+
ContentTransferError = class extends Error {
|
|
1192
|
+
code;
|
|
1193
|
+
path;
|
|
1194
|
+
constructor(code, message, path) {
|
|
1195
|
+
super(message);
|
|
1196
|
+
this.code = code;
|
|
1197
|
+
this.path = path;
|
|
1198
|
+
this[TRANSFER_ERROR] = true;
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* One error class across every loaded copy: while `@ai-matrx/kit/content-transfer`
|
|
1202
|
+
* still bundles this module for its not-yet-repointed consumers (ALC-16), an
|
|
1203
|
+
* error raised by one copy is `instanceof` the other.
|
|
1204
|
+
*/
|
|
1205
|
+
static [Symbol.hasInstance](value) {
|
|
1206
|
+
return typeof value === "object" && value !== null && value[TRANSFER_ERROR] === true;
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
bound = /* @__PURE__ */ Symbol.for("ai-matrx.alchemy.operate.bound-all-matching");
|
|
1210
|
+
stop = (s) => {
|
|
1211
|
+
if (s.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1212
|
+
};
|
|
1213
|
+
enc = (x) => x.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
1214
|
+
dec = (x) => x.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1215
|
+
maxSurfacePointerSegmentLength = 64;
|
|
1216
|
+
maxSurfacePointerLength = 192;
|
|
1217
|
+
truncateSurfacePointer = (value, maxLength) => {
|
|
1218
|
+
const characters = Array.from(value);
|
|
1219
|
+
return characters.length > maxLength ? `${characters.slice(0, maxLength - 1).join("")}\u2026` : value;
|
|
1220
|
+
};
|
|
1221
|
+
uid = () => globalThis.crypto?.randomUUID?.() ?? `capture-${Date.now()}-${Math.random()}`;
|
|
1222
|
+
editDraft = (d, p) => revise(d, p, [], "Manual edit", true, "manual");
|
|
1223
|
+
resetDraft = (s) => createDraft(s);
|
|
1224
|
+
sourceChanged = (d, s) => d.sourceId !== s.sourceId || d.sourceRevision !== s.revision;
|
|
1225
|
+
textValue = (value) => value === void 0 || value === null ? "" : typeof value === "string" ? value : (0, import_json_format.stringifyJson)(value, { style: "compact" });
|
|
1226
|
+
limitKeys = [
|
|
1227
|
+
"maxRows",
|
|
1228
|
+
"maxStringChars",
|
|
1229
|
+
"maxDepth",
|
|
1230
|
+
"maxArrayItems",
|
|
1231
|
+
"targetTokens"
|
|
1232
|
+
];
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
|
|
1236
|
+
// src/operate/formats/rich-html.ts
|
|
1237
|
+
var rich_html_exports = {};
|
|
1238
|
+
__export(rich_html_exports, {
|
|
1239
|
+
loadMarkdownHtmlEngine: () => loadMarkdownHtmlEngine,
|
|
1240
|
+
markdownPlainText: () => markdownPlainText,
|
|
1241
|
+
richHtmlEngine: () => richHtmlEngine
|
|
1242
|
+
});
|
|
1243
|
+
async function loadMarkdownHtmlEngine() {
|
|
1244
|
+
const g = globalThis;
|
|
1245
|
+
g[ENGINE] ??= import("@ai-matrx/print/markdown-html").then((m) => m.createMarkdownHtmlEngine());
|
|
1246
|
+
return g[ENGINE];
|
|
1247
|
+
}
|
|
1248
|
+
function parseOptions(options, signal) {
|
|
1249
|
+
return {
|
|
1250
|
+
signal,
|
|
1251
|
+
...options.onNotice ? { onNotice: options.onNotice } : {},
|
|
1252
|
+
...options.assets ? { assets: options.assets } : {}
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
async function markdownPlainText(markdown, options, signal) {
|
|
1256
|
+
const engine = await loadMarkdownHtmlEngine();
|
|
1257
|
+
return engine.plainText(await engine.parse(markdown, parseOptions(options, signal)));
|
|
1258
|
+
}
|
|
1259
|
+
var ENGINE, richHtmlEngine;
|
|
1260
|
+
var init_rich_html = __esm({
|
|
1261
|
+
"src/operate/formats/rich-html.ts"() {
|
|
1262
|
+
"use strict";
|
|
1263
|
+
init_core();
|
|
1264
|
+
ENGINE = /* @__PURE__ */ Symbol.for("ai-matrx.alchemy.operate.markdown-html-engine");
|
|
1265
|
+
richHtmlEngine = {
|
|
1266
|
+
async build(draft, options, signal) {
|
|
1267
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1268
|
+
if (draft.payload.kind !== "markdown") {
|
|
1269
|
+
throw new ContentTransferError("unsupported-format", "Formatted copy needs Markdown content. Copy it as plain text instead.");
|
|
1270
|
+
}
|
|
1271
|
+
const engine = await loadMarkdownHtmlEngine();
|
|
1272
|
+
const tree = await engine.parse(draft.payload.text, parseOptions(options, signal));
|
|
1273
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1274
|
+
const html = engine.fragment(tree, { skin: options.skin ?? "inline", profile: options.profile ?? "generic" });
|
|
1275
|
+
return sealTransferArtifact({
|
|
1276
|
+
snapshotId: draft.snapshotId,
|
|
1277
|
+
draftRevision: draft.revision,
|
|
1278
|
+
format: "rich-html",
|
|
1279
|
+
plainText: engine.plainText(tree),
|
|
1280
|
+
html,
|
|
1281
|
+
file: { filename: options.filename ?? "export.html", mime: "text/html;charset=utf-8", bytes: new TextEncoder().encode(html) },
|
|
1282
|
+
omissions: draft.omissions.map((o) => ({ ...o }))
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
});
|
|
1288
|
+
|
|
1289
|
+
// src/operate/formats/document.ts
|
|
1290
|
+
var document_exports = {};
|
|
1291
|
+
__export(document_exports, {
|
|
1292
|
+
documentEngine: () => documentEngine,
|
|
1293
|
+
documentHtmlEngine: () => documentHtmlEngine
|
|
1294
|
+
});
|
|
1295
|
+
function markdownOf(draft) {
|
|
1296
|
+
const p = draft.payload;
|
|
1297
|
+
if (p.kind === "markdown") return p.text;
|
|
1298
|
+
if (p.kind === "text") {
|
|
1299
|
+
if (!p.language) return p.text;
|
|
1300
|
+
return fencedCodeBlock(p.text, p.language);
|
|
1301
|
+
}
|
|
1302
|
+
throw new ContentTransferError("unsupported-format", "A document needs text or Markdown content. Download it as JSON or CSV instead.");
|
|
1303
|
+
}
|
|
1304
|
+
function documentEngine(format) {
|
|
1305
|
+
return {
|
|
1306
|
+
async build(draft, options, signal) {
|
|
1307
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1308
|
+
const source = markdownOf(draft);
|
|
1309
|
+
const { exportDocument } = await import("@ai-matrx/print/document");
|
|
1310
|
+
const name = stem(options.filename);
|
|
1311
|
+
const out = await exportDocument(source, format, {
|
|
1312
|
+
...name ? { fileName: name } : {},
|
|
1313
|
+
...options.onNotice ? { onNotice: (n) => options.onNotice?.({ code: n.code, sentence: n.message, remedy: n.remedy }) } : {}
|
|
1314
|
+
});
|
|
1315
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1316
|
+
return sealTransferArtifact({
|
|
1317
|
+
snapshotId: draft.snapshotId,
|
|
1318
|
+
draftRevision: draft.revision,
|
|
1319
|
+
format,
|
|
1320
|
+
plainText: source,
|
|
1321
|
+
file: { filename: out.fileName, mime: out.mime, bytes: out.bytes },
|
|
1322
|
+
omissions: draft.omissions.map((o) => ({ ...o }))
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
var enc2, stem, documentHtmlEngine;
|
|
1328
|
+
var init_document = __esm({
|
|
1329
|
+
"src/operate/formats/document.ts"() {
|
|
1330
|
+
"use strict";
|
|
1331
|
+
init_core();
|
|
1332
|
+
init_fenced_code();
|
|
1333
|
+
init_rich_html();
|
|
1334
|
+
enc2 = new TextEncoder();
|
|
1335
|
+
stem = (filename) => filename ? filename.replace(/\.[a-z0-9]+$/i, "") : void 0;
|
|
1336
|
+
documentHtmlEngine = {
|
|
1337
|
+
async build(draft, options, signal) {
|
|
1338
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1339
|
+
const engine = await loadMarkdownHtmlEngine();
|
|
1340
|
+
const tree = await engine.parse(markdownOf(draft), {
|
|
1341
|
+
signal,
|
|
1342
|
+
...options.onNotice ? { onNotice: options.onNotice } : {},
|
|
1343
|
+
...options.assets ? { assets: options.assets } : {}
|
|
1344
|
+
});
|
|
1345
|
+
const page = engine.document(tree);
|
|
1346
|
+
return sealTransferArtifact({
|
|
1347
|
+
snapshotId: draft.snapshotId,
|
|
1348
|
+
draftRevision: draft.revision,
|
|
1349
|
+
format: "html",
|
|
1350
|
+
plainText: engine.plainText(tree),
|
|
1351
|
+
html: page,
|
|
1352
|
+
file: { filename: options.filename ?? "export.html", mime: "text/html;charset=utf-8", bytes: enc2.encode(page) },
|
|
1353
|
+
omissions: draft.omissions.map((o) => ({ ...o }))
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
// src/operate/formats/xlsx.ts
|
|
1361
|
+
var xlsx_exports = {};
|
|
1362
|
+
__export(xlsx_exports, {
|
|
1363
|
+
xlsxEngine: () => xlsxEngine
|
|
1364
|
+
});
|
|
1365
|
+
var cell, xlsxEngine;
|
|
1366
|
+
var init_xlsx = __esm({
|
|
1367
|
+
"src/operate/formats/xlsx.ts"() {
|
|
1368
|
+
"use strict";
|
|
1369
|
+
init_core();
|
|
1370
|
+
cell = (value) => value === void 0 || value === null ? null : typeof value === "string" || typeof value === "number" || typeof value === "boolean" ? value : JSON.stringify(value);
|
|
1371
|
+
xlsxEngine = {
|
|
1372
|
+
async build(draft, options, signal) {
|
|
1373
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1374
|
+
const p = draft.payload;
|
|
1375
|
+
if (p.kind !== "rows") throw new ContentTransferError("unsupported-format", "An Excel workbook needs table rows. Download it as CSV or JSON instead.");
|
|
1376
|
+
const columns = p.columns.filter(
|
|
1377
|
+
(c) => c.visible && c.exportable !== false && c.classification !== "secret" && c.classification !== "credential"
|
|
1378
|
+
);
|
|
1379
|
+
const XLSX = await import("xlsx");
|
|
1380
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1381
|
+
const sheet = XLSX.utils.aoa_to_sheet([columns.map((c) => c.label), ...p.rows.map((row) => columns.map((c) => cell(readTransferCell(row, c))))]);
|
|
1382
|
+
const book = XLSX.utils.book_new();
|
|
1383
|
+
const filename = options.filename ?? "export.xlsx";
|
|
1384
|
+
const sheetName = filename.replace(/\.xlsx$/i, "").replace(/[\\/?*[\]:]/g, " ").trim().slice(0, 31) || "Data";
|
|
1385
|
+
XLSX.utils.book_append_sheet(book, sheet, sheetName);
|
|
1386
|
+
const written = XLSX.write(book, { type: "array", bookType: "xlsx", compression: true });
|
|
1387
|
+
return sealTransferArtifact({
|
|
1388
|
+
snapshotId: draft.snapshotId,
|
|
1389
|
+
draftRevision: draft.revision,
|
|
1390
|
+
format: "xlsx",
|
|
1391
|
+
plainText: serialize(draft, "tsv", { spreadsheetSafe: true }).plainText,
|
|
1392
|
+
file: {
|
|
1393
|
+
filename,
|
|
1394
|
+
mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
1395
|
+
bytes: written instanceof Uint8Array ? written : new Uint8Array(written)
|
|
1396
|
+
},
|
|
1397
|
+
omissions: draft.omissions.map((o) => ({ ...o }))
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
});
|
|
1403
|
+
|
|
17
1404
|
// src/index.ts
|
|
18
1405
|
var src_exports = {};
|
|
1406
|
+
__export(src_exports, {
|
|
1407
|
+
ContentTransferError: () => ContentTransferError,
|
|
1408
|
+
FORMAT_ADAPTERS: () => FORMAT_ADAPTERS,
|
|
1409
|
+
applySectionSelection: () => applySectionSelection,
|
|
1410
|
+
applyTransferLimits: () => applyTransferLimits,
|
|
1411
|
+
buildAgentPayload: () => buildAgentPayload,
|
|
1412
|
+
capture: () => capture,
|
|
1413
|
+
collectAllMatching: () => collectAllMatching,
|
|
1414
|
+
createBrowserTransport: () => createBrowserTransport,
|
|
1415
|
+
createDelivery: () => createDelivery,
|
|
1416
|
+
createDraft: () => createDraft,
|
|
1417
|
+
createSurfaceTransferHandle: () => createSurfaceTransferHandle,
|
|
1418
|
+
directSource: () => directSource,
|
|
1419
|
+
editDraft: () => editDraft,
|
|
1420
|
+
eligibleFormats: () => eligibleFormats,
|
|
1421
|
+
extensionForLanguage: () => extensionForLanguage,
|
|
1422
|
+
fenceJsonBlock: () => fenceJsonBlock,
|
|
1423
|
+
formatAdapter: () => formatAdapter,
|
|
1424
|
+
isSealed: () => isSealed,
|
|
1425
|
+
normalizeTransferJson: () => normalizeTransferJson,
|
|
1426
|
+
openPreparation: () => openPreparation,
|
|
1427
|
+
projectSnapshot: () => projectSnapshot,
|
|
1428
|
+
readTransferCell: () => readTransferCell,
|
|
1429
|
+
reduceJson: () => reduceJson,
|
|
1430
|
+
refreshDraft: () => refreshDraft,
|
|
1431
|
+
resetDraft: () => resetDraft,
|
|
1432
|
+
resolveTransferPreferences: () => resolveTransferPreferences,
|
|
1433
|
+
resolveTransferRegistry: () => resolveTransferRegistry,
|
|
1434
|
+
sealArtifact: () => sealArtifact,
|
|
1435
|
+
sealDraft: () => sealDraft,
|
|
1436
|
+
sealTransferArtifact: () => sealTransferArtifact,
|
|
1437
|
+
serialize: () => serialize,
|
|
1438
|
+
sourceChanged: () => sourceChanged,
|
|
1439
|
+
transformRows: () => transformRows,
|
|
1440
|
+
undoDraft: () => undoDraft
|
|
1441
|
+
});
|
|
19
1442
|
module.exports = __toCommonJS(src_exports);
|
|
20
|
-
|
|
1443
|
+
|
|
1444
|
+
// src/operate.ts
|
|
1445
|
+
init_core();
|
|
1446
|
+
|
|
1447
|
+
// src/operate/formats.ts
|
|
1448
|
+
init_core();
|
|
1449
|
+
init_fenced_code();
|
|
1450
|
+
var enc3 = new TextEncoder();
|
|
1451
|
+
var isRows = (p) => p.kind === "rows";
|
|
1452
|
+
var isProse = (p) => p.kind === "markdown" || p.kind === "text";
|
|
1453
|
+
var always = () => true;
|
|
1454
|
+
var LANGUAGE_EXTENSION = {
|
|
1455
|
+
typescript: "ts",
|
|
1456
|
+
ts: "ts",
|
|
1457
|
+
tsx: "tsx",
|
|
1458
|
+
javascript: "js",
|
|
1459
|
+
js: "js",
|
|
1460
|
+
jsx: "jsx",
|
|
1461
|
+
python: "py",
|
|
1462
|
+
py: "py",
|
|
1463
|
+
json: "json",
|
|
1464
|
+
html: "html",
|
|
1465
|
+
css: "css",
|
|
1466
|
+
sql: "sql",
|
|
1467
|
+
bash: "sh",
|
|
1468
|
+
sh: "sh",
|
|
1469
|
+
shell: "sh",
|
|
1470
|
+
zsh: "sh",
|
|
1471
|
+
yaml: "yaml",
|
|
1472
|
+
yml: "yaml",
|
|
1473
|
+
markdown: "md",
|
|
1474
|
+
md: "md",
|
|
1475
|
+
go: "go",
|
|
1476
|
+
rust: "rs",
|
|
1477
|
+
java: "java",
|
|
1478
|
+
ruby: "rb",
|
|
1479
|
+
php: "php",
|
|
1480
|
+
csharp: "cs",
|
|
1481
|
+
cs: "cs",
|
|
1482
|
+
cpp: "cpp",
|
|
1483
|
+
c: "c",
|
|
1484
|
+
swift: "swift",
|
|
1485
|
+
kotlin: "kt",
|
|
1486
|
+
xml: "xml",
|
|
1487
|
+
toml: "toml"
|
|
1488
|
+
};
|
|
1489
|
+
function extensionForLanguage(language) {
|
|
1490
|
+
return language && LANGUAGE_EXTENSION[language.trim().toLowerCase()] || "txt";
|
|
1491
|
+
}
|
|
1492
|
+
function checkSignal(signal) {
|
|
1493
|
+
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
|
|
1494
|
+
}
|
|
1495
|
+
function textArtifact(draft, format, text, mime, filename, html) {
|
|
1496
|
+
return sealTransferArtifact({
|
|
1497
|
+
snapshotId: draft.snapshotId,
|
|
1498
|
+
draftRevision: draft.revision,
|
|
1499
|
+
format,
|
|
1500
|
+
plainText: text,
|
|
1501
|
+
...html === void 0 ? {} : { html },
|
|
1502
|
+
file: { filename, mime, bytes: enc3.encode(html ?? text) },
|
|
1503
|
+
omissions: draft.omissions.map((o) => ({ ...o }))
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
function serialized(format, extension) {
|
|
1507
|
+
return {
|
|
1508
|
+
async build(draft, options, signal) {
|
|
1509
|
+
checkSignal(signal);
|
|
1510
|
+
const a = serialize(draft, format, {
|
|
1511
|
+
filename: options.filename ?? `export.${extension}`,
|
|
1512
|
+
...options.spreadsheetSafe === void 0 ? { spreadsheetSafe: format === "csv" || format === "tsv" } : { spreadsheetSafe: options.spreadsheetSafe }
|
|
1513
|
+
});
|
|
1514
|
+
return a;
|
|
1515
|
+
}
|
|
1516
|
+
};
|
|
1517
|
+
}
|
|
1518
|
+
var plainEngine = {
|
|
1519
|
+
async build(draft, options, signal) {
|
|
1520
|
+
checkSignal(signal);
|
|
1521
|
+
if (draft.payload.kind === "markdown") {
|
|
1522
|
+
const { markdownPlainText: markdownPlainText2 } = await Promise.resolve().then(() => (init_rich_html(), rich_html_exports));
|
|
1523
|
+
const text = await markdownPlainText2(draft.payload.text, options, signal);
|
|
1524
|
+
return textArtifact(draft, "plain", text, "text/plain;charset=utf-8", options.filename ?? "export.txt");
|
|
1525
|
+
}
|
|
1526
|
+
const ext = draft.payload.kind === "text" ? extensionForLanguage(draft.payload.language) : "txt";
|
|
1527
|
+
const a = serialize(draft, "plain", { filename: options.filename ?? `export.${ext}` });
|
|
1528
|
+
return a;
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
var markdownEngine = {
|
|
1532
|
+
async build(draft, options, signal) {
|
|
1533
|
+
checkSignal(signal);
|
|
1534
|
+
const p = draft.payload;
|
|
1535
|
+
if (p.kind === "text" && p.language) {
|
|
1536
|
+
const text = fencedCodeBlock(p.text, p.language);
|
|
1537
|
+
return textArtifact(draft, "markdown", text, "text/markdown;charset=utf-8", options.filename ?? "export.md");
|
|
1538
|
+
}
|
|
1539
|
+
return serialize(draft, "markdown", { filename: options.filename ?? "export.md" });
|
|
1540
|
+
}
|
|
1541
|
+
};
|
|
1542
|
+
var htmlEngine = {
|
|
1543
|
+
async build(draft, options, signal) {
|
|
1544
|
+
checkSignal(signal);
|
|
1545
|
+
if (isProse(draft.payload)) {
|
|
1546
|
+
const { documentHtmlEngine: documentHtmlEngine2 } = await Promise.resolve().then(() => (init_document(), document_exports));
|
|
1547
|
+
return documentHtmlEngine2.build(draft, options, signal);
|
|
1548
|
+
}
|
|
1549
|
+
return serialize(draft, "html", { filename: options.filename ?? "export.html" });
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
var lazy = (pick) => pick;
|
|
1553
|
+
var FORMAT_ADAPTERS = Object.freeze([
|
|
1554
|
+
{ id: "plain", label: "Plain text", extension: "txt", mime: "text/plain;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: always, load: async () => plainEngine },
|
|
1555
|
+
{ id: "markdown", label: "Markdown", extension: "md", mime: "text/markdown;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: (p) => p.kind !== "json" && p.kind !== "registered", load: async () => markdownEngine },
|
|
1556
|
+
{
|
|
1557
|
+
// Google Docs and Word are ONE action until a destination profile produces different bytes (1.9a).
|
|
1558
|
+
id: "rich-html",
|
|
1559
|
+
label: "Copy formatted",
|
|
1560
|
+
extension: "html",
|
|
1561
|
+
mime: "text/html;charset=utf-8",
|
|
1562
|
+
modes: ["copy"],
|
|
1563
|
+
runsOn: "client",
|
|
1564
|
+
supports: (p) => p.kind === "markdown",
|
|
1565
|
+
load: lazy(async () => (await Promise.resolve().then(() => (init_rich_html(), rich_html_exports))).richHtmlEngine)
|
|
1566
|
+
},
|
|
1567
|
+
{ id: "html", label: "HTML page", extension: "html", mime: "text/html;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: (p) => p.kind !== "registered", load: async () => htmlEngine },
|
|
1568
|
+
{ id: "json", label: "JSON", extension: "json", mime: "application/json;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: (p) => p.kind !== "registered", load: async () => serialized("json", "json") },
|
|
1569
|
+
{ id: "compact-json", label: "Compact JSON", extension: "json", mime: "application/json;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: (p) => p.kind !== "registered", load: async () => serialized("compact-json", "json") },
|
|
1570
|
+
{ id: "csv", label: "CSV", extension: "csv", mime: "text/csv;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: isRows, load: async () => serialized("csv", "csv") },
|
|
1571
|
+
{ id: "tsv", label: "Google Sheets", extension: "tsv", mime: "text/tab-separated-values;charset=utf-8", modes: ["copy", "download"], runsOn: "client", supports: isRows, load: async () => serialized("tsv", "tsv") },
|
|
1572
|
+
{
|
|
1573
|
+
id: "xlsx",
|
|
1574
|
+
label: "Excel workbook",
|
|
1575
|
+
extension: "xlsx",
|
|
1576
|
+
mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
1577
|
+
modes: ["download"],
|
|
1578
|
+
runsOn: "client",
|
|
1579
|
+
supports: isRows,
|
|
1580
|
+
load: lazy(async () => (await Promise.resolve().then(() => (init_xlsx(), xlsx_exports))).xlsxEngine)
|
|
1581
|
+
},
|
|
1582
|
+
{
|
|
1583
|
+
id: "pdf",
|
|
1584
|
+
label: "PDF",
|
|
1585
|
+
extension: "pdf",
|
|
1586
|
+
mime: "application/pdf",
|
|
1587
|
+
modes: ["download"],
|
|
1588
|
+
runsOn: "client",
|
|
1589
|
+
supports: isProse,
|
|
1590
|
+
load: lazy(async () => (await Promise.resolve().then(() => (init_document(), document_exports))).documentEngine("pdf"))
|
|
1591
|
+
},
|
|
1592
|
+
{
|
|
1593
|
+
id: "docx",
|
|
1594
|
+
label: "Word document",
|
|
1595
|
+
extension: "docx",
|
|
1596
|
+
mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
1597
|
+
modes: ["download"],
|
|
1598
|
+
runsOn: "client",
|
|
1599
|
+
supports: isProse,
|
|
1600
|
+
load: lazy(async () => (await Promise.resolve().then(() => (init_document(), document_exports))).documentEngine("docx"))
|
|
1601
|
+
},
|
|
1602
|
+
{
|
|
1603
|
+
id: "epub",
|
|
1604
|
+
label: "EPUB book",
|
|
1605
|
+
extension: "epub",
|
|
1606
|
+
mime: "application/epub+zip",
|
|
1607
|
+
modes: ["download"],
|
|
1608
|
+
runsOn: "client",
|
|
1609
|
+
supports: isProse,
|
|
1610
|
+
load: lazy(async () => (await Promise.resolve().then(() => (init_document(), document_exports))).documentEngine("epub"))
|
|
1611
|
+
}
|
|
1612
|
+
]);
|
|
1613
|
+
function eligibleFormats(payload, registered = [], mode) {
|
|
1614
|
+
return resolveTransferRegistry(FORMAT_ADAPTERS, registered).filter(
|
|
1615
|
+
(f) => f.supports(payload) && (mode === void 0 || f.modes.includes(mode))
|
|
1616
|
+
);
|
|
1617
|
+
}
|
|
1618
|
+
function formatAdapter(id, registered = []) {
|
|
1619
|
+
const found = resolveTransferRegistry(FORMAT_ADAPTERS, registered).find((f) => f.id === id);
|
|
1620
|
+
if (!found) throw new ContentTransferError("unsupported-format", `There is no "${id}" format. Choose one of the formats offered for this content.`);
|
|
1621
|
+
return found;
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
// src/operate/preparation.ts
|
|
1625
|
+
init_core();
|
|
1626
|
+
var SEALED = /* @__PURE__ */ Symbol.for("ai-matrx.alchemy.operate.sealed-artifacts");
|
|
1627
|
+
function sealedSet() {
|
|
1628
|
+
const g = globalThis;
|
|
1629
|
+
g[SEALED] ??= /* @__PURE__ */ new WeakSet();
|
|
1630
|
+
return g[SEALED];
|
|
1631
|
+
}
|
|
1632
|
+
function sealArtifact(artifact) {
|
|
1633
|
+
const frozen = sealTransferArtifact(artifact);
|
|
1634
|
+
sealedSet().add(frozen);
|
|
1635
|
+
return frozen;
|
|
1636
|
+
}
|
|
1637
|
+
function isSealed(artifact) {
|
|
1638
|
+
return typeof artifact === "object" && artifact !== null && sealedSet().has(artifact);
|
|
1639
|
+
}
|
|
1640
|
+
var notSealed = {
|
|
1641
|
+
status: "error",
|
|
1642
|
+
code: "not-sealed",
|
|
1643
|
+
message: "This content was not prepared for delivery, so nothing was copied or saved. Prepare it again and retry.",
|
|
1644
|
+
retryable: true
|
|
1645
|
+
};
|
|
1646
|
+
var optionsKey = (o) => JSON.stringify({ f: o.filename ?? null, s: o.spreadsheetSafe ?? null, k: o.skin ?? null, p: o.profile ?? null, h: o.highlightCode ?? false });
|
|
1647
|
+
async function openPreparation(source, scope, signal, options = {}) {
|
|
1648
|
+
const { snapshot } = await capture(source, signal, scope);
|
|
1649
|
+
let draft = createDraft(snapshot);
|
|
1650
|
+
const transforms = /* @__PURE__ */ new Map();
|
|
1651
|
+
for (const t of options.transforms ?? []) {
|
|
1652
|
+
if (transforms.has(t.id)) throw new ContentTransferError("duplicate-registration", `Transform "${t.id}" is registered more than once`);
|
|
1653
|
+
transforms.set(t.id, t);
|
|
1654
|
+
}
|
|
1655
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1656
|
+
return {
|
|
1657
|
+
get snapshot() {
|
|
1658
|
+
return snapshot;
|
|
1659
|
+
},
|
|
1660
|
+
get draft() {
|
|
1661
|
+
return draft;
|
|
1662
|
+
},
|
|
1663
|
+
async transform(id, transformOptions, transformSignal) {
|
|
1664
|
+
const t = transforms.get(id);
|
|
1665
|
+
if (!t) throw new ContentTransferError("unsupported-transform", `There is no "${id}" preparation step here.`);
|
|
1666
|
+
draft = await t.apply(draft, transformOptions, transformSignal);
|
|
1667
|
+
return draft;
|
|
1668
|
+
},
|
|
1669
|
+
edit(payload) {
|
|
1670
|
+
draft = editDraft(draft, payload);
|
|
1671
|
+
return draft;
|
|
1672
|
+
},
|
|
1673
|
+
selectSections(ids) {
|
|
1674
|
+
draft = applySectionSelection(draft, snapshot, ids);
|
|
1675
|
+
return draft;
|
|
1676
|
+
},
|
|
1677
|
+
undo() {
|
|
1678
|
+
draft = undoDraft(draft);
|
|
1679
|
+
return draft;
|
|
1680
|
+
},
|
|
1681
|
+
seal(format, formatOptions, sealSignal) {
|
|
1682
|
+
const adapter = formatAdapter(format, options.formats);
|
|
1683
|
+
if (!adapter.supports(draft.payload)) {
|
|
1684
|
+
return Promise.reject(new ContentTransferError("unsupported-format", `${adapter.label} is not available for this content.`));
|
|
1685
|
+
}
|
|
1686
|
+
const key = `${draft.revision}\0${format}\0${optionsKey(formatOptions)}`;
|
|
1687
|
+
const hit = cache.get(key);
|
|
1688
|
+
if (hit) return hit;
|
|
1689
|
+
const at2 = draft;
|
|
1690
|
+
const built = adapter.load().then((engine) => engine.build(at2, formatOptions, sealSignal)).then(sealArtifact);
|
|
1691
|
+
built.catch(() => cache.delete(key));
|
|
1692
|
+
cache.set(key, built);
|
|
1693
|
+
return built;
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
}
|
|
1697
|
+
async function sealDraft(draft, format, options, signal, formats) {
|
|
1698
|
+
const adapter = formatAdapter(format, formats);
|
|
1699
|
+
if (!adapter.supports(draft.payload)) throw new ContentTransferError("unsupported-format", `${adapter.label} is not available for this content.`);
|
|
1700
|
+
return sealArtifact(await (await adapter.load()).build(draft, options, signal));
|
|
1701
|
+
}
|
|
1702
|
+
function narrow(outcome) {
|
|
1703
|
+
if (outcome.status === "success" && outcome.delivered === "action") {
|
|
1704
|
+
return { status: "success", delivered: "clipboard", mimeTypes: outcome.mimeTypes };
|
|
1705
|
+
}
|
|
1706
|
+
if (outcome.status === "queued") {
|
|
1707
|
+
return { status: "error", code: "unexpected-queued", message: outcome.message, retryable: false };
|
|
1708
|
+
}
|
|
1709
|
+
return outcome;
|
|
1710
|
+
}
|
|
1711
|
+
function createDelivery(ports = {}) {
|
|
1712
|
+
const transport = ports.transport ?? createBrowserTransport();
|
|
1713
|
+
return {
|
|
1714
|
+
async copy(artifact, signal) {
|
|
1715
|
+
if (!isSealed(artifact)) return notSealed;
|
|
1716
|
+
return narrow(await transport.copy(artifact, signal));
|
|
1717
|
+
},
|
|
1718
|
+
copyPending(pending, signal, options = {}) {
|
|
1719
|
+
const clipboard = globalThis.navigator?.clipboard;
|
|
1720
|
+
const Item = globalThis.ClipboardItem;
|
|
1721
|
+
const checked = pending.then((a) => {
|
|
1722
|
+
if (!isSealed(a)) throw new ContentTransferError("not-sealed", notSealed.status === "error" ? notSealed.message : "");
|
|
1723
|
+
return a;
|
|
1724
|
+
});
|
|
1725
|
+
if (clipboard?.write && typeof Item === "function") {
|
|
1726
|
+
const text = checked.then((a) => new Blob([a.plainText], { type: "text/plain" }));
|
|
1727
|
+
const entries = { "text/plain": text };
|
|
1728
|
+
if (options.html) entries["text/html"] = checked.then((a) => new Blob([a.html ?? a.plainText], { type: "text/html" }));
|
|
1729
|
+
let item = null;
|
|
1730
|
+
try {
|
|
1731
|
+
item = new Item(entries);
|
|
1732
|
+
} catch {
|
|
1733
|
+
item = null;
|
|
1734
|
+
}
|
|
1735
|
+
if (item) {
|
|
1736
|
+
const written = clipboard.write([item]);
|
|
1737
|
+
return written.then(
|
|
1738
|
+
async () => signal.aborted ? { status: "cancelled" } : { status: "success", delivered: "clipboard", mimeTypes: options.html ? ["text/plain", "text/html"] : ["text/plain"] },
|
|
1739
|
+
async () => {
|
|
1740
|
+
try {
|
|
1741
|
+
const a = await checked;
|
|
1742
|
+
return narrow(await transport.copy(a, signal));
|
|
1743
|
+
} catch (error) {
|
|
1744
|
+
return error instanceof ContentTransferError && error.code === "not-sealed" ? notSealed : { status: "error", code: "clipboard-rejected", message: "The clipboard refused the copy. Try again.", retryable: true };
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
);
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
return checked.then(
|
|
1751
|
+
async (a) => narrow(await transport.copy(a, signal)),
|
|
1752
|
+
() => notSealed
|
|
1753
|
+
);
|
|
1754
|
+
},
|
|
1755
|
+
async download(artifact, signal) {
|
|
1756
|
+
if (!isSealed(artifact)) return notSealed;
|
|
1757
|
+
return narrow(await transport.download(artifact, signal));
|
|
1758
|
+
},
|
|
1759
|
+
async send(artifact, to, via) {
|
|
1760
|
+
if (!isSealed(artifact)) {
|
|
1761
|
+
return { status: "refused", to, reason: "failed", sentence: notSealed.status === "error" ? notSealed.message : "", remedy: "Prepare the content again, then send it." };
|
|
1762
|
+
}
|
|
1763
|
+
if (!ports.door) {
|
|
1764
|
+
return {
|
|
1765
|
+
status: "refused",
|
|
1766
|
+
to,
|
|
1767
|
+
reason: "unapplicable",
|
|
1768
|
+
sentence: "Sending to a destination is not available here yet, so nothing was sent.",
|
|
1769
|
+
remedy: "Copy or download it instead, then paste it where it belongs."
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
return ports.door.apply({ to, value: artifact.file ? artifact.file.bytes : artifact.plainText, origin: "user", via });
|
|
1773
|
+
}
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
21
1776
|
//# sourceMappingURL=index.cjs.map
|