proxylang 0.3.0 → 0.5.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.
@@ -1,126 +1,399 @@
1
+ import { createHash, randomUUID } from "node:crypto";
1
2
  import { isIP } from "node:net";
2
- import ipaddr from "ipaddr.js";
3
3
  import { z } from "zod";
4
+ import ipaddr from "ipaddr.js";
4
5
  import { stringify } from "yaml";
5
6
  import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
6
7
  import { join, resolve } from "node:path";
7
- import { randomUUID } from "node:crypto";
8
- //#region src/rulesets.ts
9
- function canonical(value) {
10
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
11
- if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
12
- return JSON.stringify(value);
13
- }
14
- function validateRuleSets(entries, engine, diagnostics, path) {
15
- const definitions = /* @__PURE__ */ new Map();
16
- const urls = /* @__PURE__ */ new Map();
17
- const error = (code) => diagnostics.push({
18
- severity: "error",
19
- code,
20
- path,
21
- message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
22
- });
23
- const visit = (m) => {
24
- if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
25
- const key = canonical(m);
26
- if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
27
- definitions.set(m.id, key);
28
- if (m.type === "ruleSet") visit(m.when);
29
- else {
30
- if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
31
- if (m.engine === "surge") {
32
- const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
33
- const url = new URL(m.url).href;
34
- if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
35
- urls.set(url, settings);
36
- }
37
- }
38
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
39
- else if (m.type === "not") visit(m.condition);
40
- };
41
- const walk = (items) => {
42
- for (const item of items) if (item.type === "rule") visit(item.when);
43
- else if (item.type === "block") {
44
- if (item.when) visit(item.when);
45
- walk(item.rules);
46
- } else walk(item.policy.rules);
47
- };
48
- walk(entries);
8
+ //#region src/surge-definitions.ts
9
+ var ProfileDefinitionError = class extends Error {
10
+ code;
11
+ constructor(code) {
12
+ super(code);
13
+ this.code = code;
14
+ this.name = "ProfileDefinitionError";
15
+ }
16
+ };
17
+ const fail$1 = (code) => {
18
+ throw new ProfileDefinitionError(code);
19
+ };
20
+ /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
21
+ function inspectDefinition(root) {
22
+ let edges = 0;
23
+ let objects = 0;
24
+ const visiting = /* @__PURE__ */ new Set();
25
+ const heights = /* @__PURE__ */ new Map();
26
+ function visit(value, depth) {
27
+ if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
28
+ if (value === null || typeof value !== "object") {
29
+ if (![
30
+ "undefined",
31
+ "string",
32
+ "number",
33
+ "boolean"
34
+ ].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
35
+ return 0;
36
+ }
37
+ if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
38
+ const cached = heights.get(value);
39
+ if (cached !== void 0) {
40
+ if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
41
+ return cached;
42
+ }
43
+ if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
44
+ const proto = Object.getPrototypeOf(value);
45
+ if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
46
+ if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
47
+ visiting.add(value);
48
+ let height = 0;
49
+ for (const key of Reflect.ownKeys(value)) {
50
+ if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
51
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
52
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
53
+ height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
54
+ }
55
+ visiting.delete(value);
56
+ heights.set(value, height);
57
+ return height;
58
+ }
59
+ visit(root, 0);
49
60
  }
50
- function lowerRuleSets(rules, diagnostics, path) {
51
- let count = 0;
52
- let origins = 0;
53
- const lower = (m, origin, depth) => {
54
- if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
55
- if (m.type === "ruleSet") {
56
- origin.push(`rule-set:${m.id}`);
57
- return lower(m.when, origin, depth + 1);
61
+ /** Count output occurrences, not identities, before allocating each copied value. */
62
+ function snapshot(input) {
63
+ let remaining = 1e5;
64
+ function copy(value, depth) {
65
+ if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
66
+ if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
67
+ if (value === null || typeof value !== "object") return value;
68
+ if (Array.isArray(value)) {
69
+ const output = [];
70
+ for (const item of value) output.push(copy(item, depth + 1));
71
+ return output;
58
72
  }
59
- if (m.type === "all" || m.type === "any") return {
60
- ...m,
61
- conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
62
- };
63
- if (m.type === "not") return {
64
- ...m,
65
- condition: lower(m.condition, origin, depth + 1)
66
- };
67
- return m;
68
- };
69
- try {
70
- if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
71
- return rules.map((r) => {
72
- const origin = [...r.origin];
73
- const when = lower(r.when, origin, 0);
74
- origins += origin.length;
75
- if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
76
- return {
77
- ...r,
78
- when,
79
- origin
80
- };
81
- });
82
- } catch {
83
- diagnostics.push({
84
- severity: "error",
85
- code: "EXPANSION_LIMIT",
86
- path,
87
- message: "展开规则、条件或来源超过预算"
73
+ const output = {};
74
+ for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
75
+ value: copy(item, depth + 1),
76
+ enumerable: true,
77
+ writable: true,
78
+ configurable: true
88
79
  });
89
- return [];
80
+ return output;
90
81
  }
82
+ return copy(input, 0);
91
83
  }
92
- function collectNativeRuleSets(rules, target, diagnostics) {
93
- const found = /* @__PURE__ */ new Map();
94
- const visit = (m, nested) => {
95
- if (m.type === "nativeRuleSet") {
96
- found.set(m.id, m);
97
- if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
98
- severity: "error",
99
- code: "RULESET_COMPOSITION_UNSUPPORTED",
100
- target: target.id,
101
- path: `targets.${target.id}.ruleSets.${m.id}`,
102
- message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
103
- });
104
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
105
- else if (m.type === "not") visit(m.condition, true);
106
- else if (m.type === "ruleSet") visit(m.when, nested);
84
+ function snapshotDefinition(input) {
85
+ inspectDefinition(input);
86
+ return snapshot(input);
87
+ }
88
+ function exactDefinition(value, keys) {
89
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
90
+ if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
91
+ }
92
+ const outbound = {
93
+ direct: Object.freeze({ builtin: "DIRECT" }),
94
+ reject: Object.freeze({ builtin: "REJECT" }),
95
+ rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
96
+ rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
97
+ rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
98
+ };
99
+ function defineProxyGroup(input) {
100
+ inspectDefinition(input);
101
+ exactDefinition(input, [
102
+ "id",
103
+ "name",
104
+ "algorithm",
105
+ "members",
106
+ "url",
107
+ "intervalSeconds",
108
+ "timeoutSeconds"
109
+ ]);
110
+ if (!input.algorithm || ![
111
+ "select",
112
+ "surge-smart",
113
+ "urltest"
114
+ ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
115
+ exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
116
+ "type",
117
+ "url",
118
+ "intervalSeconds",
119
+ "toleranceMs"
120
+ ] : ["type"]);
121
+ if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
122
+ return {
123
+ ...input,
124
+ type: "proxy-group",
125
+ algorithm: { ...input.algorithm },
126
+ members: [...input.members]
107
127
  };
108
- rules.forEach((r) => visit(r.when, false));
109
- for (const r of found.values()) diagnostics.push({
110
- severity: "warning",
111
- code: "EXTERNAL_RULESET_UNVERIFIED",
112
- target: target.id,
113
- path: `targets.${target.id}.ruleSets.${r.id}`,
114
- message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
128
+ }
129
+ function defineRoute(input) {
130
+ inspectDefinition(input);
131
+ exactDefinition(input, ["when", "to"]);
132
+ return {
133
+ ...input,
134
+ type: "route"
135
+ };
136
+ }
137
+ function defineRoutes(input) {
138
+ inspectDefinition(input);
139
+ exactDefinition(input, ["when", "to"]);
140
+ if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
141
+ return input.when.map((when) => ({
142
+ type: "route",
143
+ when,
144
+ to: input.to
145
+ }));
146
+ }
147
+ function selectProxies(nodes, query = {}) {
148
+ inspectDefinition({
149
+ nodes,
150
+ query
115
151
  });
116
- return [...found.values()];
152
+ exactDefinition(query, [
153
+ "ids",
154
+ "regions",
155
+ "providers",
156
+ "tags"
157
+ ]);
158
+ if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
159
+ for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
160
+ return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag))));
117
161
  }
118
- //#endregion
119
- //#region src/schema.ts
120
- const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
121
- const domain$1 = 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])?$/);
122
- const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
123
- const cidr$1 = z.string().refine((x) => {
162
+ function lowerSurgeProfile(input) {
163
+ inspectDefinition(input);
164
+ exactDefinition(input, [
165
+ "target",
166
+ "managed",
167
+ "general",
168
+ "hosts",
169
+ "nodes",
170
+ "tunnels",
171
+ "names",
172
+ "groups",
173
+ "routes",
174
+ "fallback"
175
+ ]);
176
+ if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail$1("DEFINITION_NOT_DATA");
177
+ const registry = /* @__PURE__ */ new Map();
178
+ const names = Object.assign(Object.create(null), input.names);
179
+ for (const resource of [
180
+ ...input.nodes,
181
+ ...input.tunnels ?? [],
182
+ ...input.groups
183
+ ]) {
184
+ if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
185
+ if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
186
+ registry.set(resource.id, resource);
187
+ const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
188
+ if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
189
+ Object.defineProperty(names, resource.id, {
190
+ value: names[resource.id] ?? name,
191
+ enumerable: true,
192
+ configurable: true,
193
+ writable: true
194
+ });
195
+ }
196
+ function lower(destination) {
197
+ if (typeof destination === "string") {
198
+ if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
199
+ return { ref: destination };
200
+ }
201
+ if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
202
+ if ("builtin" in destination) {
203
+ exactDefinition(destination, ["builtin"]);
204
+ if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
205
+ return { builtin: destination.builtin };
206
+ }
207
+ if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
208
+ return { ref: destination.id };
209
+ }
210
+ const groups = input.groups.map((definition) => {
211
+ exactDefinition(definition, [
212
+ "type",
213
+ "id",
214
+ "name",
215
+ "algorithm",
216
+ "members",
217
+ "url",
218
+ "intervalSeconds",
219
+ "timeoutSeconds"
220
+ ]);
221
+ if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
222
+ if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
223
+ exactDefinition(definition.algorithm, ["type"]);
224
+ if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
225
+ const { id, url, intervalSeconds, timeoutSeconds } = definition;
226
+ return {
227
+ id,
228
+ type: definition.algorithm.type === "select" ? "select" : "smart",
229
+ members: definition.members.map(lower),
230
+ ...url === void 0 ? {} : { url },
231
+ ...intervalSeconds === void 0 ? {} : { intervalSeconds },
232
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
233
+ };
234
+ });
235
+ const rules = input.routes.map((definition) => {
236
+ exactDefinition(definition, [
237
+ "type",
238
+ "when",
239
+ "to"
240
+ ]);
241
+ if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
242
+ return {
243
+ when: definition.when,
244
+ then: lower(definition.to)
245
+ };
246
+ });
247
+ const { routes: _routes, groups: _groups, fallback, ...rest } = input;
248
+ return snapshot({
249
+ ...rest,
250
+ names,
251
+ groups,
252
+ rules,
253
+ fallback: lower(fallback)
254
+ });
255
+ }
256
+ function condition(value) {
257
+ inspectDefinition(value);
258
+ return value;
259
+ }
260
+ function atom$2(type) {
261
+ return (value, options = {}) => {
262
+ inspectDefinition(options);
263
+ return condition({
264
+ ...options,
265
+ type,
266
+ value
267
+ });
268
+ };
269
+ }
270
+ const surgeMatch = {
271
+ domain: atom$2("domain"),
272
+ domainSuffix: atom$2("domainSuffix"),
273
+ ipCidr: atom$2("ipCidr"),
274
+ ipCidr6: atom$2("ipCidr6"),
275
+ sourceIp: atom$2("sourceIp"),
276
+ processName: atom$2("processName"),
277
+ macAddress: atom$2("macAddress"),
278
+ network: (value, options = {}) => {
279
+ inspectDefinition(options);
280
+ return condition({
281
+ ...options,
282
+ type: "network",
283
+ value
284
+ });
285
+ },
286
+ port: (from, to, options = {}) => {
287
+ inspectDefinition(options);
288
+ return condition({
289
+ ...options,
290
+ type: "port",
291
+ from,
292
+ ...to === void 0 ? {} : { to }
293
+ });
294
+ },
295
+ sourcePort: (from, to, options = {}) => {
296
+ inspectDefinition(options);
297
+ return condition({
298
+ ...options,
299
+ type: "sourcePort",
300
+ from,
301
+ ...to === void 0 ? {} : { to }
302
+ });
303
+ },
304
+ all: (conditions, options = {}) => {
305
+ inspectDefinition({
306
+ conditions,
307
+ options
308
+ });
309
+ return condition({
310
+ ...options,
311
+ type: "all",
312
+ conditions: [...conditions]
313
+ });
314
+ },
315
+ any: (conditions, options = {}) => {
316
+ inspectDefinition({
317
+ conditions,
318
+ options
319
+ });
320
+ return condition({
321
+ ...options,
322
+ type: "any",
323
+ conditions: [...conditions]
324
+ });
325
+ },
326
+ not: (value, options = {}) => {
327
+ inspectDefinition({
328
+ value,
329
+ options
330
+ });
331
+ return condition({
332
+ ...options,
333
+ type: "not",
334
+ condition: value
335
+ });
336
+ },
337
+ ruleSet: (options) => {
338
+ inspectDefinition(options);
339
+ return condition({
340
+ ...options,
341
+ type: "ruleSet"
342
+ });
343
+ }
344
+ };
345
+ //#endregion
346
+ //#region src/dns.ts
347
+ const domain$2 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
348
+ function dohUrl(value) {
349
+ const url = new URL(value);
350
+ if (!/^https:\/\/[^/]+\//.test(value)) url.pathname = "/dns-query";
351
+ return url;
352
+ }
353
+ const server = z.string().max(2048).refine((value) => {
354
+ if (isIP(value) && !value.includes("%")) return true;
355
+ if (!value.startsWith("https://") || /[\s\p{C},()\\"'?#]/u.test(value)) return false;
356
+ try {
357
+ const url = new URL(value);
358
+ const authority = value.slice(8).split("/")[0];
359
+ const path = value.slice(8 + authority.length);
360
+ return !url.username && !url.password && !authority.endsWith(":") && !!url.hostname && (!path || url.pathname === path);
361
+ } catch {
362
+ return false;
363
+ }
364
+ });
365
+ const dnsRulesSchema = z.array(z.strictObject({
366
+ pattern: z.string().min(1).max(253).refine((value) => domain$2.test(value.startsWith("*.") ? value.slice(2) : value)),
367
+ server
368
+ })).max(2e3).superRefine((rules, ctx) => {
369
+ if (rules.length > 2e3 || rules.some((rule) => rule.pattern.length > 253 || rule.server.length > 2048)) return;
370
+ for (let i = 0; i < rules.length; i++) for (let j = 0; j < i; j++) {
371
+ const a = rules[i], b = rules[j];
372
+ const x = a.pattern.toLowerCase(), y = b.pattern.toLowerCase();
373
+ if (x === y || overlap(x, y) && a.server !== b.server) {
374
+ ctx.addIssue({
375
+ code: "custom",
376
+ message: "DNS_RULE_CONFLICT"
377
+ });
378
+ return;
379
+ }
380
+ }
381
+ });
382
+ function overlap(a, b) {
383
+ const wildA = a.startsWith("*."), wildB = b.startsWith("*.");
384
+ if (wildA && wildB) return a.slice(1).endsWith(b.slice(1)) || b.slice(1).endsWith(a.slice(1));
385
+ return wildA ? b.endsWith(a.slice(1)) : wildB && a.endsWith(b.slice(1));
386
+ }
387
+ function dnsCondition(rule) {
388
+ const pattern = rule.pattern.toLowerCase();
389
+ return pattern.startsWith("*.") ? { domain_regex: [`^.+\\.${pattern.slice(2).replaceAll(".", "\\.")}$`] } : { domain: [pattern] };
390
+ }
391
+ //#endregion
392
+ //#region src/schema.ts
393
+ const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
394
+ const domain$1 = 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])?$/);
395
+ const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
396
+ const cidr$1 = z.string().refine((x) => {
124
397
  try {
125
398
  const [address, prefix] = x.split("/");
126
399
  if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
@@ -130,9 +403,10 @@ const cidr$1 = z.string().refine((x) => {
130
403
  return false;
131
404
  }
132
405
  });
406
+ const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
133
407
  const port$1 = z.number().int().min(1).max(65535);
134
408
  const network = z.enum(["tcp", "udp"]);
135
- const atom$2 = (type, value) => z.strictObject({
409
+ const atom$1 = (type, value) => z.strictObject({
136
410
  type: z.literal(type),
137
411
  value
138
412
  });
@@ -154,7 +428,9 @@ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
154
428
  ...remoteBase,
155
429
  engine: z.literal("surge"),
156
430
  format: z.enum(["rule-set", "domain-set"]),
157
- intervalSeconds: updateInterval.optional()
431
+ intervalSeconds: updateInterval.optional(),
432
+ noResolve: z.boolean().optional(),
433
+ extendedMatching: z.boolean().optional()
158
434
  }),
159
435
  z.strictObject({
160
436
  ...remoteBase,
@@ -181,10 +457,23 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
181
457
  id: idSchema,
182
458
  when: matchSchema
183
459
  }),
184
- atom$2("domain", domain$1),
185
- atom$2("domainSuffix", domain$1),
186
- atom$2("ipCidr", cidr$1),
187
- atom$2("sourceIp", cidr$1),
460
+ z.strictObject({
461
+ type: z.literal("domain"),
462
+ value: domain$1,
463
+ extendedMatching: z.boolean().optional()
464
+ }),
465
+ z.strictObject({
466
+ type: z.literal("domainSuffix"),
467
+ value: domain$1,
468
+ extendedMatching: z.boolean().optional()
469
+ }),
470
+ z.strictObject({
471
+ type: z.literal("ipCidr"),
472
+ value: cidr$1,
473
+ noResolve: z.boolean().optional()
474
+ }),
475
+ atom$1("sourceIp", z.union([ip$1, cidr$1])),
476
+ atom$1("processName", processNameSchema),
188
477
  z.strictObject({
189
478
  type: z.literal("port"),
190
479
  from: port$1,
@@ -275,7 +564,7 @@ const uuidNode = {
275
564
  tls: tlsSchema.optional(),
276
565
  transport: transportSchema.optional()
277
566
  };
278
- const surgeOptions = { blockQuic: z.enum([
567
+ const surgeOptions$1 = { blockQuic: z.enum([
279
568
  "auto",
280
569
  "on",
281
570
  "off"
@@ -288,7 +577,7 @@ const nodeSchema = z.discriminatedUnion("type", [
288
577
  serverName: domain$1.optional(),
289
578
  skipCertVerify: z.boolean().optional(),
290
579
  surge: z.strictObject({
291
- ...surgeOptions,
580
+ ...surgeOptions$1,
292
581
  udpRelay: z.literal(true).optional()
293
582
  }).optional()
294
583
  }),
@@ -299,7 +588,7 @@ const nodeSchema = z.discriminatedUnion("type", [
299
588
  serverName: domain$1.optional(),
300
589
  skipCertVerify: z.boolean().optional(),
301
590
  surge: z.strictObject({
302
- ...surgeOptions,
591
+ ...surgeOptions$1,
303
592
  udpRelay: z.literal(true).optional()
304
593
  }).optional()
305
594
  }),
@@ -314,7 +603,7 @@ const nodeSchema = z.discriminatedUnion("type", [
314
603
  ...nodeBase,
315
604
  type: z.literal("shadowsocks"),
316
605
  surge: z.strictObject({
317
- ...surgeOptions,
606
+ ...surgeOptions$1,
318
607
  udpRelay: z.boolean().optional()
319
608
  }).optional(),
320
609
  method: z.enum([
@@ -327,7 +616,7 @@ const nodeSchema = z.discriminatedUnion("type", [
327
616
  z.strictObject({
328
617
  ...uuidNode,
329
618
  type: z.literal("vmess"),
330
- surge: z.strictObject(surgeOptions).optional()
619
+ surge: z.strictObject(surgeOptions$1).optional()
331
620
  }),
332
621
  z.strictObject({
333
622
  ...uuidNode,
@@ -400,8 +689,11 @@ const groupSchema$1 = z.union([
400
689
  const requestSchema = z.strictObject({
401
690
  network,
402
691
  domain: domain$1.optional(),
692
+ tlsSni: domain$1.optional(),
693
+ httpHost: domain$1.optional(),
403
694
  ip: ip$1.optional(),
404
695
  sourceIp: ip$1.optional(),
696
+ processName: processNameSchema.optional(),
405
697
  port: port$1.optional(),
406
698
  sourcePort: port$1.optional()
407
699
  });
@@ -413,6 +705,7 @@ const configSchema = z.strictObject({
413
705
  "mihomo",
414
706
  "stash"
415
707
  ]),
708
+ dns: dnsRulesSchema.optional(),
416
709
  nodes: z.array(nodeSchema),
417
710
  endpoints: z.array(endpointSchema).max(1e3).optional(),
418
711
  groups: z.array(groupSchema$1),
@@ -490,38 +783,149 @@ function deepFreeze(value) {
490
783
  return value;
491
784
  }
492
785
  //#endregion
493
- //#region src/rules.ts
494
- function expandRules(entries, diagnostics, path = "routing") {
495
- const output = [];
496
- const seen = /* @__PURE__ */ new Set();
497
- let limited = false;
498
- const error = (code, where, message) => diagnostics.push({
786
+ //#region src/rulesets.ts
787
+ function canonical(value) {
788
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
789
+ if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
790
+ return JSON.stringify(value);
791
+ }
792
+ function validateRuleSets(entries, engine, diagnostics, path) {
793
+ const definitions = /* @__PURE__ */ new Map();
794
+ const urls = /* @__PURE__ */ new Map();
795
+ const error = (code) => diagnostics.push({
499
796
  severity: "error",
500
797
  code,
501
- path: where,
502
- message
798
+ path,
799
+ message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
503
800
  });
504
- function resolve(action, bindings, inPolicy, where) {
505
- if (action.type === "slot") {
506
- if (!Object.hasOwn(bindings, action.name)) {
507
- error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
508
- return;
509
- }
510
- return bindings[action.name];
511
- }
512
- if (inPolicy && action.type === "route") {
513
- error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
514
- return;
515
- }
516
- return action;
517
- }
518
- function walk(items, prefix, guards, bindings, inPolicy, origin) {
519
- for (const entry of items) {
520
- if (limited) return;
521
- if (entry.type === "rule" && output.length >= 1e4) {
522
- limited = true;
523
- error("EXPANSION_LIMIT", path, "展开规则超过10000条");
524
- return;
801
+ const visit = (m) => {
802
+ if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
803
+ const key = canonical(m);
804
+ if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
805
+ definitions.set(m.id, key);
806
+ if (m.type === "ruleSet") visit(m.when);
807
+ else {
808
+ if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
809
+ if (m.engine === "surge") {
810
+ const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
811
+ const url = new URL(m.url).href;
812
+ if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
813
+ urls.set(url, settings);
814
+ }
815
+ }
816
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
817
+ else if (m.type === "not") visit(m.condition);
818
+ };
819
+ const walk = (items) => {
820
+ for (const item of items) if (item.type === "rule") visit(item.when);
821
+ else if (item.type === "block") {
822
+ if (item.when) visit(item.when);
823
+ walk(item.rules);
824
+ } else walk(item.policy.rules);
825
+ };
826
+ walk(entries);
827
+ }
828
+ function lowerRuleSets(rules, diagnostics, path) {
829
+ let count = 0;
830
+ let origins = 0;
831
+ const lower = (m, origin, depth) => {
832
+ if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
833
+ if (m.type === "ruleSet") {
834
+ origin.push(`rule-set:${m.id}`);
835
+ return lower(m.when, origin, depth + 1);
836
+ }
837
+ if (m.type === "all" || m.type === "any") return {
838
+ ...m,
839
+ conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
840
+ };
841
+ if (m.type === "not") return {
842
+ ...m,
843
+ condition: lower(m.condition, origin, depth + 1)
844
+ };
845
+ return m;
846
+ };
847
+ try {
848
+ if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
849
+ return rules.map((r) => {
850
+ const origin = [...r.origin];
851
+ const when = lower(r.when, origin, 0);
852
+ origins += origin.length;
853
+ if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
854
+ return {
855
+ ...r,
856
+ when,
857
+ origin
858
+ };
859
+ });
860
+ } catch {
861
+ diagnostics.push({
862
+ severity: "error",
863
+ code: "EXPANSION_LIMIT",
864
+ path,
865
+ message: "展开规则、条件或来源超过预算"
866
+ });
867
+ return [];
868
+ }
869
+ }
870
+ function collectNativeRuleSets(rules, target, diagnostics) {
871
+ const found = /* @__PURE__ */ new Map();
872
+ const visit = (m, nested) => {
873
+ if (m.type === "nativeRuleSet") {
874
+ found.set(m.id, m);
875
+ if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
876
+ severity: "error",
877
+ code: "RULESET_COMPOSITION_UNSUPPORTED",
878
+ target: target.id,
879
+ path: `targets.${target.id}.ruleSets.${m.id}`,
880
+ message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
881
+ });
882
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
883
+ else if (m.type === "not") visit(m.condition, true);
884
+ else if (m.type === "ruleSet") visit(m.when, nested);
885
+ };
886
+ rules.forEach((r) => visit(r.when, false));
887
+ for (const r of found.values()) diagnostics.push({
888
+ severity: "warning",
889
+ code: "EXTERNAL_RULESET_UNVERIFIED",
890
+ target: target.id,
891
+ path: `targets.${target.id}.ruleSets.${r.id}`,
892
+ message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
893
+ });
894
+ return [...found.values()];
895
+ }
896
+ //#endregion
897
+ //#region src/rules.ts
898
+ function expandRules(entries, diagnostics, path = "routing") {
899
+ const output = [];
900
+ const seen = /* @__PURE__ */ new Set();
901
+ let limited = false;
902
+ const error = (code, where, message) => diagnostics.push({
903
+ severity: "error",
904
+ code,
905
+ path: where,
906
+ message
907
+ });
908
+ function resolve(action, bindings, inPolicy, where) {
909
+ if (action.type === "slot") {
910
+ if (!Object.hasOwn(bindings, action.name)) {
911
+ error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
912
+ return;
913
+ }
914
+ return bindings[action.name];
915
+ }
916
+ if (inPolicy && action.type === "route") {
917
+ error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
918
+ return;
919
+ }
920
+ return action;
921
+ }
922
+ function walk(items, prefix, guards, bindings, inPolicy, origin) {
923
+ for (const entry of items) {
924
+ if (limited) return;
925
+ if (entry.type === "rule" && output.length >= 1e4) {
926
+ limited = true;
927
+ error("EXPANSION_LIMIT", path, "展开规则超过10000条");
928
+ return;
525
929
  }
526
930
  const id = `${prefix}/${entry.id}`;
527
931
  if (seen.has(id)) {
@@ -563,7 +967,7 @@ function expandRules(entries, diagnostics, path = "routing") {
563
967
  function inCidr(address, cidr) {
564
968
  if (!address) return false;
565
969
  const parsed = ipaddr.parse(address);
566
- const [base, bits] = ipaddr.parseCIDR(cidr);
970
+ const [base, bits] = ipaddr.parseCIDR(cidr.includes("/") ? cidr : `${cidr}/${cidr.includes(":") ? 128 : 32}`);
567
971
  return parsed.kind() === base.kind() && parsed.match(base, bits);
568
972
  }
569
973
  var StaticRuleSetUnknownError = class extends Error {
@@ -602,17 +1006,24 @@ function evaluate(condition, request) {
602
1006
  let present;
603
1007
  switch (condition.type) {
604
1008
  case "domain":
605
- present = request.domain !== void 0;
606
- matched = request.domain === condition.value;
607
- break;
608
- case "domainSuffix":
609
- present = request.domain !== void 0;
610
- matched = request.domain === condition.value || !!request.domain?.endsWith(`.${condition.value}`);
1009
+ case "domainSuffix": {
1010
+ const domains = condition.extendedMatching ? [
1011
+ request.domain,
1012
+ request.tlsSni,
1013
+ request.httpHost
1014
+ ] : [request.domain];
1015
+ present = domains.some((value) => value !== void 0);
1016
+ matched = domains.some((value) => value !== void 0 && (value === condition.value || condition.type === "domainSuffix" && value.endsWith(`.${condition.value}`)));
611
1017
  break;
1018
+ }
612
1019
  case "ipCidr":
613
1020
  present = request.ip !== void 0;
614
1021
  matched = inCidr(request.ip, condition.value);
615
1022
  break;
1023
+ case "processName":
1024
+ present = request.processName !== void 0;
1025
+ matched = request.processName === condition.value;
1026
+ break;
616
1027
  case "sourceIp":
617
1028
  present = request.sourceIp !== void 0;
618
1029
  matched = inCidr(request.sourceIp, condition.value);
@@ -908,8 +1319,9 @@ function conditionText$1(condition) {
908
1319
  case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
909
1320
  case "domain": return `DOMAIN,${condition.value}`;
910
1321
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
911
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
912
- case "sourceIp": return `SRC-IP-CIDR,${condition.value}`;
1322
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}${condition.noResolve !== false ? ",no-resolve" : ""}`;
1323
+ case "processName": return `PROCESS-NAME,${condition.value}`;
1324
+ case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
913
1325
  case "network": return `NETWORK,${condition.value}`;
914
1326
  case "port":
915
1327
  case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
@@ -921,7 +1333,7 @@ function clashConfig(plan, secret) {
921
1333
  const config = {
922
1334
  proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
923
1335
  "proxy-groups": program.groups.map((g) => clashGroup(g)),
924
- rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)},no-resolve` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
1336
+ rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)}${rule.when.noResolve !== false ? ",no-resolve" : ""}` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
925
1337
  };
926
1338
  if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
927
1339
  type: "http",
@@ -1283,7 +1695,7 @@ function compile(input) {
1283
1695
  }
1284
1696
  const parsed = configSchema.safeParse(input);
1285
1697
  if (!parsed.success) {
1286
- for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1698
+ for (const issue of parsed.error.issues.slice(0, 20)) error(issue.message === "DNS_RULE_CONFLICT" ? "DNS_RULE_CONFLICT" : "INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1287
1699
  return deepFreeze({
1288
1700
  ok: false,
1289
1701
  diagnostics,
@@ -1371,6 +1783,10 @@ function compile(input) {
1371
1783
  if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
1372
1784
  if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
1373
1785
  if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
1786
+ if (program.dns?.length) {
1787
+ if (target.engine !== "sing-box") error("DNS_TARGET_UNSUPPORTED", path, "通用 DNS 需要 sing-box standalone 或 Surge Profile", target.id);
1788
+ else if (target.mode !== "standalone") error("DNS_MODE_UNSUPPORTED", path, "通用 DNS 需要 standalone", target.id);
1789
+ }
1374
1790
  for (const endpoint of program.endpoints ?? []) {
1375
1791
  if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 端点仅支持 sing-box 1.12.0", target.id);
1376
1792
  if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
@@ -1393,6 +1809,13 @@ function compile(input) {
1393
1809
  if (target.engine === "surge") {
1394
1810
  for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
1395
1811
  }
1812
+ const checkOptions = (condition) => {
1813
+ if ("extendedMatching" in condition && condition.extendedMatching === true && target.engine !== "surge" || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box") error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
1814
+ if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(checkOptions);
1815
+ else if (condition.type === "not") checkOptions(condition.condition);
1816
+ else if (condition.type === "ruleSet") checkOptions(condition.when);
1817
+ };
1818
+ rules.forEach((rule) => checkOptions(rule.when));
1396
1819
  const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
1397
1820
  for (const resource of nativeRuleSets) if (!descriptor.nativeRuleSets.includes(resource.format)) error("RULESET_UNSUPPORTED", `${path}.ruleSets.${resource.id}`, "精确目标不支持此原生规则资源格式", target.id);
1398
1821
  plans.push({
@@ -1638,50 +2061,51 @@ const groupSchema = z.strictObject({
1638
2061
  intervalSeconds: z.number().int().positive().max(2147483647).optional(),
1639
2062
  timeoutSeconds: z.number().int().positive().max(3600).optional()
1640
2063
  });
1641
- const options = {
2064
+ const options$1 = {
1642
2065
  noResolve: z.boolean().optional(),
1643
2066
  extendedMatching: z.boolean().optional()
1644
2067
  };
1645
- const atom$1 = (type, value) => z.strictObject({
2068
+ const atom = (type, value) => z.strictObject({
1646
2069
  type: z.literal(type),
1647
2070
  value,
1648
- ...options
2071
+ ...options$1
1649
2072
  });
1650
2073
  const conditionSchema = z.lazy(() => z.union([
1651
- atom$1("domain", domain),
1652
- atom$1("domainSuffix", domain),
1653
- atom$1("ipCidr", cidr(4)),
1654
- atom$1("ipCidr6", cidr(6)),
1655
- atom$1("sourceIp", z.union([ip, cidr()])),
1656
- atom$1("processName", safe),
1657
- atom$1("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
2074
+ atom("domain", domain),
2075
+ atom("domainSuffix", domain),
2076
+ atom("ipCidr", cidr(4)),
2077
+ atom("ipCidr6", cidr(6)),
2078
+ atom("sourceIp", z.union([ip, cidr()])),
2079
+ atom("processName", safe),
2080
+ atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
1658
2081
  z.strictObject({
1659
2082
  type: z.enum(["port", "sourcePort"]),
1660
2083
  from: port,
1661
2084
  to: port.optional(),
1662
- ...options
2085
+ ...options$1
1663
2086
  }).refine((v) => v.to === void 0 || v.to >= v.from),
1664
2087
  z.strictObject({
1665
2088
  type: z.literal("network"),
1666
2089
  value: z.enum(["tcp", "udp"]),
1667
- ...options
2090
+ ...options$1
1668
2091
  }),
1669
2092
  z.strictObject({
1670
2093
  type: z.enum(["all", "any"]),
1671
2094
  conditions: z.array(conditionSchema).min(2).max(100),
1672
- ...options
2095
+ ...options$1
1673
2096
  }),
1674
2097
  z.strictObject({
1675
2098
  type: z.literal("not"),
1676
2099
  condition: conditionSchema,
1677
- ...options
2100
+ ...options$1
1678
2101
  }),
1679
2102
  z.strictObject({
1680
2103
  type: z.literal("ruleSet"),
1681
2104
  format: z.enum(["rule-set", "domain-set"]),
1682
2105
  url: url.optional(),
1683
2106
  builtin: z.enum(["LAN", "SYSTEM"]).optional(),
1684
- ...options
2107
+ intervalSeconds: z.number().int().min(60).max(2147483647).optional(),
2108
+ ...options$1
1685
2109
  }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
1686
2110
  ]));
1687
2111
  const managedSchema = z.strictObject({
@@ -1823,10 +2247,13 @@ function compileSurgeProfile(input) {
1823
2247
  if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
1824
2248
  if (c.type === "not") checkCondition(c.condition, depth + 1);
1825
2249
  if (c.type === "ruleSet") {
2250
+ if (c.intervalSeconds !== void 0 && (depth > 0 || c.builtin)) error("RULESET_COMPOSITION_UNSUPPORTED");
1826
2251
  if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
1827
2252
  if (c.url) {
1828
- if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
1829
- formats.set(c.url, c.format);
2253
+ const key = new URL(c.url).href;
2254
+ const settings = `${c.format}:${c.intervalSeconds ?? 86400}`;
2255
+ if (formats.has(key) && formats.get(key) !== settings) error("RULESET_FORMAT_CONFLICT");
2256
+ formats.set(key, settings);
1830
2257
  }
1831
2258
  }
1832
2259
  };
@@ -1852,7 +2279,11 @@ function compileSurgeProfile(input) {
1852
2279
  return result;
1853
2280
  }
1854
2281
  function conditionOptions(c) {
1855
- return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
2282
+ return [
2283
+ ...c.noResolve ? ["no-resolve"] : [],
2284
+ ...c.extendedMatching ? ["extended-matching"] : [],
2285
+ ...c.type === "ruleSet" && c.intervalSeconds !== void 0 ? [`update-interval=${c.intervalSeconds}`] : []
2286
+ ];
1856
2287
  }
1857
2288
  function conditionText(c) {
1858
2289
  switch (c.type) {
@@ -1878,414 +2309,76 @@ function renderProfile(compilation, read) {
1878
2309
  const p = plans.get(compilation);
1879
2310
  if (!p) throw new RenderError("COMPILATION_FAILED");
1880
2311
  const name = (id) => p.names?.[id] ?? id;
1881
- const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
1882
- const credential = (token, kind) => {
1883
- const value = read(token);
1884
- 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");
1885
- return value;
1886
- };
1887
- const lines = [];
1888
- if (p.managed) {
1889
- const address = new URL(p.managed.url);
1890
- for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
1891
- lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
1892
- }
1893
- lines.push("[General]");
1894
- for (const [k, v] of Object.entries(p.general ?? {})) {
1895
- const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
1896
- lines.push(`${k} = ${value}`);
1897
- }
1898
- lines.push("", "[Host]");
1899
- for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
1900
- lines.push("", "[Proxy]");
1901
- for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
1902
- for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
1903
- for (const t of p.tunnels ?? []) {
1904
- lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
1905
- if (t.type === "tailscale") {
1906
- lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
1907
- if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1908
- if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
1909
- if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
1910
- } else {
1911
- lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
1912
- if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1913
- if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
1914
- for (const peer of t.peers) {
1915
- const values = [`public-key = ${peer.publicKey}`];
1916
- if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
1917
- values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
1918
- if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
1919
- lines.push(`peer = (${values.join(", ")})`);
1920
- }
1921
- }
1922
- }
1923
- lines.push("", "[Proxy Group]");
1924
- for (const g of p.groups) lines.push(`${name(g.id)} = ${[
1925
- g.type,
1926
- ...g.members.map(action),
1927
- ...g.url ? [`url=${g.url}`] : [],
1928
- ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
1929
- ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
1930
- ].join(", ")}`);
1931
- lines.push("", "[Rule]");
1932
- for (const r of p.rules) lines.push([
1933
- conditionText(r.when),
1934
- action(r.then),
1935
- ...conditionOptions(r.when)
1936
- ].join(","));
1937
- lines.push(`FINAL,${action(p.fallback)}`, "");
1938
- return deepFreeze({
1939
- artifactKind: "surge-profile",
1940
- content: lines.join("\n")
1941
- });
1942
- }
1943
- function renderSurgeProfile(compilation, resolveSecret) {
1944
- return renderProfile(compilation, secretReader(resolveSecret));
1945
- }
1946
- function renderSurgeProfiles(compilations, resolveSecret) {
1947
- if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
1948
- const read = secretReader(resolveSecret);
1949
- return deepFreeze(compilations.map((c) => renderProfile(c, read)));
1950
- }
1951
- //#endregion
1952
- //#region src/surge-definitions.ts
1953
- var ProfileDefinitionError = class extends Error {
1954
- code;
1955
- constructor(code) {
1956
- super(code);
1957
- this.code = code;
1958
- this.name = "ProfileDefinitionError";
1959
- }
1960
- };
1961
- const fail$1 = (code) => {
1962
- throw new ProfileDefinitionError(code);
1963
- };
1964
- /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
1965
- function inspectDefinition(root) {
1966
- let edges = 0;
1967
- let objects = 0;
1968
- const visiting = /* @__PURE__ */ new Set();
1969
- const heights = /* @__PURE__ */ new Map();
1970
- function visit(value, depth) {
1971
- if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
1972
- if (value === null || typeof value !== "object") {
1973
- if (![
1974
- "undefined",
1975
- "string",
1976
- "number",
1977
- "boolean"
1978
- ].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
1979
- return 0;
1980
- }
1981
- if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
1982
- const cached = heights.get(value);
1983
- if (cached !== void 0) {
1984
- if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
1985
- return cached;
1986
- }
1987
- if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
1988
- const proto = Object.getPrototypeOf(value);
1989
- if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
1990
- if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
1991
- visiting.add(value);
1992
- let height = 0;
1993
- for (const key of Reflect.ownKeys(value)) {
1994
- if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
1995
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
1996
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
1997
- height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
1998
- }
1999
- visiting.delete(value);
2000
- heights.set(value, height);
2001
- return height;
2002
- }
2003
- visit(root, 0);
2004
- }
2005
- /** Count output occurrences, not identities, before allocating each copied value. */
2006
- function snapshot(input) {
2007
- let remaining = 1e5;
2008
- function copy(value, depth) {
2009
- if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2010
- if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
2011
- if (value === null || typeof value !== "object") return value;
2012
- if (Array.isArray(value)) {
2013
- const output = [];
2014
- for (const item of value) output.push(copy(item, depth + 1));
2015
- return output;
2016
- }
2017
- const output = {};
2018
- for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
2019
- value: copy(item, depth + 1),
2020
- enumerable: true,
2021
- writable: true,
2022
- configurable: true
2023
- });
2024
- return output;
2025
- }
2026
- return copy(input, 0);
2027
- }
2028
- function snapshotDefinition(input) {
2029
- inspectDefinition(input);
2030
- return snapshot(input);
2031
- }
2032
- function exactDefinition(value, keys) {
2033
- if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
2034
- if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
2035
- }
2036
- const outbound = {
2037
- direct: Object.freeze({ builtin: "DIRECT" }),
2038
- reject: Object.freeze({ builtin: "REJECT" }),
2039
- rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
2040
- rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
2041
- rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
2042
- };
2043
- function defineProxyGroup(input) {
2044
- inspectDefinition(input);
2045
- exactDefinition(input, [
2046
- "id",
2047
- "name",
2048
- "algorithm",
2049
- "members",
2050
- "url",
2051
- "intervalSeconds",
2052
- "timeoutSeconds"
2053
- ]);
2054
- if (!input.algorithm || ![
2055
- "select",
2056
- "surge-smart",
2057
- "urltest"
2058
- ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2059
- exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
2060
- "type",
2061
- "url",
2062
- "intervalSeconds",
2063
- "toleranceMs"
2064
- ] : ["type"]);
2065
- if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
2066
- return {
2067
- ...input,
2068
- type: "proxy-group",
2069
- algorithm: { ...input.algorithm },
2070
- members: [...input.members]
2071
- };
2072
- }
2073
- function defineRoute(input) {
2074
- inspectDefinition(input);
2075
- exactDefinition(input, ["when", "to"]);
2076
- return {
2077
- ...input,
2078
- type: "route"
2079
- };
2080
- }
2081
- function defineRoutes(input) {
2082
- inspectDefinition(input);
2083
- exactDefinition(input, ["when", "to"]);
2084
- if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
2085
- return input.when.map((when) => ({
2086
- type: "route",
2087
- when,
2088
- to: input.to
2089
- }));
2090
- }
2091
- function selectProxies(nodes, query = {}) {
2092
- inspectDefinition({
2093
- nodes,
2094
- query
2095
- });
2096
- exactDefinition(query, [
2097
- "ids",
2098
- "regions",
2099
- "providers",
2100
- "tags"
2101
- ]);
2102
- if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
2103
- for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
2104
- return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag))));
2105
- }
2106
- function lowerSurgeProfile(input) {
2107
- inspectDefinition(input);
2108
- exactDefinition(input, [
2109
- "target",
2110
- "managed",
2111
- "general",
2112
- "hosts",
2113
- "nodes",
2114
- "tunnels",
2115
- "names",
2116
- "groups",
2117
- "routes",
2118
- "fallback"
2119
- ]);
2120
- if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail$1("DEFINITION_NOT_DATA");
2121
- const registry = /* @__PURE__ */ new Map();
2122
- const names = Object.assign(Object.create(null), input.names);
2123
- for (const resource of [
2124
- ...input.nodes,
2125
- ...input.tunnels ?? [],
2126
- ...input.groups
2127
- ]) {
2128
- if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
2129
- if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
2130
- registry.set(resource.id, resource);
2131
- const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
2132
- if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
2133
- Object.defineProperty(names, resource.id, {
2134
- value: names[resource.id] ?? name,
2135
- enumerable: true,
2136
- configurable: true,
2137
- writable: true
2138
- });
2312
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
2313
+ const credential = (token, kind) => {
2314
+ const value = read(token);
2315
+ 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");
2316
+ return value;
2317
+ };
2318
+ const lines = [];
2319
+ if (p.managed) {
2320
+ const address = new URL(p.managed.url);
2321
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
2322
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
2139
2323
  }
2140
- function lower(destination) {
2141
- if (typeof destination === "string") {
2142
- if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
2143
- return { ref: destination };
2144
- }
2145
- if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
2146
- if ("builtin" in destination) {
2147
- exactDefinition(destination, ["builtin"]);
2148
- if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
2149
- return { builtin: destination.builtin };
2324
+ lines.push("[General]");
2325
+ for (const [k, v] of Object.entries(p.general ?? {})) {
2326
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
2327
+ lines.push(`${k} = ${value}`);
2328
+ }
2329
+ lines.push("", "[Host]");
2330
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
2331
+ lines.push("", "[Proxy]");
2332
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
2333
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
2334
+ for (const t of p.tunnels ?? []) {
2335
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
2336
+ if (t.type === "tailscale") {
2337
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
2338
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2339
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
2340
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
2341
+ } else {
2342
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
2343
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2344
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
2345
+ for (const peer of t.peers) {
2346
+ const values = [`public-key = ${peer.publicKey}`];
2347
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
2348
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
2349
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
2350
+ lines.push(`peer = (${values.join(", ")})`);
2351
+ }
2150
2352
  }
2151
- if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
2152
- return { ref: destination.id };
2153
2353
  }
2154
- const groups = input.groups.map((definition) => {
2155
- exactDefinition(definition, [
2156
- "type",
2157
- "id",
2158
- "name",
2159
- "algorithm",
2160
- "members",
2161
- "url",
2162
- "intervalSeconds",
2163
- "timeoutSeconds"
2164
- ]);
2165
- if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
2166
- if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2167
- exactDefinition(definition.algorithm, ["type"]);
2168
- if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
2169
- const { id, url, intervalSeconds, timeoutSeconds } = definition;
2170
- return {
2171
- id,
2172
- type: definition.algorithm.type === "select" ? "select" : "smart",
2173
- members: definition.members.map(lower),
2174
- ...url === void 0 ? {} : { url },
2175
- ...intervalSeconds === void 0 ? {} : { intervalSeconds },
2176
- ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
2177
- };
2178
- });
2179
- const rules = input.routes.map((definition) => {
2180
- exactDefinition(definition, [
2181
- "type",
2182
- "when",
2183
- "to"
2184
- ]);
2185
- if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
2186
- return {
2187
- when: definition.when,
2188
- then: lower(definition.to)
2189
- };
2190
- });
2191
- const { routes: _routes, groups: _groups, fallback, ...rest } = input;
2192
- return snapshot({
2193
- ...rest,
2194
- names,
2195
- groups,
2196
- rules,
2197
- fallback: lower(fallback)
2354
+ lines.push("", "[Proxy Group]");
2355
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
2356
+ g.type,
2357
+ ...g.members.map(action),
2358
+ ...g.url ? [`url=${g.url}`] : [],
2359
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
2360
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
2361
+ ].join(", ")}`);
2362
+ lines.push("", "[Rule]");
2363
+ for (const r of p.rules) lines.push([
2364
+ conditionText(r.when),
2365
+ action(r.then),
2366
+ ...conditionOptions(r.when)
2367
+ ].join(","));
2368
+ lines.push(`FINAL,${action(p.fallback)}`, "");
2369
+ return deepFreeze({
2370
+ artifactKind: "surge-profile",
2371
+ content: lines.join("\n")
2198
2372
  });
2199
2373
  }
2200
- function condition(value) {
2201
- inspectDefinition(value);
2202
- return value;
2374
+ function renderSurgeProfile(compilation, resolveSecret) {
2375
+ return renderProfile(compilation, secretReader(resolveSecret));
2203
2376
  }
2204
- function atom(type) {
2205
- return (value, options = {}) => {
2206
- inspectDefinition(options);
2207
- return condition({
2208
- ...options,
2209
- type,
2210
- value
2211
- });
2212
- };
2377
+ function renderSurgeProfiles(compilations, resolveSecret) {
2378
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
2379
+ const read = secretReader(resolveSecret);
2380
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2213
2381
  }
2214
- const surgeMatch = {
2215
- domain: atom("domain"),
2216
- domainSuffix: atom("domainSuffix"),
2217
- ipCidr: atom("ipCidr"),
2218
- ipCidr6: atom("ipCidr6"),
2219
- sourceIp: atom("sourceIp"),
2220
- processName: atom("processName"),
2221
- macAddress: atom("macAddress"),
2222
- network: (value, options = {}) => {
2223
- inspectDefinition(options);
2224
- return condition({
2225
- ...options,
2226
- type: "network",
2227
- value
2228
- });
2229
- },
2230
- port: (from, to, options = {}) => {
2231
- inspectDefinition(options);
2232
- return condition({
2233
- ...options,
2234
- type: "port",
2235
- from,
2236
- ...to === void 0 ? {} : { to }
2237
- });
2238
- },
2239
- sourcePort: (from, to, options = {}) => {
2240
- inspectDefinition(options);
2241
- return condition({
2242
- ...options,
2243
- type: "sourcePort",
2244
- from,
2245
- ...to === void 0 ? {} : { to }
2246
- });
2247
- },
2248
- all: (conditions, options = {}) => {
2249
- inspectDefinition({
2250
- conditions,
2251
- options
2252
- });
2253
- return condition({
2254
- ...options,
2255
- type: "all",
2256
- conditions: [...conditions]
2257
- });
2258
- },
2259
- any: (conditions, options = {}) => {
2260
- inspectDefinition({
2261
- conditions,
2262
- options
2263
- });
2264
- return condition({
2265
- ...options,
2266
- type: "any",
2267
- conditions: [...conditions]
2268
- });
2269
- },
2270
- not: (value, options = {}) => {
2271
- inspectDefinition({
2272
- value,
2273
- options
2274
- });
2275
- return condition({
2276
- ...options,
2277
- type: "not",
2278
- condition: value
2279
- });
2280
- },
2281
- ruleSet: (options) => {
2282
- inspectDefinition(options);
2283
- return condition({
2284
- ...options,
2285
- type: "ruleSet"
2286
- });
2287
- }
2288
- };
2289
2382
  //#endregion
2290
2383
  //#region src/profile.ts
2291
2384
  const fail = (code) => {
@@ -2315,7 +2408,8 @@ function defineProfile(input) {
2315
2408
  "routes",
2316
2409
  "fallback",
2317
2410
  "surge",
2318
- "singBox"
2411
+ "singBox",
2412
+ "dns"
2319
2413
  ]);
2320
2414
  exactDefinition(input.target, [
2321
2415
  "engine",
@@ -2351,6 +2445,11 @@ function defineProfile(input) {
2351
2445
  const proxies = flatten(input.proxies);
2352
2446
  const groups = flatten(input.groups);
2353
2447
  const routes = flatten(input.routes);
2448
+ const dns = input.dns === void 0 ? void 0 : flatten(input.dns);
2449
+ if (dns) {
2450
+ const checked = dnsRulesSchema.safeParse(dns);
2451
+ if (!checked.success) fail(checked.error.issues.some((issue) => issue.message === "DNS_RULE_CONFLICT") ? "DNS_RULE_CONFLICT" : "INVALID_DNS_RULES");
2452
+ }
2354
2453
  let surge;
2355
2454
  if (input.surge !== void 0) {
2356
2455
  let general;
@@ -2388,9 +2487,11 @@ function defineProfile(input) {
2388
2487
  ...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
2389
2488
  };
2390
2489
  }
2391
- const { surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2490
+ if (dns?.length && surge?.hosts?.length) fail("DNS_HOSTS_CONFLICT");
2491
+ const { dns: _dns, surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2392
2492
  return snapshotProfile({
2393
2493
  ...rest,
2494
+ ...dns === void 0 ? {} : { dns },
2394
2495
  proxies,
2395
2496
  groups,
2396
2497
  routes,
@@ -2411,11 +2512,15 @@ function surgeCondition$1(condition, depth = 0) {
2411
2512
  if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2412
2513
  const value = parsed.data;
2413
2514
  if (value.type === "ruleSet") return surgeCondition$1(value.when, depth);
2414
- if (value.type !== "nativeRuleSet" || value.engine !== "surge" || value.intervalSeconds !== void 0) return fail("PROFILE_CONDITION_UNSUPPORTED");
2515
+ if (value.type !== "nativeRuleSet" || value.engine !== "surge") return fail("PROFILE_CONDITION_UNSUPPORTED");
2516
+ if (depth > 0 && value.intervalSeconds !== void 0) return fail("RULESET_COMPOSITION_UNSUPPORTED");
2415
2517
  return {
2416
2518
  type: "ruleSet",
2417
2519
  format: value.format,
2418
- url: value.url
2520
+ url: value.url,
2521
+ ...value.intervalSeconds !== void 0 ? { intervalSeconds: value.intervalSeconds } : {},
2522
+ ...value.noResolve !== void 0 ? { noResolve: value.noResolve } : {},
2523
+ ...value.extendedMatching !== void 0 ? { extendedMatching: value.extendedMatching } : {}
2419
2524
  };
2420
2525
  }
2421
2526
  if (condition.type === "all" || condition.type === "any") {
@@ -2452,6 +2557,7 @@ function compileProfile(input) {
2452
2557
  const compilation = compileSurgeProfile(lowerSurgeProfile({
2453
2558
  target: profile.target,
2454
2559
  ...profile.surge,
2560
+ ...profile.dns?.length ? { hosts: profile.dns } : {},
2455
2561
  nodes,
2456
2562
  tunnels: endpoints,
2457
2563
  groups: profile.groups,
@@ -2497,55 +2603,58 @@ function compileProfile(input) {
2497
2603
  to: destination.id
2498
2604
  };
2499
2605
  };
2606
+ const groups = profile.groups.map((definition) => {
2607
+ exactDefinition(definition, [
2608
+ "type",
2609
+ "id",
2610
+ "name",
2611
+ "algorithm",
2612
+ "members",
2613
+ "url",
2614
+ "intervalSeconds",
2615
+ "timeoutSeconds"
2616
+ ]);
2617
+ if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2618
+ if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2619
+ exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2620
+ "type",
2621
+ "url",
2622
+ "intervalSeconds",
2623
+ "toleranceMs"
2624
+ ] : ["type"]);
2625
+ const members = definition.members.map((member) => {
2626
+ const action = lower(member);
2627
+ if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2628
+ return action.to;
2629
+ });
2630
+ return {
2631
+ ...definition.algorithm,
2632
+ id: definition.id,
2633
+ members
2634
+ };
2635
+ });
2636
+ const routing = profile.routes.map((route, index) => {
2637
+ exactDefinition(route, [
2638
+ "type",
2639
+ "when",
2640
+ "to"
2641
+ ]);
2642
+ if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2643
+ return {
2644
+ type: "rule",
2645
+ id: `route-${index + 1}`,
2646
+ when: route.when,
2647
+ then: lower(route.to)
2648
+ };
2649
+ });
2500
2650
  const compilation = compile(snapshotDefinition({
2501
2651
  programs: { profile: {
2502
2652
  engine: "sing-box",
2653
+ ...profile.dns === void 0 ? {} : { dns: profile.dns },
2503
2654
  nodes,
2504
2655
  endpoints,
2505
- groups: profile.groups.map((definition) => {
2506
- exactDefinition(definition, [
2507
- "type",
2508
- "id",
2509
- "name",
2510
- "algorithm",
2511
- "members",
2512
- "url",
2513
- "intervalSeconds",
2514
- "timeoutSeconds"
2515
- ]);
2516
- if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2517
- if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2518
- exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2519
- "type",
2520
- "url",
2521
- "intervalSeconds",
2522
- "toleranceMs"
2523
- ] : ["type"]);
2524
- const members = definition.members.map((member) => {
2525
- const action = lower(member);
2526
- if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2527
- return action.to;
2528
- });
2529
- return {
2530
- ...definition.algorithm,
2531
- id: definition.id,
2532
- members
2533
- };
2534
- }),
2535
- routing: profile.routes.map((route, index) => {
2536
- exactDefinition(route, [
2537
- "type",
2538
- "when",
2539
- "to"
2540
- ]);
2541
- if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2542
- return {
2543
- type: "rule",
2544
- id: `route-${index + 1}`,
2545
- when: route.when,
2546
- then: lower(route.to)
2547
- };
2548
- }),
2656
+ groups,
2657
+ routing,
2549
2658
  fallback: lower(profile.fallback),
2550
2659
  ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
2551
2660
  } },
@@ -2592,19 +2701,35 @@ const ruleSet = (definition) => ({
2592
2701
  ...definition,
2593
2702
  type: "ruleSet"
2594
2703
  });
2704
+ function options(value, keys) {
2705
+ inspectDefinition(value);
2706
+ exactDefinition(value, keys);
2707
+ if (Object.values(value).some((v) => v !== void 0 && typeof v !== "boolean")) throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
2708
+ return { ...value };
2709
+ }
2595
2710
  const match = {
2711
+ processName: (value) => {
2712
+ if (!processNameSchema.safeParse(value).success) throw new Error("INVALID_PROCESS_NAME");
2713
+ return {
2714
+ type: "processName",
2715
+ value
2716
+ };
2717
+ },
2596
2718
  ruleSet: (set) => set,
2597
- domain: (value) => ({
2719
+ domain: (value, opts = {}) => ({
2598
2720
  type: "domain",
2599
- value
2721
+ value,
2722
+ ...options(opts, ["extendedMatching"])
2600
2723
  }),
2601
- domainSuffix: (value) => ({
2724
+ domainSuffix: (value, opts = {}) => ({
2602
2725
  type: "domainSuffix",
2603
- value
2726
+ value,
2727
+ ...options(opts, ["extendedMatching"])
2604
2728
  }),
2605
- ipCidr: (value) => ({
2729
+ ipCidr: (value, opts = {}) => ({
2606
2730
  type: "ipCidr",
2607
- value
2731
+ value,
2732
+ ...options(opts, ["noResolve"])
2608
2733
  }),
2609
2734
  sourceIp: (value) => ({
2610
2735
  type: "sourceIp",
@@ -2637,6 +2762,58 @@ const match = {
2637
2762
  condition
2638
2763
  })
2639
2764
  };
2765
+ function nativeConstructor(engine) {
2766
+ function construct(value) {
2767
+ inspectDefinition(value);
2768
+ if (!value || typeof value !== "object") throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
2769
+ exactDefinition(value, [
2770
+ "id",
2771
+ "url",
2772
+ "format",
2773
+ "intervalSeconds",
2774
+ "noResolve",
2775
+ "extendedMatching",
2776
+ "behavior",
2777
+ "to"
2778
+ ]);
2779
+ const input = value;
2780
+ const { to, ...resource } = input;
2781
+ exactDefinition(resource, [
2782
+ "id",
2783
+ "url",
2784
+ "format",
2785
+ "intervalSeconds",
2786
+ ...engine === "surge" ? ["noResolve", "extendedMatching"] : engine === "mihomo" ? ["behavior"] : []
2787
+ ]);
2788
+ const parsed = nativeRuleSetSchema.safeParse({
2789
+ ...engine === "surge" ? { format: "rule-set" } : {},
2790
+ ...resource,
2791
+ id: resource.id ?? "ruleset-pending",
2792
+ type: "nativeRuleSet",
2793
+ engine
2794
+ });
2795
+ if (!parsed.success) throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
2796
+ const { id: _id, type: _type, ...fields } = parsed.data;
2797
+ const id = resource.id ?? `ruleset-${createHash("sha256").update(JSON.stringify(Object.entries(fields).filter(([, value]) => value !== void 0).sort(([a], [b]) => a.localeCompare(b)))).digest("hex").slice(0, 16)}`;
2798
+ const when = snapshotDefinition({
2799
+ ...parsed.data,
2800
+ id
2801
+ });
2802
+ if (Object.hasOwn(input, "to")) {
2803
+ if (to === void 0) throw new ProfileDefinitionError("INVALID_DESTINATION");
2804
+ return {
2805
+ type: "route",
2806
+ when,
2807
+ to
2808
+ };
2809
+ }
2810
+ return when;
2811
+ }
2812
+ return construct;
2813
+ }
2814
+ const surgeRuleSet = nativeConstructor("surge");
2815
+ const mihomoRuleSet = nativeConstructor("mihomo");
2816
+ const singboxRuleSet = nativeConstructor("sing-box");
2640
2817
  const direct = () => ({ type: "direct" });
2641
2818
  const reject = () => ({ type: "reject" });
2642
2819
  const route = (to) => ({
@@ -2697,18 +2874,12 @@ const surge$1 = {
2697
2874
  config: surgeConfig,
2698
2875
  match: surgeMatch,
2699
2876
  smart: () => ({ type: "surge-smart" }),
2700
- ruleSet: (options) => ({
2701
- format: "rule-set",
2702
- ...options,
2703
- type: "nativeRuleSet",
2704
- engine: "surge"
2705
- })
2877
+ ruleSet: surgeRuleSet
2878
+ };
2879
+ const mihomo = {
2880
+ ruleSet: mihomoRuleSet,
2881
+ ruleProvider: mihomoRuleSet
2706
2882
  };
2707
- const mihomo = { ruleProvider: (options) => ({
2708
- ...options,
2709
- type: "nativeRuleSet",
2710
- engine: "mihomo"
2711
- }) };
2712
2883
  /** Protocol constructors keep credentials and options specific to their protocol. */
2713
2884
  function nodeConstructor(type) {
2714
2885
  return (options) => ({
@@ -2726,11 +2897,7 @@ const proxy = {
2726
2897
  vless: nodeConstructor("vless")
2727
2898
  };
2728
2899
  const singbox$1 = {
2729
- ruleSet: (options) => ({
2730
- ...options,
2731
- type: "nativeRuleSet",
2732
- engine: "sing-box"
2733
- }),
2900
+ ruleSet: singboxRuleSet,
2734
2901
  tailscale: (options) => ({
2735
2902
  ...options,
2736
2903
  type: "sing-box-tailscale"
@@ -2770,7 +2937,8 @@ function singCondition(condition) {
2770
2937
  case "domain": return { domain: [condition.value] };
2771
2938
  case "domainSuffix": return { domain_suffix: [condition.value] };
2772
2939
  case "ipCidr": return { ip_cidr: [condition.value] };
2773
- case "sourceIp": return { source_ip_cidr: [condition.value] };
2940
+ case "processName": return { process_name: [condition.value] };
2941
+ case "sourceIp": return { source_ip_cidr: [condition.value.includes("/") ? condition.value : `${condition.value}/${isIP(condition.value) === 6 ? 128 : 32}`] };
2774
2942
  case "network": return { network: [condition.value] };
2775
2943
  case "port":
2776
2944
  case "sourcePort": {
@@ -2798,7 +2966,13 @@ function singbox(plan, secret) {
2798
2966
  tag: DIRECT,
2799
2967
  ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
2800
2968
  }];
2801
- for (const node of program.nodes) outbounds.push(singboxProxy(node, secret));
2969
+ for (const node of program.nodes) outbounds.push({
2970
+ ...singboxProxy(node, secret),
2971
+ ...modern && program.dns?.length ? { domain_resolver: {
2972
+ server: DNS,
2973
+ strategy: "prefer_ipv4"
2974
+ } } : {}
2975
+ });
2802
2976
  for (const group of program.groups) outbounds.push(singboxGroup(group));
2803
2977
  const rules = plan.rules.map((rule) => ({
2804
2978
  ...singCondition(rule.when),
@@ -2833,8 +3007,7 @@ function singbox(plan, secret) {
2833
3007
  type: "udp",
2834
3008
  tag: DNS,
2835
3009
  server: listener.resolver,
2836
- server_port: 53,
2837
- detour: DIRECT
3010
+ server_port: 53
2838
3011
  } : {
2839
3012
  tag: DNS,
2840
3013
  address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
@@ -2843,11 +3016,51 @@ function singbox(plan, secret) {
2843
3016
  final: DNS,
2844
3017
  strategy: "prefer_ipv4"
2845
3018
  };
2846
- if (modern) routing.default_domain_resolver = {
3019
+ if (modern && !program.dns?.length) routing.default_domain_resolver = {
2847
3020
  server: DNS,
2848
3021
  strategy: "prefer_ipv4"
2849
3022
  };
2850
3023
  }
3024
+ if (program.dns?.length) {
3025
+ const dns = config.dns;
3026
+ dns.rules = program.dns.map((rule, index) => {
3027
+ const tag = `pl-domain-dns-${index}`;
3028
+ if (isIP(rule.server)) dns.servers.push(modern ? {
3029
+ type: "udp",
3030
+ tag,
3031
+ server: rule.server,
3032
+ server_port: 53
3033
+ } : {
3034
+ tag,
3035
+ address: `udp://${isIP(rule.server) === 6 ? `[${rule.server}]` : rule.server}`,
3036
+ detour: DIRECT
3037
+ });
3038
+ else {
3039
+ const url = dohUrl(rule.server);
3040
+ dns.servers.push(modern ? {
3041
+ type: "https",
3042
+ tag,
3043
+ server: url.hostname.replace(/^\[|\]$/g, ""),
3044
+ server_port: Number(url.port || 443),
3045
+ path: url.pathname,
3046
+ tls: { enabled: true },
3047
+ domain_resolver: {
3048
+ server: DNS,
3049
+ strategy: "prefer_ipv4"
3050
+ }
3051
+ } : {
3052
+ tag,
3053
+ address: url.href,
3054
+ address_resolver: DNS,
3055
+ detour: DIRECT
3056
+ });
3057
+ }
3058
+ return {
3059
+ ...dnsCondition(rule),
3060
+ server: tag
3061
+ };
3062
+ });
3063
+ }
2851
3064
  if (program.endpoints?.length) {
2852
3065
  config.endpoints = program.endpoints.map((endpoint) => ({
2853
3066
  type: "tailscale",
@@ -2865,22 +3078,29 @@ function singbox(plan, secret) {
2865
3078
  type: "udp",
2866
3079
  tag: `pl-ts-dns-${endpoint.id}`,
2867
3080
  server: endpoint.bootstrapResolver,
2868
- server_port: 53,
2869
- detour: DIRECT
3081
+ server_port: 53
2870
3082
  });
2871
3083
  }
2872
3084
  return config;
2873
3085
  }
3086
+ function surgeOptions(condition) {
3087
+ return [
3088
+ ...condition.type === "ipCidr" && condition.noResolve !== false ? ["no-resolve"] : [],
3089
+ ...condition.type === "nativeRuleSet" && condition.engine === "surge" && condition.noResolve ? ["no-resolve"] : [],
3090
+ ..."extendedMatching" in condition && condition.extendedMatching ? ["extended-matching"] : []
3091
+ ].map((value) => `,${value}`).join("");
3092
+ }
2874
3093
  function surgeCondition(condition) {
2875
3094
  switch (condition.type) {
2876
3095
  case "ruleSet": return surgeCondition(condition.when);
2877
3096
  case "nativeRuleSet": return `${condition.format === "domain-set" ? "DOMAIN-SET" : "RULE-SET"},${condition.url}`;
2878
3097
  case "all":
2879
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)})`).join(",")})`;
2880
- case "not": return `NOT,((${surgeCondition(condition.condition)}))`;
3098
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)}${surgeOptions(c)})`).join(",")})`;
3099
+ case "not": return `NOT,((${surgeCondition(condition.condition)}${surgeOptions(condition.condition)}))`;
2881
3100
  case "domain": return `DOMAIN,${condition.value}`;
2882
3101
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
2883
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
3102
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}`;
3103
+ case "processName": return `PROCESS-NAME,${condition.value}`;
2884
3104
  case "sourceIp": return `SRC-IP,${condition.value}`;
2885
3105
  case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
2886
3106
  case "port":
@@ -2898,10 +3118,7 @@ function surge(plan, secret) {
2898
3118
  lines.push("", "[Rule]");
2899
3119
  for (const rule of plan.rules) {
2900
3120
  lines.push(`# ${rule.id}`);
2901
- if (rule.when.type === "ipCidr") {
2902
- const condition = surgeCondition(rule.when).replace(/,no-resolve$/, "");
2903
- lines.push(`${condition},${policy(rule.then)},no-resolve`);
2904
- } else lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
3121
+ lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${surgeOptions(rule.when)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
2905
3122
  }
2906
3123
  lines.push(`FINAL,${policy(plan.program.fallback)}`);
2907
3124
  return lines.join("\n") + "\n";
@@ -3300,4 +3517,4 @@ async function runBuild(input, output, options = {}) {
3300
3517
  };
3301
3518
  }
3302
3519
  //#endregion
3303
- export { defineRoute as A, compileStrategyGroups as B, strategy as C, defineProfile as D, compileProfile as E, renderSurgeProfile as F, surgeProxy as G, nativeNameSchema as H, renderSurgeProfiles as I, assertData as J, validateProxyOptions as K, secretReader as L, outbound as M, selectProxies as N, ProfileDefinitionError as O, compileSurgeProfile as P, requestSchema as Q, compile as R, slot as S, use as T, targetCatalog as U, isReservedNativeName as V, RenderError as W, idSchema as X, deepFreeze as Y, nodeSchema as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, defineRoutes as j, defineProxyGroup as k, group as l, reject as m, profileBuildFailure as n, block as o, proxy as p, StaticRuleSetUnknownError as q, runBuild as r, defineConfig as s, defineBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, explain as z };
3520
+ export { renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, selectProxies as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, outbound as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, group as l, reject as m, profileBuildFailure as n, block as o, proxy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, defineBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, surgeProxy as z };