proxylang 0.1.1 → 0.1.3

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.
package/dist/index.js CHANGED
@@ -1 +1,584 @@
1
- export { s as RenderError, c as StaticRuleSetUnknownError, u as block, t as buildToDirectory, r as compile, a as compileStrategyGroups, d as defineConfig, f as direct, i as explain, p as group, m as match, h as mihomo, g as policy, _ as proxy, v as reject, n as render, y as route, b as rule, x as ruleSet, S as secret, C as selectNodes, w as sequence, T as singbox, E as slot, D as strategy, O as surge, o as targetCatalog, k as use } from "./host-Cw60hFyr.js";
1
+ import { A as slot, C as route, D as selectNodes, E as secret, F as deepFreeze, I as idSchema, L as nodeSchema, M as surge, N as use, O as sequence, P as assertData, S as reject, T as ruleSet, _ as group, a as explain, b as policy, c as nativeNameSchema, d as surgeProxy, f as validateProxyOptions, g as direct, h as defineConfig, i as compile, j as strategy, k as singbox, l as targetCatalog, m as block, n as render, o as compileStrategyGroups, p as StaticRuleSetUnknownError, r as secretReader, s as isReservedNativeName, t as buildToDirectory, u as RenderError, v as match, w as rule, x as proxy, y as mihomo } from "./host-CB08cTs0.js";
2
+ import { z } from "zod";
3
+ import { isIP } from "node:net";
4
+ import ipaddr from "ipaddr.js";
5
+ //#region src/proxy-fragments.ts
6
+ const inputSchema$1 = z.strictObject({
7
+ target: z.strictObject({
8
+ engine: z.string(),
9
+ platform: z.string(),
10
+ version: z.string()
11
+ }),
12
+ nodes: z.array(nodeSchema).max(1e3),
13
+ names: z.record(idSchema, nativeNameSchema).optional(),
14
+ externals: z.array(z.strictObject({
15
+ id: idSchema,
16
+ nativeName: nativeNameSchema,
17
+ kind: z.enum(["proxy", "group"])
18
+ })).max(1e3).optional()
19
+ });
20
+ const plans$1 = /* @__PURE__ */ new WeakMap();
21
+ function compileProxyNodes(input) {
22
+ const diagnostics = [];
23
+ const error = (code, path, message) => diagnostics.push({
24
+ severity: "error",
25
+ code,
26
+ path,
27
+ message
28
+ });
29
+ const failure = () => deepFreeze({
30
+ ok: false,
31
+ artifactKind: "proxy-nodes",
32
+ diagnostics,
33
+ bindings: [],
34
+ requirements: []
35
+ });
36
+ try {
37
+ assertData(input);
38
+ } catch {
39
+ error("INVALID_INPUT_GRAPH", "$", "输入必须是有限纯数据,不接受 builder 或访问器");
40
+ return failure();
41
+ }
42
+ const parsed = inputSchema$1.safeParse(input);
43
+ if (!parsed.success) {
44
+ error("INVALID_SCHEMA", "$", "节点、名字或外部声明不符合严格 schema");
45
+ return failure();
46
+ }
47
+ const { target, nodes, names = {}, externals = [] } = deepFreeze(parsed.data);
48
+ const ids = [...nodes.map((n) => n.id), ...externals.map((e) => e.id)];
49
+ if (ids.length > 1e3) error("RESOURCE_LIMIT", "$", "节点和外部声明总数最多1000");
50
+ if (new Set(ids).size !== ids.length) error("DUPLICATE_RESOURCE", "$", "节点与外部声明 ID 必须唯一");
51
+ const nodeIds = new Set(nodes.map((n) => n.id));
52
+ if (Object.keys(names).some((id) => !nodeIds.has(id))) error("UNKNOWN_NAME_MAPPING", "names", "名字映射只能引用输入节点");
53
+ const bindings = nodes.map((node) => ({
54
+ id: node.id,
55
+ nativeName: Object.hasOwn(names, node.id) ? names[node.id] : node.id
56
+ }));
57
+ const symbols = [...bindings, ...externals];
58
+ if (symbols.some((s) => !nativeNameSchema.safeParse(s.nativeName).success || isReservedNativeName(s.nativeName, "surge"))) error("INVALID_NATIVE_NAME", "names", "原生名不合法或与目标内建策略冲突");
59
+ if (new Set(symbols.map((s) => s.nativeName)).size !== symbols.length) error("DUPLICATE_NATIVE_NAME", "names", "节点和外部符号的原生名必须唯一");
60
+ const allIds = new Set(ids);
61
+ const byId = new Map(nodes.map((n) => [n.id, n]));
62
+ for (const node of nodes) if (node.via && !allIds.has(node.via)) error("MISSING_REFERENCE", `nodes.${node.id}.via`, "拨号依赖未声明");
63
+ const states = /* @__PURE__ */ new Map();
64
+ const visit = (id) => {
65
+ if (states.get(id) === 1) {
66
+ error("RESOURCE_CYCLE", `nodes.${id}.via`, "内部拨号依赖形成循环");
67
+ return;
68
+ }
69
+ if (states.get(id) === 2) return;
70
+ states.set(id, 1);
71
+ const via = byId.get(id)?.via;
72
+ if (via && byId.has(via)) visit(via);
73
+ states.set(id, 2);
74
+ };
75
+ if (ids.length <= 1e3) for (const id of byId.keys()) visit(id);
76
+ if (diagnostics.length) return failure();
77
+ if (target.engine !== "surge" || target.platform !== "macos" || target.version !== "6.10.0") {
78
+ error("UNKNOWN_TARGET", "target", "节点片段仅支持 Surge macOS 6.10.0");
79
+ return failure();
80
+ }
81
+ const descriptor = targetCatalog.find((t) => t.engine === "surge" && t.version === target.version);
82
+ for (const node of nodes) {
83
+ if (!descriptor.protocols.includes(node.type)) error("PROTOCOL_UNSUPPORTED", `nodes.${node.id}`, "精确目标不支持该节点协议");
84
+ validateProxyOptions(node, {
85
+ id: "nodes",
86
+ program: "nodes",
87
+ engine: "surge",
88
+ platform: "macos",
89
+ version: target.version
90
+ }, diagnostics);
91
+ }
92
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
93
+ const requirements = externals.flatMap((external) => {
94
+ const usedBy = nodes.filter((node) => node.via === external.id).map((node) => node.id);
95
+ return usedBy.length ? [{
96
+ ...external,
97
+ usedBy
98
+ }] : [];
99
+ });
100
+ if (requirements.length) diagnostics.push({
101
+ severity: "warning",
102
+ code: "EXTERNAL_REFERENCE_UNVERIFIED",
103
+ path: "externals",
104
+ message: "必须逐设备验证原生符号、include 闭包及完整依赖图;未知动态组须拒绝"
105
+ });
106
+ const compilation = deepFreeze({
107
+ ok: true,
108
+ artifactKind: "proxy-nodes",
109
+ diagnostics,
110
+ bindings,
111
+ requirements
112
+ });
113
+ plans$1.set(compilation, deepFreeze({
114
+ nodes,
115
+ names: Object.fromEntries(symbols.map((s) => [s.id, s.nativeName]))
116
+ }));
117
+ return compilation;
118
+ }
119
+ function renderProxyNodes(compilation, resolveSecret) {
120
+ const plan = plans$1.get(compilation);
121
+ if (!plan) throw new RenderError("COMPILATION_FAILED");
122
+ const secret = secretReader(resolveSecret);
123
+ const entries = plan.nodes.map((node) => ({
124
+ id: node.id,
125
+ content: surgeProxy(node, secret, (id) => plan.names[id]) + "\n"
126
+ }));
127
+ return deepFreeze({
128
+ artifactKind: "proxy-nodes",
129
+ content: entries.map((e) => e.content).join(""),
130
+ entries
131
+ });
132
+ }
133
+ //#endregion
134
+ //#region src/surge-profile.ts
135
+ const builtin = z.enum([
136
+ "DIRECT",
137
+ "REJECT",
138
+ "REJECT-DROP",
139
+ "REJECT-NO-DROP",
140
+ "REJECT-TINYGIF"
141
+ ]);
142
+ const policy$1 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
143
+ const token = z.strictObject({
144
+ type: z.literal("env"),
145
+ name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
146
+ });
147
+ const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
148
+ const domain = 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])?$/);
149
+ const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
150
+ const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
151
+ const cidr = (version) => safe.refine((v) => {
152
+ try {
153
+ const [address] = ipaddr.parseCIDR(v);
154
+ return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
155
+ } catch {
156
+ return false;
157
+ }
158
+ });
159
+ const port = z.number().int().min(1).max(65535);
160
+ function addressPort(value, allowHost, portRequired) {
161
+ if (!portRequired && isIP(value)) return true;
162
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
163
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
164
+ const host = match[1];
165
+ return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
166
+ }
167
+ const listener = safe.refine((v) => addressPort(v, false, false));
168
+ const endpoint = safe.refine((v) => addressPort(v, true, true));
169
+ const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
170
+ const url = z.string().min(1).max(4096).refine((v) => {
171
+ try {
172
+ const u = new URL(v);
173
+ return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
174
+ } catch {
175
+ return false;
176
+ }
177
+ });
178
+ const encryptedDns = z.string().max(4096).refine((v) => {
179
+ try {
180
+ const u = new URL(v);
181
+ return [
182
+ "https:",
183
+ "h3:",
184
+ "quic:",
185
+ "tls:",
186
+ "tcp:"
187
+ ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
188
+ } catch {
189
+ return false;
190
+ }
191
+ });
192
+ const list = (item) => z.array(item).min(1).max(1e3);
193
+ const control = z.strictObject({
194
+ password: token,
195
+ listen: safe.refine((v) => addressPort(v, false, true))
196
+ });
197
+ const generalSchema = z.strictObject({
198
+ loglevel: z.enum([
199
+ "verbose",
200
+ "info",
201
+ "notify",
202
+ "warning"
203
+ ]).optional(),
204
+ "dns-server": list(dns).optional(),
205
+ "encrypted-dns-server": list(encryptedDns).optional(),
206
+ "show-error-page-for-reject": z.boolean().optional(),
207
+ "exclude-simple-hostnames": z.boolean().optional(),
208
+ "internet-test-url": url.optional(),
209
+ "skip-proxy": list(z.union([
210
+ hostPattern,
211
+ ip,
212
+ cidr()
213
+ ])).optional(),
214
+ ipv6: z.boolean().optional(),
215
+ "ipv6-vif": z.enum([
216
+ "auto",
217
+ "always",
218
+ "disabled"
219
+ ]).optional(),
220
+ "bypass-system": z.boolean().optional(),
221
+ replica: z.boolean().optional(),
222
+ "tls-provider": z.enum(["default", "openssl"]).optional(),
223
+ "bypass-tun": list(cidr()).optional(),
224
+ "always-real-ip": list(hostPattern).optional(),
225
+ "http-api": control.optional(),
226
+ "http-api-web-dashboard": z.boolean().optional(),
227
+ "external-controller-access": control.optional(),
228
+ "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(),
229
+ "http-listen": listener.optional(),
230
+ "socks5-listen": listener.optional(),
231
+ "proxy-restricted-to-lan": z.boolean().optional()
232
+ });
233
+ const hostSchema = z.strictObject({
234
+ pattern: hostPattern,
235
+ address: z.union([ip, domain]).optional(),
236
+ server: z.union([dns, encryptedDns]).optional()
237
+ }).refine((v) => v.address !== void 0 || v.server !== void 0);
238
+ 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);
239
+ const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
240
+ const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
241
+ type: z.literal("tailscale"),
242
+ id: idSchema,
243
+ sectionName,
244
+ authKey: token,
245
+ hostname: domain,
246
+ dnsServer: list(dns).optional(),
247
+ autoAddMagicDnsRule: z.boolean().optional(),
248
+ idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
249
+ }), z.strictObject({
250
+ type: z.literal("wireguard"),
251
+ id: idSchema,
252
+ sectionName,
253
+ privateKey: token,
254
+ selfIp: ip.refine((v) => isIP(v) === 4),
255
+ dnsServer: list(dns).optional(),
256
+ mtu: z.number().int().min(576).max(9e3).optional(),
257
+ peers: list(z.strictObject({
258
+ publicKey: key,
259
+ endpoint,
260
+ allowedIps: list(cidr()),
261
+ presharedKey: token.optional(),
262
+ persistentKeepalive: z.number().int().min(0).max(65535).optional()
263
+ }))
264
+ })]);
265
+ const groupSchema = z.strictObject({
266
+ id: idSchema,
267
+ type: z.enum(["select", "smart"]),
268
+ members: list(policy$1),
269
+ url: url.optional(),
270
+ intervalSeconds: z.number().int().positive().max(2147483647).optional(),
271
+ timeoutSeconds: z.number().int().positive().max(3600).optional()
272
+ });
273
+ const options = {
274
+ noResolve: z.boolean().optional(),
275
+ extendedMatching: z.boolean().optional()
276
+ };
277
+ const atom = (type, value) => z.strictObject({
278
+ type: z.literal(type),
279
+ value,
280
+ ...options
281
+ });
282
+ const conditionSchema = z.lazy(() => z.union([
283
+ atom("domain", domain),
284
+ atom("domainSuffix", domain),
285
+ atom("ipCidr", cidr(4)),
286
+ atom("ipCidr6", cidr(6)),
287
+ atom("sourceIp", z.union([ip, cidr()])),
288
+ atom("processName", safe),
289
+ atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
290
+ z.strictObject({
291
+ type: z.enum(["port", "sourcePort"]),
292
+ from: port,
293
+ to: port.optional(),
294
+ ...options
295
+ }).refine((v) => v.to === void 0 || v.to >= v.from),
296
+ z.strictObject({
297
+ type: z.literal("network"),
298
+ value: z.enum(["tcp", "udp"]),
299
+ ...options
300
+ }),
301
+ z.strictObject({
302
+ type: z.enum(["all", "any"]),
303
+ conditions: z.array(conditionSchema).min(2).max(100),
304
+ ...options
305
+ }),
306
+ z.strictObject({
307
+ type: z.literal("not"),
308
+ condition: conditionSchema,
309
+ ...options
310
+ }),
311
+ z.strictObject({
312
+ type: z.literal("ruleSet"),
313
+ format: z.enum(["rule-set", "domain-set"]),
314
+ url: url.optional(),
315
+ builtin: z.enum(["LAN", "SYSTEM"]).optional(),
316
+ ...options
317
+ }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
318
+ ]));
319
+ const managedSchema = z.strictObject({
320
+ url: url.refine((v) => !new URL(v).search && !v.includes("?")),
321
+ 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(),
322
+ intervalSeconds: z.number().int().min(60).max(2147483647),
323
+ strict: z.boolean()
324
+ });
325
+ const inputSchema = z.strictObject({
326
+ target: z.strictObject({
327
+ engine: z.literal("surge"),
328
+ platform: z.enum(["macos", "ios"]),
329
+ version: z.string()
330
+ }),
331
+ managed: managedSchema.optional(),
332
+ general: generalSchema.optional(),
333
+ hosts: z.array(hostSchema).max(2e3).optional(),
334
+ nodes: z.array(nodeSchema).max(1e3),
335
+ tunnels: z.array(tunnelSchema).max(1e3).optional(),
336
+ groups: z.array(groupSchema).max(1e3),
337
+ rules: z.array(z.strictObject({
338
+ when: conditionSchema,
339
+ then: policy$1
340
+ })).max(1e4),
341
+ fallback: policy$1,
342
+ names: z.record(idSchema, nativeNameSchema).optional()
343
+ });
344
+ const plans = /* @__PURE__ */ new WeakMap();
345
+ function compileSurgeProfile(input) {
346
+ const diagnostics = [];
347
+ const error = (code) => diagnostics.push({
348
+ severity: "error",
349
+ code,
350
+ path: "$",
351
+ message: code
352
+ });
353
+ const failure = () => deepFreeze({
354
+ ok: false,
355
+ artifactKind: "surge-profile",
356
+ diagnostics,
357
+ bindings: []
358
+ });
359
+ try {
360
+ assertData(input);
361
+ } catch {
362
+ error("INVALID_INPUT_GRAPH");
363
+ return failure();
364
+ }
365
+ const parsed = inputSchema.safeParse(input);
366
+ if (!parsed.success) {
367
+ error("INVALID_SCHEMA");
368
+ return failure();
369
+ }
370
+ if (parsed.data.general) {
371
+ const general = parsed.data.general;
372
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
373
+ }
374
+ const p = deepFreeze(parsed.data);
375
+ if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
376
+ const tunnels = p.tunnels ?? [];
377
+ const resources = [
378
+ ...p.nodes,
379
+ ...tunnels,
380
+ ...p.groups
381
+ ];
382
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
383
+ const ids = new Set(resources.map((r) => r.id));
384
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
385
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
386
+ const bindings = resources.map((r) => ({
387
+ id: r.id,
388
+ nativeName: p.names?.[r.id] ?? r.id
389
+ }));
390
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
391
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
392
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
393
+ if (p.target.platform === "ios" && [
394
+ "bypass-system",
395
+ "replica",
396
+ "tls-provider",
397
+ "bypass-tun",
398
+ "external-controller-access"
399
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
400
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
401
+ const checkPolicy = (action) => {
402
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
403
+ };
404
+ const edges = new Map(resources.map((r) => [r.id, []]));
405
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
406
+ for (const node of p.nodes) {
407
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
408
+ validateProxyOptions(node, {
409
+ id: "profile",
410
+ engine: "surge"
411
+ }, diagnostics);
412
+ if (node.via) {
413
+ checkPolicy({ ref: node.via });
414
+ edges.get(node.id).push(node.via);
415
+ }
416
+ }
417
+ for (const group of p.groups) {
418
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
419
+ for (const member of group.members) {
420
+ checkPolicy(member);
421
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
422
+ if ("ref" in member) edges.get(group.id).push(member.ref);
423
+ }
424
+ }
425
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
426
+ const visit = (id) => {
427
+ if (active.has(id)) {
428
+ error("RESOURCE_CYCLE");
429
+ return;
430
+ }
431
+ if (visited.has(id)) return;
432
+ active.add(id);
433
+ for (const next of edges.get(id) ?? []) visit(next);
434
+ active.delete(id);
435
+ visited.add(id);
436
+ };
437
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
438
+ const formats = /* @__PURE__ */ new Map();
439
+ const checkCondition = (c, depth) => {
440
+ if (depth > 10) {
441
+ error("LOGICAL_DEPTH_EXCEEDED");
442
+ return;
443
+ }
444
+ if (c.noResolve !== void 0 && ![
445
+ "ipCidr",
446
+ "ipCidr6",
447
+ "ruleSet"
448
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
449
+ if (c.extendedMatching !== void 0 && ![
450
+ "domain",
451
+ "domainSuffix",
452
+ "ruleSet"
453
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
454
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
455
+ if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
456
+ if (c.type === "not") checkCondition(c.condition, depth + 1);
457
+ if (c.type === "ruleSet") {
458
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
459
+ if (c.url) {
460
+ if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
461
+ formats.set(c.url, c.format);
462
+ }
463
+ }
464
+ };
465
+ for (const rule of p.rules) {
466
+ checkPolicy(rule.then);
467
+ checkCondition(rule.when, 0);
468
+ }
469
+ checkPolicy(p.fallback);
470
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
471
+ if (formats.size) diagnostics.push({
472
+ severity: "warning",
473
+ code: "EXTERNAL_RULESET_UNVERIFIED",
474
+ path: "rules",
475
+ message: "External rule sets are resolved by the client, not by the compiler."
476
+ });
477
+ const result = deepFreeze({
478
+ ok: true,
479
+ artifactKind: "surge-profile",
480
+ diagnostics,
481
+ bindings
482
+ });
483
+ plans.set(result, p);
484
+ return result;
485
+ }
486
+ function conditionOptions(c) {
487
+ return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
488
+ }
489
+ function conditionText(c) {
490
+ switch (c.type) {
491
+ case "all":
492
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
493
+ case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
494
+ case "port":
495
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
496
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
497
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
498
+ default: return `${{
499
+ domain: "DOMAIN",
500
+ domainSuffix: "DOMAIN-SUFFIX",
501
+ ipCidr: "IP-CIDR",
502
+ ipCidr6: "IP-CIDR6",
503
+ sourceIp: "SRC-IP",
504
+ processName: "PROCESS-NAME",
505
+ macAddress: "MAC-ADDRESS"
506
+ }[c.type]},${c.value}`;
507
+ }
508
+ }
509
+ function renderProfile(compilation, read) {
510
+ const p = plans.get(compilation);
511
+ if (!p) throw new RenderError("COMPILATION_FAILED");
512
+ const name = (id) => p.names?.[id] ?? id;
513
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
514
+ const credential = (token, kind) => {
515
+ const value = read(token);
516
+ 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");
517
+ return value;
518
+ };
519
+ const lines = [];
520
+ if (p.managed) {
521
+ const address = new URL(p.managed.url);
522
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
523
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
524
+ }
525
+ lines.push("[General]");
526
+ for (const [k, v] of Object.entries(p.general ?? {})) {
527
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
528
+ lines.push(`${k} = ${value}`);
529
+ }
530
+ lines.push("", "[Host]");
531
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
532
+ lines.push("", "[Proxy]");
533
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
534
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
535
+ for (const t of p.tunnels ?? []) {
536
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
537
+ if (t.type === "tailscale") {
538
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
539
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
540
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
541
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
542
+ } else {
543
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
544
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
545
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
546
+ for (const peer of t.peers) {
547
+ const values = [`public-key = ${peer.publicKey}`];
548
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
549
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
550
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
551
+ lines.push(`peer = (${values.join(", ")})`);
552
+ }
553
+ }
554
+ }
555
+ lines.push("", "[Proxy Group]");
556
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
557
+ g.type,
558
+ ...g.members.map(action),
559
+ ...g.url ? [`url=${g.url}`] : [],
560
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
561
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
562
+ ].join(", ")}`);
563
+ lines.push("", "[Rule]");
564
+ for (const r of p.rules) lines.push([
565
+ conditionText(r.when),
566
+ action(r.then),
567
+ ...conditionOptions(r.when)
568
+ ].join(","));
569
+ lines.push(`FINAL,${action(p.fallback)}`, "");
570
+ return deepFreeze({
571
+ artifactKind: "surge-profile",
572
+ content: lines.join("\n")
573
+ });
574
+ }
575
+ function renderSurgeProfile(compilation, resolveSecret) {
576
+ return renderProfile(compilation, secretReader(resolveSecret));
577
+ }
578
+ function renderSurgeProfiles(compilations, resolveSecret) {
579
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
580
+ const read = secretReader(resolveSecret);
581
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
582
+ }
583
+ //#endregion
584
+ export { RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineConfig, direct, explain, group, match, mihomo, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, secret, selectNodes, sequence, singbox, slot, strategy, surge, targetCatalog, use };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Composable routing policies in TypeScript with explicit platform targets",
5
5
  "homepage": "https://github.com/CorrectRoadH/proxylang#readme",
6
6
  "bugs": {