proxylang 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3619 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { z } from "zod";
3
+ import ipaddr from "ipaddr.js";
4
+ import { isIP } from "node:net";
5
+ import { randomUUID } from "node:crypto";
6
+ import { join, resolve } from "node:path";
7
+ import { stringify } from "yaml";
8
+ import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
9
+ //#region src/model/identity.ts
10
+ const kinds = /* @__PURE__ */ new WeakMap();
11
+ const origins = /* @__PURE__ */ new WeakMap();
12
+ function kindOf(value) {
13
+ return value !== null && typeof value === "object" ? kinds.get(value) : void 0;
14
+ }
15
+ function originOf(value) {
16
+ return value !== null && typeof value === "object" ? origins.get(value) : void 0;
17
+ }
18
+ function captureOrigin() {
19
+ for (const frame of ((/* @__PURE__ */ new Error()).stack ?? "").split("\n").slice(1)) {
20
+ const match = /(?:at\s+(?:.*?\s+\()?)(file:\/\/\/[^\s)]+|\/[^\s)]+):(\d+):(\d+)\)?$/.exec(frame);
21
+ if (!match) continue;
22
+ let file = match[1];
23
+ if (file.startsWith("file:")) file = fileURLToPath(file);
24
+ if (/\/(?:src\/(?:authoring|model|build)|dist|node_modules)\//.test(file)) continue;
25
+ return Object.freeze({
26
+ file,
27
+ line: Number(match[2]),
28
+ column: Number(match[3])
29
+ });
30
+ }
31
+ }
32
+ function register(value, kind, origin = captureOrigin()) {
33
+ kinds.set(value, kind);
34
+ if (origin) origins.set(value, origin);
35
+ return Object.freeze(value);
36
+ }
37
+ //#endregion
38
+ //#region src/model/definitions.ts
39
+ function validDiagnosticPath(path) {
40
+ return typeof path === "string" && path.length <= 512 && /^[a-zA-Z][a-zA-Z0-9_.[\]-]*$/.test(path);
41
+ }
42
+ function definitionDiagnostic(error) {
43
+ try {
44
+ if (!error || typeof error !== "object") return;
45
+ const own = (key) => Object.getOwnPropertyDescriptor(error, key)?.value;
46
+ const code = own("code");
47
+ if (own("name") !== "ProfileDefinitionError" || typeof code !== "string" || ![
48
+ "INVALID_REQUEST",
49
+ "INVALID_ASSUMPTIONS",
50
+ "INVALID_RESOURCE",
51
+ "INVALID_FIELD",
52
+ "UNKNOWN_FIELD",
53
+ "EMPTY_FRAGMENT",
54
+ "INVALID_PROFILE_DEFINITION",
55
+ "INVALID_BUILD_DEFINITION",
56
+ "PROFILE_EXTENSION_UNSUPPORTED",
57
+ "DNS_HOSTS_CONFLICT",
58
+ "DNS_RULE_CONFLICT"
59
+ ].includes(code)) return;
60
+ const output = { code };
61
+ const paths = own("paths");
62
+ if (Array.isArray(paths) && paths.length <= 16) {
63
+ const values = Array.from({ length: paths.length }, (_, i) => Object.getOwnPropertyDescriptor(paths, String(i))?.value);
64
+ if (values.every(validDiagnosticPath)) output.paths = values;
65
+ }
66
+ const origin = own("origin");
67
+ if (origin && typeof origin === "object") {
68
+ const field = (key) => Object.getOwnPropertyDescriptor(origin, key)?.value;
69
+ const file = field("file"), line = field("line"), column = field("column");
70
+ if (typeof file === "string" && file.length <= 4096 && !/[\p{C}]/u.test(file) && Number.isInteger(line) && Number.isInteger(column) && line > 0 && column > 0) output.origin = {
71
+ file,
72
+ line,
73
+ column
74
+ };
75
+ }
76
+ return output;
77
+ } catch {
78
+ return;
79
+ }
80
+ }
81
+ var ProfileDefinitionError = class extends Error {
82
+ code;
83
+ paths;
84
+ origin;
85
+ constructor(code, paths) {
86
+ const normalized = code === "DEFINITION_UNKNOWN_FIELD" ? "UNKNOWN_FIELD" : code.startsWith("DEFINITION_") ? "INVALID_PROFILE_DEFINITION" : code.startsWith("INVALID_") && ![
87
+ "INVALID_BUILD_DEFINITION",
88
+ "INVALID_PROFILE_DEFINITION",
89
+ "INVALID_RESOURCE",
90
+ "INVALID_REQUEST",
91
+ "INVALID_ASSUMPTIONS"
92
+ ].includes(code) ? "INVALID_FIELD" : code;
93
+ super(normalized);
94
+ this.code = code;
95
+ this.code = normalized;
96
+ this.origin = captureOrigin();
97
+ this.name = "ProfileDefinitionError";
98
+ if (paths?.length && paths.every((p) => typeof p === "string")) this.paths = Object.freeze([...paths]);
99
+ }
100
+ };
101
+ const fail$3 = (code) => {
102
+ throw new ProfileDefinitionError(code);
103
+ };
104
+ /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
105
+ function inspectDefinition(root) {
106
+ let edges = 0;
107
+ let objects = 0;
108
+ const visiting = /* @__PURE__ */ new Set();
109
+ const heights = /* @__PURE__ */ new Map();
110
+ function visit(value, depth) {
111
+ if (depth > 64) fail$3("DEFINITION_DEPTH_EXCEEDED");
112
+ if (value === null || typeof value !== "object") {
113
+ if (![
114
+ "undefined",
115
+ "string",
116
+ "number",
117
+ "boolean"
118
+ ].includes(typeof value) && value !== null) fail$3("DEFINITION_NOT_DATA");
119
+ return 0;
120
+ }
121
+ if (visiting.has(value)) fail$3("DEFINITION_CYCLE");
122
+ const cached = heights.get(value);
123
+ if (cached !== void 0) {
124
+ if (depth + cached > 64) fail$3("DEFINITION_DEPTH_EXCEEDED");
125
+ return cached;
126
+ }
127
+ if (++objects > 2e4) fail$3("DEFINITION_OBJECT_BUDGET_EXCEEDED");
128
+ const proto = Object.getPrototypeOf(value);
129
+ if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$3("DEFINITION_NOT_DATA");
130
+ if (Array.isArray(value) && value.length > 1e5) fail$3("DEFINITION_EDGE_BUDGET_EXCEEDED");
131
+ visiting.add(value);
132
+ let height = 0;
133
+ for (const key of Reflect.ownKeys(value)) {
134
+ if (++edges > 1e5) fail$3("DEFINITION_EDGE_BUDGET_EXCEEDED");
135
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
136
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$3("DEFINITION_NOT_DATA");
137
+ height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
138
+ }
139
+ visiting.delete(value);
140
+ heights.set(value, height);
141
+ return height;
142
+ }
143
+ visit(root, 0);
144
+ }
145
+ /** Count output occurrences, not identities, before allocating each copied value. */
146
+ function snapshot(input) {
147
+ let remaining = 1e5;
148
+ function copy(value, depth) {
149
+ if (--remaining < 0) fail$3("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
150
+ if (depth > 64) fail$3("DEFINITION_DEPTH_EXCEEDED");
151
+ if (value === null || typeof value !== "object") return value;
152
+ if (kindOf(value)) return value;
153
+ if (Array.isArray(value)) {
154
+ const output = [];
155
+ for (const item of value) output.push(copy(item, depth + 1));
156
+ return output;
157
+ }
158
+ const output = {};
159
+ for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
160
+ value: copy(item, depth + 1),
161
+ enumerable: true,
162
+ writable: true,
163
+ configurable: true
164
+ });
165
+ return output;
166
+ }
167
+ return copy(input, 0);
168
+ }
169
+ function snapshotDefinition(input) {
170
+ inspectDefinition(input);
171
+ return snapshot(input);
172
+ }
173
+ function exactDefinition(value, keys) {
174
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail$3("DEFINITION_NOT_DATA");
175
+ const unknown = Object.keys(value).filter((key) => !keys.includes(key));
176
+ if (unknown.length) throw new ProfileDefinitionError("UNKNOWN_FIELD", unknown);
177
+ }
178
+ //#endregion
179
+ //#region src/model/tun.ts
180
+ function validTunAddresses(addresses) {
181
+ const families = /* @__PURE__ */ new Set();
182
+ try {
183
+ for (const value of addresses) {
184
+ const [address, prefix] = ipaddr.parseCIDR(value);
185
+ const family = address.kind();
186
+ const bits = family === "ipv4" ? 32 : 128;
187
+ if (families.has(family) || prefix > bits - 2) return false;
188
+ families.add(family);
189
+ const numeric = address.toByteArray().reduce((total, byte) => total << 8n | BigInt(byte), 0n);
190
+ const mask = (1n << BigInt(bits - prefix)) - 1n;
191
+ if ((numeric & mask) === mask) return false;
192
+ }
193
+ return true;
194
+ } catch {
195
+ return false;
196
+ }
197
+ }
198
+ function unsafeTunResolvers(model) {
199
+ if (!model.tun) return [];
200
+ const networks = model.tun.address.map((value) => ipaddr.parseCIDR(value));
201
+ return [
202
+ ...model.listener ? [model.listener.resolver] : [],
203
+ ...(model.dns ?? []).map((rule) => isIP(rule.server) ? rule.server : new URL(rule.server).hostname.replace(/^\[|\]$/g, "")),
204
+ ...(model.endpoints ?? []).map((endpoint) => endpoint.bootstrapResolver)
205
+ ].filter((value) => {
206
+ if (!isIP(value)) return false;
207
+ const address = ipaddr.process(value);
208
+ return ["loopback", "unspecified"].includes(address.range()) || networks.some(([network, prefix]) => address.kind() === network.kind() && address.match(network, prefix));
209
+ });
210
+ }
211
+ //#endregion
212
+ //#region src/model/schema.ts
213
+ const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
214
+ const domain$3 = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
215
+ const ip$2 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
216
+ const cidr$1 = z.string().refine((x) => {
217
+ try {
218
+ const [address, prefix] = x.split("/");
219
+ if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
220
+ ipaddr.parseCIDR(x);
221
+ return true;
222
+ } catch {
223
+ return false;
224
+ }
225
+ });
226
+ const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
227
+ const port$2 = z.number().int().min(1).max(65535);
228
+ const network = z.enum(["tcp", "udp"]);
229
+ const atom$1 = (type, value) => z.strictObject({
230
+ type: z.literal(type),
231
+ value
232
+ });
233
+ const remoteBase = {
234
+ type: z.literal("nativeRuleSet"),
235
+ id: idSchema,
236
+ url: z.string().max(2048).refine((value) => {
237
+ try {
238
+ const url = new URL(value);
239
+ return /^https?:\/\//.test(value) && ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.hash && !/[\s\p{C},()\\"']/u.test(value);
240
+ } catch {
241
+ return false;
242
+ }
243
+ })
244
+ };
245
+ const updateInterval = z.number().int().min(60).max(2147483647);
246
+ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
247
+ z.strictObject({
248
+ ...remoteBase,
249
+ engine: z.literal("surge"),
250
+ format: z.enum(["rule-set", "domain-set"]),
251
+ intervalSeconds: updateInterval.optional(),
252
+ noResolve: z.boolean().optional(),
253
+ includeSniffed: z.boolean().optional()
254
+ }),
255
+ z.strictObject({
256
+ ...remoteBase,
257
+ engine: z.literal("sing-box"),
258
+ format: z.enum(["source", "binary"]),
259
+ intervalSeconds: updateInterval,
260
+ resolve: z.boolean().optional()
261
+ }),
262
+ z.strictObject({
263
+ ...remoteBase,
264
+ engine: z.literal("mihomo"),
265
+ format: z.enum(["yaml", "text"]),
266
+ behavior: z.enum([
267
+ "domain",
268
+ "ipcidr",
269
+ "classical"
270
+ ]),
271
+ intervalSeconds: updateInterval
272
+ })
273
+ ]);
274
+ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
275
+ nativeRuleSetSchema,
276
+ z.strictObject({
277
+ type: z.literal("domain"),
278
+ value: domain$3,
279
+ includeSniffed: z.boolean().optional()
280
+ }),
281
+ z.strictObject({
282
+ type: z.literal("domainSuffix"),
283
+ value: domain$3,
284
+ includeSniffed: z.boolean().optional()
285
+ }),
286
+ z.strictObject({
287
+ type: z.literal("ipCidr"),
288
+ value: cidr$1,
289
+ noResolve: z.boolean().optional()
290
+ }),
291
+ atom$1("sourceIp", z.union([ip$2, cidr$1])),
292
+ atom$1("processName", processNameSchema),
293
+ z.strictObject({
294
+ type: z.literal("port"),
295
+ from: port$2,
296
+ to: port$2
297
+ }).refine((v) => v.from <= v.to),
298
+ z.strictObject({
299
+ type: z.literal("sourcePort"),
300
+ from: port$2,
301
+ to: port$2
302
+ }).refine((v) => v.from <= v.to),
303
+ z.strictObject({
304
+ type: z.literal("network"),
305
+ value: network
306
+ }),
307
+ z.strictObject({
308
+ type: z.enum(["all", "any"]),
309
+ conditions: z.array(matchSchema).min(1)
310
+ }),
311
+ z.strictObject({
312
+ type: z.literal("not"),
313
+ condition: matchSchema
314
+ })
315
+ ]));
316
+ const unique = (values) => new Set(values).size === values.length;
317
+ const secretSchema = z.custom((v) => kindOf(v) === "secret");
318
+ const nodeBase = {
319
+ id: idSchema,
320
+ server: z.union([ip$2, domain$3]),
321
+ port: port$2,
322
+ via: idSchema.optional(),
323
+ tcpFastOpen: z.boolean().optional()
324
+ };
325
+ const tlsSchema = z.strictObject({
326
+ serverName: domain$3,
327
+ skipCertVerify: z.boolean().optional(),
328
+ alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
329
+ });
330
+ const transportSchema = z.strictObject({
331
+ type: z.literal("ws"),
332
+ path: z.string().max(2048).regex(/^\/[A-Za-z0-9/._~-]*$/).refine((x) => !x.startsWith("//")),
333
+ host: domain$3.optional()
334
+ });
335
+ const uuidNode = {
336
+ ...nodeBase,
337
+ uuid: secretSchema,
338
+ tls: tlsSchema.optional(),
339
+ transport: transportSchema.optional()
340
+ };
341
+ const surgeOptions = { blockQuic: z.enum([
342
+ "auto",
343
+ "on",
344
+ "off"
345
+ ]).optional() };
346
+ const portHoppingSchema = z.string().max(2048).regex(/^[0-9]+(?:-[0-9]+)?(?:;[0-9]+(?:-[0-9]+)?)*$/).refine((value) => value.split(";").every((part) => {
347
+ const [start, end = start] = part.split("-").map(Number);
348
+ return start !== void 0 && end !== void 0 && start >= 1 && end <= 65535 && start <= end;
349
+ }));
350
+ const nodeSchema = z.discriminatedUnion("type", [
351
+ z.strictObject({
352
+ ...nodeBase,
353
+ type: z.literal("trojan"),
354
+ password: secretSchema,
355
+ serverName: domain$3.optional(),
356
+ skipCertVerify: z.boolean().optional(),
357
+ surge: z.strictObject({
358
+ ...surgeOptions,
359
+ udpRelay: z.literal(true).optional()
360
+ }).optional()
361
+ }),
362
+ z.strictObject({
363
+ ...nodeBase,
364
+ type: z.literal("anytls"),
365
+ password: secretSchema,
366
+ serverName: domain$3.optional(),
367
+ skipCertVerify: z.boolean().optional(),
368
+ surge: z.strictObject({
369
+ ...surgeOptions,
370
+ udpRelay: z.literal(true).optional()
371
+ }).optional()
372
+ }),
373
+ z.strictObject({
374
+ ...nodeBase,
375
+ type: z.literal("hysteria2"),
376
+ tcpFastOpen: z.never().optional(),
377
+ password: secretSchema,
378
+ serverName: domain$3.optional(),
379
+ skipCertVerify: z.boolean().optional(),
380
+ portHopping: portHoppingSchema.optional(),
381
+ portHoppingInterval: z.number().int().positive().optional()
382
+ }).refine((node) => node.portHoppingInterval === void 0 || node.portHopping !== void 0),
383
+ z.strictObject({
384
+ ...nodeBase,
385
+ type: z.literal("http"),
386
+ serverName: z.undefined().optional(),
387
+ password: secretSchema,
388
+ username: secretSchema.optional()
389
+ }),
390
+ z.strictObject({
391
+ ...nodeBase,
392
+ type: z.literal("shadowsocks"),
393
+ surge: z.strictObject({
394
+ ...surgeOptions,
395
+ udpRelay: z.boolean().optional()
396
+ }).optional(),
397
+ method: z.enum([
398
+ "aes-128-gcm",
399
+ "aes-256-gcm",
400
+ "chacha20-ietf-poly1305"
401
+ ]),
402
+ password: secretSchema
403
+ }),
404
+ z.strictObject({
405
+ ...uuidNode,
406
+ type: z.literal("vmess"),
407
+ surge: z.strictObject(surgeOptions).optional()
408
+ }),
409
+ z.strictObject({
410
+ ...uuidNode,
411
+ type: z.literal("vless"),
412
+ flow: z.literal("xtls-rprx-vision").optional(),
413
+ packetEncoding: z.enum(["xudp", "packetaddr"]).optional(),
414
+ utlsFingerprint: z.literal("chrome").optional(),
415
+ reality: z.strictObject({
416
+ publicKey: z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine((value) => Buffer.from(value, "base64url").toString("base64url") === value),
417
+ shortId: z.string().regex(/^(?:[0-9a-fA-F]{2}){0,8}$/)
418
+ }).optional()
419
+ }).refine((node) => !node.reality || !!node.tls && node.utlsFingerprint === "chrome").refine((node) => !node.flow || !!node.tls && !node.transport).refine((node) => !node.utlsFingerprint || !!node.tls)
420
+ ]).refine((node) => !("transport" in node && node.transport && node.tls?.alpn) || node.tls.alpn.length === 1 && node.tls.alpn[0] === "http/1.1");
421
+ const endpointSchema = z.strictObject({
422
+ type: z.literal("sing-box-tailscale"),
423
+ id: idSchema,
424
+ hostname: domain$3.refine((x) => !x.includes(".")),
425
+ stateDirectory: z.string().max(4096).refine((x) => x.startsWith("/") && !/[\p{C}$\\]/u.test(x) && x.split("/").slice(1).every((part) => part !== "" && part !== "." && part !== "..")),
426
+ acceptRoutes: z.boolean(),
427
+ bootstrapResolver: ip$2,
428
+ authKey: secretSchema.optional(),
429
+ exitNode: ip$2.optional(),
430
+ exitNodeAllowLanAccess: z.boolean().optional()
431
+ }).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
432
+ function assertData(value) {
433
+ const ancestors = /* @__PURE__ */ new Set();
434
+ let count = 0;
435
+ const visit = (v, depth) => {
436
+ if (++count > 1e5 || depth > 64) throw new Error("INPUT_LIMIT");
437
+ if (v === void 0 || v === null || [
438
+ "string",
439
+ "number",
440
+ "boolean"
441
+ ].includes(typeof v)) return;
442
+ if (typeof v !== "object" || ancestors.has(v)) throw new Error("INPUT_GRAPH");
443
+ if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) throw new Error("INPUT_OBJECT");
444
+ ancestors.add(v);
445
+ for (const key of Reflect.ownKeys(v)) {
446
+ const descriptor = Object.getOwnPropertyDescriptor(v, key);
447
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(v) && key === "length")) throw new Error("INPUT_OBJECT");
448
+ visit(descriptor.value, depth + 1);
449
+ }
450
+ ancestors.delete(v);
451
+ };
452
+ visit(value, 0);
453
+ }
454
+ function deepFreeze(value) {
455
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
456
+ Object.freeze(value);
457
+ for (const item of Object.values(value)) deepFreeze(item);
458
+ }
459
+ return value;
460
+ }
461
+ const engineOptionsSchema = z.strictObject({
462
+ mode: z.enum(["standalone", "fragment"]).optional(),
463
+ listener: z.strictObject({
464
+ port: port$2,
465
+ resolver: ip$2
466
+ }).optional(),
467
+ domainMatching: z.literal("prefer-sniffed").optional(),
468
+ serverAliases: z.record(domain$3, z.union([domain$3, ip$2])).optional(),
469
+ cacheFile: z.boolean().optional(),
470
+ unsupportedUdp: z.literal("reject").optional(),
471
+ tun: z.strictObject({
472
+ address: z.array(cidr$1).min(1).max(2).refine(validTunAddresses),
473
+ stack: z.enum([
474
+ "system",
475
+ "gvisor",
476
+ "mixed"
477
+ ]),
478
+ autoRoute: z.boolean(),
479
+ strictRoute: z.boolean(),
480
+ dnsMode: z.enum([
481
+ "disabled",
482
+ "native",
483
+ "hijack"
484
+ ]),
485
+ routeExcludeAddress: z.array(cidr$1).optional()
486
+ }).refine((t) => !t.strictRoute || t.autoRoute).optional()
487
+ });
488
+ //#endregion
489
+ //#region src/authoring/data.ts
490
+ function frozen(value) {
491
+ return deepFreeze(snapshotDefinition(value));
492
+ }
493
+ function created(value, kind) {
494
+ return register(frozen(value), kind);
495
+ }
496
+ function requireKind(value, kinds) {
497
+ if (!kinds.includes(kindOf(value))) throw new ProfileDefinitionError("INVALID_RESOURCE");
498
+ }
499
+ function flatten(input) {
500
+ inspectDefinition(input);
501
+ let budget = 1e5;
502
+ const output = [];
503
+ const visit = (v) => {
504
+ if (--budget < 0) throw new ProfileDefinitionError("INVALID_PROFILE_DEFINITION");
505
+ if (Array.isArray(v)) for (const x of v) visit(x);
506
+ else output.push(v);
507
+ };
508
+ visit(input);
509
+ return output;
510
+ }
511
+ function parsed(schema, value) {
512
+ inspectDefinition(value);
513
+ const result = schema.safeParse(value);
514
+ if (!result.success) throw new ProfileDefinitionError(result.error.issues.filter((i) => i.code === "unrecognized_keys").length ? "UNKNOWN_FIELD" : "INVALID_FIELD", result.error.issues.flatMap((i) => i.code === "unrecognized_keys" ? i.keys.map((k) => [...i.path, k].join(".")) : [i.path.join(".")]));
515
+ return result.data;
516
+ }
517
+ function inspectRecord(value) {
518
+ inspectDefinition(value);
519
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new ProfileDefinitionError("INVALID_FIELD");
520
+ }
521
+ //#endregion
522
+ //#region src/model/names.ts
523
+ const nativeNameSchema = z.string().min(1).max(256).refine((value) => value.trim() === value && !/[\p{C}\p{Zl}\p{Zp},=[\]()#;]/u.test(value) && !["DIRECT", "REJECT"].includes(value.toUpperCase()) && !value.toLowerCase().startsWith("pl-"));
524
+ function isReservedNativeName(name, engine) {
525
+ return (engine === "surge" ? [
526
+ "REJECT-DROP",
527
+ "REJECT-NO-DROP",
528
+ "REJECT-TINYGIF"
529
+ ] : engine === "mihomo" ? [
530
+ "GLOBAL",
531
+ "PASS",
532
+ "COMPATIBLE",
533
+ "REJECT-DROP",
534
+ "PASS-RULE"
535
+ ] : engine === "stash" ? [
536
+ "GLOBAL",
537
+ "PASS",
538
+ "COMPATIBLE",
539
+ "REJECT-DROP"
540
+ ] : []).includes(name.toUpperCase());
541
+ }
542
+ //#endregion
543
+ //#region src/model/surge-schema.ts
544
+ const builtin = z.enum([
545
+ "DIRECT",
546
+ "REJECT",
547
+ "REJECT-DROP",
548
+ "REJECT-NO-DROP",
549
+ "REJECT-TINYGIF"
550
+ ]);
551
+ const policy$2 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
552
+ const token = secretSchema;
553
+ const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
554
+ const domain$2 = z.string().max(253).regex(/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/);
555
+ const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
556
+ const ip$1 = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
557
+ const cidr = (version) => safe.refine((v) => {
558
+ try {
559
+ const [address] = ipaddr.parseCIDR(v);
560
+ return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
561
+ } catch {
562
+ return false;
563
+ }
564
+ });
565
+ const port$1 = z.number().int().min(1).max(65535);
566
+ function addressPort(value, allowHost, portRequired) {
567
+ if (!portRequired && isIP(value)) return true;
568
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
569
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
570
+ const host = match[1];
571
+ return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain$2.safeParse(host).success;
572
+ }
573
+ const listener = safe.refine((v) => addressPort(v, false, false));
574
+ const endpoint = safe.refine((v) => addressPort(v, true, true));
575
+ const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
576
+ const url = z.string().min(1).max(4096).refine((v) => {
577
+ try {
578
+ const u = new URL(v);
579
+ return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
580
+ } catch {
581
+ return false;
582
+ }
583
+ });
584
+ const encryptedDns = z.string().max(4096).refine((v) => {
585
+ try {
586
+ const u = new URL(v);
587
+ return [
588
+ "https:",
589
+ "h3:",
590
+ "quic:",
591
+ "tls:",
592
+ "tcp:"
593
+ ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
594
+ } catch {
595
+ return false;
596
+ }
597
+ });
598
+ const list = (item) => z.array(item).min(1).max(1e3);
599
+ const control = z.strictObject({
600
+ password: token,
601
+ listen: safe.refine((v) => addressPort(v, false, true))
602
+ });
603
+ const generalSchema = z.strictObject({
604
+ "udp-policy-not-supported-behaviour": z.enum(["DIRECT", "REJECT"]).optional(),
605
+ loglevel: z.enum([
606
+ "verbose",
607
+ "info",
608
+ "notify",
609
+ "warning"
610
+ ]).optional(),
611
+ "dns-server": list(dns).optional(),
612
+ "encrypted-dns-server": list(encryptedDns).optional(),
613
+ "show-error-page-for-reject": z.boolean().optional(),
614
+ "exclude-simple-hostnames": z.boolean().optional(),
615
+ "internet-test-url": url.optional(),
616
+ "skip-proxy": list(z.union([
617
+ hostPattern,
618
+ ip$1,
619
+ cidr()
620
+ ])).optional(),
621
+ ipv6: z.boolean().optional(),
622
+ "ipv6-vif": z.enum([
623
+ "auto",
624
+ "always",
625
+ "disabled"
626
+ ]).optional(),
627
+ "bypass-system": z.boolean().optional(),
628
+ replica: z.boolean().optional(),
629
+ "tls-provider": z.enum(["default", "openssl"]).optional(),
630
+ "bypass-tun": list(cidr()).optional(),
631
+ "always-real-ip": list(hostPattern).optional(),
632
+ "http-api": control.optional(),
633
+ "http-api-web-dashboard": z.boolean().optional(),
634
+ "external-controller-access": control.optional(),
635
+ "hijack-dns": list(safe.refine((v) => /^\*(?::\d+)?$/.test(v) ? !v.includes(":") || Number(v.slice(2)) > 0 && Number(v.slice(2)) <= 65535 : addressPort(v, false, false))).optional(),
636
+ "http-listen": listener.optional(),
637
+ "socks5-listen": listener.optional(),
638
+ "proxy-restricted-to-lan": z.boolean().optional()
639
+ });
640
+ /** Internal fragment validation; caller must inspect data descriptors before invoking. */
641
+ const validateSurgeGeneral = (input) => generalSchema.safeParse(input).success;
642
+ const hostSchema = z.strictObject({
643
+ pattern: hostPattern,
644
+ address: z.union([ip$1, domain$2]).optional(),
645
+ server: z.union([dns, encryptedDns]).optional()
646
+ }).refine((v) => v.address !== void 0 || v.server !== void 0);
647
+ const key = z.string().regex(/^[A-Za-z0-9+/]{43}=$/).refine((v) => Buffer.from(v, "base64").length === 32 && Buffer.from(v, "base64").toString("base64") === v);
648
+ const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
649
+ const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
650
+ type: z.literal("tailscale"),
651
+ id: idSchema,
652
+ sectionName,
653
+ authKey: token,
654
+ hostname: domain$2,
655
+ dnsServer: list(dns).optional(),
656
+ autoAddMagicDnsRule: z.boolean().optional(),
657
+ idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
658
+ }), z.strictObject({
659
+ type: z.literal("wireguard"),
660
+ id: idSchema,
661
+ sectionName,
662
+ privateKey: token,
663
+ selfIp: ip$1.refine((v) => isIP(v) === 4),
664
+ dnsServer: list(dns).optional(),
665
+ mtu: z.number().int().min(576).max(9e3).optional(),
666
+ peers: list(z.strictObject({
667
+ publicKey: key,
668
+ endpoint,
669
+ allowedIps: list(cidr()),
670
+ presharedKey: token.optional(),
671
+ persistentKeepalive: z.number().int().min(0).max(65535).optional()
672
+ }))
673
+ })]);
674
+ const groupSchema = z.strictObject({
675
+ id: idSchema,
676
+ type: z.enum(["select", "smart"]),
677
+ members: list(policy$2),
678
+ url: url.optional(),
679
+ intervalSeconds: z.number().int().positive().max(2147483647).optional(),
680
+ timeoutSeconds: z.number().int().positive().max(3600).optional()
681
+ });
682
+ const groupTestSchema = groupSchema.pick({
683
+ url: true,
684
+ intervalSeconds: true,
685
+ timeoutSeconds: true
686
+ }).required({ url: true });
687
+ const options = { noResolve: z.boolean().optional() };
688
+ const domainOptions = {
689
+ ...options,
690
+ includeSniffed: z.boolean().optional()
691
+ };
692
+ const atom = (type, value) => z.strictObject({
693
+ type: z.literal(type),
694
+ value,
695
+ ...["domain", "domainSuffix"].includes(type) ? domainOptions : options
696
+ });
697
+ const conditionSchema = z.lazy(() => z.union([
698
+ atom("domain", domain$2),
699
+ atom("domainSuffix", domain$2),
700
+ atom("ipCidr", cidr(4)),
701
+ atom("ipCidr6", cidr(6)),
702
+ z.strictObject({
703
+ type: z.literal("ipAsn"),
704
+ value: z.number().int().min(1).max(4294967295),
705
+ ...options
706
+ }),
707
+ atom("sourceIp", z.union([ip$1, cidr()])),
708
+ atom("processName", safe),
709
+ atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
710
+ z.strictObject({
711
+ type: z.enum(["port", "sourcePort"]),
712
+ from: port$1,
713
+ to: port$1.optional(),
714
+ ...options
715
+ }).refine((v) => v.to === void 0 || v.to >= v.from),
716
+ z.strictObject({
717
+ type: z.literal("network"),
718
+ value: z.enum(["tcp", "udp"]),
719
+ ...options
720
+ }),
721
+ z.strictObject({
722
+ type: z.enum(["all", "any"]),
723
+ conditions: z.array(conditionSchema).min(1).max(100),
724
+ ...options
725
+ }),
726
+ z.strictObject({
727
+ type: z.literal("not"),
728
+ condition: conditionSchema,
729
+ ...options
730
+ }),
731
+ z.strictObject({
732
+ type: z.literal("ruleSet"),
733
+ format: z.enum(["rule-set", "domain-set"]),
734
+ url: url.optional(),
735
+ builtin: z.enum(["LAN", "SYSTEM"]).optional(),
736
+ intervalSeconds: z.number().int().min(60).max(2147483647).optional(),
737
+ ...domainOptions
738
+ }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
739
+ ]));
740
+ const managedSchema = z.strictObject({
741
+ url: url.refine((v) => !new URL(v).search && !v.includes("?")),
742
+ query: z.record(z.string().min(1).max(128).regex(/^[A-Za-z][A-Za-z0-9_-]*$/), z.union([z.string().max(4096), token])).optional(),
743
+ intervalSeconds: z.number().int().min(60).max(2147483647),
744
+ strict: z.boolean()
745
+ });
746
+ const inputSchema = z.strictObject({
747
+ target: z.strictObject({
748
+ engine: z.literal("surge"),
749
+ platform: z.enum(["macos", "ios"]),
750
+ version: z.string()
751
+ }),
752
+ managed: managedSchema.optional(),
753
+ general: generalSchema.optional(),
754
+ hosts: z.array(hostSchema).max(2e3).optional(),
755
+ nodes: z.array(nodeSchema).max(1e3),
756
+ tunnels: z.array(tunnelSchema).max(1e3).optional(),
757
+ groups: z.array(groupSchema).max(1e3),
758
+ rules: z.array(z.strictObject({
759
+ when: conditionSchema,
760
+ then: policy$2
761
+ })).max(1e4),
762
+ fallback: policy$2,
763
+ names: z.record(idSchema, nativeNameSchema).optional()
764
+ });
765
+ //#endregion
766
+ //#region src/model/dns.ts
767
+ const domain$1 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
768
+ function dohUrl(value) {
769
+ const url = new URL(value);
770
+ if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
771
+ return url;
772
+ }
773
+ const server = z.string().max(2048).refine((value) => {
774
+ if (isIP(value) && !value.includes("%")) return true;
775
+ if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
776
+ try {
777
+ const url = new URL(value);
778
+ const authority = value.slice(8).split("/")[0];
779
+ const path = value.slice(8 + authority.length);
780
+ return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
781
+ } catch {
782
+ return false;
783
+ }
784
+ });
785
+ const dnsRulesSchema = z.array(z.strictObject({
786
+ pattern: z.string().min(1).max(253).refine((value) => domain$1.test(value.startsWith("*.") ? value.slice(2) : value)),
787
+ server
788
+ })).max(2e3).superRefine((rules, ctx) => {
789
+ if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
790
+ for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
791
+ const a = rules[i], b = rules[j];
792
+ const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
793
+ if (x === y || overlap(x, y) && a.server !== b.server) {
794
+ ctx.addIssue({
795
+ code: "custom",
796
+ message: "DNS_RULE_CONFLICT"
797
+ });
798
+ return;
799
+ }
800
+ }
801
+ });
802
+ function overlap(a, b) {
803
+ const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
804
+ if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
805
+ return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
806
+ }
807
+ function dnsCondition(rule) {
808
+ const pattern = rule.pattern.toLowerCase();
809
+ return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
810
+ }
811
+ //#endregion
812
+ //#region src/authoring/profile.ts
813
+ const fail$2 = (code) => {
814
+ throw new ProfileDefinitionError(code);
815
+ };
816
+ function defineProfile(input) {
817
+ if (kindOf(input) === "profile") return input;
818
+ inspectDefinition(input);
819
+ exactDefinition(input, [
820
+ "target",
821
+ "proxies",
822
+ "groups",
823
+ "routes",
824
+ "fallback",
825
+ "surge",
826
+ "singBox",
827
+ "mihomo",
828
+ "dns",
829
+ "cases"
830
+ ]);
831
+ exactDefinition(input.target, [
832
+ "engine",
833
+ "platform",
834
+ "version"
835
+ ]);
836
+ if (input.surge !== void 0) exactDefinition(input.surge, [
837
+ "managed",
838
+ "general",
839
+ "hosts"
840
+ ]);
841
+ if (input.singBox !== void 0) {
842
+ exactDefinition(input.singBox, [
843
+ "mode",
844
+ "listener",
845
+ "tun",
846
+ "domainMatching",
847
+ "serverAliases",
848
+ "cacheFile",
849
+ "unsupportedUdp"
850
+ ]);
851
+ if (input.singBox.mode !== void 0 && !["fragment", "standalone"].includes(input.singBox.mode)) fail$2("INVALID_PROFILE_DEFINITION");
852
+ if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
853
+ }
854
+ if (input.mihomo !== void 0) {
855
+ exactDefinition(input.mihomo, ["mode", "listener"]);
856
+ if (input.mihomo.listener) exactDefinition(input.mihomo.listener, ["port", "resolver"]);
857
+ }
858
+ if (input.surge !== void 0 && input.target.engine !== "surge" || input.singBox !== void 0 && input.target.engine !== "sing-box" || input.mihomo !== void 0 && input.target.engine !== "mihomo") fail$2("PROFILE_EXTENSION_UNSUPPORTED");
859
+ if (![
860
+ input.target.engine,
861
+ input.target.platform,
862
+ input.target.version
863
+ ].every((v) => typeof v === "string")) fail$2("INVALID_FIELD");
864
+ if (input.singBox !== void 0) parsed(engineOptionsSchema, input.singBox);
865
+ if (input.mihomo !== void 0) parsed(engineOptionsSchema, input.mihomo);
866
+ let remaining = 1e5;
867
+ function flatten(fragments) {
868
+ const result = [];
869
+ function visit(value) {
870
+ if (--remaining < 0) fail$2("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
871
+ if (Array.isArray(value)) for (const item of value) visit(item);
872
+ else {
873
+ if (!value || typeof value !== "object") fail$2("INVALID_PROFILE_DEFINITION");
874
+ result.push(value);
875
+ }
876
+ }
877
+ visit(fragments);
878
+ return result;
879
+ }
880
+ const proxies = [...new Set(flatten(input.proxies))];
881
+ for (const proxy of proxies) requireKind(proxy, [
882
+ "node",
883
+ "tunnel",
884
+ "endpoint"
885
+ ]);
886
+ const groups = [...new Set(flatten(input.groups))];
887
+ for (const group of groups) requireKind(group, ["group"]);
888
+ const routes = flatten(input.routes);
889
+ for (const route of routes) {
890
+ requireKind(route, ["route"]);
891
+ requireKind(route.to, [
892
+ "node",
893
+ "group",
894
+ "tunnel",
895
+ "endpoint",
896
+ "builtin"
897
+ ]);
898
+ }
899
+ requireKind(input.fallback, [
900
+ "node",
901
+ "group",
902
+ "tunnel",
903
+ "endpoint",
904
+ "builtin"
905
+ ]);
906
+ const cases = input.cases === void 0 ? [] : flatten(input.cases);
907
+ if (cases) for (const item of cases) {
908
+ exactDefinition(item, [
909
+ "name",
910
+ "request",
911
+ "assume",
912
+ "expect"
913
+ ]);
914
+ if (typeof item.name !== "string" || !item.name) fail$2("INVALID_FIELD");
915
+ requireKind(item.expect, [
916
+ "node",
917
+ "group",
918
+ "tunnel",
919
+ "endpoint",
920
+ "builtin"
921
+ ]);
922
+ }
923
+ const dns = input.dns === void 0 ? [] : flatten(input.dns);
924
+ if (dns) {
925
+ const checked = dnsRulesSchema.safeParse(dns);
926
+ if (!checked.success) fail$2(checked.error.issues.some((issue) => issue.message === "DNS_RULE_CONFLICT") ? "DNS_RULE_CONFLICT" : "INVALID_DNS_RULES");
927
+ }
928
+ let surge;
929
+ if (input.surge !== void 0) {
930
+ let general;
931
+ if (input.surge.general !== void 0) {
932
+ general = {};
933
+ const checked = /* @__PURE__ */ new Set();
934
+ const costs = /* @__PURE__ */ new Map();
935
+ let validationRemaining = 1e5;
936
+ function cost(value) {
937
+ if (!value || typeof value !== "object") return 1;
938
+ const cached = costs.get(value);
939
+ if (cached !== void 0) return cached;
940
+ let total = 1;
941
+ for (const item of Object.values(value)) {
942
+ total += cost(item);
943
+ if (total > 1e5) fail$2("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
944
+ }
945
+ costs.set(value, total);
946
+ return total;
947
+ }
948
+ const fragments = Array.isArray(input.surge.general) ? input.surge.general : [input.surge.general];
949
+ for (const fragment of flatten(fragments)) {
950
+ if (!checked.has(fragment)) {
951
+ validationRemaining -= cost(fragment);
952
+ if (validationRemaining < 0) fail$2("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
953
+ if (!validateSurgeGeneral(fragment)) fail$2("INVALID_SURGE_GENERAL");
954
+ checked.add(fragment);
955
+ }
956
+ Object.assign(general, fragment);
957
+ }
958
+ }
959
+ surge = {
960
+ ...input.surge,
961
+ ...general === void 0 ? {} : { general },
962
+ ...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
963
+ };
964
+ }
965
+ if (surge?.hosts) for (const host of surge.hosts) parsed(hostSchema, host);
966
+ if (surge?.managed) parsed(managedSchema, surge.managed);
967
+ if (dns?.length && surge?.hosts?.length) {
968
+ if (dns.length + surge.hosts.length > 2e3) fail$2("INVALID_SURGE_HOSTS");
969
+ const patterns = new Map(dns.map((entry, index) => [entry.pattern.toLowerCase(), index]));
970
+ for (const [index, host] of surge.hosts.entries()) {
971
+ if (typeof host?.pattern !== "string") fail$2("INVALID_SURGE_HOSTS");
972
+ const dnsIndex = patterns.get(host.pattern.toLowerCase());
973
+ if (dnsIndex !== void 0) throw new ProfileDefinitionError("DNS_HOSTS_CONFLICT", [`dns[${dnsIndex}]`, `surge.hosts[${index}]`]);
974
+ }
975
+ }
976
+ const { dns: _dns, surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
977
+ return created({
978
+ ...rest,
979
+ dns,
980
+ cases: cases.map((item) => kindOf(item) === "case" ? item : created(item, "case")),
981
+ proxies,
982
+ groups,
983
+ routes,
984
+ ...surge === void 0 ? {} : { surge }
985
+ }, "profile");
986
+ }
987
+ //#endregion
988
+ //#region src/model/secret-store.ts
989
+ const secretSources = /* @__PURE__ */ new WeakMap();
990
+ function sourceFor(secrets, ref) {
991
+ return secrets ? secretSources.get(secrets)?.get(ref) : void 0;
992
+ }
993
+ //#endregion
994
+ //#region src/authoring/build.ts
995
+ function record(value, keys) {
996
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
997
+ for (const key of Reflect.ownKeys(value)) {
998
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
999
+ if (typeof key !== "string" || keys && !keys.includes(key) || !descriptor.enumerable || !("value" in descriptor)) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
1000
+ }
1001
+ }
1002
+ /** Capture the immutable batch before any secret source is invoked. */
1003
+ function defineBuild(input) {
1004
+ if (kindOf(input) === "build") return input;
1005
+ try {
1006
+ record(input, [
1007
+ "profiles",
1008
+ "secrets",
1009
+ "outDir"
1010
+ ]);
1011
+ if (input.outDir !== void 0 && (typeof input.outDir !== "string" || !input.outDir.trim() || input.outDir.trim() !== input.outDir || input.outDir.includes("\0"))) throw new Error();
1012
+ record(input.profiles);
1013
+ const keys = Object.keys(input.profiles);
1014
+ if (!keys.length || keys.length > 16 || keys.some((k) => !/^[a-z0-9][a-z0-9-]*$/.test(k))) throw new Error();
1015
+ for (const p of Object.values(input.profiles)) requireKind(p, ["profile"]);
1016
+ if (input.secrets !== void 0) requireKind(input.secrets, ["secrets"]);
1017
+ return created({
1018
+ ...input.outDir === void 0 ? {} : { outDir: input.outDir },
1019
+ profiles: input.profiles,
1020
+ ...input.secrets === void 0 ? {} : { secrets: input.secrets }
1021
+ }, "build");
1022
+ } catch {
1023
+ throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
1024
+ }
1025
+ }
1026
+ //#endregion
1027
+ //#region src/model/routing-model.ts
1028
+ const exitId = (exit) => "builtin" in exit ? exit.builtin : exit.id;
1029
+ function normalizeRouting(profile, inspected) {
1030
+ const sets = /* @__PURE__ */ new Map();
1031
+ const modern = profile.target.engine === "sing-box" && profile.target.version === "1.14.4";
1032
+ const lower = (condition) => {
1033
+ if (condition.type === "all" || condition.type === "any") return {
1034
+ type: condition.type,
1035
+ conditions: condition.conditions.map(lower)
1036
+ };
1037
+ if (condition.type === "not") return {
1038
+ type: "not",
1039
+ condition: lower(condition.condition)
1040
+ };
1041
+ if (condition.type === "ruleSetSource" || condition.type === "ruleSet") {
1042
+ const native = condition.type === "ruleSetSource" ? inspected.mapped.get(condition) : void 0;
1043
+ const canonical = native?.id ?? condition.id;
1044
+ sets.set(condition, canonical);
1045
+ return {
1046
+ type: "ruleSet",
1047
+ id: condition.id,
1048
+ canonical,
1049
+ resource: condition,
1050
+ resolves: !!(modern && native?.engine === "sing-box" && native.resolve)
1051
+ };
1052
+ }
1053
+ const ip = [
1054
+ "ipCidr",
1055
+ "ipCidr6",
1056
+ "ipAsn"
1057
+ ].includes(condition.type);
1058
+ const noResolve = "noResolve" in condition ? condition.noResolve : void 0;
1059
+ const resolves = ip && (profile.target.engine === "surge" || modern ? noResolve !== true : profile.target.engine === "mihomo" || profile.target.engine === "stash" ? noResolve === false : false);
1060
+ return {
1061
+ ...condition,
1062
+ resolves
1063
+ };
1064
+ };
1065
+ return deepFreeze({
1066
+ target: profile.target,
1067
+ ...profile.singBox?.domainMatching ? { domainMatching: profile.singBox.domainMatching } : {},
1068
+ rules: profile.routes.map((r, index) => ({
1069
+ index,
1070
+ when: lower(r.when),
1071
+ exit: exitId(r.to),
1072
+ origin: originOf(r)
1073
+ })),
1074
+ fallback: exitId(profile.fallback),
1075
+ ruleSets: sets
1076
+ });
1077
+ }
1078
+ //#endregion
1079
+ //#region src/routing/request.ts
1080
+ const domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
1081
+ const ip = z.string().refine((v) => isIP(v) !== 0 && !v.includes("%"));
1082
+ const port = z.number().int().min(1).max(65535);
1083
+ const schema = z.strictObject({
1084
+ network: z.enum(["tcp", "udp"]).optional(),
1085
+ domain: domain.optional(),
1086
+ sniffedDomain: domain.optional(),
1087
+ ip: ip.optional(),
1088
+ resolvedIp: ip.optional(),
1089
+ asn: z.number().int().min(1).max(4294967295).optional(),
1090
+ port: port.optional(),
1091
+ sourceIp: ip.optional(),
1092
+ sourcePort: port.optional(),
1093
+ processName: processNameSchema.optional(),
1094
+ macAddress: z.string().regex(/^(?:[a-f0-9]{2}:){5}[a-f0-9]{2}$/i).optional()
1095
+ });
1096
+ function parseRequest(input) {
1097
+ try {
1098
+ inspectDefinition(input);
1099
+ } catch {
1100
+ throw new ProfileDefinitionError("INVALID_REQUEST", ["request"]);
1101
+ }
1102
+ const parsed = schema.safeParse(input);
1103
+ if (!parsed.success) throw new ProfileDefinitionError("INVALID_REQUEST", parsed.error.issues.flatMap((i) => i.code === "unrecognized_keys" ? i.keys : i.path.length ? [i.path.join(".")] : ["request"]));
1104
+ if (parsed.data.ip !== void 0 && parsed.data.resolvedIp !== void 0) throw new ProfileDefinitionError("INVALID_REQUEST", ["ip", "resolvedIp"]);
1105
+ return Object.freeze({
1106
+ ...parsed.data,
1107
+ network: parsed.data.network ?? "tcp"
1108
+ });
1109
+ }
1110
+ //#endregion
1111
+ //#region src/routing/assumptions.ts
1112
+ function prepareAssumptions(model, input = {}) {
1113
+ const values = /* @__PURE__ */ new Map();
1114
+ const errors = [];
1115
+ try {
1116
+ inspectDefinition(input);
1117
+ } catch {
1118
+ return {
1119
+ values,
1120
+ errors: [{
1121
+ code: "INVALID_ASSUMPTIONS",
1122
+ path: "assume"
1123
+ }]
1124
+ };
1125
+ }
1126
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((k) => !["hit", "miss"].includes(k))) return {
1127
+ values,
1128
+ errors: [{
1129
+ code: "INVALID_ASSUMPTIONS",
1130
+ path: "assume"
1131
+ }]
1132
+ };
1133
+ for (const field of ["hit", "miss"]) {
1134
+ const refs = input[field];
1135
+ if (refs === void 0) continue;
1136
+ if (!Array.isArray(refs)) {
1137
+ errors.push({
1138
+ code: "INVALID_ASSUMPTIONS",
1139
+ path: `assume.${field}`
1140
+ });
1141
+ continue;
1142
+ }
1143
+ refs.forEach((ref, i) => {
1144
+ const path = `assume.${field}[${i}]`;
1145
+ if (kindOf(ref) !== "ruleSet" || !model.ruleSets.has(ref)) {
1146
+ errors.push({
1147
+ code: "ASSUMPTION_UNKNOWN_RULESET",
1148
+ path
1149
+ });
1150
+ return;
1151
+ }
1152
+ const canonical = model.ruleSets.get(ref);
1153
+ const value = field === "hit";
1154
+ if (values.has(canonical) && values.get(canonical) !== value) errors.push({
1155
+ code: "INVALID_ASSUMPTIONS",
1156
+ path
1157
+ });
1158
+ else values.set(canonical, value);
1159
+ });
1160
+ }
1161
+ return {
1162
+ values,
1163
+ errors
1164
+ };
1165
+ }
1166
+ //#endregion
1167
+ //#region src/routing/evaluate.ts
1168
+ const yes = { matched: true };
1169
+ const no = { matched: false };
1170
+ const unknown = (needs) => ({
1171
+ matched: null,
1172
+ needs
1173
+ });
1174
+ function combine(type, children) {
1175
+ if (type === "all" && children.some((c) => c.matched === false)) return no;
1176
+ if (type === "any" && children.some((c) => c.matched === true)) return yes;
1177
+ return children.find((c) => c.matched === null) ?? (type === "all" ? yes : no);
1178
+ }
1179
+ function ipMatches(value, cidr) {
1180
+ const address = ipaddr.parse(value);
1181
+ if (!cidr.includes("/")) {
1182
+ const other = ipaddr.parse(cidr);
1183
+ return address.kind() === other.kind() && address.toNormalizedString() === other.toNormalizedString();
1184
+ }
1185
+ const [network, bits] = ipaddr.parseCIDR(cidr);
1186
+ return address.kind() === network.kind() && address.match(network, bits);
1187
+ }
1188
+ function evaluate(model, request, assumptions) {
1189
+ let resolved = false;
1190
+ const trace = [];
1191
+ const currentIp = () => request.ip ?? (resolved ? request.resolvedIp : void 0);
1192
+ const atom = (condition, nested) => {
1193
+ if (condition.type === "all" || condition.type === "any") return combine(condition.type, condition.conditions.map((c) => atom(c, true)));
1194
+ if (condition.type === "not") {
1195
+ const result = atom(condition.condition, true);
1196
+ return result.matched === null ? result : { matched: !result.matched };
1197
+ }
1198
+ if (condition.resolves && !currentIp() && nested && !resolved) return unknown({ kind: "dns" });
1199
+ switch (condition.type) {
1200
+ case "ruleSet": return assumptions.has(condition.canonical) ? { matched: assumptions.get(condition.canonical) } : unknown({
1201
+ kind: "ruleSet",
1202
+ id: condition.id
1203
+ });
1204
+ case "domain":
1205
+ case "domainSuffix": return { matched: (model.target.engine === "sing-box" && model.domainMatching === "prefer-sniffed" ? [request.sniffedDomain ?? request.domain] : model.target.engine === "surge" && condition.includeSniffed ? [request.domain, request.sniffedDomain] : [request.domain]).some((v) => v !== void 0 && (v === condition.value || condition.type === "domainSuffix" && v.endsWith("." + condition.value))) };
1206
+ case "ipCidr":
1207
+ case "ipCidr6":
1208
+ case "ipAsn": {
1209
+ const ip = currentIp();
1210
+ if (!ip) return resolved ? unknown({ kind: "dns" }) : no;
1211
+ if (condition.type === "ipAsn") return request.asn === void 0 ? unknown({ kind: "asn" }) : { matched: request.asn === condition.value };
1212
+ return { matched: ipMatches(ip, condition.value) };
1213
+ }
1214
+ case "sourceIp": return { matched: request.sourceIp !== void 0 && ipMatches(request.sourceIp, condition.value) };
1215
+ case "network": return { matched: (request.network ?? "tcp") === condition.value };
1216
+ case "processName": return { matched: request.processName === condition.value };
1217
+ case "macAddress": return { matched: request.macAddress?.toLowerCase() === condition.value.toLowerCase() };
1218
+ case "port":
1219
+ case "sourcePort": {
1220
+ const port = condition.type === "port" ? request.port : request.sourcePort;
1221
+ return { matched: port !== void 0 && port >= condition.from && port <= (condition.to ?? condition.from) };
1222
+ }
1223
+ }
1224
+ };
1225
+ for (const rule of model.rules) {
1226
+ if (!request.ip && "resolves" in rule.when && rule.when.resolves) resolved = true;
1227
+ const result = atom(rule.when, false);
1228
+ trace.push({
1229
+ index: rule.index,
1230
+ matched: result.matched,
1231
+ ...rule.origin ? { origin: rule.origin } : {}
1232
+ });
1233
+ if (result.matched === null) return {
1234
+ outcome: "indeterminate",
1235
+ needs: result.needs,
1236
+ trace
1237
+ };
1238
+ if (result.matched) return {
1239
+ outcome: "matched",
1240
+ exit: rule.exit,
1241
+ route: {
1242
+ index: rule.index,
1243
+ ...rule.origin ? { origin: rule.origin } : {}
1244
+ },
1245
+ trace
1246
+ };
1247
+ }
1248
+ return {
1249
+ outcome: "fallback",
1250
+ exit: model.fallback,
1251
+ trace
1252
+ };
1253
+ }
1254
+ //#endregion
1255
+ //#region src/build/cases.ts
1256
+ function checkCases(profile, key, prepared, valid) {
1257
+ const diagnostics = [];
1258
+ const cases = [];
1259
+ const names = /* @__PURE__ */ new Set();
1260
+ const add = (code, path, resource) => diagnostics.push({
1261
+ severity: "error",
1262
+ code,
1263
+ path,
1264
+ profile: key,
1265
+ message: code,
1266
+ origin: originOf(resource) ?? originOf(profile)
1267
+ });
1268
+ const parsed = profile.cases.map((c, index) => {
1269
+ const path = `cases[${index}]`;
1270
+ if (names.has(c.name)) add("CASE_NAME_DUPLICATE", path + ".name", c);
1271
+ names.add(c.name);
1272
+ let request;
1273
+ try {
1274
+ request = parseRequest(c.request);
1275
+ } catch (e) {
1276
+ for (const field of e instanceof ProfileDefinitionError ? e.paths ?? ["request"] : ["request"]) add("INVALID_REQUEST", path + ".request" + (field === "request" ? "" : "." + field), c);
1277
+ }
1278
+ const assume = prepared.ruleSets ? prepareAssumptions({ ruleSets: prepared.ruleSets }, c.assume) : void 0;
1279
+ for (const e of assume?.errors ?? []) add(e.code, path + "." + e.path, c);
1280
+ return {
1281
+ c,
1282
+ request,
1283
+ assume
1284
+ };
1285
+ });
1286
+ const runnable = valid && diagnostics.length === 0 && prepared.routing !== void 0;
1287
+ for (const { c, request, assume } of parsed) {
1288
+ const base = {
1289
+ name: c.name,
1290
+ profile: key,
1291
+ expected: exitId(c.expect)
1292
+ };
1293
+ if (!runnable || !request || !assume) {
1294
+ cases.push({
1295
+ ...base,
1296
+ ok: false,
1297
+ outcome: "skipped"
1298
+ });
1299
+ continue;
1300
+ }
1301
+ const explanation = evaluate(prepared.routing, request, assume.values);
1302
+ cases.push({
1303
+ ...base,
1304
+ ok: explanation.outcome !== "indeterminate" && explanation.exit === base.expected,
1305
+ outcome: explanation.outcome,
1306
+ ...explanation.exit ? { actual: explanation.exit } : {},
1307
+ ...explanation.needs ? { needs: explanation.needs } : {},
1308
+ ...explanation.route ? { route: explanation.route } : {}
1309
+ });
1310
+ }
1311
+ return {
1312
+ diagnostics,
1313
+ cases
1314
+ };
1315
+ }
1316
+ //#endregion
1317
+ //#region src/model/diagnostic-view.ts
1318
+ function diagnosticView(profile, inspected) {
1319
+ const diagnosticSecret = register({
1320
+ type: "env",
1321
+ name: "TEST_DIAGNOSTIC_ONLY"
1322
+ }, "secret");
1323
+ const surge = profile.target.engine === "surge";
1324
+ const destination = (exit) => !surge && "builtin" in exit && !["DIRECT", "REJECT"].includes(exit.builtin) ? { builtin: "DIRECT" } : exit;
1325
+ const proxies = profile.proxies.map((resource) => {
1326
+ if (surge && resource.type === "sing-box-tailscale" || !surge && ["tailscale", "wireguard"].includes(resource.type)) return {
1327
+ type: "trojan",
1328
+ id: resource.id,
1329
+ server: "192.0.2.1",
1330
+ port: 443,
1331
+ password: diagnosticSecret
1332
+ };
1333
+ return resource;
1334
+ });
1335
+ const groups = profile.groups.map((resource) => {
1336
+ const algorithm = (surge ? resource.algorithm.type === "urltest" : resource.algorithm.type === "surge-smart" || profile.target.engine === "stash" && resource.algorithm.type !== "select") ? { type: "select" } : resource.algorithm;
1337
+ const { surge: options, ...rest } = resource;
1338
+ return {
1339
+ ...rest,
1340
+ algorithm,
1341
+ members: resource.members.map(destination),
1342
+ ...surge && algorithm.type === "select" && options ? { surge: options } : {}
1343
+ };
1344
+ });
1345
+ const stripName = (resource) => {
1346
+ const { name: _name, ...rest } = resource;
1347
+ return rest;
1348
+ };
1349
+ return {
1350
+ ...profile,
1351
+ proxies: proxies.map(stripName),
1352
+ groups: groups.map(stripName),
1353
+ routes: inspected.rules.map((r) => ({
1354
+ ...r,
1355
+ to: destination(r.to)
1356
+ })),
1357
+ fallback: destination(profile.fallback)
1358
+ };
1359
+ }
1360
+ //#endregion
1361
+ //#region src/model/protocols.ts
1362
+ function nodeIsTcpOnly(node, engine, version) {
1363
+ return node.type === "http" || node.type === "anytls" && engine !== "surge" && !(engine === "sing-box" && version === "1.14.4") || node.type === "vmess" || node.type === "vless" && !(engine === "sing-box" && version === "1.14.4" && node.packetEncoding) || engine === "surge" && node.type === "shadowsocks" && node.surge?.udpRelay === false;
1364
+ }
1365
+ //#endregion
1366
+ //#region src/model/network.ts
1367
+ function truthPossibilities(condition, network) {
1368
+ switch (condition.type) {
1369
+ case "network": return [condition.value === network];
1370
+ case "not": return truthPossibilities(condition.condition, network).map((v) => !v);
1371
+ case "all": {
1372
+ const sets = condition.conditions.map((c) => truthPossibilities(c, network));
1373
+ return [...sets.every((s) => s.includes(true)) ? [true] : [], ...sets.some((s) => s.includes(false)) ? [false] : []];
1374
+ }
1375
+ case "any": {
1376
+ const sets = condition.conditions.map((c) => truthPossibilities(c, network));
1377
+ return [...sets.some((s) => s.includes(true)) ? [true] : [], ...sets.every((s) => s.includes(false)) ? [false] : []];
1378
+ }
1379
+ default: return [false, true];
1380
+ }
1381
+ }
1382
+ //#endregion
1383
+ //#region src/model/inspect-profile.ts
1384
+ function inspectProfile(profile, key, secrets, checkSecrets = true) {
1385
+ const diagnostics = [];
1386
+ const selections = [];
1387
+ const error = (code, path, object, message = code) => diagnostics.push({
1388
+ severity: "error",
1389
+ code,
1390
+ profile: key,
1391
+ path,
1392
+ message,
1393
+ origin: originOf(object) ?? originOf(profile)
1394
+ });
1395
+ const resources = [...profile.proxies, ...profile.groups];
1396
+ const listed = new Set(resources);
1397
+ const ids = /* @__PURE__ */ new Map();
1398
+ const names = /* @__PURE__ */ new Map();
1399
+ const usedNames = /* @__PURE__ */ new Map();
1400
+ const id = (object, path) => {
1401
+ const old = ids.get(object.id);
1402
+ if (old && old !== object) error("DUPLICATE_ID", path, object);
1403
+ else ids.set(object.id, object);
1404
+ };
1405
+ for (const resource of resources) {
1406
+ const path = resource.type === "proxy-group" ? `groups.${resource.id}` : `proxies.${resource.id}`;
1407
+ id(resource, path + ".id");
1408
+ const name = resource.name ?? resource.id;
1409
+ names.set(resource.id, name);
1410
+ if (usedNames.has(name) || [
1411
+ "DIRECT",
1412
+ "REJECT",
1413
+ "REJECT-DROP",
1414
+ "REJECT-NO-DROP",
1415
+ "REJECT-TINYGIF"
1416
+ ].includes(name.toUpperCase()) || isReservedNativeName(name, profile.target.engine)) error("DUPLICATE_NATIVE_NAME", path + ".name", resource);
1417
+ else usedNames.set(name, resource);
1418
+ if (!nativeNameSchema.safeParse(name).success && !["DIRECT", "REJECT"].includes(name.toUpperCase())) error("NAME_UNSAFE", path + ".name", resource);
1419
+ selections.push({
1420
+ kind: "name",
1421
+ resource: resource.id,
1422
+ nativeName: name
1423
+ });
1424
+ }
1425
+ for (const resource of resources) {
1426
+ const path = resource.type === "proxy-group" ? `groups.${resource.id}` : `proxies.${resource.id}`;
1427
+ if (kindOf(resource) === "tunnel" && profile.target.engine !== "surge" || kindOf(resource) === "endpoint" && profile.target.engine !== "sing-box") error("TUNNEL_UNSUPPORTED", path, resource);
1428
+ if (resource.type === "proxy-group") {
1429
+ if (resource.surge !== void 0 && (profile.target.engine !== "surge" || resource.algorithm.type !== "select")) error("GROUP_OPTION_UNSUPPORTED", path + ".surge", resource);
1430
+ if (resource.algorithm.type === "surge-smart" && profile.target.engine !== "surge") error("ALGORITHM_ENGINE_MISMATCH", path + ".algorithm", resource);
1431
+ else if (resource.algorithm.type === "auto" && profile.target.engine === "stash" || resource.algorithm.type === "urltest" && ["surge", "stash"].includes(profile.target.engine)) error("GROUP_ALGORITHM_UNSUPPORTED", path + ".algorithm", resource);
1432
+ }
1433
+ }
1434
+ const reference = (exit, path, owner) => {
1435
+ if (kindOf(exit) !== "builtin" && !listed.has(exit)) error("UNLISTED_EXIT", path, owner);
1436
+ if (profile.target.engine !== "surge" && "builtin" in exit && !["DIRECT", "REJECT"].includes(exit.builtin)) error("EXIT_UNSUPPORTED", path, owner);
1437
+ };
1438
+ const edges = /* @__PURE__ */ new Map();
1439
+ for (const resource of resources) {
1440
+ const path = resource.type === "proxy-group" ? `groups.${resource.id}` : `proxies.${resource.id}`;
1441
+ if (resource.type === "proxy-group") {
1442
+ resource.members.forEach((m, i) => {
1443
+ reference(m, `${path}.members[${i}]`, resource);
1444
+ if (kindOf(m) === "endpoint") error("MEMBER_TYPE_UNSUPPORTED", `${path}.members[${i}]`, resource);
1445
+ });
1446
+ edges.set(resource, resource.members.filter((m) => kindOf(m) !== "builtin"));
1447
+ if (resource.algorithm.type === "auto" && profile.target.engine !== "stash") selections.push({
1448
+ kind: "algorithm",
1449
+ group: resource.id,
1450
+ algorithm: profile.target.engine === "surge" ? "surge-smart" : "urltest",
1451
+ ...profile.target.engine === "surge" ? {} : { parameters: {
1452
+ url: "https://www.gstatic.com/generate_204",
1453
+ intervalSeconds: 180,
1454
+ toleranceMs: 50
1455
+ } }
1456
+ });
1457
+ } else if ("via" in resource && resource.via) {
1458
+ reference(resource.via, path + ".via", resource);
1459
+ edges.set(resource, [resource.via]);
1460
+ }
1461
+ }
1462
+ const active = [];
1463
+ const visited = /* @__PURE__ */ new Set();
1464
+ const cycleKeys = /* @__PURE__ */ new Set();
1465
+ const visit = (v) => {
1466
+ const at = active.indexOf(v);
1467
+ if (at !== -1) {
1468
+ const ids = active.slice(at).map((r) => r.id);
1469
+ const signature = [...ids].sort().join(",");
1470
+ if (!cycleKeys.has(signature)) {
1471
+ cycleKeys.add(signature);
1472
+ error("GROUP_CYCLE", `${kindOf(v) === "group" ? "groups" : "proxies"}.${ids[0]}`, v, `Dependency cycle: ${ids.join(" -> ")}`);
1473
+ }
1474
+ return;
1475
+ }
1476
+ if (visited.has(v)) return;
1477
+ active.push(v);
1478
+ for (const edge of edges.get(v) ?? []) visit(edge);
1479
+ active.pop();
1480
+ visited.add(v);
1481
+ };
1482
+ resources.forEach(visit);
1483
+ const tcpCache = /* @__PURE__ */ new Map();
1484
+ const tcpVisiting = /* @__PURE__ */ new Set();
1485
+ const tcpOnly = (exit) => {
1486
+ const cached = tcpCache.get(exit);
1487
+ if (cached !== void 0) return cached;
1488
+ if (tcpVisiting.has(exit)) return false;
1489
+ tcpVisiting.add(exit);
1490
+ let tcp = kindOf(exit) === "node" && nodeIsTcpOnly(exit, profile.target.engine, profile.target.version);
1491
+ for (const edge of edges.get(exit) ?? []) tcp = tcpOnly(edge) || tcp;
1492
+ tcpVisiting.delete(exit);
1493
+ tcpCache.set(exit, tcp);
1494
+ return tcp;
1495
+ };
1496
+ const rejectUnsupportedSurgeUdp = profile.target.engine === "surge" && profile.surge?.general?.["udp-policy-not-supported-behaviour"] === "REJECT";
1497
+ const relayCache = /* @__PURE__ */ new Map();
1498
+ const relayVisiting = /* @__PURE__ */ new Set();
1499
+ const unsafeSurgeRelay = (exit) => {
1500
+ const cached = relayCache.get(exit);
1501
+ if (cached !== void 0) return cached;
1502
+ if (relayVisiting.has(exit)) return false;
1503
+ relayVisiting.add(exit);
1504
+ const unsafe = kindOf(exit) === "group" ? (edges.get(exit) ?? []).some((member) => unsafeSurgeRelay(member)) : "via" in exit && exit.via !== void 0 && tcpOnly(exit.via);
1505
+ relayVisiting.delete(exit);
1506
+ relayCache.set(exit, unsafe);
1507
+ return unsafe;
1508
+ };
1509
+ const requiresTcp = (exit) => rejectUnsupportedSurgeUdp ? unsafeSurgeRelay(exit) : tcpOnly(exit);
1510
+ if (!(profile.target.engine === "sing-box" && profile.target.version === "1.14.4" && profile.singBox?.unsupportedUdp === "reject")) {
1511
+ profile.routes.forEach((route, i) => {
1512
+ if (requiresTcp(route.to) && truthPossibilities(route.when, "udp").includes(true)) error("TCP_ONLY_EXIT", `routes[${i}].to`, route);
1513
+ });
1514
+ if (requiresTcp(profile.fallback)) error("TCP_ONLY_EXIT", "fallback", profile);
1515
+ }
1516
+ const secretRefs = /* @__PURE__ */ new Set();
1517
+ const scanned = /* @__PURE__ */ new WeakSet();
1518
+ function scan(value, path, owner) {
1519
+ if (!value || typeof value !== "object") return;
1520
+ if (kindOf(value) === "secret") {
1521
+ const ref = value;
1522
+ secretRefs.add(ref);
1523
+ if (checkSecrets && !sourceFor(secrets, ref)) error("SECRET_UNDECLARED", path, owner);
1524
+ return;
1525
+ }
1526
+ if (value !== owner && [
1527
+ "node",
1528
+ "group",
1529
+ "tunnel",
1530
+ "endpoint"
1531
+ ].includes(kindOf(value) ?? "")) return;
1532
+ if (scanned.has(value)) return;
1533
+ scanned.add(value);
1534
+ if (Array.isArray(value)) value.forEach((v, i) => scan(v, `${path}[${i}]`, owner));
1535
+ else for (const [k, v] of Object.entries(value)) scan(v, `${path}.${k}`, owner);
1536
+ scanned.delete(value);
1537
+ }
1538
+ profile.proxies.forEach((r) => scan(r, `proxies.${r.id}`, r));
1539
+ if (profile.surge) scan(profile.surge, "surge", profile);
1540
+ const sources = /* @__PURE__ */ new Map();
1541
+ const mapped = /* @__PURE__ */ new Map();
1542
+ const usedSets = /* @__PURE__ */ new Set();
1543
+ const branch = profile.target.engine === "sing-box" ? "singBox" : profile.target.engine === "mihomo" ? "mihomo" : "surge";
1544
+ function lower(condition, path, depth = 0) {
1545
+ if (profile.target.engine === "surge" && depth >= 10 && [
1546
+ "all",
1547
+ "any",
1548
+ "not"
1549
+ ].includes(condition.type)) {
1550
+ error("LOGICAL_DEPTH_EXCEEDED", path, condition);
1551
+ return {
1552
+ type: "domain",
1553
+ value: "diagnostic.example"
1554
+ };
1555
+ }
1556
+ if (condition.type === "all" || condition.type === "any") return {
1557
+ ...condition,
1558
+ conditions: condition.conditions.map((c, i) => lower(c, `${path}.conditions[${i}]`, depth + 1))
1559
+ };
1560
+ if (condition.type === "not") return {
1561
+ ...condition,
1562
+ condition: lower(condition.condition, path + ".condition", depth + 1)
1563
+ };
1564
+ const placeholder = {
1565
+ type: "domain",
1566
+ value: "diagnostic.example"
1567
+ };
1568
+ if (profile.target.engine === "surge" && depth > 10) {
1569
+ error("LOGICAL_DEPTH_EXCEEDED", path, condition);
1570
+ return placeholder;
1571
+ }
1572
+ if (profile.target.engine !== "surge" && [
1573
+ "ruleSet",
1574
+ "ipAsn",
1575
+ "ipCidr6",
1576
+ "macAddress"
1577
+ ].includes(condition.type)) {
1578
+ error(condition.type === "ruleSet" && profile.target.engine === "stash" ? "RULESET_UNSUPPORTED" : "CONDITION_UNSUPPORTED", path, condition);
1579
+ return placeholder;
1580
+ }
1581
+ if (condition.type !== "ruleSetSource") return condition;
1582
+ const set = condition;
1583
+ id(set, path);
1584
+ if (profile.target.engine === "stash") {
1585
+ error("RULESET_UNSUPPORTED", path, set);
1586
+ return placeholder;
1587
+ }
1588
+ const source = set[branch];
1589
+ if (!source) {
1590
+ error("RULESET_SOURCE_MISSING", path, set);
1591
+ return placeholder;
1592
+ }
1593
+ const format = "format" in source ? source.format ?? "rule-set" : "rule-set";
1594
+ const signature = JSON.stringify([
1595
+ format,
1596
+ source.intervalSeconds ?? 86400,
1597
+ "behavior" in source ? source.behavior : void 0
1598
+ ]);
1599
+ const previous = sources.get(source.url);
1600
+ if (previous && previous.signature !== signature) error("RULESET_SOURCE_CONFLICT", path, set);
1601
+ const nativeName = previous && branch !== "surge" ? previous.nativeName : set.id;
1602
+ if (!previous) sources.set(source.url, {
1603
+ signature,
1604
+ nativeName: set.id
1605
+ });
1606
+ if (!usedSets.has(set)) {
1607
+ selections.push({
1608
+ kind: "ruleSet",
1609
+ ruleSet: set.id,
1610
+ branch,
1611
+ nativeName
1612
+ });
1613
+ usedSets.add(set);
1614
+ }
1615
+ if (branch === "surge" && depth && source.intervalSeconds !== void 0) error("CONDITION_UNSUPPORTED", path, set);
1616
+ const native = {
1617
+ type: "nativeRuleSet",
1618
+ id: nativeName,
1619
+ engine: profile.target.engine,
1620
+ format,
1621
+ ...source,
1622
+ ...branch === "surge" && depth ? { intervalSeconds: void 0 } : {}
1623
+ };
1624
+ mapped.set(set, native);
1625
+ return native;
1626
+ }
1627
+ const rules = profile.routes.map((route, i) => {
1628
+ reference(route.to, `routes[${i}].to`, route);
1629
+ return {
1630
+ ...route,
1631
+ when: lower(route.when, `routes[${i}].when`)
1632
+ };
1633
+ });
1634
+ reference(profile.fallback, "fallback", profile);
1635
+ profile.cases?.forEach((c, i) => reference(c.expect, `cases[${i}].expect`, c));
1636
+ return {
1637
+ diagnostics,
1638
+ selections,
1639
+ names,
1640
+ rules,
1641
+ secretRefs,
1642
+ ruleSets: usedSets,
1643
+ mapped
1644
+ };
1645
+ }
1646
+ //#endregion
1647
+ //#region src/model/normalize.ts
1648
+ const fail$1 = (code) => {
1649
+ throw new ProfileDefinitionError(code);
1650
+ };
1651
+ function normalizeProfile(profile) {
1652
+ const byId = /* @__PURE__ */ new Map();
1653
+ for (const resource of [...profile.proxies, ...profile.groups]) {
1654
+ if (!resource || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
1655
+ byId.set(resource.id, resource);
1656
+ }
1657
+ const destination = (value) => {
1658
+ if (!value || typeof value !== "object") return fail$1("INVALID_DESTINATION");
1659
+ if ("builtin" in value) {
1660
+ exactDefinition(value, ["builtin"]);
1661
+ if (value.builtin === "DIRECT") return { type: "direct" };
1662
+ if (value.builtin === "REJECT") return { type: "reject" };
1663
+ return fail$1("PROFILE_DESTINATION_UNSUPPORTED");
1664
+ }
1665
+ return {
1666
+ type: "route",
1667
+ to: value.id
1668
+ };
1669
+ };
1670
+ const algorithm = (group) => {
1671
+ exactDefinition(group, [
1672
+ "type",
1673
+ "id",
1674
+ "name",
1675
+ "algorithm",
1676
+ "members",
1677
+ "surge"
1678
+ ]);
1679
+ if (group.type !== "proxy-group" || !group.members.length) fail$1("INVALID_GROUP_DEFINITION");
1680
+ const a = group.algorithm;
1681
+ exactDefinition(a, a.type === "urltest" ? [
1682
+ "type",
1683
+ "url",
1684
+ "intervalSeconds",
1685
+ "toleranceMs"
1686
+ ] : ["type"]);
1687
+ const members = group.members.map((m) => {
1688
+ const x = destination(m);
1689
+ return x.type === "route" ? x.to : x.type === "direct" ? "DIRECT" : "REJECT";
1690
+ });
1691
+ if (a.type === "auto") return {
1692
+ id: group.id,
1693
+ members,
1694
+ type: "urltest",
1695
+ url: "https://www.gstatic.com/generate_204",
1696
+ intervalSeconds: 180,
1697
+ toleranceMs: 50
1698
+ };
1699
+ if (a.type === "urltest") {
1700
+ let url;
1701
+ try {
1702
+ url = new URL(a.url);
1703
+ } catch {
1704
+ return fail$1("INVALID_GROUP_DEFINITION");
1705
+ }
1706
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || !Number.isInteger(a.intervalSeconds ?? 180) || (a.intervalSeconds ?? 180) < 1 || (a.intervalSeconds ?? 180) > 86400 || !Number.isInteger(a.toleranceMs ?? 50) || (a.toleranceMs ?? 50) < 0 || (a.toleranceMs ?? 50) > 6e4) fail$1("INVALID_GROUP_DEFINITION");
1707
+ }
1708
+ return {
1709
+ ...a,
1710
+ id: group.id,
1711
+ members
1712
+ };
1713
+ };
1714
+ const nodes = [], endpoints = [];
1715
+ for (const item of profile.proxies) if (item.type === "sing-box-tailscale") {
1716
+ const { name: _name, ...native } = item;
1717
+ const parsed = endpointSchema.safeParse(native);
1718
+ if (!parsed.success) fail$1("INVALID_RESOURCE_DEFINITION");
1719
+ endpoints.push(parsed.data);
1720
+ } else {
1721
+ const { name: _name, ...native } = item;
1722
+ if ("via" in native && native.via) Object.assign(native, { via: native.via.id });
1723
+ const parsed = nodeSchema.safeParse(native);
1724
+ if (!parsed.success) fail$1("INVALID_RESOURCE_DEFINITION");
1725
+ nodes.push(parsed.data);
1726
+ }
1727
+ const extension = profile.target.engine === "sing-box" ? profile.singBox : profile.mihomo;
1728
+ if (!engineOptionsSchema.safeParse(extension ?? {}).success) fail$1("INVALID_PROFILE_DEFINITION");
1729
+ const mode = extension?.mode ?? (profile.target.engine === "sing-box" ? "standalone" : "fragment");
1730
+ return deepFreeze(snapshotDefinition({
1731
+ target: {
1732
+ ...profile.target,
1733
+ id: "profile",
1734
+ mode
1735
+ },
1736
+ nodes,
1737
+ endpoints,
1738
+ groups: profile.groups.map(algorithm),
1739
+ rules: profile.routes.map((r, i) => {
1740
+ exactDefinition(r, [
1741
+ "type",
1742
+ "when",
1743
+ "to"
1744
+ ]);
1745
+ if (r.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
1746
+ const when = matchSchema.safeParse(r.when);
1747
+ if (!when.success) throw new ProfileDefinitionError("PROFILE_CONDITION_UNSUPPORTED", [`routes[${i}].when`]);
1748
+ return {
1749
+ id: `route-${i + 1}`,
1750
+ when: when.data,
1751
+ then: destination(r.to),
1752
+ origin: []
1753
+ };
1754
+ }),
1755
+ fallback: destination(profile.fallback),
1756
+ ...profile.dns === void 0 ? {} : { dns: profile.dns },
1757
+ ...extension
1758
+ }));
1759
+ }
1760
+ //#endregion
1761
+ //#region src/model/errors.ts
1762
+ var RenderError = class extends Error {
1763
+ code;
1764
+ constructor(code) {
1765
+ super(code);
1766
+ this.code = code;
1767
+ this.name = "RenderError";
1768
+ }
1769
+ };
1770
+ //#endregion
1771
+ //#region src/model/proxy-values.ts
1772
+ function uuid(token, secret) {
1773
+ const value = secret(token);
1774
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) throw new RenderError("INVALID_UUID_SECRET");
1775
+ return value;
1776
+ }
1777
+ function aliasProxyServer(node, aliases) {
1778
+ const server = aliases?.[node.server];
1779
+ if (!server) return node;
1780
+ if (node.type === "trojan" || node.type === "anytls" || node.type === "hysteria2") return {
1781
+ ...node,
1782
+ server,
1783
+ serverName: node.serverName ?? node.server
1784
+ };
1785
+ return {
1786
+ ...node,
1787
+ server
1788
+ };
1789
+ }
1790
+ //#endregion
1791
+ //#region src/engines/surge/proxies.ts
1792
+ function surgeProxy(node, secret, name = (id) => id) {
1793
+ const atom = (value) => {
1794
+ if (!/^[A-Za-z0-9_./:@+%-]+$/.test(value)) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
1795
+ return value;
1796
+ };
1797
+ const params = [
1798
+ `${name(node.id)} = ${node.type === "shadowsocks" ? "ss" : node.type}`,
1799
+ node.server,
1800
+ String(node.port)
1801
+ ];
1802
+ switch (node.type) {
1803
+ case "http":
1804
+ if (node.username) params.push(`username=${atom(secret(node.username))}`);
1805
+ params.push(`password=${atom(secret(node.password))}`);
1806
+ break;
1807
+ case "hysteria2":
1808
+ params.push(`password=${atom(secret(node.password))}`);
1809
+ if (node.serverName) params.push(`sni=${node.serverName}`);
1810
+ if (node.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.skipCertVerify}`);
1811
+ if (node.portHopping) params.push(`port-hopping=${node.portHopping}`);
1812
+ if (node.portHoppingInterval !== void 0) params.push(`port-hopping-interval=${node.portHoppingInterval}`);
1813
+ break;
1814
+ case "trojan":
1815
+ case "anytls":
1816
+ params.push(`password=${atom(secret(node.password))}`);
1817
+ if (node.serverName) params.push(`sni=${node.serverName}`);
1818
+ if (node.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.skipCertVerify}`);
1819
+ break;
1820
+ case "shadowsocks":
1821
+ params.push(`encrypt-method=${node.method}`, `password=${atom(secret(node.password))}`);
1822
+ break;
1823
+ case "vmess":
1824
+ params.push(`username=${uuid(node.uuid, secret)}`, "vmess-aead=true", "encrypt-method=aes-128-gcm", `tls=${!!node.tls}`);
1825
+ if (node.tls) params.push(`sni=${node.tls.serverName}`);
1826
+ if (node.tls?.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.tls.skipCertVerify}`);
1827
+ if (node.transport) {
1828
+ params.push("ws=true", `ws-path=${node.transport.path}`);
1829
+ if (node.transport.host) params.push(`ws-headers=Host:${node.transport.host}`);
1830
+ }
1831
+ break;
1832
+ case "vless": throw new RenderError("PROTOCOL_UNSUPPORTED");
1833
+ }
1834
+ if (node.tcpFastOpen !== void 0) params.push(`tfo=${node.tcpFastOpen}`);
1835
+ if (node.type === "trojan" || node.type === "anytls" && node.surge?.udpRelay) params.push("udp-relay=true");
1836
+ if (node.type === "shadowsocks") params.push(`udp-relay=${node.surge?.udpRelay ?? true}`, `block-quic=${node.surge?.blockQuic ?? "off"}`);
1837
+ if (node.type !== "shadowsocks" && "surge" in node && node.surge?.blockQuic !== void 0) params.push(`block-quic=${node.surge.blockQuic}`);
1838
+ if (node.via) params.push(`underlying-proxy=${name(node.via)}`);
1839
+ return params.join(", ");
1840
+ }
1841
+ //#endregion
1842
+ //#region src/targets/proxies.ts
1843
+ function validateProxyOptions(node, target, diagnostics) {
1844
+ if (node.type === "hysteria2") {
1845
+ if (target.engine === "surge" && node.portHopping && node.via) diagnostics.push({
1846
+ severity: "error",
1847
+ code: "PROXY_OPTION_UNSUPPORTED",
1848
+ target: target.id,
1849
+ path: `proxies.${node.id}`,
1850
+ message: "Surge 端口跳跃不能与 underlying-proxy 同用"
1851
+ });
1852
+ return;
1853
+ }
1854
+ const tls = "tls" in node ? node.tls : void 0;
1855
+ const modern = target.engine === "sing-box" && target.version === "1.14.4";
1856
+ if (node.type === "vless" && !modern && (node.flow !== void 0 || node.packetEncoding !== void 0 || node.reality !== void 0 || node.utlsFingerprint !== void 0)) diagnostics.push({
1857
+ severity: "error",
1858
+ code: "PROXY_OPTION_UNSUPPORTED",
1859
+ target: target.id,
1860
+ path: `proxies.${node.id}`,
1861
+ message: "VLESS 扩展选项仅支持 sing-box 1.14.4"
1862
+ });
1863
+ if (target.engine !== "surge") {
1864
+ const surgeOptions = "surge" in node ? node.surge : void 0;
1865
+ const supportedUdpDeclaration = modern && surgeOptions !== void 0 && [
1866
+ "trojan",
1867
+ "anytls",
1868
+ "shadowsocks"
1869
+ ].includes(node.type) && Object.keys(surgeOptions).length === 1 && "udpRelay" in surgeOptions && surgeOptions.udpRelay === true;
1870
+ if (!modern && node.tcpFastOpen !== void 0 || modern && node.type === "anytls" && node.tcpFastOpen === true || !modern && "skipCertVerify" in node && node.skipCertVerify !== void 0 || !modern && tls?.skipCertVerify !== void 0 || surgeOptions !== void 0 && !supportedUdpDeclaration) diagnostics.push({
1871
+ severity: "error",
1872
+ code: "PROXY_OPTION_UNSUPPORTED",
1873
+ target: target.id,
1874
+ path: `proxies.${node.id}`,
1875
+ message: "显式节点选项尚未实现此精确目标的编码"
1876
+ });
1877
+ return;
1878
+ }
1879
+ if (("serverName" in node ? node.serverName : tls?.serverName) === "off" || tls?.alpn !== void 0) diagnostics.push({
1880
+ severity: "error",
1881
+ code: "PROXY_OPTION_UNSUPPORTED",
1882
+ target: target.id,
1883
+ path: `proxies.${node.id}`,
1884
+ message: "Surge 编码不接受特殊 SNI off 或显式 ALPN;不会丢弃 TLS 选项"
1885
+ });
1886
+ }
1887
+ //#endregion
1888
+ //#region src/engines/surge/profile.ts
1889
+ const plans = /* @__PURE__ */ new WeakMap();
1890
+ function compileSurgeProfile(input) {
1891
+ const diagnostics = [];
1892
+ const error = (code, path = "$") => diagnostics.push({
1893
+ severity: "error",
1894
+ code,
1895
+ path,
1896
+ message: code
1897
+ });
1898
+ const failure = () => deepFreeze({
1899
+ ok: false,
1900
+ artifactKind: "surge-profile",
1901
+ diagnostics,
1902
+ bindings: []
1903
+ });
1904
+ try {
1905
+ assertData(input);
1906
+ } catch {
1907
+ error("INVALID_INPUT_GRAPH");
1908
+ return failure();
1909
+ }
1910
+ const parsed = inputSchema.safeParse(input);
1911
+ if (!parsed.success) {
1912
+ error("INVALID_SCHEMA");
1913
+ return failure();
1914
+ }
1915
+ if (parsed.data.general) {
1916
+ const general = parsed.data.general;
1917
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
1918
+ }
1919
+ const p = deepFreeze(parsed.data);
1920
+ const tunnels = p.tunnels ?? [];
1921
+ const resources = [
1922
+ ...p.nodes,
1923
+ ...tunnels,
1924
+ ...p.groups
1925
+ ];
1926
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
1927
+ const ids = new Set(resources.map((r) => r.id));
1928
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
1929
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
1930
+ const bindings = resources.map((r) => ({
1931
+ id: r.id,
1932
+ nativeName: p.names?.[r.id] ?? r.id
1933
+ }));
1934
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
1935
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
1936
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
1937
+ if (p.target.platform === "ios" && [
1938
+ "bypass-system",
1939
+ "replica",
1940
+ "tls-provider",
1941
+ "bypass-tun",
1942
+ "external-controller-access"
1943
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
1944
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
1945
+ const checkPolicy = (action, path = "$") => {
1946
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE", path);
1947
+ };
1948
+ const edges = new Map(resources.map((r) => [r.id, []]));
1949
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
1950
+ for (const node of p.nodes) {
1951
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED", `proxies.${node.id}`);
1952
+ validateProxyOptions(node, {
1953
+ id: "profile",
1954
+ engine: "surge"
1955
+ }, diagnostics);
1956
+ if (node.via) {
1957
+ checkPolicy({ ref: node.via }, `proxies.${node.id}.via`);
1958
+ edges.get(node.id).push(node.via);
1959
+ }
1960
+ }
1961
+ for (const group of p.groups) {
1962
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
1963
+ for (const [i, member] of group.members.entries()) {
1964
+ checkPolicy(member, `groups.${group.id}.members[${i}]`);
1965
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED", `groups.${group.id}.members[${i}]`);
1966
+ if ("ref" in member) edges.get(group.id).push(member.ref);
1967
+ }
1968
+ }
1969
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
1970
+ const visit = (id) => {
1971
+ if (active.has(id)) {
1972
+ error("RESOURCE_CYCLE", `${p.groups.some((g) => g.id === id) ? "groups" : "proxies"}.${id}`);
1973
+ return;
1974
+ }
1975
+ if (visited.has(id)) return;
1976
+ active.add(id);
1977
+ for (const next of edges.get(id) ?? []) visit(next);
1978
+ active.delete(id);
1979
+ visited.add(id);
1980
+ };
1981
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
1982
+ const formats = /* @__PURE__ */ new Map();
1983
+ const checkCondition = (c, depth, path) => {
1984
+ if (depth > 10) {
1985
+ error("LOGICAL_DEPTH_EXCEEDED", path);
1986
+ return;
1987
+ }
1988
+ if (c.noResolve !== void 0 && ![
1989
+ "ipCidr",
1990
+ "ipCidr6",
1991
+ "ipAsn",
1992
+ "ruleSet"
1993
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED", path);
1994
+ if (c.includeSniffed !== void 0 && ![
1995
+ "domain",
1996
+ "domainSuffix",
1997
+ "ruleSet"
1998
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED", path);
1999
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED", path);
2000
+ if (c.type === "all" || c.type === "any") for (const [i, child] of c.conditions.entries()) checkCondition(child, depth + 1, `${path}.conditions[${i}]`);
2001
+ if (c.type === "not") checkCondition(c.condition, depth + 1, path + ".condition");
2002
+ if (c.type === "ruleSet") {
2003
+ if (c.intervalSeconds !== void 0 && (depth > 0 || c.builtin)) error("RULESET_COMPOSITION_UNSUPPORTED", path);
2004
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
2005
+ if (c.url) {
2006
+ const key = c.url;
2007
+ const settings = `${c.format}:${c.intervalSeconds ?? 86400}`;
2008
+ if (formats.has(key) && formats.get(key) !== settings) error("RULESET_FORMAT_CONFLICT");
2009
+ formats.set(key, settings);
2010
+ }
2011
+ }
2012
+ };
2013
+ for (const [i, rule] of p.rules.entries()) {
2014
+ checkPolicy(rule.then, `routes[${i}].to`);
2015
+ checkCondition(rule.when, 0, `routes[${i}].when`);
2016
+ }
2017
+ checkPolicy(p.fallback, "fallback");
2018
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
2019
+ if (formats.size) diagnostics.push({
2020
+ severity: "warning",
2021
+ code: "EXTERNAL_RULESET_UNVERIFIED",
2022
+ path: "rules",
2023
+ message: "External rule sets are resolved by the client, not by the compiler."
2024
+ });
2025
+ const result = deepFreeze({
2026
+ ok: true,
2027
+ artifactKind: "surge-profile",
2028
+ diagnostics,
2029
+ bindings
2030
+ });
2031
+ plans.set(result, p);
2032
+ return result;
2033
+ }
2034
+ function conditionOptions(c) {
2035
+ return [
2036
+ ...c.noResolve ? ["no-resolve"] : [],
2037
+ ..."includeSniffed" in c && c.includeSniffed ? ["extended-matching"] : [],
2038
+ ...c.type === "ruleSet" && c.intervalSeconds !== void 0 ? [`update-interval=${c.intervalSeconds}`] : []
2039
+ ];
2040
+ }
2041
+ function conditionText$2(c) {
2042
+ switch (c.type) {
2043
+ case "all":
2044
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText$2(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
2045
+ case "not": return `NOT,((${[conditionText$2(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
2046
+ case "port":
2047
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
2048
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
2049
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
2050
+ default: return `${{
2051
+ domain: "DOMAIN",
2052
+ domainSuffix: "DOMAIN-SUFFIX",
2053
+ ipCidr: "IP-CIDR",
2054
+ ipCidr6: "IP-CIDR6",
2055
+ ipAsn: "IP-ASN",
2056
+ sourceIp: "SRC-IP",
2057
+ processName: "PROCESS-NAME",
2058
+ macAddress: "MAC-ADDRESS"
2059
+ }[c.type]},${c.value}`;
2060
+ }
2061
+ }
2062
+ function renderProfile(compilation, read) {
2063
+ const p = plans.get(compilation);
2064
+ if (!p) throw new RenderError("COMPILATION_FAILED");
2065
+ const name = (id) => p.names?.[id] ?? id;
2066
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
2067
+ const credential = (token, kind) => {
2068
+ const value = read(token);
2069
+ if (!(kind === "key" ? key.safeParse(value).success : kind === "control" ? /^[A-Za-z0-9_.+%-]+$/.test(value) : /^[A-Za-z0-9_-]+$/.test(value))) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
2070
+ return value;
2071
+ };
2072
+ const lines = [];
2073
+ if (p.managed) {
2074
+ const address = new URL(p.managed.url);
2075
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
2076
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
2077
+ }
2078
+ lines.push("[General]");
2079
+ for (const [k, v] of Object.entries(p.general ?? {})) {
2080
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
2081
+ lines.push(`${k} = ${value}`);
2082
+ }
2083
+ lines.push("", "[Host]");
2084
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
2085
+ lines.push("", "[Proxy]");
2086
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
2087
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
2088
+ for (const t of p.tunnels ?? []) {
2089
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
2090
+ if (t.type === "tailscale") {
2091
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
2092
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2093
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
2094
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
2095
+ } else {
2096
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
2097
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2098
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
2099
+ for (const peer of t.peers) {
2100
+ const values = [`public-key = ${peer.publicKey}`];
2101
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
2102
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
2103
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
2104
+ lines.push(`peer = (${values.join(", ")})`);
2105
+ }
2106
+ }
2107
+ }
2108
+ lines.push("", "[Proxy Group]");
2109
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
2110
+ g.type,
2111
+ ...g.members.map(action),
2112
+ ...g.url ? [`url=${g.url}`] : [],
2113
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
2114
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
2115
+ ].join(", ")}`);
2116
+ lines.push("", "[Rule]");
2117
+ for (const r of p.rules) lines.push([
2118
+ conditionText$2(r.when),
2119
+ action(r.then),
2120
+ ...conditionOptions(r.when)
2121
+ ].join(","));
2122
+ lines.push(`FINAL,${action(p.fallback)}`, "");
2123
+ return deepFreeze({
2124
+ artifactKind: "surge-profile",
2125
+ content: lines.join("\n")
2126
+ });
2127
+ }
2128
+ function renderSurgeProfiles(compilations, resolveSecret) {
2129
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
2130
+ const read = resolveSecret;
2131
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2132
+ }
2133
+ //#endregion
2134
+ //#region src/model/normalize-surge.ts
2135
+ const outbound = {
2136
+ direct: { builtin: "DIRECT" },
2137
+ reject: { builtin: "REJECT" },
2138
+ rejectDrop: { builtin: "REJECT-DROP" },
2139
+ rejectNoDrop: { builtin: "REJECT-NO-DROP" },
2140
+ rejectTinyGif: { builtin: "REJECT-TINYGIF" }
2141
+ };
2142
+ const fail = (code) => {
2143
+ throw new ProfileDefinitionError(code);
2144
+ };
2145
+ function lowerSurgeProfile(input) {
2146
+ inspectDefinition(input);
2147
+ exactDefinition(input, [
2148
+ "target",
2149
+ "managed",
2150
+ "general",
2151
+ "hosts",
2152
+ "nodes",
2153
+ "tunnels",
2154
+ "names",
2155
+ "groups",
2156
+ "routes",
2157
+ "fallback"
2158
+ ]);
2159
+ if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail("DEFINITION_NOT_DATA");
2160
+ const registry = /* @__PURE__ */ new Map();
2161
+ const names = Object.assign(Object.create(null), input.names);
2162
+ for (const resource of [
2163
+ ...input.nodes,
2164
+ ...input.tunnels ?? [],
2165
+ ...input.groups
2166
+ ]) {
2167
+ if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
2168
+ registry.set(resource.id, resource);
2169
+ const name = "name" in resource ? resource.name ?? resource.id : resource.id;
2170
+ if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail("GROUP_NAME_CONFLICT");
2171
+ Object.defineProperty(names, resource.id, {
2172
+ value: names[resource.id] ?? name,
2173
+ enumerable: true,
2174
+ configurable: true,
2175
+ writable: true
2176
+ });
2177
+ }
2178
+ function lower(destination) {
2179
+ if (!destination || typeof destination !== "object") fail("INVALID_DESTINATION");
2180
+ if ("builtin" in destination) {
2181
+ exactDefinition(destination, ["builtin"]);
2182
+ if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail("INVALID_DESTINATION");
2183
+ return { builtin: destination.builtin };
2184
+ }
2185
+ return { ref: destination.id };
2186
+ }
2187
+ const groups = input.groups.map((definition) => {
2188
+ exactDefinition(definition, [
2189
+ "type",
2190
+ "id",
2191
+ "name",
2192
+ "algorithm",
2193
+ "members",
2194
+ "surge"
2195
+ ]);
2196
+ if (definition.type !== "proxy-group") fail("INVALID_GROUP_DEFINITION");
2197
+ if (!definition.algorithm || ![
2198
+ "select",
2199
+ "surge-smart",
2200
+ "auto"
2201
+ ].includes(definition.algorithm.type)) fail("UNSUPPORTED_GROUP_ALGORITHM");
2202
+ exactDefinition(definition.algorithm, ["type"]);
2203
+ if (!Array.isArray(definition.members)) fail("INVALID_GROUP_DEFINITION");
2204
+ const { id } = definition;
2205
+ return {
2206
+ id,
2207
+ type: definition.algorithm.type === "select" ? "select" : "smart",
2208
+ members: definition.members.map(lower),
2209
+ ...definition.surge
2210
+ };
2211
+ });
2212
+ const rules = input.routes.map((definition) => {
2213
+ exactDefinition(definition, [
2214
+ "type",
2215
+ "when",
2216
+ "to"
2217
+ ]);
2218
+ if (definition.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2219
+ return {
2220
+ when: definition.when,
2221
+ then: lower(definition.to)
2222
+ };
2223
+ });
2224
+ const { routes: _routes, groups: _groups, fallback, ...rest } = input;
2225
+ return deepFreeze(snapshotDefinition({
2226
+ ...rest,
2227
+ names,
2228
+ groups,
2229
+ rules,
2230
+ fallback: lower(fallback)
2231
+ }));
2232
+ }
2233
+ function surgeCondition(c, depth = 0) {
2234
+ if (depth > 10) throw new ProfileDefinitionError("LOGICAL_DEPTH_EXCEEDED");
2235
+ if (c.type === "nativeRuleSet") {
2236
+ if (c.engine !== "surge") throw new ProfileDefinitionError("PROFILE_CONDITION_UNSUPPORTED");
2237
+ if (depth && c.intervalSeconds !== void 0) throw new ProfileDefinitionError("RULESET_COMPOSITION_UNSUPPORTED");
2238
+ const { engine: _engine, id: _id, ...fields } = c;
2239
+ return {
2240
+ ...fields,
2241
+ type: "ruleSet"
2242
+ };
2243
+ }
2244
+ if (c.type === "ruleSet") return {
2245
+ type: "ruleSet",
2246
+ format: "rule-set",
2247
+ builtin: c.builtin
2248
+ };
2249
+ if (c.type === "all" || c.type === "any") return {
2250
+ ...c,
2251
+ conditions: c.conditions.map((x) => surgeCondition(x, depth + 1))
2252
+ };
2253
+ if (c.type === "not") return {
2254
+ ...c,
2255
+ condition: surgeCondition(c.condition, depth + 1)
2256
+ };
2257
+ if (c.type === "ipCidr" && isIP(c.value.split("/")[0]) === 6) return {
2258
+ ...c,
2259
+ type: "ipCidr6"
2260
+ };
2261
+ return c;
2262
+ }
2263
+ function normalizeSurgeProfile(p) {
2264
+ const nodes = p.proxies.filter((x) => ![
2265
+ "tailscale",
2266
+ "wireguard",
2267
+ "sing-box-tailscale"
2268
+ ].includes(x.type));
2269
+ const tunnels = p.proxies.filter((x) => ["tailscale", "wireguard"].includes(x.type));
2270
+ if (p.proxies.some((x) => x.type === "sing-box-tailscale")) throw new ProfileDefinitionError("PROFILE_ENDPOINT_UNSUPPORTED");
2271
+ const groups = p.groups;
2272
+ return lowerSurgeProfile({
2273
+ target: p.target,
2274
+ ...p.surge,
2275
+ ...p.dns?.length ? { hosts: [...p.dns, ...p.surge?.hosts ?? []] } : {},
2276
+ nodes: nodes.map((n) => {
2277
+ const { name: _name, ...rest } = n;
2278
+ return {
2279
+ ...rest,
2280
+ ..."via" in rest && rest.via ? { via: rest.via.id } : {}
2281
+ };
2282
+ }),
2283
+ tunnels: tunnels.map((t) => {
2284
+ const { name: _name, ...rest } = t;
2285
+ return rest;
2286
+ }),
2287
+ names: Object.fromEntries([...p.proxies, ...p.groups].map((r) => [r.id, r.name ?? r.id])),
2288
+ groups,
2289
+ routes: p.routes.map((r) => ({
2290
+ ...r,
2291
+ when: surgeCondition(r.when)
2292
+ })),
2293
+ fallback: p.fallback
2294
+ });
2295
+ }
2296
+ //#endregion
2297
+ //#region src/model/semantics.ts
2298
+ const singboxMemberTag = (id) => id === "DIRECT" ? "pl-direct" : id === "REJECT" ? "pl-reject" : id;
2299
+ /** Only top-level atoms (or transparent named wrappers) can request ordered DNS. */
2300
+ function needsResolve(condition) {
2301
+ return condition.type === "ipCidr" && condition.noResolve !== true || condition.type === "nativeRuleSet" && condition.engine === "sing-box" && condition.resolve === true;
2302
+ }
2303
+ //#endregion
2304
+ //#region src/engines/sing-box/groups.ts
2305
+ function singboxGroup(group, name = (id) => id) {
2306
+ if (group.type !== "select" && group.type !== "urltest") throw new Error("GROUP_UNSUPPORTED");
2307
+ return group.type === "select" ? {
2308
+ type: "selector",
2309
+ tag: name(group.id),
2310
+ outbounds: group.members.map(name),
2311
+ default: name(group.members[0]),
2312
+ interrupt_exist_connections: false
2313
+ } : {
2314
+ type: "urltest",
2315
+ tag: name(group.id),
2316
+ outbounds: group.members.map(name),
2317
+ url: group.url,
2318
+ interval: `${group.intervalSeconds ?? 180}s`,
2319
+ tolerance: group.toleranceMs ?? 50,
2320
+ idle_timeout: "30m",
2321
+ interrupt_exist_connections: false
2322
+ };
2323
+ }
2324
+ //#endregion
2325
+ //#region src/engines/sing-box/proxies.ts
2326
+ function singboxProxy(node, secret) {
2327
+ const result = {
2328
+ type: node.type,
2329
+ tag: node.id,
2330
+ server: node.server,
2331
+ server_port: node.port,
2332
+ ...node.via ? { detour: node.via } : {},
2333
+ ...node.tcpFastOpen !== void 0 ? { tcp_fast_open: node.tcpFastOpen } : {}
2334
+ };
2335
+ switch (node.type) {
2336
+ case "hysteria2":
2337
+ result.password = secret(node.password);
2338
+ result.tls = {
2339
+ enabled: true,
2340
+ ...node.serverName ? { server_name: node.serverName } : {},
2341
+ ...node.skipCertVerify !== void 0 ? { insecure: node.skipCertVerify } : {}
2342
+ };
2343
+ if (node.portHopping) {
2344
+ delete result.server_port;
2345
+ result.server_ports = node.portHopping.split(";").map((part) => part.includes("-") ? part.replace("-", ":") : `${part}:${part}`);
2346
+ }
2347
+ if (node.portHoppingInterval !== void 0) result.hop_interval = `${node.portHoppingInterval}s`;
2348
+ break;
2349
+ case "http":
2350
+ result.password = secret(node.password);
2351
+ if (node.username) result.username = secret(node.username);
2352
+ break;
2353
+ case "trojan":
2354
+ case "anytls":
2355
+ result.password = secret(node.password);
2356
+ result.tls = {
2357
+ enabled: true,
2358
+ ...node.serverName ? { server_name: node.serverName } : {},
2359
+ ...node.skipCertVerify !== void 0 ? { insecure: node.skipCertVerify } : {}
2360
+ };
2361
+ break;
2362
+ case "shadowsocks":
2363
+ result.password = secret(node.password);
2364
+ result.method = node.method;
2365
+ break;
2366
+ case "vmess":
2367
+ case "vless":
2368
+ result.uuid = uuid(node.uuid, secret);
2369
+ result.network = "tcp";
2370
+ if (node.type === "vless") {
2371
+ if (node.flow) result.flow = node.flow;
2372
+ if (node.packetEncoding) {
2373
+ result.packet_encoding = node.packetEncoding;
2374
+ delete result.network;
2375
+ }
2376
+ }
2377
+ if (node.type === "vmess") Object.assign(result, {
2378
+ security: "aes-128-gcm",
2379
+ alter_id: 0
2380
+ });
2381
+ if (node.tls) result.tls = {
2382
+ enabled: true,
2383
+ server_name: node.tls.serverName,
2384
+ ...node.tls.alpn ? { alpn: [...node.tls.alpn] } : {},
2385
+ ...node.tls.skipCertVerify !== void 0 ? { insecure: node.tls.skipCertVerify } : {},
2386
+ ...node.type === "vless" && node.utlsFingerprint ? { utls: {
2387
+ enabled: true,
2388
+ fingerprint: node.utlsFingerprint
2389
+ } } : {},
2390
+ ...node.type === "vless" && node.reality ? { reality: {
2391
+ enabled: true,
2392
+ public_key: node.reality.publicKey,
2393
+ short_id: node.reality.shortId
2394
+ } } : {}
2395
+ };
2396
+ if (node.transport) result.transport = {
2397
+ type: "ws",
2398
+ path: node.transport.path,
2399
+ ...node.transport.host ? { headers: { Host: node.transport.host } } : {}
2400
+ };
2401
+ }
2402
+ return result;
2403
+ }
2404
+ //#endregion
2405
+ //#region src/targets/catalog.ts
2406
+ const targetCatalog = deepFreeze([
2407
+ {
2408
+ engine: "sing-box",
2409
+ version: "1.14.4",
2410
+ autoGroup: "urltest",
2411
+ platforms: ["linux", "macos"],
2412
+ protocols: [
2413
+ "hysteria2",
2414
+ "trojan",
2415
+ "http",
2416
+ "anytls",
2417
+ "shadowsocks",
2418
+ "vmess",
2419
+ "vless"
2420
+ ],
2421
+ endpoints: ["sing-box-tailscale"],
2422
+ groups: ["select", "urltest"],
2423
+ nativeRuleSets: ["source", "binary"],
2424
+ dns: "typed"
2425
+ },
2426
+ {
2427
+ engine: "sing-box",
2428
+ version: "1.12.0",
2429
+ autoGroup: "urltest",
2430
+ platforms: ["linux", "macos"],
2431
+ protocols: [
2432
+ "hysteria2",
2433
+ "trojan",
2434
+ "http",
2435
+ "anytls",
2436
+ "shadowsocks",
2437
+ "vmess",
2438
+ "vless"
2439
+ ],
2440
+ endpoints: ["sing-box-tailscale"],
2441
+ groups: ["select", "urltest"],
2442
+ nativeRuleSets: ["source", "binary"],
2443
+ dns: "typed"
2444
+ },
2445
+ {
2446
+ engine: "surge",
2447
+ version: "5.21.0",
2448
+ autoGroup: "surge-smart",
2449
+ platforms: ["ios"],
2450
+ protocols: [
2451
+ "hysteria2",
2452
+ "trojan",
2453
+ "http",
2454
+ "anytls",
2455
+ "shadowsocks",
2456
+ "vmess"
2457
+ ],
2458
+ endpoints: [],
2459
+ groups: ["select", "surge-smart"],
2460
+ nativeRuleSets: ["rule-set", "domain-set"],
2461
+ dns: "general"
2462
+ },
2463
+ {
2464
+ engine: "surge",
2465
+ version: "6.10.0",
2466
+ autoGroup: "surge-smart",
2467
+ platforms: ["macos"],
2468
+ protocols: [
2469
+ "hysteria2",
2470
+ "trojan",
2471
+ "http",
2472
+ "anytls",
2473
+ "shadowsocks",
2474
+ "vmess"
2475
+ ],
2476
+ endpoints: [],
2477
+ groups: ["select", "surge-smart"],
2478
+ nativeRuleSets: ["rule-set", "domain-set"],
2479
+ dns: "general"
2480
+ },
2481
+ {
2482
+ engine: "mihomo",
2483
+ version: "1.19.32",
2484
+ autoGroup: "urltest",
2485
+ platforms: ["linux", "macos"],
2486
+ protocols: [
2487
+ "hysteria2",
2488
+ "trojan",
2489
+ "http",
2490
+ "anytls",
2491
+ "shadowsocks",
2492
+ "vmess",
2493
+ "vless"
2494
+ ],
2495
+ endpoints: [],
2496
+ groups: ["select", "urltest"],
2497
+ nativeRuleSets: ["yaml", "text"],
2498
+ dns: "clash"
2499
+ },
2500
+ {
2501
+ engine: "stash",
2502
+ version: "4.2.1",
2503
+ autoGroup: null,
2504
+ platforms: ["macos"],
2505
+ protocols: [
2506
+ "hysteria2",
2507
+ "trojan",
2508
+ "http",
2509
+ "anytls",
2510
+ "shadowsocks",
2511
+ "vmess"
2512
+ ],
2513
+ endpoints: [],
2514
+ groups: ["select"],
2515
+ nativeRuleSets: [],
2516
+ dns: "external"
2517
+ }
2518
+ ]);
2519
+ //#endregion
2520
+ //#region src/engines/sing-box/render.ts
2521
+ const DIRECT = "pl-direct";
2522
+ const DNS = "pl-dns";
2523
+ const actionTag = (a, name) => a.type === "route" ? name(a.to) : a.type === "direct" ? DIRECT : "pl-reject";
2524
+ function singCondition(condition) {
2525
+ switch (condition.type) {
2526
+ case "nativeRuleSet": return { rule_set: [condition.id] };
2527
+ case "all":
2528
+ case "any": return {
2529
+ type: "logical",
2530
+ mode: condition.type === "all" ? "and" : "or",
2531
+ rules: condition.conditions.map(singCondition)
2532
+ };
2533
+ case "not": return {
2534
+ type: "logical",
2535
+ mode: "and",
2536
+ rules: [singCondition(condition.condition)],
2537
+ invert: true
2538
+ };
2539
+ case "domain": return { domain: [condition.value] };
2540
+ case "domainSuffix": return { domain_suffix: [condition.value] };
2541
+ case "ipCidr": return { ip_cidr: [condition.value] };
2542
+ case "processName": return { process_name: [condition.value] };
2543
+ case "sourceIp": return { source_ip_cidr: [condition.value.includes("/") ? condition.value : `${condition.value}/${isIP(condition.value) === 6 ? 128 : 32}`] };
2544
+ case "network": return { network: [condition.value] };
2545
+ case "port":
2546
+ case "sourcePort": {
2547
+ const key = condition.type === "port" ? "port" : "source_port";
2548
+ return condition.from === condition.to ? { [key]: [condition.from] } : { [`${key}_range`]: [`${condition.from}:${condition.to}`] };
2549
+ }
2550
+ }
2551
+ }
2552
+ function singAction(action, name) {
2553
+ return action.type === "reject" ? {
2554
+ action: "reject",
2555
+ method: "default",
2556
+ no_drop: true
2557
+ } : {
2558
+ action: "route",
2559
+ outbound: actionTag(action, name)
2560
+ };
2561
+ }
2562
+ function singbox(plan, secret) {
2563
+ const model = plan.model, target = model.target;
2564
+ const name = (id) => plan.names?.get(id) ?? id;
2565
+ const modern = targetCatalog.find((entry) => entry.engine === target.engine && entry.version === target.version)?.dns === "typed";
2566
+ const standalone = target.mode === "standalone";
2567
+ const routedDns = target.version === "1.14.4" && standalone && !!model.dns?.length;
2568
+ const domainResolver = routedDns ? "pl-routed-dns" : DNS;
2569
+ const outbounds = [{
2570
+ type: "direct",
2571
+ tag: DIRECT,
2572
+ ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
2573
+ }];
2574
+ if (model.groups.some((group) => group.members.includes("REJECT"))) outbounds.push({
2575
+ type: "block",
2576
+ tag: "pl-reject"
2577
+ });
2578
+ for (const node of model.nodes) outbounds.push({
2579
+ ...singboxProxy(aliasProxyServer(node, model.serverAliases), secret),
2580
+ tag: name(node.id),
2581
+ ...node.via ? { detour: name(node.via) } : {},
2582
+ ...modern && model.dns?.length ? { domain_resolver: {
2583
+ server: domainResolver,
2584
+ strategy: "prefer_ipv4"
2585
+ } } : {}
2586
+ });
2587
+ for (const group of model.groups) outbounds.push(singboxGroup(group, (id) => singboxMemberTag(name(id))));
2588
+ const rules = model.rules.flatMap((rule) => [...target.version === "1.14.4" && needsResolve(rule.when) ? [{
2589
+ ip_cidr: ["0.0.0.0/0", "::/0"],
2590
+ invert: true,
2591
+ action: "resolve"
2592
+ }] : [], {
2593
+ ...singCondition(rule.when),
2594
+ ...singAction(rule.then, name)
2595
+ }]);
2596
+ const routing = { rules };
2597
+ if (model.domainMatching === "prefer-sniffed") rules.unshift({
2598
+ action: "sniff",
2599
+ sniffer: ["http", "tls"]
2600
+ });
2601
+ if (model.tun) {
2602
+ rules.unshift({
2603
+ inbound: ["pl-tun"],
2604
+ port: 53,
2605
+ action: "hijack-dns"
2606
+ });
2607
+ if (model.tun.autoRoute) routing.auto_detect_interface = true;
2608
+ }
2609
+ if (routedDns) rules.unshift({
2610
+ inbound: ["pl-dns-listener"],
2611
+ action: "hijack-dns"
2612
+ });
2613
+ if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
2614
+ type: "remote",
2615
+ tag: r.id,
2616
+ url: r.url,
2617
+ format: r.format,
2618
+ update_interval: `${r.intervalSeconds}s`,
2619
+ download_detour: DIRECT
2620
+ }));
2621
+ if (model.fallback.type === "reject") rules.push(singAction(model.fallback, name));
2622
+ else routing.final = actionTag(model.fallback, name);
2623
+ const config = {
2624
+ log: { level: "warn" },
2625
+ outbounds,
2626
+ route: routing
2627
+ };
2628
+ if (model.cacheFile) config.experimental = { cache_file: { enabled: true } };
2629
+ if (standalone) {
2630
+ const listener = model.listener;
2631
+ config.inbounds = [
2632
+ {
2633
+ type: "mixed",
2634
+ tag: "pl-listener",
2635
+ listen: "127.0.0.1",
2636
+ listen_port: listener.port
2637
+ },
2638
+ ...routedDns ? [{
2639
+ type: "direct",
2640
+ tag: "pl-dns-listener",
2641
+ listen: "127.0.0.1",
2642
+ listen_port: listener.port,
2643
+ network: "udp"
2644
+ }] : [],
2645
+ ...model.tun ? [{
2646
+ type: "tun",
2647
+ tag: "pl-tun",
2648
+ address: [...model.tun.address],
2649
+ stack: model.tun.stack,
2650
+ auto_route: model.tun.autoRoute,
2651
+ strict_route: model.tun.strictRoute,
2652
+ dns_mode: model.tun.dnsMode,
2653
+ ...model.tun.routeExcludeAddress ? { route_exclude_address: [...model.tun.routeExcludeAddress] } : {}
2654
+ }] : []
2655
+ ];
2656
+ config.dns = {
2657
+ servers: [modern ? {
2658
+ type: "udp",
2659
+ tag: DNS,
2660
+ server: listener.resolver,
2661
+ server_port: 53
2662
+ } : {
2663
+ tag: DNS,
2664
+ address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
2665
+ detour: DIRECT
2666
+ }],
2667
+ final: DNS,
2668
+ strategy: "prefer_ipv4",
2669
+ ...model.domainMatching ? { reverse_mapping: true } : {}
2670
+ };
2671
+ if (modern && (!model.dns?.length || target.version === "1.14.4")) routing.default_domain_resolver = {
2672
+ server: domainResolver,
2673
+ strategy: "prefer_ipv4"
2674
+ };
2675
+ }
2676
+ if (model.dns?.length) {
2677
+ const dns = config.dns;
2678
+ if (routedDns) dns.servers.push({
2679
+ type: "udp",
2680
+ tag: "pl-routed-dns",
2681
+ server: "127.0.0.1",
2682
+ server_port: model.listener.port
2683
+ });
2684
+ dns.rules = model.dns.map((rule, index) => {
2685
+ const tag = `pl-domain-dns-${index}`;
2686
+ if (isIP(rule.server)) dns.servers.push(modern ? {
2687
+ type: "udp",
2688
+ tag,
2689
+ server: rule.server,
2690
+ server_port: 53
2691
+ } : {
2692
+ tag,
2693
+ address: `udp://${isIP(rule.server) === 6 ? `[${rule.server}]` : rule.server}`,
2694
+ detour: DIRECT
2695
+ });
2696
+ else {
2697
+ const url = dohUrl(rule.server);
2698
+ dns.servers.push(modern ? {
2699
+ type: "https",
2700
+ tag,
2701
+ server: url.hostname.replace(/^\[|\]$/g, ""),
2702
+ server_port: Number(url.port || 443),
2703
+ path: url.pathname,
2704
+ tls: { enabled: true },
2705
+ domain_resolver: {
2706
+ server: DNS,
2707
+ strategy: "prefer_ipv4"
2708
+ }
2709
+ } : {
2710
+ tag,
2711
+ address: url.href,
2712
+ address_resolver: DNS,
2713
+ detour: DIRECT
2714
+ });
2715
+ }
2716
+ return {
2717
+ ...dnsCondition(rule),
2718
+ server: tag
2719
+ };
2720
+ });
2721
+ }
2722
+ if (model.endpoints?.length) {
2723
+ config.endpoints = model.endpoints.map((endpoint) => ({
2724
+ type: "tailscale",
2725
+ tag: name(endpoint.id),
2726
+ hostname: endpoint.hostname,
2727
+ state_directory: endpoint.stateDirectory,
2728
+ accept_routes: endpoint.acceptRoutes,
2729
+ domain_resolver: { server: `pl-ts-dns-${endpoint.id}` },
2730
+ ...endpoint.authKey ? { auth_key: secret(endpoint.authKey) } : {},
2731
+ ...endpoint.exitNode ? { exit_node: endpoint.exitNode } : {},
2732
+ ...endpoint.exitNodeAllowLanAccess !== void 0 ? { exit_node_allow_lan_access: endpoint.exitNodeAllowLanAccess } : {}
2733
+ }));
2734
+ const dns = config.dns;
2735
+ for (const endpoint of model.endpoints) dns.servers.push({
2736
+ type: "udp",
2737
+ tag: `pl-ts-dns-${endpoint.id}`,
2738
+ server: endpoint.bootstrapResolver,
2739
+ server_port: 53
2740
+ });
2741
+ }
2742
+ return config;
2743
+ }
2744
+ //#endregion
2745
+ //#region src/engines/mihomo/proxies.ts
2746
+ function clashProxy$1(node, secret, name = (id) => id) {
2747
+ const result = {
2748
+ name: name(node.id),
2749
+ type: node.type === "shadowsocks" ? "ss" : node.type,
2750
+ server: node.server,
2751
+ port: node.port,
2752
+ ...node.via ? { "dialer-proxy": name(node.via) } : {}
2753
+ };
2754
+ switch (node.type) {
2755
+ case "hysteria2":
2756
+ result.password = secret(node.password);
2757
+ if (node.serverName) result.sni = node.serverName;
2758
+ if (node.skipCertVerify !== void 0) result["skip-cert-verify"] = node.skipCertVerify;
2759
+ if (node.portHopping) result.ports = node.portHopping.replaceAll(";", ",");
2760
+ if (node.portHoppingInterval !== void 0) result["hop-interval"] = node.portHoppingInterval;
2761
+ break;
2762
+ case "http":
2763
+ result.password = secret(node.password);
2764
+ if (node.username) result.username = secret(node.username);
2765
+ break;
2766
+ case "trojan":
2767
+ case "anytls":
2768
+ result.password = secret(node.password);
2769
+ if (node.serverName) result.sni = node.serverName;
2770
+ if (node.type === "trojan") result.udp = true;
2771
+ break;
2772
+ case "shadowsocks":
2773
+ result.password = secret(node.password);
2774
+ result.cipher = node.method;
2775
+ result.udp = true;
2776
+ break;
2777
+ case "vmess":
2778
+ case "vless":
2779
+ result.uuid = uuid(node.uuid, secret);
2780
+ result.udp = false;
2781
+ if (node.type === "vmess") Object.assign(result, {
2782
+ cipher: "aes-128-gcm",
2783
+ alterId: 0
2784
+ });
2785
+ result.tls = !!node.tls;
2786
+ if (node.tls) {
2787
+ result.servername = node.tls.serverName;
2788
+ if (node.tls.alpn) result.alpn = [...node.tls.alpn];
2789
+ }
2790
+ if (node.transport) {
2791
+ result.network = "ws";
2792
+ result["ws-opts"] = {
2793
+ path: node.transport.path,
2794
+ ...node.transport.host ? { headers: { Host: node.transport.host } } : {}
2795
+ };
2796
+ }
2797
+ }
2798
+ return result;
2799
+ }
2800
+ //#endregion
2801
+ //#region src/engines/mihomo/render.ts
2802
+ function clashGroup$1(group, name = (id) => id) {
2803
+ if (group.type !== "select" && group.type !== "urltest") throw new Error("GROUP_UNSUPPORTED");
2804
+ return {
2805
+ name: name(group.id),
2806
+ type: group.type === "select" ? "select" : "url-test",
2807
+ proxies: group.members.map(name),
2808
+ ...group.type === "urltest" ? {
2809
+ url: group.url,
2810
+ interval: group.intervalSeconds ?? 180,
2811
+ tolerance: group.toleranceMs ?? 50
2812
+ } : {}
2813
+ };
2814
+ }
2815
+ function conditionText$1(condition) {
2816
+ switch (condition.type) {
2817
+ case "nativeRuleSet": return `RULE-SET,${condition.id}`;
2818
+ case "all":
2819
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText$1(c)})`).join(",")})`;
2820
+ case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
2821
+ case "domain": return `DOMAIN,${condition.value}`;
2822
+ case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
2823
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}${condition.noResolve !== false ? ",no-resolve" : ""}`;
2824
+ case "processName": return `PROCESS-NAME,${condition.value}`;
2825
+ case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
2826
+ case "network": return `NETWORK,${condition.value}`;
2827
+ case "port":
2828
+ case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
2829
+ }
2830
+ }
2831
+ const policy$1 = (action, name) => action.type === "route" ? name(action.to) : action.type === "direct" ? "DIRECT" : "REJECT";
2832
+ function clashConfig$1(plan, secret) {
2833
+ const model = plan.model, target = model.target;
2834
+ const name = (id) => plan.names?.get(id) ?? id;
2835
+ const config = {
2836
+ proxies: model.nodes.map((node) => clashProxy$1(node, secret, name)),
2837
+ "proxy-groups": model.groups.map((g) => clashGroup$1(g, name)),
2838
+ rules: [...model.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$1(rule.then, name)}${rule.when.noResolve !== false ? ",no-resolve" : ""}` : `${conditionText$1(rule.when)},${policy$1(rule.then, name)}`), `MATCH,${policy$1(model.fallback, name)}`]
2839
+ };
2840
+ if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
2841
+ type: "http",
2842
+ url: r.url,
2843
+ path: `rule-providers/pl-${r.id}.${r.format === "yaml" ? "yaml" : "txt"}`,
2844
+ interval: r.intervalSeconds,
2845
+ behavior: "behavior" in r ? r.behavior : "classical",
2846
+ format: r.format,
2847
+ proxy: "DIRECT"
2848
+ }]));
2849
+ if (target.mode === "standalone") {
2850
+ const listener = model.listener;
2851
+ Object.assign(config, {
2852
+ "mixed-port": listener.port,
2853
+ "allow-lan": false,
2854
+ "bind-address": "127.0.0.1",
2855
+ mode: "rule",
2856
+ ipv6: false,
2857
+ "geo-auto-update": false,
2858
+ sniffer: { enable: false },
2859
+ dns: {
2860
+ enable: true,
2861
+ ipv6: false,
2862
+ "enhanced-mode": "redir-host",
2863
+ nameserver: [listener.resolver],
2864
+ "default-nameserver": [listener.resolver],
2865
+ "respect-rules": false,
2866
+ "use-hosts": false,
2867
+ "use-system-hosts": false
2868
+ }
2869
+ });
2870
+ }
2871
+ return config;
2872
+ }
2873
+ //#endregion
2874
+ //#region src/engines/stash/proxies.ts
2875
+ function clashProxy(node, secret, name = (id) => id) {
2876
+ const result = {
2877
+ name: name(node.id),
2878
+ type: node.type === "shadowsocks" ? "ss" : node.type,
2879
+ server: node.server,
2880
+ port: node.port,
2881
+ ...node.via ? { "dialer-proxy": name(node.via) } : {},
2882
+ "block-quic": "off"
2883
+ };
2884
+ switch (node.type) {
2885
+ case "hysteria2":
2886
+ result.auth = secret(node.password);
2887
+ if (node.serverName) result.sni = node.serverName;
2888
+ if (node.skipCertVerify !== void 0) result["skip-cert-verify"] = node.skipCertVerify;
2889
+ if (node.portHopping) result.ports = node.portHopping.replaceAll(";", ",");
2890
+ if (node.portHoppingInterval !== void 0) result["hop-interval"] = node.portHoppingInterval;
2891
+ break;
2892
+ case "http":
2893
+ result.password = secret(node.password);
2894
+ if (node.username) result.username = secret(node.username);
2895
+ break;
2896
+ case "trojan":
2897
+ case "anytls":
2898
+ result.password = secret(node.password);
2899
+ if (node.serverName) result.sni = node.serverName;
2900
+ if (node.type === "trojan") result.udp = true;
2901
+ break;
2902
+ case "shadowsocks":
2903
+ result.password = secret(node.password);
2904
+ result.cipher = node.method;
2905
+ result.udp = true;
2906
+ break;
2907
+ case "vmess":
2908
+ case "vless":
2909
+ result.uuid = uuid(node.uuid, secret);
2910
+ result.udp = false;
2911
+ if (node.type === "vmess") Object.assign(result, {
2912
+ cipher: "aes-128-gcm",
2913
+ alterId: 0
2914
+ });
2915
+ result.tls = !!node.tls;
2916
+ if (node.tls) {
2917
+ result.sni = node.tls.serverName;
2918
+ if (node.tls.alpn) result.alpn = [...node.tls.alpn];
2919
+ }
2920
+ if (node.transport) {
2921
+ result.network = "ws";
2922
+ result["ws-opts"] = {
2923
+ path: node.transport.path,
2924
+ ...node.transport.host ? { headers: { Host: node.transport.host } } : {}
2925
+ };
2926
+ }
2927
+ }
2928
+ return result;
2929
+ }
2930
+ //#endregion
2931
+ //#region src/engines/stash/render.ts
2932
+ function clashGroup(group, name = (id) => id) {
2933
+ if (group.type !== "select" && group.type !== "urltest") throw new Error("GROUP_UNSUPPORTED");
2934
+ return {
2935
+ name: name(group.id),
2936
+ type: group.type === "select" ? "select" : "url-test",
2937
+ proxies: group.members.map(name),
2938
+ ...group.type === "urltest" ? {
2939
+ url: group.url,
2940
+ interval: group.intervalSeconds ?? 180,
2941
+ tolerance: group.toleranceMs ?? 50
2942
+ } : {}
2943
+ };
2944
+ }
2945
+ function conditionText(condition) {
2946
+ switch (condition.type) {
2947
+ case "nativeRuleSet": return `RULE-SET,${condition.id}`;
2948
+ case "all":
2949
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText(c)})`).join(",")})`;
2950
+ case "not": return `NOT,((${conditionText(condition.condition)}))`;
2951
+ case "domain": return `DOMAIN,${condition.value}`;
2952
+ case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
2953
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}${condition.noResolve !== false ? ",no-resolve" : ""}`;
2954
+ case "processName": return `PROCESS-NAME,${condition.value}`;
2955
+ case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
2956
+ case "network": return `NETWORK,${condition.value}`;
2957
+ case "port":
2958
+ case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
2959
+ }
2960
+ }
2961
+ const policy = (action, name) => action.type === "route" ? name(action.to) : action.type === "direct" ? "DIRECT" : "REJECT";
2962
+ function clashConfig(plan, secret) {
2963
+ const model = plan.model, target = model.target;
2964
+ const name = (id) => plan.names?.get(id) ?? id;
2965
+ const config = {
2966
+ proxies: model.nodes.map((node) => clashProxy(node, secret, name)),
2967
+ "proxy-groups": model.groups.map((g) => clashGroup(g, name)),
2968
+ rules: [...model.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText(rule.when).replace(/,no-resolve$/, "")},${policy(rule.then, name)}${rule.when.noResolve !== false ? ",no-resolve" : ""}` : `${conditionText(rule.when)},${policy(rule.then, name)}`), `MATCH,${policy(model.fallback, name)}`]
2969
+ };
2970
+ if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
2971
+ type: "http",
2972
+ url: r.url,
2973
+ path: `rule-providers/pl-${r.id}.${r.format === "yaml" ? "yaml" : "txt"}`,
2974
+ interval: r.intervalSeconds,
2975
+ behavior: "behavior" in r ? r.behavior : "classical",
2976
+ format: r.format,
2977
+ proxy: "DIRECT"
2978
+ }]));
2979
+ if (target.mode === "standalone") {
2980
+ const listener = model.listener;
2981
+ Object.assign(config, {
2982
+ "mixed-port": listener.port,
2983
+ "allow-lan": false,
2984
+ "bind-address": "127.0.0.1",
2985
+ mode: "rule",
2986
+ ipv6: false,
2987
+ "geo-auto-update": false,
2988
+ sniffer: { enable: false },
2989
+ dns: {
2990
+ enable: true,
2991
+ ipv6: false,
2992
+ "enhanced-mode": "redir-host",
2993
+ nameserver: [listener.resolver],
2994
+ "default-nameserver": [listener.resolver],
2995
+ "respect-rules": false,
2996
+ "use-hosts": false,
2997
+ "use-system-hosts": false
2998
+ }
2999
+ });
3000
+ }
3001
+ return config;
3002
+ }
3003
+ //#endregion
3004
+ //#region src/engines/sing-box/check.ts
3005
+ function engineChecks$2(model) {
3006
+ const t = model.target;
3007
+ const modern = model.target.version === "1.14.4";
3008
+ return {
3009
+ node(node, error) {
3010
+ if (!isIP(node.server) && !modern) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `proxies.${node.id}.server`);
3011
+ },
3012
+ group(group, error) {
3013
+ if (group.members.some((x) => ["DIRECT", "REJECT"].includes(x)) && (!modern || group.type !== "select")) error("GROUP_BUILTIN_UNSUPPORTED", `groups.${group.id}`);
3014
+ },
3015
+ profile(error) {
3016
+ if (model.dns?.length && t.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", "dns");
3017
+ if (!modern && (model.domainMatching !== void 0 || model.serverAliases !== void 0 || model.cacheFile !== void 0 || model.unsupportedUdp !== void 0)) error("PROGRAM_OPTION_UNSUPPORTED", "singBox");
3018
+ if (model.cacheFile !== void 0 && t.mode !== "standalone") error("PROGRAM_OPTION_UNSUPPORTED", "singBox.cacheFile");
3019
+ if (model.tun) {
3020
+ if (!modern || t.mode !== "standalone") error("TUN_TARGET_UNSUPPORTED", "singBox.tun");
3021
+ if (unsafeTunResolvers(model).length) error("TUN_DNS_LOOP", "singBox.tun");
3022
+ }
3023
+ },
3024
+ match(m, path, nested, error) {
3025
+ if ("includeSniffed" in m && m.includeSniffed && !(modern && model.domainMatching === "prefer-sniffed")) error("MATCH_OPTION_UNSUPPORTED", path);
3026
+ if (m.type === "ipCidr" && t.engine === "sing-box") {
3027
+ if (!modern && m.noResolve !== void 0) error("MATCH_OPTION_UNSUPPORTED", path);
3028
+ if (modern && nested && m.noResolve !== true) error("RESOLVE_NESTED", path);
3029
+ }
3030
+ if (m.type === "nativeRuleSet") {
3031
+ if (m.engine === "sing-box" && m.resolve !== void 0 && !modern) error("MATCH_OPTION_UNSUPPORTED", path);
3032
+ if (m.engine === "sing-box" && m.resolve && nested) error("RESOLVE_NESTED", path);
3033
+ }
3034
+ }
3035
+ };
3036
+ }
3037
+ //#endregion
3038
+ //#region src/engines/mihomo/check.ts
3039
+ function engineChecks$1(model) {
3040
+ const t = model.target;
3041
+ return {
3042
+ node(node, error) {
3043
+ if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `proxies.${node.id}.server`);
3044
+ },
3045
+ group(group, error) {
3046
+ if (group.members.some((x) => ["DIRECT", "REJECT"].includes(x))) error("GROUP_BUILTIN_UNSUPPORTED", `groups.${group.id}`);
3047
+ },
3048
+ profile(error) {
3049
+ if (model.dns?.length) error("DNS_MODE_UNSUPPORTED", "dns");
3050
+ if (model.domainMatching !== void 0 || model.serverAliases !== void 0 || model.cacheFile !== void 0 || model.unsupportedUdp !== void 0) error("PROGRAM_OPTION_UNSUPPORTED", "singBox");
3051
+ if (model.cacheFile !== void 0 && t.mode !== "standalone") error("PROGRAM_OPTION_UNSUPPORTED", "singBox.cacheFile");
3052
+ if (model.tun) error("TUN_TARGET_UNSUPPORTED", "singBox.tun");
3053
+ },
3054
+ match(m, path, _nested, error) {
3055
+ if ("includeSniffed" in m && m.includeSniffed) error("MATCH_OPTION_UNSUPPORTED", path);
3056
+ }
3057
+ };
3058
+ }
3059
+ //#endregion
3060
+ //#region src/engines/stash/check.ts
3061
+ function engineChecks(model) {
3062
+ const t = model.target;
3063
+ return {
3064
+ node(node, error) {
3065
+ if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `proxies.${node.id}.server`);
3066
+ },
3067
+ group(group, error) {
3068
+ if (group.members.some((x) => ["DIRECT", "REJECT"].includes(x))) error("GROUP_BUILTIN_UNSUPPORTED", `groups.${group.id}`);
3069
+ },
3070
+ profile(error) {
3071
+ if (t.mode !== "fragment") error("MODE_UNSUPPORTED", "mode");
3072
+ if (model.dns?.length) error("DNS_MODE_UNSUPPORTED", "dns");
3073
+ if (model.domainMatching !== void 0 || model.serverAliases !== void 0 || model.cacheFile !== void 0 || model.unsupportedUdp !== void 0) error("PROGRAM_OPTION_UNSUPPORTED", "singBox");
3074
+ if (model.cacheFile !== void 0 && t.mode !== "standalone") error("PROGRAM_OPTION_UNSUPPORTED", "singBox.cacheFile");
3075
+ if (model.tun) error("TUN_TARGET_UNSUPPORTED", "singBox.tun");
3076
+ },
3077
+ match(m, path, _nested, error) {
3078
+ if (m.type === "sourceIp" || m.type === "sourcePort" || m.type === "port" && m.from !== m.to) error("MATCH_UNSUPPORTED", path);
3079
+ if ("includeSniffed" in m && m.includeSniffed) error("MATCH_OPTION_UNSUPPORTED", path);
3080
+ }
3081
+ };
3082
+ }
3083
+ //#endregion
3084
+ //#region src/model/paths.ts
3085
+ function pathsOverlap(a, b) {
3086
+ return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
3087
+ }
3088
+ //#endregion
3089
+ //#region src/targets/check.ts
3090
+ function checkTarget(model, checks) {
3091
+ const diagnostics = [];
3092
+ const error = (code, path) => diagnostics.push({
3093
+ severity: "error",
3094
+ code,
3095
+ path,
3096
+ message: code,
3097
+ target: "profile"
3098
+ });
3099
+ const t = model.target;
3100
+ const descriptor = targetCatalog.find((d) => d.engine === t.engine && d.version === t.version && d.platforms.includes(t.platform));
3101
+ if (!descriptor) error("UNKNOWN_TARGET", "target");
3102
+ const resources = [
3103
+ ...model.nodes,
3104
+ ...model.groups,
3105
+ ...model.endpoints
3106
+ ];
3107
+ const registry = new Map(resources.map((r) => [r.id, r]));
3108
+ const edges = new Map(resources.map((r) => [r.id, "members" in r ? r.members : "via" in r && r.via ? [r.via] : []]));
3109
+ if (resources.length > 1e3) error("RESOURCE_LIMIT", "proxies");
3110
+ for (const [id, refs] of edges) for (const [index, ref] of refs.entries()) {
3111
+ const path = registry.get(id)?.type === "select" || registry.get(id)?.type === "urltest" ? `groups.${id}.members[${index}]` : `proxies.${id}.via`;
3112
+ if (!registry.has(ref) && !["DIRECT", "REJECT"].includes(ref)) error("MISSING_REFERENCE", path);
3113
+ if (registry.get(ref)?.type === "sing-box-tailscale") error("ENDPOINT_REFERENCE_UNSUPPORTED", path);
3114
+ }
3115
+ const state = /* @__PURE__ */ new Map(), tcp = /* @__PURE__ */ new Map();
3116
+ const visit = (id) => {
3117
+ if (state.get(id) === 1) {
3118
+ error("RESOURCE_CYCLE", `${model.groups.some((g) => g.id === id) ? "groups" : "proxies"}.${id}`);
3119
+ return true;
3120
+ }
3121
+ if (state.get(id) === 2) return tcp.get(id) ?? false;
3122
+ state.set(id, 1);
3123
+ const item = registry.get(id);
3124
+ let limited = !!item && "server" in item && nodeIsTcpOnly(item, t.engine, t.version);
3125
+ for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
3126
+ state.set(id, 2);
3127
+ tcp.set(id, limited);
3128
+ return limited;
3129
+ };
3130
+ if (resources.length <= 1e3) for (const id of registry.keys()) visit(id);
3131
+ const action = (a, path, udp) => {
3132
+ if (a.type === "route") {
3133
+ if (!registry.has(a.to)) error("MISSING_REFERENCE", path);
3134
+ else if (udp && tcp.get(a.to) && model.unsupportedUdp !== "reject") error("NETWORK_UNSUPPORTED", path);
3135
+ }
3136
+ };
3137
+ model.rules.forEach((r, i) => action(r.then, `routes[${i}].to`, truthPossibilities(r.when, "udp").includes(true)));
3138
+ action(model.fallback, "fallback", true);
3139
+ for (const node of model.nodes) {
3140
+ validateProxyOptions(node, t, diagnostics);
3141
+ if (!descriptor?.protocols.includes(node.type)) error("PROTOCOL_UNSUPPORTED", `proxies.${node.id}`);
3142
+ checks.node(node, error);
3143
+ }
3144
+ for (const group of model.groups) {
3145
+ if (!descriptor?.groups.includes(group.type)) error("GROUP_UNSUPPORTED", `groups.${group.id}`);
3146
+ checks.group(group, error);
3147
+ }
3148
+ if (t.mode === "standalone" && !model.listener) error("LISTENER_REQUIRED", "listener");
3149
+ if (t.mode === "fragment" && model.listener) error("UNUSED_LISTENER", "listener");
3150
+ if (model.listener && (!Number.isInteger(model.listener.port) || model.listener.port < 1 || model.listener.port > 65535 || !isIP(model.listener.resolver))) error("INVALID_SCHEMA", "listener");
3151
+ checks.profile(error);
3152
+ for (const [i, ep] of model.endpoints.entries()) {
3153
+ if (!descriptor?.endpoints.includes(ep.type)) error("ENDPOINT_UNSUPPORTED", `proxies.${ep.id}`);
3154
+ if (t.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `proxies.${ep.id}`);
3155
+ if (model.endpoints.slice(0, i).some((x) => pathsOverlap(ep.stateDirectory, x.stateDirectory))) error("ENDPOINT_STATE_OVERLAP", `proxies.${ep.id}`);
3156
+ }
3157
+ const sets = /* @__PURE__ */ new Map();
3158
+ const inspect = (m, path, nested = false) => {
3159
+ if (m.type === "all" || m.type === "any") {
3160
+ m.conditions.forEach((x, i) => inspect(x, `${path}.conditions[${i}]`, true));
3161
+ return;
3162
+ }
3163
+ if (m.type === "not") {
3164
+ inspect(m.condition, path + ".condition", true);
3165
+ return;
3166
+ }
3167
+ checks.match(m, path, nested, error);
3168
+ if (m.type === "nativeRuleSet") {
3169
+ if (m.engine !== t.engine) error("NATIVE_TARGET_MISMATCH", path);
3170
+ if (!descriptor?.nativeRuleSets.includes(m.format)) error("RULESET_UNSUPPORTED", path);
3171
+ if (!sets.get(m.id)) sets.set(m.id, m);
3172
+ }
3173
+ };
3174
+ model.rules.forEach((r, i) => inspect(r.when, `routes[${i}].when`));
3175
+ for (const set of sets.values()) diagnostics.push({
3176
+ severity: "warning",
3177
+ code: "EXTERNAL_RULESET_UNVERIFIED",
3178
+ path: `ruleSets.${set.id}`,
3179
+ message: "External content is owned by the client",
3180
+ target: "profile"
3181
+ });
3182
+ return {
3183
+ ok: !diagnostics.some((d) => d.severity === "error"),
3184
+ diagnostics,
3185
+ plan: {
3186
+ model,
3187
+ nativeRuleSets: [...sets.values()]
3188
+ }
3189
+ };
3190
+ }
3191
+ //#endregion
3192
+ //#region src/build/plans.ts
3193
+ function prepareProfile(input, key, secrets, checkSecrets = true) {
3194
+ let engine = "surge";
3195
+ const collected = [];
3196
+ let selections = [];
3197
+ let ruleSets;
3198
+ try {
3199
+ const p = defineProfile(input);
3200
+ engine = p.target.engine;
3201
+ snapshotDefinition(p.routes.map((r) => r.when));
3202
+ const inspected = inspectProfile(p, key, secrets, checkSecrets);
3203
+ selections = inspected.selections;
3204
+ const routing = normalizeRouting(p, inspected);
3205
+ ruleSets = routing.ruleSets;
3206
+ collected.push(...inspected.diagnostics);
3207
+ const invalid = collected.some((d) => d.severity === "error");
3208
+ const view = invalid ? diagnosticView(p, inspected) : {
3209
+ ...p,
3210
+ routes: inspected.rules
3211
+ };
3212
+ const project = (d) => ({
3213
+ ...d,
3214
+ code: diagnosticCode(d.code),
3215
+ profile: key,
3216
+ origin: d.origin ?? diagnosticOrigin(p, d.path)
3217
+ });
3218
+ if (!targetCatalog.find((d) => d.engine === engine && d.version === p.target.version && d.platforms.includes(p.target.platform))) return {
3219
+ engine,
3220
+ selections,
3221
+ ruleSets,
3222
+ ok: false,
3223
+ diagnostics: [...collected, {
3224
+ severity: "error",
3225
+ code: "TARGET_UNSUPPORTED",
3226
+ profile: key,
3227
+ origin: originOf(p),
3228
+ path: "target",
3229
+ message: "Unsupported exact target"
3230
+ }]
3231
+ };
3232
+ const allDiagnostics = (ds) => {
3233
+ const seen = /* @__PURE__ */ new Set();
3234
+ return [...collected, ...ds.map(project)].filter((d) => {
3235
+ const key = JSON.stringify([d.code, d.path]);
3236
+ if (seen.has(key)) return false;
3237
+ seen.add(key);
3238
+ return true;
3239
+ });
3240
+ };
3241
+ if (p.surge && engine !== "surge" || p.singBox && engine !== "sing-box" || p.mihomo && engine !== "mihomo") throw new ProfileDefinitionError("PROFILE_EXTENSION_UNSUPPORTED");
3242
+ if (engine === "surge") {
3243
+ const native = compileSurgeProfile(normalizeSurgeProfile(view));
3244
+ return {
3245
+ engine,
3246
+ selections,
3247
+ ruleSets,
3248
+ ok: native.ok && !collected.some((d) => d.severity === "error"),
3249
+ diagnostics: allDiagnostics(native.diagnostics),
3250
+ ...!invalid && native.ok ? {
3251
+ native,
3252
+ routing
3253
+ } : {}
3254
+ };
3255
+ }
3256
+ const model = normalizeProfile(view);
3257
+ const result = checkTarget(model, (engine === "sing-box" ? engineChecks$2 : engine === "mihomo" ? engineChecks$1 : engineChecks)(model));
3258
+ return {
3259
+ engine,
3260
+ selections,
3261
+ ruleSets,
3262
+ ok: result.ok && !collected.some((d) => d.severity === "error"),
3263
+ diagnostics: allDiagnostics(result.diagnostics),
3264
+ ...!invalid && result.ok ? {
3265
+ plan: {
3266
+ ...result.plan,
3267
+ names: inspected.names
3268
+ },
3269
+ routing
3270
+ } : {}
3271
+ };
3272
+ } catch (e) {
3273
+ return {
3274
+ engine,
3275
+ selections,
3276
+ ruleSets,
3277
+ ok: false,
3278
+ code: e instanceof ProfileDefinitionError ? e.code : "INVALID_PROFILE_DEFINITION",
3279
+ paths: e instanceof ProfileDefinitionError ? e.paths : void 0,
3280
+ diagnostics: [...collected, {
3281
+ severity: "error",
3282
+ code: diagnosticCode(e instanceof ProfileDefinitionError ? e.code : "INVALID_FIELD"),
3283
+ profile: key,
3284
+ path: e instanceof ProfileDefinitionError ? e.paths?.[0] ?? "$" : "$",
3285
+ message: "Profile validation failed",
3286
+ origin: originOf(input)
3287
+ }]
3288
+ };
3289
+ }
3290
+ }
3291
+ function renderPrepared(prepared, read) {
3292
+ if (!prepared.ok) throw new Error("INVALID_PLAN");
3293
+ if (prepared.native) return renderSurgeProfiles([prepared.native], read)[0].content;
3294
+ const plan = prepared.plan;
3295
+ return prepared.engine === "sing-box" ? JSON.stringify(singbox(plan, read), null, 2) + "\n" : stringify(prepared.engine === "mihomo" ? clashConfig$1(plan, read) : clashConfig(plan, read));
3296
+ }
3297
+ function diagnosticCode(code) {
3298
+ return {
3299
+ UNKNOWN_TARGET: "TARGET_UNSUPPORTED",
3300
+ INVALID_NATIVE_NAME: "NAME_UNSAFE",
3301
+ MISSING_REFERENCE: "UNLISTED_EXIT",
3302
+ RESOURCE_CYCLE: "GROUP_CYCLE",
3303
+ GROUP_CYCLE: "GROUP_CYCLE",
3304
+ DUPLICATE_RESOURCE: "DUPLICATE_ID",
3305
+ DUPLICATE_RESOURCE_ID: "DUPLICATE_ID",
3306
+ NETWORK_UNSUPPORTED: "TCP_ONLY_EXIT",
3307
+ GROUP_UNSUPPORTED: "GROUP_ALGORITHM_UNSUPPORTED",
3308
+ UNSUPPORTED_GROUP_ALGORITHM: "GROUP_ALGORITHM_UNSUPPORTED",
3309
+ GROUP_BUILTIN_UNSUPPORTED: "MEMBER_TYPE_UNSUPPORTED",
3310
+ ENDPOINT_REFERENCE_UNSUPPORTED: "MEMBER_TYPE_UNSUPPORTED",
3311
+ PROFILE_GROUP_MEMBER_UNSUPPORTED: "MEMBER_TYPE_UNSUPPORTED",
3312
+ SMART_MEMBER_UNSUPPORTED: "MEMBER_TYPE_UNSUPPORTED",
3313
+ PLATFORM_RULE_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3314
+ RULE_OPTION_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3315
+ RULESET_COMPOSITION_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3316
+ MATCH_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3317
+ MATCH_OPTION_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3318
+ PLATFORM_CONDITION_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3319
+ PROFILE_CONDITION_UNSUPPORTED: "CONDITION_UNSUPPORTED",
3320
+ DNS_MODE_UNSUPPORTED: "DNS_UNSUPPORTED",
3321
+ PROFILE_ENDPOINT_UNSUPPORTED: "TUNNEL_UNSUPPORTED",
3322
+ ENDPOINT_UNSUPPORTED: "TUNNEL_UNSUPPORTED",
3323
+ MODE_UNSUPPORTED: "TARGET_UNSUPPORTED"
3324
+ }[code] ?? code;
3325
+ }
3326
+ function diagnosticOrigin(p, path) {
3327
+ const route = /^routes\[(\d+)\]/.exec(path);
3328
+ if (route) return originOf(p.routes[Number(route[1])]) ?? originOf(p);
3329
+ const resource = /^(?:proxies|groups)\.([a-z0-9_-]+)/.exec(path);
3330
+ if (resource) return originOf([...p.proxies, ...p.groups].find((r) => r.id === resource[1])) ?? originOf(p);
3331
+ return originOf(p);
3332
+ }
3333
+ //#endregion
3334
+ //#region src/build/secrets.ts
3335
+ const failures = /* @__PURE__ */ new WeakMap();
3336
+ function secretFailure(error) {
3337
+ return error && typeof error === "object" ? failures.get(error) ?? {} : {};
3338
+ }
3339
+ function secretReader(secrets, validation) {
3340
+ const values = /* @__PURE__ */ new Map();
3341
+ return (token) => {
3342
+ if (values.has(token)) return values.get(token);
3343
+ const source = sourceFor(secrets, token);
3344
+ let code;
3345
+ let value;
3346
+ if (!source) code = "SECRET_UNDECLARED";
3347
+ else if (validation) {
3348
+ if (source.validation === void 0) code = "SECRET_VALIDATION_MISSING";
3349
+ else value = source.validation;
3350
+ } else value = source.value ?? (source.env === void 0 ? void 0 : process.env[source.env]);
3351
+ if (!code && (typeof value !== "string" || !value.length)) code = "SECRET_MISSING";
3352
+ if (code) {
3353
+ const error = new RenderError(code);
3354
+ failures.set(error, { secretName: token.name });
3355
+ throw error;
3356
+ }
3357
+ values.set(token, value);
3358
+ return value;
3359
+ };
3360
+ }
3361
+ //#endregion
3362
+ //#region src/build/publish.ts
3363
+ var SurgePublishError = class extends Error {
3364
+ published;
3365
+ constructor(message, published) {
3366
+ super(message);
3367
+ this.published = published;
3368
+ }
3369
+ };
3370
+ async function publishProfiles(files, surgeDirectory, io = { rename }) {
3371
+ if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.(?:conf|json|yaml)$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
3372
+ const root = resolve(surgeDirectory);
3373
+ const generations = join(root, ".generations");
3374
+ const id = randomUUID();
3375
+ const generation = join(generations, id);
3376
+ const pointer = join(root, `.out-${id}`);
3377
+ const output = join(root, "out");
3378
+ const backup = join(generations, `legacy-${id}`);
3379
+ const lock = join(root, ".build-lock");
3380
+ const remove = io.rm ?? rm;
3381
+ let failure;
3382
+ let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
3383
+ async function directory(path) {
3384
+ await mkdir(path, {
3385
+ recursive: true,
3386
+ mode: 448
3387
+ });
3388
+ const stat = await lstat(path);
3389
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3390
+ }
3391
+ try {
3392
+ await directory(root);
3393
+ try {
3394
+ await mkdir(lock, { mode: 448 });
3395
+ locked = true;
3396
+ } catch (error) {
3397
+ if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
3398
+ throw error;
3399
+ }
3400
+ await directory(generations);
3401
+ let previous;
3402
+ try {
3403
+ previous = await lstat(output);
3404
+ } catch (error) {
3405
+ if (error.code !== "ENOENT") throw error;
3406
+ }
3407
+ if (previous?.isSymbolicLink()) {
3408
+ const target = await readlink(output);
3409
+ if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
3410
+ const stat = await lstat(join(root, target));
3411
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3412
+ } else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3413
+ await mkdir(generation, { mode: 448 });
3414
+ created = true;
3415
+ for (const [name, content] of files) await writeFile(join(generation, name), content, {
3416
+ mode: 384,
3417
+ flag: "wx"
3418
+ });
3419
+ await symlink(`.generations/${id}`, pointer, "dir");
3420
+ if (previous?.isDirectory()) {
3421
+ await io.rename(output, backup);
3422
+ movedLegacy = true;
3423
+ }
3424
+ try {
3425
+ await io.rename(pointer, output);
3426
+ committed = true;
3427
+ } catch (error) {
3428
+ if (movedLegacy) try {
3429
+ await io.rename(backup, output);
3430
+ movedLegacy = false;
3431
+ } catch {
3432
+ recoveryFailed = true;
3433
+ throw new Error("PUBLISH_RECOVERY_REQUIRED");
3434
+ }
3435
+ throw error;
3436
+ }
3437
+ } catch (error) {
3438
+ const code = error instanceof Error && /^(?:INVALID_PROFILE_FILENAMES|OUTPUT_LOCKED|UNMANAGED_OUTPUT_LINK|UNSAFE_OUTPUT_DIRECTORY|PUBLISH_RECOVERY_REQUIRED)$/.test(error.message) ? error.message : "PROFILE_PUBLISH_FAILED";
3439
+ failure = new Error(code);
3440
+ } finally {
3441
+ if (!recoveryFailed) try {
3442
+ await remove(pointer, { force: true });
3443
+ if (created && !committed) await remove(generation, {
3444
+ recursive: true,
3445
+ force: true
3446
+ });
3447
+ if (locked) await remove(lock, {
3448
+ recursive: true,
3449
+ force: true
3450
+ });
3451
+ } catch {
3452
+ failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
3453
+ }
3454
+ }
3455
+ if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
3456
+ }
3457
+ //#endregion
3458
+ //#region src/build/explain.ts
3459
+ function explainProfile(profile, request, assume) {
3460
+ if (kindOf(profile) !== "profile") return {
3461
+ ok: false,
3462
+ diagnostics: [{
3463
+ severity: "error",
3464
+ code: "INVALID_RESOURCE",
3465
+ path: "profile",
3466
+ profile: "profile",
3467
+ message: "INVALID_RESOURCE"
3468
+ }]
3469
+ };
3470
+ const prepared = prepareProfile(profile, "profile", void 0, false);
3471
+ if (!prepared.ok || !prepared.routing) return {
3472
+ ok: false,
3473
+ diagnostics: prepared.diagnostics.map(({ target: _target, ...d }) => ({
3474
+ ...d,
3475
+ profile: "profile"
3476
+ }))
3477
+ };
3478
+ const parsed = parseRequest(request);
3479
+ const assumptions = prepareAssumptions(prepared.routing, assume);
3480
+ if (assumptions.errors.length) return {
3481
+ ok: false,
3482
+ diagnostics: assumptions.errors.map((e) => ({
3483
+ severity: "error",
3484
+ code: e.code,
3485
+ path: e.path,
3486
+ message: e.code,
3487
+ profile: "profile",
3488
+ origin: originOf(profile)
3489
+ }))
3490
+ };
3491
+ return {
3492
+ ok: true,
3493
+ explanation: evaluate(prepared.routing, parsed, assumptions.values)
3494
+ };
3495
+ }
3496
+ //#endregion
3497
+ //#region src/build/index.ts
3498
+ function compile(definition) {
3499
+ if (kindOf(definition) !== "build") throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3500
+ const entries = Object.entries(definition.profiles);
3501
+ const prepared = entries.map(([key, p]) => prepareProfile(p, key, definition.secrets));
3502
+ const extra = entries.map(() => []);
3503
+ const endpoints = entries.flatMap(([key, p], index) => p.proxies.flatMap((resource) => resource.type === "sing-box-tailscale" ? [{
3504
+ key,
3505
+ index,
3506
+ resource
3507
+ }] : []));
3508
+ for (let i = 0; i < endpoints.length; i++) {
3509
+ const a = endpoints[i];
3510
+ const add = (index, key, resource) => extra[index].push({
3511
+ severity: "error",
3512
+ code: "ENDPOINT_STATE_OVERLAP",
3513
+ profile: key,
3514
+ path: `proxies.${resource.id}.stateDirectory`,
3515
+ message: "Endpoint state directories must be exclusive",
3516
+ origin: originOf(resource)
3517
+ });
3518
+ if (definition.outDir !== void 0 && pathsOverlap(resolve(definition.outDir), a.resource.stateDirectory)) add(a.index, a.key, a.resource);
3519
+ for (let j = 0; j < i; j++) {
3520
+ const b = endpoints[j];
3521
+ if (pathsOverlap(a.resource.stateDirectory, b.resource.stateDirectory)) {
3522
+ add(a.index, a.key, a.resource);
3523
+ add(b.index, b.key, b.resource);
3524
+ }
3525
+ }
3526
+ }
3527
+ const profiles = prepared.map((p, i) => {
3528
+ const diagnostics = [...p.diagnostics, ...extra[i]].map((d) => {
3529
+ const { target: _target, ...rest } = d;
3530
+ return {
3531
+ ...rest,
3532
+ profile: entries[i][0]
3533
+ };
3534
+ });
3535
+ return {
3536
+ key: entries[i][0],
3537
+ target: entries[i][1].target,
3538
+ ok: p.ok && !diagnostics.some((d) => d.severity === "error"),
3539
+ diagnostics,
3540
+ selections: p.selections
3541
+ };
3542
+ });
3543
+ const cases = profiles.flatMap((p, i) => {
3544
+ const result = checkCases(entries[i][1], p.key, prepared[i], p.ok);
3545
+ p.diagnostics.push(...result.diagnostics);
3546
+ p.ok = p.ok && result.diagnostics.length === 0;
3547
+ return result.cases;
3548
+ });
3549
+ const profileOk = profiles.every((p) => p.ok);
3550
+ const ok = profileOk && cases.every((c) => c.ok);
3551
+ return {
3552
+ check: Object.freeze({
3553
+ ok,
3554
+ code: !profileOk ? "CHECK_FAILED" : ok ? "CHECKED" : "CASE_FAILED",
3555
+ outputDirectoryChecked: definition.outDir !== void 0,
3556
+ profiles,
3557
+ cases
3558
+ }),
3559
+ prepared,
3560
+ entries
3561
+ };
3562
+ }
3563
+ function checkBuild(definition) {
3564
+ return compile(definition).check;
3565
+ }
3566
+ async function runBuild(definition, options = {}) {
3567
+ const { check, prepared, entries } = compile(definition);
3568
+ if (Object.keys(options).some((k) => k !== "validation") || options.validation !== void 0 && typeof options.validation !== "boolean") return {
3569
+ published: false,
3570
+ exitCode: 1,
3571
+ code: "INVALID_BUILD_OPTIONS",
3572
+ check
3573
+ };
3574
+ if (!check.ok) return {
3575
+ published: false,
3576
+ exitCode: 1,
3577
+ code: check.code,
3578
+ check
3579
+ };
3580
+ if (definition.outDir === void 0) return {
3581
+ published: false,
3582
+ exitCode: 1,
3583
+ code: "OUTPUT_DIRECTORY_REQUIRED",
3584
+ check
3585
+ };
3586
+ const output = resolve(definition.outDir);
3587
+ const active = join(output, "out");
3588
+ try {
3589
+ const read = secretReader(definition.secrets, options.validation ?? false);
3590
+ const files = /* @__PURE__ */ new Map();
3591
+ for (const [i, p] of prepared.entries()) files.set(`${entries[i][0]}.${p.engine === "surge" ? "conf" : p.engine === "sing-box" ? "json" : "yaml"}`, renderPrepared(p, read));
3592
+ await publishProfiles(files, output);
3593
+ return {
3594
+ published: true,
3595
+ exitCode: 0,
3596
+ code: "PUBLISHED",
3597
+ check,
3598
+ active
3599
+ };
3600
+ } catch (error) {
3601
+ if (error instanceof SurgePublishError) return {
3602
+ published: error.published,
3603
+ exitCode: error.published || error.message === "PUBLISH_RECOVERY_REQUIRED" ? 2 : 1,
3604
+ code: error.message,
3605
+ check,
3606
+ ...error.published ? { active } : {},
3607
+ ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "Preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
3608
+ };
3609
+ return {
3610
+ published: false,
3611
+ exitCode: 1,
3612
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED",
3613
+ check,
3614
+ ...secretFailure(error)
3615
+ };
3616
+ }
3617
+ }
3618
+ //#endregion
3619
+ export { definitionDiagnostic as C, ProfileDefinitionError as S, inspectDefinition as T, endpointSchema as _, defineBuild as a, nativeRuleSetSchema as b, dnsRulesSchema as c, tunnelSchema as d, created as f, requireKind as g, parsed as h, targetCatalog as i, conditionSchema as l, inspectRecord as m, runBuild as n, secretSources as o, flatten as p, explainProfile as r, defineProfile as s, checkBuild as t, groupTestSchema as u, idSchema as v, exactDefinition as w, nodeSchema as x, matchSchema as y };