vimp-engine 0.39.0 → 0.41.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.
Files changed (62) hide show
  1. package/README.md +2 -2
  2. package/bin/vimp-sim.js +2 -2
  3. package/core/Cargo.toml +2 -2
  4. package/package.json +3 -4
  5. package/src/client/boot.js +11 -87
  6. package/src/client/components/controller/Vote.js +26 -0
  7. package/src/client/components/model/Controls.js +9 -1
  8. package/src/client/components/model/RoomMenu.js +1 -1
  9. package/src/client/components/model/Vote.js +202 -0
  10. package/src/client/components/view/Auth.js +3 -3
  11. package/src/client/components/view/Panel.js +176 -6
  12. package/src/client/components/view/Voice.js +6 -1
  13. package/src/client/components/view/Vote.js +71 -2
  14. package/src/client/lib/formBuilder.js +7 -6
  15. package/src/client/lib/hostVoteCommand.js +2 -2
  16. package/src/client/lib/pickActiveGame.js +3 -12
  17. package/src/client/lib/retryOnNetworkError.js +0 -9
  18. package/src/client/main.js +47 -90
  19. package/src/client/network/SessionSupervisor.js +14 -14
  20. package/src/client/network/WebRtcManager.js +1 -2
  21. package/src/client/network/policyClose.js +10 -77
  22. package/src/client/style.css +85 -10
  23. package/src/client/views/gameShell.js +2 -4
  24. package/src/client/views/includes/auth.pug +1 -4
  25. package/src/client/views/includes/lobby.pug +3 -6
  26. package/src/client/voice/MicCapture.js +3 -1
  27. package/src/config/abiOps.js +42 -0
  28. package/src/config/closeCodes.js +7 -9
  29. package/src/config/gameCodes.js +1 -1
  30. package/src/config/hostDefaults.js +2 -2
  31. package/src/config/lobby.js +3 -4
  32. package/src/config/menuName.js +3 -0
  33. package/src/config/wsports.js +1 -1
  34. package/src/devtools/ScenarioRunner.js +1 -1
  35. package/src/devtools/builtinScenario.js +2 -2
  36. package/src/devtools/contract/rules/a2-package-scripts.js +1 -1
  37. package/src/devtools/contract/rules/a4-vite-config.js +1 -1
  38. package/src/devtools/contract/rules/c4-component-dependencies.js +1 -1
  39. package/src/devtools/invariants.js +1 -1
  40. package/src/devtools/pluginLoader.js +2 -2
  41. package/src/host/GameCoreAdapter.js +83 -4
  42. package/src/host/HostGame.js +93 -17
  43. package/src/host/PortMachine.js +4 -21
  44. package/src/host/commandFailure.js +2 -2
  45. package/src/host/identity.js +3 -3
  46. package/src/host/meta/core/CommandProcessor.js +2 -2
  47. package/src/host/meta/core/RoundManager.js +8 -1
  48. package/src/host/meta/core/VoteCoordinator.js +56 -1
  49. package/src/host/meta/modules/Accolades.js +1 -1
  50. package/src/host/meta/modules/TimerManager.js +16 -2
  51. package/src/host/meta/modules/Vote.js +65 -0
  52. package/src/host/meta/player/ParticipantManager.js +19 -3
  53. package/src/lib/capabilities.js +17 -0
  54. package/src/lib/createHostRuntime.js +1 -1
  55. package/src/lib/gameConfigView.js +7 -0
  56. package/src/lib/loadGamePackage.js +7 -9
  57. package/src/lib/offlinePlayerData.js +1 -1
  58. package/src/lib/validators.js +2 -2
  59. package/src/lib/voicePacket.js +1 -1
  60. package/src/standalone/index.js +3 -2
  61. package/src/client/lib/footerLink.js +0 -30
  62. package/src/client/network/WebSocketTransport.js +0 -78
@@ -11,6 +11,19 @@ const DEFAULT_BAR_MAX = 100;
11
11
  const EMPTY_BLOCK_COLOR = '#888';
12
12
  const BAR_FILL_DELAY_MS = 500;
13
13
  const BAR_FILL_DURATION_MS = 500;
14
+ // длительность подсветки is-up / is-down у flashOnChange-поля
15
+ const FLASH_DURATION_MS = 400;
16
+ // свойства поля, при которых ячейка строится как span-разметка, а не голый
17
+ // textContent (поле без них работает как раньше)
18
+ const RICH_PROPS = [
19
+ 'label',
20
+ 'labelFrom',
21
+ 'format',
22
+ 'prefix',
23
+ 'suffix',
24
+ 'emptyWhen',
25
+ 'flashOnChange',
26
+ ];
14
27
 
15
28
  // системная настройка «уменьшить движение» — округление в один момент
16
29
  // времени: matchMedia недоступен в тестовой среде без happy-dom-полифилла
@@ -22,7 +35,10 @@ export default class PanelView {
22
35
  // config — { containerId (движок), fields (схема игры: массив
23
36
  // { name, elem, type: 'bar'|'value'|'time'|'weapon', max?, blocks? }) }
24
37
  // Семантику ячейки задаёт type, а не имя поля: игра с полем `energy`
25
- // вместо `health` получает тот же бар
38
+ // вместо `health` получает тот же бар. Необязательные свойства поля:
39
+ // label, labelFrom { field, labels }, hidden, format ('int' | 'money' |
40
+ // 'tenths' | 'fraction'), prefix, suffix, emptyWhen, flashOnChange,
41
+ // countdown { for }
26
42
  constructor(model, config) {
27
43
  if (panelView) {
28
44
  return panelView;
@@ -35,6 +51,12 @@ export default class PanelView {
35
51
  this._panels = {};
36
52
  this._fields = {};
37
53
  this._bars = {};
54
+ // последние значения полей: нужны labelFrom и пересчёту зависимых ячеек
55
+ this._values = {};
56
+ this._rich = {};
57
+ this._flashTimers = {};
58
+ // имя поля-источника → имена полей, чья подпись берётся по его значению
59
+ this._dependents = {};
38
60
  this._weaponList = fields
39
61
  .filter(field => field.type === 'weapon')
40
62
  .map(field => field.name);
@@ -54,22 +76,60 @@ export default class PanelView {
54
76
  _buildPanel(container, fields) {
55
77
  const table = document.createElement('table');
56
78
  const row = table.insertRow(-1);
79
+ const gaugeTargets = new Set(
80
+ fields.map(field => field.countdown?.for).filter(Boolean),
81
+ );
57
82
 
58
83
  for (const field of fields) {
84
+ this._fields[field.name] = field;
85
+
86
+ if (field.labelFrom) {
87
+ const { field: source } = field.labelFrom;
88
+
89
+ (this._dependents[source] ??= []).push(field.name);
90
+ }
91
+
92
+ // служебное поле хранит значение, но ячейки у него нет
93
+ if (field.hidden) {
94
+ continue;
95
+ }
96
+
59
97
  const cell = row.insertCell(-1);
60
98
 
61
99
  cell.setAttribute('id', field.elem);
62
100
  this._panels[field.name] = cell;
63
- this._fields[field.name] = field;
64
101
 
65
102
  if (field.type === 'bar') {
66
103
  this._initBar(field, cell);
104
+ } else if (
105
+ RICH_PROPS.some(prop => prop in field) ||
106
+ gaugeTargets.has(field.name)
107
+ ) {
108
+ this._initRichCell(field, cell);
67
109
  }
68
110
  }
69
111
 
70
112
  container.appendChild(table);
71
113
  }
72
114
 
115
+ // разметка ячейки с подписью: span.panel-label + span.panel-value +
116
+ // div.panel-gauge
117
+ _initRichCell(field, cell) {
118
+ cell.textContent = '';
119
+
120
+ const label = document.createElement('span');
121
+ const value = document.createElement('span');
122
+ const gauge = document.createElement('div');
123
+
124
+ label.className = 'panel-label';
125
+ value.className = 'panel-value';
126
+ gauge.className = 'panel-gauge';
127
+ gauge.style.display = 'none';
128
+
129
+ cell.append(label, value, gauge);
130
+ this._rich[field.name] = { label, value, gauge };
131
+ }
132
+
73
133
  // инициализирует полосу-бар поля type: 'bar'
74
134
  _initBar(field, cell) {
75
135
  cell.textContent = '';
@@ -148,15 +208,117 @@ export default class PanelView {
148
208
  // обновляет пользовательскую панель
149
209
  update(data) {
150
210
  const { name, value } = data;
211
+ const field = this._fields[name];
151
212
  const elem = this._panels[name];
213
+ const previous = this._values[name];
152
214
 
153
- if (this._fields[name]?.type === 'bar') {
215
+ this._values[name] = value;
216
+
217
+ if (field?.type === 'bar') {
154
218
  this._updateBar(name, value);
155
- } else {
219
+ } else if (this._rich[name]) {
220
+ this._renderRich(name);
221
+
222
+ if (field.flashOnChange && previous !== undefined && value !== previous) {
223
+ this._flash(name, value > previous ? 'is-up' : 'is-down');
224
+ }
225
+ } else if (elem) {
156
226
  elem.textContent = value;
157
227
  }
158
228
 
159
- elem.style.display = 'table-cell';
229
+ // подпись зависимых ячеек берётся по значению этого поля
230
+ for (const dependent of this._dependents[name] ?? []) {
231
+ if (this._rich[dependent]) {
232
+ this._renderRich(dependent);
233
+ }
234
+ }
235
+
236
+ if (field?.countdown) {
237
+ this._runCountdown(field.countdown.for, value);
238
+ }
239
+
240
+ if (elem) {
241
+ elem.style.display = 'table-cell';
242
+ }
243
+ }
244
+
245
+ // подпись и значение ячейки: объектная форма записи labelFrom.labels
246
+ // перекрывает format / prefix / suffix / max самого поля
247
+ _renderRich(name) {
248
+ const field = this._fields[name];
249
+ const { label, value } = this._rich[name];
250
+ const raw = this._values[name];
251
+ const entry =
252
+ field.labelFrom?.labels?.[this._values[field.labelFrom.field]];
253
+ const spec = typeof entry === 'object' && entry !== null ? entry : {};
254
+ const text = typeof entry === 'string' ? entry : spec.text;
255
+
256
+ label.textContent = [field.label, text].filter(Boolean).join(' ');
257
+ // значение поля-источника может прийти раньше собственного
258
+ value.textContent =
259
+ raw === undefined
260
+ ? ''
261
+ : this._format(raw, {
262
+ format: spec.format ?? field.format,
263
+ prefix: spec.prefix ?? field.prefix,
264
+ suffix: spec.suffix ?? field.suffix,
265
+ max: spec.max,
266
+ });
267
+ this._panels[name].classList.toggle(
268
+ 'is-empty',
269
+ 'emptyWhen' in field && raw === field.emptyWhen,
270
+ );
271
+ }
272
+
273
+ _format(raw, { format = 'int', prefix = '', suffix = '', max }) {
274
+ let text;
275
+
276
+ if (typeof raw === 'string') {
277
+ text = raw; // time уже отформатирован моделью
278
+ } else if (format === 'money') {
279
+ text = `$ ${raw}`;
280
+ } else if (format === 'tenths') {
281
+ text = raw.toFixed(1);
282
+ } else if (format === 'fraction') {
283
+ text = max === undefined ? `${raw}` : `${raw}/${max}`;
284
+ } else {
285
+ text = `${raw}`;
286
+ }
287
+
288
+ return `${prefix}${text}${suffix}`;
289
+ }
290
+
291
+ // кратко подсвечивает ячейку классом is-up / is-down
292
+ _flash(name, className) {
293
+ const cell = this._panels[name];
294
+
295
+ clearTimeout(this._flashTimers[name]);
296
+ cell.classList.remove('is-up', 'is-down');
297
+ cell.classList.add(className);
298
+ this._flashTimers[name] = setTimeout(() => {
299
+ cell.classList.remove(className);
300
+ }, FLASH_DURATION_MS);
301
+ }
302
+
303
+ // шкала div.panel-gauge ячейки target заполняется от 0 до 100 % за
304
+ // duration мс (повторное значение перезапускает её); 0 — скрывает
305
+ _runCountdown(target, duration) {
306
+ const gauge = this._rich[target]?.gauge;
307
+
308
+ if (!gauge) {
309
+ return;
310
+ }
311
+
312
+ gauge.style.animation = 'none';
313
+
314
+ if (!(duration > 0)) {
315
+ gauge.style.display = 'none';
316
+ return;
317
+ }
318
+
319
+ gauge.style.display = 'block';
320
+ void gauge.offsetWidth; // перезапуск CSS-анимации
321
+ gauge.style.animation = `panel-gauge-fill ${duration}ms linear forwards`;
160
322
  }
161
323
 
162
324
  // перерисовывает бар по текущему значению
@@ -263,7 +425,11 @@ export default class PanelView {
263
425
  }
264
426
 
265
427
  hidePanel(name) {
266
- this._panels[name].style.display = 'none';
428
+ const elem = this._panels[name];
429
+
430
+ if (elem) {
431
+ elem.style.display = 'none';
432
+ }
267
433
  }
268
434
 
269
435
  // с задержкой BAR_FILL_DELAY_MS заполняет bar-поля (например, здоровье)
@@ -303,6 +469,10 @@ export default class PanelView {
303
469
  for (const weaponName of this._weaponList) {
304
470
  const elem = this._panels[weaponName];
305
471
 
472
+ if (!elem) {
473
+ continue;
474
+ }
475
+
306
476
  if (weaponName === activeWeaponName) {
307
477
  elem.classList.add('active');
308
478
  } else {
@@ -65,7 +65,12 @@ export default class VoiceView {
65
65
  this._nameElem = document.createElement('span');
66
66
  this._nameElem.className = 'voice-name';
67
67
 
68
- own.append(createIcon(), ring, this._timerElem, this._textElem);
68
+ // кольцо центрируется на значке, а не на крайнем элементе строки
69
+ const mark = document.createElement('span');
70
+
71
+ mark.className = 'voice-mark';
72
+ mark.append(createIcon(), ring);
73
+ own.append(mark, this._timerElem, this._textElem);
69
74
  incoming.append(createIcon(), this._nameElem);
70
75
  this._hud.append(own, incoming);
71
76
  container.appendChild(this._hud);
@@ -28,11 +28,42 @@ export default class VoteView {
28
28
 
29
29
  this._mPublic.on('vote', 'createVote', this);
30
30
  this._mPublic.on('clear', 'removeVote', this);
31
+ this._mPublic.on('hint', 'setHint', this);
32
+ }
33
+
34
+ // подсказка меню: иконка под значком рации (`#menu-hints`), класс
35
+ // `is-on` у горящей. Узлы строятся без innerHTML — имя пришло от хоста
36
+ setHint({ name, on }) {
37
+ let box = document.getElementById('menu-hints');
38
+
39
+ if (!box) {
40
+ box = document.createElement('div');
41
+ box.setAttribute('id', 'menu-hints');
42
+ this._container.appendChild(box);
43
+ }
44
+
45
+ let hint = null;
46
+
47
+ for (const child of box.children) {
48
+ if (child.dataset.name === name) {
49
+ hint = child;
50
+ }
51
+ }
52
+
53
+ if (!hint) {
54
+ hint = document.createElement('div');
55
+ hint.setAttribute('class', 'menu-hint');
56
+ hint.dataset.name = name;
57
+ hint.appendChild(createCartIcon());
58
+ box.appendChild(hint);
59
+ }
60
+
61
+ hint.classList.toggle('is-on', on === true);
31
62
  }
32
63
 
33
64
  // создает окно голосования
34
65
  createVote(data) {
35
- const { title, list, back, more, time } = data;
66
+ const { title, list, back, more, time, style, level } = data;
36
67
  const vote = document.createElement('div');
37
68
  const p = document.createElement('p');
38
69
  const ol = document.createElement('ol');
@@ -44,6 +75,10 @@ export default class VoteView {
44
75
 
45
76
  vote.setAttribute('id', this._voteId);
46
77
 
78
+ if (style) {
79
+ vote.classList.add(`vote-style-${style}`, `vote-level-${level}`);
80
+ }
81
+
47
82
  p.setAttribute('class', this._titleClass);
48
83
  p.textContent = title;
49
84
 
@@ -51,7 +86,22 @@ export default class VoteView {
51
86
 
52
87
  list.forEach(item => {
53
88
  const li = document.createElement('li');
54
- li.textContent = item;
89
+
90
+ // личное меню передаёт объекты { text, disabled, group }
91
+ if (typeof item === 'object') {
92
+ li.textContent = item.text;
93
+
94
+ if (item.disabled) {
95
+ li.classList.add('disabled');
96
+ }
97
+
98
+ if (item.group) {
99
+ li.classList.add('group');
100
+ }
101
+ } else {
102
+ li.textContent = item;
103
+ }
104
+
55
105
  ol.appendChild(li);
56
106
  });
57
107
 
@@ -106,3 +156,22 @@ export default class VoteView {
106
156
  }
107
157
  }
108
158
  }
159
+
160
+ // SVG-заглушка корзины: подсказка работает без игровых стилей и файлов
161
+ function createCartIcon() {
162
+ const ns = 'http://www.w3.org/2000/svg';
163
+ const svg = document.createElementNS(ns, 'svg');
164
+ const path = document.createElementNS(ns, 'path');
165
+
166
+ svg.setAttribute('viewBox', '0 0 24 24');
167
+ svg.setAttribute('width', '24');
168
+ svg.setAttribute('height', '24');
169
+ path.setAttribute('fill', 'currentColor');
170
+ path.setAttribute(
171
+ 'd',
172
+ 'M7 18a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm10 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4ZM1 2v2h2l3.6 7.6-1.4 2.4A2 2 0 0 0 7 17h12v-2H7.4l1.1-2h7.5a2 2 0 0 0 1.7-1l3.6-6.5A1 1 0 0 0 20.4 4H5.2l-.9-2H1Z',
173
+ );
174
+ svg.appendChild(path);
175
+
176
+ return svg;
177
+ }
@@ -4,9 +4,10 @@ import { resolveDescriptor } from '../../lib/formControls.js';
4
4
  import { toDisplay, toStored, isNumericField } from '../../lib/formUnit.js';
5
5
 
6
6
  // Общий билдер полей форм (room-форма и auth-форма используют один
7
- // контракт дескрипторов — docs.vimp.lgick.dev/en/plugin-api, раздел "Form
8
- // schema"). control: 'select'|'text'|'checkbox'|'radio'; все контролы —
9
- // нативные элементы формы, без визуальной кастомизации.
7
+ // контракт дескрипторов —
8
+ // VIMP docs: plugin-api.md § "Form schema"). control:
9
+ // 'select'|'text'|'checkbox'|'radio'; все контролы — нативные элементы формы,
10
+ // без визуальной кастомизации.
10
11
  //
11
12
  // Имя контрола приезжает от игры и разрешается через append-only реестр
12
13
  // (lib/formControls.js): имена, выведенные из эксплуатации в v3 ('range',
@@ -270,8 +271,8 @@ const builders = {
270
271
  // control» на имени, которое реестр считает живым
271
272
  export const FORM_CONTROLS = Object.keys(builders);
272
273
 
273
- // строит одно поле формы по дескриптору (docs.vimp.lgick.dev/en/plugin-api,
274
- // "Form schema")
274
+ // строит одно поле формы по дескриптору
275
+ // (VIMP docs: plugin-api.md § "Form schema")
275
276
  export function buildField(descriptor, ctx = {}) {
276
277
  // алиас выведенного контрола ('range' → numeric 'text') разрешается
277
278
  // здесь же, где строится поле, и теми же правилами, что в валидации
@@ -292,7 +293,7 @@ export function buildField(descriptor, ctx = {}) {
292
293
  }
293
294
 
294
295
  // засеивает default каждого дескриптора room-формы значением из roomDefaults
295
- // (docs.vimp.lgick.dev/en/plugin-api "Form schema": roomDefaults остаётся
296
+ // (VIMP docs: plugin-api.md § "Form schema": roomDefaults остаётся
296
297
  // единственным источником значений по умолчанию); явный descriptor.default,
297
298
  // если он есть в схеме, побеждает. Вынесено из populateRoomForm (main.js),
298
299
  // чтобы этот же код был накрыт тестом, а не продублирован в нём
@@ -1,6 +1,6 @@
1
1
  // Голосование «Change host» (host-migration этап 10): команда /changehost и
2
2
  // окно у гостей. Голоса считает мастер, поэтому команда в лобби-режиме не
3
- // уходит хосту. В solo/dedicated мастера нет — команда остаётся обычным
3
+ // уходит хосту. В solo мастера нет — команда остаётся обычным
4
4
  // текстом для игры.
5
5
 
6
6
  // имя голосования движка; префикс '@' зарезервирован движком
@@ -13,7 +13,7 @@ const COMMAND = '/changehost';
13
13
  /**
14
14
  * Разбор сообщения чата.
15
15
  * @param {string} text
16
- * @param {string} bootMode - 'lobby' | 'solo' | 'dedicated'.
16
+ * @param {string} bootMode - 'lobby' | 'solo'.
17
17
  * @returns {'start'|'usage'|null} null — не перехватывать.
18
18
  */
19
19
  export function parseChangeHost(text, bootMode) {
@@ -19,23 +19,14 @@ export function isGameAvailable(manifest) {
19
19
  }
20
20
 
21
21
  /**
22
- * Активная игра вкладки.
23
- *
24
- * Обе ветки фильтруются одинаково: сохранённый выбор игры (`gameId`) тоже мог
25
- * указывать на игру, ставшую недоступной после обновления движка, и брать её
26
- * «раз уж попросили» значило бы падать там, где можно объяснить.
22
+ * Активная игра вкладки: первая доступная игра каталога.
27
23
  * @param {Array<Object>} manifests - Каталог мастера.
28
- * @param {string} [gameId] - Сохранённый выбор игры (boot.gameId).
29
24
  * @returns {Object|undefined} Манифест активной игры.
30
25
  * @throws {Error} Если каталог непустой, но играбельной игры в нём нет —
31
26
  * с причиной по каждой строке.
32
27
  */
33
- export function pickActiveGame(manifests, gameId) {
34
- const active = gameId
35
- ? manifests.find(
36
- manifest => manifest.id === gameId && isGameAvailable(manifest),
37
- )
38
- : manifests.find(isGameAvailable);
28
+ export function pickActiveGame(manifests) {
29
+ const active = manifests.find(isGameAvailable);
39
30
 
40
31
  if (active) {
41
32
  return active;
@@ -19,15 +19,6 @@ export class NetworkFailure extends Error {
19
19
 
20
20
  export const isNetworkFailure = error => error instanceof NetworkFailure;
21
21
 
22
- /**
23
- * Оборачивает отказ чтения тела ответа: SyntaxError — это мусор в JSON,
24
- * любой другой отказ (TypeError обрыва) — сбой сети.
25
- * @param {Error} error
26
- * @returns {Error}
27
- */
28
- export const bodyReadFailure = error =>
29
- error instanceof SyntaxError ? error : new NetworkFailure(error);
30
-
31
22
  /**
32
23
  * @param {Function} doFetch - (...args) => Promise<Response>: сам fetch.
33
24
  * @param {*} url