@web-auto/camo 0.2.0 → 0.2.1

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 (114) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +586 -586
  3. package/bin/browser-service.mjs +11 -11
  4. package/bin/camo.mjs +22 -22
  5. package/package.json +48 -48
  6. package/scripts/build.mjs +19 -19
  7. package/scripts/bump-version.mjs +34 -34
  8. package/scripts/check-file-size.mjs +80 -80
  9. package/scripts/file-size-policy.json +12 -2
  10. package/scripts/install.mjs +76 -76
  11. package/scripts/release.sh +54 -54
  12. package/src/autoscript/action-providers/index.mjs +6 -6
  13. package/src/autoscript/impact-engine.mjs +78 -78
  14. package/src/autoscript/runtime.mjs +1017 -1017
  15. package/src/autoscript/schema.mjs +376 -376
  16. package/src/cli.mjs +405 -405
  17. package/src/commands/attach.mjs +141 -141
  18. package/src/commands/autoscript.mjs +1011 -1011
  19. package/src/commands/browser.mjs +1255 -1255
  20. package/src/commands/container.mjs +401 -401
  21. package/src/commands/cookies.mjs +69 -69
  22. package/src/commands/create.mjs +98 -98
  23. package/src/commands/devtools.mjs +349 -349
  24. package/src/commands/events.mjs +152 -152
  25. package/src/commands/highlight-mode.mjs +24 -24
  26. package/src/commands/init.mjs +68 -68
  27. package/src/commands/lifecycle.mjs +275 -275
  28. package/src/commands/mouse.mjs +45 -45
  29. package/src/commands/profile.mjs +46 -46
  30. package/src/commands/record.mjs +115 -115
  31. package/src/commands/system.mjs +14 -14
  32. package/src/commands/window.mjs +123 -123
  33. package/src/container/change-notifier.mjs +362 -362
  34. package/src/container/element-filter.mjs +143 -143
  35. package/src/container/index.mjs +3 -3
  36. package/src/container/runtime-core/checkpoint.mjs +209 -209
  37. package/src/container/runtime-core/index.mjs +21 -21
  38. package/src/container/runtime-core/operations/index.mjs +774 -774
  39. package/src/container/runtime-core/operations/selector-scripts.mjs +277 -277
  40. package/src/container/runtime-core/operations/tab-pool.mjs +746 -746
  41. package/src/container/runtime-core/operations/viewport.mjs +189 -189
  42. package/src/container/runtime-core/search.mjs +190 -190
  43. package/src/container/runtime-core/subscription.mjs +224 -224
  44. package/src/container/runtime-core/utils.mjs +94 -94
  45. package/src/container/runtime-core/validation.mjs +127 -127
  46. package/src/container/runtime-core.mjs +1 -1
  47. package/src/container/subscription-registry.mjs +459 -459
  48. package/src/core/actions.mjs +561 -561
  49. package/src/core/browser.mjs +266 -266
  50. package/src/core/index.mjs +52 -52
  51. package/src/core/utils.mjs +91 -91
  52. package/src/events/daemon-entry.mjs +33 -33
  53. package/src/events/daemon.mjs +80 -80
  54. package/src/events/progress-log.mjs +109 -109
  55. package/src/events/ws-server.mjs +239 -239
  56. package/src/lib/client.mjs +200 -200
  57. package/src/lifecycle/cleanup.mjs +83 -83
  58. package/src/lifecycle/lock.mjs +126 -126
  59. package/src/lifecycle/session-registry.mjs +279 -279
  60. package/src/lifecycle/session-view.mjs +76 -76
  61. package/src/lifecycle/session-watchdog.mjs +281 -281
  62. package/src/services/browser-service/index.js +671 -671
  63. package/src/services/browser-service/internal/BrowserSession.input.test.js +389 -389
  64. package/src/services/browser-service/internal/BrowserSession.js +325 -304
  65. package/src/services/browser-service/internal/ElementRegistry.js +60 -60
  66. package/src/services/browser-service/internal/ProfileLock.js +84 -84
  67. package/src/services/browser-service/internal/SessionManager.js +184 -184
  68. package/src/services/browser-service/internal/SessionManager.test.js +39 -39
  69. package/src/services/browser-service/internal/browser-session/cookies.js +144 -144
  70. package/src/services/browser-service/internal/browser-session/input-ops.js +222 -222
  71. package/src/services/browser-service/internal/browser-session/input-pipeline.js +144 -144
  72. package/src/services/browser-service/internal/browser-session/logging.js +46 -46
  73. package/src/services/browser-service/internal/browser-session/navigation.js +38 -38
  74. package/src/services/browser-service/internal/browser-session/page-hooks.js +442 -442
  75. package/src/services/browser-service/internal/browser-session/page-management.js +302 -302
  76. package/src/services/browser-service/internal/browser-session/page-management.test.js +148 -148
  77. package/src/services/browser-service/internal/browser-session/recording.js +198 -198
  78. package/src/services/browser-service/internal/browser-session/runtime-events.js +61 -61
  79. package/src/services/browser-service/internal/browser-session/session-core.js +84 -84
  80. package/src/services/browser-service/internal/browser-session/session-state.js +38 -38
  81. package/src/services/browser-service/internal/browser-session/types.js +14 -14
  82. package/src/services/browser-service/internal/browser-session/utils.js +95 -95
  83. package/src/services/browser-service/internal/browser-session/viewport-manager.js +46 -46
  84. package/src/services/browser-service/internal/browser-session/viewport.js +215 -215
  85. package/src/services/browser-service/internal/container-matcher.js +851 -851
  86. package/src/services/browser-service/internal/container-registry.js +182 -182
  87. package/src/services/browser-service/internal/engine-manager.js +259 -259
  88. package/src/services/browser-service/internal/fingerprint.js +203 -203
  89. package/src/services/browser-service/internal/heartbeat.js +137 -137
  90. package/src/services/browser-service/internal/logging.js +46 -46
  91. package/src/services/browser-service/internal/page-runtime/runtime.js +1317 -1317
  92. package/src/services/browser-service/internal/pageRuntime.js +28 -28
  93. package/src/services/browser-service/internal/runtimeInjector.js +31 -31
  94. package/src/services/browser-service/internal/service-process-logger.js +140 -140
  95. package/src/services/browser-service/internal/state-bus.js +45 -45
  96. package/src/services/browser-service/internal/storage-paths.js +42 -42
  97. package/src/services/browser-service/internal/ws-server.js +1194 -1194
  98. package/src/services/browser-service/internal/ws-server.test.js +58 -58
  99. package/src/services/browser-service/server.mjs +6 -6
  100. package/src/services/controller/cli-bridge.js +93 -93
  101. package/src/services/controller/container-index.js +50 -50
  102. package/src/services/controller/container-storage.js +36 -36
  103. package/src/services/controller/controller-actions.js +207 -207
  104. package/src/services/controller/controller.js +1138 -1138
  105. package/src/services/controller/selectors.js +54 -54
  106. package/src/services/controller/transport.js +125 -125
  107. package/src/utils/args.mjs +26 -26
  108. package/src/utils/browser-service.mjs +544 -544
  109. package/src/utils/command-log.mjs +64 -64
  110. package/src/utils/config.mjs +214 -214
  111. package/src/utils/fingerprint.mjs +181 -181
  112. package/src/utils/help.mjs +216 -216
  113. package/src/utils/js-policy.mjs +13 -13
  114. package/src/utils/ws-client.mjs +30 -30
@@ -1,376 +1,376 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- function toArray(value) {
5
- return Array.isArray(value) ? value : [];
6
- }
7
-
8
- function toTrimmedString(value) {
9
- return typeof value === 'string' ? value.trim() : '';
10
- }
11
-
12
- function normalizeTrigger(value) {
13
- if (!value) return { type: 'startup' };
14
- if (typeof value === 'string') {
15
- const token = value.trim();
16
- if (!token) return { type: 'startup' };
17
- if (token === 'startup' || token === 'manual') return { type: token };
18
- const [subscriptionId, event] = token.split('.');
19
- if (subscriptionId && event) {
20
- return { type: 'subscription_event', subscriptionId: subscriptionId.trim(), event: event.trim() };
21
- }
22
- return { type: 'unknown', raw: token };
23
- }
24
- if (typeof value !== 'object') return { type: 'startup' };
25
- if (value.type === 'startup' || value.type === 'manual') return { type: value.type };
26
- const subscriptionId = toTrimmedString(value.subscriptionId || value.subscription);
27
- const event = toTrimmedString(value.event);
28
- if (subscriptionId && event) {
29
- return { type: 'subscription_event', subscriptionId, event };
30
- }
31
- return { type: 'unknown', raw: value };
32
- }
33
-
34
- function normalizeCondition(value) {
35
- if (!value) return null;
36
- if (typeof value === 'string') {
37
- const text = value.trim();
38
- if (!text) return null;
39
- if (text.startsWith('operation_done:')) {
40
- return { type: 'operation_done', operationId: text.slice('operation_done:'.length).trim() };
41
- }
42
- if (text.startsWith('subscription_exist:')) {
43
- return { type: 'subscription_exist', subscriptionId: text.slice('subscription_exist:'.length).trim() };
44
- }
45
- if (text.startsWith('subscription_appear:')) {
46
- return { type: 'subscription_appear', subscriptionId: text.slice('subscription_appear:'.length).trim() };
47
- }
48
- return null;
49
- }
50
- if (typeof value !== 'object') return null;
51
- const type = toTrimmedString(value.type);
52
- if (!type) return null;
53
- return {
54
- type,
55
- operationId: toTrimmedString(value.operationId || value.operation) || null,
56
- subscriptionId: toTrimmedString(value.subscriptionId || value.subscription) || null,
57
- };
58
- }
59
-
60
- function normalizeRetry(value, defaults = {}) {
61
- const retry = value && typeof value === 'object' ? value : {};
62
- const attempts = Math.max(1, Number(retry.attempts ?? defaults.attempts ?? 1) || 1);
63
- const backoffMs = Math.max(0, Number(retry.backoffMs ?? defaults.backoffMs ?? 0) || 0);
64
- return { attempts, backoffMs };
65
- }
66
-
67
- function normalizeRecovery(value, defaults = {}) {
68
- const recovery = value && typeof value === 'object' ? value : {};
69
- const attempts = Math.max(0, Number(recovery.attempts ?? defaults.attempts ?? 0) || 0);
70
- const actions = toArray(recovery.actions ?? defaults.actions ?? [])
71
- .map((item) => toTrimmedString(item))
72
- .filter(Boolean);
73
- return { attempts, actions };
74
- }
75
-
76
- function normalizeValidation(value, defaults = {}) {
77
- const validation = value && typeof value === 'object' ? value : {};
78
- const mode = toTrimmedString(validation.mode || defaults.validationMode || 'none') || 'none';
79
- return {
80
- mode,
81
- pre: validation.pre && typeof validation.pre === 'object' ? validation.pre : null,
82
- post: validation.post && typeof validation.post === 'object' ? validation.post : null,
83
- };
84
- }
85
-
86
- function normalizePacing(value, defaults = {}) {
87
- const pacing = value && typeof value === 'object' ? value : {};
88
- const operationMinIntervalMs = Math.max(
89
- 0,
90
- Number(
91
- pacing.operationMinIntervalMs
92
- ?? pacing.minIntervalMs
93
- ?? defaults.operationMinIntervalMs
94
- ?? defaults.minIntervalMs
95
- ?? 0,
96
- ) || 0,
97
- );
98
- const eventCooldownMs = Math.max(
99
- 0,
100
- Number(pacing.eventCooldownMs ?? defaults.eventCooldownMs ?? 0) || 0,
101
- );
102
- const jitterMs = Math.max(
103
- 0,
104
- Number(pacing.jitterMs ?? defaults.jitterMs ?? 0) || 0,
105
- );
106
- const navigationMinIntervalMs = Math.max(
107
- 0,
108
- Number(pacing.navigationMinIntervalMs ?? defaults.navigationMinIntervalMs ?? 0) || 0,
109
- );
110
- const timeoutMsRaw = pacing.timeoutMs ?? defaults.timeoutMs;
111
- const timeoutMs = timeoutMsRaw === null || timeoutMsRaw === undefined
112
- ? null
113
- : Math.max(0, Number(timeoutMsRaw) || 0);
114
-
115
- return {
116
- operationMinIntervalMs,
117
- eventCooldownMs,
118
- jitterMs,
119
- navigationMinIntervalMs,
120
- timeoutMs,
121
- };
122
- }
123
-
124
- function normalizeSubscription(item, index, defaults) {
125
- if (!item || typeof item !== 'object') return null;
126
- const id = toTrimmedString(item.id) || `subscription_${index + 1}`;
127
- const selector = toTrimmedString(item.selector);
128
- if (!selector) return null;
129
- const events = toArray(item.events).map((name) => toTrimmedString(name)).filter(Boolean);
130
- const pageUrlIncludes = toArray(item.pageUrlIncludes).map((token) => toTrimmedString(token)).filter(Boolean);
131
- const pageUrlExcludes = toArray(item.pageUrlExcludes).map((token) => toTrimmedString(token)).filter(Boolean);
132
- return {
133
- id,
134
- selector,
135
- visible: item.visible !== false,
136
- pageUrlIncludes,
137
- pageUrlExcludes,
138
- events: events.length > 0 ? events : ['appear', 'exist', 'disappear', 'change'],
139
- dependsOn: toArray(item.dependsOn).map((x) => toTrimmedString(x)).filter(Boolean),
140
- retry: normalizeRetry(item.retry, defaults.retry),
141
- impact: toTrimmedString(item.impact || defaults.impact || 'subscription') || 'subscription',
142
- };
143
- }
144
-
145
- function normalizeOperation(item, index, defaults) {
146
- if (!item || typeof item !== 'object') return null;
147
- const id = toTrimmedString(item.id) || `operation_${index + 1}`;
148
- const action = toTrimmedString(item.action);
149
- if (!action) return null;
150
- const params = item.params && typeof item.params === 'object'
151
- ? { ...item.params }
152
- : {
153
- ...(item.selector ? { selector: item.selector } : {}),
154
- ...(item.url ? { url: item.url } : {}),
155
- ...(item.text !== undefined ? { text: item.text } : {}),
156
- ...(item.script !== undefined ? { script: item.script } : {}),
157
- ...(item.ms !== undefined ? { ms: item.ms } : {}),
158
- ...(item.value !== undefined ? { value: item.value } : {}),
159
- };
160
-
161
- return {
162
- id,
163
- enabled: item.enabled !== false,
164
- action,
165
- params,
166
- trigger: normalizeTrigger(item.trigger),
167
- dependsOn: toArray(item.dependsOn).map((x) => toTrimmedString(x)).filter(Boolean),
168
- conditions: toArray(item.conditions).map(normalizeCondition).filter(Boolean),
169
- retry: normalizeRetry(item.retry, defaults.retry),
170
- impact: toTrimmedString(item.impact || defaults.impact || 'op') || 'op',
171
- onFailure: toTrimmedString(item.onFailure || defaults.onFailure || 'chain_stop') || 'chain_stop',
172
- pacing: normalizePacing(item.pacing, defaults.pacing || {}),
173
- timeoutMs: (() => {
174
- const timeoutRaw = item.timeoutMs ?? defaults.timeoutMs;
175
- if (timeoutRaw === null || timeoutRaw === undefined || timeoutRaw === '') return null;
176
- return Math.max(0, Number(timeoutRaw) || 0);
177
- })(),
178
- validation: normalizeValidation(item.validate || item.validation, defaults),
179
- checkpoint: {
180
- containerId: toTrimmedString(item.checkpoint?.containerId || item.containerId) || null,
181
- targetCheckpoint: toTrimmedString(item.checkpoint?.targetCheckpoint) || null,
182
- recovery: normalizeRecovery(item.checkpoint?.recovery, defaults.recovery),
183
- },
184
- once: item.once !== false,
185
- oncePerAppear: item.oncePerAppear === true,
186
- };
187
- }
188
-
189
- function topoSortOperations(operations) {
190
- const byId = new Map(operations.map((op) => [op.id, op]));
191
- const temp = new Set();
192
- const visited = new Set();
193
- const sorted = [];
194
- const cycles = [];
195
-
196
- const dfs = (id, trace = []) => {
197
- if (visited.has(id)) return;
198
- if (temp.has(id)) {
199
- const cyclePath = [...trace, id];
200
- cycles.push(cyclePath);
201
- return;
202
- }
203
- temp.add(id);
204
- const node = byId.get(id);
205
- for (const dep of node?.dependsOn || []) {
206
- if (!byId.has(dep)) continue;
207
- dfs(dep, [...trace, id]);
208
- }
209
- temp.delete(id);
210
- visited.add(id);
211
- if (node) sorted.push(node);
212
- };
213
-
214
- for (const op of operations) dfs(op.id);
215
- return { sorted, cycles };
216
- }
217
-
218
- export function loadAutoscriptFile(filePath) {
219
- const resolvedPath = path.resolve(filePath);
220
- if (!fs.existsSync(resolvedPath)) {
221
- throw new Error(`Autoscript file not found: ${resolvedPath}`);
222
- }
223
- let payload = null;
224
- try {
225
- payload = JSON.parse(fs.readFileSync(resolvedPath, 'utf8'));
226
- } catch (err) {
227
- throw new Error(`Invalid autoscript JSON: ${err?.message || String(err)}`);
228
- }
229
- return { resolvedPath, payload };
230
- }
231
-
232
- export function normalizeAutoscript(raw, sourcePath = null) {
233
- const defaults = raw?.defaults && typeof raw.defaults === 'object' ? raw.defaults : {};
234
- const subscriptions = toArray(raw?.subscriptions)
235
- .map((item, index) => normalizeSubscription(item, index, defaults))
236
- .filter(Boolean);
237
- const operations = toArray(raw?.operations)
238
- .map((item, index) => normalizeOperation(item, index, defaults))
239
- .filter(Boolean);
240
-
241
- return {
242
- version: Number(raw?.version || 1),
243
- sourcePath,
244
- name: toTrimmedString(raw?.name) || (sourcePath ? path.basename(sourcePath) : 'autoscript'),
245
- profileId: toTrimmedString(raw?.profileId) || null,
246
- throttle: Math.max(100, Number(raw?.throttle || 500) || 500),
247
- defaults: {
248
- retry: normalizeRetry(defaults.retry, {}),
249
- impact: toTrimmedString(defaults.impact || 'op') || 'op',
250
- onFailure: toTrimmedString(defaults.onFailure || 'chain_stop') || 'chain_stop',
251
- filterMode: toTrimmedString(defaults.filterMode || 'strict') || 'strict',
252
- validationMode: toTrimmedString(defaults.validationMode || 'none') || 'none',
253
- recovery: normalizeRecovery(defaults.recovery, {}),
254
- pacing: normalizePacing(defaults.pacing, {}),
255
- timeoutMs: (() => {
256
- const timeoutRaw = defaults.timeoutMs;
257
- if (timeoutRaw === null || timeoutRaw === undefined || timeoutRaw === '') return null;
258
- return Math.max(0, Number(timeoutRaw) || 0);
259
- })(),
260
- },
261
- subscriptions,
262
- operations,
263
- raw,
264
- };
265
- }
266
-
267
- export function validateAutoscript(script) {
268
- const errors = [];
269
- const warnings = [];
270
- const subscriptionIds = new Set();
271
- const operationIds = new Set();
272
-
273
- for (const subscription of script.subscriptions) {
274
- if (subscriptionIds.has(subscription.id)) {
275
- errors.push(`duplicate subscription id: ${subscription.id}`);
276
- }
277
- subscriptionIds.add(subscription.id);
278
- }
279
- for (const operation of script.operations) {
280
- if (operationIds.has(operation.id)) {
281
- errors.push(`duplicate operation id: ${operation.id}`);
282
- }
283
- operationIds.add(operation.id);
284
- }
285
-
286
- for (const operation of script.operations) {
287
- if (operation.trigger?.type === 'subscription_event') {
288
- if (!subscriptionIds.has(operation.trigger.subscriptionId)) {
289
- errors.push(`operation ${operation.id}: unknown trigger subscription ${operation.trigger.subscriptionId}`);
290
- }
291
- } else if (operation.trigger?.type === 'unknown') {
292
- errors.push(`operation ${operation.id}: unsupported trigger ${JSON.stringify(operation.trigger.raw)}`);
293
- }
294
-
295
- for (const dep of operation.dependsOn || []) {
296
- if (!operationIds.has(dep)) {
297
- errors.push(`operation ${operation.id}: unknown dependency ${dep}`);
298
- }
299
- }
300
-
301
- for (const condition of operation.conditions || []) {
302
- if (condition.type === 'operation_done' && condition.operationId && !operationIds.has(condition.operationId)) {
303
- errors.push(`operation ${operation.id}: unknown condition operation ${condition.operationId}`);
304
- }
305
- if ((condition.type === 'subscription_exist' || condition.type === 'subscription_appear')
306
- && condition.subscriptionId && !subscriptionIds.has(condition.subscriptionId)) {
307
- errors.push(`operation ${operation.id}: unknown condition subscription ${condition.subscriptionId}`);
308
- }
309
- }
310
-
311
- if (!operation.enabled) {
312
- warnings.push(`operation ${operation.id} is disabled`);
313
- }
314
- }
315
-
316
- const topo = topoSortOperations(script.operations);
317
- if (topo.cycles.length > 0) {
318
- for (const cycle of topo.cycles) {
319
- errors.push(`operation dependency cycle: ${cycle.join(' -> ')}`);
320
- }
321
- }
322
-
323
- return {
324
- ok: errors.length === 0,
325
- errors,
326
- warnings,
327
- topologicalOrder: topo.sorted.map((item) => item.id),
328
- };
329
- }
330
-
331
- export function explainAutoscript(script) {
332
- const validation = validateAutoscript(script);
333
- const operationMap = Object.fromEntries(
334
- script.operations.map((operation) => [
335
- operation.id,
336
- {
337
- trigger: operation.trigger,
338
- dependsOn: operation.dependsOn,
339
- impact: operation.impact,
340
- onFailure: operation.onFailure,
341
- retry: operation.retry,
342
- pacing: operation.pacing,
343
- timeoutMs: operation.timeoutMs,
344
- validation: operation.validation,
345
- checkpoint: operation.checkpoint,
346
- },
347
- ]),
348
- );
349
-
350
- return {
351
- ok: validation.ok,
352
- validation,
353
- summary: {
354
- name: script.name,
355
- version: script.version,
356
- subscriptions: script.subscriptions.length,
357
- operations: script.operations.length,
358
- throttle: script.throttle,
359
- },
360
- defaults: script.defaults,
361
- subscriptionOrder: script.subscriptions.map((item) => item.id),
362
- operationOrder: validation.topologicalOrder,
363
- operationMap,
364
- };
365
- }
366
-
367
- export function loadAndValidateAutoscript(filePath) {
368
- const { resolvedPath, payload } = loadAutoscriptFile(filePath);
369
- const script = normalizeAutoscript(payload, resolvedPath);
370
- const validation = validateAutoscript(script);
371
- return {
372
- script,
373
- validation,
374
- sourcePath: resolvedPath,
375
- };
376
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function toArray(value) {
5
+ return Array.isArray(value) ? value : [];
6
+ }
7
+
8
+ function toTrimmedString(value) {
9
+ return typeof value === 'string' ? value.trim() : '';
10
+ }
11
+
12
+ function normalizeTrigger(value) {
13
+ if (!value) return { type: 'startup' };
14
+ if (typeof value === 'string') {
15
+ const token = value.trim();
16
+ if (!token) return { type: 'startup' };
17
+ if (token === 'startup' || token === 'manual') return { type: token };
18
+ const [subscriptionId, event] = token.split('.');
19
+ if (subscriptionId && event) {
20
+ return { type: 'subscription_event', subscriptionId: subscriptionId.trim(), event: event.trim() };
21
+ }
22
+ return { type: 'unknown', raw: token };
23
+ }
24
+ if (typeof value !== 'object') return { type: 'startup' };
25
+ if (value.type === 'startup' || value.type === 'manual') return { type: value.type };
26
+ const subscriptionId = toTrimmedString(value.subscriptionId || value.subscription);
27
+ const event = toTrimmedString(value.event);
28
+ if (subscriptionId && event) {
29
+ return { type: 'subscription_event', subscriptionId, event };
30
+ }
31
+ return { type: 'unknown', raw: value };
32
+ }
33
+
34
+ function normalizeCondition(value) {
35
+ if (!value) return null;
36
+ if (typeof value === 'string') {
37
+ const text = value.trim();
38
+ if (!text) return null;
39
+ if (text.startsWith('operation_done:')) {
40
+ return { type: 'operation_done', operationId: text.slice('operation_done:'.length).trim() };
41
+ }
42
+ if (text.startsWith('subscription_exist:')) {
43
+ return { type: 'subscription_exist', subscriptionId: text.slice('subscription_exist:'.length).trim() };
44
+ }
45
+ if (text.startsWith('subscription_appear:')) {
46
+ return { type: 'subscription_appear', subscriptionId: text.slice('subscription_appear:'.length).trim() };
47
+ }
48
+ return null;
49
+ }
50
+ if (typeof value !== 'object') return null;
51
+ const type = toTrimmedString(value.type);
52
+ if (!type) return null;
53
+ return {
54
+ type,
55
+ operationId: toTrimmedString(value.operationId || value.operation) || null,
56
+ subscriptionId: toTrimmedString(value.subscriptionId || value.subscription) || null,
57
+ };
58
+ }
59
+
60
+ function normalizeRetry(value, defaults = {}) {
61
+ const retry = value && typeof value === 'object' ? value : {};
62
+ const attempts = Math.max(1, Number(retry.attempts ?? defaults.attempts ?? 1) || 1);
63
+ const backoffMs = Math.max(0, Number(retry.backoffMs ?? defaults.backoffMs ?? 0) || 0);
64
+ return { attempts, backoffMs };
65
+ }
66
+
67
+ function normalizeRecovery(value, defaults = {}) {
68
+ const recovery = value && typeof value === 'object' ? value : {};
69
+ const attempts = Math.max(0, Number(recovery.attempts ?? defaults.attempts ?? 0) || 0);
70
+ const actions = toArray(recovery.actions ?? defaults.actions ?? [])
71
+ .map((item) => toTrimmedString(item))
72
+ .filter(Boolean);
73
+ return { attempts, actions };
74
+ }
75
+
76
+ function normalizeValidation(value, defaults = {}) {
77
+ const validation = value && typeof value === 'object' ? value : {};
78
+ const mode = toTrimmedString(validation.mode || defaults.validationMode || 'none') || 'none';
79
+ return {
80
+ mode,
81
+ pre: validation.pre && typeof validation.pre === 'object' ? validation.pre : null,
82
+ post: validation.post && typeof validation.post === 'object' ? validation.post : null,
83
+ };
84
+ }
85
+
86
+ function normalizePacing(value, defaults = {}) {
87
+ const pacing = value && typeof value === 'object' ? value : {};
88
+ const operationMinIntervalMs = Math.max(
89
+ 0,
90
+ Number(
91
+ pacing.operationMinIntervalMs
92
+ ?? pacing.minIntervalMs
93
+ ?? defaults.operationMinIntervalMs
94
+ ?? defaults.minIntervalMs
95
+ ?? 0,
96
+ ) || 0,
97
+ );
98
+ const eventCooldownMs = Math.max(
99
+ 0,
100
+ Number(pacing.eventCooldownMs ?? defaults.eventCooldownMs ?? 0) || 0,
101
+ );
102
+ const jitterMs = Math.max(
103
+ 0,
104
+ Number(pacing.jitterMs ?? defaults.jitterMs ?? 0) || 0,
105
+ );
106
+ const navigationMinIntervalMs = Math.max(
107
+ 0,
108
+ Number(pacing.navigationMinIntervalMs ?? defaults.navigationMinIntervalMs ?? 0) || 0,
109
+ );
110
+ const timeoutMsRaw = pacing.timeoutMs ?? defaults.timeoutMs;
111
+ const timeoutMs = timeoutMsRaw === null || timeoutMsRaw === undefined
112
+ ? null
113
+ : Math.max(0, Number(timeoutMsRaw) || 0);
114
+
115
+ return {
116
+ operationMinIntervalMs,
117
+ eventCooldownMs,
118
+ jitterMs,
119
+ navigationMinIntervalMs,
120
+ timeoutMs,
121
+ };
122
+ }
123
+
124
+ function normalizeSubscription(item, index, defaults) {
125
+ if (!item || typeof item !== 'object') return null;
126
+ const id = toTrimmedString(item.id) || `subscription_${index + 1}`;
127
+ const selector = toTrimmedString(item.selector);
128
+ if (!selector) return null;
129
+ const events = toArray(item.events).map((name) => toTrimmedString(name)).filter(Boolean);
130
+ const pageUrlIncludes = toArray(item.pageUrlIncludes).map((token) => toTrimmedString(token)).filter(Boolean);
131
+ const pageUrlExcludes = toArray(item.pageUrlExcludes).map((token) => toTrimmedString(token)).filter(Boolean);
132
+ return {
133
+ id,
134
+ selector,
135
+ visible: item.visible !== false,
136
+ pageUrlIncludes,
137
+ pageUrlExcludes,
138
+ events: events.length > 0 ? events : ['appear', 'exist', 'disappear', 'change'],
139
+ dependsOn: toArray(item.dependsOn).map((x) => toTrimmedString(x)).filter(Boolean),
140
+ retry: normalizeRetry(item.retry, defaults.retry),
141
+ impact: toTrimmedString(item.impact || defaults.impact || 'subscription') || 'subscription',
142
+ };
143
+ }
144
+
145
+ function normalizeOperation(item, index, defaults) {
146
+ if (!item || typeof item !== 'object') return null;
147
+ const id = toTrimmedString(item.id) || `operation_${index + 1}`;
148
+ const action = toTrimmedString(item.action);
149
+ if (!action) return null;
150
+ const params = item.params && typeof item.params === 'object'
151
+ ? { ...item.params }
152
+ : {
153
+ ...(item.selector ? { selector: item.selector } : {}),
154
+ ...(item.url ? { url: item.url } : {}),
155
+ ...(item.text !== undefined ? { text: item.text } : {}),
156
+ ...(item.script !== undefined ? { script: item.script } : {}),
157
+ ...(item.ms !== undefined ? { ms: item.ms } : {}),
158
+ ...(item.value !== undefined ? { value: item.value } : {}),
159
+ };
160
+
161
+ return {
162
+ id,
163
+ enabled: item.enabled !== false,
164
+ action,
165
+ params,
166
+ trigger: normalizeTrigger(item.trigger),
167
+ dependsOn: toArray(item.dependsOn).map((x) => toTrimmedString(x)).filter(Boolean),
168
+ conditions: toArray(item.conditions).map(normalizeCondition).filter(Boolean),
169
+ retry: normalizeRetry(item.retry, defaults.retry),
170
+ impact: toTrimmedString(item.impact || defaults.impact || 'op') || 'op',
171
+ onFailure: toTrimmedString(item.onFailure || defaults.onFailure || 'chain_stop') || 'chain_stop',
172
+ pacing: normalizePacing(item.pacing, defaults.pacing || {}),
173
+ timeoutMs: (() => {
174
+ const timeoutRaw = item.timeoutMs ?? defaults.timeoutMs;
175
+ if (timeoutRaw === null || timeoutRaw === undefined || timeoutRaw === '') return null;
176
+ return Math.max(0, Number(timeoutRaw) || 0);
177
+ })(),
178
+ validation: normalizeValidation(item.validate || item.validation, defaults),
179
+ checkpoint: {
180
+ containerId: toTrimmedString(item.checkpoint?.containerId || item.containerId) || null,
181
+ targetCheckpoint: toTrimmedString(item.checkpoint?.targetCheckpoint) || null,
182
+ recovery: normalizeRecovery(item.checkpoint?.recovery, defaults.recovery),
183
+ },
184
+ once: item.once !== false,
185
+ oncePerAppear: item.oncePerAppear === true,
186
+ };
187
+ }
188
+
189
+ function topoSortOperations(operations) {
190
+ const byId = new Map(operations.map((op) => [op.id, op]));
191
+ const temp = new Set();
192
+ const visited = new Set();
193
+ const sorted = [];
194
+ const cycles = [];
195
+
196
+ const dfs = (id, trace = []) => {
197
+ if (visited.has(id)) return;
198
+ if (temp.has(id)) {
199
+ const cyclePath = [...trace, id];
200
+ cycles.push(cyclePath);
201
+ return;
202
+ }
203
+ temp.add(id);
204
+ const node = byId.get(id);
205
+ for (const dep of node?.dependsOn || []) {
206
+ if (!byId.has(dep)) continue;
207
+ dfs(dep, [...trace, id]);
208
+ }
209
+ temp.delete(id);
210
+ visited.add(id);
211
+ if (node) sorted.push(node);
212
+ };
213
+
214
+ for (const op of operations) dfs(op.id);
215
+ return { sorted, cycles };
216
+ }
217
+
218
+ export function loadAutoscriptFile(filePath) {
219
+ const resolvedPath = path.resolve(filePath);
220
+ if (!fs.existsSync(resolvedPath)) {
221
+ throw new Error(`Autoscript file not found: ${resolvedPath}`);
222
+ }
223
+ let payload = null;
224
+ try {
225
+ payload = JSON.parse(fs.readFileSync(resolvedPath, 'utf8'));
226
+ } catch (err) {
227
+ throw new Error(`Invalid autoscript JSON: ${err?.message || String(err)}`);
228
+ }
229
+ return { resolvedPath, payload };
230
+ }
231
+
232
+ export function normalizeAutoscript(raw, sourcePath = null) {
233
+ const defaults = raw?.defaults && typeof raw.defaults === 'object' ? raw.defaults : {};
234
+ const subscriptions = toArray(raw?.subscriptions)
235
+ .map((item, index) => normalizeSubscription(item, index, defaults))
236
+ .filter(Boolean);
237
+ const operations = toArray(raw?.operations)
238
+ .map((item, index) => normalizeOperation(item, index, defaults))
239
+ .filter(Boolean);
240
+
241
+ return {
242
+ version: Number(raw?.version || 1),
243
+ sourcePath,
244
+ name: toTrimmedString(raw?.name) || (sourcePath ? path.basename(sourcePath) : 'autoscript'),
245
+ profileId: toTrimmedString(raw?.profileId) || null,
246
+ throttle: Math.max(100, Number(raw?.throttle || 500) || 500),
247
+ defaults: {
248
+ retry: normalizeRetry(defaults.retry, {}),
249
+ impact: toTrimmedString(defaults.impact || 'op') || 'op',
250
+ onFailure: toTrimmedString(defaults.onFailure || 'chain_stop') || 'chain_stop',
251
+ filterMode: toTrimmedString(defaults.filterMode || 'strict') || 'strict',
252
+ validationMode: toTrimmedString(defaults.validationMode || 'none') || 'none',
253
+ recovery: normalizeRecovery(defaults.recovery, {}),
254
+ pacing: normalizePacing(defaults.pacing, {}),
255
+ timeoutMs: (() => {
256
+ const timeoutRaw = defaults.timeoutMs;
257
+ if (timeoutRaw === null || timeoutRaw === undefined || timeoutRaw === '') return null;
258
+ return Math.max(0, Number(timeoutRaw) || 0);
259
+ })(),
260
+ },
261
+ subscriptions,
262
+ operations,
263
+ raw,
264
+ };
265
+ }
266
+
267
+ export function validateAutoscript(script) {
268
+ const errors = [];
269
+ const warnings = [];
270
+ const subscriptionIds = new Set();
271
+ const operationIds = new Set();
272
+
273
+ for (const subscription of script.subscriptions) {
274
+ if (subscriptionIds.has(subscription.id)) {
275
+ errors.push(`duplicate subscription id: ${subscription.id}`);
276
+ }
277
+ subscriptionIds.add(subscription.id);
278
+ }
279
+ for (const operation of script.operations) {
280
+ if (operationIds.has(operation.id)) {
281
+ errors.push(`duplicate operation id: ${operation.id}`);
282
+ }
283
+ operationIds.add(operation.id);
284
+ }
285
+
286
+ for (const operation of script.operations) {
287
+ if (operation.trigger?.type === 'subscription_event') {
288
+ if (!subscriptionIds.has(operation.trigger.subscriptionId)) {
289
+ errors.push(`operation ${operation.id}: unknown trigger subscription ${operation.trigger.subscriptionId}`);
290
+ }
291
+ } else if (operation.trigger?.type === 'unknown') {
292
+ errors.push(`operation ${operation.id}: unsupported trigger ${JSON.stringify(operation.trigger.raw)}`);
293
+ }
294
+
295
+ for (const dep of operation.dependsOn || []) {
296
+ if (!operationIds.has(dep)) {
297
+ errors.push(`operation ${operation.id}: unknown dependency ${dep}`);
298
+ }
299
+ }
300
+
301
+ for (const condition of operation.conditions || []) {
302
+ if (condition.type === 'operation_done' && condition.operationId && !operationIds.has(condition.operationId)) {
303
+ errors.push(`operation ${operation.id}: unknown condition operation ${condition.operationId}`);
304
+ }
305
+ if ((condition.type === 'subscription_exist' || condition.type === 'subscription_appear')
306
+ && condition.subscriptionId && !subscriptionIds.has(condition.subscriptionId)) {
307
+ errors.push(`operation ${operation.id}: unknown condition subscription ${condition.subscriptionId}`);
308
+ }
309
+ }
310
+
311
+ if (!operation.enabled) {
312
+ warnings.push(`operation ${operation.id} is disabled`);
313
+ }
314
+ }
315
+
316
+ const topo = topoSortOperations(script.operations);
317
+ if (topo.cycles.length > 0) {
318
+ for (const cycle of topo.cycles) {
319
+ errors.push(`operation dependency cycle: ${cycle.join(' -> ')}`);
320
+ }
321
+ }
322
+
323
+ return {
324
+ ok: errors.length === 0,
325
+ errors,
326
+ warnings,
327
+ topologicalOrder: topo.sorted.map((item) => item.id),
328
+ };
329
+ }
330
+
331
+ export function explainAutoscript(script) {
332
+ const validation = validateAutoscript(script);
333
+ const operationMap = Object.fromEntries(
334
+ script.operations.map((operation) => [
335
+ operation.id,
336
+ {
337
+ trigger: operation.trigger,
338
+ dependsOn: operation.dependsOn,
339
+ impact: operation.impact,
340
+ onFailure: operation.onFailure,
341
+ retry: operation.retry,
342
+ pacing: operation.pacing,
343
+ timeoutMs: operation.timeoutMs,
344
+ validation: operation.validation,
345
+ checkpoint: operation.checkpoint,
346
+ },
347
+ ]),
348
+ );
349
+
350
+ return {
351
+ ok: validation.ok,
352
+ validation,
353
+ summary: {
354
+ name: script.name,
355
+ version: script.version,
356
+ subscriptions: script.subscriptions.length,
357
+ operations: script.operations.length,
358
+ throttle: script.throttle,
359
+ },
360
+ defaults: script.defaults,
361
+ subscriptionOrder: script.subscriptions.map((item) => item.id),
362
+ operationOrder: validation.topologicalOrder,
363
+ operationMap,
364
+ };
365
+ }
366
+
367
+ export function loadAndValidateAutoscript(filePath) {
368
+ const { resolvedPath, payload } = loadAutoscriptFile(filePath);
369
+ const script = normalizeAutoscript(payload, resolvedPath);
370
+ const validation = validateAutoscript(script);
371
+ return {
372
+ script,
373
+ validation,
374
+ sourcePath: resolvedPath,
375
+ };
376
+ }