hfs 0.53.0-beta8 → 0.53.0-beta9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/admin/assets/{index-tmp9ryDR.js → index-CKQY3dM7.js} +112 -112
  2. package/admin/assets/{sha512-DvhxPRFX.js → sha512-CRQiqPhg.js} +1 -1
  3. package/admin/index.html +1 -1
  4. package/frontend/assets/{index-legacy-DygVvUke.js → index-legacy-D0PyKu9K.js} +7 -7
  5. package/frontend/assets/{sha512-legacy-BpgpVL8p.js → sha512-legacy-Sd8TlhD9.js} +1 -1
  6. package/frontend/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/api.get_file_list.js +2 -2
  9. package/src/api.log.js +3 -3
  10. package/src/api.plugins.js +0 -4
  11. package/src/commands.js +16 -5
  12. package/src/consoleLog.js +1 -1
  13. package/src/const.js +2 -2
  14. package/src/cross.js +5 -1
  15. package/src/customHtml.js +14 -3
  16. package/src/ddns.js +24 -13
  17. package/src/debounceAsync.js +5 -1
  18. package/src/events.js +16 -7
  19. package/src/fileAttr.js +35 -13
  20. package/src/frontEndApis.js +10 -19
  21. package/src/github.js +22 -6
  22. package/src/index.js +2 -2
  23. package/src/langs/hfs-lang-de.json +1 -1
  24. package/src/langs/hfs-lang-el.json +1 -1
  25. package/src/langs/hfs-lang-es.json +1 -1
  26. package/src/langs/hfs-lang-fi.json +8 -3
  27. package/src/langs/hfs-lang-fr.json +1 -1
  28. package/src/langs/hfs-lang-hu.json +1 -1
  29. package/src/langs/hfs-lang-it.json +7 -3
  30. package/src/langs/hfs-lang-ja.json +1 -1
  31. package/src/langs/hfs-lang-ko.json +1 -1
  32. package/src/langs/hfs-lang-nl.json +1 -1
  33. package/src/langs/hfs-lang-pt-br.json +1 -1
  34. package/src/langs/hfs-lang-ru.json +11 -8
  35. package/src/langs/hfs-lang-sr.json +1 -1
  36. package/src/langs/hfs-lang-vi.json +1 -1
  37. package/src/langs/hfs-lang-zh-tw.json +1 -1
  38. package/src/langs/hfs-lang-zh.json +1 -1
  39. package/src/misc.js +40 -1
  40. package/src/plugins.js +29 -4
  41. package/src/serveGuiAndSharedFiles.js +12 -0
  42. package/src/serveGuiFiles.js +1 -1
  43. package/src/update.js +3 -3
  44. package/src/upload.js +9 -11
  45. package/src/util-http.js +7 -3
  46. /package/src/{ip.js → ips.js} +0 -0
@@ -18,7 +18,7 @@
18
18
  "select_tooltip": "Selezionare serve con la funziona Zip e per cancellare (dove disponibile), ma puoi anche filtrare la lista",
19
19
  "delete_hint": "Per poter cancellare bisogna prima cliccare Seleziona",
20
20
  "delete_confirm": "Cancellare {n,plural, one{l'elemento} =8 =11 {gli # elementi} other{i # elementi}}?",
21
- "delete_completed": "Cancellazione: {n} riusciti",
21
+ "delete_completed": "Cancellazione{n,plural, one{ riuscita} other{: # riusciti}}",
22
22
  "delete_failed": ", {n,plural, one{# fallito} other{# falliti}}",
23
23
  "delete_select": "Seleziona qualcosa per poter cancellare",
24
24
  "Delete": "Cancella",
@@ -49,7 +49,7 @@
49
49
  "Full timestamp:": "Data e ora:",
50
50
  "Search was interrupted": "Ricerca interrotta",
51
51
  "Stop list": "Interrompi",
52
- "upload_starting": "Ora dovrebbe iniziare il download",
52
+ "download_starting": "Ora dovrebbe iniziare il download",
53
53
  "wrong_account": "L'account {u} non ha accesso a questa cartella, prova con un altro",
54
54
  "no_upload_here": "Non hai il permesso di uplodare in questa cartella",
55
55
  "Create folder": "Crea cartella",
@@ -149,6 +149,10 @@
149
149
  "Menu": "Menu",
150
150
  "clipboard": "Appunti ({content})",
151
151
  "to_clipboard_source_tooltip": "Vai alla cartella d'origine dei file negli appunti",
152
- "more_items": "{rest,plural,one{Un altro elemento} other{# altri elementi}}"
152
+ "more_items": "{n,plural,one{Un altro elemento} other{# altri elementi}}",
153
+ "Show details": "Mostra dettagli",
154
+ "upload_conflict": "esiste già",
155
+ "Logged in": "Benvenuto",
156
+ "Logged out": "Arrivederci"
153
157
  }
154
158
  }
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "全タイムスタンプ:",
52
52
  "Search was interrupted": "検索は中断されました",
53
53
  "Stop list": "リストを停止",
54
- "upload_starting": "ダウンロードはまもなく開始します",
54
+ "download_starting": "ダウンロードはまもなく開始します",
55
55
  "wrong_account": "アカウント {u}はアクセスできません 他のアカウントで試してください",
56
56
  "no_upload_here": "このフォルダにアップロードは許可されていません",
57
57
  "Create folder": "新しいフォルダ",
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "전체 타임스탬프:",
52
52
  "Search was interrupted": "검색이 중단되었습니다.",
53
53
  "Stop list": "중지 목록",
54
- "upload_starting": "이제 다운로드가 시작됩니다.",
54
+ "download_starting": "이제 다운로드가 시작됩니다.",
55
55
  "wrong_account": "계정 {u}은(는) 접근 권한이 없습니다. 다른 계정을 시도해보십시오.",
56
56
  "no_upload_here": "현재 폴더에 대한 업로드 권한이 없습니다.",
57
57
  "Create folder": "폴더 생성",
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "Volledige timestamp:",
52
52
  "Search was interrupted": "Zoeken is onderbroken",
53
53
  "Stop list": "Stop lijst",
54
- "upload_starting": "Uw download zou nu moeten starten",
54
+ "download_starting": "Uw download zou nu moeten starten",
55
55
  "wrong_account": "Account {u} heeft geen toegang, probeer een andere",
56
56
  "no_upload_here": "Geen upload toestemming voor de huidige map",
57
57
  "Create folder": "Creeer map",
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "Data e Hora:",
52
52
  "Search was interrupted": "Pesquisa foi interrompida",
53
53
  "Stop list": "Lista parada",
54
- "upload_starting": "Seu download deve começar agora",
54
+ "download_starting": "Seu download deve começar agora",
55
55
  "wrong_account": "A conta {u} não tem acesso, tente outra.",
56
56
  "no_upload_here": "Você não possui permissão para enviar arquivos na pasta atual",
57
57
  "Create folder": "Criar pasta",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Mefistofell, SanokKule",
3
- "version": 2.5,
4
- "hfs_version": "0.52.0",
3
+ "version": 2.6,
4
+ "hfs_version": "0.53.0",
5
5
  "translate": {
6
6
  "Select": "Выбор",
7
7
  "n_files": "{n,plural, one{# файл} few{# файла} many{# файлов}}",
@@ -129,7 +129,7 @@
129
129
  "showHelp_F_body": "полноэкранный режим",
130
130
  "Destination": "Назначение",
131
131
  "in_queue": "{n} в очереди",
132
- "enter_comment": "Комментарий для файла",
132
+ "enter_comment": "Комментарий для {name}",
133
133
  "Comment": "Комментировать",
134
134
  "upload_dd_hint": "Вы можете загрузить файлы перетащив их в список файлов",
135
135
  "Upload not available": "Загрузка недоступна",
@@ -138,7 +138,7 @@
138
138
  "good_bad": "{good} {good,plural, one{перемещён} other{перемещено}}, {bad} неуспешно",
139
139
  "after_cut": "Выбранное скопировано в буфер обмена.\nПерейдите в папку назначения для вставки.",
140
140
  "Cancel clipboard": "Отменить буфер обмена",
141
- "to_clipboard_source": "Вернуться в исходную папку",
141
+ "to_clipboard_source": "В папку",
142
142
  "Paste": "Вставить",
143
143
  "clipboard_list": "Элементы в буфере обмена:",
144
144
  "Close": "Закрыть",
@@ -159,9 +159,12 @@
159
159
  "Rename to avoid overwriting": "Переименовать для избежания перезаписи",
160
160
  "Overwrite existing files": "Перезаписать существующие файлы",
161
161
  "Menu": "Меню",
162
- "_PLUGINS SECTION": "",
163
- "_PLUGIN thumbnails": "",
164
- "Enable tiles mode": "Просмотр в режиме плиток",
165
- "thumbnails_switchBack": "Изменить вид можно в настройках"
162
+ "clipboard": "Буфер обмена ({content})",
163
+ "to_clipboard_source_tooltip": "Перейти в папку где находится содержимое из буфера обмена",
164
+ "more_items": "Ещё {rest} элементов",
165
+ "Show details": "Показать детали",
166
+ "upload_conflict": "уже существует",
167
+ "Logged in": "Вход выполнен",
168
+ "Logged out": "Выход выполнен"
166
169
  }
167
170
  }
@@ -53,7 +53,7 @@
53
53
  "Search was interrupted": "Претрага је прекинута",
54
54
  "Stop list": "Заустави",
55
55
  "Upload": "Отпреми",
56
- "upload_starting": "Отпремање је почело",
56
+ "download_starting": "Отпремање је почело",
57
57
  "wrong_account": "Корисник {u} нема приступ овом директоријуму",
58
58
  "no_upload_here": "Немогуће отпремање овде",
59
59
  "Create folder": "Креирај фолдер",
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "Dấu thời gian đầy đủ:",
52
52
  "Search was interrupted": "Tìm kiếm bị gián đoạn!",
53
53
  "Stop list": "DỪNG",
54
- "upload_starting": "Tải lên bây giờ sẽ bắt đầu",
54
+ "download_starting": "Tải lên bây giờ sẽ bắt đầu",
55
55
  "wrong_account": "Tài khoản {u} ko có quyền, chọn tk khác đi:)",
56
56
  "no_upload_here": "Không có quyền tải lên cho thư mục hiện tại",
57
57
  "Create folder": "Tạo thư mục",
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "完整的時間戳:",
52
52
  "Search was interrupted": "搜尋已中止",
53
53
  "Stop list": "停止",
54
- "upload_starting": "開始下載",
54
+ "download_starting": "開始下載",
55
55
  "wrong_account": "使用者 {u} 沒有存取權限,請更換使用者",
56
56
  "no_upload_here": "沒有上傳權限",
57
57
  "Create folder": "建立資料夾",
@@ -51,7 +51,7 @@
51
51
  "Full timestamp:": "完整的时间戳:",
52
52
  "Search was interrupted": "搜索已中断",
53
53
  "Stop list": "停止",
54
- "upload_starting": "开始下载",
54
+ "download_starting": "开始下载",
55
55
  "wrong_account": "用户 {u} 没有访问权限,请更换用户",
56
56
  "no_upload_here": "没有上传权限",
57
57
  "Create folder": "创建文件夹",
package/src/misc.js CHANGED
@@ -18,7 +18,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  return (mod && mod.__esModule) ? mod : { "default": mod };
19
19
  };
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.apiAssertTypes = exports.AsapStream = exports.asyncGeneratorToReadable = exports.same = exports.makeNetMatcher = exports.isLocalHost = exports.pattern2filter = void 0;
21
+ exports.deleteNode = exports.createStreamLimiter = exports.apiAssertTypes = exports.AsapStream = exports.asyncGeneratorToReadable = exports.same = exports.makeNetMatcher = exports.isLocalHost = exports.pattern2filter = void 0;
22
22
  const path_1 = require("path");
23
23
  const assert_1 = __importDefault(require("assert"));
24
24
  __exportStar(require("./util-http"), exports);
@@ -32,6 +32,10 @@ const apiMiddleware_1 = require("./apiMiddleware");
32
32
  const const_1 = require("./const");
33
33
  const cross_1 = require("./cross");
34
34
  const net_1 = require("net");
35
+ const vfs_1 = require("./vfs");
36
+ const events_1 = __importDefault(require("./events"));
37
+ const promises_1 = require("fs/promises");
38
+ const comments_1 = require("./comments");
35
39
  function pattern2filter(pattern) {
36
40
  const matcher = (0, cross_1.makeMatcher)(pattern.includes('*') ? pattern // if you specify *, we'll respect its position
37
41
  : pattern.split('|').map(x => `*${x}*`).join('|'));
@@ -122,3 +126,38 @@ function apiAssertTypes(paramsByType) {
122
126
  throw new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, 'bad ' + name);
123
127
  }
124
128
  exports.apiAssertTypes = apiAssertTypes;
129
+ function createStreamLimiter(limit) {
130
+ let got = 0;
131
+ return new stream_1.Transform({
132
+ transform(chunk, enc, cb) {
133
+ const left = limit - got;
134
+ got += chunk.length;
135
+ if (left > 0) {
136
+ this.push(chunk.length >= left ? chunk.slice(0, left) : chunk);
137
+ if (got >= limit)
138
+ this.end();
139
+ }
140
+ cb();
141
+ }
142
+ });
143
+ }
144
+ exports.createStreamLimiter = createStreamLimiter;
145
+ async function deleteNode(ctx, node, uri) {
146
+ const { source } = node;
147
+ if (!source)
148
+ return const_1.HTTP_METHOD_NOT_ALLOWED;
149
+ if ((0, vfs_1.statusCodeForMissingPerm)(node, 'can_delete', ctx))
150
+ return ctx.status;
151
+ try {
152
+ if (await events_1.default.emitAsync('deleting', { node, ctx }).isDefaultPrevented())
153
+ return null; // stop
154
+ ctx.logExtra(null, { target: decodeURI(uri) });
155
+ await (0, promises_1.rm)(source, { recursive: true });
156
+ void (0, comments_1.setCommentFor)(source, '');
157
+ return true;
158
+ }
159
+ catch (e) {
160
+ return e;
161
+ }
162
+ }
163
+ exports.deleteNode = deleteNode;
package/src/plugins.js CHANGED
@@ -44,6 +44,8 @@ const path_1 = require("path");
44
44
  const customHtml_1 = require("./customHtml");
45
45
  const kvstorage_1 = require("@rejetto/kvstorage");
46
46
  const first_1 = require("./first");
47
+ const frontEndApis_1 = require("./frontEndApis");
48
+ const index_1 = require("./index");
47
49
  exports.PATH = 'plugins';
48
50
  exports.DISABLING_SUFFIX = '-disabled';
49
51
  exports.STORAGE_FOLDER = 'storage';
@@ -131,9 +133,17 @@ async function initPlugin(pl, morePassedToInit) {
131
133
  log: console.log,
132
134
  getHfsConfig: config_1.getConfig,
133
135
  customApiCall,
136
+ notifyClient: frontEndApis_1.notifyClient,
134
137
  ...morePassedToInit
135
138
  })));
136
139
  }
140
+ const already = new Set();
141
+ function warnOnce(msg) {
142
+ if (already.has(msg))
143
+ return;
144
+ already.add(msg);
145
+ console.log('Warning: ' + msg);
146
+ }
137
147
  const pluginsMiddleware = async (ctx, next) => {
138
148
  var _a;
139
149
  const after = {};
@@ -149,7 +159,11 @@ const pluginsMiddleware = async (ctx, next) => {
149
159
  lastStatus = ctx.status;
150
160
  lastBody = ctx.body;
151
161
  }
152
- if (res === true)
162
+ if (res === true) { // true for legacy pre-0.53
163
+ ctx.stop();
164
+ warnOnce(`plugin ${id} is using deprecated API (return true on middleware) and may not work with future versions (check for an update to "${id}")`);
165
+ }
166
+ if (ctx.isStopped)
153
167
  console.debug("plugin blocked request", ctx.pluginBlockedRequest = id);
154
168
  if (typeof res === 'function')
155
169
  after[id] = res;
@@ -187,6 +201,10 @@ function printError(id, e) {
187
201
  console.log(`error middleware plugin ${id}: ${(e === null || e === void 0 ? void 0 : e.message) || e}`);
188
202
  console.debug(e);
189
203
  }
204
+ events_1.default.once('app', () => Object.assign(index_1.app.context, {
205
+ isStopped: false,
206
+ stop() { this.isStopped = true; }
207
+ }));
190
208
  class Plugin {
191
209
  constructor(id, folder, data, onUnload) {
192
210
  this.id = id;
@@ -264,7 +282,9 @@ const serverCode = (0, config_1.defineConfig)('server_code', '', async (script,
264
282
  const res = {};
265
283
  try {
266
284
  new Function('exports', script)(res); // parse
267
- return new Plugin(exports.SERVER_CODE_ID, '', await initPlugin(res), lodash_1.default.noop);
285
+ await initPlugin(res);
286
+ res.getCustomHtml = () => (0, misc_1.callable)(res.customHtml) || {};
287
+ return new Plugin(exports.SERVER_CODE_ID, '', res, lodash_1.default.noop);
268
288
  }
269
289
  catch (e) {
270
290
  return console.error(k + ':', e.message || String(e));
@@ -417,7 +437,12 @@ function watchPlugin(id, path) {
417
437
  log(...args) {
418
438
  console.log('plugin', id + ':', ...args);
419
439
  },
420
- getConfig: (cfgKey) => { var _a, _b, _c, _d, _e; return (_c = (_b = (_a = exports.pluginsConfig.get()) === null || _a === void 0 ? void 0 : _a[id]) === null || _b === void 0 ? void 0 : _b[cfgKey]) !== null && _c !== void 0 ? _c : (_e = (_d = pluginData.config) === null || _d === void 0 ? void 0 : _d[cfgKey]) === null || _e === void 0 ? void 0 : _e.defaultValue; },
440
+ getConfig(cfgKey) {
441
+ var _a, _b, _c, _d;
442
+ const cur = (_a = exports.pluginsConfig.get()) === null || _a === void 0 ? void 0 : _a[id];
443
+ return cfgKey ? (_b = cur === null || cur === void 0 ? void 0 : cur[cfgKey]) !== null && _b !== void 0 ? _b : (_d = (_c = pluginData.config) === null || _c === void 0 ? void 0 : _c[cfgKey]) === null || _d === void 0 ? void 0 : _d.defaultValue
444
+ : lodash_1.default.defaults(cur, (0, misc_1.objSameKeys)(pluginData.config, x => x.defaultValue));
445
+ },
421
446
  setConfig: (cfgKey, value) => setPluginConfig(id, { [cfgKey]: value }),
422
447
  subscribeConfig(cfgKey, cb) {
423
448
  let last = this.getConfig(cfgKey);
@@ -437,7 +462,7 @@ function watchPlugin(id, path) {
437
462
  });
438
463
  const folder = (0, path_1.dirname)(module);
439
464
  const { state, unwatch } = (0, customHtml_1.watchLoadCustomHtml)(folder);
440
- pluginData.customHtml = state;
465
+ pluginData.getCustomHtml = () => Object.assign(Object.fromEntries(state), (0, misc_1.callable)(pluginData.customHtml) || {});
441
466
  const plugin = new Plugin(id, folder, pluginData, async () => {
442
467
  unwatch();
443
468
  await Promise.allSettled(dbs.map(x => x.flush()));
@@ -88,6 +88,18 @@ const serveGuiAndSharedFiles = async (ctx, next) => {
88
88
  res(Promise.all(locks));
89
89
  }));
90
90
  }
91
+ if (ctx.method === 'DELETE') {
92
+ const res = await (0, misc_1.deleteNode)(ctx, node, ctx.path);
93
+ if (typeof res === 'number')
94
+ return ctx.status = res;
95
+ if (res instanceof Error) {
96
+ ctx.body = res.message || String(res);
97
+ return ctx.status = cross_const_1.HTTP_SERVER_ERROR;
98
+ }
99
+ if (res)
100
+ return ctx.status = cross_const_1.HTTP_OK;
101
+ return;
102
+ }
91
103
  const { get } = ctx.query;
92
104
  if (node.default && path.endsWith('/') && !get) // final/ needed on browser to make resource urls correctly with html pages
93
105
  node = (_a = await (0, vfs_1.urlToNode)(node.default, ctx, node)) !== null && _a !== void 0 ? _a : node;
@@ -129,7 +129,7 @@ async function treatIndex(ctx, filesUri, body) {
129
129
  prefixUrl: ctx.state.revProxyPath,
130
130
  dontOverwriteUploading: upload_1.dontOverwriteUploading.get(),
131
131
  forceTheme: (0, plugins_1.mapPlugins)(p => lodash_1.default.isString(p.isTheme) ? p.isTheme : undefined).find(Boolean),
132
- customHtml: lodash_1.default.omit(Object.fromEntries(customHtml_1.customHtmlState.sections), ['top', 'bottom']),
132
+ customHtml: lodash_1.default.omit((0, customHtml_1.getAllSections)(), ['top', 'bottom', 'htmlHead', 'style']),
133
133
  ...(0, misc_1.newObj)(misc_1.FRONTEND_OPTIONS, (v, k) => (0, config_1.getConfig)(k)),
134
134
  lang
135
135
  }, null, 4).replace(/<(\/script)/g, '<"+"$1') /*avoid breaking our script container*/}
package/src/update.js CHANGED
@@ -18,14 +18,14 @@ const config_1 = require("./config");
18
18
  const util_os_1 = require("./util-os");
19
19
  const first_1 = require("./first");
20
20
  const updateToBeta = (0, config_1.defineConfig)('update_to_beta', false);
21
- async function getUpdates() {
21
+ async function getUpdates(strict = false) {
22
22
  const stable = await (0, github_1.getRepoInfo)(const_1.HFS_REPO + '/releases/latest');
23
23
  const verStable = ver(stable);
24
24
  const ret = await getBetas();
25
25
  stable.isNewer = config_1.currentVersion.olderThan(stable.tag_name);
26
26
  if (stable.isNewer || const_1.RUNNING_BETA)
27
27
  ret.push(stable);
28
- return ret;
28
+ return ret.filter(x => !strict || x.isNewer);
29
29
  function ver(x) {
30
30
  return (0, config_1.versionToScalar)(x.name);
31
31
  }
@@ -73,7 +73,7 @@ async function update(tagOrUrl = '') {
73
73
  if (!updateSource) {
74
74
  if (/^\d/.test(tagOrUrl)) // work even if the tag is passed without the initial 'v' (useful for console commands)
75
75
  tagOrUrl = 'v' + tagOrUrl;
76
- const update = !tagOrUrl ? (await getUpdates())[0]
76
+ const update = !tagOrUrl ? (await getUpdates(true))[0]
77
77
  : await (0, github_1.getRepoInfo)(const_1.HFS_REPO + '/releases/tags/' + tagOrUrl).catch(e => {
78
78
  if (e.message === '404')
79
79
  console.error("version not found");
package/src/upload.js CHANGED
@@ -103,25 +103,23 @@ function uploadWriter(base, path, ctx) {
103
103
  const resuming = resume && resumable;
104
104
  if (!resuming)
105
105
  resume = 0;
106
- const writeStream = resuming ? fs_1.default.createWriteStream(resumable, { flags: 'r+', start: resume })
107
- : fs_1.default.createWriteStream(tempName);
106
+ const writeStream = (0, misc_1.createStreamLimiter)(reqSize !== null && reqSize !== void 0 ? reqSize : Infinity);
108
107
  if (resuming) {
109
108
  fs_1.default.rm(tempName, () => { });
110
109
  tempName = resumable;
111
110
  }
112
111
  cancelDeletion(tempName);
113
112
  ctx.state.uploadDestinationPath = tempName;
114
- trackProgress();
115
113
  // allow plugins to mess with the write-stream, because the read-stream can be complicated in case of multipart
116
114
  const obj = { ctx, writeStream };
117
115
  const resEvent = events_1.default.emit('uploadStart', obj);
118
- if (resEvent === null || resEvent === void 0 ? void 0 : resEvent.preventDefault())
119
- return writeStream.close(() => {
120
- try {
121
- fs_1.default.unlinkSync(writeStream.path);
122
- }
123
- catch (_a) { }
124
- });
116
+ if (resEvent === null || resEvent === void 0 ? void 0 : resEvent.isDefaultPrevented())
117
+ return;
118
+ const fileStream = resuming ? fs_1.default.createWriteStream(resumable, { flags: 'r+', start: resume })
119
+ : fs_1.default.createWriteStream(tempName);
120
+ writeStream.pipe(fileStream);
121
+ Object.assign(obj, { fileStream });
122
+ trackProgress();
125
123
  const lockMiddleware = (0, misc_1.pendingPromise)(); // outside we need to know when all operations stopped
126
124
  writeStream.once('close', async () => {
127
125
  try {
@@ -183,7 +181,7 @@ function uploadWriter(base, path, ctx) {
183
181
  return;
184
182
  const h = setInterval(() => {
185
183
  const now = Date.now();
186
- const got = writeStream.bytesWritten;
184
+ const got = fileStream.bytesWritten;
187
185
  const inSpeed = (0, throttler_1.roundSpeed)((got - lastGot) / (now - lastGotTime));
188
186
  lastGot = got;
189
187
  lastGotTime = now;
package/src/util-http.js CHANGED
@@ -25,13 +25,17 @@ async function httpWithBody(url, options) {
25
25
  exports.httpWithBody = httpWithBody;
26
26
  function httpStream(url, { body, jar, noRedirect, httpThrow, ...options } = {}) {
27
27
  return new Promise((resolve, reject) => {
28
- var _a, _b;
29
- var _c;
28
+ var _a, _b, _c;
29
+ var _d, _e;
30
30
  (_a = options.headers) !== null && _a !== void 0 ? _a : (options.headers = {});
31
31
  if (body) {
32
32
  options.method || (options.method = 'POST');
33
+ if (lodash_1.default.isPlainObject(body)) {
34
+ (_b = (_d = options.headers)['content-type']) !== null && _b !== void 0 ? _b : (_d['content-type'] = 'application/json');
35
+ body = JSON.stringify(body);
36
+ }
33
37
  if (!(body instanceof node_stream_1.Readable))
34
- (_b = (_c = options.headers)['Content-Length']) !== null && _b !== void 0 ? _b : (_c['Content-Length'] = Buffer.byteLength(body));
38
+ (_c = (_e = options.headers)['content-length']) !== null && _c !== void 0 ? _c : (_e['content-length'] = Buffer.byteLength(body));
35
39
  }
36
40
  if (jar)
37
41
  options.headers.cookie = lodash_1.default.map(jar, (v, k) => `${k}=${v}; `).join('')
File without changes