UNPKG

@settlemint/sdk-utils

Version:

Shared utilities and helper functions for SettleMint SDK modules

286 lines (278 loc) • 10.1 kB
import { ZodError, z } from "zod"; //#region src/validation/validate.ts /** * Validates a value against a given Zod schema. * * @param schema - The Zod schema to validate against. * @param value - The value to validate. * @returns The validated and parsed value. * @throws Will throw an error if validation fails, with formatted error messages. * * @example * import { validate } from "@settlemint/sdk-utils/validation"; * * const validatedId = validate(IdSchema, "550e8400-e29b-41d4-a716-446655440000"); */ function validate(schema, value) { try { return schema.parse(value); } catch (error) { if (error instanceof ZodError) { const formattedErrors = error.issues.map((err) => `- ${err.path.join(".")}: ${err.message}`).join("\n"); throw new Error(`Validation error${error.issues.length > 1 ? "s" : ""}:\n${formattedErrors}`); } throw error; } } //#endregion //#region src/validation/access-token.schema.ts /** * Schema for validating application access tokens. * Application access tokens start with 'sm_aat_' prefix. */ const ApplicationAccessTokenSchema = z.string().regex(/^sm_aat_.+$/); /** * Schema for validating personal access tokens. * Personal access tokens start with 'sm_pat_' prefix. */ const PersonalAccessTokenSchema = z.string().regex(/^sm_pat_.+$/); /** * Schema for validating both application and personal access tokens. * Accepts tokens starting with either 'sm_pat_' or 'sm_aat_' prefix. */ const AccessTokenSchema = z.string().regex(/^(sm_pat_.+|sm_aat_.+)$/); //#endregion //#region src/json.ts /** * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails. * * @param value - The JSON string to parse * @param defaultValue - The value to return if parsing fails or results in null/undefined * @returns The parsed JSON value as type T, or the default value if parsing fails * * @example * import { tryParseJson } from "@settlemint/sdk-utils"; * * const config = tryParseJson<{ port: number }>( * '{"port": 3000}', * { port: 8080 } * ); * // Returns: { port: 3000 } * * const invalid = tryParseJson<string[]>( * 'invalid json', * [] * ); * // Returns: [] */ function tryParseJson(value, defaultValue = null) { try { const parsed = JSON.parse(value); if (parsed === undefined || parsed === null) { return defaultValue; } return parsed; } catch (_err) { return defaultValue; } } /** * Extracts a JSON object from a string. * * @param value - The string to extract the JSON object from * @returns The parsed JSON object, or null if no JSON object is found * @throws {Error} If the input string is too long (longer than 5000 characters) * @example * import { extractJsonObject } from "@settlemint/sdk-utils"; * * const json = extractJsonObject<{ port: number }>( * 'port info: {"port": 3000}', * ); * // Returns: { port: 3000 } */ function extractJsonObject(value) { if (value.length > 5e3) { throw new Error("Input too long"); } const result = /\{([\s\S]*)\}/.exec(value); if (!result) { return null; } return tryParseJson(result[0]); } /** * Converts a value to a JSON stringifiable format. * * @param value - The value to convert * @returns The JSON stringifiable value * * @example * import { makeJsonStringifiable } from "@settlemint/sdk-utils"; * * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) }); * // Returns: '{"amount":"1000"}' */ function makeJsonStringifiable(value) { if (value === undefined || value === null) { return value; } return tryParseJson(JSON.stringify(value, (_, value$1) => typeof value$1 === "bigint" ? value$1.toString() : value$1)); } //#endregion //#region src/validation/unique-name.schema.ts /** * Schema for validating unique names used across the SettleMint platform. * Only accepts lowercase alphanumeric characters and hyphens. * Used for workspace names, application names, service names etc. * * @example * import { UniqueNameSchema } from "@settlemint/sdk-utils/validation"; * * // Validate a workspace name * const isValidName = UniqueNameSchema.safeParse("my-workspace-123").success; * // true * * // Invalid names will fail validation * const isInvalidName = UniqueNameSchema.safeParse("My Workspace!").success; * // false */ const UniqueNameSchema = z.string().regex(/^[a-z0-9-]+$/); //#endregion //#region src/validation/url.schema.ts /** * Schema for validating URLs. * * @example * import { UrlSchema } from "@settlemint/sdk-utils/validation"; * * // Validate a URL * const isValidUrl = UrlSchema.safeParse("https://console.settlemint.com").success; * // true * * // Invalid URLs will fail validation * const isInvalidUrl = UrlSchema.safeParse("not-a-url").success; * // false */ const UrlSchema = z.string().url(); /** * Schema for validating URL paths. * * @example * import { UrlPathSchema } from "@settlemint/sdk-utils/validation"; * * // Validate a URL path * const isValidPath = UrlPathSchema.safeParse("/api/v1/users").success; * // true * * // Invalid paths will fail validation * const isInvalidPath = UrlPathSchema.safeParse("not-a-path").success; * // false */ const UrlPathSchema = z.string().regex(/^\/(?:[a-zA-Z0-9-_]+(?:\/[a-zA-Z0-9-_]+)*\/?)?$/, { message: "Invalid URL path format. Must start with '/' and can contain letters, numbers, hyphens, and underscores." }); /** * Schema that accepts either a full URL or a URL path. * * @example * import { UrlOrPathSchema } from "@settlemint/sdk-utils/validation"; * * // Validate a URL * const isValidUrl = UrlOrPathSchema.safeParse("https://console.settlemint.com").success; * // true * * // Validate a path * const isValidPath = UrlOrPathSchema.safeParse("/api/v1/users").success; * // true */ const UrlOrPathSchema = z.union([UrlSchema, UrlPathSchema]); //#endregion //#region src/validation/dot-env.schema.ts /** * Use this value to indicate that the resources are not part of the SettleMint platform. */ const STANDALONE_INSTANCE = "standalone"; /** * Use this value to indicate that the resources are not part of the SettleMint platform. */ const LOCAL_INSTANCE = "local"; /** * Schema for validating environment variables used by the SettleMint SDK. * Defines validation rules and types for configuration values like URLs, * access tokens, workspace names, and service endpoints. */ const DotEnvSchema = z.object({ SETTLEMINT_INSTANCE: z.union([ UrlSchema, z.literal(STANDALONE_INSTANCE), z.literal(LOCAL_INSTANCE) ]).default("https://console.settlemint.com"), SETTLEMINT_ACCESS_TOKEN: ApplicationAccessTokenSchema.optional(), SETTLEMINT_PERSONAL_ACCESS_TOKEN: PersonalAccessTokenSchema.optional(), SETTLEMINT_WORKSPACE: UniqueNameSchema.optional(), SETTLEMINT_APPLICATION: UniqueNameSchema.optional(), SETTLEMINT_BLOCKCHAIN_NETWORK: UniqueNameSchema.optional(), SETTLEMINT_BLOCKCHAIN_NETWORK_CHAIN_ID: z.string().optional(), SETTLEMINT_BLOCKCHAIN_NODE: UniqueNameSchema.optional(), SETTLEMINT_BLOCKCHAIN_NODE_JSON_RPC_ENDPOINT: UrlSchema.optional(), SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER: UniqueNameSchema.optional(), SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER_JSON_RPC_ENDPOINT: UrlSchema.optional(), SETTLEMINT_HASURA: UniqueNameSchema.optional(), SETTLEMINT_HASURA_ENDPOINT: UrlSchema.optional(), SETTLEMINT_HASURA_ADMIN_SECRET: z.string().optional(), SETTLEMINT_HASURA_DATABASE_URL: z.string().optional(), SETTLEMINT_THEGRAPH: UniqueNameSchema.optional(), SETTLEMINT_THEGRAPH_SUBGRAPHS_ENDPOINTS: z.preprocess((value) => tryParseJson(value, []), z.array(UrlSchema).optional()), SETTLEMINT_THEGRAPH_DEFAULT_SUBGRAPH: z.string().optional(), SETTLEMINT_PORTAL: UniqueNameSchema.optional(), SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT: UrlSchema.optional(), SETTLEMINT_PORTAL_REST_ENDPOINT: UrlSchema.optional(), SETTLEMINT_PORTAL_WS_ENDPOINT: UrlSchema.optional(), SETTLEMINT_HD_PRIVATE_KEY: UniqueNameSchema.optional(), SETTLEMINT_HD_PRIVATE_KEY_FORWARDER_ADDRESS: z.string().optional(), SETTLEMINT_ACCESSIBLE_PRIVATE_KEY: UniqueNameSchema.optional(), SETTLEMINT_MINIO: UniqueNameSchema.optional(), SETTLEMINT_MINIO_ENDPOINT: UrlSchema.optional(), SETTLEMINT_MINIO_ACCESS_KEY: z.string().optional(), SETTLEMINT_MINIO_SECRET_KEY: z.string().optional(), SETTLEMINT_IPFS: UniqueNameSchema.optional(), SETTLEMINT_IPFS_API_ENDPOINT: UrlSchema.optional(), SETTLEMINT_IPFS_PINNING_ENDPOINT: UrlSchema.optional(), SETTLEMINT_IPFS_GATEWAY_ENDPOINT: UrlSchema.optional(), SETTLEMINT_CUSTOM_DEPLOYMENT: UniqueNameSchema.optional(), SETTLEMINT_CUSTOM_DEPLOYMENT_ENDPOINT: UrlSchema.optional(), SETTLEMINT_BLOCKSCOUT: UniqueNameSchema.optional(), SETTLEMINT_BLOCKSCOUT_GRAPHQL_ENDPOINT: UrlSchema.optional(), SETTLEMINT_BLOCKSCOUT_UI_ENDPOINT: UrlSchema.optional(), SETTLEMINT_NEW_PROJECT_NAME: z.string().optional(), SETTLEMINT_LOG_LEVEL: z.enum([ "debug", "info", "warn", "error", "none" ]).default("warn") }); /** * Partial version of the environment variables schema where all fields are optional. * Useful for validating incomplete configurations during development or build time. */ const DotEnvSchemaPartial = DotEnvSchema.partial(); //#endregion //#region src/validation/id.schema.ts /** * Schema for validating database IDs. Accepts both PostgreSQL UUIDs and MongoDB ObjectIDs. * PostgreSQL UUIDs are 32 hexadecimal characters with hyphens (e.g. 123e4567-e89b-12d3-a456-426614174000). * MongoDB ObjectIDs are 24 hexadecimal characters (e.g. 507f1f77bcf86cd799439011). * * @example * import { IdSchema } from "@settlemint/sdk-utils/validation"; * * // Validate PostgreSQL UUID * const isValidUuid = IdSchema.safeParse("123e4567-e89b-12d3-a456-426614174000").success; * * // Validate MongoDB ObjectID * const isValidObjectId = IdSchema.safeParse("507f1f77bcf86cd799439011").success; */ const IdSchema = z.union([z.string().uuid(), z.string().regex(/^[0-9a-fA-F]{24}$/)]); //#endregion export { AccessTokenSchema, ApplicationAccessTokenSchema, DotEnvSchema, DotEnvSchemaPartial, IdSchema, LOCAL_INSTANCE, PersonalAccessTokenSchema, STANDALONE_INSTANCE, UniqueNameSchema, UrlOrPathSchema, UrlPathSchema, UrlSchema, validate }; //# sourceMappingURL=validation.js.map