pict-section-prompteditor 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Zip packaging for generated prompts: a folder of markdown files in a single
5
+ * download. jszip does the byte work; this wraps the two seams the section
6
+ * needs (build a zip from named files, hand a blob to the browser as a
7
+ * download) and stays usable from node tests via the nodebuffer type.
8
+ */
9
+
10
+ function _getJSZip()
11
+ {
12
+ if (typeof window !== 'undefined' && window.JSZip) { return window.JSZip; }
13
+ try { return require('jszip'); }
14
+ catch (pError) { return null; }
15
+ }
16
+
17
+ /**
18
+ * Build a zip from [{ Name, Content }] entries. Duplicate names get a numeric
19
+ * suffix so every entry survives.
20
+ * @param {Array<{Name: string, Content: string}>} pFiles
21
+ * @param {object} [pOptions] - { Type: 'blob' | 'nodebuffer' (default 'blob') }
22
+ * @returns {Promise<Blob|Buffer>}
23
+ */
24
+ function buildZip(pFiles, pOptions)
25
+ {
26
+ let tmpJSZip = _getJSZip();
27
+ if (!tmpJSZip) { return Promise.reject(new Error('jszip is not available')); }
28
+ let tmpType = (pOptions && pOptions.Type) || 'blob';
29
+ let tmpZip = new tmpJSZip();
30
+ let tmpSeen = {};
31
+ (pFiles || []).forEach((pFile) =>
32
+ {
33
+ let tmpName = String(pFile.Name || 'file.md');
34
+ if (tmpSeen[tmpName])
35
+ {
36
+ let tmpDot = tmpName.lastIndexOf('.');
37
+ let tmpBase = (tmpDot > 0) ? tmpName.slice(0, tmpDot) : tmpName;
38
+ let tmpExt = (tmpDot > 0) ? tmpName.slice(tmpDot) : '';
39
+ tmpName = tmpBase + '-' + (tmpSeen[pFile.Name] + 1) + tmpExt;
40
+ }
41
+ tmpSeen[pFile.Name] = (tmpSeen[pFile.Name] || 0) + 1;
42
+ tmpZip.file(tmpName, String(pFile.Content || ''));
43
+ });
44
+ return tmpZip.generateAsync({ type: tmpType });
45
+ }
46
+
47
+ /**
48
+ * Hand a blob to the browser as a named download.
49
+ * @param {Blob} pBlob
50
+ * @param {string} pFileName
51
+ */
52
+ function downloadBlob(pBlob, pFileName)
53
+ {
54
+ if (typeof document === 'undefined') { return; }
55
+ let tmpURL = URL.createObjectURL(pBlob);
56
+ let tmpAnchor = document.createElement('a');
57
+ tmpAnchor.href = tmpURL;
58
+ tmpAnchor.download = pFileName || 'prompts.zip';
59
+ document.body.appendChild(tmpAnchor);
60
+ tmpAnchor.click();
61
+ document.body.removeChild(tmpAnchor);
62
+ setTimeout(() => URL.revokeObjectURL(tmpURL), 1000);
63
+ }
64
+
65
+ module.exports = { buildZip, downloadBlob };