landson-agri-sdk-kit
Version:
Software Development Kit for the Landson Agri API
1,060 lines (1,047 loc) • 25.3 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
AnalyticsService: () => AnalyticsService,
AuthService: () => AuthService,
CategoryService: () => CategoryService,
CategoryStatus: () => CategoryStatus,
HealthService: () => HealthService,
LandsonAgriClient: () => LandsonAgriClient,
NotificationService: () => NotificationService,
RoleService: () => RoleService,
StorageService: () => StorageService,
UserService: () => UserService,
UserStatus: () => UserStatus
});
module.exports = __toCommonJS(index_exports);
// src/client.ts
var import_axios = __toESM(require("axios"), 1);
// src/services/auth.service.ts
var AuthService = class {
constructor(client) {
this.client = client;
}
/**
* Login with email and password
*/
async login(data) {
const response = await this.client.request({
method: "POST",
url: "/auth/login",
data
});
if (response.success && response.data) {
this.client.setAccessToken(response.data.accessToken);
if (response.data.tokenId) {
this.client.setSessionId(response.data.tokenId);
}
}
return response;
}
/**
* Request an OTP code for phone login
*/
async requestPhoneLogin(data) {
return await this.client.request({
method: "POST",
url: "/auth/phone-login/request",
data
});
}
/**
* Verify phone login with OTP code
*/
async verifyPhoneLogin(data) {
const response = await this.client.request({
method: "POST",
url: "/auth/phone-login/verify",
data
});
if (response.success && response.data) {
this.client.setAccessToken(response.data.accessToken);
if (response.data.tokenId) {
this.client.setSessionId(response.data.tokenId);
}
}
return response;
}
/**
* Register a new user
*/
async register(data) {
return await this.client.request({
method: "POST",
url: "/auth/register",
data
});
}
/**
* Verify phone number after registration
*/
async verifyPhone(data) {
return await this.client.request({
method: "POST",
url: "/auth/phone-verification/verify-registration",
data
});
}
/**
* Request login OTP code
*/
async requestLoginOtp(data) {
return await this.client.request({
method: "POST",
url: "/auth/login-otp",
data
});
}
/**
* Resend OTP code
*/
async resendOtp(data) {
return await this.client.request({
method: "POST",
url: "/auth/resend-otp",
data
});
}
/**
* Verify OTP code
*/
async verifyOtp(data) {
const response = await this.client.request({
method: "POST",
url: "/auth/verify-otp",
data
});
if (response.success && response.data && data.type === "login") {
this.client.setAccessToken(response.data.accessToken);
if (response.data.tokenId) {
this.client.setSessionId(response.data.tokenId);
}
}
return response;
}
/**
* Request password reset
*/
async requestPasswordReset(data) {
return await this.client.request({
method: "POST",
url: "/auth/forgot-password",
data
});
}
/**
* Reset password with OTP code
*/
async resetPassword(data) {
return await this.client.request({
method: "POST",
url: "/auth/reset-password",
data
});
}
/**
* Send phone verification code
*/
async sendPhoneVerification(data) {
return await this.client.request({
method: "POST",
url: "/auth/phone-verification/send",
data
});
}
/**
* Verify user's phone number
*/
async verifyUserPhone(data) {
return await this.client.request({
method: "POST",
url: "/auth/phone-verification/verify",
data
});
}
/**
* Logout user
*/
async logout() {
var _a, _b;
const response = await this.client.request({
method: "POST",
url: "/auth/logout"
});
if (response.success) {
this.client.clearAccessToken();
(_b = (_a = this.client).clearSessionId) == null ? void 0 : _b.call(_a);
}
return response;
}
/**
* Refresh token
*/
async refreshToken(refreshToken) {
const response = await this.client.request({
method: "POST",
url: "/auth/refresh-token",
data: { refreshToken }
});
if (response.success && response.data) {
this.client.setAccessToken(response.data.accessToken);
if (response.data.tokenId) {
this.client.setSessionId(response.data.tokenId);
}
}
return response;
}
/**
* Get current user profile
*/
async getCurrentUser() {
return await this.client.request({
method: "GET",
url: "/auth/me"
});
}
/**
* Test SMS service
*/
async testSms(phoneNumber) {
return await this.client.request({
method: "POST",
url: "/auth/test-sms",
data: { phoneNumber }
});
}
};
// src/services/user.service.ts
var UserService = class {
constructor(client) {
this.client = client;
}
/**
* Get current user profile
*/
async getCurrentUser() {
return await this.client.request({
method: "GET",
url: "/users/profile/me"
});
}
/**
* Update current user profile
*/
async updateCurrentUser(data) {
return await this.client.request({
method: "PUT",
url: "/users/profile/update",
data
});
}
/**
* Change current user password
*/
async changePassword(data) {
return await this.client.request({
method: "PUT",
url: "/users/profile/change-password",
data
});
}
/**
* Upload profile image
*/
async uploadProfileImage(file) {
const formData = new FormData();
formData.append("image", file);
return await this.client.request({
method: "POST",
url: "/users/profile/image",
headers: {
"Content-Type": "multipart/form-data"
},
data: formData
});
}
/**
* Delete profile image
*/
async deleteProfileImage() {
return await this.client.request({
method: "DELETE",
url: "/users/profile/image"
});
}
/**
* Update profile image URL directly
*/
async updateProfileImageUrl(data) {
return await this.client.request({
method: "PUT",
url: "/users/profile/image-url",
data
});
}
/**
* Get presigned URL for profile image upload
*/
async getProfileImageUploadUrl(contentType = "image/jpeg") {
return await this.client.request({
method: "GET",
url: "/users/profile/image-upload-url",
params: { contentType }
});
}
/**
* Get all users (admin only)
*/
async getUsers(params) {
return await this.client.request({
method: "GET",
url: "/users",
params
});
}
/**
* Get a specific user by ID (admin only)
*/
async getUserById(userId) {
return await this.client.request({
method: "GET",
url: `/users/${userId}`
});
}
/**
* Update a specific user by ID (admin only)
*/
async updateUser(userId, data) {
return await this.client.request({
method: "PUT",
url: `/users/${userId}`,
data
});
}
/**
* Delete a user by ID (admin only)
*/
async deleteUser(userId) {
return await this.client.request({
method: "DELETE",
url: `/users/${userId}`
});
}
/**
* Change user status (admin only)
*/
async changeUserStatus(userId, status) {
return await this.client.request({
method: "PATCH",
url: `/users/${userId}/status`,
data: { status }
});
}
/**
* Create a new user (admin only)
*/
async createUser(data) {
return await this.client.request({
method: "POST",
url: "/users",
data
});
}
};
// src/services/role.service.ts
var RoleService = class {
constructor(client) {
this.client = client;
}
/**
* Get all roles with pagination and filtering (admin only)
*/
async getRoles(params) {
return await this.client.request({
method: "GET",
url: "/auth/roles",
params
});
}
/**
* Get a specific role by ID (admin only)
*/
async getRoleById(roleId) {
return await this.client.request({
method: "GET",
url: `/auth/roles/${roleId}`
});
}
/**
* Create a new role (admin only)
*/
async createRole(data) {
return await this.client.request({
method: "POST",
url: "/auth/roles",
data
});
}
/**
* Update a role (admin only)
*/
async updateRole(roleId, data) {
return await this.client.request({
method: "PUT",
url: `/auth/roles/${roleId}`,
data
});
}
/**
* Delete a role (admin only)
*/
async deleteRole(roleId) {
return await this.client.request({
method: "DELETE",
url: `/auth/roles/${roleId}`
});
}
/**
* Get all permissions (admin only)
*/
async getPermissions() {
return await this.client.request({
method: "GET",
url: "/auth/permissions"
});
}
/**
* Assign roles to a user (admin only)
*/
async assignRolesToUser(userId, roleIds) {
return await this.client.request({
method: "POST",
url: `/users/${userId}/roles`,
data: { roleIds }
});
}
/**
* Remove roles from a user (admin only)
*/
async removeRolesFromUser(userId, roleIds) {
return await this.client.request({
method: "DELETE",
url: `/users/${userId}/roles`,
data: { roleIds }
});
}
};
// src/services/storage.service.ts
var StorageService = class {
constructor(client) {
this.client = client;
}
/**
* Upload a file directly to S3
*/
async uploadFile(file, options) {
const formData = new FormData();
formData.append("file", file);
if (options == null ? void 0 : options.folder) {
formData.append("folder", options.folder);
}
if (options == null ? void 0 : options.filename) {
formData.append("filename", options.filename);
}
if ((options == null ? void 0 : options.isPublic) !== void 0) {
formData.append("isPublic", options.isPublic.toString());
}
return await this.client.request({
method: "POST",
url: "/storage/upload",
headers: {
"Content-Type": "multipart/form-data"
},
data: formData
});
}
/**
* Generate a pre-signed URL for direct upload to S3
*/
async generatePresignedUrl(options) {
return await this.client.request({
method: "POST",
url: "/storage/presigned-url",
data: options
});
}
/**
* Get download URL for a file
*/
async getDownloadUrl(key) {
return await this.client.request({
method: "GET",
url: `/storage/download-url/${encodeURIComponent(key)}`
});
}
/**
* Download a file directly (browser only)
* This will start the download of the file through the browser
*/
async downloadFile(key) {
var _a;
const response = await this.getDownloadUrl(key);
if (response.success && ((_a = response.data) == null ? void 0 : _a.url)) {
const a = document.createElement("a");
a.style.display = "none";
a.href = response.data.url;
a.download = key.split("/").pop() || "download";
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
} else {
throw new Error("Failed to get download URL");
}
}
/**
* Get metadata for a file
*/
async getFileMetadata(key) {
return await this.client.request({
method: "GET",
url: `/storage/metadata/${encodeURIComponent(key)}`
});
}
/**
* Update file metadata or move the file
*/
async updateFile(key, options) {
return await this.client.request({
method: "PUT",
url: `/storage/${encodeURIComponent(key)}`,
data: options
});
}
/**
* Delete a file from S3
*/
async deleteFile(key) {
return await this.client.request({
method: "DELETE",
url: `/storage/${encodeURIComponent(key)}`
});
}
/**
* List files in a folder
*/
async listFiles(prefix = "", recursive = false) {
return await this.client.request({
method: "GET",
url: "/storage/list",
params: { prefix, recursive }
});
}
/**
* Create a new folder
*/
async createFolder(options) {
return await this.client.request({
method: "POST",
url: "/storage/folders",
data: options
});
}
/**
* Check if storage service is healthy
*/
async healthCheck() {
try {
await this.listFiles("", false);
return { success: true, data: true };
} catch (error) {
return { success: false, data: false, error: error.message || "Unknown error" };
}
}
};
// src/services/notification.service.ts
var NotificationService = class {
constructor(client) {
this.client = client;
}
/**
* Subscribe to notifications
*/
async subscribe(data) {
return await this.client.request({
method: "POST",
url: "/notifications/subscribe",
data
});
}
/**
* Verify notification subscription
*/
async verify(email, token) {
return await this.client.request({
method: "GET",
url: "/notifications/verify",
params: { email, token }
});
}
/**
* Unsubscribe from notifications
*/
async unsubscribe(email) {
return await this.client.request({
method: "GET",
url: "/notifications/unsubscribe",
params: { email }
});
}
};
// src/services/analytics.service.ts
var AnalyticsService = class {
constructor(client) {
this.client = client;
}
/**
* Get version statistics
*/
async getVersionStatistics() {
return await this.client.request({
method: "GET",
url: "/admin/analytics/versions"
});
}
/**
* Get popular endpoints
*/
async getPopularEndpoints(version) {
return await this.client.request({
method: "GET",
url: "/admin/analytics/endpoints",
params: version ? { version } : void 0
});
}
/**
* Get version-specific stats
*/
async getVersionSpecificStats(version) {
return await this.client.request({
method: "GET",
url: `/admin/analytics/version/${version}`
});
}
};
// src/services/health.service.ts
var HealthService = class {
constructor(client) {
this.client = client;
}
/**
* Basic health check
*/
async check() {
return await this.client.request({
method: "GET",
url: "/health"
});
}
/**
* Detailed health check with all subsystems
*/
async detailedCheck() {
return await this.client.request({
method: "GET",
url: "/health/detailed"
});
}
/**
* Database health check
*/
async checkDatabase() {
return await this.client.request({
method: "GET",
url: "/health/database"
});
}
/**
* Redis health check
*/
async checkRedis() {
return await this.client.request({
method: "GET",
url: "/health/redis"
});
}
/**
* Memory usage health check
*/
async checkMemory() {
return await this.client.request({
method: "GET",
url: "/health/memory"
});
}
/**
* CPU usage health check
*/
async checkCpu() {
return await this.client.request({
method: "GET",
url: "/health/cpu"
});
}
/**
* Disk space health check
*/
async checkDisk() {
return await this.client.request({
method: "GET",
url: "/health/disk"
});
}
/**
* External dependencies health check
*/
async checkExternal(url) {
return await this.client.request({
method: "GET",
url: "/health/external",
params: url ? { url } : void 0
});
}
/**
* Analytics service health check
*/
async checkAnalytics() {
return await this.client.request({
method: "GET",
url: "/health/analytics"
});
}
/**
* Error monitoring service health check
*/
async checkErrorMonitoring() {
return await this.client.request({
method: "GET",
url: "/health/error-monitoring"
});
}
/**
* Mail service health check
*/
async checkMail() {
return await this.client.request({
method: "GET",
url: "/health/mail"
});
}
/**
* S3 storage service health check
*/
async checkS3() {
return await this.client.request({
method: "GET",
url: "/health/s3"
});
}
};
// src/services/category.service.ts
var CategoryService = class {
constructor(client) {
this.client = client;
}
/**
* Get all categories with filtering
*/
async getCategories(params) {
return await this.client.request({
method: "GET",
url: "/categories",
params
});
}
/**
* Get category statistics (admin only)
*/
async getStats() {
return await this.client.request({
method: "GET",
url: "/categories/stats"
});
}
/**
* Get a category by ID
*/
async getCategoryById(id, options) {
return await this.client.request({
method: "GET",
url: `/categories/${id}`,
params: options
});
}
/**
* Get a category by slug
*/
async getCategoryBySlug(slug, options) {
return await this.client.request({
method: "GET",
url: `/categories/slug/${slug}`,
params: options
});
}
/**
* Create a new category (admin only)
*/
async createCategory(data) {
return await this.client.request({
method: "POST",
url: "/categories",
data
});
}
/**
* Update a category (admin only)
*/
async updateCategory(id, data) {
return await this.client.request({
method: "PUT",
url: `/categories/${id}`,
data
});
}
/**
* Delete a category (admin only)
*/
async deleteCategory(id, hard) {
return await this.client.request({
method: "DELETE",
url: `/categories/${id}`,
params: { hard }
});
}
/**
* Get hierarchical category tree
*/
async getCategoryTree(params) {
return await this.client.request({
method: "GET",
url: "/categories",
params: {
...params,
tree: true
}
});
}
};
// src/client.ts
var LandsonAgriClient = class {
constructor(config) {
this.accessToken = null;
this.sessionId = null;
this.debugMode = false;
this.client = import_axios.default.create({
baseURL: config.baseURL || "https://landson-agri-backend.onrender.com/api/v1",
timeout: config.timeout || 1e4,
headers: {
"Content-Type": "application/json",
...config.headers
}
});
this.debugMode = config.debug || false;
this.client.interceptors.request.use(
(config2) => {
if (this.accessToken) {
if (this.debugMode) {
console.log(`[DEBUG] SDK: Adding auth token to request: ${config2.url}`);
}
config2.headers["Authorization"] = `Bearer ${this.accessToken}`;
if (this.sessionId) {
if (this.debugMode) {
console.log(`[DEBUG] SDK: Adding session ID to request: ${config2.url}`);
}
config2.headers["X-Session-ID"] = this.sessionId;
} else if (this.debugMode) {
console.warn(`[DEBUG] SDK: No session ID available for request: ${config2.url}`);
try {
const parts = this.accessToken.split(".");
if (parts.length === 3) {
const payload = JSON.parse(atob(parts[1]));
if (payload.jti) {
console.log(`[DEBUG] SDK: Extracted session ID from JWT: ${payload.jti}`);
this.setSessionId(payload.jti);
config2.headers["X-Session-ID"] = payload.jti;
}
}
} catch (e) {
console.error("[DEBUG] SDK: Could not extract session ID from JWT", e);
}
}
} else if (this.debugMode) {
console.warn(`[DEBUG] SDK: No access token available for request: ${config2.url}`);
}
return config2;
},
(error) => Promise.reject(error)
);
this.auth = new AuthService(this);
this.users = new UserService(this);
this.roles = new RoleService(this);
this.storage = new StorageService(this);
this.notifications = new NotificationService(this);
this.analytics = new AnalyticsService(this);
this.health = new HealthService(this);
this.categories = new CategoryService(this);
}
// Set debug mode
setDebugMode(debug) {
this.debugMode = debug;
}
// Get debug mode
isDebugMode() {
return this.debugMode;
}
// Set the access token
setAccessToken(token) {
if (this.debugMode) {
console.log(`[DEBUG] SDK: Setting access token`, {
tokenLength: token ? token.length : 0,
tokenStart: token ? token.substring(0, 10) + "..." : null
});
}
this.accessToken = token;
}
// Clear the access token
clearAccessToken() {
if (this.debugMode) {
console.log("[DEBUG] SDK: Clearing access token");
}
this.accessToken = null;
}
// Get the current access token
getAccessToken() {
if (this.debugMode && !this.accessToken) {
console.warn("[DEBUG] SDK: getAccessToken called but no token is set");
}
return this.accessToken;
}
// Set the session ID
setSessionId(id) {
if (this.debugMode) {
console.log(`[DEBUG] SDK: Setting session ID`, {
idLength: id ? id.length : 0,
idStart: id ? id.substring(0, 10) + "..." : null
});
}
this.sessionId = id;
}
// Clear the session ID
clearSessionId() {
if (this.debugMode) {
console.log("[DEBUG] SDK: Clearing session ID");
}
this.sessionId = null;
}
// Get the current session ID
getSessionId() {
if (this.debugMode && !this.sessionId) {
console.warn("[DEBUG] SDK: getSessionId called but no session ID is set");
}
return this.sessionId;
}
// Generic API request method
async request(config) {
try {
const response = await this.client.request(config);
return {
success: true,
data: response.data,
status: response.status
};
} catch (error) {
if (error.response) {
return {
success: false,
status: error.response.status,
error: {
message: error.response.data.message || "An error occurred",
details: error.response.data.details || error.response.data
}
};
} else if (error.request) {
return {
success: false,
error: {
message: "No response from server",
details: error.request
}
};
} else {
return {
success: false,
error: {
message: error.message,
details: error
}
};
}
}
}
};
// src/types.ts
var UserStatus = /* @__PURE__ */ ((UserStatus2) => {
UserStatus2["ACTIVE"] = "ACTIVE";
UserStatus2["INACTIVE"] = "INACTIVE";
UserStatus2["SUSPENDED"] = "SUSPENDED";
UserStatus2["PENDING_VERIFICATION"] = "PENDING_VERIFICATION";
return UserStatus2;
})(UserStatus || {});
var CategoryStatus = /* @__PURE__ */ ((CategoryStatus2) => {
CategoryStatus2["ACTIVE"] = "ACTIVE";
CategoryStatus2["INACTIVE"] = "INACTIVE";
CategoryStatus2["ARCHIVED"] = "ARCHIVED";
return CategoryStatus2;
})(CategoryStatus || {});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AnalyticsService,
AuthService,
CategoryService,
CategoryStatus,
HealthService,
LandsonAgriClient,
NotificationService,
RoleService,
StorageService,
UserService,
UserStatus
});