@payark/sdk-effect 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/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # @payark/sdk-effect
2
+
3
+ A high-performance, functional TypeScript SDK for [PayArk](https://payark-public-demo.vercel.app/), built natively on the [Effect](https://effect.website/) ecosystem.
4
+
5
+ > **Native Effect** · **Type-safe** · **Runtime Validation** · **Zero Promise overhead**
6
+
7
+ ---
8
+
9
+ ## Features
10
+
11
+ - **Effect-Native**: Built directly on `@effect/platform/HttpClient`. Returns pure `Effect` types without Promise wrappers.
12
+ - **Strict Validation**: All API responses are parsed and validated at runtime using `@effect/schema`, ensuring your data is exactly what you expect.
13
+ - **Branded Types**: IDs (e.g., `PaymentId`, `ProjectId`) are branded for compile-time safety, preventing mix-ups.
14
+ - **Structured Errors**: Errors are typed as `PayArkEffectError`, a `TaggedError` that integrates seamlessly with `Effect.catchTag`.
15
+ - **Tracing Ready**: Fully instrumented for observability with Effect's built-in tracing.
16
+ - **Zero-Dependency Core**: Lightweight and tree-shakeable.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ # bun
22
+ bun add @payark/sdk-effect
23
+
24
+ # npm
25
+ npm install @payark/sdk-effect
26
+ ```
27
+
28
+ > **Note**: This package requires `effect` as a peer dependency.
29
+
30
+ ## Quick Start
31
+
32
+ ```ts
33
+ import { Effect, Console } from "effect";
34
+ import { PayArkEffect } from "@payark/sdk-effect";
35
+
36
+ // 1. Initialize the client
37
+ const payark = new PayArkEffect({
38
+ apiKey: "sk_live_...",
39
+ // optional: baseUrl, timeout, etc.
40
+ });
41
+
42
+ // 2. Define your program
43
+ const program = Effect.gen(function* (_) {
44
+ // Create a checkout session
45
+ const session = yield* _(
46
+ payark.checkout.create({
47
+ amount: 1000, // NPR 1000
48
+ provider: "esewa",
49
+ returnUrl: "https://your-site.com/success",
50
+ }),
51
+ );
52
+
53
+ yield* _(Console.log(`Checkout created: ${session.checkout_url}`));
54
+
55
+ // Retrieve payment details later
56
+ const payment = yield* _(
57
+ payark.payments.retrieve(session.id.replace("ch_", "pay_")),
58
+ );
59
+
60
+ return payment;
61
+ });
62
+
63
+ // 3. Run safely
64
+ const result = await Effect.runPromise(
65
+ program.pipe(
66
+ Effect.catchTag("PayArkEffectError", (err) =>
67
+ Console.error(`Payment failed: ${err.message} (${err.code})`),
68
+ ),
69
+ ),
70
+ );
71
+ ```
72
+
73
+ ## API Reference
74
+
75
+ ### Resources
76
+
77
+ - **`payark.checkout`**: Create hosted payment sessions.
78
+ - **`payark.payments`**: List and retrieve payment records.
79
+ - **`payark.projects`**: Manage project settings (requires PAT).
80
+
81
+ ### Types & Schemas
82
+
83
+ We export all Zod-like schemas for runtime validation if you need them independently:
84
+
85
+ ```ts
86
+ import { PaymentSchema } from "@payark/sdk-effect";
87
+ import { Schema } from "@effect/schema";
88
+
89
+ const isPayment = Schema.is(PaymentSchema);
90
+ ```
91
+
92
+ ## Error Handling
93
+
94
+ All methods return an `Effect<Success, Error, Requirements>`. The error channel is strictly typed.
95
+
96
+ ```ts
97
+ import { PayArkEffectError } from "@payark/sdk-effect";
98
+ import { Effect } from "effect";
99
+
100
+ // ...
101
+
102
+ program.pipe(
103
+ Effect.catchTag("PayArkEffectError", (error) => {
104
+ // error is fully typed
105
+ console.error(error.statusCode); // 400, 401, etc.
106
+ console.error(error.code); // "authentication_error", "invalid_request_error"
107
+ return Effect.succeed(null);
108
+ }),
109
+ Effect.catchTag("ParseError", (error) => {
110
+ // Handle schema validation errors (e.g. API changed shape)
111
+ console.error("Response validation failed", error);
112
+ return Effect.die(error);
113
+ }),
114
+ );
115
+ ```
116
+
117
+ ## Configuration & Testing
118
+
119
+ You can interact with the underlying `HttpClient` by providing layers. This is useful for testing or custom networking requirements.
120
+
121
+ ```ts
122
+ import { PayArkEffect } from "@payark/sdk-effect";
123
+ import { HttpClient } from "@effect/platform";
124
+
125
+ // The SDK uses the default HttpClient by default, but you can provide your own context.
126
+ // (Advanced usage for testing mocking)
127
+ ```
128
+
129
+ ## License
130
+
131
+ MIT
@@ -0,0 +1,202 @@
1
+ import { Effect, Context, Layer } from 'effect';
2
+ import * as effect_Cause from 'effect/Cause';
3
+ import * as effect_Types from 'effect/Types';
4
+ import { PayArkErrorCode, PayArkErrorBody, PayArkConfig, CreateCheckoutParams, ListPaymentsParams } from '@payark/sdk';
5
+ export { CheckoutSession, ListPaymentsParams, PaginatedResponse, PaginationMeta, PayArkConfig, PayArkErrorBody, PayArkErrorCode, Payment, PaymentStatus, Project, Provider, WebhookEvent, WebhookEventType } from '@payark/sdk';
6
+ import { Schema, ParseResult } from '@effect/schema';
7
+ import { HttpClient } from '@effect/platform';
8
+
9
+ declare const PayArkEffectError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
10
+ readonly _tag: "PayArkEffectError";
11
+ } & Readonly<A>;
12
+ /**
13
+ * Effect-compatible error class for PayArk SDK.
14
+ * Extends Data.TaggedError for easy matching in Effect.catchTag.
15
+ */
16
+ declare class PayArkEffectError extends PayArkEffectError_base<{
17
+ readonly message: string;
18
+ readonly statusCode: number;
19
+ readonly code: PayArkErrorCode;
20
+ readonly raw?: PayArkErrorBody;
21
+ }> {
22
+ /** Human-readable representation for logging/debugging. */
23
+ toString(): string;
24
+ }
25
+
26
+ /**
27
+ * Supported payment providers on the PayArk platform.
28
+ */
29
+ declare const ProviderSchema: Schema.Literal<["esewa", "khalti", "connectips", "imepay", "fonepay", "sandbox"]>;
30
+ /**
31
+ * Branded Type for Checkout Session ID.
32
+ */
33
+ declare const CheckoutSessionId: Schema.brand<typeof Schema.String, "CheckoutSessionId">;
34
+ type CheckoutSessionId = Schema.Schema.Type<typeof CheckoutSessionId>;
35
+ /**
36
+ * Branded Type for Payment ID.
37
+ */
38
+ declare const PaymentId: Schema.brand<typeof Schema.String, "PaymentId">;
39
+ type PaymentId = Schema.Schema.Type<typeof PaymentId>;
40
+ /**
41
+ * Branded Type for Project ID.
42
+ */
43
+ declare const ProjectId: Schema.brand<typeof Schema.String, "ProjectId">;
44
+ type ProjectId = Schema.Schema.Type<typeof ProjectId>;
45
+ /**
46
+ * Schema for creating a checkout session.
47
+ */
48
+ declare const CreateCheckoutSchema: Schema.Struct<{
49
+ amount: typeof Schema.Number;
50
+ currency: Schema.optionalWith<typeof Schema.String, {
51
+ default: () => "NPR";
52
+ }>;
53
+ provider: Schema.Literal<["esewa", "khalti", "connectips", "imepay", "fonepay", "sandbox"]>;
54
+ returnUrl: typeof Schema.String;
55
+ cancelUrl: Schema.optional<typeof Schema.String>;
56
+ metadata: Schema.optional<Schema.Record$<typeof Schema.String, typeof Schema.Any>>;
57
+ }>;
58
+ /**
59
+ * Schema for a checkout session response.
60
+ */
61
+ declare const CheckoutSessionSchema: Schema.Struct<{
62
+ id: Schema.brand<typeof Schema.String, "CheckoutSessionId">;
63
+ checkout_url: typeof Schema.String;
64
+ payment_method: Schema.Struct<{
65
+ type: Schema.Literal<["esewa", "khalti", "connectips", "imepay", "fonepay", "sandbox"]>;
66
+ url: Schema.optional<typeof Schema.String>;
67
+ method: Schema.optional<Schema.Union<[Schema.Literal<["GET"]>, Schema.Literal<["POST"]>]>>;
68
+ fields: Schema.optional<Schema.Record$<typeof Schema.String, typeof Schema.String>>;
69
+ }>;
70
+ }>;
71
+ /**
72
+ * Schema for a Payment response.
73
+ */
74
+ declare const PaymentSchema: Schema.Struct<{
75
+ id: Schema.brand<typeof Schema.String, "PaymentId">;
76
+ project_id: Schema.brand<typeof Schema.String, "ProjectId">;
77
+ amount: typeof Schema.Number;
78
+ currency: typeof Schema.String;
79
+ status: Schema.Union<[Schema.Literal<["pending"]>, Schema.Literal<["success"]>, Schema.Literal<["failed"]>]>;
80
+ provider_ref: Schema.optional<Schema.NullOr<typeof Schema.String>>;
81
+ metadata_json: Schema.optional<Schema.NullOr<Schema.Record$<typeof Schema.String, typeof Schema.Any>>>;
82
+ gateway_response: Schema.optional<Schema.NullOr<Schema.Record$<typeof Schema.String, typeof Schema.Any>>>;
83
+ created_at: typeof Schema.String;
84
+ updated_at: Schema.optional<typeof Schema.String>;
85
+ }>;
86
+ /**
87
+ * Schema for a Project response.
88
+ */
89
+ declare const ProjectSchema: Schema.Struct<{
90
+ id: Schema.brand<typeof Schema.String, "ProjectId">;
91
+ name: typeof Schema.String;
92
+ api_key_secret: typeof Schema.String;
93
+ created_at: typeof Schema.String;
94
+ }>;
95
+ /**
96
+ * Higher-order schema for paginated responses.
97
+ */
98
+ declare const PaginatedResponseSchema: <A, I>(item: Schema.Schema<A, I>) => Schema.Struct<{
99
+ data: Schema.Array$<Schema.Schema<A, I, never>>;
100
+ meta: Schema.Struct<{
101
+ total: Schema.NullOr<typeof Schema.Number>;
102
+ limit: typeof Schema.Number;
103
+ offset: typeof Schema.Number;
104
+ }>;
105
+ }>;
106
+ type CheckoutSession = Schema.Schema.Type<typeof CheckoutSessionSchema>;
107
+ type Payment = Schema.Schema.Type<typeof PaymentSchema>;
108
+ type Project = Schema.Schema.Type<typeof ProjectSchema>;
109
+ interface PaginatedResponse<T> {
110
+ readonly data: ReadonlyArray<T>;
111
+ readonly meta: {
112
+ readonly total: number | null;
113
+ readonly limit: number;
114
+ readonly offset: number;
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Effect-based resource for PayArk Checkout.
120
+ */
121
+ declare class CheckoutEffect {
122
+ private readonly config;
123
+ constructor(config: PayArkConfig);
124
+ /**
125
+ * Create a new checkout session.
126
+ *
127
+ * @param params - Configuration for the checkout session.
128
+ * @returns Effect that resolves to the created checkout session.
129
+ */
130
+ create(params: CreateCheckoutParams): Effect.Effect<CheckoutSession, PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
131
+ }
132
+
133
+ /**
134
+ * Effect-based resource for PayArk Payments.
135
+ */
136
+ declare class PaymentsEffect {
137
+ private readonly config;
138
+ constructor(config: PayArkConfig);
139
+ /**
140
+ * List payments for the authenticated project.
141
+ *
142
+ * @param params - Optional pagination parameters.
143
+ * @returns Effect that resolves to paginated payments.
144
+ */
145
+ list(params?: ListPaymentsParams): Effect.Effect<PaginatedResponse<Payment>, PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
146
+ /**
147
+ * Retrieve a single payment by its ID.
148
+ *
149
+ * @param id - The payment identifier.
150
+ * @returns Effect that resolves to the payment object.
151
+ */
152
+ retrieve(id: string): Effect.Effect<Payment, PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
153
+ }
154
+
155
+ /**
156
+ * Effect-based resource for PayArk Projects.
157
+ */
158
+ declare class ProjectsEffect {
159
+ private readonly config;
160
+ constructor(config: PayArkConfig);
161
+ /**
162
+ * List all projects belonging to the authenticated account.
163
+ *
164
+ * @returns Effect that resolves to an array of projects.
165
+ */
166
+ list(): Effect.Effect<readonly Project[], PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
167
+ }
168
+
169
+ /**
170
+ * Main entry point for the Effect-based PayArk API.
171
+ */
172
+ declare class PayArkEffect {
173
+ private readonly config;
174
+ private _checkout?;
175
+ private _payments?;
176
+ private _projects?;
177
+ constructor(config: PayArkConfig);
178
+ /**
179
+ * Checkout sessions resource (Effect).
180
+ */
181
+ get checkout(): CheckoutEffect;
182
+ /**
183
+ * Payments resource (Effect).
184
+ */
185
+ get payments(): PaymentsEffect;
186
+ /**
187
+ * Projects resource (Effect).
188
+ */
189
+ get projects(): ProjectsEffect;
190
+ }
191
+ declare const PayArk_base: Context.TagClass<PayArk, "@payark/sdk-effect/PayArk", PayArkEffect>;
192
+ /**
193
+ * Service tag for the PayArk API.
194
+ */
195
+ declare class PayArk extends PayArk_base {
196
+ /**
197
+ * Create a Layer that provides the PayArk service.
198
+ */
199
+ static readonly Live: (config: PayArkConfig) => Layer.Layer<PayArk, never, never>;
200
+ }
201
+
202
+ export { CheckoutSessionId, CheckoutSessionSchema, CreateCheckoutSchema, PaginatedResponseSchema, PayArk, PayArkEffect, PayArkEffectError, PaymentId, PaymentSchema, ProjectId, ProjectSchema, ProviderSchema };
@@ -0,0 +1,202 @@
1
+ import { Effect, Context, Layer } from 'effect';
2
+ import * as effect_Cause from 'effect/Cause';
3
+ import * as effect_Types from 'effect/Types';
4
+ import { PayArkErrorCode, PayArkErrorBody, PayArkConfig, CreateCheckoutParams, ListPaymentsParams } from '@payark/sdk';
5
+ export { CheckoutSession, ListPaymentsParams, PaginatedResponse, PaginationMeta, PayArkConfig, PayArkErrorBody, PayArkErrorCode, Payment, PaymentStatus, Project, Provider, WebhookEvent, WebhookEventType } from '@payark/sdk';
6
+ import { Schema, ParseResult } from '@effect/schema';
7
+ import { HttpClient } from '@effect/platform';
8
+
9
+ declare const PayArkEffectError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
10
+ readonly _tag: "PayArkEffectError";
11
+ } & Readonly<A>;
12
+ /**
13
+ * Effect-compatible error class for PayArk SDK.
14
+ * Extends Data.TaggedError for easy matching in Effect.catchTag.
15
+ */
16
+ declare class PayArkEffectError extends PayArkEffectError_base<{
17
+ readonly message: string;
18
+ readonly statusCode: number;
19
+ readonly code: PayArkErrorCode;
20
+ readonly raw?: PayArkErrorBody;
21
+ }> {
22
+ /** Human-readable representation for logging/debugging. */
23
+ toString(): string;
24
+ }
25
+
26
+ /**
27
+ * Supported payment providers on the PayArk platform.
28
+ */
29
+ declare const ProviderSchema: Schema.Literal<["esewa", "khalti", "connectips", "imepay", "fonepay", "sandbox"]>;
30
+ /**
31
+ * Branded Type for Checkout Session ID.
32
+ */
33
+ declare const CheckoutSessionId: Schema.brand<typeof Schema.String, "CheckoutSessionId">;
34
+ type CheckoutSessionId = Schema.Schema.Type<typeof CheckoutSessionId>;
35
+ /**
36
+ * Branded Type for Payment ID.
37
+ */
38
+ declare const PaymentId: Schema.brand<typeof Schema.String, "PaymentId">;
39
+ type PaymentId = Schema.Schema.Type<typeof PaymentId>;
40
+ /**
41
+ * Branded Type for Project ID.
42
+ */
43
+ declare const ProjectId: Schema.brand<typeof Schema.String, "ProjectId">;
44
+ type ProjectId = Schema.Schema.Type<typeof ProjectId>;
45
+ /**
46
+ * Schema for creating a checkout session.
47
+ */
48
+ declare const CreateCheckoutSchema: Schema.Struct<{
49
+ amount: typeof Schema.Number;
50
+ currency: Schema.optionalWith<typeof Schema.String, {
51
+ default: () => "NPR";
52
+ }>;
53
+ provider: Schema.Literal<["esewa", "khalti", "connectips", "imepay", "fonepay", "sandbox"]>;
54
+ returnUrl: typeof Schema.String;
55
+ cancelUrl: Schema.optional<typeof Schema.String>;
56
+ metadata: Schema.optional<Schema.Record$<typeof Schema.String, typeof Schema.Any>>;
57
+ }>;
58
+ /**
59
+ * Schema for a checkout session response.
60
+ */
61
+ declare const CheckoutSessionSchema: Schema.Struct<{
62
+ id: Schema.brand<typeof Schema.String, "CheckoutSessionId">;
63
+ checkout_url: typeof Schema.String;
64
+ payment_method: Schema.Struct<{
65
+ type: Schema.Literal<["esewa", "khalti", "connectips", "imepay", "fonepay", "sandbox"]>;
66
+ url: Schema.optional<typeof Schema.String>;
67
+ method: Schema.optional<Schema.Union<[Schema.Literal<["GET"]>, Schema.Literal<["POST"]>]>>;
68
+ fields: Schema.optional<Schema.Record$<typeof Schema.String, typeof Schema.String>>;
69
+ }>;
70
+ }>;
71
+ /**
72
+ * Schema for a Payment response.
73
+ */
74
+ declare const PaymentSchema: Schema.Struct<{
75
+ id: Schema.brand<typeof Schema.String, "PaymentId">;
76
+ project_id: Schema.brand<typeof Schema.String, "ProjectId">;
77
+ amount: typeof Schema.Number;
78
+ currency: typeof Schema.String;
79
+ status: Schema.Union<[Schema.Literal<["pending"]>, Schema.Literal<["success"]>, Schema.Literal<["failed"]>]>;
80
+ provider_ref: Schema.optional<Schema.NullOr<typeof Schema.String>>;
81
+ metadata_json: Schema.optional<Schema.NullOr<Schema.Record$<typeof Schema.String, typeof Schema.Any>>>;
82
+ gateway_response: Schema.optional<Schema.NullOr<Schema.Record$<typeof Schema.String, typeof Schema.Any>>>;
83
+ created_at: typeof Schema.String;
84
+ updated_at: Schema.optional<typeof Schema.String>;
85
+ }>;
86
+ /**
87
+ * Schema for a Project response.
88
+ */
89
+ declare const ProjectSchema: Schema.Struct<{
90
+ id: Schema.brand<typeof Schema.String, "ProjectId">;
91
+ name: typeof Schema.String;
92
+ api_key_secret: typeof Schema.String;
93
+ created_at: typeof Schema.String;
94
+ }>;
95
+ /**
96
+ * Higher-order schema for paginated responses.
97
+ */
98
+ declare const PaginatedResponseSchema: <A, I>(item: Schema.Schema<A, I>) => Schema.Struct<{
99
+ data: Schema.Array$<Schema.Schema<A, I, never>>;
100
+ meta: Schema.Struct<{
101
+ total: Schema.NullOr<typeof Schema.Number>;
102
+ limit: typeof Schema.Number;
103
+ offset: typeof Schema.Number;
104
+ }>;
105
+ }>;
106
+ type CheckoutSession = Schema.Schema.Type<typeof CheckoutSessionSchema>;
107
+ type Payment = Schema.Schema.Type<typeof PaymentSchema>;
108
+ type Project = Schema.Schema.Type<typeof ProjectSchema>;
109
+ interface PaginatedResponse<T> {
110
+ readonly data: ReadonlyArray<T>;
111
+ readonly meta: {
112
+ readonly total: number | null;
113
+ readonly limit: number;
114
+ readonly offset: number;
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Effect-based resource for PayArk Checkout.
120
+ */
121
+ declare class CheckoutEffect {
122
+ private readonly config;
123
+ constructor(config: PayArkConfig);
124
+ /**
125
+ * Create a new checkout session.
126
+ *
127
+ * @param params - Configuration for the checkout session.
128
+ * @returns Effect that resolves to the created checkout session.
129
+ */
130
+ create(params: CreateCheckoutParams): Effect.Effect<CheckoutSession, PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
131
+ }
132
+
133
+ /**
134
+ * Effect-based resource for PayArk Payments.
135
+ */
136
+ declare class PaymentsEffect {
137
+ private readonly config;
138
+ constructor(config: PayArkConfig);
139
+ /**
140
+ * List payments for the authenticated project.
141
+ *
142
+ * @param params - Optional pagination parameters.
143
+ * @returns Effect that resolves to paginated payments.
144
+ */
145
+ list(params?: ListPaymentsParams): Effect.Effect<PaginatedResponse<Payment>, PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
146
+ /**
147
+ * Retrieve a single payment by its ID.
148
+ *
149
+ * @param id - The payment identifier.
150
+ * @returns Effect that resolves to the payment object.
151
+ */
152
+ retrieve(id: string): Effect.Effect<Payment, PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
153
+ }
154
+
155
+ /**
156
+ * Effect-based resource for PayArk Projects.
157
+ */
158
+ declare class ProjectsEffect {
159
+ private readonly config;
160
+ constructor(config: PayArkConfig);
161
+ /**
162
+ * List all projects belonging to the authenticated account.
163
+ *
164
+ * @returns Effect that resolves to an array of projects.
165
+ */
166
+ list(): Effect.Effect<readonly Project[], PayArkEffectError | ParseResult.ParseError, HttpClient.HttpClient>;
167
+ }
168
+
169
+ /**
170
+ * Main entry point for the Effect-based PayArk API.
171
+ */
172
+ declare class PayArkEffect {
173
+ private readonly config;
174
+ private _checkout?;
175
+ private _payments?;
176
+ private _projects?;
177
+ constructor(config: PayArkConfig);
178
+ /**
179
+ * Checkout sessions resource (Effect).
180
+ */
181
+ get checkout(): CheckoutEffect;
182
+ /**
183
+ * Payments resource (Effect).
184
+ */
185
+ get payments(): PaymentsEffect;
186
+ /**
187
+ * Projects resource (Effect).
188
+ */
189
+ get projects(): ProjectsEffect;
190
+ }
191
+ declare const PayArk_base: Context.TagClass<PayArk, "@payark/sdk-effect/PayArk", PayArkEffect>;
192
+ /**
193
+ * Service tag for the PayArk API.
194
+ */
195
+ declare class PayArk extends PayArk_base {
196
+ /**
197
+ * Create a Layer that provides the PayArk service.
198
+ */
199
+ static readonly Live: (config: PayArkConfig) => Layer.Layer<PayArk, never, never>;
200
+ }
201
+
202
+ export { CheckoutSessionId, CheckoutSessionSchema, CreateCheckoutSchema, PaginatedResponseSchema, PayArk, PayArkEffect, PayArkEffectError, PaymentId, PaymentSchema, ProjectId, ProjectSchema, ProviderSchema };
package/dist/index.js ADDED
@@ -0,0 +1,315 @@
1
+ 'use strict';
2
+
3
+ var effect = require('effect');
4
+ var schema = require('@effect/schema');
5
+ var platform = require('@effect/platform');
6
+ var sdk = require('@payark/sdk');
7
+
8
+ // src/index.ts
9
+ var PayArkEffectError = class extends effect.Data.TaggedError("PayArkEffectError") {
10
+ /** Human-readable representation for logging/debugging. */
11
+ toString() {
12
+ return `[PayArkEffectError: ${this.code}] ${this.message} (HTTP ${this.statusCode})`;
13
+ }
14
+ };
15
+ var PayArkConfigService = class extends effect.Context.Tag("PayArkConfigService")() {
16
+ };
17
+ var request = (method, path, options) => effect.Effect.gen(function* (_) {
18
+ const config = yield* _(PayArkConfigService);
19
+ const client = yield* _(platform.HttpClient.HttpClient);
20
+ const baseUrl = (config.baseUrl ?? "https://api.payark.com").replace(
21
+ /\/+$/,
22
+ ""
23
+ );
24
+ const url = new URL(`${baseUrl}${path}`);
25
+ if (options?.query) {
26
+ for (const [key, value] of Object.entries(options.query)) {
27
+ if (value !== void 0) {
28
+ url.searchParams.set(key, String(value));
29
+ }
30
+ }
31
+ }
32
+ const headers = {
33
+ Authorization: `Bearer ${config.apiKey}`,
34
+ "Content-Type": "application/json",
35
+ Accept: "application/json",
36
+ "User-Agent": `payark-sdk-effect/${sdk.SDK_VERSION}`,
37
+ ...options?.headers
38
+ };
39
+ if (config.sandbox) {
40
+ headers["x-sandbox-mode"] = "true";
41
+ }
42
+ let req = platform.HttpClientRequest.make(method)(url.toString()).pipe(
43
+ platform.HttpClientRequest.setHeaders(headers)
44
+ );
45
+ if (options?.body) {
46
+ req = yield* _(
47
+ platform.HttpClientRequest.bodyJson(options.body)(req).pipe(
48
+ effect.Effect.mapError(
49
+ (e) => new PayArkEffectError({
50
+ message: `Invalid request body: ${String(e)}`,
51
+ statusCode: 400,
52
+ code: "invalid_request_error"
53
+ })
54
+ )
55
+ )
56
+ );
57
+ }
58
+ const response = yield* _(
59
+ client.execute(req).pipe(
60
+ effect.Effect.mapError(
61
+ (e) => new PayArkEffectError({
62
+ message: `Network error: ${e.message}`,
63
+ statusCode: 0,
64
+ code: "connection_error"
65
+ })
66
+ )
67
+ )
68
+ );
69
+ if (response.status >= 200 && response.status < 300) {
70
+ if (response.status === 204) return {};
71
+ return yield* _(
72
+ response.json.pipe(
73
+ effect.Effect.mapError(
74
+ (e) => new PayArkEffectError({
75
+ message: `Failed to parse response: ${String(e)}`,
76
+ statusCode: response.status,
77
+ code: "api_error"
78
+ })
79
+ )
80
+ )
81
+ );
82
+ }
83
+ const errorBody = yield* _(
84
+ response.json.pipe(
85
+ effect.Effect.catchAll(() => effect.Effect.succeed({ error: void 0 }))
86
+ )
87
+ );
88
+ return yield* _(
89
+ effect.Effect.fail(
90
+ new PayArkEffectError({
91
+ message: errorBody?.error || `Request failed with status ${response.status}`,
92
+ statusCode: response.status,
93
+ code: mapStatusToCode(response.status),
94
+ raw: errorBody
95
+ })
96
+ )
97
+ );
98
+ });
99
+ function mapStatusToCode(status) {
100
+ if (status === 401) return "authentication_error";
101
+ if (status === 403) return "permission_error";
102
+ if (status === 400 || status === 422) return "invalid_request_error";
103
+ if (status === 404) return "not_found_error";
104
+ if (status === 429) return "rate_limit_error";
105
+ if (status >= 500) return "api_error";
106
+ return "unknown_error";
107
+ }
108
+ var ProviderSchema = schema.Schema.Union(
109
+ schema.Schema.Literal(
110
+ "esewa",
111
+ "khalti",
112
+ "connectips",
113
+ "imepay",
114
+ "fonepay",
115
+ "sandbox"
116
+ )
117
+ );
118
+ var CheckoutSessionId = schema.Schema.String.pipe(
119
+ schema.Schema.brand("CheckoutSessionId")
120
+ );
121
+ var PaymentId = schema.Schema.String.pipe(schema.Schema.brand("PaymentId"));
122
+ var ProjectId = schema.Schema.String.pipe(schema.Schema.brand("ProjectId"));
123
+ var CreateCheckoutSchema = schema.Schema.Struct({
124
+ amount: schema.Schema.Number,
125
+ currency: schema.Schema.optionalWith(schema.Schema.String, {
126
+ default: () => "NPR"
127
+ }),
128
+ provider: ProviderSchema,
129
+ returnUrl: schema.Schema.String,
130
+ cancelUrl: schema.Schema.optional(schema.Schema.String),
131
+ metadata: schema.Schema.optional(
132
+ schema.Schema.Record({ key: schema.Schema.String, value: schema.Schema.Any })
133
+ )
134
+ });
135
+ var CheckoutSessionSchema = schema.Schema.Struct({
136
+ id: CheckoutSessionId,
137
+ checkout_url: schema.Schema.String,
138
+ payment_method: schema.Schema.Struct({
139
+ type: ProviderSchema,
140
+ url: schema.Schema.optional(schema.Schema.String),
141
+ method: schema.Schema.optional(
142
+ schema.Schema.Union(schema.Schema.Literal("GET"), schema.Schema.Literal("POST"))
143
+ ),
144
+ fields: schema.Schema.optional(
145
+ schema.Schema.Record({ key: schema.Schema.String, value: schema.Schema.String })
146
+ )
147
+ })
148
+ });
149
+ var PaymentSchema = schema.Schema.Struct({
150
+ id: PaymentId,
151
+ project_id: ProjectId,
152
+ amount: schema.Schema.Number,
153
+ currency: schema.Schema.String,
154
+ status: schema.Schema.Union(
155
+ schema.Schema.Literal("pending"),
156
+ schema.Schema.Literal("success"),
157
+ schema.Schema.Literal("failed")
158
+ ),
159
+ provider_ref: schema.Schema.optional(schema.Schema.NullOr(schema.Schema.String)),
160
+ metadata_json: schema.Schema.optional(
161
+ schema.Schema.NullOr(schema.Schema.Record({ key: schema.Schema.String, value: schema.Schema.Any }))
162
+ ),
163
+ gateway_response: schema.Schema.optional(
164
+ schema.Schema.NullOr(schema.Schema.Record({ key: schema.Schema.String, value: schema.Schema.Any }))
165
+ ),
166
+ created_at: schema.Schema.String,
167
+ updated_at: schema.Schema.optional(schema.Schema.String)
168
+ });
169
+ var ProjectSchema = schema.Schema.Struct({
170
+ id: ProjectId,
171
+ name: schema.Schema.String,
172
+ api_key_secret: schema.Schema.String,
173
+ created_at: schema.Schema.String
174
+ });
175
+ var PaginatedResponseSchema = (item) => schema.Schema.Struct({
176
+ data: schema.Schema.Array(item),
177
+ meta: schema.Schema.Struct({
178
+ total: schema.Schema.NullOr(schema.Schema.Number),
179
+ limit: schema.Schema.Number,
180
+ offset: schema.Schema.Number
181
+ })
182
+ });
183
+
184
+ // src/resources/checkout.ts
185
+ var CheckoutEffect = class {
186
+ constructor(config) {
187
+ this.config = config;
188
+ }
189
+ /**
190
+ * Create a new checkout session.
191
+ *
192
+ * @param params - Configuration for the checkout session.
193
+ * @returns Effect that resolves to the created checkout session.
194
+ */
195
+ create(params) {
196
+ return request("POST", "/v1/checkout", { body: params }).pipe(
197
+ effect.Effect.flatMap(schema.Schema.decodeUnknown(CheckoutSessionSchema)),
198
+ effect.Effect.provideService(PayArkConfigService, this.config)
199
+ );
200
+ }
201
+ };
202
+ var PaymentsEffect = class {
203
+ constructor(config) {
204
+ this.config = config;
205
+ }
206
+ /**
207
+ * List payments for the authenticated project.
208
+ *
209
+ * @param params - Optional pagination parameters.
210
+ * @returns Effect that resolves to paginated payments.
211
+ */
212
+ list(params = {}) {
213
+ return request("GET", "/v1/payments", {
214
+ query: {
215
+ limit: params.limit,
216
+ offset: params.offset,
217
+ projectId: params.projectId
218
+ }
219
+ }).pipe(
220
+ effect.Effect.flatMap(
221
+ schema.Schema.decodeUnknown(PaginatedResponseSchema(PaymentSchema))
222
+ ),
223
+ effect.Effect.provideService(PayArkConfigService, this.config)
224
+ );
225
+ }
226
+ /**
227
+ * Retrieve a single payment by its ID.
228
+ *
229
+ * @param id - The payment identifier.
230
+ * @returns Effect that resolves to the payment object.
231
+ */
232
+ retrieve(id) {
233
+ return request(
234
+ "GET",
235
+ `/v1/payments/${encodeURIComponent(id)}`
236
+ ).pipe(
237
+ effect.Effect.flatMap(schema.Schema.decodeUnknown(PaymentSchema)),
238
+ effect.Effect.provideService(PayArkConfigService, this.config)
239
+ );
240
+ }
241
+ };
242
+ var ProjectsEffect = class {
243
+ constructor(config) {
244
+ this.config = config;
245
+ }
246
+ /**
247
+ * List all projects belonging to the authenticated account.
248
+ *
249
+ * @returns Effect that resolves to an array of projects.
250
+ */
251
+ list() {
252
+ return request("GET", "/v1/projects").pipe(
253
+ effect.Effect.flatMap(schema.Schema.decodeUnknown(schema.Schema.Array(ProjectSchema))),
254
+ effect.Effect.provideService(PayArkConfigService, this.config)
255
+ );
256
+ }
257
+ };
258
+
259
+ // src/index.ts
260
+ var PayArkEffect = class {
261
+ constructor(config) {
262
+ this.config = config;
263
+ }
264
+ _checkout;
265
+ _payments;
266
+ _projects;
267
+ /**
268
+ * Checkout sessions resource (Effect).
269
+ */
270
+ get checkout() {
271
+ if (!this._checkout) {
272
+ this._checkout = new CheckoutEffect(this.config);
273
+ }
274
+ return this._checkout;
275
+ }
276
+ /**
277
+ * Payments resource (Effect).
278
+ */
279
+ get payments() {
280
+ if (!this._payments) {
281
+ this._payments = new PaymentsEffect(this.config);
282
+ }
283
+ return this._payments;
284
+ }
285
+ /**
286
+ * Projects resource (Effect).
287
+ */
288
+ get projects() {
289
+ if (!this._projects) {
290
+ this._projects = new ProjectsEffect(this.config);
291
+ }
292
+ return this._projects;
293
+ }
294
+ };
295
+ var PayArk = class _PayArk extends effect.Context.Tag("@payark/sdk-effect/PayArk")() {
296
+ /**
297
+ * Create a Layer that provides the PayArk service.
298
+ */
299
+ static Live = (config) => effect.Layer.succeed(_PayArk, new PayArkEffect(config));
300
+ };
301
+
302
+ exports.CheckoutSessionId = CheckoutSessionId;
303
+ exports.CheckoutSessionSchema = CheckoutSessionSchema;
304
+ exports.CreateCheckoutSchema = CreateCheckoutSchema;
305
+ exports.PaginatedResponseSchema = PaginatedResponseSchema;
306
+ exports.PayArk = PayArk;
307
+ exports.PayArkEffect = PayArkEffect;
308
+ exports.PayArkEffectError = PayArkEffectError;
309
+ exports.PaymentId = PaymentId;
310
+ exports.PaymentSchema = PaymentSchema;
311
+ exports.ProjectId = ProjectId;
312
+ exports.ProjectSchema = ProjectSchema;
313
+ exports.ProviderSchema = ProviderSchema;
314
+ //# sourceMappingURL=index.js.map
315
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/schemas.ts","../src/resources/checkout.ts","../src/resources/payments.ts","../src/resources/projects.ts","../src/index.ts"],"names":["Data","Context","Effect","HttpClient","SDK_VERSION","HttpClientRequest","Schema","Layer"],"mappings":";;;;;;;;AAOO,IAAM,iBAAA,GAAN,cAAgCA,WAAA,CAAK,WAAA,CAAY,mBAAmB,CAAA,CAKxE;AAAA;AAAA,EAEQ,QAAA,GAAmB;AAC1B,IAAA,OAAO,CAAA,oBAAA,EAAuB,KAAK,IAAI,CAAA,EAAA,EAAK,KAAK,OAAO,CAAA,OAAA,EAAU,KAAK,UAAU,CAAA,CAAA,CAAA;AAAA,EACnF;AACF;ACRO,IAAM,sBAAN,cAAkCC,cAAA,CAAQ,GAAA,CAAI,qBAAqB,GAGxE,CAAE;AAAC,CAAA;AAKE,IAAM,OAAA,GAAU,CACrB,MAAA,EACA,IAAA,EACA,YAUAC,aAAA,CAAO,GAAA,CAAI,WAAW,CAAA,EAAG;AACvB,EAAA,MAAM,MAAA,GAAS,OAAO,CAAA,CAAE,mBAAmB,CAAA;AAC3C,EAAA,MAAM,MAAA,GAAS,OAAO,CAAA,CAAEC,mBAAA,CAAW,UAAU,CAAA;AAE7C,EAAA,MAAM,OAAA,GAAA,CAAW,MAAA,CAAO,OAAA,IAAW,wBAAA,EAA0B,OAAA;AAAA,IAC3D,MAAA;AAAA,IACA;AAAA,GACF;AACA,EAAA,MAAM,MAAM,IAAI,GAAA,CAAI,GAAG,OAAO,CAAA,EAAG,IAAI,CAAA,CAAE,CAAA;AAEvC,EAAA,IAAI,SAAS,KAAA,EAAO;AAClB,IAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,OAAA,CAAQ,KAAK,CAAA,EAAG;AACxD,MAAA,IAAI,UAAU,MAAA,EAAW;AACvB,QAAA,GAAA,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F;AAKO,IAAM,SAAN,MAAM,OAAA,SAAeD,eAAQ,GAAA,CAAI,2BAA2B,GAGjE,CAAE;AAAA;AAAA;AAAA;AAAA,EAIF,OAAgB,IAAA,GAAO,CAAC,MAAA,KACtBM,YAAA,CAAM,QAAQ,OAAA,EAAQ,IAAI,YAAA,CAAa,MAAM,CAAC,CAAA;AAClD","file":"index.js","sourcesContent":["import { Data } from \"effect\";\nimport type { PayArkErrorCode, PayArkErrorBody } from \"@payark/sdk\";\n\n/**\n * Effect-compatible error class for PayArk SDK.\n * Extends Data.TaggedError for easy matching in Effect.catchTag.\n */\nexport class PayArkEffectError extends Data.TaggedError(\"PayArkEffectError\")<{\n readonly message: string;\n readonly statusCode: number;\n readonly code: PayArkErrorCode;\n readonly raw?: PayArkErrorBody;\n}> {\n /** Human-readable representation for logging/debugging. */\n override toString(): string {\n return `[PayArkEffectError: ${this.code}] ${this.message} (HTTP ${this.statusCode})`;\n }\n}\n","import { Effect, Context } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { PayArkEffectError } from \"./errors\";\nimport { SDK_VERSION } from \"@payark/sdk\";\nimport type { PayArkConfig, PayArkErrorCode } from \"@payark/sdk\";\n\n/**\n * Service tag for the PayArk configuration.\n */\nexport class PayArkConfigService extends Context.Tag(\"PayArkConfigService\")<\n PayArkConfigService,\n PayArkConfig\n>() {}\n\n/**\n * Executes an HTTP request using Effect and returns the JSON body or a PayArkEffectError.\n */\nexport const request = <T>(\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n options?: {\n readonly query?: Record<string, string | number | undefined>;\n readonly body?: any;\n readonly headers?: Record<string, string>;\n },\n): Effect.Effect<\n T,\n PayArkEffectError,\n PayArkConfigService | HttpClient.HttpClient\n> =>\n Effect.gen(function* (_) {\n const config = yield* _(PayArkConfigService);\n const client = yield* _(HttpClient.HttpClient);\n\n const baseUrl = (config.baseUrl ?? \"https://api.payark.com\").replace(\n /\\/+$/,\n \"\",\n );\n const url = new URL(`${baseUrl}${path}`);\n\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${config.apiKey}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"User-Agent\": `payark-sdk-effect/${SDK_VERSION}`,\n ...options?.headers,\n };\n\n if (config.sandbox) {\n headers[\"x-sandbox-mode\"] = \"true\";\n }\n\n let req = HttpClientRequest.make(method)(url.toString()).pipe(\n HttpClientRequest.setHeaders(headers),\n );\n\n if (options?.body) {\n req = yield* _(\n HttpClientRequest.bodyJson(options.body)(req).pipe(\n Effect.mapError(\n (e) =>\n new PayArkEffectError({\n message: `Invalid request body: ${String(e)}`,\n statusCode: 400,\n code: \"invalid_request_error\",\n }),\n ),\n ),\n );\n }\n\n const response = yield* _(\n client.execute(req).pipe(\n Effect.mapError(\n (e) =>\n new PayArkEffectError({\n message: `Network error: ${e.message}`,\n statusCode: 0,\n code: \"connection_error\",\n }),\n ),\n ),\n );\n\n if (response.status >= 200 && response.status < 300) {\n if (response.status === 204) return {} as T;\n return (yield* _(\n response.json.pipe(\n Effect.mapError(\n (e) =>\n new PayArkEffectError({\n message: `Failed to parse response: ${String(e)}`,\n statusCode: response.status,\n code: \"api_error\",\n }),\n ),\n ),\n )) as T;\n }\n\n const errorBody: any = yield* _(\n response.json.pipe(\n Effect.catchAll(() => Effect.succeed({ error: undefined })),\n ),\n );\n\n return yield* _(\n Effect.fail(\n new PayArkEffectError({\n message:\n errorBody?.error || `Request failed with status ${response.status}`,\n statusCode: response.status,\n code: mapStatusToCode(response.status),\n raw: errorBody,\n }),\n ),\n );\n });\n\nfunction mapStatusToCode(status: number): PayArkErrorCode {\n if (status === 401) return \"authentication_error\";\n if (status === 403) return \"permission_error\";\n if (status === 400 || status === 422) return \"invalid_request_error\";\n if (status === 404) return \"not_found_error\";\n if (status === 429) return \"rate_limit_error\";\n if (status >= 500) return \"api_error\";\n return \"unknown_error\";\n}\n","import { Schema } from \"@effect/schema\";\n\n/**\n * Supported payment providers on the PayArk platform.\n */\nexport const ProviderSchema = Schema.Union(\n Schema.Literal(\n \"esewa\",\n \"khalti\",\n \"connectips\",\n \"imepay\",\n \"fonepay\",\n \"sandbox\",\n ),\n);\n\n// ── Branded Types ──────────────────────────────────────────────────────────\n\n/**\n * Branded Type for Checkout Session ID.\n */\nexport const CheckoutSessionId = Schema.String.pipe(\n Schema.brand(\"CheckoutSessionId\"),\n);\nexport type CheckoutSessionId = Schema.Schema.Type<typeof CheckoutSessionId>;\n\n/**\n * Branded Type for Payment ID.\n */\nexport const PaymentId = Schema.String.pipe(Schema.brand(\"PaymentId\"));\nexport type PaymentId = Schema.Schema.Type<typeof PaymentId>;\n\n/**\n * Branded Type for Project ID.\n */\nexport const ProjectId = Schema.String.pipe(Schema.brand(\"ProjectId\"));\nexport type ProjectId = Schema.Schema.Type<typeof ProjectId>;\n\n/**\n * Schema for creating a checkout session.\n */\nexport const CreateCheckoutSchema = Schema.Struct({\n amount: Schema.Number,\n currency: Schema.optionalWith(Schema.String, {\n default: () => \"NPR\" as const,\n }),\n provider: ProviderSchema,\n returnUrl: Schema.String,\n cancelUrl: Schema.optional(Schema.String),\n metadata: Schema.optional(\n Schema.Record({ key: Schema.String, value: Schema.Any }),\n ),\n});\n\n/**\n * Schema for a checkout session response.\n */\nexport const CheckoutSessionSchema = Schema.Struct({\n id: CheckoutSessionId,\n checkout_url: Schema.String,\n payment_method: Schema.Struct({\n type: ProviderSchema,\n url: Schema.optional(Schema.String),\n method: Schema.optional(\n Schema.Union(Schema.Literal(\"GET\"), Schema.Literal(\"POST\")),\n ),\n fields: Schema.optional(\n Schema.Record({ key: Schema.String, value: Schema.String }),\n ),\n }),\n});\n\n/**\n * Schema for a Payment response.\n */\nexport const PaymentSchema = Schema.Struct({\n id: PaymentId,\n project_id: ProjectId,\n amount: Schema.Number,\n currency: Schema.String,\n status: Schema.Union(\n Schema.Literal(\"pending\"),\n Schema.Literal(\"success\"),\n Schema.Literal(\"failed\"),\n ),\n provider_ref: Schema.optional(Schema.NullOr(Schema.String)),\n metadata_json: Schema.optional(\n Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Any })),\n ),\n gateway_response: Schema.optional(\n Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Any })),\n ),\n created_at: Schema.String,\n updated_at: Schema.optional(Schema.String),\n});\n\n/**\n * Schema for a Project response.\n */\nexport const ProjectSchema = Schema.Struct({\n id: ProjectId,\n name: Schema.String,\n api_key_secret: Schema.String,\n created_at: Schema.String,\n});\n\n/**\n * Higher-order schema for paginated responses.\n */\nexport const PaginatedResponseSchema = <A, I>(item: Schema.Schema<A, I>) =>\n Schema.Struct({\n data: Schema.Array(item),\n meta: Schema.Struct({\n total: Schema.NullOr(Schema.Number),\n limit: Schema.Number,\n offset: Schema.Number,\n }),\n });\n\n// ── Inferred Types ─────────────────────────────────────────────────────────\n\nexport type CheckoutSession = Schema.Schema.Type<typeof CheckoutSessionSchema>;\nexport type Payment = Schema.Schema.Type<typeof PaymentSchema>;\nexport type Project = Schema.Schema.Type<typeof ProjectSchema>;\nexport interface PaginatedResponse<T> {\n readonly data: ReadonlyArray<T>;\n readonly meta: {\n readonly total: number | null;\n readonly limit: number;\n readonly offset: number;\n };\n}\n","import { Effect } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { PayArkConfigService, request } from \"../http\";\nimport { CheckoutSessionSchema } from \"../schemas\";\nimport { PayArkEffectError } from \"../errors\";\nimport type { CreateCheckoutParams, PayArkConfig } from \"@payark/sdk\";\nimport type { CheckoutSession } from \"../schemas\";\nimport type { HttpClient } from \"@effect/platform\";\nimport type { ParseResult } from \"@effect/schema\";\n\n/**\n * Effect-based resource for PayArk Checkout.\n */\nexport class CheckoutEffect {\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * Create a new checkout session.\n *\n * @param params - Configuration for the checkout session.\n * @returns Effect that resolves to the created checkout session.\n */\n create(\n params: CreateCheckoutParams,\n ): Effect.Effect<\n CheckoutSession,\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\"POST\", \"/v1/checkout\", { body: params }).pipe(\n Effect.flatMap(Schema.decodeUnknown(CheckoutSessionSchema)),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n}\n","import { Effect } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { PayArkConfigService, request } from \"../http\";\nimport { PaymentSchema, PaginatedResponseSchema } from \"../schemas\";\nimport { PayArkEffectError } from \"../errors\";\nimport type { PayArkConfig, ListPaymentsParams } from \"@payark/sdk\";\nimport type { Payment, PaginatedResponse } from \"../schemas\";\nimport type { HttpClient } from \"@effect/platform\";\nimport type { ParseResult } from \"@effect/schema\";\n\n/**\n * Effect-based resource for PayArk Payments.\n */\nexport class PaymentsEffect {\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * List payments for the authenticated project.\n *\n * @param params - Optional pagination parameters.\n * @returns Effect that resolves to paginated payments.\n */\n list(\n params: ListPaymentsParams = {},\n ): Effect.Effect<\n PaginatedResponse<Payment>,\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\"GET\", \"/v1/payments\", {\n query: {\n limit: params.limit,\n offset: params.offset,\n projectId: params.projectId,\n },\n }).pipe(\n Effect.flatMap(\n Schema.decodeUnknown(PaginatedResponseSchema(PaymentSchema)),\n ),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n\n /**\n * Retrieve a single payment by its ID.\n *\n * @param id - The payment identifier.\n * @returns Effect that resolves to the payment object.\n */\n retrieve(\n id: string,\n ): Effect.Effect<\n Payment,\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\n \"GET\",\n `/v1/payments/${encodeURIComponent(id)}`,\n ).pipe(\n Effect.flatMap(Schema.decodeUnknown(PaymentSchema)),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n}\n","import { Effect } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { PayArkConfigService, request } from \"../http\";\nimport { ProjectSchema } from \"../schemas\";\nimport { PayArkEffectError } from \"../errors\";\nimport type { PayArkConfig } from \"@payark/sdk\";\nimport type { Project } from \"../schemas\";\nimport type { HttpClient } from \"@effect/platform\";\nimport type { ParseResult } from \"@effect/schema\";\n\n/**\n * Effect-based resource for PayArk Projects.\n */\nexport class ProjectsEffect {\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * List all projects belonging to the authenticated account.\n *\n * @returns Effect that resolves to an array of projects.\n */\n list(): Effect.Effect<\n readonly Project[],\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\"GET\", \"/v1/projects\").pipe(\n Effect.flatMap(Schema.decodeUnknown(Schema.Array(ProjectSchema))),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n}\n","import { Context, Layer } from \"effect\";\nimport { CheckoutEffect } from \"./resources/checkout\";\nimport { PaymentsEffect } from \"./resources/payments\";\nimport { ProjectsEffect } from \"./resources/projects\";\nimport type { PayArkConfig } from \"@payark/sdk\";\n\n/**\n * Main entry point for the Effect-based PayArk API.\n */\nexport class PayArkEffect {\n private _checkout?: CheckoutEffect;\n private _payments?: PaymentsEffect;\n private _projects?: ProjectsEffect;\n\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * Checkout sessions resource (Effect).\n */\n get checkout(): CheckoutEffect {\n if (!this._checkout) {\n this._checkout = new CheckoutEffect(this.config);\n }\n return this._checkout;\n }\n\n /**\n * Payments resource (Effect).\n */\n get payments(): PaymentsEffect {\n if (!this._payments) {\n this._payments = new PaymentsEffect(this.config);\n }\n return this._payments;\n }\n\n /**\n * Projects resource (Effect).\n */\n get projects(): ProjectsEffect {\n if (!this._projects) {\n this._projects = new ProjectsEffect(this.config);\n }\n return this._projects;\n }\n}\n\n/**\n * Service tag for the PayArk API.\n */\nexport class PayArk extends Context.Tag(\"@payark/sdk-effect/PayArk\")<\n PayArk,\n PayArkEffect\n>() {\n /**\n * Create a Layer that provides the PayArk service.\n */\n static readonly Live = (config: PayArkConfig) =>\n Layer.succeed(PayArk, new PayArkEffect(config));\n}\n\nexport { PayArkEffectError } from \"./errors\";\nexport * from \"./schemas\";\nexport type {\n PayArkConfig,\n CheckoutSession,\n Payment,\n PaymentStatus,\n Project,\n ListPaymentsParams,\n PaginatedResponse,\n PaginationMeta,\n Provider,\n WebhookEvent,\n WebhookEventType,\n PayArkErrorBody,\n PayArkErrorCode,\n} from \"@payark/sdk\";\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,302 @@
1
+ import { Data, Context, Layer, Effect } from 'effect';
2
+ import { Schema } from '@effect/schema';
3
+ import { HttpClient, HttpClientRequest } from '@effect/platform';
4
+ import { SDK_VERSION } from '@payark/sdk';
5
+
6
+ // src/index.ts
7
+ var PayArkEffectError = class extends Data.TaggedError("PayArkEffectError") {
8
+ /** Human-readable representation for logging/debugging. */
9
+ toString() {
10
+ return `[PayArkEffectError: ${this.code}] ${this.message} (HTTP ${this.statusCode})`;
11
+ }
12
+ };
13
+ var PayArkConfigService = class extends Context.Tag("PayArkConfigService")() {
14
+ };
15
+ var request = (method, path, options) => Effect.gen(function* (_) {
16
+ const config = yield* _(PayArkConfigService);
17
+ const client = yield* _(HttpClient.HttpClient);
18
+ const baseUrl = (config.baseUrl ?? "https://api.payark.com").replace(
19
+ /\/+$/,
20
+ ""
21
+ );
22
+ const url = new URL(`${baseUrl}${path}`);
23
+ if (options?.query) {
24
+ for (const [key, value] of Object.entries(options.query)) {
25
+ if (value !== void 0) {
26
+ url.searchParams.set(key, String(value));
27
+ }
28
+ }
29
+ }
30
+ const headers = {
31
+ Authorization: `Bearer ${config.apiKey}`,
32
+ "Content-Type": "application/json",
33
+ Accept: "application/json",
34
+ "User-Agent": `payark-sdk-effect/${SDK_VERSION}`,
35
+ ...options?.headers
36
+ };
37
+ if (config.sandbox) {
38
+ headers["x-sandbox-mode"] = "true";
39
+ }
40
+ let req = HttpClientRequest.make(method)(url.toString()).pipe(
41
+ HttpClientRequest.setHeaders(headers)
42
+ );
43
+ if (options?.body) {
44
+ req = yield* _(
45
+ HttpClientRequest.bodyJson(options.body)(req).pipe(
46
+ Effect.mapError(
47
+ (e) => new PayArkEffectError({
48
+ message: `Invalid request body: ${String(e)}`,
49
+ statusCode: 400,
50
+ code: "invalid_request_error"
51
+ })
52
+ )
53
+ )
54
+ );
55
+ }
56
+ const response = yield* _(
57
+ client.execute(req).pipe(
58
+ Effect.mapError(
59
+ (e) => new PayArkEffectError({
60
+ message: `Network error: ${e.message}`,
61
+ statusCode: 0,
62
+ code: "connection_error"
63
+ })
64
+ )
65
+ )
66
+ );
67
+ if (response.status >= 200 && response.status < 300) {
68
+ if (response.status === 204) return {};
69
+ return yield* _(
70
+ response.json.pipe(
71
+ Effect.mapError(
72
+ (e) => new PayArkEffectError({
73
+ message: `Failed to parse response: ${String(e)}`,
74
+ statusCode: response.status,
75
+ code: "api_error"
76
+ })
77
+ )
78
+ )
79
+ );
80
+ }
81
+ const errorBody = yield* _(
82
+ response.json.pipe(
83
+ Effect.catchAll(() => Effect.succeed({ error: void 0 }))
84
+ )
85
+ );
86
+ return yield* _(
87
+ Effect.fail(
88
+ new PayArkEffectError({
89
+ message: errorBody?.error || `Request failed with status ${response.status}`,
90
+ statusCode: response.status,
91
+ code: mapStatusToCode(response.status),
92
+ raw: errorBody
93
+ })
94
+ )
95
+ );
96
+ });
97
+ function mapStatusToCode(status) {
98
+ if (status === 401) return "authentication_error";
99
+ if (status === 403) return "permission_error";
100
+ if (status === 400 || status === 422) return "invalid_request_error";
101
+ if (status === 404) return "not_found_error";
102
+ if (status === 429) return "rate_limit_error";
103
+ if (status >= 500) return "api_error";
104
+ return "unknown_error";
105
+ }
106
+ var ProviderSchema = Schema.Union(
107
+ Schema.Literal(
108
+ "esewa",
109
+ "khalti",
110
+ "connectips",
111
+ "imepay",
112
+ "fonepay",
113
+ "sandbox"
114
+ )
115
+ );
116
+ var CheckoutSessionId = Schema.String.pipe(
117
+ Schema.brand("CheckoutSessionId")
118
+ );
119
+ var PaymentId = Schema.String.pipe(Schema.brand("PaymentId"));
120
+ var ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
121
+ var CreateCheckoutSchema = Schema.Struct({
122
+ amount: Schema.Number,
123
+ currency: Schema.optionalWith(Schema.String, {
124
+ default: () => "NPR"
125
+ }),
126
+ provider: ProviderSchema,
127
+ returnUrl: Schema.String,
128
+ cancelUrl: Schema.optional(Schema.String),
129
+ metadata: Schema.optional(
130
+ Schema.Record({ key: Schema.String, value: Schema.Any })
131
+ )
132
+ });
133
+ var CheckoutSessionSchema = Schema.Struct({
134
+ id: CheckoutSessionId,
135
+ checkout_url: Schema.String,
136
+ payment_method: Schema.Struct({
137
+ type: ProviderSchema,
138
+ url: Schema.optional(Schema.String),
139
+ method: Schema.optional(
140
+ Schema.Union(Schema.Literal("GET"), Schema.Literal("POST"))
141
+ ),
142
+ fields: Schema.optional(
143
+ Schema.Record({ key: Schema.String, value: Schema.String })
144
+ )
145
+ })
146
+ });
147
+ var PaymentSchema = Schema.Struct({
148
+ id: PaymentId,
149
+ project_id: ProjectId,
150
+ amount: Schema.Number,
151
+ currency: Schema.String,
152
+ status: Schema.Union(
153
+ Schema.Literal("pending"),
154
+ Schema.Literal("success"),
155
+ Schema.Literal("failed")
156
+ ),
157
+ provider_ref: Schema.optional(Schema.NullOr(Schema.String)),
158
+ metadata_json: Schema.optional(
159
+ Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Any }))
160
+ ),
161
+ gateway_response: Schema.optional(
162
+ Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Any }))
163
+ ),
164
+ created_at: Schema.String,
165
+ updated_at: Schema.optional(Schema.String)
166
+ });
167
+ var ProjectSchema = Schema.Struct({
168
+ id: ProjectId,
169
+ name: Schema.String,
170
+ api_key_secret: Schema.String,
171
+ created_at: Schema.String
172
+ });
173
+ var PaginatedResponseSchema = (item) => Schema.Struct({
174
+ data: Schema.Array(item),
175
+ meta: Schema.Struct({
176
+ total: Schema.NullOr(Schema.Number),
177
+ limit: Schema.Number,
178
+ offset: Schema.Number
179
+ })
180
+ });
181
+
182
+ // src/resources/checkout.ts
183
+ var CheckoutEffect = class {
184
+ constructor(config) {
185
+ this.config = config;
186
+ }
187
+ /**
188
+ * Create a new checkout session.
189
+ *
190
+ * @param params - Configuration for the checkout session.
191
+ * @returns Effect that resolves to the created checkout session.
192
+ */
193
+ create(params) {
194
+ return request("POST", "/v1/checkout", { body: params }).pipe(
195
+ Effect.flatMap(Schema.decodeUnknown(CheckoutSessionSchema)),
196
+ Effect.provideService(PayArkConfigService, this.config)
197
+ );
198
+ }
199
+ };
200
+ var PaymentsEffect = class {
201
+ constructor(config) {
202
+ this.config = config;
203
+ }
204
+ /**
205
+ * List payments for the authenticated project.
206
+ *
207
+ * @param params - Optional pagination parameters.
208
+ * @returns Effect that resolves to paginated payments.
209
+ */
210
+ list(params = {}) {
211
+ return request("GET", "/v1/payments", {
212
+ query: {
213
+ limit: params.limit,
214
+ offset: params.offset,
215
+ projectId: params.projectId
216
+ }
217
+ }).pipe(
218
+ Effect.flatMap(
219
+ Schema.decodeUnknown(PaginatedResponseSchema(PaymentSchema))
220
+ ),
221
+ Effect.provideService(PayArkConfigService, this.config)
222
+ );
223
+ }
224
+ /**
225
+ * Retrieve a single payment by its ID.
226
+ *
227
+ * @param id - The payment identifier.
228
+ * @returns Effect that resolves to the payment object.
229
+ */
230
+ retrieve(id) {
231
+ return request(
232
+ "GET",
233
+ `/v1/payments/${encodeURIComponent(id)}`
234
+ ).pipe(
235
+ Effect.flatMap(Schema.decodeUnknown(PaymentSchema)),
236
+ Effect.provideService(PayArkConfigService, this.config)
237
+ );
238
+ }
239
+ };
240
+ var ProjectsEffect = class {
241
+ constructor(config) {
242
+ this.config = config;
243
+ }
244
+ /**
245
+ * List all projects belonging to the authenticated account.
246
+ *
247
+ * @returns Effect that resolves to an array of projects.
248
+ */
249
+ list() {
250
+ return request("GET", "/v1/projects").pipe(
251
+ Effect.flatMap(Schema.decodeUnknown(Schema.Array(ProjectSchema))),
252
+ Effect.provideService(PayArkConfigService, this.config)
253
+ );
254
+ }
255
+ };
256
+
257
+ // src/index.ts
258
+ var PayArkEffect = class {
259
+ constructor(config) {
260
+ this.config = config;
261
+ }
262
+ _checkout;
263
+ _payments;
264
+ _projects;
265
+ /**
266
+ * Checkout sessions resource (Effect).
267
+ */
268
+ get checkout() {
269
+ if (!this._checkout) {
270
+ this._checkout = new CheckoutEffect(this.config);
271
+ }
272
+ return this._checkout;
273
+ }
274
+ /**
275
+ * Payments resource (Effect).
276
+ */
277
+ get payments() {
278
+ if (!this._payments) {
279
+ this._payments = new PaymentsEffect(this.config);
280
+ }
281
+ return this._payments;
282
+ }
283
+ /**
284
+ * Projects resource (Effect).
285
+ */
286
+ get projects() {
287
+ if (!this._projects) {
288
+ this._projects = new ProjectsEffect(this.config);
289
+ }
290
+ return this._projects;
291
+ }
292
+ };
293
+ var PayArk = class _PayArk extends Context.Tag("@payark/sdk-effect/PayArk")() {
294
+ /**
295
+ * Create a Layer that provides the PayArk service.
296
+ */
297
+ static Live = (config) => Layer.succeed(_PayArk, new PayArkEffect(config));
298
+ };
299
+
300
+ export { CheckoutSessionId, CheckoutSessionSchema, CreateCheckoutSchema, PaginatedResponseSchema, PayArk, PayArkEffect, PayArkEffectError, PaymentId, PaymentSchema, ProjectId, ProjectSchema, ProviderSchema };
301
+ //# sourceMappingURL=index.mjs.map
302
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/schemas.ts","../src/resources/checkout.ts","../src/resources/payments.ts","../src/resources/projects.ts","../src/index.ts"],"names":["Effect","Schema","Context"],"mappings":";;;;;;AAOO,IAAM,iBAAA,GAAN,cAAgC,IAAA,CAAK,WAAA,CAAY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M,eAAN,MAAmB;AAAA,EAKxB,YAA6B,MAAA,EAAsB;AAAtB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAuB;AAAA,EAJ5C,SAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA;AAAA;AAAA;AAAA,EAOR,IAAI,QAAA,GAA2B;AAC7B,IAAA,IAAI,CAAC,KAAK,SAAA,EAAW;AACnB,MAAA,IAAA,CAAK,SAAA,GAAY,IAAI,cAAA,CAAe,IAAA,CAAK,MAAM,CAAA;AAAA,IACjD;AACA,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,QAAA,GAA2B;AAC7B,IAAA,IAAI,CAAC,KAAK,SAAA,EAAW;AACnB,MAAA,IAAA,CAAK,SAAA,GAAY,IAAI,cAAA,CAAe,IAAA,CAAK,MAAM,CAAA;AAAA,IACjD;AACA,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,QAAA,GAA2B;AAC7B,IAAA,IAAI,CAAC,KAAK,SAAA,EAAW;AACnB,MAAA,IAAA,CAAK,SAAA,GAAY,IAAI,cAAA,CAAe,IAAA,CAAK,MAAM,CAAA;AAAA,IACjD;AACA,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AACF;AAKO,IAAM,SAAN,MAAM,OAAA,SAAeE,QAAQ,GAAA,CAAI,2BAA2B,GAGjE,CAAE;AAAA;AAAA;AAAA;AAAA,EAIF,OAAgB,IAAA,GAAO,CAAC,MAAA,KACtB,KAAA,CAAM,QAAQ,OAAA,EAAQ,IAAI,YAAA,CAAa,MAAM,CAAC,CAAA;AAClD","file":"index.mjs","sourcesContent":["import { Data } from \"effect\";\nimport type { PayArkErrorCode, PayArkErrorBody } from \"@payark/sdk\";\n\n/**\n * Effect-compatible error class for PayArk SDK.\n * Extends Data.TaggedError for easy matching in Effect.catchTag.\n */\nexport class PayArkEffectError extends Data.TaggedError(\"PayArkEffectError\")<{\n readonly message: string;\n readonly statusCode: number;\n readonly code: PayArkErrorCode;\n readonly raw?: PayArkErrorBody;\n}> {\n /** Human-readable representation for logging/debugging. */\n override toString(): string {\n return `[PayArkEffectError: ${this.code}] ${this.message} (HTTP ${this.statusCode})`;\n }\n}\n","import { Effect, Context } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"@effect/platform\";\nimport { PayArkEffectError } from \"./errors\";\nimport { SDK_VERSION } from \"@payark/sdk\";\nimport type { PayArkConfig, PayArkErrorCode } from \"@payark/sdk\";\n\n/**\n * Service tag for the PayArk configuration.\n */\nexport class PayArkConfigService extends Context.Tag(\"PayArkConfigService\")<\n PayArkConfigService,\n PayArkConfig\n>() {}\n\n/**\n * Executes an HTTP request using Effect and returns the JSON body or a PayArkEffectError.\n */\nexport const request = <T>(\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n options?: {\n readonly query?: Record<string, string | number | undefined>;\n readonly body?: any;\n readonly headers?: Record<string, string>;\n },\n): Effect.Effect<\n T,\n PayArkEffectError,\n PayArkConfigService | HttpClient.HttpClient\n> =>\n Effect.gen(function* (_) {\n const config = yield* _(PayArkConfigService);\n const client = yield* _(HttpClient.HttpClient);\n\n const baseUrl = (config.baseUrl ?? \"https://api.payark.com\").replace(\n /\\/+$/,\n \"\",\n );\n const url = new URL(`${baseUrl}${path}`);\n\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${config.apiKey}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"User-Agent\": `payark-sdk-effect/${SDK_VERSION}`,\n ...options?.headers,\n };\n\n if (config.sandbox) {\n headers[\"x-sandbox-mode\"] = \"true\";\n }\n\n let req = HttpClientRequest.make(method)(url.toString()).pipe(\n HttpClientRequest.setHeaders(headers),\n );\n\n if (options?.body) {\n req = yield* _(\n HttpClientRequest.bodyJson(options.body)(req).pipe(\n Effect.mapError(\n (e) =>\n new PayArkEffectError({\n message: `Invalid request body: ${String(e)}`,\n statusCode: 400,\n code: \"invalid_request_error\",\n }),\n ),\n ),\n );\n }\n\n const response = yield* _(\n client.execute(req).pipe(\n Effect.mapError(\n (e) =>\n new PayArkEffectError({\n message: `Network error: ${e.message}`,\n statusCode: 0,\n code: \"connection_error\",\n }),\n ),\n ),\n );\n\n if (response.status >= 200 && response.status < 300) {\n if (response.status === 204) return {} as T;\n return (yield* _(\n response.json.pipe(\n Effect.mapError(\n (e) =>\n new PayArkEffectError({\n message: `Failed to parse response: ${String(e)}`,\n statusCode: response.status,\n code: \"api_error\",\n }),\n ),\n ),\n )) as T;\n }\n\n const errorBody: any = yield* _(\n response.json.pipe(\n Effect.catchAll(() => Effect.succeed({ error: undefined })),\n ),\n );\n\n return yield* _(\n Effect.fail(\n new PayArkEffectError({\n message:\n errorBody?.error || `Request failed with status ${response.status}`,\n statusCode: response.status,\n code: mapStatusToCode(response.status),\n raw: errorBody,\n }),\n ),\n );\n });\n\nfunction mapStatusToCode(status: number): PayArkErrorCode {\n if (status === 401) return \"authentication_error\";\n if (status === 403) return \"permission_error\";\n if (status === 400 || status === 422) return \"invalid_request_error\";\n if (status === 404) return \"not_found_error\";\n if (status === 429) return \"rate_limit_error\";\n if (status >= 500) return \"api_error\";\n return \"unknown_error\";\n}\n","import { Schema } from \"@effect/schema\";\n\n/**\n * Supported payment providers on the PayArk platform.\n */\nexport const ProviderSchema = Schema.Union(\n Schema.Literal(\n \"esewa\",\n \"khalti\",\n \"connectips\",\n \"imepay\",\n \"fonepay\",\n \"sandbox\",\n ),\n);\n\n// ── Branded Types ──────────────────────────────────────────────────────────\n\n/**\n * Branded Type for Checkout Session ID.\n */\nexport const CheckoutSessionId = Schema.String.pipe(\n Schema.brand(\"CheckoutSessionId\"),\n);\nexport type CheckoutSessionId = Schema.Schema.Type<typeof CheckoutSessionId>;\n\n/**\n * Branded Type for Payment ID.\n */\nexport const PaymentId = Schema.String.pipe(Schema.brand(\"PaymentId\"));\nexport type PaymentId = Schema.Schema.Type<typeof PaymentId>;\n\n/**\n * Branded Type for Project ID.\n */\nexport const ProjectId = Schema.String.pipe(Schema.brand(\"ProjectId\"));\nexport type ProjectId = Schema.Schema.Type<typeof ProjectId>;\n\n/**\n * Schema for creating a checkout session.\n */\nexport const CreateCheckoutSchema = Schema.Struct({\n amount: Schema.Number,\n currency: Schema.optionalWith(Schema.String, {\n default: () => \"NPR\" as const,\n }),\n provider: ProviderSchema,\n returnUrl: Schema.String,\n cancelUrl: Schema.optional(Schema.String),\n metadata: Schema.optional(\n Schema.Record({ key: Schema.String, value: Schema.Any }),\n ),\n});\n\n/**\n * Schema for a checkout session response.\n */\nexport const CheckoutSessionSchema = Schema.Struct({\n id: CheckoutSessionId,\n checkout_url: Schema.String,\n payment_method: Schema.Struct({\n type: ProviderSchema,\n url: Schema.optional(Schema.String),\n method: Schema.optional(\n Schema.Union(Schema.Literal(\"GET\"), Schema.Literal(\"POST\")),\n ),\n fields: Schema.optional(\n Schema.Record({ key: Schema.String, value: Schema.String }),\n ),\n }),\n});\n\n/**\n * Schema for a Payment response.\n */\nexport const PaymentSchema = Schema.Struct({\n id: PaymentId,\n project_id: ProjectId,\n amount: Schema.Number,\n currency: Schema.String,\n status: Schema.Union(\n Schema.Literal(\"pending\"),\n Schema.Literal(\"success\"),\n Schema.Literal(\"failed\"),\n ),\n provider_ref: Schema.optional(Schema.NullOr(Schema.String)),\n metadata_json: Schema.optional(\n Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Any })),\n ),\n gateway_response: Schema.optional(\n Schema.NullOr(Schema.Record({ key: Schema.String, value: Schema.Any })),\n ),\n created_at: Schema.String,\n updated_at: Schema.optional(Schema.String),\n});\n\n/**\n * Schema for a Project response.\n */\nexport const ProjectSchema = Schema.Struct({\n id: ProjectId,\n name: Schema.String,\n api_key_secret: Schema.String,\n created_at: Schema.String,\n});\n\n/**\n * Higher-order schema for paginated responses.\n */\nexport const PaginatedResponseSchema = <A, I>(item: Schema.Schema<A, I>) =>\n Schema.Struct({\n data: Schema.Array(item),\n meta: Schema.Struct({\n total: Schema.NullOr(Schema.Number),\n limit: Schema.Number,\n offset: Schema.Number,\n }),\n });\n\n// ── Inferred Types ─────────────────────────────────────────────────────────\n\nexport type CheckoutSession = Schema.Schema.Type<typeof CheckoutSessionSchema>;\nexport type Payment = Schema.Schema.Type<typeof PaymentSchema>;\nexport type Project = Schema.Schema.Type<typeof ProjectSchema>;\nexport interface PaginatedResponse<T> {\n readonly data: ReadonlyArray<T>;\n readonly meta: {\n readonly total: number | null;\n readonly limit: number;\n readonly offset: number;\n };\n}\n","import { Effect } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { PayArkConfigService, request } from \"../http\";\nimport { CheckoutSessionSchema } from \"../schemas\";\nimport { PayArkEffectError } from \"../errors\";\nimport type { CreateCheckoutParams, PayArkConfig } from \"@payark/sdk\";\nimport type { CheckoutSession } from \"../schemas\";\nimport type { HttpClient } from \"@effect/platform\";\nimport type { ParseResult } from \"@effect/schema\";\n\n/**\n * Effect-based resource for PayArk Checkout.\n */\nexport class CheckoutEffect {\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * Create a new checkout session.\n *\n * @param params - Configuration for the checkout session.\n * @returns Effect that resolves to the created checkout session.\n */\n create(\n params: CreateCheckoutParams,\n ): Effect.Effect<\n CheckoutSession,\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\"POST\", \"/v1/checkout\", { body: params }).pipe(\n Effect.flatMap(Schema.decodeUnknown(CheckoutSessionSchema)),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n}\n","import { Effect } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { PayArkConfigService, request } from \"../http\";\nimport { PaymentSchema, PaginatedResponseSchema } from \"../schemas\";\nimport { PayArkEffectError } from \"../errors\";\nimport type { PayArkConfig, ListPaymentsParams } from \"@payark/sdk\";\nimport type { Payment, PaginatedResponse } from \"../schemas\";\nimport type { HttpClient } from \"@effect/platform\";\nimport type { ParseResult } from \"@effect/schema\";\n\n/**\n * Effect-based resource for PayArk Payments.\n */\nexport class PaymentsEffect {\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * List payments for the authenticated project.\n *\n * @param params - Optional pagination parameters.\n * @returns Effect that resolves to paginated payments.\n */\n list(\n params: ListPaymentsParams = {},\n ): Effect.Effect<\n PaginatedResponse<Payment>,\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\"GET\", \"/v1/payments\", {\n query: {\n limit: params.limit,\n offset: params.offset,\n projectId: params.projectId,\n },\n }).pipe(\n Effect.flatMap(\n Schema.decodeUnknown(PaginatedResponseSchema(PaymentSchema)),\n ),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n\n /**\n * Retrieve a single payment by its ID.\n *\n * @param id - The payment identifier.\n * @returns Effect that resolves to the payment object.\n */\n retrieve(\n id: string,\n ): Effect.Effect<\n Payment,\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\n \"GET\",\n `/v1/payments/${encodeURIComponent(id)}`,\n ).pipe(\n Effect.flatMap(Schema.decodeUnknown(PaymentSchema)),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n}\n","import { Effect } from \"effect\";\nimport { Schema } from \"@effect/schema\";\nimport { PayArkConfigService, request } from \"../http\";\nimport { ProjectSchema } from \"../schemas\";\nimport { PayArkEffectError } from \"../errors\";\nimport type { PayArkConfig } from \"@payark/sdk\";\nimport type { Project } from \"../schemas\";\nimport type { HttpClient } from \"@effect/platform\";\nimport type { ParseResult } from \"@effect/schema\";\n\n/**\n * Effect-based resource for PayArk Projects.\n */\nexport class ProjectsEffect {\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * List all projects belonging to the authenticated account.\n *\n * @returns Effect that resolves to an array of projects.\n */\n list(): Effect.Effect<\n readonly Project[],\n PayArkEffectError | ParseResult.ParseError,\n HttpClient.HttpClient\n > {\n return request<unknown>(\"GET\", \"/v1/projects\").pipe(\n Effect.flatMap(Schema.decodeUnknown(Schema.Array(ProjectSchema))),\n Effect.provideService(PayArkConfigService, this.config),\n );\n }\n}\n","import { Context, Layer } from \"effect\";\nimport { CheckoutEffect } from \"./resources/checkout\";\nimport { PaymentsEffect } from \"./resources/payments\";\nimport { ProjectsEffect } from \"./resources/projects\";\nimport type { PayArkConfig } from \"@payark/sdk\";\n\n/**\n * Main entry point for the Effect-based PayArk API.\n */\nexport class PayArkEffect {\n private _checkout?: CheckoutEffect;\n private _payments?: PaymentsEffect;\n private _projects?: ProjectsEffect;\n\n constructor(private readonly config: PayArkConfig) {}\n\n /**\n * Checkout sessions resource (Effect).\n */\n get checkout(): CheckoutEffect {\n if (!this._checkout) {\n this._checkout = new CheckoutEffect(this.config);\n }\n return this._checkout;\n }\n\n /**\n * Payments resource (Effect).\n */\n get payments(): PaymentsEffect {\n if (!this._payments) {\n this._payments = new PaymentsEffect(this.config);\n }\n return this._payments;\n }\n\n /**\n * Projects resource (Effect).\n */\n get projects(): ProjectsEffect {\n if (!this._projects) {\n this._projects = new ProjectsEffect(this.config);\n }\n return this._projects;\n }\n}\n\n/**\n * Service tag for the PayArk API.\n */\nexport class PayArk extends Context.Tag(\"@payark/sdk-effect/PayArk\")<\n PayArk,\n PayArkEffect\n>() {\n /**\n * Create a Layer that provides the PayArk service.\n */\n static readonly Live = (config: PayArkConfig) =>\n Layer.succeed(PayArk, new PayArkEffect(config));\n}\n\nexport { PayArkEffectError } from \"./errors\";\nexport * from \"./schemas\";\nexport type {\n PayArkConfig,\n CheckoutSession,\n Payment,\n PaymentStatus,\n Project,\n ListPaymentsParams,\n PaginatedResponse,\n PaginationMeta,\n Provider,\n WebhookEvent,\n WebhookEventType,\n PayArkErrorBody,\n PayArkErrorCode,\n} from \"@payark/sdk\";\n"]}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@payark/sdk-effect",
3
+ "version": "0.1.0",
4
+ "description": "Functional, type-safe Effect SDK for the PayArk API.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup",
21
+ "dev": "tsup --watch",
22
+ "test": "bun test",
23
+ "lint": "tsc --noEmit",
24
+ "prepublishOnly": "bun run build"
25
+ },
26
+ "keywords": [
27
+ "payark",
28
+ "payment",
29
+ "effect",
30
+ "functional",
31
+ "typescript",
32
+ "sdk"
33
+ ],
34
+ "author": "PayArk",
35
+ "license": "MIT",
36
+ "devDependencies": {
37
+ "tsup": "^8.0.0",
38
+ "typescript": "^5.7.0",
39
+ "@types/node": "^20.0.0"
40
+ },
41
+ "dependencies": {
42
+ "@effect/platform": "^0.94.5",
43
+ "@effect/platform-node": "^0.104.1",
44
+ "@effect/schema": "^0.75.5",
45
+ "@payark/sdk": "workspace:*",
46
+ "effect": "^3.19.18"
47
+ }
48
+ }