proxylang 0.1.7 → 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 { H as compile, U as explain, Z as StaticRuleSetUnknownError, a as surgeBuildFailure, i as runSurgeBuild, n as runBuild, nt as requestSchema, q as targetCatalog, s as buildToDirectory } from "./profile-build-BLB8hvyw.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";
@@ -16,7 +16,6 @@ const failure = (code) => {
16
16
  };
17
17
  const usages = {
18
18
  "profile-build": ["proxylang profile-build config.ts --out DIRECTORY [--validation]"],
19
- "surge-build": ["proxylang surge-build config.ts --out DIRECTORY [--validation]"],
20
19
  targets: ["proxylang targets"],
21
20
  check: ["proxylang check config.ts"],
22
21
  explain: ["proxylang explain config.ts --target ID --request JSON", "proxylang explain config.ts --target ID --request-file FILE"],
@@ -85,7 +84,7 @@ async function main(args) {
85
84
  });
86
85
  return 0;
87
86
  }
88
- if (command === "surge-build" || command === "profile-build") return surgeBuildCommand(file, rest, command === "profile-build");
87
+ if (command === "profile-build") return profileBuildCommand(file, rest);
89
88
  if (![
90
89
  "check",
91
90
  "explain",
@@ -166,9 +165,9 @@ async function main(args) {
166
165
  });
167
166
  return built.exitCode;
168
167
  }
169
- async function surgeBuildCommand(file, args, portable) {
168
+ async function profileBuildCommand(file, args) {
170
169
  const invalid = () => {
171
- print(surgeBuildFailure("INVALID_ARGUMENTS"));
170
+ print(profileBuildFailure("INVALID_ARGUMENTS"));
172
171
  return 1;
173
172
  };
174
173
  if (!file?.trim() || file.startsWith("-")) return invalid();
@@ -192,10 +191,10 @@ async function surgeBuildCommand(file, args, portable) {
192
191
  const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
193
192
  config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
194
193
  } catch {
195
- print(surgeBuildFailure("PROFILE_DEFINITION_FAILED", validation));
194
+ print(profileBuildFailure("PROFILE_DEFINITION_FAILED", validation));
196
195
  return 1;
197
196
  }
198
- const result = portable ? await runBuild(config, output, { validation }) : await runSurgeBuild(config, output, { validation });
197
+ const result = await runBuild(config, output, { validation });
199
198
  print(result);
200
199
  return result.exitCode;
201
200
  }
package/dist/index.d.ts CHANGED
@@ -586,31 +586,20 @@ export declare function compile(input: unknown): Compilation;
586
586
  export declare function explain(compilation: Compilation, target: string, request: Request): Explanation;
587
587
  //#endregion
588
588
  //#region src/surge-definitions.d.ts
589
- type Builtin = Extract<SurgePolicy, {
590
- builtin: string;
591
- }>;
592
- type Destination = ProxyNode | ProxyGroupDefinition | SurgeTunnel | Builtin;
593
- interface ProxyGroupDefinition<A extends GroupAlgorithm = Extract<GroupAlgorithm, {
594
- type: "select" | "surge-smart";
595
- }>, D extends ProfileDestination = Destination> {
589
+ interface ProxyGroupDefinition {
596
590
  readonly type: "proxy-group";
597
591
  readonly id: string;
598
592
  readonly name: string;
599
- readonly algorithm: A;
600
- readonly members: readonly D[];
593
+ readonly algorithm: GroupAlgorithm;
594
+ readonly members: readonly ProfileDestination[];
601
595
  readonly url?: string;
602
596
  readonly intervalSeconds?: number;
603
597
  readonly timeoutSeconds?: number;
604
598
  }
605
- type RouteDefinition<C extends ProfileCondition = SurgeCondition, D extends ProfileDestination = Destination> = {
599
+ type RouteDefinition = {
606
600
  readonly type: "route";
607
- readonly when: C;
608
- readonly to: D;
609
- };
610
- type SurgeProfileDefinition = Omit<SurgeProfileInput, "groups" | "rules" | "fallback"> & {
611
- readonly groups: readonly ProxyGroupDefinition[];
612
- readonly routes: readonly RouteDefinition[];
613
- readonly fallback: Destination;
601
+ readonly when: ProfileCondition;
602
+ readonly to: ProfileDestination;
614
603
  };
615
604
  export declare class ProfileDefinitionError extends Error {
616
605
  readonly code: string;
@@ -633,19 +622,18 @@ export declare const outbound: {
633
622
  readonly builtin: "REJECT-TINYGIF";
634
623
  }>;
635
624
  };
636
- export declare function defineProxyGroup<A extends GroupAlgorithm, D extends ProfileDestination>(input: Omit<ProxyGroupDefinition<A, D>, "type">): ProxyGroupDefinition<A, D>;
637
- export declare function defineRoute<C extends ProfileCondition, D extends ProfileDestination>(input: Omit<RouteDefinition<C, D>, "type">): RouteDefinition<C, D>;
638
- export declare function defineRoutes<C extends ProfileCondition, D extends ProfileDestination>(input: {
639
- readonly when: readonly C[];
640
- readonly to: D;
641
- }): RouteDefinition<C, D>[];
625
+ export declare function defineProxyGroup(input: Omit<ProxyGroupDefinition, "type">): ProxyGroupDefinition;
626
+ export declare function defineRoute(input: Omit<RouteDefinition, "type">): RouteDefinition;
627
+ export declare function defineRoutes(input: {
628
+ readonly when: readonly ProfileCondition[];
629
+ readonly to: ProfileDestination;
630
+ }): RouteDefinition[];
642
631
  export declare function selectProxies(nodes: readonly ProxyNode[], query?: {
643
632
  ids?: readonly string[];
644
633
  regions?: readonly string[];
645
634
  providers?: readonly string[];
646
635
  tags?: readonly string[];
647
636
  }): ProxyNode[];
648
- export declare function defineSurgeProfile(input: SurgeProfileDefinition): SurgeProfileInput;
649
637
  //#endregion
650
638
  //#region src/profile.d.ts
651
639
  type DeepReadonly<T> = T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]>; } : T;
@@ -662,23 +650,26 @@ type ProfileCondition = Exclude<Match | SurgeCondition, {
662
650
  readonly noResolve?: boolean;
663
651
  readonly extendedMatching?: boolean;
664
652
  };
665
- interface ProfileProxyGroup extends ProxyGroupDefinition<GroupAlgorithm, ProfileDestination> {}
666
- type ProfileDestination = ProxyNode | ProfileProxyGroup | SurgeTunnel | TailscaleEndpoint | {
653
+ type ProfileDestination = string | ProxyNode | ProxyGroupDefinition | SurgeTunnel | TailscaleEndpoint | {
667
654
  readonly builtin: "DIRECT" | "REJECT" | "REJECT-DROP" | "REJECT-NO-DROP" | "REJECT-TINYGIF";
668
655
  };
669
- 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
+ };
670
662
  type ProfileDefinition = {
671
663
  readonly target: SurgeProfileInput["target"] | {
672
664
  readonly engine: "sing-box";
673
665
  readonly platform: "macos" | "linux";
674
666
  readonly version: string;
675
667
  };
676
- readonly nodes: readonly ProxyNode[];
677
- readonly groups: readonly ProxyGroupDefinition<GroupAlgorithm, ProfileDestination>[];
678
- readonly routes: readonly RouteDefinition<ProfileCondition, ProfileDestination>[];
668
+ readonly proxies: Fragments<ProfileProxy>;
669
+ readonly groups: Fragments<ProxyGroupDefinition>;
670
+ readonly routes: Fragments<RouteDefinition>;
679
671
  readonly fallback: ProfileDestination;
680
- readonly endpoints?: readonly (SurgeTunnel | TailscaleEndpoint)[];
681
- readonly surge?: DeepReadonly<SurgeConfig>;
672
+ readonly surge?: SurgeConfig;
682
673
  readonly singBox?: {
683
674
  readonly mode: "fragment" | "standalone";
684
675
  readonly listener?: {
@@ -687,7 +678,12 @@ type ProfileDefinition = {
687
678
  };
688
679
  };
689
680
  };
690
- 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
+ }>;
691
687
  type ProfileCompilation = {
692
688
  readonly engine: "surge";
693
689
  readonly ok: boolean;
@@ -701,7 +697,7 @@ type ProfileCompilation = {
701
697
  readonly ok: false;
702
698
  readonly code: string;
703
699
  };
704
- declare function surgeConfig(input: SurgeConfig): DeepReadonly<SurgeConfig>;
700
+ declare function surgeConfig(input: SurgeConfig): SurgeConfig;
705
701
  export declare function defineProfile(input: ProfileDefinition | Profile): Profile;
706
702
  /** No secrets or I/O. All engine adaptations retain strict validation. */
707
703
  export declare function compileProfile(input: ProfileDefinition | Profile): ProfileCompilation;
@@ -966,22 +962,12 @@ type ProxyNodeArtifact = {
966
962
  export declare function compileProxyNodes(input: unknown): ProxyNodeCompilation;
967
963
  export declare function renderProxyNodes(compilation: ProxyNodeCompilation, resolveSecret: (token: Secret) => string | undefined): ProxyNodeArtifact;
968
964
  //#endregion
969
- //#region src/surge-compose.d.ts
970
- /** Bind shared names only for included resources; explicit input mappings remain compiler-checked. */
971
- export declare function surgeProfile(input: SurgeProfileInput, names?: Readonly<Record<string, string>>): SurgeProfileInput;
972
- /** Stable queries produce native-profile policy references without consumer mapping code. */
973
- export declare function surgeMembers(nodes: readonly ProxyNode[], query?: Parameters<typeof selectNodes>[1]): SurgePolicy[];
974
- //#endregion
975
- //#region src/surge-host.d.ts
976
- /** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
977
- export declare function buildSurgeProfilesToDirectory(profiles: Readonly<Record<string, SurgeProfileInput>>, output: string, resolveSecret?: (token: Secret) => string | undefined): Promise<BuildResult>;
978
- //#endregion
979
- //#region src/build-core.d.ts
965
+ //#region src/profile-build.d.ts
980
966
  type BuildContext = {
981
967
  readonly validation: boolean;
982
968
  };
983
- type BuildDefinition$1<T> = {
984
- readonly profiles: Readonly<Record<string, T>>;
969
+ type BuildDefinition = {
970
+ readonly profiles: Readonly<Record<string, Profile | ProfileDefinition>>;
985
971
  readonly preflight?: () => readonly string[];
986
972
  readonly resolveSecret?: (token: Secret, context: BuildContext) => string | undefined;
987
973
  };
@@ -990,21 +976,11 @@ type ProfileBuildResult = BuildResult & {
990
976
  readonly validation: boolean;
991
977
  readonly profileCount: number;
992
978
  };
993
- //#endregion
994
- //#region src/surge-build.d.ts
995
- type SurgeBuildContext = BuildContext;
996
- type SurgeBuildDefinition = BuildDefinition$1<SurgeProfileInput>;
997
- type SurgeBuildResult = ProfileBuildResult;
998
- export declare function defineSurgeBuild(input: SurgeBuildDefinition): SurgeBuildDefinition;
999
- export declare function runSurgeBuild(input: SurgeBuildDefinition, output: string, options?: {
1000
- readonly validation?: boolean;
1001
- }): Promise<SurgeBuildResult>;
1002
- //#endregion
1003
- //#region src/profile-build.d.ts
1004
- type BuildDefinition = BuildDefinition$1<Profile>;
979
+ /** Capture data and callback references before application preflight can change its source. */
1005
980
  export declare function defineBuild(input: BuildDefinition): BuildDefinition;
981
+ /** Pure orchestration result; the CLI owns stdout and process exit status. */
1006
982
  export declare function runBuild(input: BuildDefinition, output: string, options?: {
1007
983
  readonly validation?: boolean;
1008
984
  }): Promise<ProfileBuildResult>;
1009
985
  //#endregion
1010
- export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Destination, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeBuildContext, SurgeBuildDefinition, SurgeBuildResult, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileDefinition, 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 { $ as deepFreeze, A as defineProfile, B as renderSurgeProfiles, C as sequence, D as surge, E as strategy, F as defineSurgeProfile, G as isReservedNativeName, H as compile, I as outbound, J as RenderError, K as nativeNameSchema, L as selectProxies, M as defineProxyGroup, N as defineRoute, O as use, P as defineRoutes, Q as assertData, R as compileSurgeProfile, S as selectNodes, T as slot, U as explain, V as secretReader, W as compileStrategyGroups, X as validateProxyOptions, Y as surgeProxy, Z as StaticRuleSetUnknownError, _ as reject, b as ruleSet, c as render, d as direct, et as idSchema, f as group, g as proxy, h as policy, i as runSurgeBuild, j as ProfileDefinitionError, k as compileProfile, l as block, m as mihomo, n as runBuild, o as buildSurgeProfilesToDirectory, p as match, q as targetCatalog, r as defineSurgeBuild, s as buildToDirectory, t as defineBuild, tt as nodeSchema, u as defineConfig, v as route, w as singbox, x as secret, y as rule, z as renderSurgeProfile } from "./profile-build-BLB8hvyw.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({
@@ -129,23 +129,4 @@ function renderProxyNodes(compilation, resolveSecret) {
129
129
  });
130
130
  }
131
131
  //#endregion
132
- //#region src/surge-compose.ts
133
- /** Bind shared names only for included resources; explicit input mappings remain compiler-checked. */
134
- function surgeProfile(input, names = {}) {
135
- const bindings = {};
136
- for (const node of input.nodes) bindings[node.id] = names[node.id] ?? node.label ?? node.id;
137
- for (const resource of [...input.tunnels ?? [], ...input.groups]) bindings[resource.id] = names[resource.id] ?? resource.id;
138
- return {
139
- ...input,
140
- names: {
141
- ...bindings,
142
- ...input.names
143
- }
144
- };
145
- }
146
- /** Stable queries produce native-profile policy references without consumer mapping code. */
147
- function surgeMembers(nodes, query = {}) {
148
- return selectNodes(nodes, query).map((ref) => ({ ref }));
149
- }
150
- //#endregion
151
- export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildSurgeProfilesToDirectory, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, defineSurgeBuild, defineSurgeProfile, direct, explain, group, match, mihomo, outbound, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, runSurgeBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, surgeMembers, surgeProfile, targetCatalog, use };
132
+ export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
@@ -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(),
@@ -2101,7 +2103,7 @@ function selectProxies(nodes, query = {}) {
2101
2103
  for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
2102
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))));
2103
2105
  }
2104
- function defineSurgeProfile(input) {
2106
+ function lowerSurgeProfile(input) {
2105
2107
  inspectDefinition(input);
2106
2108
  exactDefinition(input, [
2107
2109
  "target",
@@ -2136,6 +2138,10 @@ function defineSurgeProfile(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");
2377
- const compilation = compileSurgeProfile(defineSurgeProfile({
2451
+ if (endpoints.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
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
  } },
@@ -3094,14 +3170,8 @@ async function publishProfiles(files, surgeDirectory, io = { rename }) {
3094
3170
  if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
3095
3171
  }
3096
3172
  //#endregion
3097
- //#region src/surge-host.ts
3098
- /** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
3099
- async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (token) => process.env[token.name]) {
3100
- if (typeof output !== "string" || !output.trim()) return {
3101
- published: false,
3102
- exitCode: 1,
3103
- code: "INVALID_OUTPUT_DIRECTORY"
3104
- };
3173
+ //#region src/profile-build.ts
3174
+ async function publish(profiles, output, resolver) {
3105
3175
  try {
3106
3176
  const entries = Object.entries(profiles);
3107
3177
  if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
@@ -3109,14 +3179,26 @@ async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (
3109
3179
  exitCode: 1,
3110
3180
  code: "INVALID_PROFILE_FILENAMES"
3111
3181
  };
3112
- const compiled = entries.map(([, input]) => compileSurgeProfile(input));
3113
- if (compiled.some((profile) => !profile.ok)) return {
3182
+ const compiled = entries.map(([, profile]) => compileProfile(profile));
3183
+ const invalid = compiled.find((profile) => !profile.ok);
3184
+ if (invalid) return {
3185
+ published: false,
3186
+ exitCode: 1,
3187
+ code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
3188
+ };
3189
+ if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(resolve(output), endpoint.stateDirectory))))) return {
3114
3190
  published: false,
3115
3191
  exitCode: 1,
3116
- code: "COMPILATION_FAILED"
3192
+ code: "ENDPOINT_STATE_OVERLAP"
3117
3193
  };
3118
- const artifacts = renderSurgeProfiles(compiled, resolveSecret);
3119
- await publishProfiles(new Map(entries.map(([id], i) => [`${id}.conf`, artifacts[i].content])), output);
3194
+ const read = secretReader(resolver);
3195
+ const files = /* @__PURE__ */ new Map();
3196
+ for (const [index, profile] of compiled.entries()) {
3197
+ if (profile.engine === "invalid") throw new Error();
3198
+ const artifacts = profile.engine === "surge" ? renderSurgeProfiles([profile.compilation], read) : render(profile.compilation, read);
3199
+ files.set(`${entries[index][0]}.${profile.engine === "surge" ? "conf" : "json"}`, artifacts[0].content);
3200
+ }
3201
+ await publishProfiles(files, output);
3120
3202
  return {
3121
3203
  published: true,
3122
3204
  exitCode: 0,
@@ -3138,8 +3220,6 @@ async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (
3138
3220
  };
3139
3221
  }
3140
3222
  }
3141
- //#endregion
3142
- //#region src/build-core.ts
3143
3223
  function record(value, keys) {
3144
3224
  if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3145
3225
  for (const key of Reflect.ownKeys(value)) {
@@ -3148,7 +3228,7 @@ function record(value, keys) {
3148
3228
  }
3149
3229
  }
3150
3230
  /** Capture data and callback references before application preflight can change its source. */
3151
- function captureBuild(input, snapshot) {
3231
+ function defineBuild(input) {
3152
3232
  try {
3153
3233
  record(input, [
3154
3234
  "profiles",
@@ -3158,7 +3238,7 @@ function captureBuild(input, snapshot) {
3158
3238
  record(input.profiles);
3159
3239
  for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
3160
3240
  return Object.freeze({
3161
- profiles: deepFreeze(snapshot(input.profiles)),
3241
+ profiles: snapshotProfile(input.profiles),
3162
3242
  ...input.preflight === void 0 ? {} : { preflight: input.preflight },
3163
3243
  ...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
3164
3244
  });
@@ -3177,7 +3257,7 @@ function profileBuildFailure(code, validation = false, profileCount = 0) {
3177
3257
  };
3178
3258
  }
3179
3259
  /** Pure orchestration result; the CLI owns stdout and process exit status. */
3180
- async function executeBuild(input, output, options, capture, publish) {
3260
+ async function runBuild(input, output, options = {}) {
3181
3261
  let validation;
3182
3262
  try {
3183
3263
  record(options, ["validation"]);
@@ -3188,7 +3268,7 @@ async function executeBuild(input, output, options, capture, publish) {
3188
3268
  }
3189
3269
  let definition;
3190
3270
  try {
3191
- definition = capture(input);
3271
+ definition = defineBuild(input);
3192
3272
  } catch {
3193
3273
  return profileBuildFailure("INVALID_BUILD_DEFINITION", validation);
3194
3274
  }
@@ -3220,70 +3300,4 @@ async function executeBuild(input, output, options, capture, publish) {
3220
3300
  };
3221
3301
  }
3222
3302
  //#endregion
3223
- //#region src/surge-build.ts
3224
- const surgeBuildFailure = profileBuildFailure;
3225
- function defineSurgeBuild(input) {
3226
- return captureBuild(input, snapshotDefinition);
3227
- }
3228
- function runSurgeBuild(input, output, options = {}) {
3229
- return executeBuild(input, output, options, defineSurgeBuild, buildSurgeProfilesToDirectory);
3230
- }
3231
- //#endregion
3232
- //#region src/profile-build.ts
3233
- function defineBuild(input) {
3234
- return captureBuild(input, snapshotProfile);
3235
- }
3236
- async function publish(profiles, output, resolver) {
3237
- try {
3238
- const entries = Object.entries(profiles);
3239
- if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
3240
- published: false,
3241
- exitCode: 1,
3242
- code: "INVALID_PROFILE_FILENAMES"
3243
- };
3244
- const compiled = entries.map(([, profile]) => compileProfile(profile));
3245
- const invalid = compiled.find((profile) => !profile.ok);
3246
- if (invalid) return {
3247
- published: false,
3248
- exitCode: 1,
3249
- code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
3250
- };
3251
- if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(resolve(output), endpoint.stateDirectory))))) return {
3252
- published: false,
3253
- exitCode: 1,
3254
- code: "ENDPOINT_STATE_OVERLAP"
3255
- };
3256
- const read = secretReader(resolver);
3257
- const files = /* @__PURE__ */ new Map();
3258
- for (const [index, profile] of compiled.entries()) {
3259
- if (profile.engine === "invalid") throw new Error();
3260
- const artifacts = profile.engine === "surge" ? renderSurgeProfiles([profile.compilation], read) : render(profile.compilation, read);
3261
- files.set(`${entries[index][0]}.${profile.engine === "surge" ? "conf" : "json"}`, artifacts[0].content);
3262
- }
3263
- await publishProfiles(files, output);
3264
- return {
3265
- published: true,
3266
- exitCode: 0,
3267
- code: "PUBLISHED",
3268
- active: join(resolve(output), "out")
3269
- };
3270
- } catch (error) {
3271
- if (error instanceof SurgePublishError) return {
3272
- published: error.published,
3273
- exitCode: error.published ? 2 : 1,
3274
- code: error.message,
3275
- ...error.published ? { active: join(resolve(output), "out") } : {},
3276
- ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
3277
- };
3278
- return {
3279
- published: false,
3280
- exitCode: 1,
3281
- code: error instanceof RenderError ? error.code : "BUILD_FAILED"
3282
- };
3283
- }
3284
- }
3285
- function runBuild(input, output, options = {}) {
3286
- return executeBuild(input, output, options, defineBuild, publish);
3287
- }
3288
- //#endregion
3289
- export { deepFreeze as $, defineProfile as A, renderSurgeProfiles as B, sequence as C, surge$1 as D, strategy as E, defineSurgeProfile as F, isReservedNativeName as G, compile as H, outbound as I, RenderError as J, nativeNameSchema as K, selectProxies as L, defineProxyGroup as M, defineRoute as N, use as O, defineRoutes as P, assertData as Q, compileSurgeProfile as R, selectNodes as S, slot as T, explain as U, secretReader as V, compileStrategyGroups as W, validateProxyOptions as X, surgeProxy as Y, StaticRuleSetUnknownError as Z, reject as _, surgeBuildFailure as a, ruleSet as b, render as c, direct as d, idSchema as et, group as f, proxy as g, policy as h, runSurgeBuild as i, ProfileDefinitionError as j, compileProfile as k, block as l, mihomo as m, runBuild as n, requestSchema as nt, buildSurgeProfilesToDirectory as o, match as p, targetCatalog as q, defineSurgeBuild as r, buildToDirectory as s, defineBuild as t, nodeSchema as tt, defineConfig as u, route as v, singbox$1 as w, secret as x, rule as y, renderSurgeProfile as z };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.1.7",
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": {