@astrasyncai/verification-gateway 2.0.0 → 2.0.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 (91) hide show
  1. package/dist/adapter-interface/interface.d.mts +2 -2
  2. package/dist/adapter-interface/interface.d.ts +2 -2
  3. package/dist/adapters/express.d.mts +2 -2
  4. package/dist/adapters/express.d.ts +2 -2
  5. package/dist/adapters/express.js +118 -5
  6. package/dist/adapters/express.js.map +1 -1
  7. package/dist/adapters/express.mjs +118 -5
  8. package/dist/adapters/express.mjs.map +1 -1
  9. package/dist/adapters/nextjs.d.mts +2 -2
  10. package/dist/adapters/nextjs.d.ts +2 -2
  11. package/dist/adapters/nextjs.js +189 -9
  12. package/dist/adapters/nextjs.js.map +1 -1
  13. package/dist/adapters/nextjs.mjs +189 -9
  14. package/dist/adapters/nextjs.mjs.map +1 -1
  15. package/dist/adapters/sdk.d.mts +2 -2
  16. package/dist/adapters/sdk.d.ts +2 -2
  17. package/dist/adapters/sdk.js +1 -0
  18. package/dist/adapters/sdk.js.map +1 -1
  19. package/dist/adapters/sdk.mjs +1 -0
  20. package/dist/adapters/sdk.mjs.map +1 -1
  21. package/dist/agent/index.d.mts +2 -2
  22. package/dist/agent/index.d.ts +2 -2
  23. package/dist/browser/background.d.mts +2 -0
  24. package/dist/browser/background.d.ts +2 -0
  25. package/dist/browser/background.js +4090 -0
  26. package/dist/browser/background.js.map +1 -0
  27. package/dist/browser/background.mjs +4088 -0
  28. package/dist/browser/background.mjs.map +1 -0
  29. package/dist/browser/browser-adapter.d.mts +10 -6
  30. package/dist/browser/browser-adapter.d.ts +10 -6
  31. package/dist/browser/browser-adapter.js +16 -5
  32. package/dist/browser/browser-adapter.js.map +1 -1
  33. package/dist/browser/browser-adapter.mjs +14 -4
  34. package/dist/browser/browser-adapter.mjs.map +1 -1
  35. package/dist/cli/index.d.mts +2 -2
  36. package/dist/cli/index.d.ts +2 -2
  37. package/dist/cli/index.js +1 -1
  38. package/dist/cli/index.js.map +1 -1
  39. package/dist/cli/index.mjs +1 -1
  40. package/dist/cli/index.mjs.map +1 -1
  41. package/dist/cursor/cursor-adapter.d.mts +3 -4
  42. package/dist/cursor/cursor-adapter.d.ts +3 -4
  43. package/dist/cursor/cursor-adapter.js.map +1 -1
  44. package/dist/cursor/cursor-adapter.mjs.map +1 -1
  45. package/dist/cursor/extension.d.mts +27 -0
  46. package/dist/cursor/extension.d.ts +27 -0
  47. package/dist/cursor/extension.js +4057 -0
  48. package/dist/cursor/extension.js.map +1 -0
  49. package/dist/cursor/extension.mjs +4029 -0
  50. package/dist/cursor/extension.mjs.map +1 -0
  51. package/dist/{express-DIEyq1Tz.d.ts → express-Bcl-uBUE.d.ts} +1 -1
  52. package/dist/{express-Cp4eg77F.d.mts → express-CtwDIZyF.d.mts} +1 -1
  53. package/dist/gateway/gateway.d.mts +2 -2
  54. package/dist/gateway/gateway.d.ts +2 -2
  55. package/dist/gateway/gateway.js +17 -17
  56. package/dist/gateway/gateway.js.map +1 -1
  57. package/dist/gateway/gateway.mjs +11 -18
  58. package/dist/gateway/gateway.mjs.map +1 -1
  59. package/dist/git-trigger/git-hooks.d.mts +2 -2
  60. package/dist/git-trigger/git-hooks.d.ts +2 -2
  61. package/dist/git-trigger/git-hooks.js +1 -2
  62. package/dist/git-trigger/git-hooks.js.map +1 -1
  63. package/dist/git-trigger/git-hooks.mjs +1 -9
  64. package/dist/git-trigger/git-hooks.mjs.map +1 -1
  65. package/dist/{index-CoLebmwv.d.mts → index-B1ThcGZl.d.mts} +1 -1
  66. package/dist/{index-BhTbGU-o.d.mts → index-BY8yQ8N8.d.mts} +1 -1
  67. package/dist/{index-Bhfxq9xI.d.ts → index-CtYSYwn3.d.ts} +1 -1
  68. package/dist/{index-CNkmHmpi.d.ts → index-DnoXfdFd.d.ts} +1 -1
  69. package/dist/index.d.mts +7 -7
  70. package/dist/index.d.ts +7 -7
  71. package/dist/index.js +201 -14
  72. package/dist/index.js.map +1 -1
  73. package/dist/index.mjs +201 -14
  74. package/dist/index.mjs.map +1 -1
  75. package/dist/local-evaluator/evaluator.d.mts +2 -2
  76. package/dist/local-evaluator/evaluator.d.ts +2 -2
  77. package/dist/local-evaluator/evaluator.js.map +1 -1
  78. package/dist/local-evaluator/evaluator.mjs.map +1 -1
  79. package/dist/{nextjs-_C_FcJY5.d.mts → nextjs-BQyMCSx_.d.mts} +1 -1
  80. package/dist/{nextjs-Cag7libc.d.ts → nextjs-CEldnIJ9.d.ts} +1 -1
  81. package/dist/{sdk-DAJahT3p.d.mts → sdk-BhvuJSrH.d.mts} +1 -1
  82. package/dist/{sdk-CMPDFUjo.d.ts → sdk-BlyVSC_S.d.ts} +1 -1
  83. package/dist/transport/index.d.mts +2 -2
  84. package/dist/transport/index.d.ts +2 -2
  85. package/dist/{types-Ce2mFJkO.d.ts → types-79qS7aON.d.ts} +2 -2
  86. package/dist/{types-Bf8pML07.d.mts → types-CxQwJKbd.d.mts} +17 -2
  87. package/dist/{types-Bf8pML07.d.ts → types-CxQwJKbd.d.ts} +17 -2
  88. package/dist/{types-BvpGdsv1.d.mts → types-jJnPXStc.d.mts} +2 -2
  89. package/dist/ui/index.d.mts +1 -1
  90. package/dist/ui/index.d.ts +1 -1
  91. package/package.json +3 -2
@@ -0,0 +1,4057 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/cursor/extension.ts
21
+ var extension_exports = {};
22
+ __export(extension_exports, {
23
+ activate: () => activate,
24
+ deactivate: () => deactivate
25
+ });
26
+ module.exports = __toCommonJS(extension_exports);
27
+
28
+ // src/adapter-interface/interface.ts
29
+ var ADAPTER_INTERFACE_VERSION = 1;
30
+
31
+ // src/adapter-interface/purpose-mapping.ts
32
+ var TOOL_PURPOSE_MAP = {
33
+ // Shell
34
+ shell_exec: "shell.exec",
35
+ run_command: "shell.exec",
36
+ execute: "shell.exec",
37
+ terminal_exec: "shell.exec",
38
+ run_terminal_command: "shell.exec",
39
+ // File read
40
+ file_read: "file.read",
41
+ read_file: "file.read",
42
+ // File write
43
+ file_write: "file.write",
44
+ write_file: "file.write",
45
+ create_file: "file.write",
46
+ edit_file: "file.write",
47
+ // File delete
48
+ file_delete: "file.delete",
49
+ delete_file: "file.delete",
50
+ // Network
51
+ http_request: "network.request",
52
+ fetch: "network.request",
53
+ web_request: "network.request",
54
+ // Email
55
+ send_email: "email.send",
56
+ read_email: "email.read",
57
+ // Calendar
58
+ create_event: "calendar.create",
59
+ // Database
60
+ query_database: "database.query",
61
+ write_database: "database.write",
62
+ // Payment
63
+ payment_execute: "payment.execute"
64
+ };
65
+ function mapToolToPurpose(toolName) {
66
+ return TOOL_PURPOSE_MAP[toolName] || `tool.${toolName}`;
67
+ }
68
+ function extractTarget(toolName, args) {
69
+ const purpose = mapToolToPurpose(toolName);
70
+ if (purpose.startsWith("shell.")) {
71
+ return String(args.command || args.cmd || args.script || "");
72
+ }
73
+ if (purpose.startsWith("file.")) {
74
+ return String(args.path || args.file || args.filename || args.file_path || "");
75
+ }
76
+ if (purpose.startsWith("network.")) {
77
+ return String(args.url || args.endpoint || args.uri || "");
78
+ }
79
+ if (purpose.startsWith("email.")) {
80
+ return String(args.to || args.recipient || args.address || "");
81
+ }
82
+ if (purpose.startsWith("database.")) {
83
+ return String(args.query || args.table || "");
84
+ }
85
+ if (purpose.startsWith("payment.")) {
86
+ return String(args.description || args.merchant || args.amount || "");
87
+ }
88
+ if (args.command) return String(args.command);
89
+ if (args.path) return String(args.path);
90
+ if (args.url) return String(args.url);
91
+ for (const val of Object.values(args)) {
92
+ if (typeof val === "string" && val.length > 0) return val;
93
+ }
94
+ return toolName;
95
+ }
96
+ function extractNetworkDomains(target) {
97
+ try {
98
+ if (target.startsWith("http://") || target.startsWith("https://")) {
99
+ const url = new URL(target);
100
+ return [url.hostname];
101
+ }
102
+ } catch {
103
+ }
104
+ return void 0;
105
+ }
106
+
107
+ // src/cursor/cursor-adapter.ts
108
+ var CursorAdapter = class {
109
+ constructor(options) {
110
+ this.interfaceVersion = ADAPTER_INTERFACE_VERSION;
111
+ this.disposables = [];
112
+ this.outputChannel = null;
113
+ this._isRunning = false;
114
+ this.onApprovalRequired = options?.onApprovalRequired ?? (async () => false);
115
+ if (options?.vscode) {
116
+ this.vscode = options.vscode;
117
+ }
118
+ }
119
+ get isRunning() {
120
+ return this._isRunning;
121
+ }
122
+ async initialize(config) {
123
+ this.gateway = config.gateway;
124
+ if (config.adapterOptions.vscode) {
125
+ this.vscode = config.adapterOptions.vscode;
126
+ }
127
+ if (!this.vscode) {
128
+ throw new Error("CursorAdapter requires vscode API \u2014 pass it via adapterOptions.vscode");
129
+ }
130
+ this.outputChannel = this.vscode.window.createOutputChannel("AstraSync Local Guard");
131
+ this.disposables.push(
132
+ this.vscode.workspace.onDidCreateFiles((e) => {
133
+ for (const file of e.files) {
134
+ this.evaluateFileAction("file_write", file.fsPath);
135
+ }
136
+ })
137
+ );
138
+ this.disposables.push(
139
+ this.vscode.workspace.onDidDeleteFiles((e) => {
140
+ for (const file of e.files) {
141
+ this.evaluateFileAction("file_delete", file.fsPath);
142
+ }
143
+ })
144
+ );
145
+ this.disposables.push(
146
+ this.vscode.workspace.onDidSaveTextDocument((doc) => {
147
+ this.evaluateFileAction("file_write", doc.fileName);
148
+ })
149
+ );
150
+ this.disposables.push(
151
+ this.vscode.commands.registerCommand("astrasync.status", () => {
152
+ this.outputChannel?.show();
153
+ this.vscode.window.showInformationMessage("AstraSync Local Guard is active");
154
+ })
155
+ );
156
+ this._isRunning = true;
157
+ this.log("AstraSync Local Guard for Cursor \u2014 initialized");
158
+ }
159
+ async shutdown() {
160
+ for (const d of this.disposables) {
161
+ d.dispose();
162
+ }
163
+ this.disposables = [];
164
+ this.outputChannel?.dispose();
165
+ this.outputChannel = null;
166
+ this._isRunning = false;
167
+ }
168
+ async interceptAction(action) {
169
+ const raw = action.raw;
170
+ if (!raw.type) {
171
+ return { intercepted: false, skipReason: "No action type" };
172
+ }
173
+ const context = this.extractContext(action);
174
+ return { intercepted: true, context };
175
+ }
176
+ extractContext(action) {
177
+ const raw = action.raw;
178
+ let toolName;
179
+ const args = {};
180
+ switch (raw.type) {
181
+ case "file.create":
182
+ case "file.save":
183
+ toolName = "file_write";
184
+ args.path = raw.path || "";
185
+ break;
186
+ case "file.delete":
187
+ toolName = "file_delete";
188
+ args.path = raw.path || "";
189
+ break;
190
+ case "file.read":
191
+ toolName = "file_read";
192
+ args.path = raw.path || "";
193
+ break;
194
+ case "terminal.exec":
195
+ toolName = "shell_exec";
196
+ args.command = raw.command || "";
197
+ break;
198
+ case "network.request":
199
+ toolName = "http_request";
200
+ args.url = raw.url || "";
201
+ break;
202
+ default:
203
+ toolName = raw.type;
204
+ }
205
+ const purpose = mapToolToPurpose(toolName);
206
+ const target = extractTarget(toolName, args);
207
+ const networkAccess = extractNetworkDomains(target);
208
+ return {
209
+ purpose,
210
+ action: toolName,
211
+ target,
212
+ ...networkAccess && { networkAccess }
213
+ };
214
+ }
215
+ async enforceDecision(decision) {
216
+ switch (decision.recommendation) {
217
+ case "DENY":
218
+ this.log(`BLOCKED: ${decision.reason}`);
219
+ this.vscode.window.showErrorMessage(
220
+ `AstraSync blocked action: ${decision.reason}`
221
+ );
222
+ break;
223
+ case "MANUAL_REVIEW":
224
+ this.log(`REVIEW: ${decision.reason}`);
225
+ break;
226
+ case "ALLOW":
227
+ break;
228
+ }
229
+ }
230
+ // =====================================================================
231
+ // Internal helpers
232
+ // =====================================================================
233
+ async evaluateFileAction(toolName, filePath) {
234
+ const action = {
235
+ raw: {
236
+ type: toolName === "file_delete" ? "file.delete" : "file.save",
237
+ path: filePath
238
+ },
239
+ platform: "cursor",
240
+ timestamp: /* @__PURE__ */ new Date()
241
+ };
242
+ const interception = await this.interceptAction(action);
243
+ if (!interception.intercepted || !interception.context) return;
244
+ const decision = await this.gateway.evaluate(interception.context);
245
+ if (decision.recommendation === "DENY") {
246
+ await this.enforceDecision(decision);
247
+ } else if (decision.recommendation === "MANUAL_REVIEW") {
248
+ const approved = await this.handleApproval(interception.context, decision);
249
+ if (!approved) {
250
+ await this.enforceDecision({ ...decision, recommendation: "DENY" });
251
+ }
252
+ }
253
+ this.log(`${decision.recommendation}: ${interception.context.purpose} -> ${interception.context.target}`);
254
+ }
255
+ async handleApproval(context, decision) {
256
+ if (this.onApprovalRequired) {
257
+ return this.onApprovalRequired(context, decision);
258
+ }
259
+ const choice = await this.vscode.window.showWarningMessage(
260
+ `AstraSync: ${decision.reason}. Allow?`,
261
+ "Allow",
262
+ "Deny"
263
+ );
264
+ return choice === "Allow";
265
+ }
266
+ log(message) {
267
+ this.outputChannel?.appendLine(`[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}`);
268
+ }
269
+ };
270
+
271
+ // src/gateway/types.ts
272
+ var HIGH_RISK_COMMANDS = [
273
+ "rm",
274
+ "rmdir",
275
+ "dd",
276
+ "mkfs",
277
+ "chmod",
278
+ "chown",
279
+ "sudo",
280
+ "su",
281
+ "curl",
282
+ "wget",
283
+ "nc",
284
+ "netcat",
285
+ "ssh",
286
+ "scp",
287
+ "rsync",
288
+ "git push",
289
+ "npm publish",
290
+ "docker",
291
+ "kubectl"
292
+ ];
293
+ var SENSITIVE_PATHS = [
294
+ ".ssh",
295
+ ".aws",
296
+ ".gnupg",
297
+ ".env",
298
+ "credentials",
299
+ "secrets",
300
+ "password",
301
+ ".git/config",
302
+ "/etc",
303
+ "/var",
304
+ "/root",
305
+ "id_rsa",
306
+ ".npmrc",
307
+ ".pypirc"
308
+ ];
309
+
310
+ // src/local-evaluator/evaluator.ts
311
+ var LocalEvaluator = class {
312
+ constructor(policy) {
313
+ this.requestCounts = /* @__PURE__ */ new Map();
314
+ this.policy = policy;
315
+ }
316
+ /**
317
+ * Update the policy (e.g. after hot-reload or sync).
318
+ */
319
+ updatePolicy(policy) {
320
+ this.policy = policy;
321
+ }
322
+ /**
323
+ * Evaluate an action context against the loaded policy.
324
+ */
325
+ evaluate(context) {
326
+ const purposeRule = this.policy.purposes.find((p) => p.id === context.purpose);
327
+ if (!purposeRule) {
328
+ return { recommendation: "DENY", reason: "Purpose not in policy" };
329
+ }
330
+ if (!purposeRule.allowed) {
331
+ return { recommendation: "DENY", reason: "Purpose explicitly blocked" };
332
+ }
333
+ if (purposeRule.targets && !this.matchesAnyPattern(context.target, purposeRule.targets)) {
334
+ return { recommendation: "DENY", reason: "Target not in allowed list" };
335
+ }
336
+ if (purposeRule.blockedPatterns && this.matchesAnyPattern(context.target, purposeRule.blockedPatterns)) {
337
+ return { recommendation: "DENY", reason: "Target matches blocked pattern" };
338
+ }
339
+ const scopeBlock = this.checkScopeBlock(context);
340
+ if (scopeBlock) {
341
+ return { recommendation: "DENY", reason: scopeBlock };
342
+ }
343
+ const limitViolation = this.checkLimits(context);
344
+ if (limitViolation) {
345
+ return { recommendation: "DENY", reason: limitViolation };
346
+ }
347
+ if (context.purpose === "sub_agent.spawn" && this.policy.selfInstantiation) {
348
+ if (!this.policy.selfInstantiation.allowed) {
349
+ return { recommendation: "DENY", reason: "Sub-agent spawning is not allowed" };
350
+ }
351
+ const depth = context.metadata?.subAgentDepth || 0;
352
+ if (this.policy.selfInstantiation.maxDepth !== void 0 && depth >= this.policy.selfInstantiation.maxDepth) {
353
+ return { recommendation: "DENY", reason: `Sub-agent depth ${depth} exceeds max depth ${this.policy.selfInstantiation.maxDepth}` };
354
+ }
355
+ }
356
+ if (purposeRule.requiresApproval) {
357
+ return { recommendation: "MANUAL_REVIEW", reason: "Purpose requires approval" };
358
+ }
359
+ const riskDecision = this.checkRiskThresholds(context);
360
+ if (riskDecision) {
361
+ return riskDecision;
362
+ }
363
+ return {
364
+ recommendation: "ALLOW",
365
+ reason: "All PDLSS checks passed",
366
+ evaluatedDimensions: {
367
+ purpose: true,
368
+ scope: !!this.policy.scope,
369
+ limits: !!this.policy.limits,
370
+ riskThresholds: !!this.policy.riskThresholds
371
+ }
372
+ };
373
+ }
374
+ checkScopeBlock(context) {
375
+ const scope = this.policy.scope;
376
+ if (!scope) return null;
377
+ if (scope.blockedDomains) {
378
+ const targetDomain = this.extractDomain(context.target);
379
+ if (this.matchesAnyPattern(targetDomain, scope.blockedDomains)) {
380
+ return `Target blocked by scope: ${context.target}`;
381
+ }
382
+ if (context.networkAccess) {
383
+ for (const domain of context.networkAccess) {
384
+ if (this.matchesAnyPattern(this.extractDomain(domain), scope.blockedDomains)) {
385
+ return `Domain blocked by scope: ${domain}`;
386
+ }
387
+ }
388
+ }
389
+ }
390
+ if (scope.blockedResources && this.matchesAnyPattern(context.target, scope.blockedResources)) {
391
+ return `Resource blocked by scope: ${context.target}`;
392
+ }
393
+ if (scope.allowedDomains && context.networkAccess) {
394
+ for (const domain of context.networkAccess) {
395
+ if (!this.matchesAnyPattern(this.extractDomain(domain), scope.allowedDomains)) {
396
+ return `Domain not in allowed list: ${domain}`;
397
+ }
398
+ }
399
+ }
400
+ return null;
401
+ }
402
+ checkLimits(context) {
403
+ const limits = this.policy.limits;
404
+ if (!limits) return null;
405
+ if (limits.maxTransactionAmount !== void 0 && context.transactionValue !== void 0) {
406
+ if (context.transactionValue > limits.maxTransactionAmount) {
407
+ return `Transaction value ${context.transactionValue} exceeds limit ${limits.maxTransactionAmount}`;
408
+ }
409
+ }
410
+ if (limits.maxRequestsPerHour !== void 0) {
411
+ const key = context.purpose;
412
+ const now = Date.now();
413
+ const entry = this.requestCounts.get(key);
414
+ const hourMs = 36e5;
415
+ if (!entry || now - entry.windowStart > hourMs) {
416
+ this.requestCounts.set(key, { count: 1, windowStart: now });
417
+ } else {
418
+ entry.count++;
419
+ if (entry.count > limits.maxRequestsPerHour) {
420
+ return `Rate limit exceeded: ${entry.count}/${limits.maxRequestsPerHour} requests per hour`;
421
+ }
422
+ }
423
+ }
424
+ return null;
425
+ }
426
+ checkRiskThresholds(context) {
427
+ if (!this.policy.riskThresholds) return null;
428
+ const riskScore = this.calculateRiskScore(context);
429
+ const thresholds = this.policy.riskThresholds;
430
+ if (riskScore >= thresholds.autoBlock.min) {
431
+ return { recommendation: "DENY", reason: `Risk score ${riskScore} exceeds block threshold` };
432
+ }
433
+ if (riskScore >= thresholds.requireApproval.min) {
434
+ return { recommendation: "MANUAL_REVIEW", reason: `Risk score ${riskScore} requires approval` };
435
+ }
436
+ return null;
437
+ }
438
+ calculateRiskScore(context) {
439
+ let score = 0;
440
+ if (context.riskFactors?.length) {
441
+ const severityScores = {
442
+ low: 10,
443
+ medium: 40,
444
+ high: 70,
445
+ critical: 90
446
+ };
447
+ for (const factor of context.riskFactors) {
448
+ const factorScore = severityScores[factor.severity] || 0;
449
+ if (factorScore > score) score = factorScore;
450
+ }
451
+ return score;
452
+ }
453
+ if (context.purpose === "shell.exec" && context.target) {
454
+ const targetLower = context.target.toLowerCase();
455
+ for (const cmd of HIGH_RISK_COMMANDS) {
456
+ if (targetLower.startsWith(cmd) || targetLower.includes(` ${cmd} `) || targetLower.includes(` ${cmd}`)) {
457
+ score = Math.max(score, 80);
458
+ break;
459
+ }
460
+ }
461
+ }
462
+ if ((context.purpose === "file.read" || context.purpose === "file.write" || context.purpose === "file.delete") && context.target) {
463
+ const targetLower = context.target.toLowerCase();
464
+ for (const sensitivePath of SENSITIVE_PATHS) {
465
+ if (targetLower.includes(sensitivePath.toLowerCase())) {
466
+ score = Math.max(score, 50);
467
+ break;
468
+ }
469
+ }
470
+ }
471
+ return score;
472
+ }
473
+ /**
474
+ * Extract domain from a URL-like string (strips protocol and path).
475
+ */
476
+ extractDomain(value) {
477
+ let domain = value;
478
+ const protoIndex = domain.indexOf("://");
479
+ if (protoIndex !== -1) domain = domain.slice(protoIndex + 3);
480
+ const slashIndex = domain.indexOf("/");
481
+ if (slashIndex !== -1) domain = domain.slice(0, slashIndex);
482
+ const colonIndex = domain.indexOf(":");
483
+ if (colonIndex !== -1) domain = domain.slice(0, colonIndex);
484
+ return domain;
485
+ }
486
+ /**
487
+ * Check if a value matches any of the given glob patterns.
488
+ */
489
+ matchesAnyPattern(value, patterns) {
490
+ return patterns.some((pattern) => this.matchGlob(value, pattern));
491
+ }
492
+ /**
493
+ * Simple glob pattern matching.
494
+ * Supports * (matches any characters including / and spaces) and ? (single char).
495
+ * Uses the same approach as the backend's matchGlobPattern.
496
+ */
497
+ matchGlob(value, pattern) {
498
+ if (pattern === value) return true;
499
+ const regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
500
+ try {
501
+ return new RegExp(`^${regexStr}$`, "i").test(value);
502
+ } catch {
503
+ return false;
504
+ }
505
+ }
506
+ };
507
+
508
+ // ../../node_modules/js-yaml/dist/js-yaml.mjs
509
+ function isNothing(subject) {
510
+ return typeof subject === "undefined" || subject === null;
511
+ }
512
+ function isObject(subject) {
513
+ return typeof subject === "object" && subject !== null;
514
+ }
515
+ function toArray(sequence) {
516
+ if (Array.isArray(sequence)) return sequence;
517
+ else if (isNothing(sequence)) return [];
518
+ return [sequence];
519
+ }
520
+ function extend(target, source) {
521
+ var index, length, key, sourceKeys;
522
+ if (source) {
523
+ sourceKeys = Object.keys(source);
524
+ for (index = 0, length = sourceKeys.length; index < length; index += 1) {
525
+ key = sourceKeys[index];
526
+ target[key] = source[key];
527
+ }
528
+ }
529
+ return target;
530
+ }
531
+ function repeat(string, count) {
532
+ var result = "", cycle;
533
+ for (cycle = 0; cycle < count; cycle += 1) {
534
+ result += string;
535
+ }
536
+ return result;
537
+ }
538
+ function isNegativeZero(number) {
539
+ return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
540
+ }
541
+ var isNothing_1 = isNothing;
542
+ var isObject_1 = isObject;
543
+ var toArray_1 = toArray;
544
+ var repeat_1 = repeat;
545
+ var isNegativeZero_1 = isNegativeZero;
546
+ var extend_1 = extend;
547
+ var common = {
548
+ isNothing: isNothing_1,
549
+ isObject: isObject_1,
550
+ toArray: toArray_1,
551
+ repeat: repeat_1,
552
+ isNegativeZero: isNegativeZero_1,
553
+ extend: extend_1
554
+ };
555
+ function formatError(exception2, compact) {
556
+ var where = "", message = exception2.reason || "(unknown reason)";
557
+ if (!exception2.mark) return message;
558
+ if (exception2.mark.name) {
559
+ where += 'in "' + exception2.mark.name + '" ';
560
+ }
561
+ where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")";
562
+ if (!compact && exception2.mark.snippet) {
563
+ where += "\n\n" + exception2.mark.snippet;
564
+ }
565
+ return message + " " + where;
566
+ }
567
+ function YAMLException$1(reason, mark) {
568
+ Error.call(this);
569
+ this.name = "YAMLException";
570
+ this.reason = reason;
571
+ this.mark = mark;
572
+ this.message = formatError(this, false);
573
+ if (Error.captureStackTrace) {
574
+ Error.captureStackTrace(this, this.constructor);
575
+ } else {
576
+ this.stack = new Error().stack || "";
577
+ }
578
+ }
579
+ YAMLException$1.prototype = Object.create(Error.prototype);
580
+ YAMLException$1.prototype.constructor = YAMLException$1;
581
+ YAMLException$1.prototype.toString = function toString(compact) {
582
+ return this.name + ": " + formatError(this, compact);
583
+ };
584
+ var exception = YAMLException$1;
585
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
586
+ var head = "";
587
+ var tail = "";
588
+ var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
589
+ if (position - lineStart > maxHalfLength) {
590
+ head = " ... ";
591
+ lineStart = position - maxHalfLength + head.length;
592
+ }
593
+ if (lineEnd - position > maxHalfLength) {
594
+ tail = " ...";
595
+ lineEnd = position + maxHalfLength - tail.length;
596
+ }
597
+ return {
598
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
599
+ pos: position - lineStart + head.length
600
+ // relative position
601
+ };
602
+ }
603
+ function padStart(string, max) {
604
+ return common.repeat(" ", max - string.length) + string;
605
+ }
606
+ function makeSnippet(mark, options) {
607
+ options = Object.create(options || null);
608
+ if (!mark.buffer) return null;
609
+ if (!options.maxLength) options.maxLength = 79;
610
+ if (typeof options.indent !== "number") options.indent = 1;
611
+ if (typeof options.linesBefore !== "number") options.linesBefore = 3;
612
+ if (typeof options.linesAfter !== "number") options.linesAfter = 2;
613
+ var re = /\r?\n|\r|\0/g;
614
+ var lineStarts = [0];
615
+ var lineEnds = [];
616
+ var match;
617
+ var foundLineNo = -1;
618
+ while (match = re.exec(mark.buffer)) {
619
+ lineEnds.push(match.index);
620
+ lineStarts.push(match.index + match[0].length);
621
+ if (mark.position <= match.index && foundLineNo < 0) {
622
+ foundLineNo = lineStarts.length - 2;
623
+ }
624
+ }
625
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
626
+ var result = "", i, line;
627
+ var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
628
+ var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
629
+ for (i = 1; i <= options.linesBefore; i++) {
630
+ if (foundLineNo - i < 0) break;
631
+ line = getLine(
632
+ mark.buffer,
633
+ lineStarts[foundLineNo - i],
634
+ lineEnds[foundLineNo - i],
635
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
636
+ maxLineLength
637
+ );
638
+ result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result;
639
+ }
640
+ line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
641
+ result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
642
+ result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
643
+ for (i = 1; i <= options.linesAfter; i++) {
644
+ if (foundLineNo + i >= lineEnds.length) break;
645
+ line = getLine(
646
+ mark.buffer,
647
+ lineStarts[foundLineNo + i],
648
+ lineEnds[foundLineNo + i],
649
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
650
+ maxLineLength
651
+ );
652
+ result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + "\n";
653
+ }
654
+ return result.replace(/\n$/, "");
655
+ }
656
+ var snippet = makeSnippet;
657
+ var TYPE_CONSTRUCTOR_OPTIONS = [
658
+ "kind",
659
+ "multi",
660
+ "resolve",
661
+ "construct",
662
+ "instanceOf",
663
+ "predicate",
664
+ "represent",
665
+ "representName",
666
+ "defaultStyle",
667
+ "styleAliases"
668
+ ];
669
+ var YAML_NODE_KINDS = [
670
+ "scalar",
671
+ "sequence",
672
+ "mapping"
673
+ ];
674
+ function compileStyleAliases(map2) {
675
+ var result = {};
676
+ if (map2 !== null) {
677
+ Object.keys(map2).forEach(function(style) {
678
+ map2[style].forEach(function(alias) {
679
+ result[String(alias)] = style;
680
+ });
681
+ });
682
+ }
683
+ return result;
684
+ }
685
+ function Type$1(tag, options) {
686
+ options = options || {};
687
+ Object.keys(options).forEach(function(name) {
688
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
689
+ throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
690
+ }
691
+ });
692
+ this.options = options;
693
+ this.tag = tag;
694
+ this.kind = options["kind"] || null;
695
+ this.resolve = options["resolve"] || function() {
696
+ return true;
697
+ };
698
+ this.construct = options["construct"] || function(data) {
699
+ return data;
700
+ };
701
+ this.instanceOf = options["instanceOf"] || null;
702
+ this.predicate = options["predicate"] || null;
703
+ this.represent = options["represent"] || null;
704
+ this.representName = options["representName"] || null;
705
+ this.defaultStyle = options["defaultStyle"] || null;
706
+ this.multi = options["multi"] || false;
707
+ this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
708
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
709
+ throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
710
+ }
711
+ }
712
+ var type = Type$1;
713
+ function compileList(schema2, name) {
714
+ var result = [];
715
+ schema2[name].forEach(function(currentType) {
716
+ var newIndex = result.length;
717
+ result.forEach(function(previousType, previousIndex) {
718
+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
719
+ newIndex = previousIndex;
720
+ }
721
+ });
722
+ result[newIndex] = currentType;
723
+ });
724
+ return result;
725
+ }
726
+ function compileMap() {
727
+ var result = {
728
+ scalar: {},
729
+ sequence: {},
730
+ mapping: {},
731
+ fallback: {},
732
+ multi: {
733
+ scalar: [],
734
+ sequence: [],
735
+ mapping: [],
736
+ fallback: []
737
+ }
738
+ }, index, length;
739
+ function collectType(type2) {
740
+ if (type2.multi) {
741
+ result.multi[type2.kind].push(type2);
742
+ result.multi["fallback"].push(type2);
743
+ } else {
744
+ result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
745
+ }
746
+ }
747
+ for (index = 0, length = arguments.length; index < length; index += 1) {
748
+ arguments[index].forEach(collectType);
749
+ }
750
+ return result;
751
+ }
752
+ function Schema$1(definition) {
753
+ return this.extend(definition);
754
+ }
755
+ Schema$1.prototype.extend = function extend2(definition) {
756
+ var implicit = [];
757
+ var explicit = [];
758
+ if (definition instanceof type) {
759
+ explicit.push(definition);
760
+ } else if (Array.isArray(definition)) {
761
+ explicit = explicit.concat(definition);
762
+ } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
763
+ if (definition.implicit) implicit = implicit.concat(definition.implicit);
764
+ if (definition.explicit) explicit = explicit.concat(definition.explicit);
765
+ } else {
766
+ throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
767
+ }
768
+ implicit.forEach(function(type$1) {
769
+ if (!(type$1 instanceof type)) {
770
+ throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
771
+ }
772
+ if (type$1.loadKind && type$1.loadKind !== "scalar") {
773
+ throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
774
+ }
775
+ if (type$1.multi) {
776
+ throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
777
+ }
778
+ });
779
+ explicit.forEach(function(type$1) {
780
+ if (!(type$1 instanceof type)) {
781
+ throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
782
+ }
783
+ });
784
+ var result = Object.create(Schema$1.prototype);
785
+ result.implicit = (this.implicit || []).concat(implicit);
786
+ result.explicit = (this.explicit || []).concat(explicit);
787
+ result.compiledImplicit = compileList(result, "implicit");
788
+ result.compiledExplicit = compileList(result, "explicit");
789
+ result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
790
+ return result;
791
+ };
792
+ var schema = Schema$1;
793
+ var str = new type("tag:yaml.org,2002:str", {
794
+ kind: "scalar",
795
+ construct: function(data) {
796
+ return data !== null ? data : "";
797
+ }
798
+ });
799
+ var seq = new type("tag:yaml.org,2002:seq", {
800
+ kind: "sequence",
801
+ construct: function(data) {
802
+ return data !== null ? data : [];
803
+ }
804
+ });
805
+ var map = new type("tag:yaml.org,2002:map", {
806
+ kind: "mapping",
807
+ construct: function(data) {
808
+ return data !== null ? data : {};
809
+ }
810
+ });
811
+ var failsafe = new schema({
812
+ explicit: [
813
+ str,
814
+ seq,
815
+ map
816
+ ]
817
+ });
818
+ function resolveYamlNull(data) {
819
+ if (data === null) return true;
820
+ var max = data.length;
821
+ return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
822
+ }
823
+ function constructYamlNull() {
824
+ return null;
825
+ }
826
+ function isNull(object) {
827
+ return object === null;
828
+ }
829
+ var _null = new type("tag:yaml.org,2002:null", {
830
+ kind: "scalar",
831
+ resolve: resolveYamlNull,
832
+ construct: constructYamlNull,
833
+ predicate: isNull,
834
+ represent: {
835
+ canonical: function() {
836
+ return "~";
837
+ },
838
+ lowercase: function() {
839
+ return "null";
840
+ },
841
+ uppercase: function() {
842
+ return "NULL";
843
+ },
844
+ camelcase: function() {
845
+ return "Null";
846
+ },
847
+ empty: function() {
848
+ return "";
849
+ }
850
+ },
851
+ defaultStyle: "lowercase"
852
+ });
853
+ function resolveYamlBoolean(data) {
854
+ if (data === null) return false;
855
+ var max = data.length;
856
+ return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
857
+ }
858
+ function constructYamlBoolean(data) {
859
+ return data === "true" || data === "True" || data === "TRUE";
860
+ }
861
+ function isBoolean(object) {
862
+ return Object.prototype.toString.call(object) === "[object Boolean]";
863
+ }
864
+ var bool = new type("tag:yaml.org,2002:bool", {
865
+ kind: "scalar",
866
+ resolve: resolveYamlBoolean,
867
+ construct: constructYamlBoolean,
868
+ predicate: isBoolean,
869
+ represent: {
870
+ lowercase: function(object) {
871
+ return object ? "true" : "false";
872
+ },
873
+ uppercase: function(object) {
874
+ return object ? "TRUE" : "FALSE";
875
+ },
876
+ camelcase: function(object) {
877
+ return object ? "True" : "False";
878
+ }
879
+ },
880
+ defaultStyle: "lowercase"
881
+ });
882
+ function isHexCode(c) {
883
+ return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
884
+ }
885
+ function isOctCode(c) {
886
+ return 48 <= c && c <= 55;
887
+ }
888
+ function isDecCode(c) {
889
+ return 48 <= c && c <= 57;
890
+ }
891
+ function resolveYamlInteger(data) {
892
+ if (data === null) return false;
893
+ var max = data.length, index = 0, hasDigits = false, ch;
894
+ if (!max) return false;
895
+ ch = data[index];
896
+ if (ch === "-" || ch === "+") {
897
+ ch = data[++index];
898
+ }
899
+ if (ch === "0") {
900
+ if (index + 1 === max) return true;
901
+ ch = data[++index];
902
+ if (ch === "b") {
903
+ index++;
904
+ for (; index < max; index++) {
905
+ ch = data[index];
906
+ if (ch === "_") continue;
907
+ if (ch !== "0" && ch !== "1") return false;
908
+ hasDigits = true;
909
+ }
910
+ return hasDigits && ch !== "_";
911
+ }
912
+ if (ch === "x") {
913
+ index++;
914
+ for (; index < max; index++) {
915
+ ch = data[index];
916
+ if (ch === "_") continue;
917
+ if (!isHexCode(data.charCodeAt(index))) return false;
918
+ hasDigits = true;
919
+ }
920
+ return hasDigits && ch !== "_";
921
+ }
922
+ if (ch === "o") {
923
+ index++;
924
+ for (; index < max; index++) {
925
+ ch = data[index];
926
+ if (ch === "_") continue;
927
+ if (!isOctCode(data.charCodeAt(index))) return false;
928
+ hasDigits = true;
929
+ }
930
+ return hasDigits && ch !== "_";
931
+ }
932
+ }
933
+ if (ch === "_") return false;
934
+ for (; index < max; index++) {
935
+ ch = data[index];
936
+ if (ch === "_") continue;
937
+ if (!isDecCode(data.charCodeAt(index))) {
938
+ return false;
939
+ }
940
+ hasDigits = true;
941
+ }
942
+ if (!hasDigits || ch === "_") return false;
943
+ return true;
944
+ }
945
+ function constructYamlInteger(data) {
946
+ var value = data, sign = 1, ch;
947
+ if (value.indexOf("_") !== -1) {
948
+ value = value.replace(/_/g, "");
949
+ }
950
+ ch = value[0];
951
+ if (ch === "-" || ch === "+") {
952
+ if (ch === "-") sign = -1;
953
+ value = value.slice(1);
954
+ ch = value[0];
955
+ }
956
+ if (value === "0") return 0;
957
+ if (ch === "0") {
958
+ if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
959
+ if (value[1] === "x") return sign * parseInt(value.slice(2), 16);
960
+ if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
961
+ }
962
+ return sign * parseInt(value, 10);
963
+ }
964
+ function isInteger(object) {
965
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
966
+ }
967
+ var int = new type("tag:yaml.org,2002:int", {
968
+ kind: "scalar",
969
+ resolve: resolveYamlInteger,
970
+ construct: constructYamlInteger,
971
+ predicate: isInteger,
972
+ represent: {
973
+ binary: function(obj) {
974
+ return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
975
+ },
976
+ octal: function(obj) {
977
+ return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
978
+ },
979
+ decimal: function(obj) {
980
+ return obj.toString(10);
981
+ },
982
+ /* eslint-disable max-len */
983
+ hexadecimal: function(obj) {
984
+ return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
985
+ }
986
+ },
987
+ defaultStyle: "decimal",
988
+ styleAliases: {
989
+ binary: [2, "bin"],
990
+ octal: [8, "oct"],
991
+ decimal: [10, "dec"],
992
+ hexadecimal: [16, "hex"]
993
+ }
994
+ });
995
+ var YAML_FLOAT_PATTERN = new RegExp(
996
+ // 2.5e4, 2.5 and integers
997
+ "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
998
+ );
999
+ function resolveYamlFloat(data) {
1000
+ if (data === null) return false;
1001
+ if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
1002
+ // Probably should update regexp & check speed
1003
+ data[data.length - 1] === "_") {
1004
+ return false;
1005
+ }
1006
+ return true;
1007
+ }
1008
+ function constructYamlFloat(data) {
1009
+ var value, sign;
1010
+ value = data.replace(/_/g, "").toLowerCase();
1011
+ sign = value[0] === "-" ? -1 : 1;
1012
+ if ("+-".indexOf(value[0]) >= 0) {
1013
+ value = value.slice(1);
1014
+ }
1015
+ if (value === ".inf") {
1016
+ return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
1017
+ } else if (value === ".nan") {
1018
+ return NaN;
1019
+ }
1020
+ return sign * parseFloat(value, 10);
1021
+ }
1022
+ var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
1023
+ function representYamlFloat(object, style) {
1024
+ var res;
1025
+ if (isNaN(object)) {
1026
+ switch (style) {
1027
+ case "lowercase":
1028
+ return ".nan";
1029
+ case "uppercase":
1030
+ return ".NAN";
1031
+ case "camelcase":
1032
+ return ".NaN";
1033
+ }
1034
+ } else if (Number.POSITIVE_INFINITY === object) {
1035
+ switch (style) {
1036
+ case "lowercase":
1037
+ return ".inf";
1038
+ case "uppercase":
1039
+ return ".INF";
1040
+ case "camelcase":
1041
+ return ".Inf";
1042
+ }
1043
+ } else if (Number.NEGATIVE_INFINITY === object) {
1044
+ switch (style) {
1045
+ case "lowercase":
1046
+ return "-.inf";
1047
+ case "uppercase":
1048
+ return "-.INF";
1049
+ case "camelcase":
1050
+ return "-.Inf";
1051
+ }
1052
+ } else if (common.isNegativeZero(object)) {
1053
+ return "-0.0";
1054
+ }
1055
+ res = object.toString(10);
1056
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
1057
+ }
1058
+ function isFloat(object) {
1059
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
1060
+ }
1061
+ var float = new type("tag:yaml.org,2002:float", {
1062
+ kind: "scalar",
1063
+ resolve: resolveYamlFloat,
1064
+ construct: constructYamlFloat,
1065
+ predicate: isFloat,
1066
+ represent: representYamlFloat,
1067
+ defaultStyle: "lowercase"
1068
+ });
1069
+ var json = failsafe.extend({
1070
+ implicit: [
1071
+ _null,
1072
+ bool,
1073
+ int,
1074
+ float
1075
+ ]
1076
+ });
1077
+ var core = json;
1078
+ var YAML_DATE_REGEXP = new RegExp(
1079
+ "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
1080
+ );
1081
+ var YAML_TIMESTAMP_REGEXP = new RegExp(
1082
+ "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
1083
+ );
1084
+ function resolveYamlTimestamp(data) {
1085
+ if (data === null) return false;
1086
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
1087
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
1088
+ return false;
1089
+ }
1090
+ function constructYamlTimestamp(data) {
1091
+ var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
1092
+ match = YAML_DATE_REGEXP.exec(data);
1093
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
1094
+ if (match === null) throw new Error("Date resolve error");
1095
+ year = +match[1];
1096
+ month = +match[2] - 1;
1097
+ day = +match[3];
1098
+ if (!match[4]) {
1099
+ return new Date(Date.UTC(year, month, day));
1100
+ }
1101
+ hour = +match[4];
1102
+ minute = +match[5];
1103
+ second = +match[6];
1104
+ if (match[7]) {
1105
+ fraction = match[7].slice(0, 3);
1106
+ while (fraction.length < 3) {
1107
+ fraction += "0";
1108
+ }
1109
+ fraction = +fraction;
1110
+ }
1111
+ if (match[9]) {
1112
+ tz_hour = +match[10];
1113
+ tz_minute = +(match[11] || 0);
1114
+ delta = (tz_hour * 60 + tz_minute) * 6e4;
1115
+ if (match[9] === "-") delta = -delta;
1116
+ }
1117
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
1118
+ if (delta) date.setTime(date.getTime() - delta);
1119
+ return date;
1120
+ }
1121
+ function representYamlTimestamp(object) {
1122
+ return object.toISOString();
1123
+ }
1124
+ var timestamp = new type("tag:yaml.org,2002:timestamp", {
1125
+ kind: "scalar",
1126
+ resolve: resolveYamlTimestamp,
1127
+ construct: constructYamlTimestamp,
1128
+ instanceOf: Date,
1129
+ represent: representYamlTimestamp
1130
+ });
1131
+ function resolveYamlMerge(data) {
1132
+ return data === "<<" || data === null;
1133
+ }
1134
+ var merge = new type("tag:yaml.org,2002:merge", {
1135
+ kind: "scalar",
1136
+ resolve: resolveYamlMerge
1137
+ });
1138
+ var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
1139
+ function resolveYamlBinary(data) {
1140
+ if (data === null) return false;
1141
+ var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;
1142
+ for (idx = 0; idx < max; idx++) {
1143
+ code = map2.indexOf(data.charAt(idx));
1144
+ if (code > 64) continue;
1145
+ if (code < 0) return false;
1146
+ bitlen += 6;
1147
+ }
1148
+ return bitlen % 8 === 0;
1149
+ }
1150
+ function constructYamlBinary(data) {
1151
+ var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];
1152
+ for (idx = 0; idx < max; idx++) {
1153
+ if (idx % 4 === 0 && idx) {
1154
+ result.push(bits >> 16 & 255);
1155
+ result.push(bits >> 8 & 255);
1156
+ result.push(bits & 255);
1157
+ }
1158
+ bits = bits << 6 | map2.indexOf(input.charAt(idx));
1159
+ }
1160
+ tailbits = max % 4 * 6;
1161
+ if (tailbits === 0) {
1162
+ result.push(bits >> 16 & 255);
1163
+ result.push(bits >> 8 & 255);
1164
+ result.push(bits & 255);
1165
+ } else if (tailbits === 18) {
1166
+ result.push(bits >> 10 & 255);
1167
+ result.push(bits >> 2 & 255);
1168
+ } else if (tailbits === 12) {
1169
+ result.push(bits >> 4 & 255);
1170
+ }
1171
+ return new Uint8Array(result);
1172
+ }
1173
+ function representYamlBinary(object) {
1174
+ var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP;
1175
+ for (idx = 0; idx < max; idx++) {
1176
+ if (idx % 3 === 0 && idx) {
1177
+ result += map2[bits >> 18 & 63];
1178
+ result += map2[bits >> 12 & 63];
1179
+ result += map2[bits >> 6 & 63];
1180
+ result += map2[bits & 63];
1181
+ }
1182
+ bits = (bits << 8) + object[idx];
1183
+ }
1184
+ tail = max % 3;
1185
+ if (tail === 0) {
1186
+ result += map2[bits >> 18 & 63];
1187
+ result += map2[bits >> 12 & 63];
1188
+ result += map2[bits >> 6 & 63];
1189
+ result += map2[bits & 63];
1190
+ } else if (tail === 2) {
1191
+ result += map2[bits >> 10 & 63];
1192
+ result += map2[bits >> 4 & 63];
1193
+ result += map2[bits << 2 & 63];
1194
+ result += map2[64];
1195
+ } else if (tail === 1) {
1196
+ result += map2[bits >> 2 & 63];
1197
+ result += map2[bits << 4 & 63];
1198
+ result += map2[64];
1199
+ result += map2[64];
1200
+ }
1201
+ return result;
1202
+ }
1203
+ function isBinary(obj) {
1204
+ return Object.prototype.toString.call(obj) === "[object Uint8Array]";
1205
+ }
1206
+ var binary = new type("tag:yaml.org,2002:binary", {
1207
+ kind: "scalar",
1208
+ resolve: resolveYamlBinary,
1209
+ construct: constructYamlBinary,
1210
+ predicate: isBinary,
1211
+ represent: representYamlBinary
1212
+ });
1213
+ var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
1214
+ var _toString$2 = Object.prototype.toString;
1215
+ function resolveYamlOmap(data) {
1216
+ if (data === null) return true;
1217
+ var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;
1218
+ for (index = 0, length = object.length; index < length; index += 1) {
1219
+ pair = object[index];
1220
+ pairHasKey = false;
1221
+ if (_toString$2.call(pair) !== "[object Object]") return false;
1222
+ for (pairKey in pair) {
1223
+ if (_hasOwnProperty$3.call(pair, pairKey)) {
1224
+ if (!pairHasKey) pairHasKey = true;
1225
+ else return false;
1226
+ }
1227
+ }
1228
+ if (!pairHasKey) return false;
1229
+ if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
1230
+ else return false;
1231
+ }
1232
+ return true;
1233
+ }
1234
+ function constructYamlOmap(data) {
1235
+ return data !== null ? data : [];
1236
+ }
1237
+ var omap = new type("tag:yaml.org,2002:omap", {
1238
+ kind: "sequence",
1239
+ resolve: resolveYamlOmap,
1240
+ construct: constructYamlOmap
1241
+ });
1242
+ var _toString$1 = Object.prototype.toString;
1243
+ function resolveYamlPairs(data) {
1244
+ if (data === null) return true;
1245
+ var index, length, pair, keys, result, object = data;
1246
+ result = new Array(object.length);
1247
+ for (index = 0, length = object.length; index < length; index += 1) {
1248
+ pair = object[index];
1249
+ if (_toString$1.call(pair) !== "[object Object]") return false;
1250
+ keys = Object.keys(pair);
1251
+ if (keys.length !== 1) return false;
1252
+ result[index] = [keys[0], pair[keys[0]]];
1253
+ }
1254
+ return true;
1255
+ }
1256
+ function constructYamlPairs(data) {
1257
+ if (data === null) return [];
1258
+ var index, length, pair, keys, result, object = data;
1259
+ result = new Array(object.length);
1260
+ for (index = 0, length = object.length; index < length; index += 1) {
1261
+ pair = object[index];
1262
+ keys = Object.keys(pair);
1263
+ result[index] = [keys[0], pair[keys[0]]];
1264
+ }
1265
+ return result;
1266
+ }
1267
+ var pairs = new type("tag:yaml.org,2002:pairs", {
1268
+ kind: "sequence",
1269
+ resolve: resolveYamlPairs,
1270
+ construct: constructYamlPairs
1271
+ });
1272
+ var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
1273
+ function resolveYamlSet(data) {
1274
+ if (data === null) return true;
1275
+ var key, object = data;
1276
+ for (key in object) {
1277
+ if (_hasOwnProperty$2.call(object, key)) {
1278
+ if (object[key] !== null) return false;
1279
+ }
1280
+ }
1281
+ return true;
1282
+ }
1283
+ function constructYamlSet(data) {
1284
+ return data !== null ? data : {};
1285
+ }
1286
+ var set = new type("tag:yaml.org,2002:set", {
1287
+ kind: "mapping",
1288
+ resolve: resolveYamlSet,
1289
+ construct: constructYamlSet
1290
+ });
1291
+ var _default = core.extend({
1292
+ implicit: [
1293
+ timestamp,
1294
+ merge
1295
+ ],
1296
+ explicit: [
1297
+ binary,
1298
+ omap,
1299
+ pairs,
1300
+ set
1301
+ ]
1302
+ });
1303
+ var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
1304
+ var CONTEXT_FLOW_IN = 1;
1305
+ var CONTEXT_FLOW_OUT = 2;
1306
+ var CONTEXT_BLOCK_IN = 3;
1307
+ var CONTEXT_BLOCK_OUT = 4;
1308
+ var CHOMPING_CLIP = 1;
1309
+ var CHOMPING_STRIP = 2;
1310
+ var CHOMPING_KEEP = 3;
1311
+ var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1312
+ var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
1313
+ var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
1314
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
1315
+ var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
1316
+ function _class(obj) {
1317
+ return Object.prototype.toString.call(obj);
1318
+ }
1319
+ function is_EOL(c) {
1320
+ return c === 10 || c === 13;
1321
+ }
1322
+ function is_WHITE_SPACE(c) {
1323
+ return c === 9 || c === 32;
1324
+ }
1325
+ function is_WS_OR_EOL(c) {
1326
+ return c === 9 || c === 32 || c === 10 || c === 13;
1327
+ }
1328
+ function is_FLOW_INDICATOR(c) {
1329
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
1330
+ }
1331
+ function fromHexCode(c) {
1332
+ var lc;
1333
+ if (48 <= c && c <= 57) {
1334
+ return c - 48;
1335
+ }
1336
+ lc = c | 32;
1337
+ if (97 <= lc && lc <= 102) {
1338
+ return lc - 97 + 10;
1339
+ }
1340
+ return -1;
1341
+ }
1342
+ function escapedHexLen(c) {
1343
+ if (c === 120) {
1344
+ return 2;
1345
+ }
1346
+ if (c === 117) {
1347
+ return 4;
1348
+ }
1349
+ if (c === 85) {
1350
+ return 8;
1351
+ }
1352
+ return 0;
1353
+ }
1354
+ function fromDecimalCode(c) {
1355
+ if (48 <= c && c <= 57) {
1356
+ return c - 48;
1357
+ }
1358
+ return -1;
1359
+ }
1360
+ function simpleEscapeSequence(c) {
1361
+ return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
1362
+ }
1363
+ function charFromCodepoint(c) {
1364
+ if (c <= 65535) {
1365
+ return String.fromCharCode(c);
1366
+ }
1367
+ return String.fromCharCode(
1368
+ (c - 65536 >> 10) + 55296,
1369
+ (c - 65536 & 1023) + 56320
1370
+ );
1371
+ }
1372
+ function setProperty(object, key, value) {
1373
+ if (key === "__proto__") {
1374
+ Object.defineProperty(object, key, {
1375
+ configurable: true,
1376
+ enumerable: true,
1377
+ writable: true,
1378
+ value
1379
+ });
1380
+ } else {
1381
+ object[key] = value;
1382
+ }
1383
+ }
1384
+ var simpleEscapeCheck = new Array(256);
1385
+ var simpleEscapeMap = new Array(256);
1386
+ for (i = 0; i < 256; i++) {
1387
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1388
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
1389
+ }
1390
+ var i;
1391
+ function State$1(input, options) {
1392
+ this.input = input;
1393
+ this.filename = options["filename"] || null;
1394
+ this.schema = options["schema"] || _default;
1395
+ this.onWarning = options["onWarning"] || null;
1396
+ this.legacy = options["legacy"] || false;
1397
+ this.json = options["json"] || false;
1398
+ this.listener = options["listener"] || null;
1399
+ this.implicitTypes = this.schema.compiledImplicit;
1400
+ this.typeMap = this.schema.compiledTypeMap;
1401
+ this.length = input.length;
1402
+ this.position = 0;
1403
+ this.line = 0;
1404
+ this.lineStart = 0;
1405
+ this.lineIndent = 0;
1406
+ this.firstTabInLine = -1;
1407
+ this.documents = [];
1408
+ }
1409
+ function generateError(state, message) {
1410
+ var mark = {
1411
+ name: state.filename,
1412
+ buffer: state.input.slice(0, -1),
1413
+ // omit trailing \0
1414
+ position: state.position,
1415
+ line: state.line,
1416
+ column: state.position - state.lineStart
1417
+ };
1418
+ mark.snippet = snippet(mark);
1419
+ return new exception(message, mark);
1420
+ }
1421
+ function throwError(state, message) {
1422
+ throw generateError(state, message);
1423
+ }
1424
+ function throwWarning(state, message) {
1425
+ if (state.onWarning) {
1426
+ state.onWarning.call(null, generateError(state, message));
1427
+ }
1428
+ }
1429
+ var directiveHandlers = {
1430
+ YAML: function handleYamlDirective(state, name, args) {
1431
+ var match, major, minor;
1432
+ if (state.version !== null) {
1433
+ throwError(state, "duplication of %YAML directive");
1434
+ }
1435
+ if (args.length !== 1) {
1436
+ throwError(state, "YAML directive accepts exactly one argument");
1437
+ }
1438
+ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
1439
+ if (match === null) {
1440
+ throwError(state, "ill-formed argument of the YAML directive");
1441
+ }
1442
+ major = parseInt(match[1], 10);
1443
+ minor = parseInt(match[2], 10);
1444
+ if (major !== 1) {
1445
+ throwError(state, "unacceptable YAML version of the document");
1446
+ }
1447
+ state.version = args[0];
1448
+ state.checkLineBreaks = minor < 2;
1449
+ if (minor !== 1 && minor !== 2) {
1450
+ throwWarning(state, "unsupported YAML version of the document");
1451
+ }
1452
+ },
1453
+ TAG: function handleTagDirective(state, name, args) {
1454
+ var handle, prefix;
1455
+ if (args.length !== 2) {
1456
+ throwError(state, "TAG directive accepts exactly two arguments");
1457
+ }
1458
+ handle = args[0];
1459
+ prefix = args[1];
1460
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
1461
+ throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
1462
+ }
1463
+ if (_hasOwnProperty$1.call(state.tagMap, handle)) {
1464
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
1465
+ }
1466
+ if (!PATTERN_TAG_URI.test(prefix)) {
1467
+ throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
1468
+ }
1469
+ try {
1470
+ prefix = decodeURIComponent(prefix);
1471
+ } catch (err) {
1472
+ throwError(state, "tag prefix is malformed: " + prefix);
1473
+ }
1474
+ state.tagMap[handle] = prefix;
1475
+ }
1476
+ };
1477
+ function captureSegment(state, start, end, checkJson) {
1478
+ var _position, _length, _character, _result;
1479
+ if (start < end) {
1480
+ _result = state.input.slice(start, end);
1481
+ if (checkJson) {
1482
+ for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
1483
+ _character = _result.charCodeAt(_position);
1484
+ if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
1485
+ throwError(state, "expected valid JSON character");
1486
+ }
1487
+ }
1488
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
1489
+ throwError(state, "the stream contains non-printable characters");
1490
+ }
1491
+ state.result += _result;
1492
+ }
1493
+ }
1494
+ function mergeMappings(state, destination, source, overridableKeys) {
1495
+ var sourceKeys, key, index, quantity;
1496
+ if (!common.isObject(source)) {
1497
+ throwError(state, "cannot merge mappings; the provided source object is unacceptable");
1498
+ }
1499
+ sourceKeys = Object.keys(source);
1500
+ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
1501
+ key = sourceKeys[index];
1502
+ if (!_hasOwnProperty$1.call(destination, key)) {
1503
+ setProperty(destination, key, source[key]);
1504
+ overridableKeys[key] = true;
1505
+ }
1506
+ }
1507
+ }
1508
+ function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
1509
+ var index, quantity;
1510
+ if (Array.isArray(keyNode)) {
1511
+ keyNode = Array.prototype.slice.call(keyNode);
1512
+ for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
1513
+ if (Array.isArray(keyNode[index])) {
1514
+ throwError(state, "nested arrays are not supported inside keys");
1515
+ }
1516
+ if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
1517
+ keyNode[index] = "[object Object]";
1518
+ }
1519
+ }
1520
+ }
1521
+ if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
1522
+ keyNode = "[object Object]";
1523
+ }
1524
+ keyNode = String(keyNode);
1525
+ if (_result === null) {
1526
+ _result = {};
1527
+ }
1528
+ if (keyTag === "tag:yaml.org,2002:merge") {
1529
+ if (Array.isArray(valueNode)) {
1530
+ for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
1531
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
1532
+ }
1533
+ } else {
1534
+ mergeMappings(state, _result, valueNode, overridableKeys);
1535
+ }
1536
+ } else {
1537
+ if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) {
1538
+ state.line = startLine || state.line;
1539
+ state.lineStart = startLineStart || state.lineStart;
1540
+ state.position = startPos || state.position;
1541
+ throwError(state, "duplicated mapping key");
1542
+ }
1543
+ setProperty(_result, keyNode, valueNode);
1544
+ delete overridableKeys[keyNode];
1545
+ }
1546
+ return _result;
1547
+ }
1548
+ function readLineBreak(state) {
1549
+ var ch;
1550
+ ch = state.input.charCodeAt(state.position);
1551
+ if (ch === 10) {
1552
+ state.position++;
1553
+ } else if (ch === 13) {
1554
+ state.position++;
1555
+ if (state.input.charCodeAt(state.position) === 10) {
1556
+ state.position++;
1557
+ }
1558
+ } else {
1559
+ throwError(state, "a line break is expected");
1560
+ }
1561
+ state.line += 1;
1562
+ state.lineStart = state.position;
1563
+ state.firstTabInLine = -1;
1564
+ }
1565
+ function skipSeparationSpace(state, allowComments, checkIndent) {
1566
+ var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
1567
+ while (ch !== 0) {
1568
+ while (is_WHITE_SPACE(ch)) {
1569
+ if (ch === 9 && state.firstTabInLine === -1) {
1570
+ state.firstTabInLine = state.position;
1571
+ }
1572
+ ch = state.input.charCodeAt(++state.position);
1573
+ }
1574
+ if (allowComments && ch === 35) {
1575
+ do {
1576
+ ch = state.input.charCodeAt(++state.position);
1577
+ } while (ch !== 10 && ch !== 13 && ch !== 0);
1578
+ }
1579
+ if (is_EOL(ch)) {
1580
+ readLineBreak(state);
1581
+ ch = state.input.charCodeAt(state.position);
1582
+ lineBreaks++;
1583
+ state.lineIndent = 0;
1584
+ while (ch === 32) {
1585
+ state.lineIndent++;
1586
+ ch = state.input.charCodeAt(++state.position);
1587
+ }
1588
+ } else {
1589
+ break;
1590
+ }
1591
+ }
1592
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
1593
+ throwWarning(state, "deficient indentation");
1594
+ }
1595
+ return lineBreaks;
1596
+ }
1597
+ function testDocumentSeparator(state) {
1598
+ var _position = state.position, ch;
1599
+ ch = state.input.charCodeAt(_position);
1600
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
1601
+ _position += 3;
1602
+ ch = state.input.charCodeAt(_position);
1603
+ if (ch === 0 || is_WS_OR_EOL(ch)) {
1604
+ return true;
1605
+ }
1606
+ }
1607
+ return false;
1608
+ }
1609
+ function writeFoldedLines(state, count) {
1610
+ if (count === 1) {
1611
+ state.result += " ";
1612
+ } else if (count > 1) {
1613
+ state.result += common.repeat("\n", count - 1);
1614
+ }
1615
+ }
1616
+ function readPlainScalar(state, nodeIndent, withinFlowCollection) {
1617
+ var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
1618
+ ch = state.input.charCodeAt(state.position);
1619
+ if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
1620
+ return false;
1621
+ }
1622
+ if (ch === 63 || ch === 45) {
1623
+ following = state.input.charCodeAt(state.position + 1);
1624
+ if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
1625
+ return false;
1626
+ }
1627
+ }
1628
+ state.kind = "scalar";
1629
+ state.result = "";
1630
+ captureStart = captureEnd = state.position;
1631
+ hasPendingContent = false;
1632
+ while (ch !== 0) {
1633
+ if (ch === 58) {
1634
+ following = state.input.charCodeAt(state.position + 1);
1635
+ if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
1636
+ break;
1637
+ }
1638
+ } else if (ch === 35) {
1639
+ preceding = state.input.charCodeAt(state.position - 1);
1640
+ if (is_WS_OR_EOL(preceding)) {
1641
+ break;
1642
+ }
1643
+ } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
1644
+ break;
1645
+ } else if (is_EOL(ch)) {
1646
+ _line = state.line;
1647
+ _lineStart = state.lineStart;
1648
+ _lineIndent = state.lineIndent;
1649
+ skipSeparationSpace(state, false, -1);
1650
+ if (state.lineIndent >= nodeIndent) {
1651
+ hasPendingContent = true;
1652
+ ch = state.input.charCodeAt(state.position);
1653
+ continue;
1654
+ } else {
1655
+ state.position = captureEnd;
1656
+ state.line = _line;
1657
+ state.lineStart = _lineStart;
1658
+ state.lineIndent = _lineIndent;
1659
+ break;
1660
+ }
1661
+ }
1662
+ if (hasPendingContent) {
1663
+ captureSegment(state, captureStart, captureEnd, false);
1664
+ writeFoldedLines(state, state.line - _line);
1665
+ captureStart = captureEnd = state.position;
1666
+ hasPendingContent = false;
1667
+ }
1668
+ if (!is_WHITE_SPACE(ch)) {
1669
+ captureEnd = state.position + 1;
1670
+ }
1671
+ ch = state.input.charCodeAt(++state.position);
1672
+ }
1673
+ captureSegment(state, captureStart, captureEnd, false);
1674
+ if (state.result) {
1675
+ return true;
1676
+ }
1677
+ state.kind = _kind;
1678
+ state.result = _result;
1679
+ return false;
1680
+ }
1681
+ function readSingleQuotedScalar(state, nodeIndent) {
1682
+ var ch, captureStart, captureEnd;
1683
+ ch = state.input.charCodeAt(state.position);
1684
+ if (ch !== 39) {
1685
+ return false;
1686
+ }
1687
+ state.kind = "scalar";
1688
+ state.result = "";
1689
+ state.position++;
1690
+ captureStart = captureEnd = state.position;
1691
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1692
+ if (ch === 39) {
1693
+ captureSegment(state, captureStart, state.position, true);
1694
+ ch = state.input.charCodeAt(++state.position);
1695
+ if (ch === 39) {
1696
+ captureStart = state.position;
1697
+ state.position++;
1698
+ captureEnd = state.position;
1699
+ } else {
1700
+ return true;
1701
+ }
1702
+ } else if (is_EOL(ch)) {
1703
+ captureSegment(state, captureStart, captureEnd, true);
1704
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
1705
+ captureStart = captureEnd = state.position;
1706
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
1707
+ throwError(state, "unexpected end of the document within a single quoted scalar");
1708
+ } else {
1709
+ state.position++;
1710
+ captureEnd = state.position;
1711
+ }
1712
+ }
1713
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
1714
+ }
1715
+ function readDoubleQuotedScalar(state, nodeIndent) {
1716
+ var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
1717
+ ch = state.input.charCodeAt(state.position);
1718
+ if (ch !== 34) {
1719
+ return false;
1720
+ }
1721
+ state.kind = "scalar";
1722
+ state.result = "";
1723
+ state.position++;
1724
+ captureStart = captureEnd = state.position;
1725
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1726
+ if (ch === 34) {
1727
+ captureSegment(state, captureStart, state.position, true);
1728
+ state.position++;
1729
+ return true;
1730
+ } else if (ch === 92) {
1731
+ captureSegment(state, captureStart, state.position, true);
1732
+ ch = state.input.charCodeAt(++state.position);
1733
+ if (is_EOL(ch)) {
1734
+ skipSeparationSpace(state, false, nodeIndent);
1735
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
1736
+ state.result += simpleEscapeMap[ch];
1737
+ state.position++;
1738
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
1739
+ hexLength = tmp;
1740
+ hexResult = 0;
1741
+ for (; hexLength > 0; hexLength--) {
1742
+ ch = state.input.charCodeAt(++state.position);
1743
+ if ((tmp = fromHexCode(ch)) >= 0) {
1744
+ hexResult = (hexResult << 4) + tmp;
1745
+ } else {
1746
+ throwError(state, "expected hexadecimal character");
1747
+ }
1748
+ }
1749
+ state.result += charFromCodepoint(hexResult);
1750
+ state.position++;
1751
+ } else {
1752
+ throwError(state, "unknown escape sequence");
1753
+ }
1754
+ captureStart = captureEnd = state.position;
1755
+ } else if (is_EOL(ch)) {
1756
+ captureSegment(state, captureStart, captureEnd, true);
1757
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
1758
+ captureStart = captureEnd = state.position;
1759
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
1760
+ throwError(state, "unexpected end of the document within a double quoted scalar");
1761
+ } else {
1762
+ state.position++;
1763
+ captureEnd = state.position;
1764
+ }
1765
+ }
1766
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
1767
+ }
1768
+ function readFlowCollection(state, nodeIndent) {
1769
+ var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch;
1770
+ ch = state.input.charCodeAt(state.position);
1771
+ if (ch === 91) {
1772
+ terminator = 93;
1773
+ isMapping = false;
1774
+ _result = [];
1775
+ } else if (ch === 123) {
1776
+ terminator = 125;
1777
+ isMapping = true;
1778
+ _result = {};
1779
+ } else {
1780
+ return false;
1781
+ }
1782
+ if (state.anchor !== null) {
1783
+ state.anchorMap[state.anchor] = _result;
1784
+ }
1785
+ ch = state.input.charCodeAt(++state.position);
1786
+ while (ch !== 0) {
1787
+ skipSeparationSpace(state, true, nodeIndent);
1788
+ ch = state.input.charCodeAt(state.position);
1789
+ if (ch === terminator) {
1790
+ state.position++;
1791
+ state.tag = _tag;
1792
+ state.anchor = _anchor;
1793
+ state.kind = isMapping ? "mapping" : "sequence";
1794
+ state.result = _result;
1795
+ return true;
1796
+ } else if (!readNext) {
1797
+ throwError(state, "missed comma between flow collection entries");
1798
+ } else if (ch === 44) {
1799
+ throwError(state, "expected the node content, but found ','");
1800
+ }
1801
+ keyTag = keyNode = valueNode = null;
1802
+ isPair = isExplicitPair = false;
1803
+ if (ch === 63) {
1804
+ following = state.input.charCodeAt(state.position + 1);
1805
+ if (is_WS_OR_EOL(following)) {
1806
+ isPair = isExplicitPair = true;
1807
+ state.position++;
1808
+ skipSeparationSpace(state, true, nodeIndent);
1809
+ }
1810
+ }
1811
+ _line = state.line;
1812
+ _lineStart = state.lineStart;
1813
+ _pos = state.position;
1814
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1815
+ keyTag = state.tag;
1816
+ keyNode = state.result;
1817
+ skipSeparationSpace(state, true, nodeIndent);
1818
+ ch = state.input.charCodeAt(state.position);
1819
+ if ((isExplicitPair || state.line === _line) && ch === 58) {
1820
+ isPair = true;
1821
+ ch = state.input.charCodeAt(++state.position);
1822
+ skipSeparationSpace(state, true, nodeIndent);
1823
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1824
+ valueNode = state.result;
1825
+ }
1826
+ if (isMapping) {
1827
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
1828
+ } else if (isPair) {
1829
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
1830
+ } else {
1831
+ _result.push(keyNode);
1832
+ }
1833
+ skipSeparationSpace(state, true, nodeIndent);
1834
+ ch = state.input.charCodeAt(state.position);
1835
+ if (ch === 44) {
1836
+ readNext = true;
1837
+ ch = state.input.charCodeAt(++state.position);
1838
+ } else {
1839
+ readNext = false;
1840
+ }
1841
+ }
1842
+ throwError(state, "unexpected end of the stream within a flow collection");
1843
+ }
1844
+ function readBlockScalar(state, nodeIndent) {
1845
+ var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
1846
+ ch = state.input.charCodeAt(state.position);
1847
+ if (ch === 124) {
1848
+ folding = false;
1849
+ } else if (ch === 62) {
1850
+ folding = true;
1851
+ } else {
1852
+ return false;
1853
+ }
1854
+ state.kind = "scalar";
1855
+ state.result = "";
1856
+ while (ch !== 0) {
1857
+ ch = state.input.charCodeAt(++state.position);
1858
+ if (ch === 43 || ch === 45) {
1859
+ if (CHOMPING_CLIP === chomping) {
1860
+ chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
1861
+ } else {
1862
+ throwError(state, "repeat of a chomping mode identifier");
1863
+ }
1864
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
1865
+ if (tmp === 0) {
1866
+ throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
1867
+ } else if (!detectedIndent) {
1868
+ textIndent = nodeIndent + tmp - 1;
1869
+ detectedIndent = true;
1870
+ } else {
1871
+ throwError(state, "repeat of an indentation width identifier");
1872
+ }
1873
+ } else {
1874
+ break;
1875
+ }
1876
+ }
1877
+ if (is_WHITE_SPACE(ch)) {
1878
+ do {
1879
+ ch = state.input.charCodeAt(++state.position);
1880
+ } while (is_WHITE_SPACE(ch));
1881
+ if (ch === 35) {
1882
+ do {
1883
+ ch = state.input.charCodeAt(++state.position);
1884
+ } while (!is_EOL(ch) && ch !== 0);
1885
+ }
1886
+ }
1887
+ while (ch !== 0) {
1888
+ readLineBreak(state);
1889
+ state.lineIndent = 0;
1890
+ ch = state.input.charCodeAt(state.position);
1891
+ while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
1892
+ state.lineIndent++;
1893
+ ch = state.input.charCodeAt(++state.position);
1894
+ }
1895
+ if (!detectedIndent && state.lineIndent > textIndent) {
1896
+ textIndent = state.lineIndent;
1897
+ }
1898
+ if (is_EOL(ch)) {
1899
+ emptyLines++;
1900
+ continue;
1901
+ }
1902
+ if (state.lineIndent < textIndent) {
1903
+ if (chomping === CHOMPING_KEEP) {
1904
+ state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
1905
+ } else if (chomping === CHOMPING_CLIP) {
1906
+ if (didReadContent) {
1907
+ state.result += "\n";
1908
+ }
1909
+ }
1910
+ break;
1911
+ }
1912
+ if (folding) {
1913
+ if (is_WHITE_SPACE(ch)) {
1914
+ atMoreIndented = true;
1915
+ state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
1916
+ } else if (atMoreIndented) {
1917
+ atMoreIndented = false;
1918
+ state.result += common.repeat("\n", emptyLines + 1);
1919
+ } else if (emptyLines === 0) {
1920
+ if (didReadContent) {
1921
+ state.result += " ";
1922
+ }
1923
+ } else {
1924
+ state.result += common.repeat("\n", emptyLines);
1925
+ }
1926
+ } else {
1927
+ state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
1928
+ }
1929
+ didReadContent = true;
1930
+ detectedIndent = true;
1931
+ emptyLines = 0;
1932
+ captureStart = state.position;
1933
+ while (!is_EOL(ch) && ch !== 0) {
1934
+ ch = state.input.charCodeAt(++state.position);
1935
+ }
1936
+ captureSegment(state, captureStart, state.position, false);
1937
+ }
1938
+ return true;
1939
+ }
1940
+ function readBlockSequence(state, nodeIndent) {
1941
+ var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
1942
+ if (state.firstTabInLine !== -1) return false;
1943
+ if (state.anchor !== null) {
1944
+ state.anchorMap[state.anchor] = _result;
1945
+ }
1946
+ ch = state.input.charCodeAt(state.position);
1947
+ while (ch !== 0) {
1948
+ if (state.firstTabInLine !== -1) {
1949
+ state.position = state.firstTabInLine;
1950
+ throwError(state, "tab characters must not be used in indentation");
1951
+ }
1952
+ if (ch !== 45) {
1953
+ break;
1954
+ }
1955
+ following = state.input.charCodeAt(state.position + 1);
1956
+ if (!is_WS_OR_EOL(following)) {
1957
+ break;
1958
+ }
1959
+ detected = true;
1960
+ state.position++;
1961
+ if (skipSeparationSpace(state, true, -1)) {
1962
+ if (state.lineIndent <= nodeIndent) {
1963
+ _result.push(null);
1964
+ ch = state.input.charCodeAt(state.position);
1965
+ continue;
1966
+ }
1967
+ }
1968
+ _line = state.line;
1969
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
1970
+ _result.push(state.result);
1971
+ skipSeparationSpace(state, true, -1);
1972
+ ch = state.input.charCodeAt(state.position);
1973
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
1974
+ throwError(state, "bad indentation of a sequence entry");
1975
+ } else if (state.lineIndent < nodeIndent) {
1976
+ break;
1977
+ }
1978
+ }
1979
+ if (detected) {
1980
+ state.tag = _tag;
1981
+ state.anchor = _anchor;
1982
+ state.kind = "sequence";
1983
+ state.result = _result;
1984
+ return true;
1985
+ }
1986
+ return false;
1987
+ }
1988
+ function readBlockMapping(state, nodeIndent, flowIndent) {
1989
+ var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
1990
+ if (state.firstTabInLine !== -1) return false;
1991
+ if (state.anchor !== null) {
1992
+ state.anchorMap[state.anchor] = _result;
1993
+ }
1994
+ ch = state.input.charCodeAt(state.position);
1995
+ while (ch !== 0) {
1996
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
1997
+ state.position = state.firstTabInLine;
1998
+ throwError(state, "tab characters must not be used in indentation");
1999
+ }
2000
+ following = state.input.charCodeAt(state.position + 1);
2001
+ _line = state.line;
2002
+ if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
2003
+ if (ch === 63) {
2004
+ if (atExplicitKey) {
2005
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
2006
+ keyTag = keyNode = valueNode = null;
2007
+ }
2008
+ detected = true;
2009
+ atExplicitKey = true;
2010
+ allowCompact = true;
2011
+ } else if (atExplicitKey) {
2012
+ atExplicitKey = false;
2013
+ allowCompact = true;
2014
+ } else {
2015
+ throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
2016
+ }
2017
+ state.position += 1;
2018
+ ch = following;
2019
+ } else {
2020
+ _keyLine = state.line;
2021
+ _keyLineStart = state.lineStart;
2022
+ _keyPos = state.position;
2023
+ if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
2024
+ break;
2025
+ }
2026
+ if (state.line === _line) {
2027
+ ch = state.input.charCodeAt(state.position);
2028
+ while (is_WHITE_SPACE(ch)) {
2029
+ ch = state.input.charCodeAt(++state.position);
2030
+ }
2031
+ if (ch === 58) {
2032
+ ch = state.input.charCodeAt(++state.position);
2033
+ if (!is_WS_OR_EOL(ch)) {
2034
+ throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2035
+ }
2036
+ if (atExplicitKey) {
2037
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
2038
+ keyTag = keyNode = valueNode = null;
2039
+ }
2040
+ detected = true;
2041
+ atExplicitKey = false;
2042
+ allowCompact = false;
2043
+ keyTag = state.tag;
2044
+ keyNode = state.result;
2045
+ } else if (detected) {
2046
+ throwError(state, "can not read an implicit mapping pair; a colon is missed");
2047
+ } else {
2048
+ state.tag = _tag;
2049
+ state.anchor = _anchor;
2050
+ return true;
2051
+ }
2052
+ } else if (detected) {
2053
+ throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
2054
+ } else {
2055
+ state.tag = _tag;
2056
+ state.anchor = _anchor;
2057
+ return true;
2058
+ }
2059
+ }
2060
+ if (state.line === _line || state.lineIndent > nodeIndent) {
2061
+ if (atExplicitKey) {
2062
+ _keyLine = state.line;
2063
+ _keyLineStart = state.lineStart;
2064
+ _keyPos = state.position;
2065
+ }
2066
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
2067
+ if (atExplicitKey) {
2068
+ keyNode = state.result;
2069
+ } else {
2070
+ valueNode = state.result;
2071
+ }
2072
+ }
2073
+ if (!atExplicitKey) {
2074
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
2075
+ keyTag = keyNode = valueNode = null;
2076
+ }
2077
+ skipSeparationSpace(state, true, -1);
2078
+ ch = state.input.charCodeAt(state.position);
2079
+ }
2080
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
2081
+ throwError(state, "bad indentation of a mapping entry");
2082
+ } else if (state.lineIndent < nodeIndent) {
2083
+ break;
2084
+ }
2085
+ }
2086
+ if (atExplicitKey) {
2087
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
2088
+ }
2089
+ if (detected) {
2090
+ state.tag = _tag;
2091
+ state.anchor = _anchor;
2092
+ state.kind = "mapping";
2093
+ state.result = _result;
2094
+ }
2095
+ return detected;
2096
+ }
2097
+ function readTagProperty(state) {
2098
+ var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
2099
+ ch = state.input.charCodeAt(state.position);
2100
+ if (ch !== 33) return false;
2101
+ if (state.tag !== null) {
2102
+ throwError(state, "duplication of a tag property");
2103
+ }
2104
+ ch = state.input.charCodeAt(++state.position);
2105
+ if (ch === 60) {
2106
+ isVerbatim = true;
2107
+ ch = state.input.charCodeAt(++state.position);
2108
+ } else if (ch === 33) {
2109
+ isNamed = true;
2110
+ tagHandle = "!!";
2111
+ ch = state.input.charCodeAt(++state.position);
2112
+ } else {
2113
+ tagHandle = "!";
2114
+ }
2115
+ _position = state.position;
2116
+ if (isVerbatim) {
2117
+ do {
2118
+ ch = state.input.charCodeAt(++state.position);
2119
+ } while (ch !== 0 && ch !== 62);
2120
+ if (state.position < state.length) {
2121
+ tagName = state.input.slice(_position, state.position);
2122
+ ch = state.input.charCodeAt(++state.position);
2123
+ } else {
2124
+ throwError(state, "unexpected end of the stream within a verbatim tag");
2125
+ }
2126
+ } else {
2127
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2128
+ if (ch === 33) {
2129
+ if (!isNamed) {
2130
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
2131
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
2132
+ throwError(state, "named tag handle cannot contain such characters");
2133
+ }
2134
+ isNamed = true;
2135
+ _position = state.position + 1;
2136
+ } else {
2137
+ throwError(state, "tag suffix cannot contain exclamation marks");
2138
+ }
2139
+ }
2140
+ ch = state.input.charCodeAt(++state.position);
2141
+ }
2142
+ tagName = state.input.slice(_position, state.position);
2143
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
2144
+ throwError(state, "tag suffix cannot contain flow indicator characters");
2145
+ }
2146
+ }
2147
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
2148
+ throwError(state, "tag name cannot contain such characters: " + tagName);
2149
+ }
2150
+ try {
2151
+ tagName = decodeURIComponent(tagName);
2152
+ } catch (err) {
2153
+ throwError(state, "tag name is malformed: " + tagName);
2154
+ }
2155
+ if (isVerbatim) {
2156
+ state.tag = tagName;
2157
+ } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
2158
+ state.tag = state.tagMap[tagHandle] + tagName;
2159
+ } else if (tagHandle === "!") {
2160
+ state.tag = "!" + tagName;
2161
+ } else if (tagHandle === "!!") {
2162
+ state.tag = "tag:yaml.org,2002:" + tagName;
2163
+ } else {
2164
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
2165
+ }
2166
+ return true;
2167
+ }
2168
+ function readAnchorProperty(state) {
2169
+ var _position, ch;
2170
+ ch = state.input.charCodeAt(state.position);
2171
+ if (ch !== 38) return false;
2172
+ if (state.anchor !== null) {
2173
+ throwError(state, "duplication of an anchor property");
2174
+ }
2175
+ ch = state.input.charCodeAt(++state.position);
2176
+ _position = state.position;
2177
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2178
+ ch = state.input.charCodeAt(++state.position);
2179
+ }
2180
+ if (state.position === _position) {
2181
+ throwError(state, "name of an anchor node must contain at least one character");
2182
+ }
2183
+ state.anchor = state.input.slice(_position, state.position);
2184
+ return true;
2185
+ }
2186
+ function readAlias(state) {
2187
+ var _position, alias, ch;
2188
+ ch = state.input.charCodeAt(state.position);
2189
+ if (ch !== 42) return false;
2190
+ ch = state.input.charCodeAt(++state.position);
2191
+ _position = state.position;
2192
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
2193
+ ch = state.input.charCodeAt(++state.position);
2194
+ }
2195
+ if (state.position === _position) {
2196
+ throwError(state, "name of an alias node must contain at least one character");
2197
+ }
2198
+ alias = state.input.slice(_position, state.position);
2199
+ if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
2200
+ throwError(state, 'unidentified alias "' + alias + '"');
2201
+ }
2202
+ state.result = state.anchorMap[alias];
2203
+ skipSeparationSpace(state, true, -1);
2204
+ return true;
2205
+ }
2206
+ function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
2207
+ var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent;
2208
+ if (state.listener !== null) {
2209
+ state.listener("open", state);
2210
+ }
2211
+ state.tag = null;
2212
+ state.anchor = null;
2213
+ state.kind = null;
2214
+ state.result = null;
2215
+ allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
2216
+ if (allowToSeek) {
2217
+ if (skipSeparationSpace(state, true, -1)) {
2218
+ atNewLine = true;
2219
+ if (state.lineIndent > parentIndent) {
2220
+ indentStatus = 1;
2221
+ } else if (state.lineIndent === parentIndent) {
2222
+ indentStatus = 0;
2223
+ } else if (state.lineIndent < parentIndent) {
2224
+ indentStatus = -1;
2225
+ }
2226
+ }
2227
+ }
2228
+ if (indentStatus === 1) {
2229
+ while (readTagProperty(state) || readAnchorProperty(state)) {
2230
+ if (skipSeparationSpace(state, true, -1)) {
2231
+ atNewLine = true;
2232
+ allowBlockCollections = allowBlockStyles;
2233
+ if (state.lineIndent > parentIndent) {
2234
+ indentStatus = 1;
2235
+ } else if (state.lineIndent === parentIndent) {
2236
+ indentStatus = 0;
2237
+ } else if (state.lineIndent < parentIndent) {
2238
+ indentStatus = -1;
2239
+ }
2240
+ } else {
2241
+ allowBlockCollections = false;
2242
+ }
2243
+ }
2244
+ }
2245
+ if (allowBlockCollections) {
2246
+ allowBlockCollections = atNewLine || allowCompact;
2247
+ }
2248
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
2249
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
2250
+ flowIndent = parentIndent;
2251
+ } else {
2252
+ flowIndent = parentIndent + 1;
2253
+ }
2254
+ blockIndent = state.position - state.lineStart;
2255
+ if (indentStatus === 1) {
2256
+ if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
2257
+ hasContent = true;
2258
+ } else {
2259
+ if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
2260
+ hasContent = true;
2261
+ } else if (readAlias(state)) {
2262
+ hasContent = true;
2263
+ if (state.tag !== null || state.anchor !== null) {
2264
+ throwError(state, "alias node should not have any properties");
2265
+ }
2266
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
2267
+ hasContent = true;
2268
+ if (state.tag === null) {
2269
+ state.tag = "?";
2270
+ }
2271
+ }
2272
+ if (state.anchor !== null) {
2273
+ state.anchorMap[state.anchor] = state.result;
2274
+ }
2275
+ }
2276
+ } else if (indentStatus === 0) {
2277
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
2278
+ }
2279
+ }
2280
+ if (state.tag === null) {
2281
+ if (state.anchor !== null) {
2282
+ state.anchorMap[state.anchor] = state.result;
2283
+ }
2284
+ } else if (state.tag === "?") {
2285
+ if (state.result !== null && state.kind !== "scalar") {
2286
+ throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
2287
+ }
2288
+ for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
2289
+ type2 = state.implicitTypes[typeIndex];
2290
+ if (type2.resolve(state.result)) {
2291
+ state.result = type2.construct(state.result);
2292
+ state.tag = type2.tag;
2293
+ if (state.anchor !== null) {
2294
+ state.anchorMap[state.anchor] = state.result;
2295
+ }
2296
+ break;
2297
+ }
2298
+ }
2299
+ } else if (state.tag !== "!") {
2300
+ if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) {
2301
+ type2 = state.typeMap[state.kind || "fallback"][state.tag];
2302
+ } else {
2303
+ type2 = null;
2304
+ typeList = state.typeMap.multi[state.kind || "fallback"];
2305
+ for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
2306
+ if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
2307
+ type2 = typeList[typeIndex];
2308
+ break;
2309
+ }
2310
+ }
2311
+ }
2312
+ if (!type2) {
2313
+ throwError(state, "unknown tag !<" + state.tag + ">");
2314
+ }
2315
+ if (state.result !== null && type2.kind !== state.kind) {
2316
+ throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
2317
+ }
2318
+ if (!type2.resolve(state.result, state.tag)) {
2319
+ throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
2320
+ } else {
2321
+ state.result = type2.construct(state.result, state.tag);
2322
+ if (state.anchor !== null) {
2323
+ state.anchorMap[state.anchor] = state.result;
2324
+ }
2325
+ }
2326
+ }
2327
+ if (state.listener !== null) {
2328
+ state.listener("close", state);
2329
+ }
2330
+ return state.tag !== null || state.anchor !== null || hasContent;
2331
+ }
2332
+ function readDocument(state) {
2333
+ var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
2334
+ state.version = null;
2335
+ state.checkLineBreaks = state.legacy;
2336
+ state.tagMap = /* @__PURE__ */ Object.create(null);
2337
+ state.anchorMap = /* @__PURE__ */ Object.create(null);
2338
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2339
+ skipSeparationSpace(state, true, -1);
2340
+ ch = state.input.charCodeAt(state.position);
2341
+ if (state.lineIndent > 0 || ch !== 37) {
2342
+ break;
2343
+ }
2344
+ hasDirectives = true;
2345
+ ch = state.input.charCodeAt(++state.position);
2346
+ _position = state.position;
2347
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2348
+ ch = state.input.charCodeAt(++state.position);
2349
+ }
2350
+ directiveName = state.input.slice(_position, state.position);
2351
+ directiveArgs = [];
2352
+ if (directiveName.length < 1) {
2353
+ throwError(state, "directive name must not be less than one character in length");
2354
+ }
2355
+ while (ch !== 0) {
2356
+ while (is_WHITE_SPACE(ch)) {
2357
+ ch = state.input.charCodeAt(++state.position);
2358
+ }
2359
+ if (ch === 35) {
2360
+ do {
2361
+ ch = state.input.charCodeAt(++state.position);
2362
+ } while (ch !== 0 && !is_EOL(ch));
2363
+ break;
2364
+ }
2365
+ if (is_EOL(ch)) break;
2366
+ _position = state.position;
2367
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
2368
+ ch = state.input.charCodeAt(++state.position);
2369
+ }
2370
+ directiveArgs.push(state.input.slice(_position, state.position));
2371
+ }
2372
+ if (ch !== 0) readLineBreak(state);
2373
+ if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
2374
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
2375
+ } else {
2376
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
2377
+ }
2378
+ }
2379
+ skipSeparationSpace(state, true, -1);
2380
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
2381
+ state.position += 3;
2382
+ skipSeparationSpace(state, true, -1);
2383
+ } else if (hasDirectives) {
2384
+ throwError(state, "directives end mark is expected");
2385
+ }
2386
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
2387
+ skipSeparationSpace(state, true, -1);
2388
+ if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
2389
+ throwWarning(state, "non-ASCII line breaks are interpreted as content");
2390
+ }
2391
+ state.documents.push(state.result);
2392
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
2393
+ if (state.input.charCodeAt(state.position) === 46) {
2394
+ state.position += 3;
2395
+ skipSeparationSpace(state, true, -1);
2396
+ }
2397
+ return;
2398
+ }
2399
+ if (state.position < state.length - 1) {
2400
+ throwError(state, "end of the stream or a document separator is expected");
2401
+ } else {
2402
+ return;
2403
+ }
2404
+ }
2405
+ function loadDocuments(input, options) {
2406
+ input = String(input);
2407
+ options = options || {};
2408
+ if (input.length !== 0) {
2409
+ if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
2410
+ input += "\n";
2411
+ }
2412
+ if (input.charCodeAt(0) === 65279) {
2413
+ input = input.slice(1);
2414
+ }
2415
+ }
2416
+ var state = new State$1(input, options);
2417
+ var nullpos = input.indexOf("\0");
2418
+ if (nullpos !== -1) {
2419
+ state.position = nullpos;
2420
+ throwError(state, "null byte is not allowed in input");
2421
+ }
2422
+ state.input += "\0";
2423
+ while (state.input.charCodeAt(state.position) === 32) {
2424
+ state.lineIndent += 1;
2425
+ state.position += 1;
2426
+ }
2427
+ while (state.position < state.length - 1) {
2428
+ readDocument(state);
2429
+ }
2430
+ return state.documents;
2431
+ }
2432
+ function loadAll$1(input, iterator, options) {
2433
+ if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
2434
+ options = iterator;
2435
+ iterator = null;
2436
+ }
2437
+ var documents = loadDocuments(input, options);
2438
+ if (typeof iterator !== "function") {
2439
+ return documents;
2440
+ }
2441
+ for (var index = 0, length = documents.length; index < length; index += 1) {
2442
+ iterator(documents[index]);
2443
+ }
2444
+ }
2445
+ function load$1(input, options) {
2446
+ var documents = loadDocuments(input, options);
2447
+ if (documents.length === 0) {
2448
+ return void 0;
2449
+ } else if (documents.length === 1) {
2450
+ return documents[0];
2451
+ }
2452
+ throw new exception("expected a single document in the stream, but found more");
2453
+ }
2454
+ var loadAll_1 = loadAll$1;
2455
+ var load_1 = load$1;
2456
+ var loader = {
2457
+ loadAll: loadAll_1,
2458
+ load: load_1
2459
+ };
2460
+ var _toString = Object.prototype.toString;
2461
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
2462
+ var CHAR_BOM = 65279;
2463
+ var CHAR_TAB = 9;
2464
+ var CHAR_LINE_FEED = 10;
2465
+ var CHAR_CARRIAGE_RETURN = 13;
2466
+ var CHAR_SPACE = 32;
2467
+ var CHAR_EXCLAMATION = 33;
2468
+ var CHAR_DOUBLE_QUOTE = 34;
2469
+ var CHAR_SHARP = 35;
2470
+ var CHAR_PERCENT = 37;
2471
+ var CHAR_AMPERSAND = 38;
2472
+ var CHAR_SINGLE_QUOTE = 39;
2473
+ var CHAR_ASTERISK = 42;
2474
+ var CHAR_COMMA = 44;
2475
+ var CHAR_MINUS = 45;
2476
+ var CHAR_COLON = 58;
2477
+ var CHAR_EQUALS = 61;
2478
+ var CHAR_GREATER_THAN = 62;
2479
+ var CHAR_QUESTION = 63;
2480
+ var CHAR_COMMERCIAL_AT = 64;
2481
+ var CHAR_LEFT_SQUARE_BRACKET = 91;
2482
+ var CHAR_RIGHT_SQUARE_BRACKET = 93;
2483
+ var CHAR_GRAVE_ACCENT = 96;
2484
+ var CHAR_LEFT_CURLY_BRACKET = 123;
2485
+ var CHAR_VERTICAL_LINE = 124;
2486
+ var CHAR_RIGHT_CURLY_BRACKET = 125;
2487
+ var ESCAPE_SEQUENCES = {};
2488
+ ESCAPE_SEQUENCES[0] = "\\0";
2489
+ ESCAPE_SEQUENCES[7] = "\\a";
2490
+ ESCAPE_SEQUENCES[8] = "\\b";
2491
+ ESCAPE_SEQUENCES[9] = "\\t";
2492
+ ESCAPE_SEQUENCES[10] = "\\n";
2493
+ ESCAPE_SEQUENCES[11] = "\\v";
2494
+ ESCAPE_SEQUENCES[12] = "\\f";
2495
+ ESCAPE_SEQUENCES[13] = "\\r";
2496
+ ESCAPE_SEQUENCES[27] = "\\e";
2497
+ ESCAPE_SEQUENCES[34] = '\\"';
2498
+ ESCAPE_SEQUENCES[92] = "\\\\";
2499
+ ESCAPE_SEQUENCES[133] = "\\N";
2500
+ ESCAPE_SEQUENCES[160] = "\\_";
2501
+ ESCAPE_SEQUENCES[8232] = "\\L";
2502
+ ESCAPE_SEQUENCES[8233] = "\\P";
2503
+ var DEPRECATED_BOOLEANS_SYNTAX = [
2504
+ "y",
2505
+ "Y",
2506
+ "yes",
2507
+ "Yes",
2508
+ "YES",
2509
+ "on",
2510
+ "On",
2511
+ "ON",
2512
+ "n",
2513
+ "N",
2514
+ "no",
2515
+ "No",
2516
+ "NO",
2517
+ "off",
2518
+ "Off",
2519
+ "OFF"
2520
+ ];
2521
+ var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
2522
+ function compileStyleMap(schema2, map2) {
2523
+ var result, keys, index, length, tag, style, type2;
2524
+ if (map2 === null) return {};
2525
+ result = {};
2526
+ keys = Object.keys(map2);
2527
+ for (index = 0, length = keys.length; index < length; index += 1) {
2528
+ tag = keys[index];
2529
+ style = String(map2[tag]);
2530
+ if (tag.slice(0, 2) === "!!") {
2531
+ tag = "tag:yaml.org,2002:" + tag.slice(2);
2532
+ }
2533
+ type2 = schema2.compiledTypeMap["fallback"][tag];
2534
+ if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
2535
+ style = type2.styleAliases[style];
2536
+ }
2537
+ result[tag] = style;
2538
+ }
2539
+ return result;
2540
+ }
2541
+ function encodeHex(character) {
2542
+ var string, handle, length;
2543
+ string = character.toString(16).toUpperCase();
2544
+ if (character <= 255) {
2545
+ handle = "x";
2546
+ length = 2;
2547
+ } else if (character <= 65535) {
2548
+ handle = "u";
2549
+ length = 4;
2550
+ } else if (character <= 4294967295) {
2551
+ handle = "U";
2552
+ length = 8;
2553
+ } else {
2554
+ throw new exception("code point within a string may not be greater than 0xFFFFFFFF");
2555
+ }
2556
+ return "\\" + handle + common.repeat("0", length - string.length) + string;
2557
+ }
2558
+ var QUOTING_TYPE_SINGLE = 1;
2559
+ var QUOTING_TYPE_DOUBLE = 2;
2560
+ function State(options) {
2561
+ this.schema = options["schema"] || _default;
2562
+ this.indent = Math.max(1, options["indent"] || 2);
2563
+ this.noArrayIndent = options["noArrayIndent"] || false;
2564
+ this.skipInvalid = options["skipInvalid"] || false;
2565
+ this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
2566
+ this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
2567
+ this.sortKeys = options["sortKeys"] || false;
2568
+ this.lineWidth = options["lineWidth"] || 80;
2569
+ this.noRefs = options["noRefs"] || false;
2570
+ this.noCompatMode = options["noCompatMode"] || false;
2571
+ this.condenseFlow = options["condenseFlow"] || false;
2572
+ this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
2573
+ this.forceQuotes = options["forceQuotes"] || false;
2574
+ this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
2575
+ this.implicitTypes = this.schema.compiledImplicit;
2576
+ this.explicitTypes = this.schema.compiledExplicit;
2577
+ this.tag = null;
2578
+ this.result = "";
2579
+ this.duplicates = [];
2580
+ this.usedDuplicates = null;
2581
+ }
2582
+ function indentString(string, spaces) {
2583
+ var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;
2584
+ while (position < length) {
2585
+ next = string.indexOf("\n", position);
2586
+ if (next === -1) {
2587
+ line = string.slice(position);
2588
+ position = length;
2589
+ } else {
2590
+ line = string.slice(position, next + 1);
2591
+ position = next + 1;
2592
+ }
2593
+ if (line.length && line !== "\n") result += ind;
2594
+ result += line;
2595
+ }
2596
+ return result;
2597
+ }
2598
+ function generateNextLine(state, level) {
2599
+ return "\n" + common.repeat(" ", state.indent * level);
2600
+ }
2601
+ function testImplicitResolving(state, str2) {
2602
+ var index, length, type2;
2603
+ for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
2604
+ type2 = state.implicitTypes[index];
2605
+ if (type2.resolve(str2)) {
2606
+ return true;
2607
+ }
2608
+ }
2609
+ return false;
2610
+ }
2611
+ function isWhitespace(c) {
2612
+ return c === CHAR_SPACE || c === CHAR_TAB;
2613
+ }
2614
+ function isPrintable(c) {
2615
+ return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
2616
+ }
2617
+ function isNsCharOrWhitespace(c) {
2618
+ return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
2619
+ }
2620
+ function isPlainSafe(c, prev, inblock) {
2621
+ var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
2622
+ var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
2623
+ return (
2624
+ // ns-plain-safe
2625
+ (inblock ? (
2626
+ // c = flow-in
2627
+ cIsNsCharOrWhitespace
2628
+ ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar
2629
+ );
2630
+ }
2631
+ function isPlainSafeFirst(c) {
2632
+ return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
2633
+ }
2634
+ function isPlainSafeLast(c) {
2635
+ return !isWhitespace(c) && c !== CHAR_COLON;
2636
+ }
2637
+ function codePointAt(string, pos) {
2638
+ var first = string.charCodeAt(pos), second;
2639
+ if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
2640
+ second = string.charCodeAt(pos + 1);
2641
+ if (second >= 56320 && second <= 57343) {
2642
+ return (first - 55296) * 1024 + second - 56320 + 65536;
2643
+ }
2644
+ }
2645
+ return first;
2646
+ }
2647
+ function needIndentIndicator(string) {
2648
+ var leadingSpaceRe = /^\n* /;
2649
+ return leadingSpaceRe.test(string);
2650
+ }
2651
+ var STYLE_PLAIN = 1;
2652
+ var STYLE_SINGLE = 2;
2653
+ var STYLE_LITERAL = 3;
2654
+ var STYLE_FOLDED = 4;
2655
+ var STYLE_DOUBLE = 5;
2656
+ function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
2657
+ var i;
2658
+ var char = 0;
2659
+ var prevChar = null;
2660
+ var hasLineBreak = false;
2661
+ var hasFoldableLine = false;
2662
+ var shouldTrackWidth = lineWidth !== -1;
2663
+ var previousLineBreak = -1;
2664
+ var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
2665
+ if (singleLineOnly || forceQuotes) {
2666
+ for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
2667
+ char = codePointAt(string, i);
2668
+ if (!isPrintable(char)) {
2669
+ return STYLE_DOUBLE;
2670
+ }
2671
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2672
+ prevChar = char;
2673
+ }
2674
+ } else {
2675
+ for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
2676
+ char = codePointAt(string, i);
2677
+ if (char === CHAR_LINE_FEED) {
2678
+ hasLineBreak = true;
2679
+ if (shouldTrackWidth) {
2680
+ hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
2681
+ i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
2682
+ previousLineBreak = i;
2683
+ }
2684
+ } else if (!isPrintable(char)) {
2685
+ return STYLE_DOUBLE;
2686
+ }
2687
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2688
+ prevChar = char;
2689
+ }
2690
+ hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
2691
+ }
2692
+ if (!hasLineBreak && !hasFoldableLine) {
2693
+ if (plain && !forceQuotes && !testAmbiguousType(string)) {
2694
+ return STYLE_PLAIN;
2695
+ }
2696
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2697
+ }
2698
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
2699
+ return STYLE_DOUBLE;
2700
+ }
2701
+ if (!forceQuotes) {
2702
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
2703
+ }
2704
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2705
+ }
2706
+ function writeScalar(state, string, level, iskey, inblock) {
2707
+ state.dump = (function() {
2708
+ if (string.length === 0) {
2709
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
2710
+ }
2711
+ if (!state.noCompatMode) {
2712
+ if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
2713
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
2714
+ }
2715
+ }
2716
+ var indent = state.indent * Math.max(1, level);
2717
+ var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
2718
+ var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
2719
+ function testAmbiguity(string2) {
2720
+ return testImplicitResolving(state, string2);
2721
+ }
2722
+ switch (chooseScalarStyle(
2723
+ string,
2724
+ singleLineOnly,
2725
+ state.indent,
2726
+ lineWidth,
2727
+ testAmbiguity,
2728
+ state.quotingType,
2729
+ state.forceQuotes && !iskey,
2730
+ inblock
2731
+ )) {
2732
+ case STYLE_PLAIN:
2733
+ return string;
2734
+ case STYLE_SINGLE:
2735
+ return "'" + string.replace(/'/g, "''") + "'";
2736
+ case STYLE_LITERAL:
2737
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
2738
+ case STYLE_FOLDED:
2739
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
2740
+ case STYLE_DOUBLE:
2741
+ return '"' + escapeString(string) + '"';
2742
+ default:
2743
+ throw new exception("impossible error: invalid scalar style");
2744
+ }
2745
+ })();
2746
+ }
2747
+ function blockHeader(string, indentPerLevel) {
2748
+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
2749
+ var clip = string[string.length - 1] === "\n";
2750
+ var keep = clip && (string[string.length - 2] === "\n" || string === "\n");
2751
+ var chomp = keep ? "+" : clip ? "" : "-";
2752
+ return indentIndicator + chomp + "\n";
2753
+ }
2754
+ function dropEndingNewline(string) {
2755
+ return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
2756
+ }
2757
+ function foldString(string, width) {
2758
+ var lineRe = /(\n+)([^\n]*)/g;
2759
+ var result = (function() {
2760
+ var nextLF = string.indexOf("\n");
2761
+ nextLF = nextLF !== -1 ? nextLF : string.length;
2762
+ lineRe.lastIndex = nextLF;
2763
+ return foldLine(string.slice(0, nextLF), width);
2764
+ })();
2765
+ var prevMoreIndented = string[0] === "\n" || string[0] === " ";
2766
+ var moreIndented;
2767
+ var match;
2768
+ while (match = lineRe.exec(string)) {
2769
+ var prefix = match[1], line = match[2];
2770
+ moreIndented = line[0] === " ";
2771
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
2772
+ prevMoreIndented = moreIndented;
2773
+ }
2774
+ return result;
2775
+ }
2776
+ function foldLine(line, width) {
2777
+ if (line === "" || line[0] === " ") return line;
2778
+ var breakRe = / [^ ]/g;
2779
+ var match;
2780
+ var start = 0, end, curr = 0, next = 0;
2781
+ var result = "";
2782
+ while (match = breakRe.exec(line)) {
2783
+ next = match.index;
2784
+ if (next - start > width) {
2785
+ end = curr > start ? curr : next;
2786
+ result += "\n" + line.slice(start, end);
2787
+ start = end + 1;
2788
+ }
2789
+ curr = next;
2790
+ }
2791
+ result += "\n";
2792
+ if (line.length - start > width && curr > start) {
2793
+ result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
2794
+ } else {
2795
+ result += line.slice(start);
2796
+ }
2797
+ return result.slice(1);
2798
+ }
2799
+ function escapeString(string) {
2800
+ var result = "";
2801
+ var char = 0;
2802
+ var escapeSeq;
2803
+ for (var i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
2804
+ char = codePointAt(string, i);
2805
+ escapeSeq = ESCAPE_SEQUENCES[char];
2806
+ if (!escapeSeq && isPrintable(char)) {
2807
+ result += string[i];
2808
+ if (char >= 65536) result += string[i + 1];
2809
+ } else {
2810
+ result += escapeSeq || encodeHex(char);
2811
+ }
2812
+ }
2813
+ return result;
2814
+ }
2815
+ function writeFlowSequence(state, level, object) {
2816
+ var _result = "", _tag = state.tag, index, length, value;
2817
+ for (index = 0, length = object.length; index < length; index += 1) {
2818
+ value = object[index];
2819
+ if (state.replacer) {
2820
+ value = state.replacer.call(object, String(index), value);
2821
+ }
2822
+ if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
2823
+ if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");
2824
+ _result += state.dump;
2825
+ }
2826
+ }
2827
+ state.tag = _tag;
2828
+ state.dump = "[" + _result + "]";
2829
+ }
2830
+ function writeBlockSequence(state, level, object, compact) {
2831
+ var _result = "", _tag = state.tag, index, length, value;
2832
+ for (index = 0, length = object.length; index < length; index += 1) {
2833
+ value = object[index];
2834
+ if (state.replacer) {
2835
+ value = state.replacer.call(object, String(index), value);
2836
+ }
2837
+ if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
2838
+ if (!compact || _result !== "") {
2839
+ _result += generateNextLine(state, level);
2840
+ }
2841
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2842
+ _result += "-";
2843
+ } else {
2844
+ _result += "- ";
2845
+ }
2846
+ _result += state.dump;
2847
+ }
2848
+ }
2849
+ state.tag = _tag;
2850
+ state.dump = _result || "[]";
2851
+ }
2852
+ function writeFlowMapping(state, level, object) {
2853
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
2854
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
2855
+ pairBuffer = "";
2856
+ if (_result !== "") pairBuffer += ", ";
2857
+ if (state.condenseFlow) pairBuffer += '"';
2858
+ objectKey = objectKeyList[index];
2859
+ objectValue = object[objectKey];
2860
+ if (state.replacer) {
2861
+ objectValue = state.replacer.call(object, objectKey, objectValue);
2862
+ }
2863
+ if (!writeNode(state, level, objectKey, false, false)) {
2864
+ continue;
2865
+ }
2866
+ if (state.dump.length > 1024) pairBuffer += "? ";
2867
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
2868
+ if (!writeNode(state, level, objectValue, false, false)) {
2869
+ continue;
2870
+ }
2871
+ pairBuffer += state.dump;
2872
+ _result += pairBuffer;
2873
+ }
2874
+ state.tag = _tag;
2875
+ state.dump = "{" + _result + "}";
2876
+ }
2877
+ function writeBlockMapping(state, level, object, compact) {
2878
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
2879
+ if (state.sortKeys === true) {
2880
+ objectKeyList.sort();
2881
+ } else if (typeof state.sortKeys === "function") {
2882
+ objectKeyList.sort(state.sortKeys);
2883
+ } else if (state.sortKeys) {
2884
+ throw new exception("sortKeys must be a boolean or a function");
2885
+ }
2886
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
2887
+ pairBuffer = "";
2888
+ if (!compact || _result !== "") {
2889
+ pairBuffer += generateNextLine(state, level);
2890
+ }
2891
+ objectKey = objectKeyList[index];
2892
+ objectValue = object[objectKey];
2893
+ if (state.replacer) {
2894
+ objectValue = state.replacer.call(object, objectKey, objectValue);
2895
+ }
2896
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
2897
+ continue;
2898
+ }
2899
+ explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
2900
+ if (explicitPair) {
2901
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2902
+ pairBuffer += "?";
2903
+ } else {
2904
+ pairBuffer += "? ";
2905
+ }
2906
+ }
2907
+ pairBuffer += state.dump;
2908
+ if (explicitPair) {
2909
+ pairBuffer += generateNextLine(state, level);
2910
+ }
2911
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
2912
+ continue;
2913
+ }
2914
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2915
+ pairBuffer += ":";
2916
+ } else {
2917
+ pairBuffer += ": ";
2918
+ }
2919
+ pairBuffer += state.dump;
2920
+ _result += pairBuffer;
2921
+ }
2922
+ state.tag = _tag;
2923
+ state.dump = _result || "{}";
2924
+ }
2925
+ function detectType(state, object, explicit) {
2926
+ var _result, typeList, index, length, type2, style;
2927
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
2928
+ for (index = 0, length = typeList.length; index < length; index += 1) {
2929
+ type2 = typeList[index];
2930
+ if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
2931
+ if (explicit) {
2932
+ if (type2.multi && type2.representName) {
2933
+ state.tag = type2.representName(object);
2934
+ } else {
2935
+ state.tag = type2.tag;
2936
+ }
2937
+ } else {
2938
+ state.tag = "?";
2939
+ }
2940
+ if (type2.represent) {
2941
+ style = state.styleMap[type2.tag] || type2.defaultStyle;
2942
+ if (_toString.call(type2.represent) === "[object Function]") {
2943
+ _result = type2.represent(object, style);
2944
+ } else if (_hasOwnProperty.call(type2.represent, style)) {
2945
+ _result = type2.represent[style](object, style);
2946
+ } else {
2947
+ throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
2948
+ }
2949
+ state.dump = _result;
2950
+ }
2951
+ return true;
2952
+ }
2953
+ }
2954
+ return false;
2955
+ }
2956
+ function writeNode(state, level, object, block, compact, iskey, isblockseq) {
2957
+ state.tag = null;
2958
+ state.dump = object;
2959
+ if (!detectType(state, object, false)) {
2960
+ detectType(state, object, true);
2961
+ }
2962
+ var type2 = _toString.call(state.dump);
2963
+ var inblock = block;
2964
+ var tagStr;
2965
+ if (block) {
2966
+ block = state.flowLevel < 0 || state.flowLevel > level;
2967
+ }
2968
+ var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
2969
+ if (objectOrArray) {
2970
+ duplicateIndex = state.duplicates.indexOf(object);
2971
+ duplicate = duplicateIndex !== -1;
2972
+ }
2973
+ if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
2974
+ compact = false;
2975
+ }
2976
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
2977
+ state.dump = "*ref_" + duplicateIndex;
2978
+ } else {
2979
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
2980
+ state.usedDuplicates[duplicateIndex] = true;
2981
+ }
2982
+ if (type2 === "[object Object]") {
2983
+ if (block && Object.keys(state.dump).length !== 0) {
2984
+ writeBlockMapping(state, level, state.dump, compact);
2985
+ if (duplicate) {
2986
+ state.dump = "&ref_" + duplicateIndex + state.dump;
2987
+ }
2988
+ } else {
2989
+ writeFlowMapping(state, level, state.dump);
2990
+ if (duplicate) {
2991
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2992
+ }
2993
+ }
2994
+ } else if (type2 === "[object Array]") {
2995
+ if (block && state.dump.length !== 0) {
2996
+ if (state.noArrayIndent && !isblockseq && level > 0) {
2997
+ writeBlockSequence(state, level - 1, state.dump, compact);
2998
+ } else {
2999
+ writeBlockSequence(state, level, state.dump, compact);
3000
+ }
3001
+ if (duplicate) {
3002
+ state.dump = "&ref_" + duplicateIndex + state.dump;
3003
+ }
3004
+ } else {
3005
+ writeFlowSequence(state, level, state.dump);
3006
+ if (duplicate) {
3007
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
3008
+ }
3009
+ }
3010
+ } else if (type2 === "[object String]") {
3011
+ if (state.tag !== "?") {
3012
+ writeScalar(state, state.dump, level, iskey, inblock);
3013
+ }
3014
+ } else if (type2 === "[object Undefined]") {
3015
+ return false;
3016
+ } else {
3017
+ if (state.skipInvalid) return false;
3018
+ throw new exception("unacceptable kind of an object to dump " + type2);
3019
+ }
3020
+ if (state.tag !== null && state.tag !== "?") {
3021
+ tagStr = encodeURI(
3022
+ state.tag[0] === "!" ? state.tag.slice(1) : state.tag
3023
+ ).replace(/!/g, "%21");
3024
+ if (state.tag[0] === "!") {
3025
+ tagStr = "!" + tagStr;
3026
+ } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
3027
+ tagStr = "!!" + tagStr.slice(18);
3028
+ } else {
3029
+ tagStr = "!<" + tagStr + ">";
3030
+ }
3031
+ state.dump = tagStr + " " + state.dump;
3032
+ }
3033
+ }
3034
+ return true;
3035
+ }
3036
+ function getDuplicateReferences(object, state) {
3037
+ var objects = [], duplicatesIndexes = [], index, length;
3038
+ inspectNode(object, objects, duplicatesIndexes);
3039
+ for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
3040
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
3041
+ }
3042
+ state.usedDuplicates = new Array(length);
3043
+ }
3044
+ function inspectNode(object, objects, duplicatesIndexes) {
3045
+ var objectKeyList, index, length;
3046
+ if (object !== null && typeof object === "object") {
3047
+ index = objects.indexOf(object);
3048
+ if (index !== -1) {
3049
+ if (duplicatesIndexes.indexOf(index) === -1) {
3050
+ duplicatesIndexes.push(index);
3051
+ }
3052
+ } else {
3053
+ objects.push(object);
3054
+ if (Array.isArray(object)) {
3055
+ for (index = 0, length = object.length; index < length; index += 1) {
3056
+ inspectNode(object[index], objects, duplicatesIndexes);
3057
+ }
3058
+ } else {
3059
+ objectKeyList = Object.keys(object);
3060
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
3061
+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
3062
+ }
3063
+ }
3064
+ }
3065
+ }
3066
+ }
3067
+ function dump$1(input, options) {
3068
+ options = options || {};
3069
+ var state = new State(options);
3070
+ if (!state.noRefs) getDuplicateReferences(input, state);
3071
+ var value = input;
3072
+ if (state.replacer) {
3073
+ value = state.replacer.call({ "": value }, "", value);
3074
+ }
3075
+ if (writeNode(state, 0, value, true, true)) return state.dump + "\n";
3076
+ return "";
3077
+ }
3078
+ var dump_1 = dump$1;
3079
+ var dumper = {
3080
+ dump: dump_1
3081
+ };
3082
+ function renamed(from, to) {
3083
+ return function() {
3084
+ throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
3085
+ };
3086
+ }
3087
+ var load = loader.load;
3088
+ var loadAll = loader.loadAll;
3089
+ var dump = dumper.dump;
3090
+ var safeLoad = renamed("safeLoad", "load");
3091
+ var safeLoadAll = renamed("safeLoadAll", "loadAll");
3092
+ var safeDump = renamed("safeDump", "dump");
3093
+
3094
+ // src/local-evaluator/pdlss-parser.ts
3095
+ var import_fs = require("fs");
3096
+
3097
+ // src/local-evaluator/schema.ts
3098
+ function validatePolicy(policy) {
3099
+ const errors = [];
3100
+ if (!policy || typeof policy !== "object") {
3101
+ return { valid: false, errors: [{ path: "", message: "Policy must be an object" }] };
3102
+ }
3103
+ const p = policy;
3104
+ if (typeof p.version !== "string") {
3105
+ errors.push({ path: "version", message: "version is required and must be a string" });
3106
+ }
3107
+ if (typeof p.name !== "string") {
3108
+ errors.push({ path: "name", message: "name is required and must be a string" });
3109
+ }
3110
+ if (!Array.isArray(p.purposes)) {
3111
+ errors.push({ path: "purposes", message: "purposes is required and must be an array" });
3112
+ } else {
3113
+ p.purposes.forEach((purpose, i) => {
3114
+ errors.push(...validatePurpose(purpose, `purposes[${i}]`));
3115
+ });
3116
+ }
3117
+ if (p.scope !== void 0) {
3118
+ errors.push(...validateScope(p.scope, "scope"));
3119
+ }
3120
+ if (p.limits !== void 0) {
3121
+ errors.push(...validateLimits(p.limits, "limits"));
3122
+ }
3123
+ if (p.riskThresholds !== void 0) {
3124
+ errors.push(...validateRiskThresholds(p.riskThresholds, "riskThresholds"));
3125
+ }
3126
+ return { valid: errors.length === 0, errors };
3127
+ }
3128
+ function validatePurpose(purpose, path) {
3129
+ const errors = [];
3130
+ if (!purpose || typeof purpose !== "object") {
3131
+ return [{ path, message: "purpose must be an object" }];
3132
+ }
3133
+ const p = purpose;
3134
+ if (typeof p.id !== "string" || !p.id) {
3135
+ errors.push({ path: `${path}.id`, message: "id is required and must be a non-empty string" });
3136
+ }
3137
+ if (typeof p.allowed !== "boolean") {
3138
+ errors.push({ path: `${path}.allowed`, message: "allowed is required and must be a boolean" });
3139
+ }
3140
+ if (p.targets !== void 0 && !isStringArray(p.targets)) {
3141
+ errors.push({ path: `${path}.targets`, message: "targets must be an array of strings" });
3142
+ }
3143
+ if (p.blockedPatterns !== void 0 && !isStringArray(p.blockedPatterns)) {
3144
+ errors.push({ path: `${path}.blockedPatterns`, message: "blockedPatterns must be an array of strings" });
3145
+ }
3146
+ if (p.requiresApproval !== void 0 && typeof p.requiresApproval !== "boolean") {
3147
+ errors.push({ path: `${path}.requiresApproval`, message: "requiresApproval must be a boolean" });
3148
+ }
3149
+ return errors;
3150
+ }
3151
+ function validateScope(scope, path) {
3152
+ const errors = [];
3153
+ if (typeof scope !== "object" || scope === null) {
3154
+ return [{ path, message: "scope must be an object" }];
3155
+ }
3156
+ const s = scope;
3157
+ for (const field of ["allowedDomains", "blockedDomains", "blockedResources"]) {
3158
+ if (s[field] !== void 0 && !isStringArray(s[field])) {
3159
+ errors.push({ path: `${path}.${field}`, message: `${field} must be an array of strings` });
3160
+ }
3161
+ }
3162
+ return errors;
3163
+ }
3164
+ function validateLimits(limits, path) {
3165
+ const errors = [];
3166
+ if (typeof limits !== "object" || limits === null) {
3167
+ return [{ path, message: "limits must be an object" }];
3168
+ }
3169
+ const l = limits;
3170
+ if (l.maxTransactionAmount !== void 0 && typeof l.maxTransactionAmount !== "number") {
3171
+ errors.push({ path: `${path}.maxTransactionAmount`, message: "maxTransactionAmount must be a number" });
3172
+ }
3173
+ if (l.maxRequestsPerHour !== void 0 && typeof l.maxRequestsPerHour !== "number") {
3174
+ errors.push({ path: `${path}.maxRequestsPerHour`, message: "maxRequestsPerHour must be a number" });
3175
+ }
3176
+ if (l.currency !== void 0 && typeof l.currency !== "string") {
3177
+ errors.push({ path: `${path}.currency`, message: "currency must be a string" });
3178
+ }
3179
+ return errors;
3180
+ }
3181
+ function validateRiskThresholds(thresholds, path) {
3182
+ const errors = [];
3183
+ if (typeof thresholds !== "object" || thresholds === null) {
3184
+ return [{ path, message: "riskThresholds must be an object" }];
3185
+ }
3186
+ const t = thresholds;
3187
+ for (const range of ["autoAllow", "requireApproval", "autoBlock"]) {
3188
+ if (!t[range] || typeof t[range] !== "object") {
3189
+ errors.push({ path: `${path}.${range}`, message: `${range} is required and must be an object with min and max` });
3190
+ continue;
3191
+ }
3192
+ const r = t[range];
3193
+ if (typeof r.min !== "number" || typeof r.max !== "number") {
3194
+ errors.push({ path: `${path}.${range}`, message: `${range} must have numeric min and max` });
3195
+ } else if (r.min > r.max) {
3196
+ errors.push({ path: `${path}.${range}`, message: `${range}.min must be <= ${range}.max` });
3197
+ }
3198
+ }
3199
+ if (isValidThresholdShape(t)) {
3200
+ const thresholdObj = t;
3201
+ if (thresholdObj.autoAllow.max + 1 !== thresholdObj.requireApproval.min) {
3202
+ errors.push({
3203
+ path: `${path}`,
3204
+ message: `Gap between autoAllow.max (${thresholdObj.autoAllow.max}) and requireApproval.min (${thresholdObj.requireApproval.min}). Ranges must be contiguous.`
3205
+ });
3206
+ }
3207
+ if (thresholdObj.requireApproval.max + 1 !== thresholdObj.autoBlock.min) {
3208
+ errors.push({
3209
+ path: `${path}`,
3210
+ message: `Gap between requireApproval.max (${thresholdObj.requireApproval.max}) and autoBlock.min (${thresholdObj.autoBlock.min}). Ranges must be contiguous.`
3211
+ });
3212
+ }
3213
+ }
3214
+ return errors;
3215
+ }
3216
+ function isStringArray(val) {
3217
+ return Array.isArray(val) && val.every((v) => typeof v === "string");
3218
+ }
3219
+ function isValidThresholdShape(t) {
3220
+ for (const key of ["autoAllow", "requireApproval", "autoBlock"]) {
3221
+ const r = t[key];
3222
+ if (!r || typeof r !== "object") return false;
3223
+ const range = r;
3224
+ if (typeof range.min !== "number" || typeof range.max !== "number") return false;
3225
+ }
3226
+ return true;
3227
+ }
3228
+
3229
+ // src/local-evaluator/pdlss-parser.ts
3230
+ function parseYaml(yamlContent) {
3231
+ let parsed;
3232
+ try {
3233
+ parsed = load(yamlContent);
3234
+ } catch (err) {
3235
+ const message = err instanceof Error ? err.message : "Invalid YAML";
3236
+ return {
3237
+ policy: null,
3238
+ validation: { valid: false, errors: [{ path: "", message: `YAML parse error: ${message}` }] },
3239
+ rawYaml: yamlContent
3240
+ };
3241
+ }
3242
+ const validation = validatePolicy(parsed);
3243
+ if (!validation.valid) {
3244
+ return { policy: null, validation, rawYaml: yamlContent };
3245
+ }
3246
+ return {
3247
+ policy: parsed,
3248
+ validation,
3249
+ rawYaml: yamlContent
3250
+ };
3251
+ }
3252
+ function parseFile(filePath) {
3253
+ let content;
3254
+ try {
3255
+ content = (0, import_fs.readFileSync)(filePath, "utf-8");
3256
+ } catch (err) {
3257
+ const message = err instanceof Error ? err.message : "File read error";
3258
+ return {
3259
+ policy: null,
3260
+ validation: { valid: false, errors: [{ path: "", message: `Failed to read policy file: ${message}` }] }
3261
+ };
3262
+ }
3263
+ return parseYaml(content);
3264
+ }
3265
+
3266
+ // src/gateway/modes/local.ts
3267
+ function loadEvaluator(config) {
3268
+ if (config.policy) {
3269
+ return new LocalEvaluator(config.policy);
3270
+ }
3271
+ if (config.policyFile) {
3272
+ const result = parseFile(config.policyFile);
3273
+ if (!result.policy) {
3274
+ const errors = result.validation.errors.map((e) => `${e.path}: ${e.message}`).join("; ");
3275
+ throw new Error(`Invalid policy file ${config.policyFile}: ${errors}`);
3276
+ }
3277
+ return new LocalEvaluator(result.policy);
3278
+ }
3279
+ throw new Error("Local mode requires either policyFile or policy in config");
3280
+ }
3281
+ function verifyLocal(evaluator, context) {
3282
+ return evaluator.evaluate(context);
3283
+ }
3284
+
3285
+ // src/access-levels.ts
3286
+ var ACCESS_LEVEL_HIERARCHY = {
3287
+ none: 0,
3288
+ guidance: 1,
3289
+ "read-only": 2,
3290
+ standard: 3,
3291
+ full: 4,
3292
+ internal: 5
3293
+ };
3294
+ var DEFAULT_TRUST_THRESHOLDS = {
3295
+ none: 0,
3296
+ guidance: 0,
3297
+ "read-only": 20,
3298
+ standard: 40,
3299
+ full: 70,
3300
+ internal: 0
3301
+ // Internal is based on org membership, not score
3302
+ };
3303
+ function getTrustLevel(score) {
3304
+ if (score >= 80) return "PLATINUM";
3305
+ if (score >= 60) return "GOLD";
3306
+ if (score >= 40) return "SILVER";
3307
+ return "BRONZE";
3308
+ }
3309
+ function getAccessLevelForScore(trustScore, thresholds = DEFAULT_TRUST_THRESHOLDS) {
3310
+ if (trustScore >= thresholds.full) return "full";
3311
+ if (trustScore >= thresholds.standard) return "standard";
3312
+ if (trustScore >= thresholds["read-only"]) return "read-only";
3313
+ return "guidance";
3314
+ }
3315
+ function determineAccessLevel(verified, trustScore, isOrgMember, customThresholds) {
3316
+ if (!verified) {
3317
+ return "guidance";
3318
+ }
3319
+ if (isOrgMember) {
3320
+ return "internal";
3321
+ }
3322
+ const thresholds = {
3323
+ ...DEFAULT_TRUST_THRESHOLDS,
3324
+ ...customThresholds
3325
+ };
3326
+ return getAccessLevelForScore(trustScore, thresholds);
3327
+ }
3328
+
3329
+ // src/verify.ts
3330
+ var DEFAULT_CONFIG = {
3331
+ apiBaseUrl: "https://api.astrasync.ai",
3332
+ defaultAccessLevel: "guidance",
3333
+ minTrustScore: 40,
3334
+ minTrustScoreForFull: 70,
3335
+ cacheTtl: 300,
3336
+ // 5 minutes
3337
+ debug: false
3338
+ };
3339
+ var verificationCache = /* @__PURE__ */ new Map();
3340
+ function getCacheKey(credentials) {
3341
+ return `${credentials.astraId || ""}-${credentials.apiKey || ""}-${credentials.jwt || ""}`;
3342
+ }
3343
+ function getCachedResult(credentials) {
3344
+ const key = getCacheKey(credentials);
3345
+ const cached = verificationCache.get(key);
3346
+ if (cached && cached.expiresAt > Date.now()) {
3347
+ return cached.result;
3348
+ }
3349
+ if (cached) {
3350
+ verificationCache.delete(key);
3351
+ }
3352
+ return null;
3353
+ }
3354
+ function cacheResult(credentials, result, ttlSeconds) {
3355
+ const key = getCacheKey(credentials);
3356
+ verificationCache.set(key, {
3357
+ result,
3358
+ expiresAt: Date.now() + ttlSeconds * 1e3
3359
+ });
3360
+ }
3361
+ function hasCredentials(credentials) {
3362
+ return !!(credentials.astraId || credentials.apiKey || credentials.jwt);
3363
+ }
3364
+ function createGuidanceResponse(config, reason) {
3365
+ const guidance = {
3366
+ message: "This service verifies AI agents before granting access. Please register your agent with AstraSync.",
3367
+ registrationUrl: `${config.apiBaseUrl.replace("/api", "")}/register`,
3368
+ documentationUrl: `${config.apiBaseUrl.replace("/api", "")}/docs/agent-access`,
3369
+ steps: [
3370
+ "Register for an AstraSync account",
3371
+ "Create and register your agent",
3372
+ "Add your ASTRA-ID to request headers",
3373
+ "Retry your request"
3374
+ ]
3375
+ };
3376
+ return {
3377
+ verified: false,
3378
+ accessLevel: "guidance",
3379
+ guidance,
3380
+ denialReasons: reason ? [reason] : ["No valid agent credentials provided"],
3381
+ verifiedAt: /* @__PURE__ */ new Date()
3382
+ };
3383
+ }
3384
+ async function callVerifyAccessAPI(config, request) {
3385
+ const { credentials, ...requestData } = request;
3386
+ const body = {
3387
+ agentId: credentials.astraId,
3388
+ purpose: requestData.purpose || "general"
3389
+ };
3390
+ if (requestData.action) body.action = requestData.action;
3391
+ if (requestData.resourceType) body.resourceType = requestData.resourceType;
3392
+ if (requestData.resource) body.resource = requestData.resource;
3393
+ if (requestData.jurisdiction) body.jurisdiction = requestData.jurisdiction;
3394
+ if (requestData.transactionValue) body.transactionValue = requestData.transactionValue;
3395
+ if (requestData.currency) body.currency = requestData.currency;
3396
+ if (requestData.isSubAgentRequest) body.isSubAgentRequest = requestData.isSubAgentRequest;
3397
+ if (requestData.parentAgentId) body.parentAgentId = requestData.parentAgentId;
3398
+ if (requestData.subAgentDepth !== void 0) body.subAgentDepth = requestData.subAgentDepth;
3399
+ if (requestData.enableRuntimeChallenge) body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;
3400
+ if (requestData.createSession) body.createSession = requestData.createSession;
3401
+ if (requestData.durationRequired) body.durationRequired = requestData.durationRequired;
3402
+ if (requestData.counterpartyType) body.counterpartyType = requestData.counterpartyType;
3403
+ if (requestData.counterpartyUrl) body.counterpartyUrl = requestData.counterpartyUrl;
3404
+ if (requestData.runtimeChallengeOptions) body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;
3405
+ const headers = {
3406
+ "Content-Type": "application/json",
3407
+ ...config.customHeaders
3408
+ };
3409
+ if (config.apiKey) {
3410
+ headers["X-API-Key"] = config.apiKey;
3411
+ }
3412
+ if (credentials.authorizationHeader) {
3413
+ headers["Authorization"] = credentials.authorizationHeader;
3414
+ }
3415
+ try {
3416
+ const response = await fetch(`${config.apiBaseUrl}/agents/verify-access`, {
3417
+ method: "POST",
3418
+ headers,
3419
+ body: JSON.stringify(body)
3420
+ });
3421
+ const data = await response.json();
3422
+ if (!response.ok) {
3423
+ return {
3424
+ success: false,
3425
+ error: data.message || data.error || `API returned ${response.status}`
3426
+ };
3427
+ }
3428
+ return data;
3429
+ } catch (error) {
3430
+ const message = error instanceof Error ? error.message : "Unknown error";
3431
+ return {
3432
+ success: false,
3433
+ error: `Failed to call verify-access API: ${message}`
3434
+ };
3435
+ }
3436
+ }
3437
+ async function verify(config, request) {
3438
+ const mergedConfig = { ...DEFAULT_CONFIG, ...config };
3439
+ if (!hasCredentials(request.credentials)) {
3440
+ return createGuidanceResponse(mergedConfig, "No agent credentials provided");
3441
+ }
3442
+ if (mergedConfig.cacheTtl && mergedConfig.cacheTtl > 0) {
3443
+ const cached = getCachedResult(request.credentials);
3444
+ if (cached) {
3445
+ if (mergedConfig.debug) {
3446
+ console.log("[VerificationGateway] Returning cached result");
3447
+ }
3448
+ return cached;
3449
+ }
3450
+ }
3451
+ const enrichedRequest = { ...request };
3452
+ if (!enrichedRequest.counterpartyUrl && mergedConfig.counterpartyUrl) {
3453
+ enrichedRequest.counterpartyUrl = mergedConfig.counterpartyUrl;
3454
+ }
3455
+ if (!enrichedRequest.counterpartyType && mergedConfig.counterpartyType) {
3456
+ enrichedRequest.counterpartyType = mergedConfig.counterpartyType;
3457
+ }
3458
+ if (mergedConfig.debug) {
3459
+ console.log("[VerificationGateway] Calling verify-access API");
3460
+ }
3461
+ const apiResponse = await callVerifyAccessAPI(mergedConfig, enrichedRequest);
3462
+ if (!apiResponse.success) {
3463
+ return createGuidanceResponse(mergedConfig, apiResponse.error);
3464
+ }
3465
+ if (!apiResponse.access?.allowed) {
3466
+ const result2 = {
3467
+ verified: false,
3468
+ accessLevel: "guidance",
3469
+ denialReasons: apiResponse.access?.reason ? [apiResponse.access.reason] : ["Access denied"],
3470
+ requiresStepUp: apiResponse.access?.requiresStepUp,
3471
+ requiresApproval: apiResponse.access?.requiresApproval,
3472
+ guidance: {
3473
+ message: apiResponse.access?.reason || "Access denied by PDLSS policy",
3474
+ registrationUrl: `${mergedConfig.apiBaseUrl?.replace("/api", "")}/register`,
3475
+ documentationUrl: `${mergedConfig.apiBaseUrl?.replace("/api", "")}/docs/pdlss`
3476
+ },
3477
+ verifiedAt: /* @__PURE__ */ new Date(),
3478
+ // Extract sessionId so decisions can be recorded for denials too
3479
+ sessionId: apiResponse.sessionId,
3480
+ recommendation: apiResponse.recommendation,
3481
+ recommendationReasons: apiResponse.recommendationReasons
3482
+ };
3483
+ return result2;
3484
+ }
3485
+ const agent = apiResponse.agent ? {
3486
+ astraId: apiResponse.agent.astraId,
3487
+ name: apiResponse.agent.name,
3488
+ trustScore: apiResponse.agent.trustScore,
3489
+ trustLevel: getTrustLevel(apiResponse.agent.trustScore),
3490
+ blockchainVerified: apiResponse.agent.blockchainStatus === "verified",
3491
+ status: apiResponse.agent.agentStatus
3492
+ } : void 0;
3493
+ const developer = apiResponse.developer ? {
3494
+ astradId: apiResponse.developer.kyaOwnerId,
3495
+ name: apiResponse.developer.fullName,
3496
+ trustScore: apiResponse.developer.trustScore || 0,
3497
+ verified: apiResponse.developer.identityVerified
3498
+ } : void 0;
3499
+ const organization = apiResponse.organization ? {
3500
+ name: apiResponse.organization.name,
3501
+ verified: apiResponse.organization.verified,
3502
+ trustScore: apiResponse.organization.trustScore
3503
+ } : void 0;
3504
+ const pdlss = apiResponse.access?.pdlss ? {
3505
+ purposeAllowed: apiResponse.access.pdlss.purposeAllowed,
3506
+ withinDuration: apiResponse.access.pdlss.withinDuration,
3507
+ withinLimits: apiResponse.access.pdlss.withinLimits,
3508
+ scopeAllowed: apiResponse.access.pdlss.scopeAllowed,
3509
+ selfInstantiationAllowed: apiResponse.access.pdlss.selfInstantiationAllowed,
3510
+ appliedPolicy: apiResponse.access.appliedPolicy
3511
+ } : void 0;
3512
+ const trustScore = agent?.trustScore || 0;
3513
+ const isOrgMember = false;
3514
+ const accessLevel = determineAccessLevel(
3515
+ true,
3516
+ trustScore,
3517
+ isOrgMember,
3518
+ {
3519
+ "read-only": 20,
3520
+ standard: mergedConfig.minTrustScore || 40,
3521
+ full: mergedConfig.minTrustScoreForFull || 70
3522
+ }
3523
+ );
3524
+ const result = {
3525
+ verified: true,
3526
+ accessLevel,
3527
+ agent,
3528
+ developer,
3529
+ organization,
3530
+ pdlss,
3531
+ requiresStepUp: apiResponse.access?.requiresStepUp,
3532
+ requiresApproval: apiResponse.access?.requiresApproval,
3533
+ verifiedAt: /* @__PURE__ */ new Date(),
3534
+ cacheTtl: mergedConfig.cacheTtl,
3535
+ // Handshake Protocol v10 enhanced fields (present when backend returns them)
3536
+ sessionId: apiResponse.sessionId,
3537
+ runtimeChallenge: apiResponse.runtimeChallenge,
3538
+ tokenGuidance: apiResponse.tokenGuidance,
3539
+ recommendation: apiResponse.recommendation,
3540
+ recommendationReasons: apiResponse.recommendationReasons
3541
+ };
3542
+ if (result.recommendation === "deny") {
3543
+ result.verified = false;
3544
+ result.accessLevel = "none";
3545
+ result.denialReasons = result.recommendationReasons || ["Access denied by AstraSync recommendation"];
3546
+ if (result.runtimeChallenge) {
3547
+ result.guidance = {
3548
+ message: `Verification failed: ${result.runtimeChallenge.reason || "runtime challenge failed"}`,
3549
+ registrationUrl: `${mergedConfig.apiBaseUrl?.replace("/api", "")}/register`,
3550
+ documentationUrl: `${mergedConfig.apiBaseUrl?.replace("/api", "")}/docs/runtime-challenge`
3551
+ };
3552
+ }
3553
+ } else if (result.recommendation === "step_up_required") {
3554
+ result.requiresStepUp = true;
3555
+ if (ACCESS_LEVEL_HIERARCHY[result.accessLevel] > ACCESS_LEVEL_HIERARCHY["read-only"]) {
3556
+ result.accessLevel = "read-only";
3557
+ }
3558
+ result.denialReasons = result.recommendationReasons || ["Step-up verification required"];
3559
+ }
3560
+ if (mergedConfig.cacheTtl && mergedConfig.cacheTtl > 0 && result.recommendation !== "deny") {
3561
+ cacheResult(request.credentials, result, mergedConfig.cacheTtl);
3562
+ }
3563
+ return result;
3564
+ }
3565
+
3566
+ // src/gateway/modes/online.ts
3567
+ function toGatewayConfig(config) {
3568
+ return {
3569
+ apiBaseUrl: config.apiBaseUrl || "https://api.astrasync.ai",
3570
+ apiKey: config.apiKey,
3571
+ defaultAccessLevel: config.defaultAccessLevel,
3572
+ minTrustScore: config.minTrustScore,
3573
+ minTrustScoreForFull: config.minTrustScoreForFull,
3574
+ cacheTtl: config.cacheTtl,
3575
+ debug: config.debug,
3576
+ customHeaders: config.customHeaders,
3577
+ counterpartyUrl: config.counterpartyUrl,
3578
+ counterpartyType: config.counterpartyType
3579
+ };
3580
+ }
3581
+ function toVerificationRequest(context, astraId) {
3582
+ return {
3583
+ credentials: { astraId },
3584
+ purpose: context.purpose,
3585
+ action: context.action,
3586
+ resourceType: context.resourceType,
3587
+ resource: context.target,
3588
+ transactionValue: context.transactionValue,
3589
+ currency: context.currency,
3590
+ createSession: true
3591
+ };
3592
+ }
3593
+ function toDecision(result) {
3594
+ if (result.verified) {
3595
+ return {
3596
+ recommendation: "ALLOW",
3597
+ reason: `Verified with access level: ${result.accessLevel}`,
3598
+ trustScore: result.agent?.trustScore,
3599
+ sessionId: "sessionId" in result ? result.sessionId : void 0
3600
+ };
3601
+ }
3602
+ if (result.requiresStepUp || result.requiresApproval) {
3603
+ return {
3604
+ recommendation: "MANUAL_REVIEW",
3605
+ reason: result.denialReasons?.[0] || "Step-up or approval required",
3606
+ trustScore: result.agent?.trustScore
3607
+ };
3608
+ }
3609
+ return {
3610
+ recommendation: "DENY",
3611
+ reason: result.denialReasons?.[0] || "Access denied",
3612
+ trustScore: result.agent?.trustScore
3613
+ };
3614
+ }
3615
+ async function verifyOnline(config, context, astraId) {
3616
+ const gatewayConfig = toGatewayConfig(config);
3617
+ const request = toVerificationRequest(context, astraId);
3618
+ const result = await verify(gatewayConfig, request);
3619
+ return toDecision(result);
3620
+ }
3621
+
3622
+ // src/gateway/modes/hybrid.ts
3623
+ var import_fs2 = require("fs");
3624
+ var import_path = require("path");
3625
+ var MAX_QUEUE_SIZE = 1e3;
3626
+ var MAX_RETRIES = 3;
3627
+ var HybridSyncQueue = class {
3628
+ constructor(config, persistPath) {
3629
+ this.queue = [];
3630
+ this.timer = null;
3631
+ this.processing = false;
3632
+ this.persistPath = null;
3633
+ this.config = config;
3634
+ this.persistPath = persistPath ?? null;
3635
+ this.loadFromDisk();
3636
+ }
3637
+ /**
3638
+ * Start periodic sync.
3639
+ */
3640
+ start(intervalMs) {
3641
+ if (this.timer) return;
3642
+ this.timer = setInterval(() => this.flush(), intervalMs);
3643
+ }
3644
+ /**
3645
+ * Stop periodic sync and flush remaining entries.
3646
+ */
3647
+ async stop() {
3648
+ if (this.timer) {
3649
+ clearInterval(this.timer);
3650
+ this.timer = null;
3651
+ }
3652
+ await this.flush();
3653
+ this.saveToDisk();
3654
+ }
3655
+ /**
3656
+ * Add a decision to the sync queue.
3657
+ */
3658
+ enqueue(context, decision) {
3659
+ if (this.queue.length >= MAX_QUEUE_SIZE) {
3660
+ this.queue.shift();
3661
+ }
3662
+ this.queue.push({
3663
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
3664
+ context,
3665
+ decision,
3666
+ timestamp: /* @__PURE__ */ new Date(),
3667
+ retryCount: 0,
3668
+ status: "pending"
3669
+ });
3670
+ this.saveToDisk();
3671
+ }
3672
+ /**
3673
+ * Flush pending entries to the API.
3674
+ */
3675
+ async flush() {
3676
+ if (this.processing) return;
3677
+ this.processing = true;
3678
+ try {
3679
+ const pending = this.queue.filter((e) => e.status === "pending");
3680
+ for (const entry of pending) {
3681
+ try {
3682
+ await verifyOnline(this.config, entry.context);
3683
+ entry.status = "synced";
3684
+ } catch {
3685
+ entry.retryCount++;
3686
+ if (entry.retryCount >= MAX_RETRIES) {
3687
+ entry.status = "failed";
3688
+ }
3689
+ }
3690
+ }
3691
+ this.queue = this.queue.filter((e) => e.status === "pending");
3692
+ this.saveToDisk();
3693
+ } finally {
3694
+ this.processing = false;
3695
+ }
3696
+ }
3697
+ /**
3698
+ * Get queue status.
3699
+ */
3700
+ getStatus() {
3701
+ return {
3702
+ pending: this.queue.filter((e) => e.status === "pending").length,
3703
+ total: this.queue.length
3704
+ };
3705
+ }
3706
+ /**
3707
+ * Load persisted queue entries from disk.
3708
+ */
3709
+ loadFromDisk() {
3710
+ if (!this.persistPath) return;
3711
+ try {
3712
+ if (!(0, import_fs2.existsSync)(this.persistPath)) return;
3713
+ const data = (0, import_fs2.readFileSync)(this.persistPath, "utf-8");
3714
+ const entries = JSON.parse(data);
3715
+ this.queue = entries.filter((e) => e.status === "pending").map((e) => ({ ...e, timestamp: new Date(e.timestamp) }));
3716
+ } catch {
3717
+ this.queue = [];
3718
+ }
3719
+ }
3720
+ /**
3721
+ * Persist queue entries to disk.
3722
+ */
3723
+ saveToDisk() {
3724
+ if (!this.persistPath) return;
3725
+ try {
3726
+ const dir = (0, import_path.dirname)(this.persistPath);
3727
+ if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
3728
+ (0, import_fs2.writeFileSync)(this.persistPath, JSON.stringify(this.queue, null, 2), "utf-8");
3729
+ } catch {
3730
+ }
3731
+ }
3732
+ };
3733
+ function verifyHybrid(evaluator, syncQueue, context) {
3734
+ const decision = evaluator.evaluate(context);
3735
+ syncQueue.enqueue(context, decision);
3736
+ return decision;
3737
+ }
3738
+
3739
+ // src/gateway/trace-logger.ts
3740
+ var import_fs3 = require("fs");
3741
+ var import_path2 = require("path");
3742
+ var MAX_FILE_SIZE = 10 * 1024 * 1024;
3743
+ var MAX_FILES = 10;
3744
+ var TraceLogger = class {
3745
+ constructor(tracePath, enabled) {
3746
+ this.tracePath = tracePath;
3747
+ this.enabled = enabled;
3748
+ if (enabled) {
3749
+ (0, import_fs3.mkdirSync)(tracePath, { recursive: true });
3750
+ }
3751
+ }
3752
+ /**
3753
+ * Log an evaluation event.
3754
+ */
3755
+ logEvaluation(context, decision) {
3756
+ if (!this.enabled) return;
3757
+ this.write({
3758
+ id: this.generateId(),
3759
+ timestamp: /* @__PURE__ */ new Date(),
3760
+ type: "evaluation",
3761
+ context,
3762
+ decision
3763
+ });
3764
+ }
3765
+ /**
3766
+ * Log a mode switch event.
3767
+ */
3768
+ logModeSwitch(from, to) {
3769
+ if (!this.enabled) return;
3770
+ this.write({
3771
+ id: this.generateId(),
3772
+ timestamp: /* @__PURE__ */ new Date(),
3773
+ type: "mode_switch",
3774
+ metadata: { from, to }
3775
+ });
3776
+ }
3777
+ /**
3778
+ * Log an error event.
3779
+ */
3780
+ logError(error, context) {
3781
+ if (!this.enabled) return;
3782
+ this.write({
3783
+ id: this.generateId(),
3784
+ timestamp: /* @__PURE__ */ new Date(),
3785
+ type: "error",
3786
+ context,
3787
+ metadata: { error }
3788
+ });
3789
+ }
3790
+ write(event) {
3791
+ try {
3792
+ const filePath = this.getCurrentFilePath();
3793
+ const line = JSON.stringify(event) + "\n";
3794
+ if ((0, import_fs3.existsSync)(filePath)) {
3795
+ const stats = (0, import_fs3.statSync)(filePath);
3796
+ if (stats.size > MAX_FILE_SIZE) {
3797
+ this.rotate();
3798
+ }
3799
+ }
3800
+ (0, import_fs3.appendFileSync)(filePath, line);
3801
+ } catch {
3802
+ }
3803
+ }
3804
+ getCurrentFilePath() {
3805
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3806
+ return (0, import_path2.join)(this.tracePath, `trace-${date}.jsonl`);
3807
+ }
3808
+ rotate() {
3809
+ try {
3810
+ const files = (0, import_fs3.readdirSync)(this.tracePath).filter((f) => f.startsWith("trace-") && f.endsWith(".jsonl")).sort();
3811
+ while (files.length >= MAX_FILES) {
3812
+ const oldest = files.shift();
3813
+ (0, import_fs3.unlinkSync)((0, import_path2.join)(this.tracePath, oldest));
3814
+ }
3815
+ } catch {
3816
+ }
3817
+ }
3818
+ generateId() {
3819
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
3820
+ }
3821
+ };
3822
+
3823
+ // src/gateway/gateway.ts
3824
+ var AstraSyncGateway = class {
3825
+ constructor(config) {
3826
+ this.evaluator = null;
3827
+ this.syncQueue = null;
3828
+ this.traceLogger = null;
3829
+ this.initialized = false;
3830
+ this.config = config;
3831
+ this.validateConfig();
3832
+ }
3833
+ validateConfig() {
3834
+ const { mode } = this.config;
3835
+ if (mode === "online") {
3836
+ if (!this.config.apiBaseUrl && !this.config.apiKey) {
3837
+ throw new Error("Online mode requires apiBaseUrl or apiKey");
3838
+ }
3839
+ }
3840
+ if (mode === "local") {
3841
+ if (!this.config.policyFile && !this.config.policy) {
3842
+ throw new Error("Local mode requires policyFile or policy");
3843
+ }
3844
+ }
3845
+ if (mode === "hybrid") {
3846
+ if (!this.config.policyFile && !this.config.policy) {
3847
+ throw new Error("Hybrid mode requires policyFile or policy");
3848
+ }
3849
+ }
3850
+ }
3851
+ /**
3852
+ * Initialize the gateway (loads policy files, starts sync queues).
3853
+ * Called automatically on first evaluate() if not called manually.
3854
+ */
3855
+ async initialize() {
3856
+ if (this.initialized) return;
3857
+ const { mode } = this.config;
3858
+ if (mode === "local" || mode === "hybrid") {
3859
+ this.evaluator = loadEvaluator(this.config);
3860
+ }
3861
+ if (mode === "hybrid") {
3862
+ const persistPath = this.config.tracePath ? `${this.config.tracePath}/../sync-queue.json` : ".astrasync/sync-queue.json";
3863
+ this.syncQueue = new HybridSyncQueue(this.config, persistPath);
3864
+ const intervalMs = (this.config.syncInterval || 3600) * 1e3;
3865
+ this.syncQueue.start(intervalMs);
3866
+ }
3867
+ if (this.config.traceEnabled) {
3868
+ const tracePath = this.config.tracePath || ".astrasync/traces";
3869
+ this.traceLogger = new TraceLogger(tracePath, true);
3870
+ }
3871
+ this.initialized = true;
3872
+ if (this.config.debug) {
3873
+ const posture = this.config.posture || "active";
3874
+ console.log(`[AstraSyncGateway] Initialized in ${mode} mode (${posture})`);
3875
+ }
3876
+ }
3877
+ /**
3878
+ * Graceful shutdown. Flushes sync queue and cleans up resources.
3879
+ */
3880
+ async shutdown() {
3881
+ if (this.syncQueue) {
3882
+ await this.syncQueue.stop();
3883
+ this.syncQueue = null;
3884
+ }
3885
+ this.evaluator = null;
3886
+ this.initialized = false;
3887
+ if (this.config.debug) {
3888
+ console.log("[AstraSyncGateway] Shut down");
3889
+ }
3890
+ }
3891
+ /**
3892
+ * Evaluate an action against the verification policy.
3893
+ * Routes to the appropriate mode handler.
3894
+ *
3895
+ * In passive posture, evaluation runs but always returns ALLOW
3896
+ * (the real decision is logged for telemetry).
3897
+ */
3898
+ async evaluate(context, astraId) {
3899
+ if (!this.initialized) {
3900
+ await this.initialize();
3901
+ }
3902
+ let decision;
3903
+ switch (this.config.mode) {
3904
+ case "online":
3905
+ decision = await verifyOnline(this.config, context, astraId);
3906
+ break;
3907
+ case "local":
3908
+ if (!this.evaluator) throw new Error("Local evaluator not initialized");
3909
+ decision = verifyLocal(this.evaluator, context);
3910
+ break;
3911
+ case "hybrid":
3912
+ if (!this.evaluator || !this.syncQueue) throw new Error("Hybrid mode not initialized");
3913
+ decision = verifyHybrid(this.evaluator, this.syncQueue, context);
3914
+ break;
3915
+ default:
3916
+ throw new Error(`Unknown mode: ${this.config.mode}`);
3917
+ }
3918
+ if (this.config.posture === "passive" && decision.recommendation !== "ALLOW") {
3919
+ decision = {
3920
+ ...decision,
3921
+ recommendation: "ALLOW",
3922
+ reason: `[PASSIVE] Would have been ${decision.recommendation}: ${decision.reason}`
3923
+ };
3924
+ }
3925
+ this.traceLogger?.logEvaluation(context, decision);
3926
+ return decision;
3927
+ }
3928
+ /**
3929
+ * Get the current mode.
3930
+ */
3931
+ get mode() {
3932
+ return this.config.mode;
3933
+ }
3934
+ /**
3935
+ * Get the current posture (active or passive).
3936
+ */
3937
+ get posture() {
3938
+ return this.config.posture || "active";
3939
+ }
3940
+ /**
3941
+ * Switch modes at runtime (e.g. after upgrade from free to paid).
3942
+ */
3943
+ async switchMode(newMode, additionalConfig) {
3944
+ const oldMode = this.config.mode;
3945
+ await this.shutdown();
3946
+ this.config = { ...this.config, ...additionalConfig, mode: newMode };
3947
+ this.validateConfig();
3948
+ await this.initialize();
3949
+ this.traceLogger?.logModeSwitch(oldMode, newMode);
3950
+ if (this.config.debug) {
3951
+ console.log(`[AstraSyncGateway] Switched to ${newMode} mode`);
3952
+ }
3953
+ }
3954
+ /**
3955
+ * Get sync queue status (hybrid mode only).
3956
+ */
3957
+ getSyncStatus() {
3958
+ return this.syncQueue?.getStatus() || null;
3959
+ }
3960
+ };
3961
+
3962
+ // src/cursor/extension.ts
3963
+ var adapter = null;
3964
+ var gateway = null;
3965
+ async function activate(vscodeApi) {
3966
+ const config = loadConfiguration();
3967
+ gateway = new AstraSyncGateway(config.gatewayConfig);
3968
+ adapter = new CursorAdapter({
3969
+ vscode: vscodeApi,
3970
+ onApprovalRequired: async (context, decision) => {
3971
+ const choice = await vscodeApi.window.showWarningMessage(
3972
+ `AstraSync: ${decision.reason}
3973
+
3974
+ Action: ${context.action} \u2192 ${context.target}`,
3975
+ "Allow",
3976
+ "Deny"
3977
+ );
3978
+ return choice === "Allow";
3979
+ }
3980
+ });
3981
+ await adapter.initialize({
3982
+ gateway,
3983
+ adapterOptions: { vscode: vscodeApi }
3984
+ });
3985
+ vscodeApi.commands.registerCommand("astrasync.showPolicy", () => {
3986
+ const channel = vscodeApi.window.createOutputChannel("AstraSync Policy");
3987
+ channel.appendLine(`Mode: ${gateway.mode}`);
3988
+ channel.appendLine(`Posture: ${gateway.posture}`);
3989
+ channel.appendLine(`Policy file: ${config.gatewayConfig.policyFile || "(inline/none)"}`);
3990
+ channel.show();
3991
+ });
3992
+ vscodeApi.commands.registerCommand("astrasync.switchMode", async () => {
3993
+ if (!config.gatewayConfig.apiKey) {
3994
+ vscodeApi.window.showInformationMessage(
3995
+ "AstraSync: Set astrasync.apiKey in settings to enable online/hybrid mode."
3996
+ );
3997
+ return;
3998
+ }
3999
+ const choice = await vscodeApi.window.showWarningMessage(
4000
+ "Switch AstraSync mode?",
4001
+ "Local",
4002
+ "Online",
4003
+ "Hybrid"
4004
+ );
4005
+ if (choice) {
4006
+ const mode = choice.toLowerCase();
4007
+ await gateway.switchMode(mode);
4008
+ vscodeApi.window.showInformationMessage(`AstraSync: Switched to ${mode} mode`);
4009
+ }
4010
+ });
4011
+ }
4012
+ async function deactivate() {
4013
+ if (adapter) {
4014
+ await adapter.shutdown();
4015
+ adapter = null;
4016
+ }
4017
+ if (gateway) {
4018
+ await gateway.shutdown();
4019
+ gateway = null;
4020
+ }
4021
+ }
4022
+ function loadConfiguration() {
4023
+ return {
4024
+ gatewayConfig: {
4025
+ mode: "local",
4026
+ policyFile: ".astrasync/policy.yaml",
4027
+ debug: false,
4028
+ traceEnabled: true,
4029
+ posture: "active",
4030
+ // Fallback inline policy if no YAML file exists
4031
+ policy: {
4032
+ version: "1.0",
4033
+ name: "default-cursor-policy",
4034
+ purposes: [
4035
+ { id: "file.read", allowed: true },
4036
+ { id: "file.write", allowed: true },
4037
+ { id: "file.delete", allowed: false },
4038
+ { id: "shell.exec", allowed: true },
4039
+ { id: "network.fetch", allowed: true },
4040
+ { id: "payment.execute", allowed: false },
4041
+ { id: "email.send", allowed: false }
4042
+ ]
4043
+ }
4044
+ }
4045
+ };
4046
+ }
4047
+ // Annotate the CommonJS export names for ESM import in node:
4048
+ 0 && (module.exports = {
4049
+ activate,
4050
+ deactivate
4051
+ });
4052
+ /*! Bundled license information:
4053
+
4054
+ js-yaml/dist/js-yaml.mjs:
4055
+ (*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT *)
4056
+ */
4057
+ //# sourceMappingURL=extension.js.map