proxylang 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -24,7 +24,7 @@ proxylang 把这些关系直接写进代码:
24
24
  需要 **Node.js 24(最低 24.11.0)**。安装 npm 包:
25
25
 
26
26
  ```sh
27
- npm install --save-exact proxylang@0.1.2
27
+ npm install --save-exact proxylang@0.3.0
28
28
  npx proxylang --help
29
29
  ```
30
30
 
@@ -49,6 +49,37 @@ DEMO_PASSWORD=example-only vp exec node dist/cli.js build examples/clients.ts --
49
49
 
50
50
  [四客户端示例](examples/clients.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
51
51
 
52
+ ## 直接组合设备配置
53
+
54
+ Profile 的 `proxies` 同时容纳普通代理、WireGuard 和 Tailscale。规则、代理组、Host 和 General 均可直接组合嵌套数组;General 按顺序浅合并,后者整键覆盖。
55
+
56
+ ```ts
57
+ import { defineProfile, defineRoutes, outbound, proxy, secret, surge } from "proxylang";
58
+
59
+ const exit = proxy.trojan({
60
+ id: "edge",
61
+ server: "proxy.example.com",
62
+ port: 443,
63
+ password: secret("PASSWORD"),
64
+ });
65
+ const work = defineRoutes({ when: [surge.match.domainSuffix("github.com")], to: "edge" });
66
+ const local = defineRoutes({
67
+ when: [surge.match.domainSuffix("internal.example")],
68
+ to: outbound.direct,
69
+ });
70
+
71
+ const laptop = defineProfile({
72
+ target: { engine: "surge", platform: "macos", version: "6.10.0" },
73
+ proxies: [exit],
74
+ groups: [],
75
+ routes: [local, work],
76
+ fallback: "edge",
77
+ surge: { general: [{ loglevel: "notify" }], hosts: [] },
78
+ });
79
+ ```
80
+
81
+ 字符串目的地是当前 Profile 的资源 ID,不是显示名称;缺失引用会阻止构建。平台专属代理仍须满足目标能力。完整语义见[Profile 组合契约](docs/feature/target-compilation/profile-composition.md)。
82
+
52
83
  ## Usage
53
84
 
54
85
  将下面三个 TypeScript 代码块按顺序保存为项目中的 `proxy.config.ts`。
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Q as requestSchema, R as compile, U as targetCatalog, i as buildToDirectory, n as profileBuildFailure, q as StaticRuleSetUnknownError, r as runBuild, z as explain } from "./profile-build-jJlIs97b.js";
2
+ import { Q as requestSchema, R as compile, U as targetCatalog, i as buildToDirectory, n as profileBuildFailure, q as StaticRuleSetUnknownError, r as runBuild, z as explain } from "./profile-build-CA9qC6N2.js";
3
3
  import { open } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
package/dist/index.d.ts CHANGED
@@ -650,22 +650,26 @@ type ProfileCondition = Exclude<Match | SurgeCondition, {
650
650
  readonly noResolve?: boolean;
651
651
  readonly extendedMatching?: boolean;
652
652
  };
653
- type ProfileDestination = ProxyNode | ProxyGroupDefinition | SurgeTunnel | TailscaleEndpoint | {
653
+ type ProfileDestination = string | ProxyNode | ProxyGroupDefinition | SurgeTunnel | TailscaleEndpoint | {
654
654
  readonly builtin: "DIRECT" | "REJECT" | "REJECT-DROP" | "REJECT-NO-DROP" | "REJECT-TINYGIF";
655
655
  };
656
- type SurgeConfig = Pick<SurgeProfileInput, "managed" | "general" | "hosts" | "names">;
656
+ type Fragments<T> = readonly (T | Fragments<T>)[];
657
+ type ProfileProxy = ProxyNode | SurgeTunnel | TailscaleEndpoint;
658
+ type SurgeConfig = DeepReadonly<Pick<SurgeProfileInput, "managed" | "names">> & {
659
+ readonly general?: DeepReadonly<SurgeGeneral> | Fragments<DeepReadonly<SurgeGeneral>>;
660
+ readonly hosts?: Fragments<DeepReadonly<SurgeHost>>;
661
+ };
657
662
  type ProfileDefinition = {
658
663
  readonly target: SurgeProfileInput["target"] | {
659
664
  readonly engine: "sing-box";
660
665
  readonly platform: "macos" | "linux";
661
666
  readonly version: string;
662
667
  };
663
- readonly nodes: readonly ProxyNode[];
664
- readonly groups: readonly ProxyGroupDefinition[];
665
- readonly routes: readonly RouteDefinition[];
668
+ readonly proxies: Fragments<ProfileProxy>;
669
+ readonly groups: Fragments<ProxyGroupDefinition>;
670
+ readonly routes: Fragments<RouteDefinition>;
666
671
  readonly fallback: ProfileDestination;
667
- readonly endpoints?: readonly (SurgeTunnel | TailscaleEndpoint)[];
668
- readonly surge?: DeepReadonly<SurgeConfig>;
672
+ readonly surge?: SurgeConfig;
669
673
  readonly singBox?: {
670
674
  readonly mode: "fragment" | "standalone";
671
675
  readonly listener?: {
@@ -674,7 +678,12 @@ type ProfileDefinition = {
674
678
  };
675
679
  };
676
680
  };
677
- type Profile = DeepReadonly<ProfileDefinition>;
681
+ type Profile = DeepReadonly<Omit<ProfileDefinition, "proxies" | "groups" | "routes" | "surge"> & {
682
+ readonly proxies: readonly ProfileProxy[];
683
+ readonly groups: readonly ProxyGroupDefinition[];
684
+ readonly routes: readonly RouteDefinition[];
685
+ readonly surge?: Pick<SurgeProfileInput, "managed" | "general" | "hosts" | "names">;
686
+ }>;
678
687
  type ProfileCompilation = {
679
688
  readonly engine: "surge";
680
689
  readonly ok: boolean;
@@ -688,7 +697,7 @@ type ProfileCompilation = {
688
697
  readonly ok: false;
689
698
  readonly code: string;
690
699
  };
691
- declare function surgeConfig(input: SurgeConfig): DeepReadonly<SurgeConfig>;
700
+ declare function surgeConfig(input: SurgeConfig): SurgeConfig;
692
701
  export declare function defineProfile(input: ProfileDefinition | Profile): Profile;
693
702
  /** No secrets or I/O. All engine adaptations retain strict validation. */
694
703
  export declare function compileProfile(input: ProfileDefinition | Profile): ProfileCompilation;
@@ -958,7 +967,7 @@ type BuildContext = {
958
967
  readonly validation: boolean;
959
968
  };
960
969
  type BuildDefinition = {
961
- readonly profiles: Readonly<Record<string, Profile>>;
970
+ readonly profiles: Readonly<Record<string, Profile | ProfileDefinition>>;
962
971
  readonly preflight?: () => readonly string[];
963
972
  readonly resolveSecret?: (token: Secret, context: BuildContext) => string | undefined;
964
973
  };
@@ -974,4 +983,4 @@ export declare function runBuild(input: BuildDefinition, output: string, options
974
983
  readonly validation?: boolean;
975
984
  }): Promise<ProfileBuildResult>;
976
985
  //#endregion
977
- export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
986
+ export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as defineRoute, B as compileStrategyGroups, C as strategy, D as defineProfile, E as compileProfile, F as renderSurgeProfile, G as surgeProxy, H as nativeNameSchema, I as renderSurgeProfiles, J as assertData, K as validateProxyOptions, L as secretReader, M as outbound, N as selectProxies, O as ProfileDefinitionError, P as compileSurgeProfile, R as compile, S as slot, T as use, U as targetCatalog, V as isReservedNativeName, W as RenderError, X as idSchema, Y as deepFreeze, Z as nodeSchema, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as defineRoutes, k as defineProxyGroup, l as group, m as reject, o as block, p as proxy, q as StaticRuleSetUnknownError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as explain } from "./profile-build-jJlIs97b.js";
1
+ import { A as defineRoute, B as compileStrategyGroups, C as strategy, D as defineProfile, E as compileProfile, F as renderSurgeProfile, G as surgeProxy, H as nativeNameSchema, I as renderSurgeProfiles, J as assertData, K as validateProxyOptions, L as secretReader, M as outbound, N as selectProxies, O as ProfileDefinitionError, P as compileSurgeProfile, R as compile, S as slot, T as use, U as targetCatalog, V as isReservedNativeName, W as RenderError, X as idSchema, Y as deepFreeze, Z as nodeSchema, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as defineRoutes, k as defineProxyGroup, l as group, m as reject, o as block, p as proxy, q as StaticRuleSetUnknownError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as explain } from "./profile-build-CA9qC6N2.js";
2
2
  import { z } from "zod";
3
3
  //#region src/proxy-fragments.ts
4
4
  const inputSchema = z.strictObject({
@@ -1596,6 +1596,8 @@ const generalSchema = z.strictObject({
1596
1596
  "socks5-listen": listener.optional(),
1597
1597
  "proxy-restricted-to-lan": z.boolean().optional()
1598
1598
  });
1599
+ /** Internal fragment validation; caller must inspect data descriptors before invoking. */
1600
+ const validateSurgeGeneral = (input) => generalSchema.safeParse(input).success;
1599
1601
  const hostSchema = z.strictObject({
1600
1602
  pattern: hostPattern,
1601
1603
  address: z.union([ip, domain]).optional(),
@@ -2136,6 +2138,10 @@ function lowerSurgeProfile(input) {
2136
2138
  });
2137
2139
  }
2138
2140
  function lower(destination) {
2141
+ if (typeof destination === "string") {
2142
+ if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
2143
+ return { ref: destination };
2144
+ }
2139
2145
  if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
2140
2146
  if ("builtin" in destination) {
2141
2147
  exactDefinition(destination, ["builtin"]);
@@ -2304,11 +2310,10 @@ function defineProfile(input) {
2304
2310
  inspectDefinition(input);
2305
2311
  exactDefinition(input, [
2306
2312
  "target",
2307
- "nodes",
2313
+ "proxies",
2308
2314
  "groups",
2309
2315
  "routes",
2310
2316
  "fallback",
2311
- "endpoints",
2312
2317
  "surge",
2313
2318
  "singBox"
2314
2319
  ]);
@@ -2328,8 +2333,76 @@ function defineProfile(input) {
2328
2333
  if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2329
2334
  if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
2330
2335
  }
2331
- if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.endpoints !== void 0 && !Array.isArray(input.endpoints)) fail("INVALID_PROFILE_DEFINITION");
2332
- return snapshotProfile(input);
2336
+ let remaining = 1e5;
2337
+ function flatten(fragments) {
2338
+ if (!Array.isArray(fragments)) fail("INVALID_PROFILE_DEFINITION");
2339
+ const result = [];
2340
+ function visit(value) {
2341
+ if (--remaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2342
+ if (Array.isArray(value)) for (const item of value) visit(item);
2343
+ else {
2344
+ if (!value || typeof value !== "object") fail("INVALID_PROFILE_DEFINITION");
2345
+ result.push(value);
2346
+ }
2347
+ }
2348
+ visit(fragments);
2349
+ return result;
2350
+ }
2351
+ const proxies = flatten(input.proxies);
2352
+ const groups = flatten(input.groups);
2353
+ const routes = flatten(input.routes);
2354
+ let surge;
2355
+ if (input.surge !== void 0) {
2356
+ let general;
2357
+ if (input.surge.general !== void 0) {
2358
+ general = {};
2359
+ const checked = /* @__PURE__ */ new Set();
2360
+ const costs = /* @__PURE__ */ new Map();
2361
+ let validationRemaining = 1e5;
2362
+ function cost(value) {
2363
+ if (!value || typeof value !== "object") return 1;
2364
+ const cached = costs.get(value);
2365
+ if (cached !== void 0) return cached;
2366
+ let total = 1;
2367
+ for (const item of Object.values(value)) {
2368
+ total += cost(item);
2369
+ if (total > 1e5) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2370
+ }
2371
+ costs.set(value, total);
2372
+ return total;
2373
+ }
2374
+ const fragments = Array.isArray(input.surge.general) ? input.surge.general : [input.surge.general];
2375
+ for (const fragment of flatten(fragments)) {
2376
+ if (!checked.has(fragment)) {
2377
+ validationRemaining -= cost(fragment);
2378
+ if (validationRemaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2379
+ if (!validateSurgeGeneral(fragment)) fail("INVALID_SURGE_GENERAL");
2380
+ checked.add(fragment);
2381
+ }
2382
+ Object.assign(general, fragment);
2383
+ }
2384
+ }
2385
+ surge = {
2386
+ ...input.surge,
2387
+ ...general === void 0 ? {} : { general },
2388
+ ...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
2389
+ };
2390
+ }
2391
+ const { surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2392
+ return snapshotProfile({
2393
+ ...rest,
2394
+ proxies,
2395
+ groups,
2396
+ routes,
2397
+ ...surge === void 0 ? {} : { surge }
2398
+ });
2399
+ }
2400
+ function isEndpoint(proxy) {
2401
+ return [
2402
+ "wireguard",
2403
+ "tailscale",
2404
+ "sing-box-tailscale"
2405
+ ].includes(proxy.type);
2333
2406
  }
2334
2407
  function surgeCondition$1(condition, depth = 0) {
2335
2408
  if (depth > 10) return fail("LOGICAL_DEPTH_EXCEEDED");
@@ -2371,14 +2444,16 @@ function compileProfile(input) {
2371
2444
  try {
2372
2445
  const profile = defineProfile(input);
2373
2446
  snapshotDefinition(profile.routes.map((route) => route.when));
2447
+ const nodes = profile.proxies.filter((proxy) => !isEndpoint(proxy));
2448
+ const endpoints = profile.proxies.filter(isEndpoint);
2374
2449
  if (profile.target.engine === "surge") {
2375
2450
  if (profile.singBox !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2376
- if (profile.endpoints?.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2451
+ if (endpoints.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2377
2452
  const compilation = compileSurgeProfile(lowerSurgeProfile({
2378
2453
  target: profile.target,
2379
2454
  ...profile.surge,
2380
- nodes: profile.nodes,
2381
- tunnels: profile.endpoints,
2455
+ nodes,
2456
+ tunnels: endpoints,
2382
2457
  groups: profile.groups,
2383
2458
  routes: profile.routes.map((route) => ({
2384
2459
  ...route,
@@ -2394,18 +2469,21 @@ function compileProfile(input) {
2394
2469
  }
2395
2470
  if (profile.target.engine !== "sing-box") return fail("PROFILE_TARGET_UNSUPPORTED");
2396
2471
  if (profile.surge !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2397
- if (profile.endpoints?.some((endpoint) => endpoint.type !== "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2472
+ if (endpoints.some((endpoint) => endpoint.type !== "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2398
2473
  const registry = /* @__PURE__ */ new Map();
2399
- for (const resource of [
2400
- ...profile.nodes,
2401
- ...profile.groups,
2402
- ...profile.endpoints ?? []
2403
- ]) {
2474
+ for (const resource of [...profile.proxies, ...profile.groups]) {
2404
2475
  if (!resource || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
2405
2476
  if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
2406
2477
  registry.set(resource.id, resource);
2407
2478
  }
2408
2479
  const lower = (destination) => {
2480
+ if (typeof destination === "string") {
2481
+ if (!registry.has(destination)) return fail("UNKNOWN_DESTINATION_ID");
2482
+ return {
2483
+ type: "route",
2484
+ to: destination
2485
+ };
2486
+ }
2409
2487
  if (!destination || typeof destination !== "object") return fail("INVALID_DESTINATION");
2410
2488
  if ("builtin" in destination) {
2411
2489
  exactDefinition(destination, ["builtin"]);
@@ -2419,57 +2497,55 @@ function compileProfile(input) {
2419
2497
  to: destination.id
2420
2498
  };
2421
2499
  };
2422
- const groups = profile.groups.map((definition) => {
2423
- exactDefinition(definition, [
2424
- "type",
2425
- "id",
2426
- "name",
2427
- "algorithm",
2428
- "members",
2429
- "url",
2430
- "intervalSeconds",
2431
- "timeoutSeconds"
2432
- ]);
2433
- if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2434
- if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2435
- exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2436
- "type",
2437
- "url",
2438
- "intervalSeconds",
2439
- "toleranceMs"
2440
- ] : ["type"]);
2441
- const members = definition.members.map((member) => {
2442
- const action = lower(member);
2443
- if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2444
- return action.to;
2445
- });
2446
- return {
2447
- ...definition.algorithm,
2448
- id: definition.id,
2449
- members
2450
- };
2451
- });
2452
- const routing = profile.routes.map((route, index) => {
2453
- exactDefinition(route, [
2454
- "type",
2455
- "when",
2456
- "to"
2457
- ]);
2458
- if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2459
- return {
2460
- type: "rule",
2461
- id: `route-${index + 1}`,
2462
- when: route.when,
2463
- then: lower(route.to)
2464
- };
2465
- });
2466
2500
  const compilation = compile(snapshotDefinition({
2467
2501
  programs: { profile: {
2468
2502
  engine: "sing-box",
2469
- nodes: profile.nodes,
2470
- endpoints: profile.endpoints,
2471
- groups,
2472
- routing,
2503
+ nodes,
2504
+ 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
+ }),
2473
2549
  fallback: lower(profile.fallback),
2474
2550
  ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
2475
2551
  } },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Composable routing policies in TypeScript with explicit platform targets",
5
5
  "homepage": "https://github.com/CorrectRoadH/proxylang#readme",
6
6
  "bugs": {