easc 0.0.1

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.
@@ -0,0 +1,160 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
2
+ import {
3
+ validateEnvironment,
4
+ validateChannel,
5
+ validateConfig,
6
+ getConfig,
7
+ validateServerUrl,
8
+ } from "./schema";
9
+
10
+ describe("Schema utilities", () => {
11
+ const originalEnv = process.env;
12
+
13
+ beforeEach(() => {
14
+ process.env = { ...originalEnv };
15
+ });
16
+
17
+ afterEach(() => {
18
+ process.env = originalEnv;
19
+ });
20
+
21
+ describe("validateEnvironment", () => {
22
+ it("should pass when all environment variables are set", () => {
23
+ process.env.OTA_SERVER = "https://example.com";
24
+ process.env.OTA_API_KEY = "test-key";
25
+
26
+ const result = validateEnvironment();
27
+ expect(result.valid).toBe(true);
28
+ expect(result.errors).toEqual([]);
29
+ });
30
+
31
+ it("should fail when OTA_SERVER is missing", () => {
32
+ delete process.env.OTA_SERVER;
33
+ process.env.OTA_API_KEY = "test-key";
34
+
35
+ const result = validateEnvironment();
36
+ expect(result.valid).toBe(false);
37
+ expect(result.errors).toHaveLength(1);
38
+ expect(result.errors[0]).toContain("OTA_SERVER");
39
+ });
40
+
41
+ it("should fail when OTA_API_KEY is missing", () => {
42
+ process.env.OTA_SERVER = "https://example.com";
43
+ delete process.env.OTA_API_KEY;
44
+
45
+ const result = validateEnvironment();
46
+ expect(result.valid).toBe(false);
47
+ expect(result.errors).toHaveLength(1);
48
+ expect(result.errors[0]).toContain("OTA_API_KEY");
49
+ });
50
+
51
+ it("should fail when both are missing", () => {
52
+ delete process.env.OTA_SERVER;
53
+ delete process.env.OTA_API_KEY;
54
+
55
+ const result = validateEnvironment();
56
+ expect(result.valid).toBe(false);
57
+ expect(result.errors).toHaveLength(2);
58
+ });
59
+
60
+ it("should fail when OTA_SERVER is not a valid URL", () => {
61
+ process.env.OTA_SERVER = "not-a-url";
62
+ process.env.OTA_API_KEY = "test-key";
63
+
64
+ const result = validateEnvironment();
65
+ expect(result.valid).toBe(false);
66
+ expect(result.errors).toHaveLength(1);
67
+ expect(result.errors[0]).toContain("OTA_SERVER");
68
+ });
69
+ });
70
+
71
+ describe("validateChannel", () => {
72
+ it("should pass for valid channel names", () => {
73
+ const validChannels = [
74
+ "production",
75
+ "staging",
76
+ "dev",
77
+ "test-123",
78
+ "feature_branch",
79
+ ];
80
+
81
+ for (const channel of validChannels) {
82
+ const result = validateChannel(channel);
83
+ expect(result.valid).toBe(true);
84
+ expect(result.errors).toEqual([]);
85
+ }
86
+ });
87
+
88
+ it("should fail for undefined channel", () => {
89
+ const result = validateChannel(undefined);
90
+ expect(result.valid).toBe(false);
91
+ expect(result.errors).toHaveLength(1);
92
+ expect(result.errors[0]).toContain("--channel");
93
+ });
94
+
95
+ it("should fail for empty channel", () => {
96
+ const result = validateChannel("");
97
+ expect(result.valid).toBe(false);
98
+ expect(result.errors).toHaveLength(1);
99
+ });
100
+
101
+ it("should fail for invalid channel names", () => {
102
+ const invalidChannels = ["test@123", "feature/branch", "test.env"];
103
+
104
+ for (const channel of invalidChannels) {
105
+ const result = validateChannel(channel);
106
+ expect(result.valid).toBe(false);
107
+ expect(result.errors).toHaveLength(1);
108
+ expect(result.errors[0]).toContain("Invalid channel");
109
+ }
110
+ });
111
+ });
112
+
113
+ describe("validateConfig", () => {
114
+ it("should pass when everything is valid", () => {
115
+ process.env.OTA_SERVER = "https://example.com";
116
+ process.env.OTA_API_KEY = "test-key";
117
+
118
+ const result = validateConfig("production");
119
+ expect(result.valid).toBe(true);
120
+ expect(result.errors).toEqual([]);
121
+ });
122
+
123
+ it("should combine all errors", () => {
124
+ delete process.env.OTA_SERVER;
125
+ delete process.env.OTA_API_KEY;
126
+
127
+ const result = validateConfig(undefined);
128
+ expect(result.valid).toBe(false);
129
+ expect(result.errors).toHaveLength(3); // 2 env vars + 1 channel
130
+ });
131
+ });
132
+
133
+ describe("getConfig", () => {
134
+ it("should return config object", () => {
135
+ process.env.OTA_SERVER = "https://example.com";
136
+ process.env.OTA_API_KEY = "test-key";
137
+
138
+ const config = getConfig("production");
139
+ expect(config).toEqual({
140
+ otaServer: "https://example.com",
141
+ apiKey: "test-key",
142
+ channel: "production",
143
+ });
144
+ });
145
+ });
146
+
147
+ describe("validateServerUrl", () => {
148
+ it("should accept valid HTTP URLs", () => {
149
+ expect(validateServerUrl("http://localhost:8787")).toBe(true);
150
+ expect(validateServerUrl("https://example.com")).toBe(true);
151
+ expect(validateServerUrl("https://api.example.com/path")).toBe(true);
152
+ });
153
+
154
+ it("should reject invalid URLs", () => {
155
+ expect(validateServerUrl("not-a-url")).toBe(false);
156
+ expect(validateServerUrl("ftp://example.com")).toBe(false);
157
+ expect(validateServerUrl("")).toBe(false);
158
+ });
159
+ });
160
+ });
@@ -0,0 +1,151 @@
1
+ import chalk from "chalk";
2
+ import { z } from "zod";
3
+
4
+ // Zod schemas
5
+ const envSchema = z.object({
6
+ OTA_SERVER: z.string().url("OTA_SERVER must be a valid URL"),
7
+ OTA_API_KEY: z.string().min(1, "OTA_API_KEY is required"),
8
+ });
9
+
10
+ const channelSchema = z
11
+ .string()
12
+ .min(1, "Channel name is required")
13
+ .regex(
14
+ /^[a-zA-Z0-9-_]+$/,
15
+ "Channel names can only contain letters, numbers, hyphens, and underscores"
16
+ );
17
+
18
+ const configSchema = z.object({
19
+ otaServer: z.string().url(),
20
+ apiKey: z.string().min(1),
21
+ channel: channelSchema,
22
+ });
23
+
24
+ // Type exports
25
+ export type Config = z.infer<typeof configSchema>;
26
+
27
+ export interface IValidationResult {
28
+ valid: boolean;
29
+ errors: string[];
30
+ }
31
+
32
+ /**
33
+ * Format zod errors into user-friendly messages
34
+ */
35
+ function formatZodError(error: z.ZodError, context?: string): string[] {
36
+ return error.issues.map((err) => {
37
+ const path = err.path.join(".");
38
+ const message = err.message;
39
+
40
+ if (context === "environment") {
41
+ if (path === "OTA_SERVER") {
42
+ return (
43
+ `${chalk.red("OTA_SERVER")} environment variable is required or invalid\n` +
44
+ ` Set it in your .env file or export it:\n` +
45
+ ` export OTA_SERVER="https://your-ota-server.com"`
46
+ );
47
+ }
48
+ if (path === "OTA_API_KEY") {
49
+ return (
50
+ `${chalk.red("OTA_API_KEY")} environment variable is required\n` +
51
+ ` Set it in your .env file or export it:\n` +
52
+ ` export OTA_API_KEY="your-api-key"`
53
+ );
54
+ }
55
+ }
56
+
57
+ if (context === "channel") {
58
+ return (
59
+ `Invalid channel: ${chalk.red(message)}\n` +
60
+ ` Specify a valid channel:\n` +
61
+ ` easc --channel production\n` +
62
+ ` easc --channel staging`
63
+ );
64
+ }
65
+
66
+ return `${chalk.red(path)}: ${message}`;
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Validate environment variables using zod
72
+ */
73
+ export function validateEnvironment(): IValidationResult {
74
+ const result = envSchema.safeParse({
75
+ OTA_SERVER: process.env.OTA_SERVER,
76
+ OTA_API_KEY: process.env.OTA_API_KEY,
77
+ });
78
+
79
+ if (!result.success) {
80
+ return {
81
+ valid: false,
82
+ errors: formatZodError(result.error, "environment"),
83
+ };
84
+ }
85
+
86
+ return { valid: true, errors: [] };
87
+ }
88
+
89
+ /**
90
+ * Validate a channel name using zod
91
+ */
92
+ export function validateChannel(channel: string | undefined): IValidationResult {
93
+ if (!channel) {
94
+ return {
95
+ valid: false,
96
+ errors: [
97
+ `${chalk.red("--channel")} flag is required\n` +
98
+ ` Specify which channel to deploy to:\n` +
99
+ ` easc --channel production\n` +
100
+ ` easc --channel staging`,
101
+ ],
102
+ };
103
+ }
104
+
105
+ const result = channelSchema.safeParse(channel);
106
+
107
+ if (!result.success) {
108
+ return {
109
+ valid: false,
110
+ errors: formatZodError(result.error, "channel"),
111
+ };
112
+ }
113
+
114
+ return { valid: true, errors: [] };
115
+ }
116
+
117
+ /**
118
+ * Validate all configuration
119
+ */
120
+ export function validateConfig(channel: string | undefined): IValidationResult {
121
+ const envResult = validateEnvironment();
122
+ const channelResult = validateChannel(channel);
123
+
124
+ return {
125
+ valid: envResult.valid && channelResult.valid,
126
+ errors: [...envResult.errors, ...channelResult.errors],
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Get configuration from environment and arguments
132
+ */
133
+ export function getConfig(channel: string): Config {
134
+ return {
135
+ otaServer: process.env.OTA_SERVER!,
136
+ apiKey: process.env.OTA_API_KEY!,
137
+ channel,
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Validate server URL format
143
+ */
144
+ export function validateServerUrl(url: string): boolean {
145
+ try {
146
+ const parsed = new URL(url);
147
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
@@ -0,0 +1,133 @@
1
+ import fs from "fs";
2
+ import { IAppJson } from "./runtime";
3
+ import { IMetadata } from "./files";
4
+ import { Config } from "./schema";
5
+ import { PlatformType } from "../enums/platform";
6
+
7
+ export interface IUploadOptions {
8
+ platform: PlatformType;
9
+ channel: string;
10
+ runtimeVersion: string;
11
+ commitHash?: string;
12
+ bundlePath: string;
13
+ assetPaths: string[];
14
+ expoConfig: IAppJson["expo"];
15
+ metadata: IMetadata;
16
+ config: Config;
17
+ }
18
+
19
+ /**
20
+ * Upload a bundle and assets for a platform
21
+ */
22
+ export async function uploadBundle(options: IUploadOptions): Promise<void> {
23
+ const {
24
+ platform,
25
+ channel,
26
+ runtimeVersion,
27
+ commitHash,
28
+ bundlePath,
29
+ assetPaths,
30
+ expoConfig,
31
+ metadata,
32
+ config,
33
+ } = options;
34
+
35
+ const form = new FormData();
36
+ form.append("channel", channel);
37
+ form.append("runtimeVersion", runtimeVersion);
38
+ form.append("platform", platform);
39
+ form.append("expoConfig", JSON.stringify(expoConfig));
40
+ form.append("metadata", JSON.stringify(metadata));
41
+
42
+ if (commitHash) {
43
+ form.append("commitHash", commitHash);
44
+ }
45
+
46
+ // Add bundle
47
+ const bundleBuffer = fs.readFileSync(bundlePath);
48
+ const bundleBlob = new Blob([bundleBuffer]);
49
+ const bundleFileName = bundlePath.split("/").pop()!;
50
+ form.append("bundle", bundleBlob, bundleFileName);
51
+
52
+ // Add assets
53
+ assetPaths.forEach((assetPath, index) => {
54
+ const assetBuffer = fs.readFileSync(assetPath);
55
+ const assetBlob = new Blob([assetBuffer]);
56
+ const assetFileName = assetPath.split("/").pop()!;
57
+ form.append(`asset-${index}`, assetBlob, assetFileName);
58
+ });
59
+
60
+ // Upload
61
+ const url = new URL("/upload", config.otaServer);
62
+
63
+ const response = await fetch(url.toString(), {
64
+ method: "POST",
65
+ headers: {
66
+ "x-ota-api-key": config.apiKey,
67
+ },
68
+ body: form,
69
+ });
70
+
71
+ if (!response.ok) {
72
+ let errorText = "";
73
+ try {
74
+ errorText = await response.text();
75
+ } catch (e) {
76
+ errorText = "Unable to read error response";
77
+ }
78
+ throw new Error(`Upload failed: ${response.status} ${errorText}`);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Create a dry run summary
84
+ */
85
+ export function createDryRunSummary(options: {
86
+ platform: PlatformType;
87
+ bundlePath: string;
88
+ assetPaths: string[];
89
+ channel: string;
90
+ runtimeVersion: string;
91
+ commitHash?: string;
92
+ }): string {
93
+ const {
94
+ platform,
95
+ bundlePath,
96
+ assetPaths,
97
+ channel,
98
+ runtimeVersion,
99
+ commitHash,
100
+ } = options;
101
+
102
+ const bundleSize = fs.statSync(bundlePath).size;
103
+ const totalAssetSize = assetPaths.reduce((sum, path) => {
104
+ return sum + fs.statSync(path).size;
105
+ }, 0);
106
+
107
+ const lines = [
108
+ `Platform: ${platform}`,
109
+ `Channel: ${channel}`,
110
+ `Runtime Version: ${runtimeVersion}`,
111
+ ];
112
+
113
+ if (commitHash) {
114
+ lines.push(`Commit: ${commitHash}`);
115
+ }
116
+
117
+ lines.push(
118
+ `Bundle: ${formatBytes(bundleSize)}`,
119
+ `Assets: ${assetPaths.length} files (${formatBytes(totalAssetSize)})`
120
+ );
121
+
122
+ return lines.join("\n");
123
+ }
124
+
125
+ /**
126
+ * Format bytes to human readable string
127
+ */
128
+ function formatBytes(bytes: number): string {
129
+ const sizes = ["Bytes", "KB", "MB", "GB"];
130
+ if (bytes === 0) return "0 Bytes";
131
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
132
+ return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + " " + sizes[i];
133
+ }