-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaterial-export.js
More file actions
167 lines (155 loc) · 5.2 KB
/
Copy pathmaterial-export.js
File metadata and controls
167 lines (155 loc) · 5.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
(function installAtlasExport(global) {
const MAX_FILE_NAME_LENGTH = 180;
const DOWNLOADABLE_STATUSES = Object.freeze(["ready", "added"]);
function describe(item) {
if (!item || !DOWNLOADABLE_STATUSES.includes(item.status)) return null;
if (item.blobKey && item.fileName) {
return {
mode: "blob",
blobKey: String(item.blobKey),
fileName: safeFileName(item.fileName, fallbackName(item)),
mime: String(item.mime || "application/octet-stream")
};
}
const sourceTitle = item.source?.title || "";
if (item.kind === "selection" && item.text?.trim()) {
return textDescriptor(
item.text,
`${safeStem(sourceTitle || "selected-text")}-selection.txt`
);
}
if (item.kind === "link" && (item.url || item.source?.url)) {
const url = String(item.url || item.source.url).replace(/[\r\n]+/g, "");
return {
mode: "text",
fileName: safeFileName(`${safeStem(item.title || sourceTitle || "page-link")}.url`, "page-link.url"),
mime: "application/internet-shortcut;charset=utf-8",
text: `[InternetShortcut]\r\nURL=${url}\r\n`
};
}
if (item.kind === "prompt" && item.text?.trim()) {
return textDescriptor(
item.text,
`${safeStem(item.promptName || "saved-prompt")}.txt`
);
}
if (item.kind === "transcript" && item.text?.trim()) {
return textDescriptor(
item.text,
`${safeStem(sourceTitle || "video-transcript")}-transcript.txt`
);
}
if (item.kind === "document" && item.text?.trim()) {
return textDescriptor(
item.text,
`${safeStem(sourceTitle || "document")}.txt`
);
}
return null;
}
function textDescriptor(text, fileName) {
return {
mode: "text",
fileName: safeFileName(fileName, "atlas-material.txt"),
mime: "text/plain;charset=utf-8",
text: String(text).replace(/\r\n?/g, "\n").normalize("NFC")
};
}
function safeStem(value) {
return safeFileName(String(value || "material"), "material")
.replace(/\.[a-z0-9]{1,12}$/i, "") || "material";
}
function safeFileName(value, fallback = "atlas-material") {
const cleaned = String(value || "")
.normalize("NFC")
.replace(/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069/\\:*?"<>|]+/g, "-")
.replace(/\s+/g, " ")
.replace(/^\.+/g, "")
.replace(/[. ]+$/g, "")
.trim();
let name = cleaned || fallback;
if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) {
name = `_${name}`;
}
if (name.length <= MAX_FILE_NAME_LENGTH) return name;
const match = name.match(/(\.[a-z0-9]{1,12})$/i);
const extension = match?.[1] || "";
return `${name.slice(0, MAX_FILE_NAME_LENGTH - extension.length).trim()}${extension}`;
}
function fallbackName(item) {
const extension = {
screenshot: ".png",
transcript: ".vtt",
selection: ".txt",
document: ""
}[item?.kind] || "";
return `atlas-${item?.kind || "material"}${extension}`;
}
async function download(
item,
{
loadBlob,
startDownload,
createObjectUrl = (blob) => global.URL.createObjectURL(blob),
revokeObjectUrl = (url) => global.URL.revokeObjectURL(url),
scheduleRevoke = (callback) => setTimeout(callback, 30_000)
} = {}
) {
const descriptor = describe(item);
if (!descriptor) throw exportError("not-downloadable");
if (typeof startDownload !== "function") throw exportError("download-unavailable");
let blob;
if (descriptor.mode === "blob") {
blob = typeof loadBlob === "function" ? await loadBlob(descriptor.blobKey) : null;
if (!(blob instanceof Blob)) throw exportError("missing-blob");
} else {
blob = new Blob([descriptor.text], { type: descriptor.mime });
}
const objectUrl = createObjectUrl(blob);
try {
const downloadId = await startDownload({
url: objectUrl,
filename: descriptor.fileName,
conflictAction: "uniquify",
saveAs: false
});
if (!Number.isInteger(downloadId)) throw exportError("download-rejected");
scheduleRevoke(() => revokeObjectUrl(objectUrl));
return { ok: true, downloadId, fileName: descriptor.fileName };
} catch (error) {
revokeObjectUrl(objectUrl);
if (error?.name === "AtlasExportError") throw error;
throw exportError("download-rejected");
}
}
async function downloadMany(items, dependencies) {
const results = [];
for (const item of Array.isArray(items) ? items : []) {
try {
results.push({ itemId: item?.id || "", ...(await download(item, dependencies)) });
} catch (error) {
results.push({
itemId: item?.id || "",
ok: false,
code: error?.code || "download-failed",
error: error instanceof Error ? error.message : String(error)
});
}
}
return results;
}
function exportError(code) {
const error = new Error(code);
error.name = "AtlasExportError";
error.code = code;
return error;
}
global.AtlasExport = Object.freeze({
MAX_FILE_NAME_LENGTH,
DOWNLOADABLE_STATUSES,
describe,
safeFileName,
download,
downloadMany
});
})(globalThis);