@jx3box/jx3box-ui 2.4.27 → 2.4.29

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.
@@ -322,6 +322,7 @@ export default {
322
322
  publish: "Post Comment",
323
323
  },
324
324
  commentWithReply: {
325
+ refreshAfterSubmitFailed: "Your reply was posted, but the list could not be refreshed. Refresh the page to view it; do not submit again.",
325
326
  defaultName: "Anonymous Wanderer",
326
327
  top: "Pinned",
327
328
  star: "Featured",
@@ -354,6 +355,7 @@ export default {
354
355
  zlpBy: { all: "All", default: "Expansion" },
355
356
  collection: { included: "This post has been included in the author's JX3 booklet" },
356
357
  comment: {
358
+ refreshAfterSubmitFailed: "Your comment was posted, but the list could not be refreshed. Refresh the page to view it; do not submit again.",
357
359
  sortMode: "Sort:",
358
360
  desc: "Newest first",
359
361
  asc: "Oldest first",
@@ -321,7 +321,15 @@ export default {
321
321
  secretTip: "Bình luận bí mật chỉ hiển thị với bạn và tác giả, và không thể thay đổi sau đó",
322
322
  publish: "Đăng bình luận",
323
323
  },
324
- commentWithReply: { defaultName: "Hiệp khách vô danh", top: "Ghim", star: "Nổi bật", secret: "Bí mật", commentSuccess: "Bình luận thành công!", deleteSuccess: "Xóa thành công!" },
324
+ commentWithReply: {
325
+ refreshAfterSubmitFailed: "Phản hồi đã được gửi nhưng không thể tải lại danh sách. Hãy tải lại trang để xem, không cần gửi lại.",
326
+ defaultName: "Hiệp khách vô danh",
327
+ top: "Ghim",
328
+ star: "Nổi bật",
329
+ secret: "Bí mật",
330
+ commentSuccess: "Bình luận thành công!",
331
+ deleteSuccess: "Xóa thành công!",
332
+ },
325
333
  commentUpload: {
326
334
  tip: "Tải tối đa {count} ảnh định dạng {types}, mỗi ảnh không quá {size} MB",
327
335
  tipWithVideo: "Tải tối đa {count} tệp đính kèm. Hỗ trợ: {types}. Ảnh không quá {imageSize} MB, video không quá {videoSize} MB",
@@ -347,6 +355,7 @@ export default {
347
355
  zlpBy: { all: "Tất cả", default: "Bản mở rộng" },
348
356
  collection: { included: "Tác phẩm này đã được đưa vào sổ tay JX3 của tác giả" },
349
357
  comment: {
358
+ refreshAfterSubmitFailed: "Bình luận đã được gửi nhưng không thể tải lại danh sách. Hãy tải lại trang để xem, không cần gửi lại.",
350
359
  sortMode: "Sắp xếp:",
351
360
  desc: "Mới nhất trước",
352
361
  asc: "Cũ nhất trước",
@@ -380,6 +380,7 @@ export default {
380
380
  publish: "发表评论",
381
381
  },
382
382
  commentWithReply: {
383
+ refreshAfterSubmitFailed: "回复已提交,列表刷新失败,请刷新页面查看,无需重复提交。",
383
384
  defaultName: "人字榜800线无名小侠",
384
385
  top: "置顶",
385
386
  star: "精华",
@@ -459,6 +460,7 @@ export default {
459
460
  included: "该作品已被收录至作者的剑三小册",
460
461
  },
461
462
  comment: {
463
+ refreshAfterSubmitFailed: "评论已提交,列表刷新失败,请刷新页面查看,无需重复提交。",
462
464
  sortMode: "排序模式:",
463
465
  desc: "最后靠前",
464
466
  asc: "最早靠前",
@@ -321,7 +321,15 @@ export default {
321
321
  secretTip: "勾選悄悄話後僅作者和你可見,且不可再變更狀態",
322
322
  publish: "發表評論",
323
323
  },
324
- commentWithReply: { defaultName: "無名小俠", top: "置頂", star: "精華", secret: "悄悄話", commentSuccess: "評論成功!", deleteSuccess: "刪除成功!" },
324
+ commentWithReply: {
325
+ refreshAfterSubmitFailed: "回覆已提交,列表重新整理失敗,請重新整理頁面查看,無需重複提交。",
326
+ defaultName: "無名小俠",
327
+ top: "置頂",
328
+ star: "精華",
329
+ secret: "悄悄話",
330
+ commentSuccess: "評論成功!",
331
+ deleteSuccess: "刪除成功!",
332
+ },
325
333
  commentUpload: {
326
334
  tip: "最多上傳 {count} 張 {types} 格式圖片,單張圖片不能超過 {size} MB",
327
335
  tipWithVideo: "最多上傳 {count} 個附件,支援 {types},圖片不超過 {imageSize} MB,影片不超過 {videoSize} MB",
@@ -347,6 +355,7 @@ export default {
347
355
  zlpBy: { all: "全部", default: "資料片" },
348
356
  collection: { included: "該作品已被收錄至作者的劍三小冊" },
349
357
  comment: {
358
+ refreshAfterSubmitFailed: "評論已提交,列表重新整理失敗,請重新整理頁面查看,無需重複提交。",
350
359
  sortMode: "排序模式:",
351
360
  desc: "最後靠前",
352
361
  asc: "最早靠前",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jx3box/jx3box-ui",
3
- "version": "2.4.27",
3
+ "version": "2.4.29",
4
4
  "description": "JX3BOX Vue3 UI",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -57,13 +57,12 @@ export async function setOrderMode(val) {
57
57
  }
58
58
  }
59
59
 
60
- export const GET = function (url, queryParams) {
61
- return $
62
- .get(url, {
63
- params: queryParams,
64
- })
60
+ export const GET = function (url, queryParams, options = {}) {
61
+ return $.get(url, {
62
+ params: queryParams,
63
+ })
65
64
  .then((res) => res.data)
66
- .catch((err) => __handleError(err));
65
+ .catch((err) => __handleError(err, options));
67
66
  };
68
67
 
69
68
  const postRecord = {};
@@ -95,11 +94,9 @@ export const POST = function (url, queryParams, body) {
95
94
  count: 0,
96
95
  };
97
96
  }
98
- return $
99
- .post(url, body, {
100
- params: queryParams,
101
- validateStatus: (status) => status === 200,
102
- })
97
+ return $.post(url, body, {
98
+ params: queryParams,
99
+ })
103
100
  .then((res) => res.data)
104
101
  .catch((err) => __handleError(err));
105
102
  };
@@ -121,10 +118,10 @@ export const DELETE = function (url, queryParams) {
121
118
  .catch((err) => __handleError(err));
122
119
  };
123
120
 
124
- function __handleError(err) {
121
+ function __handleError(err, options = {}) {
125
122
  const status = err?.response?.status;
126
123
  const statusText = err?.response?.statusText || "Request Error";
127
- const message = err?.response?.data?.msg || err?.response?.data || "";
124
+ const message = options.errorMessage || err?.response?.data?.msg || err?.response?.data || "";
128
125
  switch (status) {
129
126
  case 401:
130
127
  case 403:
@@ -142,8 +139,8 @@ function __handleError(err) {
142
139
  });
143
140
  break;
144
141
  default:
145
- Notification.error({
146
- title: "系统:" + statusText,
142
+ Notification[options.errorMessage ? "warning" : "error"]({
143
+ title: options.errorMessage ? "" : "系统:" + statusText,
147
144
  message: message || "系统错误,请稍后重试!",
148
145
  duration: 3000,
149
146
  position: "bottom-right",
@@ -340,7 +340,7 @@ export default {
340
340
  return count > 0 ? count : "";
341
341
  },
342
342
  attachmentUploadFinish(data) {
343
- this.disableSubmitBtn = false;
343
+ this.disableSubmitBtn = true;
344
344
  const submittedContent = this.newComment.content;
345
345
  this.$emit(
346
346
  "addNewReply",
@@ -348,7 +348,10 @@ export default {
348
348
  content: submittedContent,
349
349
  attachmentList: data,
350
350
  },
351
- () => this.clearSubmittedContent(submittedContent)
351
+ () => this.clearSubmittedContent(submittedContent),
352
+ () => {
353
+ this.disableSubmitBtn = false;
354
+ }
352
355
  );
353
356
  this.showUploader = false;
354
357
  },
@@ -364,6 +367,7 @@ export default {
364
367
  },
365
368
 
366
369
  submit() {
370
+ if (this.disableSubmitBtn) return;
367
371
  this.disableSubmitBtn = true;
368
372
  if (this.$refs.uploader) {
369
373
  this.$refs.uploader.upload();
@@ -97,6 +97,7 @@ export default {
97
97
  },
98
98
  methods: {
99
99
  onSubmit() {
100
+ if (this.disableSubmitBtn) return;
100
101
  this.disableSubmitBtn = true;
101
102
  if (this.$refs.uploader) {
102
103
  this.$refs.uploader.upload();
@@ -105,14 +106,24 @@ export default {
105
106
  }
106
107
  },
107
108
  onQuickReply(item) {
108
- this.$emit("submit", {
109
- content: item,
110
- attachmentList: [],
111
- is_template: 1,
112
- });
109
+ if (this.disableSubmitBtn) return;
110
+ this.disableSubmitBtn = true;
111
+ this.$emit(
112
+ "submit",
113
+ {
114
+ content: item,
115
+ attachmentList: [],
116
+ is_template: 1,
117
+ },
118
+ undefined,
119
+ () => {
120
+ this.disableSubmitBtn = false;
121
+ }
122
+ );
113
123
  },
114
124
  // 文件上传完成后,进行数据提交
115
125
  attachmentUploadFinish(data) {
126
+ this.disableSubmitBtn = true;
116
127
  const submittedContent = this.newComment.content;
117
128
  this.$emit(
118
129
  "submit",
@@ -121,11 +132,12 @@ export default {
121
132
  is_secret: this.is_secret ? 1 : 0,
122
133
  attachmentList: data,
123
134
  },
124
- () => this.clearSubmittedContent(submittedContent)
135
+ () => this.clearSubmittedContent(submittedContent),
136
+ () => {
137
+ this.disableSubmitBtn = false;
138
+ }
125
139
  );
126
140
  this.showUploader = false;
127
-
128
- this.disableSubmitBtn = false;
129
141
  },
130
142
  clearSubmittedContent(submittedContent) {
131
143
  // 请求成功后才清空;若等待响应期间用户已修改内容,则保留新草稿。
@@ -214,8 +214,8 @@ export default {
214
214
  setWhiteComment(white) {
215
215
  this.$emit("setWhiteComment", this.item.id, white);
216
216
  },
217
- addNewReply(data, clearSubmittedContent) {
218
- POST(`${this.baseApi}/comment/${this.item.id}/reply`, null, data)
217
+ addNewReply(data, clearSubmittedContent, onSettled) {
218
+ return POST(`${this.baseApi}/comment/${this.item.id}/reply`, null, data)
219
219
  .then(() => {
220
220
  this.$notify({
221
221
  title: "",
@@ -227,9 +227,12 @@ export default {
227
227
  if (typeof clearSubmittedContent === "function") {
228
228
  clearSubmittedContent();
229
229
  }
230
- this.loadReplyList(this.pager.index);
230
+ return this.loadReplyList(this.pager.index, undefined, true);
231
231
  })
232
- .catch(() => {});
232
+ .catch(() => {})
233
+ .finally(() => {
234
+ if (typeof onSettled === "function") onSettled();
235
+ });
233
236
  },
234
237
  deleteReply(id) {
235
238
  DELETE(`${this.baseApi}/comment/${id}`)
@@ -248,8 +251,15 @@ export default {
248
251
  gotoReplyListIndex(index) {
249
252
  this.loadReplyList(index, 6);
250
253
  },
251
- loadReplyList(index, pageSize) {
252
- GET(`${this.baseApi}/comment/${this.item.id}/reply/page/${index}?pageSize=${pageSize}`)
254
+ loadReplyList(index, pageSize, afterSubmit = false) {
255
+ return GET(`${this.baseApi}/comment/${this.item.id}/reply/page/${index}?pageSize=${pageSize}`, null, {
256
+ errorMessage: afterSubmit
257
+ ? this.$jx3boxT(
258
+ "jx3boxUi.commentWithReply.refreshAfterSubmitFailed",
259
+ "回复已提交,列表刷新失败,请刷新页面查看,无需重复提交。"
260
+ )
261
+ : undefined,
262
+ })
253
263
  .then((resp) => {
254
264
  if (index == 1 && pageSize == 3) {
255
265
  // eslint-disable-next-line vue/no-mutating-props
@@ -89,6 +89,7 @@ export default {
89
89
  },
90
90
  methods: {
91
91
  submitReply() {
92
+ if (this.disableSubmitBtn) return;
92
93
  this.disableSubmitBtn = true;
93
94
  if (this.$refs.uploader) {
94
95
  this.$refs.uploader.upload();
@@ -100,7 +101,7 @@ export default {
100
101
  this.$emit("hideForm");
101
102
  },
102
103
  attachmentUploadFinish(data) {
103
- this.disableSubmitBtn = false;
104
+ this.disableSubmitBtn = true;
104
105
  const submittedContent = this.content;
105
106
  this.$emit(
106
107
  "doReply",
@@ -108,7 +109,10 @@ export default {
108
109
  content: submittedContent,
109
110
  attachmentList: data,
110
111
  },
111
- () => this.clearSubmittedContent(submittedContent)
112
+ () => this.clearSubmittedContent(submittedContent),
113
+ () => {
114
+ this.disableSubmitBtn = false;
115
+ }
112
116
  );
113
117
  this.showUploader = false;
114
118
  },
@@ -95,15 +95,20 @@ export default {
95
95
  setLikeComment(setLike) {
96
96
  this.$emit("setLikeComment", this.reply.id, setLike);
97
97
  },
98
- doReply(replyData, clearSubmittedContent) {
98
+ doReply(replyData, clearSubmittedContent, onSettled) {
99
99
  replyData.replyForUID = this.reply.userId;
100
100
  replyData.replyForCommentId = this.reply.id;
101
- this.$emit("addReply", replyData, () => {
102
- const contentCleared = clearSubmittedContent?.();
103
- if (contentCleared !== false) {
104
- this.showReplyForReplyFrom = false;
105
- }
106
- });
101
+ this.$emit(
102
+ "addReply",
103
+ replyData,
104
+ () => {
105
+ const contentCleared = clearSubmittedContent?.();
106
+ if (contentCleared !== false) {
107
+ this.showReplyForReplyFrom = false;
108
+ }
109
+ },
110
+ onSettled
111
+ );
107
112
  },
108
113
  },
109
114
  };
@@ -95,8 +95,8 @@ export default {
95
95
  setLikeComment(id, isLike) {
96
96
  this.$emit("setLikeComment", id, isLike);
97
97
  },
98
- addReply(data, clearSubmittedContent) {
99
- this.$emit("addNewReply", data, clearSubmittedContent);
98
+ addReply(data, clearSubmittedContent, onSettled) {
99
+ this.$emit("addNewReply", data, clearSubmittedContent, onSettled);
100
100
  },
101
101
  },
102
102
  };
@@ -11,7 +11,7 @@
11
11
  }}</el-button
12
12
  >
13
13
  </div>
14
- <AuthorLink class="u-block u-links" :data="data" />
14
+ <!-- <AuthorLink class="u-block u-links" :data="data" /> -->
15
15
  <AuthorRole class="u-block u-roles" :data="data" />
16
16
  <AuthorMedals class="u-block u-trophy" :medals="activeMedals" />
17
17
  <!-- <AuthorTeams class="u-block u-teams" :uid="uid" /> -->
@@ -24,7 +24,7 @@
24
24
 
25
25
  <script>
26
26
  import AuthorInfo from "../author/AuthorInfo.vue";
27
- import AuthorLink from "../author/AuthorLink.vue";
27
+ // import AuthorLink from "../author/AuthorLink.vue";
28
28
  // import AuthorFollow from "../author/AuthorFollow.vue";
29
29
  // import AuthorGift from "../author/AuthorGift.vue";
30
30
  // import AuthorFans from "../author/AuthorFans.vue";
@@ -161,7 +161,7 @@ export default {
161
161
  },
162
162
  components: {
163
163
  AuthorInfo,
164
- AuthorLink,
164
+ // AuthorLink,
165
165
  // AuthorFollow,
166
166
  // AuthorGift,
167
167
  AuthorRole,
@@ -232,14 +232,21 @@ export default {
232
232
  })
233
233
  .catch(() => {});
234
234
  },
235
- reloadCommentList(index) {
235
+ reloadCommentList(index, afterSubmit = false) {
236
236
  this.loading = true;
237
237
  let orderQuery = {};
238
238
  if (this.isDesc === "DESC") {
239
239
  orderQuery["desc"] = true;
240
240
  }
241
241
  orderQuery["orderby_likes"] = this.orderByLikes;
242
- GET(`${this.baseAPI}/comment/page/${index}`, orderQuery)
242
+ return GET(`${this.baseAPI}/comment/page/${index}`, orderQuery, {
243
+ errorMessage: afterSubmit
244
+ ? this.$jx3boxT(
245
+ "jx3boxUi.comment.refreshAfterSubmitFailed",
246
+ "评论已提交,列表刷新失败,请刷新页面查看,无需重复提交。"
247
+ )
248
+ : undefined,
249
+ })
243
250
  .then((resp) => {
244
251
  this.commentList = resp.data || [];
245
252
  this.pager = resp.page;
@@ -253,8 +260,8 @@ export default {
253
260
  handleCurrentChange(gotoIndex) {
254
261
  this.reloadCommentList(gotoIndex);
255
262
  },
256
- userSubmitInputForm(data, clearSubmittedContent) {
257
- POST(`${this.baseAPI}/comment`, null, data)
263
+ userSubmitInputForm(data, clearSubmittedContent, onSettled) {
264
+ return POST(`${this.baseAPI}/comment`, null, data)
258
265
  .then(() => {
259
266
  this.$notify({
260
267
  title: "",
@@ -268,10 +275,13 @@ export default {
268
275
  }
269
276
  // 位于第一页时才去更新数据,否则没必要,等用户自己触发
270
277
  if (this.pager.index == 1) {
271
- this.reloadCommentList(this.pager.index);
278
+ return this.reloadCommentList(this.pager.index, true);
272
279
  }
273
280
  })
274
- .catch(() => {});
281
+ .catch(() => {})
282
+ .finally(() => {
283
+ if (typeof onSettled === "function") onSettled();
284
+ });
275
285
  },
276
286
  profileLink: function (uid) {
277
287
  return authorLink(uid);
@@ -2,6 +2,7 @@ import { $cms } from "@jx3box/jx3box-common/js/api";
2
2
  import { isMiniProgram, isApp } from "@jx3box/jx3box-common/js/utils";
3
3
  import User from "@jx3box/jx3box-common/js/user";
4
4
  import { applyJx3boxClientStatRules } from "./client-stat-business";
5
+ import { DEFAULT_BLOCK_STORAGE_KEY } from "./traffic-analytics";
5
6
  import packageInfo from "../../package.json";
6
7
 
7
8
  const INSTANCE_ID_KEY = "jx3box:device_id";
@@ -15,8 +16,8 @@ const STARTUP_DELAY_MAX = 15 * 1000;
15
16
 
16
17
  let reportTask = null;
17
18
  let scheduledTimer = null;
18
- let trafficPermission = null;
19
- let trafficPermissionCheckedAt = 0;
19
+ let pendingIdentity = null;
20
+ const PERMISSION_KEY = "jx3box:client-stat-permission:v1";
20
21
  const TRAFFIC_PERMISSION_MAX_AGE = 5 * 60 * 1000;
21
22
 
22
23
  function compactPayload(payload) {
@@ -222,11 +223,28 @@ function getReportSignature() {
222
223
  }
223
224
 
224
225
  export async function reportClientStat({ force = false } = {}) {
225
- if (reportTask) return reportTask;
226
+ const today = chinaDate();
227
+ const signature = getReportSignature();
228
+ const instance = ensureClientInstanceId();
229
+ const identity = JSON.stringify([today, signature, instance]);
230
+ if (reportTask) {
231
+ if (identity === pendingIdentity) return reportTask;
232
+ await reportTask.catch(() => null);
233
+ return reportClientStat({ force });
234
+ }
226
235
 
236
+ pendingIdentity = identity;
227
237
  reportTask = (async () => {
228
- const today = chinaDate();
229
- const signature = getReportSignature();
238
+ let cached;
239
+ try {
240
+ cached = JSON.parse(localStorage.getItem(PERMISSION_KEY));
241
+ } catch (_) { /* 旧值损坏时重新向服务端确认。 */ }
242
+ if (cached?.identity === identity && cached.until > Date.now()) {
243
+ if (!cached.gate) return { reported: false, reason: "cooldown" };
244
+ if (cached.gate.traffic_allowed === false || !localStorage.getItem(DEFAULT_BLOCK_STORAGE_KEY)) {
245
+ return { reported: false, data: cached.gate };
246
+ }
247
+ }
230
248
  if (
231
249
  !force &&
232
250
  localStorage.getItem(REPORT_DATE_KEY) === today &&
@@ -235,14 +253,24 @@ export async function reportClientStat({ force = false } = {}) {
235
253
  return { reported: false, reason: "already_reported" };
236
254
  }
237
255
 
238
- const payload = buildClientStatPayload(ensureClientInstanceId());
239
- const response = await $cms({ mute: true }).post("/api/cms/system/stat/heartbeat", payload, {
240
- timeout: 10000,
241
- skipForbiddenSessionClear: true,
242
- });
256
+ const payload = buildClientStatPayload(instance);
257
+ let data;
258
+ try {
259
+ const response = await $cms({ mute: true }).post("/api/cms/system/stat/heartbeat", payload, {
260
+ timeout: 10000,
261
+ skipForbiddenSessionClear: true,
262
+ });
263
+ data = response?.data?.data;
264
+ } finally {
265
+ const gate = typeof data?.traffic_allowed === "boolean"
266
+ ? { traffic_allowed: data.traffic_allowed, blocked: data.blocked || null }
267
+ : null;
268
+ const ttl = gate ? TRAFFIC_PERMISSION_MAX_AGE : 60000 + Math.floor(Math.random() * 60000);
269
+ localStorage.setItem(PERMISSION_KEY, JSON.stringify({ identity, gate, until: Date.now() + ttl }));
270
+ }
243
271
  localStorage.setItem(REPORT_DATE_KEY, today);
244
272
  localStorage.setItem(REPORT_SIGNATURE_KEY, signature);
245
- return { reported: true, data: response?.data?.data || null, payload };
273
+ return { reported: true, data: data || null, payload };
246
274
  })().finally(() => {
247
275
  reportTask = null;
248
276
  });
@@ -250,22 +278,15 @@ export async function reportClientStat({ force = false } = {}) {
250
278
  return reportTask;
251
279
  }
252
280
 
253
- export async function resolveClientTrafficPermission({ force = false } = {}) {
254
- if (!force && trafficPermission && Date.now() - trafficPermissionCheckedAt < TRAFFIC_PERMISSION_MAX_AGE) {
255
- return trafficPermission;
256
- }
281
+ export async function resolveClientTrafficPermission() {
257
282
  try {
258
- const result = await reportClientStat({ force: true });
259
- const data = result?.data;
260
- if (data && typeof data.traffic_allowed === "boolean") {
261
- trafficPermission = data;
262
- trafficPermissionCheckedAt = Date.now();
263
- return data;
264
- }
265
- } catch (error) {
266
- // Traffic remains fail-closed when heartbeat cannot confirm permission.
283
+ let result = await reportClientStat({ force: true });
284
+ // 并发的普通日检可能只返回“今天已报”;此时仍需取得显式许可。
285
+ if (result.reason === "already_reported") result = await reportClientStat({ force: true });
286
+ return typeof result.data?.traffic_allowed === "boolean" ? result.data : null;
287
+ } catch (_) {
288
+ return null;
267
289
  }
268
- return null;
269
290
  }
270
291
 
271
292
  function isLocalhost() {
@@ -0,0 +1,335 @@
1
+ const assert = require("node:assert/strict");
2
+ const fs = require("node:fs");
3
+ const path = require("node:path");
4
+ const vm = require("node:vm");
5
+ const { test } = require("node:test");
6
+ const axios = require("axios");
7
+
8
+ function createService(status, data) {
9
+ const notifications = [];
10
+ // Exercise the service's actual Axios status validation without a live write.
11
+ const client = axios.create({
12
+ adapter: async (config) => {
13
+ const response = { status, statusText: String(status), data, config, headers: {} };
14
+ if (!config.validateStatus || config.validateStatus(status)) return response;
15
+ throw new axios.AxiosError("Request failed", undefined, config, undefined, response);
16
+ },
17
+ });
18
+ const source = fs
19
+ .readFileSync(path.join(__dirname, "../service/comment.js"), "utf8")
20
+ .replace(/^import .*;\n/gm, "")
21
+ .replace(/export /g, "");
22
+ const context = vm.createContext({
23
+ JX3BOX: { __Links: { account: { login: "/login", email_verify: "/verify" } } },
24
+ Notification: {
25
+ warning: (value) => notifications.push({ ...value, type: "warning" }),
26
+ error: (value) => notifications.push({ ...value, type: "error" }),
27
+ },
28
+ $next: () => client,
29
+ window: { location: { href: "/article" } },
30
+ });
31
+ vm.runInContext(source + "\nglobalThis.submit = POST; globalThis.get = GET;", context);
32
+ return { submit: context.submit, get: context.get, notifications };
33
+ }
34
+
35
+ for (const endpoint of ["/comment", "/comment/1/reply"]) {
36
+ for (const status of [200, 201, 202, 204]) {
37
+ test(`${endpoint} accepts HTTP ${status}`, async () => {
38
+ const data = status === 204 ? "" : { id: 123 };
39
+ const { submit, notifications } = createService(status, data);
40
+ assert.deepEqual(await submit(endpoint, null, { content: "test" }), data);
41
+ assert.equal(notifications.length, 0);
42
+ });
43
+ }
44
+ for (const status of [400, 401, 403, 406, 423, 500]) {
45
+ test(`${endpoint} rejects HTTP ${status}`, async () => {
46
+ const { submit } = createService(status, { msg: "failed" });
47
+ await assert.rejects(submit(endpoint, null, { content: "test" }), (err) => err.response.status === status);
48
+ });
49
+ }
50
+ }
51
+
52
+ // Load the real Options API methods, replacing only external imports.
53
+ function loadMethods(file, overrides = {}) {
54
+ const babel = require("@babel/core");
55
+ const bindings = {};
56
+ const source = fs.readFileSync(path.join(__dirname, "..", file), "utf8").match(/<script>([\s\S]*?)<\/script>/)[1];
57
+ const result = babel.transformSync(source, {
58
+ configFile: false,
59
+ babelrc: false,
60
+ plugins: [
61
+ ({ types: t }) => ({
62
+ visitor: {
63
+ ImportDeclaration(node) {
64
+ for (const specifier of node.node.specifiers) bindings[specifier.local.name] = {};
65
+ node.remove();
66
+ },
67
+ ExportDefaultDeclaration(node) {
68
+ node.replaceWith(
69
+ t.expressionStatement(
70
+ t.assignmentExpression(
71
+ "=",
72
+ t.memberExpression(t.identifier("globalThis"), t.identifier("component")),
73
+ node.node.declaration
74
+ )
75
+ )
76
+ );
77
+ },
78
+ },
79
+ }),
80
+ ],
81
+ });
82
+ const context = vm.createContext({ ...bindings, ...overrides });
83
+ vm.runInContext(result.code, context);
84
+ return context.component.methods;
85
+ }
86
+
87
+ for (const data of [{ code: 0 }, { code: "0" }, { code: 200 }, { id: 123 }, null, ""]) {
88
+ test(`successful response body ${JSON.stringify(data)} is passed through`, async () => {
89
+ const { submit, notifications } = createService(200, data);
90
+ assert.deepEqual(await submit("/comment", null, {}), data);
91
+ assert.equal(notifications.length, 0);
92
+ });
93
+ }
94
+
95
+ for (const [file, method, refresh] of [
96
+ ["src/single/Comment.vue", "userSubmitInputForm", "reloadCommentList"],
97
+ ["src/comment/CommentWithReply.vue", "addNewReply", "loadReplyList"],
98
+ ]) {
99
+ for (const succeeds of [true, false]) {
100
+ test(`${file}: ${succeeds ? "success clears draft and refreshes" : "failure preserves draft"}`, async () => {
101
+ const notifications = [];
102
+ let cleared = 0;
103
+ let refreshed = 0;
104
+ const methods = loadMethods(file, {
105
+ POST: () => (succeeds ? Promise.resolve({ code: 200 }) : Promise.reject(new Error("failed"))),
106
+ });
107
+ const instance = {
108
+ baseAPI: "/api",
109
+ baseApi: "/api",
110
+ item: { id: 1 },
111
+ pager: { index: 1 },
112
+ $notify: (value) => notifications.push(value),
113
+ $jx3boxT: (key, fallback) => fallback,
114
+ [refresh]: () => {
115
+ refreshed++;
116
+ },
117
+ };
118
+ methods[method].call(instance, { content: "draft" }, () => {
119
+ cleared++;
120
+ });
121
+ await new Promise((resolve) => setImmediate(resolve));
122
+ assert.equal(cleared, Number(succeeds));
123
+ assert.equal(refreshed, Number(succeeds));
124
+ assert.equal(notifications.length, Number(succeeds));
125
+ if (succeeds) assert.equal(notifications[0].type, "success");
126
+ });
127
+ }
128
+ }
129
+
130
+ for (const file of ["CommentInputForm", "CommentContent", "ReplyForReply"]) {
131
+ test(`${file}: upload completion waits for submit success and preserves edited draft`, () => {
132
+ const methods = loadMethods(`src/comment/${file}.vue`);
133
+ let clear;
134
+ const instance = {
135
+ ...methods,
136
+ newComment: { content: "draft" },
137
+ content: "draft",
138
+ $emit: (event, payload, callback) => {
139
+ clear = callback;
140
+ },
141
+ };
142
+ methods.attachmentUploadFinish.call(instance, ["https://example.com/image.png"]);
143
+ const read = () => (file === "ReplyForReply" ? instance.content : instance.newComment.content);
144
+ assert.equal(read(), "draft");
145
+ if (file === "ReplyForReply") instance.content = "new draft";
146
+ else instance.newComment.content = "new draft";
147
+ assert.equal(clear(), false);
148
+ assert.equal(read(), "new draft");
149
+ methods.attachmentUploadFinish.call(instance, []);
150
+ assert.equal(clear(), true);
151
+ assert.equal(read(), "");
152
+ });
153
+ }
154
+
155
+ test("nested reply forwards success callback through ReplyItem and ReplyList", () => {
156
+ const itemMethods = loadMethods("src/comment/ReplyItem.vue");
157
+ const listMethods = loadMethods("src/comment/ReplyList.vue");
158
+ let onSuccess;
159
+ const instance = {
160
+ reply: { id: 2, userId: 3 },
161
+ showReplyForReplyFrom: true,
162
+ $emit: (event, data, callback) =>
163
+ listMethods.addReply.call(
164
+ {
165
+ $emit: (name, payload, forwarded) => {
166
+ assert.equal(payload.replyForUID, 3);
167
+ assert.equal(payload.replyForCommentId, 2);
168
+ onSuccess = forwarded;
169
+ },
170
+ },
171
+ data,
172
+ callback
173
+ ),
174
+ };
175
+ itemMethods.doReply.call(instance, {}, () => false);
176
+ assert.equal(instance.showReplyForReplyFrom, true);
177
+ onSuccess();
178
+ assert.equal(instance.showReplyForReplyFrom, true);
179
+ itemMethods.doReply.call(instance, {}, () => true);
180
+ onSuccess();
181
+ assert.equal(instance.showReplyForReplyFrom, false);
182
+ });
183
+
184
+ for (const [file, method, uploadError] of [
185
+ ["CommentInputForm", "onSubmit", "attachmentUploadError"],
186
+ ["CommentContent", "submit", "attachmentUplodError"],
187
+ ["ReplyForReply", "submitReply", "attachmentUploadError"],
188
+ ]) {
189
+ test(`${file}: blocks duplicate submissions until settled and unlocks on upload failure`, () => {
190
+ const methods = loadMethods(`src/comment/${file}.vue`);
191
+ let submits = 0;
192
+ let settle;
193
+ const instance = {
194
+ ...methods,
195
+ $refs: {},
196
+ disableSubmitBtn: false,
197
+ newComment: { content: "draft" },
198
+ content: "draft",
199
+ $emit: (name, data, clear, onSettled) => {
200
+ submits++;
201
+ settle = onSettled;
202
+ },
203
+ };
204
+ instance[method]();
205
+ assert.equal(instance.disableSubmitBtn, true);
206
+ instance[method]();
207
+ assert.equal(submits, 1);
208
+ settle();
209
+ assert.equal(instance.disableSubmitBtn, false);
210
+ instance[method]();
211
+ assert.equal(submits, 2);
212
+ instance[uploadError]();
213
+ assert.equal(instance.disableSubmitBtn, false);
214
+ });
215
+ }
216
+
217
+ test("quick reply shares the submission lock and releases it on settlement", () => {
218
+ const methods = loadMethods("src/comment/CommentInputForm.vue");
219
+ let submits = 0;
220
+ let settle;
221
+ const instance = {
222
+ ...methods,
223
+ disableSubmitBtn: false,
224
+ $emit: (event, data, clear, callback) => {
225
+ submits++;
226
+ settle = callback;
227
+ assert.equal(clear, undefined);
228
+ },
229
+ };
230
+ instance.onQuickReply("hello");
231
+ instance.onQuickReply("hello");
232
+ instance.onSubmit();
233
+ assert.equal(submits, 1);
234
+ settle();
235
+ assert.equal(instance.disableSubmitBtn, false);
236
+ });
237
+
238
+ for (const [file, method, refresh] of [
239
+ ["src/single/Comment.vue", "userSubmitInputForm", "reloadCommentList"],
240
+ ["src/comment/CommentWithReply.vue", "addNewReply", "loadReplyList"],
241
+ ]) {
242
+ for (const succeeds of [true, false]) {
243
+ test(`${file}: submission settlement always unlocks, success=${succeeds}`, async () => {
244
+ let resolve;
245
+ let reject;
246
+ let settled = 0;
247
+ const pending = new Promise((res, rej) => {
248
+ resolve = res;
249
+ reject = rej;
250
+ });
251
+ const methods = loadMethods(file, { POST: () => pending });
252
+ const instance = {
253
+ baseAPI: "/api",
254
+ baseApi: "/api",
255
+ item: { id: 1 },
256
+ pager: { index: 1 },
257
+ $notify() {},
258
+ $jx3boxT: (key, text) => text,
259
+ [refresh]: () => Promise.resolve(),
260
+ };
261
+ const request = methods[method].call(instance, {}, undefined, () => {
262
+ settled++;
263
+ });
264
+ assert.equal(settled, 0);
265
+ if (succeeds) resolve({});
266
+ else reject(new Error("network failed"));
267
+ await request;
268
+ assert.equal(settled, 1);
269
+ });
270
+ }
271
+ test(`${file}: POST succeeds and GET fails with a contextual warning only`, async () => {
272
+ const service = createService(500, { msg: "server error" });
273
+ const notifications = [];
274
+ let cleared = 0;
275
+ let settled = 0;
276
+ const methods = loadMethods(file, { POST: () => Promise.resolve({}), GET: service.get });
277
+ const instance = {
278
+ ...methods,
279
+ baseAPI: "/api",
280
+ baseApi: "/api",
281
+ item: { id: 1 },
282
+ pager: { index: 1 },
283
+ $notify: (value) => notifications.push(value),
284
+ $jx3boxT: (key, text) => text,
285
+ };
286
+ await instance[method](
287
+ {},
288
+ () => {
289
+ cleared++;
290
+ },
291
+ () => {
292
+ settled++;
293
+ }
294
+ );
295
+ assert.equal(cleared, 1);
296
+ assert.equal(settled, 1);
297
+ assert.equal(notifications.length, 1);
298
+ assert.equal(notifications[0].type, "success");
299
+ assert.equal(service.notifications.length, 1);
300
+ assert.equal(service.notifications[0].type, "warning");
301
+ assert.match(service.notifications[0].message, /已提交.*列表刷新失败.*无需重复提交/);
302
+ assert.equal(instance.loading, file.includes("single") ? false : undefined);
303
+ });
304
+ }
305
+
306
+ test("nested reply forwards settlement even when submission fails", () => {
307
+ const item = loadMethods("src/comment/ReplyItem.vue");
308
+ const list = loadMethods("src/comment/ReplyList.vue");
309
+ let settled = 0;
310
+ const instance = {
311
+ reply: { id: 2, userId: 3 },
312
+ showReplyForReplyFrom: true,
313
+ $emit: (event, data, clear, onSettled) =>
314
+ list.addReply.call(
315
+ {
316
+ $emit: (name, payload, onSuccess, callback) => callback(),
317
+ },
318
+ data,
319
+ clear,
320
+ onSettled
321
+ ),
322
+ };
323
+ item.doReply.call(
324
+ instance,
325
+ {},
326
+ () => {
327
+ throw new Error("must not clear");
328
+ },
329
+ () => {
330
+ settled++;
331
+ }
332
+ );
333
+ assert.equal(settled, 1);
334
+ assert.equal(instance.showReplyForReplyFrom, true);
335
+ });
@@ -0,0 +1,43 @@
1
+ const assert = require("node:assert/strict");
2
+ const test = require("node:test");
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const vm = require("node:vm");
6
+
7
+ test("reuses a confirmed permission across page loads and cools down failed requests per identity", async () => {
8
+ const values = new Map([["jx3box:device_id", "fixture-id"]]);
9
+ let uid = 0;
10
+ let requests = 0;
11
+ let fail = false;
12
+ const source = fs.readFileSync(path.join(__dirname, "../src/utils/client-stat.js"), "utf8")
13
+ .replace(/^import .+;$/gm, "").replace(/^export /gm, "");
14
+ function load() {
15
+ const context = {
16
+ window: { location: { hostname: "test.jx3box.com", search: "" } },
17
+ document: {}, URLSearchParams, packageInfo: { version: "test" },
18
+ DEFAULT_BLOCK_STORAGE_KEY: "block",
19
+ User: { isLogin: () => !!uid, getInfo: () => ({ uid }) },
20
+ localStorage: { getItem: k => values.get(k) ?? null, setItem: (k, v) => values.set(k, v) },
21
+ isApp: () => false, isMiniProgram: () => false, applyJx3boxClientStatRules: v => v,
22
+ $cms: () => ({ post: async () => {
23
+ requests++;
24
+ if (fail) throw Error("offline");
25
+ return { data: { data: { traffic_allowed: true } } };
26
+ } }),
27
+ };
28
+ return vm.runInNewContext(source + "\nresolveClientTrafficPermission;", context);
29
+ }
30
+
31
+ assert.equal((await load()()).traffic_allowed, true);
32
+ assert.equal((await load()()).traffic_allowed, true);
33
+ assert.equal(requests, 1);
34
+ values.set("block", "robot");
35
+ fail = true;
36
+ assert.equal(await load()(), null);
37
+ assert.equal(await load()(), null);
38
+ assert.equal(requests, 2);
39
+ uid = 10;
40
+ fail = false;
41
+ assert.equal((await load()()).traffic_allowed, true);
42
+ assert.equal(requests, 3);
43
+ });