@superdurable/connector-west 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Super Durable
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # West TypeScript connector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@superdurable/connector-west` reads one reseller domain page, returning domain names and expiration dates. It signs each read with the current username, API password, and Unix millisecond timestamp. The password stays outside Flow input and output. Responses are decoded as GBK, matching West.cn.
4
+
5
+ `examples/basic/` runs a Dex Flow, Worker, and Client. `npm run check` replays Go provider scenarios; `npm run test:integration` uses a synthetic provider with real Dex retry and persistence. Live reseller authorization is unverified.
@@ -0,0 +1,65 @@
1
+ {
2
+ "connectorId": "west",
3
+ "releaseTag": "connectors/west/go/v0.1.0",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-west",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newListDomainsStep",
12
+ "kind": "query",
13
+ "operationId": "listDomains",
14
+ "inputType": "ListDomainsInput",
15
+ "description": "Read one page of domain names and expiration dates.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "listed",
25
+ "field": "listed",
26
+ "optional": false
27
+ },
28
+ {
29
+ "id": "providerRejected",
30
+ "field": "providerRejected",
31
+ "optional": true
32
+ },
33
+ {
34
+ "id": "invalidResponse",
35
+ "field": "invalidResponse",
36
+ "optional": true
37
+ },
38
+ {
39
+ "id": "defect",
40
+ "field": "defect",
41
+ "optional": true
42
+ }
43
+ ],
44
+ "inputSchema": {
45
+ "additionalProperties": false,
46
+ "description": "ListDomainsInput selects one reseller domain page. Zero page and limit use 1 and 20.",
47
+ "properties": {
48
+ "limit": {
49
+ "description": "Limit is the number of domains to request, from 1 to 100; zero uses 20.",
50
+ "type": "integer"
51
+ },
52
+ "page": {
53
+ "description": "Page is the one-based page number; zero selects the first page.",
54
+ "type": "integer"
55
+ }
56
+ },
57
+ "required": [
58
+ "limit",
59
+ "page"
60
+ ],
61
+ "type": "object"
62
+ }
63
+ }
64
+ ]
65
+ }
@@ -0,0 +1,128 @@
1
+ // src/generated/models.ts
2
+ import { z } from "zod";
3
+ import { SecretString } from "@superdurable/connectors-sdk";
4
+ var ConfigSchema = z.object({
5
+ "baseUrl": z.string().optional(),
6
+ "timeoutMs": z.number().int().optional(),
7
+ "maxResponseBytes": z.number().int().optional()
8
+ });
9
+ var CredentialMaterialError = class extends TypeError {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "CredentialMaterialError";
13
+ }
14
+ };
15
+ var sdkCredentialDecodingFailureMessages = /* @__PURE__ */ new Set([
16
+ "project credential decoding failed",
17
+ "shared project credential decoding failed",
18
+ "project credential decoding failed: this connector version does not support shared credentials"
19
+ ]);
20
+ function isCredentialMaterialError(error) {
21
+ return error instanceof CredentialMaterialError || error instanceof TypeError && sdkCredentialDecodingFailureMessages.has(error.message);
22
+ }
23
+ function decodeCredentials(value) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
25
+ const fields = value;
26
+ const allowed = /* @__PURE__ */ new Set(["api_password", "username"]);
27
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
28
+ if (fields["api_password"] != null && !(typeof fields["api_password"] === "string")) throw new CredentialMaterialError("credential api_password has an invalid type");
29
+ if (fields["username"] != null && !(typeof fields["username"] === "string")) throw new CredentialMaterialError("credential username has an invalid type");
30
+ const credentials = {};
31
+ if (!fields["username"]) throw new CredentialMaterialError("credential username is required");
32
+ credentials.username = fields["username"] ?? "";
33
+ if (!fields["api_password"]) throw new CredentialMaterialError("credential api_password is required");
34
+ credentials.apiPassword = new SecretString(fields["api_password"] ?? "");
35
+ return credentials;
36
+ }
37
+ var ListDomainsInputSchema = z.strictObject({
38
+ "page": z.number().int(),
39
+ "limit": z.number().int()
40
+ });
41
+ var DomainSchema = z.strictObject({
42
+ "name": z.string(),
43
+ "expiresAt": z.string()
44
+ });
45
+ var ListDomainsOutputSchema = z.strictObject({
46
+ "domains": z.array(DomainSchema).nullable(),
47
+ "page": z.number().int(),
48
+ "totalPages": z.number().int(),
49
+ "total": z.number().int()
50
+ });
51
+
52
+ // src/generated/definitions.ts
53
+ var ConnectorID = "west";
54
+ var ProviderID = "west";
55
+ var ListDomainsBranch = {
56
+ Listed: "listed",
57
+ ProviderRejected: "providerRejected",
58
+ InvalidResponse: "invalidResponse",
59
+ Defect: "defect"
60
+ };
61
+ var ListDomainsBranchListed = ListDomainsBranch.Listed;
62
+ var ListDomainsBranchProviderRejected = ListDomainsBranch.ProviderRejected;
63
+ var ListDomainsBranchInvalidResponse = ListDomainsBranch.InvalidResponse;
64
+ var ListDomainsBranchDefect = ListDomainsBranch.Defect;
65
+ var ListDomainsDefinition = {
66
+ operation: { connectorId: ConnectorID, operationId: "listDomains" },
67
+ branches: [
68
+ { id: "listed", description: "West.cn returned a domain page." },
69
+ { id: "providerRejected", description: "West.cn rejected credentials or reseller access.", optional: true },
70
+ { id: "invalidResponse", description: "West.cn returned malformed or oversized data.", optional: true },
71
+ { id: "defect", description: "Local credentials or page options are invalid.", optional: true }
72
+ ],
73
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
74
+ };
75
+ var ListDomainsMetadata = { kind: "query", idempotency: "none", authorization: "required" };
76
+
77
+ // src/generated/connection.ts
78
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
79
+ var Connection = class {
80
+ /** Stable provider and connection name. */
81
+ reference;
82
+ /** Bound provider operations. */
83
+ operations;
84
+ /** Validate a reference and bind operations. */
85
+ constructor(reference, operations) {
86
+ this.reference = ConnectionRefSchema.parse(reference);
87
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
88
+ if (!operations) throw new TypeError("connector operations are required");
89
+ this.operations = operations;
90
+ }
91
+ };
92
+ function newConnection(client, reference) {
93
+ if (!client) throw new TypeError("connector client is required");
94
+ return new Connection(reference, client);
95
+ }
96
+ function newConnectionWithOperations(operations, reference) {
97
+ return new Connection(reference, operations);
98
+ }
99
+ function newProjectConnection(project, connectionName, createClient) {
100
+ if (!project) throw new TypeError("loaded project is required");
101
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
102
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
103
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
104
+ return newConnection(createClient(project, connectionName), reference);
105
+ }
106
+
107
+ export {
108
+ ConfigSchema,
109
+ CredentialMaterialError,
110
+ isCredentialMaterialError,
111
+ decodeCredentials,
112
+ ListDomainsInputSchema,
113
+ DomainSchema,
114
+ ListDomainsOutputSchema,
115
+ ConnectorID,
116
+ ProviderID,
117
+ ListDomainsBranch,
118
+ ListDomainsBranchListed,
119
+ ListDomainsBranchProviderRejected,
120
+ ListDomainsBranchInvalidResponse,
121
+ ListDomainsBranchDefect,
122
+ ListDomainsDefinition,
123
+ ListDomainsMetadata,
124
+ Connection,
125
+ newConnection,
126
+ newConnectionWithOperations,
127
+ newProjectConnection
128
+ };
@@ -0,0 +1,101 @@
1
+ import { CredentialProvider, SecretString, Query, ConnectionRef } from '@superdurable/connectors-sdk';
2
+ import { z } from 'zod';
3
+
4
+ /** Connector configuration; omitted fields use manifest defaults. */
5
+ interface Config {
6
+ /** HTTPS origin of the West.cn reseller API without a path. Leave blank for the displayed public endpoint; override only for a trusted test server or approved proxy. */
7
+ baseUrl?: string;
8
+ /** Maximum time for one domain-list request as a positive Go duration such as 5s or 1m. Leave blank for the displayed default; raise only for a slow approved proxy. Runtime value in milliseconds. */
9
+ timeoutMs?: number;
10
+ /** Maximum domain-list response size in bytes as a positive integer. Leave blank for the displayed default; raise only if a legitimate response exceeds it. */
11
+ maxResponseBytes?: number;
12
+ }
13
+ /** Runtime schema for manifest configuration. */
14
+ declare const ConfigSchema: z.ZodObject<{
15
+ baseUrl: z.ZodOptional<z.ZodString>;
16
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
17
+ maxResponseBytes: z.ZodOptional<z.ZodNumber>;
18
+ }, z.core.$strip>;
19
+ /** Private connector credentials resolved by the host. */
20
+ interface Credentials {
21
+ /** Secret API password from https://www.west.cn/ > 代理商管理 > API接口配置. Available only to approved reseller partners. Dex stores it only as a credential and uses it to derive a 10-minute MD5 token; blank prevents requests. */
22
+ apiPassword: SecretString;
23
+ /** West.cn reseller username from https://www.west.cn/ > reseller account profile. Enter the registered account name, not an email address. It is sent as the username query parameter; blank prevents requests. */
24
+ username: string;
25
+ }
26
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
27
+ declare class CredentialMaterialError extends TypeError {
28
+ constructor(message: string);
29
+ }
30
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
31
+ declare function isCredentialMaterialError(error: unknown): boolean;
32
+ /** Decode private credential fields for the connector. */
33
+ declare function decodeCredentials(value: unknown): Credentials;
34
+ /** Host-owned source of private connector credentials. */
35
+ type CredentialSource = CredentialProvider<Credentials>;
36
+ /** ListDomainsInput selects one reseller domain page. Zero page and limit use 1 and 20. */
37
+ interface ListDomainsInput {
38
+ /** Page is the one-based page number; zero selects the first page. */
39
+ "page": number;
40
+ /** Limit is the number of domains to request, from 1 to 100; zero uses 20. */
41
+ "limit": number;
42
+ }
43
+ /** Domain contains non-personal registrar metadata. */
44
+ interface Domain {
45
+ /** Name is the registered domain name. */
46
+ "name": string;
47
+ /** ExpiresAt is the provider's expiration date text. */
48
+ "expiresAt": string;
49
+ }
50
+ /** ListDomainsOutput contains one domain page and provider pagination counts. */
51
+ interface ListDomainsOutput {
52
+ /** Domains are the returned domains in provider order. */
53
+ "domains": Array<Domain> | null;
54
+ /** Page is the returned one-based page number. */
55
+ "page": number;
56
+ /** TotalPages is the total number of pages reported by West.cn. */
57
+ "totalPages": number;
58
+ /** Total is the total number of domains reported by West.cn. */
59
+ "total": number;
60
+ }
61
+ /** Runtime validator for ListDomainsInput. */
62
+ declare const ListDomainsInputSchema: z.ZodObject<{
63
+ page: z.ZodNumber;
64
+ limit: z.ZodNumber;
65
+ }, z.core.$strict>;
66
+ /** Runtime validator for Domain. */
67
+ declare const DomainSchema: z.ZodObject<{
68
+ name: z.ZodString;
69
+ expiresAt: z.ZodString;
70
+ }, z.core.$strict>;
71
+ /** Runtime validator for ListDomainsOutput. */
72
+ declare const ListDomainsOutputSchema: z.ZodObject<{
73
+ domains: z.ZodNullable<z.ZodArray<z.ZodObject<{
74
+ name: z.ZodString;
75
+ expiresAt: z.ZodString;
76
+ }, z.core.$strict>>>;
77
+ page: z.ZodNumber;
78
+ totalPages: z.ZodNumber;
79
+ total: z.ZodNumber;
80
+ }, z.core.$strict>;
81
+
82
+ /** Typed operations supplied by a client or mock. */
83
+ interface Operations {
84
+ /** Invoke listDomains through this connection. */
85
+ listDomains(): Query<ListDomainsInput, ListDomainsOutput>;
86
+ }
87
+ /** Named connector connection kept outside Flow state. */
88
+ declare class Connection<BoundOperations = Operations> {
89
+ /** Stable provider and connection name. */
90
+ readonly reference: ConnectionRef;
91
+ /** Bound provider operations. */
92
+ readonly operations: BoundOperations;
93
+ /** Validate a reference and bind operations. */
94
+ constructor(reference: ConnectionRef, operations: BoundOperations);
95
+ }
96
+ /** Bind a client to a named connection. */
97
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
98
+ /** Bind scripted operations to a named connection. */
99
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
100
+
101
+ export { Connection as C, type Domain as D, type ListDomainsInput as L, type Operations as O, type ListDomainsOutput as a, type Config as b, type Credentials as c, ConfigSchema as d, CredentialMaterialError as e, type CredentialSource as f, DomainSchema as g, ListDomainsInputSchema as h, ListDomainsOutputSchema as i, decodeCredentials as j, isCredentialMaterialError as k, newConnectionWithOperations as l, newConnection as n };
@@ -0,0 +1,87 @@
1
+ import { L as ListDomainsInput, a as ListDomainsOutput, C as Connection, O as Operations, b as Config, c as Credentials } from './connection-Bu_m7LQq.js';
2
+ export { d as ConfigSchema, e as CredentialMaterialError, f as CredentialSource, D as Domain, g as DomainSchema, h as ListDomainsInputSchema, i as ListDomainsOutputSchema, j as decodeCredentials, k as isCredentialMaterialError, n as newConnection, l as newConnectionWithOperations } from './connection-Bu_m7LQq.js';
3
+ import { QueryDefinition, QueryStepConfig, Query, QueryResult, QueryStep, CredentialProvider, Call, QueryAttempt } from '@superdurable/connectors-sdk';
4
+ import { StepTarget } from '@superdurable/dex';
5
+ import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
6
+ import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
7
+ import 'zod';
8
+
9
+ /** Stable connector identity. */
10
+ declare const ConnectorID = "west";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "west";
13
+ /** Branch IDs for listDomains. */
14
+ declare const ListDomainsBranch: {
15
+ readonly Listed: "listed";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** West.cn returned a domain page. */
21
+ declare const ListDomainsBranchListed: "listed";
22
+ /** West.cn rejected credentials or reseller access. */
23
+ declare const ListDomainsBranchProviderRejected: "providerRejected";
24
+ /** West.cn returned malformed or oversized data. */
25
+ declare const ListDomainsBranchInvalidResponse: "invalidResponse";
26
+ /** Local credentials or page options are invalid. */
27
+ declare const ListDomainsBranchDefect: "defect";
28
+ /** Manifest definition for listDomains. */
29
+ declare const ListDomainsDefinition: QueryDefinition;
30
+ /** Manifest metadata for listDomains. */
31
+ declare const ListDomainsMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+
37
+ /** Configuration for the listDomains connector Step. */
38
+ interface ListDomainsStepConfig<StepInput, OperationInput = ListDomainsInput, OperationOutput = ListDomainsOutput> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
39
+ /** Named connection supplying this operation. */
40
+ connection: Connection<{
41
+ listDomains(): Query<OperationInput, OperationOutput>;
42
+ }>;
43
+ /** Name matching the bound connection. */
44
+ connectionName: string;
45
+ /** West.cn returned a domain page. */
46
+ listed: StepTarget<QueryResult<OperationOutput>>;
47
+ /** West.cn rejected credentials or reseller access. */
48
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
49
+ /** West.cn returned malformed or oversized data. */
50
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
51
+ /** Local credentials or page options are invalid. */
52
+ defect?: StepTarget<QueryResult<OperationOutput>>;
53
+ }
54
+ /** Build the listDomains Step from a named connection. */
55
+ declare function newListDomainsStep<StepInput, OperationInput = ListDomainsInput, OperationOutput = ListDomainsOutput>(configuration: ListDomainsStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
56
+
57
+ /** Open one named West connection from Dex project configuration. */
58
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
59
+
60
+ /** Optional provider transport and clock for deterministic verification. */
61
+ interface WestClientOptions {
62
+ /** Send one provider request. */ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
63
+ /** Supply the current time for the reseller token. */ now?: () => Date;
64
+ }
65
+ /** Read a West.cn reseller domain page using the current credential pair. */
66
+ declare class WestClient {
67
+ private readonly credentials;
68
+ private readonly baseUrl;
69
+ private readonly timeoutMs;
70
+ private readonly maxResponseBytes;
71
+ private readonly send;
72
+ private readonly now;
73
+ /** Validate endpoint and request bounds without contacting West.cn. */
74
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: WestClientOptions);
75
+ /** Bind the domain-page Query. */ listDomains(): ListDomainsOperation;
76
+ /** Sign and read one domain page. */
77
+ request(call: Call, input: ListDomainsInput): Promise<QueryAttempt<ListDomainsOutput>>;
78
+ }
79
+ /** Read a single reseller domain page. */
80
+ declare class ListDomainsOperation implements Query<ListDomainsInput, ListDomainsOutput> {
81
+ private readonly client;
82
+ /** Bind one validated client. */ constructor(client: WestClient);
83
+ /** Return the generated Query contract. */ definition(): QueryDefinition;
84
+ /** Invoke one safe provider read. */ invoke(call: Call, input: ListDomainsInput): Promise<QueryAttempt<ListDomainsOutput>>;
85
+ }
86
+
87
+ export { Config, Connection, ConnectorID, Credentials, ListDomainsBranch, ListDomainsBranchDefect, ListDomainsBranchInvalidResponse, ListDomainsBranchListed, ListDomainsBranchProviderRejected, ListDomainsDefinition, ListDomainsInput, ListDomainsMetadata, ListDomainsOutput, type ListDomainsStepConfig, ProviderID, WestClient, type WestClientOptions, newListDomainsStep, newProjectConnection };
package/dist/index.js ADDED
@@ -0,0 +1,201 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ DomainSchema,
7
+ ListDomainsBranch,
8
+ ListDomainsBranchDefect,
9
+ ListDomainsBranchInvalidResponse,
10
+ ListDomainsBranchListed,
11
+ ListDomainsBranchProviderRejected,
12
+ ListDomainsDefinition,
13
+ ListDomainsInputSchema,
14
+ ListDomainsMetadata,
15
+ ListDomainsOutputSchema,
16
+ ProviderID,
17
+ decodeCredentials,
18
+ isCredentialMaterialError,
19
+ newConnection,
20
+ newConnectionWithOperations,
21
+ newProjectConnection
22
+ } from "./chunk-WRFGEXMY.js";
23
+
24
+ // src/generated/steps.ts
25
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
26
+ function newListDomainsStep(configuration) {
27
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
28
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
29
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listDomains(), connection: connection.reference, branches: [
30
+ goToBranch("listed", listed),
31
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
32
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
33
+ ...defect ? [goToBranch("defect", defect)] : []
34
+ ] });
35
+ }
36
+
37
+ // src/client.ts
38
+ import { createHash } from "crypto";
39
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
40
+ import { BodyTooLargeError, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
41
+ var empty = { domains: [], page: 0, totalPages: 0, total: 0 };
42
+ var WestClient = class {
43
+ /** Validate endpoint and request bounds without contacting West.cn. */
44
+ constructor(config, credentials, options = {}) {
45
+ this.credentials = credentials;
46
+ if (!config || !credentials) throw new TypeError("West configuration and credential source are required");
47
+ this.baseUrl = (config.baseUrl || "https://api.west.cn").replace(/\/$/, "");
48
+ const endpoint = new URL(this.baseUrl);
49
+ if (endpoint.protocol !== "https:" || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new TypeError("West base URL must be an HTTPS origin");
50
+ this.timeoutMs = config.timeoutMs ?? 1e4;
51
+ this.maxResponseBytes = config.maxResponseBytes ?? 2097152;
52
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0 || this.maxResponseBytes > 16 << 20) throw new TypeError("West request bounds are invalid");
53
+ this.send = options.send ?? sendProviderRequest;
54
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
55
+ }
56
+ credentials;
57
+ baseUrl;
58
+ timeoutMs;
59
+ maxResponseBytes;
60
+ send;
61
+ now;
62
+ /** Bind the domain-page Query. */
63
+ listDomains() {
64
+ return new ListDomainsOperation(this);
65
+ }
66
+ /** Sign and read one domain page. */
67
+ async request(call, input) {
68
+ let credentials;
69
+ try {
70
+ credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
71
+ } catch {
72
+ return branch("defect", "AUTHENTICATION");
73
+ }
74
+ const username = credentials.username;
75
+ const password = credentials.apiPassword instanceof SecretString ? credentials.apiPassword.reveal() : "";
76
+ if (typeof username !== "string" || !validPart(username) || !validPart(password)) return branch("defect", "AUTHENTICATION");
77
+ const page = input.page || 1;
78
+ const limit = input.limit || 20;
79
+ if (!Number.isInteger(page) || page < 1 || page > 1e6 || !Number.isInteger(limit) || limit < 1 || limit > 100) return branch("defect", "VALIDATION");
80
+ const timestamp = String(this.now().getTime());
81
+ const token = createHash("md5").update(`${username}${password}${timestamp}`).digest("hex");
82
+ const query = new URLSearchParams({ act: "getdomains", username, time: timestamp, token, page: String(page), limit: String(limit) });
83
+ const request = { url: `${this.baseUrl}/api/v2/domain/?${query}`, method: "GET", headers: { Accept: "application/json" }, timeoutMs: this.timeoutMs, maxResponseBytes: this.maxResponseBytes, addressPolicy: "publicHTTPS", signal: call.context.cancellationSignal };
84
+ let response;
85
+ try {
86
+ response = await this.send(request);
87
+ } catch (error) {
88
+ if (error instanceof BodyTooLargeError && error.status === 200) return branch("invalidResponse", "RESPONSE_TOO_LARGE");
89
+ return retry("AVAILABILITY");
90
+ }
91
+ const retryAfter = Object.entries(response.headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1];
92
+ const delay = parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] ?? "" : retryAfter ?? "");
93
+ if (response.status === 429) return retry("RATE_LIMIT", delay);
94
+ if (response.status === 408 || response.status >= 500) return retry("AVAILABILITY", delay);
95
+ if (response.body.length > this.maxResponseBytes) return branch("invalidResponse", "RESPONSE_TOO_LARGE");
96
+ if (response.status !== 200) return branch("providerRejected", response.status === 401 ? "AUTHENTICATION" : response.status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION");
97
+ let data;
98
+ try {
99
+ data = JSON.parse(new TextDecoder("gbk", { fatal: true }).decode(response.body));
100
+ } catch {
101
+ return branch("invalidResponse", "PROTOCOL");
102
+ }
103
+ if (!isRecord(data) || typeof data.result !== "number" || !Number.isInteger(data.result)) return branch("invalidResponse", "PROTOCOL");
104
+ if (data.result !== 200) return branch("providerRejected", "PROVIDER_REJECTION");
105
+ if (!isRecord(data.data) || !Array.isArray(data.data.items) || data.data.items.length > limit || !validCount(data.data.pageno) || !validCount(data.data.totalpages) || !validCount(data.data.total)) return branch("invalidResponse", "PROTOCOL");
106
+ const domains = [];
107
+ for (const item of data.data.items) {
108
+ if (!isRecord(item) || typeof item.domain !== "string" || !item.domain || item.domain.length > 253 || item.domain.trim() !== item.domain || typeof item.expdate !== "string" || !item.expdate || item.expdate.length > 64) return branch("invalidResponse", "PROTOCOL");
109
+ domains.push({ name: item.domain, expiresAt: item.expdate });
110
+ }
111
+ return newQueryBranch("listed", { domains, page: data.data.pageno, totalPages: data.data.totalpages, total: data.data.total });
112
+ }
113
+ };
114
+ var ListDomainsOperation = class {
115
+ /** Bind one validated client. */
116
+ constructor(client) {
117
+ this.client = client;
118
+ }
119
+ client;
120
+ /** Return the generated Query contract. */
121
+ definition() {
122
+ return ListDomainsDefinition;
123
+ }
124
+ /** Invoke one safe provider read. */
125
+ invoke(call, input) {
126
+ return this.client.request(call, input);
127
+ }
128
+ };
129
+ function validPart(value) {
130
+ return Boolean(value) && value.length <= 512 && value.trim() === value && [...value].every((character) => character.charCodeAt(0) > 32 && character.charCodeAt(0) !== 127);
131
+ }
132
+ function validCount(value) {
133
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
134
+ }
135
+ function isRecord(value) {
136
+ return typeof value === "object" && value !== null && !Array.isArray(value);
137
+ }
138
+ function failure(kind) {
139
+ return { provider: "west", operation: "listDomains", kind, message: "West domain request failed" };
140
+ }
141
+ function branch(name, kind) {
142
+ return newQueryBranch(name, empty, {}, failure(kind));
143
+ }
144
+ function retry(kind, delay = 0) {
145
+ return newQueryRetry(failure(kind), delay);
146
+ }
147
+
148
+ // src/project.ts
149
+ function newProjectConnection2(project, connectionName) {
150
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
151
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "west" && entry.connectionName === name);
152
+ if (!selected) throw new TypeError("West project connection is not configured");
153
+ const fields = selected.configuration;
154
+ const config = ConfigSchema.parse({ ...fields, ...fields.timeout !== void 0 ? { timeoutMs: parseDurationMilliseconds(fields.timeout) } : {} });
155
+ const credentials = {
156
+ async resolve(_call, signal) {
157
+ return decodeCredentials(await loadedProject.resolveCredential("west", name, signal));
158
+ }
159
+ };
160
+ return new WestClient(config, credentials);
161
+ });
162
+ }
163
+ function parseDurationMilliseconds(value) {
164
+ if (typeof value === "number") return Math.ceil(value / 1e6);
165
+ if (typeof value !== "string") throw new TypeError("timeout must be a duration");
166
+ let remaining = value;
167
+ let milliseconds = 0;
168
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
169
+ while (remaining) {
170
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
171
+ if (!part) throw new TypeError("timeout must be a positive Go duration");
172
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
173
+ remaining = remaining.slice(part[0].length);
174
+ }
175
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("timeout must resolve to positive whole milliseconds");
176
+ return milliseconds;
177
+ }
178
+ export {
179
+ ConfigSchema,
180
+ Connection,
181
+ ConnectorID,
182
+ CredentialMaterialError,
183
+ DomainSchema,
184
+ ListDomainsBranch,
185
+ ListDomainsBranchDefect,
186
+ ListDomainsBranchInvalidResponse,
187
+ ListDomainsBranchListed,
188
+ ListDomainsBranchProviderRejected,
189
+ ListDomainsDefinition,
190
+ ListDomainsInputSchema,
191
+ ListDomainsMetadata,
192
+ ListDomainsOutputSchema,
193
+ ProviderID,
194
+ WestClient,
195
+ decodeCredentials,
196
+ isCredentialMaterialError,
197
+ newConnection,
198
+ newConnectionWithOperations,
199
+ newListDomainsStep,
200
+ newProjectConnection2 as newProjectConnection
201
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, C as Connection, L as ListDomainsInput, a as ListDomainsOutput, D as Domain } from './connection-Bu_m7LQq.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for ListDomainsInput in scripted cases. */
7
+ declare const emptyListDomainsInput: ListDomainsInput;
8
+ /** Go zero value for Domain in scripted cases. */
9
+ declare const emptyDomain: Domain;
10
+ /** Go zero value for ListDomainsOutput in scripted cases. */
11
+ declare const emptyListDomainsOutput: ListDomainsOutput;
12
+ /** Script the listed branch. */
13
+ declare function listDomainsListed(value: ListDomainsOutput, failure?: Failure): Case<ListDomainsOutput>;
14
+ /** Script the providerRejected branch. */
15
+ declare function listDomainsProviderRejected(value: ListDomainsOutput, failure?: Failure): Case<ListDomainsOutput>;
16
+ /** Script the invalidResponse branch. */
17
+ declare function listDomainsInvalidResponse(value: ListDomainsOutput, failure?: Failure): Case<ListDomainsOutput>;
18
+ /** Script the defect branch. */
19
+ declare function listDomainsDefect(value: ListDomainsOutput, failure?: Failure): Case<ListDomainsOutput>;
20
+ /** Script a safe retry of listDomains. */
21
+ declare function listDomainsRetry(failure: Failure, retryAfterMs?: number): Case<ListDomainsOutput>;
22
+ /** Manifest scenario sampleDomains for listDomains. */
23
+ declare function listDomainsSampleDomains(): Case<ListDomainsOutput>;
24
+ /** Default listDomains scenario. */
25
+ declare function listDomainsDefault(): Case<ListDomainsOutput>;
26
+ /** Scripted operations and manifest defaults for this connector. */
27
+ declare class GeneratedMock implements Operations {
28
+ #private;
29
+ constructor(connectionName: string);
30
+ connection(): Connection;
31
+ listDomains(): MockQuery<ListDomainsInput, ListDomainsOutput>;
32
+ assertNoFailures(): void;
33
+ }
34
+
35
+ export { GeneratedMock, emptyDomain, emptyListDomainsInput, emptyListDomainsOutput, listDomainsDefault, listDomainsDefect, listDomainsInvalidResponse, listDomainsListed, listDomainsProviderRejected, listDomainsRetry, listDomainsSampleDomains };
package/dist/mock.js ADDED
@@ -0,0 +1,77 @@
1
+ import {
2
+ DomainSchema,
3
+ ListDomainsDefinition,
4
+ ListDomainsInputSchema,
5
+ ListDomainsOutputSchema,
6
+ ProviderID,
7
+ newConnectionWithOperations
8
+ } from "./chunk-WRFGEXMY.js";
9
+
10
+ // src/generated/mock.ts
11
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
12
+ var emptyListDomainsInput = ListDomainsInputSchema.parse({
13
+ "page": 0,
14
+ "limit": 0
15
+ });
16
+ var emptyDomain = DomainSchema.parse({
17
+ "name": "",
18
+ "expiresAt": ""
19
+ });
20
+ var emptyListDomainsOutput = ListDomainsOutputSchema.parse({
21
+ "domains": [],
22
+ "page": 0,
23
+ "totalPages": 0,
24
+ "total": 0
25
+ });
26
+ function listDomainsListed(value, failure) {
27
+ return branchCase("listed", value, failure);
28
+ }
29
+ function listDomainsProviderRejected(value, failure) {
30
+ return branchCase("providerRejected", value, failure);
31
+ }
32
+ function listDomainsInvalidResponse(value, failure) {
33
+ return branchCase("invalidResponse", value, failure);
34
+ }
35
+ function listDomainsDefect(value, failure) {
36
+ return branchCase("defect", value, failure);
37
+ }
38
+ function listDomainsRetry(failure, retryAfterMs = 0) {
39
+ return retryCase(failure, retryAfterMs);
40
+ }
41
+ function listDomainsSampleDomains() {
42
+ const value = ListDomainsOutputSchema.parse({ "domains": [{ "expiresAt": "2030-01-01", "name": "example.cn" }], "page": 1, "total": 1, "totalPages": 1 });
43
+ return branchCase("listed", value);
44
+ }
45
+ function listDomainsDefault() {
46
+ return listDomainsSampleDomains();
47
+ }
48
+ var GeneratedMock = class {
49
+ #listDomains;
50
+ #connection;
51
+ constructor(connectionName) {
52
+ this.#listDomains = newQuery(ListDomainsDefinition).default(listDomainsDefault());
53
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
54
+ }
55
+ connection() {
56
+ return this.#connection;
57
+ }
58
+ listDomains() {
59
+ return this.#listDomains;
60
+ }
61
+ assertNoFailures() {
62
+ this.#listDomains.assertNoFailures();
63
+ }
64
+ };
65
+ export {
66
+ GeneratedMock,
67
+ emptyDomain,
68
+ emptyListDomainsInput,
69
+ emptyListDomainsOutput,
70
+ listDomainsDefault,
71
+ listDomainsDefect,
72
+ listDomainsInvalidResponse,
73
+ listDomainsListed,
74
+ listDomainsProviderRejected,
75
+ listDomainsRetry,
76
+ listDomainsSampleDomains
77
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-west",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "west connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/west/typescript"
10
+ },
11
+ "type": "module",
12
+ "engines": {
13
+ "node": "^22.0.0 || ^24.0.0"
14
+ },
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./mock": {
23
+ "types": "./dist/mock.d.ts",
24
+ "import": "./dist/mock.js"
25
+ },
26
+ "./dex-connector.json": "./dex-connector.json"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE",
32
+ "dex-connector.json"
33
+ ],
34
+ "scripts": {
35
+ "prepack": "npm run build",
36
+ "build": "tsup src/index.ts src/mock.ts --format esm --dts --clean",
37
+ "typecheck": "tsc --noEmit",
38
+ "lint": "eslint src test examples",
39
+ "test": "vitest run --exclude test/integration/**",
40
+ "test:integration": "vitest run test/integration/*.integration.test.ts",
41
+ "example:worker": "tsx examples/basic/worker.ts",
42
+ "example:start": "tsx examples/basic/start.ts",
43
+ "check": "npm run typecheck && npm run lint && npm test && npm run build"
44
+ },
45
+ "dependencies": {
46
+ "@superdurable/connectors-sdk": "0.1.1",
47
+ "@superdurable/dex": ">=1.28.0",
48
+ "zod": "^4.1.0"
49
+ },
50
+ "devDependencies": {
51
+ "@eslint/js": "^9.0.0",
52
+ "@types/node": "^22.0.0",
53
+ "eslint": "^9.0.0",
54
+ "tsup": "^8.0.0",
55
+ "tsx": "^4.23.15",
56
+ "typescript": "^5.9.0",
57
+ "typescript-eslint": "^8.0.0",
58
+ "vitest": "^3.0.0",
59
+ "yaml": "^2.9.1"
60
+ }
61
+ }