// cli/build-json-schema.ts
import { writeFileSync } from "fs";
import { join as join2 } from "path";
import { zodToJsonSchema } from "zod-to-json-schema";

// src/config/app.ts
import { z as z26 } from "zod";

// src/feature/alert/schema.ts
import { kebabCase } from "change-case";
import { z as z2 } from "zod";

// src/config/schema/email.ts
import { z } from "zod";
var EmailSchema = z.string().email();

// src/feature/alert/schema.ts
var AlertNameSchema = z2.string().min(3).max(256).regex(/^[a-z0-9\-]+$/i, "Invalid alert name").transform((value) => kebabCase(value)).describe("Define alert name.");
var AlertsDefaultSchema = z2.record(
  AlertNameSchema,
  z2.union([
    //
    EmailSchema.transform((v) => [v]),
    EmailSchema.array()
  ])
).optional().describe("Define the alerts in your app. Alerts are a way to send messages to one or more email addresses.");

// src/feature/auth/schema.ts
import { z as z5 } from "zod";

// src/config/schema/resource-id.ts
import { kebabCase as kebabCase2 } from "change-case";
import { z as z3 } from "zod";
var ResourceIdSchema = z3.string().min(3).max(24).regex(/^[a-z0-9\-]+$/i, "Invalid resource ID").transform((value) => kebabCase2(value));

// src/config/schema/duration.ts
import { parse } from "@awsless/duration";
import { z as z4 } from "zod";
var DurationSchema = z4.string().regex(/^[0-9]+ (seconds?|minutes?|hours?|days?|weeks?)$/, "Invalid duration").transform((v) => parse(v));
var durationMin = (min) => {
  return (duration) => {
    return duration.value >= min.value;
  };
};
var durationMax = (max) => {
  return (duration) => {
    return duration.value <= max.value;
  };
};

// src/feature/auth/schema.ts
var AuthDefaultSchema = z5.record(
  ResourceIdSchema,
  z5.object({
    allowUserRegistration: z5.boolean().default(true).describe("Specifies whether users can create an user account or if only the administrator can."),
    // messaging: z
    // 	.object({
    // 		fromEmail: EmailSchema.describe("Specifies the sender's email address."),
    // 		fromName: z.string().optional().describe("Specifies the sender's name."),
    // 		replyTo: EmailSchema.optional().describe(
    // 			'The destination to which the receiver of the email should reply.'
    // 		),
    // 	})
    // 	.optional()
    // 	.describe('The email configuration for sending messages.'),
    // secret: z.boolean().default(false).describe('Specifies whether you want to generate a client secret.'),
    groups: z5.string().array().default([]).describe("Specifies a list of groups that a user can belong to."),
    username: z5.object({
      // emailAlias: z.boolean().default(true).describe('Allow the user email to be used as username.'),
      caseSensitive: z5.boolean().default(false).describe(
        "Specifies whether username case sensitivity will be enabled. When usernames and email addresses are case insensitive, users can sign in as the same user when they enter a different capitalization of their user name."
      )
    }).default({}).describe("The username policy."),
    password: z5.object({
      minLength: z5.number().int().min(6).max(99).default(12).describe("Required users to have at least the minimum password length."),
      uppercase: z5.boolean().default(true).describe("Required users to use at least one uppercase letter in their password."),
      lowercase: z5.boolean().default(true).describe("Required users to use at least one lowercase letter in their password."),
      numbers: z5.boolean().default(true).describe("Required users to use at least one number in their password."),
      symbols: z5.boolean().default(true).describe("Required users to use at least one symbol in their password."),
      temporaryPasswordValidity: DurationSchema.default("7 days").describe(
        "The duration a temporary password is valid. If the user doesn't sign in during this time, an administrator must reset their password."
      )
    }).default({}).describe("The password policy."),
    validity: z5.object({
      idToken: DurationSchema.default("1 hour").describe(
        "The ID token time limit. After this limit expires, your user can't use their ID token."
      ),
      accessToken: DurationSchema.default("1 hour").describe(
        "The access token time limit. After this limit expires, your user can't use their access token."
      ),
      refreshToken: DurationSchema.default("365 days").describe(
        "The refresh token time limit. After this limit expires, your user can't use their refresh token."
      )
    }).default({}).describe("Specifies the validity duration for every JWT token.")
    // triggers: TriggersSchema.optional(),
  })
).default({}).describe("Define the authenticatable users in your app.");

// src/feature/domain/schema.ts
import { z as z6 } from "zod";
var DomainNameSchema = z6.string().regex(/[a-z\-\_\.]/g, "Invalid domain name").describe(
  "Enter a fully qualified domain name, for example, www.example.com. You can optionally include a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you specify is fully qualified. This means that Route 53 treats www.example.com (without a trailing dot) and www.example.com. (with a trailing dot) as identical."
);
var DNSTypeSchema = z6.enum(["A", "AAAA", "CAA", "CNAME", "DS", "MX", "NAPTR", "NS", "PTR", "SOA", "SPF", "SRV", "TXT"]).describe("The DNS record type.");
var TTLSchema = DurationSchema.describe("The resource record cache time to live (TTL).");
var RecordsSchema = z6.string().array().describe("One or more values that correspond with the value that you specified for the Type property.");
var DomainsDefaultSchema = z6.record(
  ResourceIdSchema,
  z6.object({
    domain: DomainNameSchema.describe("Define the domain name"),
    dns: z6.object({
      name: DomainNameSchema.optional(),
      type: DNSTypeSchema,
      ttl: TTLSchema,
      records: RecordsSchema
    }).array().optional().describe("Define the domain dns records")
  })
).optional().describe("Define the domains for your application.");

// src/feature/function/schema.ts
import { days, minutes, seconds, toDays } from "@awsless/duration";
import { gibibytes, mebibytes } from "@awsless/size";
import { z as z11 } from "zod";

// src/config/schema/local-directory.ts
import { stat } from "fs/promises";
import { z as z8 } from "zod";

// src/config/schema/relative-path.ts
import { join } from "path";
import { z as z7 } from "zod";
var basePath;
var resolvePath = (path) => {
  if (path.startsWith(".") && basePath) {
    return join(basePath, path);
  }
  return path;
};
var RelativePathSchema = z7.string().transform((path) => resolvePath(path));

// src/config/schema/local-directory.ts
var LocalDirectorySchema = z8.union([
  RelativePathSchema.refine(async (path) => {
    try {
      const s = await stat(path);
      return s.isDirectory();
    } catch (error) {
      return false;
    }
  }, `Directory doesn't exist`),
  z8.object({
    nocheck: RelativePathSchema.describe(
      "Specifies a local directory without checking if the directory exists."
    )
  }).transform((v) => v.nocheck)
]);

// src/config/schema/local-file.ts
import { stat as stat2 } from "fs/promises";
import { z as z9 } from "zod";
var LocalFileSchema = z9.union([
  RelativePathSchema.refine(async (path) => {
    try {
      const s = await stat2(path);
      return s.isFile();
    } catch (error) {
      return false;
    }
  }, `File doesn't exist`),
  z9.object({
    nocheck: RelativePathSchema.describe("Specifies a local file without checking if the file exists.")
  }).transform((v) => v.nocheck)
]);

// src/config/schema/size.ts
import { parse as parse2 } from "@awsless/size";
import { z as z10 } from "zod";
var SizeSchema = z10.string().regex(/^[0-9]+ (B|KB|MB|GB|TB|PB)$/, "Invalid size").transform((v) => parse2(v));
var sizeMin = (min) => {
  return (size) => {
    return size.value >= min.value;
  };
};
var sizeMax = (max) => {
  return (size) => {
    return size.value <= max.value;
  };
};

// src/feature/function/schema.ts
var MemorySizeSchema = SizeSchema.refine(sizeMin(mebibytes(128)), "Minimum memory size is 128 MB").refine(sizeMax(gibibytes(10)), "Maximum memory size is 10 GB").describe(
  "The amount of memory available to the function at runtime. Increasing the function memory also increases its CPU allocation. The value can be any multiple of 1 MB. You can specify a size value from 128 MB to 10 GB."
);
var TimeoutSchema = DurationSchema.refine(durationMin(seconds(10)), "Minimum timeout duration is 10 seconds").refine(durationMax(minutes(15)), "Maximum timeout duration is 15 minutes").describe(
  "The amount of time that Lambda allows a function to run before stopping it. You can specify a size value from 1 second to 15 minutes."
);
var EphemeralStorageSizeSchema = SizeSchema.refine(
  sizeMin(mebibytes(512)),
  "Minimum ephemeral storage size is 512 MB"
).refine(sizeMax(gibibytes(10)), "Minimum ephemeral storage size is 10 GB").describe("The size of the function's /tmp directory. You can specify a size value from 512 MB to 10 GB.");
var ReservedConcurrentExecutionsSchema = z11.number().int().min(0).describe("The number of simultaneous executions to reserve for the function. You can specify a number from 0.");
var EnvironmentSchema = z11.record(z11.string(), z11.string()).optional().describe("Environment variable key-value pairs.");
var ArchitectureSchema = z11.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the function supports.");
var NodeRuntimeSchema = z11.enum(["nodejs18.x", "nodejs20.x", "nodejs22.x", "nodejs24.x"]);
var ContainerRuntimeSchema = z11.literal("container");
var RuntimeSchema = NodeRuntimeSchema.or(ContainerRuntimeSchema).or(z11.string()).describe("The identifier of the function's runtime.");
var ActionSchema = z11.string();
var ActionsSchema = z11.union([ActionSchema.transform((v) => [v]), ActionSchema.array()]);
var ArnSchema = z11.string().startsWith("arn:");
var WildcardSchema = z11.literal("*");
var ResourceSchema = z11.union([ArnSchema, WildcardSchema]);
var ResourcesSchema = z11.union([ResourceSchema.transform((v) => [v]), ResourceSchema.array()]);
var PermissionSchema = z11.object({
  effect: z11.enum(["allow", "deny"]).default("allow"),
  actions: ActionsSchema,
  resources: ResourcesSchema
});
var PermissionsSchema = z11.union([PermissionSchema.transform((v) => [v]), PermissionSchema.array()]).describe("Add IAM permissions to your function.");
var WarmSchema = z11.number().int().min(0).max(10).describe("Specify how many functions you want to warm up each 5 minutes. You can specify a number from 0 to 10.");
var VPCSchema = z11.boolean().describe("Put the function inside your global VPC.");
var MinifySchema = z11.boolean().describe("Minify the function code.");
var HandlerSchema = z11.string().describe("The name of the exported method within your code that Lambda calls to run your function.");
var DescriptionSchema = z11.string().describe("A description of the function.");
var validLogRetentionDays = [
  ...[1, 3, 5, 7, 14, 30, 60, 90, 120, 150],
  ...[180, 365, 400, 545, 731, 1096, 1827, 2192],
  ...[2557, 2922, 3288, 3653]
];
var LogRetentionSchema = DurationSchema.refine(
  durationMin(days(0)),
  "Minimum log retention is 0 day, which will disable logging."
).refine(
  (duration) => {
    return validLogRetentionDays.includes(toDays(duration));
  },
  `Invalid log retention. Valid days are: ${validLogRetentionDays.map((days7) => `${days7}`).join(", ")}`
).describe("The log retention duration.");
var LogSchema = z11.union([
  z11.boolean().transform((enabled) => ({ retention: enabled ? days(7) : days(0) })),
  LogRetentionSchema.transform((retention) => ({ retention })),
  z11.object({
    // subscription: LogSubscriptionSchema.optional(),
    retention: LogRetentionSchema.optional(),
    format: z11.enum(["text", "json"]).describe(
      `The format in which Lambda sends your function's application and system logs to CloudWatch. Select between plain text and structured JSON.`
    ).optional(),
    system: z11.enum(["debug", "info", "warn"]).describe(
      "Set this property to filter the system logs for your function that Lambda sends to CloudWatch. Lambda only sends system logs at the selected level of detail and lower, where DEBUG is the highest level and WARN is the lowest."
    ).optional(),
    level: z11.enum(["trace", "debug", "info", "warn", "error", "fatal"]).describe(
      "Set this property to filter the application logs for your function that Lambda sends to CloudWatch. Lambda only sends application logs at the selected level of detail and lower, where TRACE is the highest level and FATAL is the lowest."
    ).optional()
  })
]).describe("Enable logging to a CloudWatch log group. Providing a duration value will set the log retention time.");
var LayersSchema = z11.string().array().describe(
  // `A list of function layers to add to the function's execution environment..`
  `A list of function layers to add to the function's execution environment. Specify each layer by its ARN, including the version.`
);
var FileCodeSchema = z11.object({
  file: LocalFileSchema.describe("The file path of the function code."),
  minify: MinifySchema.optional().default(true),
  external: z11.string().array().optional().describe(`A list of external packages that won't be included in the bundle.`),
  importAsString: z11.string().array().optional().describe(`A list of glob patterns, which specifies the files that should be imported as string.`)
});
var BundleCodeSchema = z11.object({
  bundle: LocalDirectorySchema.describe("The directory that needs to be bundled.")
  // dir: z.string(),
  // build: z.string(),
  // run: z.string(),
  // cacheKey:
});
var CodeSchema = z11.union([
  LocalFileSchema.transform((file) => ({
    file
  })).pipe(FileCodeSchema),
  FileCodeSchema,
  BundleCodeSchema
]).describe("Specify the code of your function.");
var FnSchema = z11.object({
  code: CodeSchema,
  // node
  handler: HandlerSchema.optional(),
  // build: BuildSchema.optional(),
  // bundle: BundleSchema.optional(),
  // container
  // ...
  runtime: RuntimeSchema.optional(),
  description: DescriptionSchema.optional(),
  warm: WarmSchema.optional(),
  vpc: VPCSchema.optional(),
  log: LogSchema.optional(),
  timeout: TimeoutSchema.optional(),
  memorySize: MemorySizeSchema.optional(),
  architecture: ArchitectureSchema.optional(),
  ephemeralStorageSize: EphemeralStorageSizeSchema.optional(),
  // retryAttempts: RetryAttemptsSchema.optional(),
  reserved: ReservedConcurrentExecutionsSchema.optional(),
  layers: LayersSchema.optional(),
  environment: EnvironmentSchema.optional(),
  permissions: PermissionsSchema.optional()
});
var FunctionSchema = z11.union([
  LocalFileSchema.transform((code) => ({
    code
  })).pipe(FnSchema),
  FnSchema
]);
var FunctionsSchema = z11.record(ResourceIdSchema, FunctionSchema).optional().describe("Define the functions in your stack.");
var FunctionDefaultSchema = z11.object({
  runtime: RuntimeSchema.default("nodejs24.x"),
  // node
  handler: HandlerSchema.default("index.default"),
  // build: BuildSchema.default({
  // 	type: 'simple',
  // 	minify: true,
  // }),
  // container
  warm: WarmSchema.default(0),
  vpc: VPCSchema.default(false),
  log: LogSchema.default(true).transform((log) => ({
    retention: log.retention ?? days(7),
    level: "level" in log ? log.level : "error",
    system: "system" in log ? log.system : "warn",
    format: "format" in log ? log.format : "json"
  })),
  timeout: TimeoutSchema.default("10 seconds"),
  memorySize: MemorySizeSchema.default("128 MB"),
  architecture: ArchitectureSchema.default("arm64"),
  ephemeralStorageSize: EphemeralStorageSizeSchema.default("512 MB"),
  // retryAttempts: RetryAttemptsSchema.default(2),
  reserved: ReservedConcurrentExecutionsSchema.optional(),
  layers: LayersSchema.optional(),
  environment: EnvironmentSchema.optional(),
  permissions: PermissionsSchema.optional()
}).default({});

// src/feature/layer/schema.ts
import { z as z13 } from "zod";

// src/config/schema/lambda.ts
import { z as z12 } from "zod";
var ArchitectureSchema2 = z12.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the function supports.");
var NodeRuntimeSchema2 = z12.enum(["nodejs18.x", "nodejs20.x", "nodejs22.x"]).describe("The identifier of the function's runtime.");

// src/feature/layer/schema.ts
var Schema = z13.object({
  file: LocalFileSchema,
  runtimes: NodeRuntimeSchema2.array().optional(),
  architecture: ArchitectureSchema2.optional(),
  packages: z13.string().array().optional().describe(
    "Define the package names that are available bundled in the layer. Those packages are not bundled while bundling the lambda."
  )
});
var LayerSchema = z13.record(
  z13.string(),
  z13.union([
    LocalFileSchema.transform((file) => ({
      file,
      description: void 0
    })),
    Schema
  ])
).optional().describe("Define the lambda layers in your stack.");

// src/feature/task/schema.ts
import { z as z14 } from "zod";
var RetryAttemptsSchema = z14.number().int().min(0).max(2).describe(
  "The maximum number of times to retry when the function returns an error. You can specify a number from 0 to 2."
);
var TaskSchema = z14.union([
  FunctionSchema.transform((consumer) => ({
    consumer,
    retryAttempts: 2
  })),
  z14.object({
    consumer: FunctionSchema,
    retryAttempts: RetryAttemptsSchema.default(2)
  })
]);
var TasksSchema = z14.record(ResourceIdSchema, TaskSchema).optional().describe("Define the tasks in your stack.");

// src/feature/on-error-log/schema.ts
var OnErrorLogDefaultSchema = TaskSchema.optional().describe(
  "Define a subscription on all Lambda functions logs."
);

// src/feature/on-failure/schema.ts
import { z as z15 } from "zod";
var NotifySchema = z15.union([
  //
  EmailSchema.transform((v) => [v]),
  EmailSchema.array()
]).describe("Receive an email notification when consuming failure entries goes wrong.");
var OnFailureDefaultSchema = z15.union([
  FunctionSchema.transform((consumer) => ({
    consumer,
    notify: []
  })),
  z15.object({
    consumer: FunctionSchema,
    notify: NotifySchema.optional()
  })
]).optional().describe(
  [
    "Defining a onFailure handler will add a global onFailure handler for the following resources:",
    "- Tasks",
    "- Crons",
    "- Queues",
    "- Topics",
    "- Pubsub",
    "- Table streams"
  ].join("\n")
);

// src/feature/pubsub/schema.ts
import { z as z16 } from "zod";
var DomainSchema = ResourceIdSchema.describe("The domain id to link your Pubsub API with.");
var PubSubDefaultSchema = z16.record(
  ResourceIdSchema,
  z16.object({
    auth: FunctionSchema,
    domain: DomainSchema.optional(),
    subDomain: z16.string().optional()
    // auth: z.union([
    // 	ResourceIdSchema,
    // 	z.object({
    // 		authorizer: FunctionSchema,
    // 		// ttl: AuthorizerTtl.default('1 hour'),
    // 	}),
    // ]),
    // policy: z
    // 	.object({
    // 		publish: z.array(z.string()).optional(),
    // 		subscribe: z.array(z.string()).optional(),
    // 	})
    // 	.optional(),
  })
).optional().describe("Define the pubsub subscriber in your stack.");
var RetryAttemptsSchema2 = z16.number().int().min(0).max(2).describe(
  "The maximum number of times to retry when the function returns an error. You can specify a number from 0 to 2."
);
var PubSubSchema = z16.record(
  ResourceIdSchema,
  z16.object({
    sql: z16.string().describe("The SQL statement used to query the IOT topic."),
    sqlVersion: z16.enum(["2015-10-08", "2016-03-23", "beta"]).default("2016-03-23").describe("The version of the SQL rules engine to use when evaluating the rule."),
    consumer: FunctionSchema.describe("The consuming lambda function properties."),
    retryAttempts: RetryAttemptsSchema2.default(2)
  })
).optional().describe("Define the pubsub subscriber in your stack.");

// src/feature/queue/schema.ts
import { days as days2, hours, minutes as minutes2, seconds as seconds2 } from "@awsless/duration";
import { kibibytes } from "@awsless/size";
import { z as z17 } from "zod";
var RetentionPeriodSchema = DurationSchema.refine(durationMin(minutes2(1)), "Minimum retention period is 1 minute").refine(durationMax(days2(14)), "Maximum retention period is 14 days").describe(
  "The number of seconds that Amazon SQS retains a message. You can specify a duration from 1 minute to 14 days."
);
var VisibilityTimeoutSchema = DurationSchema.refine(
  durationMax(hours(12)),
  "Maximum visibility timeout is 12 hours"
).describe(
  "The length of time during which a message will be unavailable after a message is delivered from the queue. You can specify a duration from 0 to 12 hours."
);
var ReceiveMessageWaitTimeSchema = DurationSchema.refine(
  durationMin(seconds2(1)),
  "Minimum receive message wait time is 1 second"
).refine(durationMax(seconds2(20)), "Maximum receive message wait time is 20 seconds").describe("Long-polling wait time. You can specify a duration from 1 to 20 seconds.");
var MaxMessageSizeSchema = SizeSchema.refine(sizeMin(kibibytes(1)), "Minimum max message size is 1 KB").refine(sizeMax(kibibytes(256)), "Maximum max message size is 256 KB").describe("Message size limit. You can specify a size from 1 KB to 256 KB.");
var BatchSizeSchema = z17.number().int().min(1, "Minimum batch size is 1").max(10, "FIFO queues support a maximum batch size of 10").describe("The maximum number of records per batch. FIFO queues are capped at 10.");
var QueueDefaultSchema = z17.object({
  retentionPeriod: RetentionPeriodSchema.default("7 days"),
  visibilityTimeout: VisibilityTimeoutSchema.default("2 minutes"),
  receiveMessageWaitTime: ReceiveMessageWaitTimeSchema.optional(),
  maxMessageSize: MaxMessageSizeSchema.default("256 KB"),
  batchSize: BatchSizeSchema.default(10)
}).default({});
var QueueSchema = z17.object({
  consumer: FunctionSchema.optional().describe("The consuming lambda function properties."),
  retentionPeriod: RetentionPeriodSchema.optional(),
  visibilityTimeout: VisibilityTimeoutSchema.optional(),
  receiveMessageWaitTime: ReceiveMessageWaitTimeSchema.optional(),
  maxMessageSize: MaxMessageSizeSchema.optional(),
  batchSize: BatchSizeSchema.optional()
});
var QueuesSchema = z17.record(
  ResourceIdSchema,
  z17.union([
    LocalFileSchema.transform((consumer) => ({
      consumer
    })).pipe(QueueSchema),
    QueueSchema
  ])
).optional().describe(
  "Define the queues in your stack. Queues are FIFO with required per-message groupId: messages with the same groupId are processed strictly in order; different groupIds parallelize."
);

// src/feature/rest/schema.ts
import { z as z19 } from "zod";

// src/config/schema/route.ts
import { z as z18 } from "zod";
var RouteSchema = z18.union([
  z18.string().regex(/^(POST|GET|PUT|DELETE|HEAD|OPTIONS|ANY)(\s\/[a-z0-9\+\_\-\/\{\}]*)$/gi, "Invalid route"),
  z18.literal("$default")
]);

// src/feature/rest/schema.ts
var RestDefaultSchema = z19.record(
  ResourceIdSchema,
  z19.object({
    domain: ResourceIdSchema.describe("The domain id to link your API with.").optional(),
    subDomain: z19.string().optional()
  })
).optional().describe("Define your global REST API's.");
var RestSchema = z19.record(
  ResourceIdSchema,
  z19.record(
    RouteSchema.describe(
      [
        "The REST API route that is comprised by the http method and http path.",
        "The possible http methods are POST, GET,PUT, DELETE, HEAD, OPTIONS, ANY.",
        "Example: GET /posts/{id}"
      ].join("\n")
    ),
    FunctionSchema
  )
).optional().describe("Define routes in your stack for your global REST API.");

// src/feature/rpc/schema.ts
import { minutes as minutes4, seconds as seconds3 } from "@awsless/duration";
import { z as z21 } from "zod";

// src/feature/router/schema.ts
import { days as days3, minutes as minutes3, parse as parse3 } from "@awsless/duration";
import { z as z20 } from "zod";
var ErrorResponsePathSchema = z20.string().describe(
  [
    "The path to the custom error page that you want to return to the viewer when your origin returns the HTTP status code specified.",
    "- We recommend that you store custom error pages in an Amazon S3 bucket.",
    "If you store custom error pages on an HTTP server and the server starts to return 5xx errors, CloudFront can't get the files that you want to return to viewers because the origin server is unavailable."
  ].join("\n")
);
var StatusCodeSchema = z20.number().int().positive().optional().describe(
  [
    "The HTTP status code that you want CloudFront to return to the viewer along with the custom error page.",
    "There are a variety of reasons that you might want CloudFront to return a status code different from the status code that your origin returned to CloudFront, for example:",
    "- Some Internet devices (some firewalls and corporate proxies, for example) intercept HTTP 4xx and 5xx and prevent the response from being returned to the viewer.",
    "If you substitute 200, the response typically won't be intercepted.",
    `- If you don't care about distinguishing among different client errors or server errors, you can specify 400 or 500 as the ResponseCode for all 4xx or 5xx errors.`,
    `- You might want to return a 200 status code (OK) and static website so your customers don't know that your website is down.`
  ].join("\n")
);
var MinTTLSchema = DurationSchema.describe(
  "The minimum amount of time, that you want to cache the error response. When this time period has elapsed, CloudFront queries your origin to see whether the problem that caused the error has been resolved and the requested object is now available."
);
var ErrorResponseSchema = z20.union([
  ErrorResponsePathSchema,
  z20.object({
    path: ErrorResponsePathSchema,
    statusCode: StatusCodeSchema.optional(),
    minTTL: MinTTLSchema.optional()
  })
]).optional();
var RouteSchema2 = z20.string().regex(/^\//, "Route must start with a slash (/)");
var VisibilitySchema = z20.boolean().default(false).describe("Whether to enable CloudWatch metrics for the WAF rule.");
var WafSettingsSchema = z20.object({
  rateLimiter: z20.object({
    limit: z20.number().min(10).max(2e9).default(10).describe(
      "The limit on requests during the specified evaluation window for a single aggregation instance for the rate-based rule."
    ),
    window: z20.union([
      z20.literal("1 minute"),
      z20.literal("2 minutes"),
      z20.literal("5 minutes"),
      z20.literal("10 minutes")
    ]).default("5 minutes").transform((v) => parse3(v)).describe(
      "The amount of time, in seconds, that AWS WAF should include in its request counts, looking back from the current time."
    ),
    visibility: VisibilitySchema
  }).optional().describe(
    "A rate-based rule counts incoming requests and rate limits requests when they are coming at too fast a rate."
  ),
  ddosProtection: z20.object({
    sensitivity: z20.object({
      challenge: z20.enum(["low", "medium", "high"]).default("low").transform((v) => v.toUpperCase()).describe("The sensitivity level for challenge requests."),
      block: z20.enum(["low", "medium", "high"]).default("low").transform((v) => v.toUpperCase()).describe("The sensitivity level for block requests.")
    }),
    exemptUriRegex: z20.string().default("^$"),
    visibility: VisibilitySchema
  }).optional().describe(
    "Provides protection against DDoS attacks targeting the application layer, also known as Layer 7 attacks. Uses 50 WCU."
  ),
  botProtection: z20.object({
    inspectionLevel: z20.enum(["common", "targeted"]).default("common").transform((v) => v.toUpperCase()),
    visibility: VisibilitySchema
  }).optional().describe(
    "Provides protection against automated bots that can consume excess resources, skew business metrics, cause downtime, or perform malicious activities. Bot Control provides additional visibility through Amazon CloudWatch and generates labels that you can use to control bot traffic to your applications. Uses 50 WCU."
  ),
  captchaImmunityTime: DurationSchema.refine(durationMin(minutes3(1)), "Minimum timeout duration is 1 minute").refine(durationMax(days3(3)), "Maximum timeout duration is 3 days").default("5 minutes").describe(
    "The amount of time that a CAPTCHA timestamp is considered valid by AWS WAF. The default setting is 5 minutes."
  ),
  challengeImmunityTime: DurationSchema.refine(durationMin(minutes3(1)), "Minimum timeout duration is 1 minute").refine(durationMax(days3(3)), "Maximum timeout duration is 3 days").default("5 minutes").describe(
    "The amount of time that a challenge timestamp is considered valid by AWS WAF. The default setting is 5 minutes."
  )
}).describe(
  "WAF settings for the router. Each rule consumes Web ACL capacity units (WCUs). The total WCUs for a web ACL can't exceed 5000. Using over 1500 WCUs affects your costs."
);
var RouterDefaultSchema = z20.record(
  ResourceIdSchema,
  z20.object({
    domain: ResourceIdSchema.describe("The domain id to link your Router.").optional(),
    subDomain: z20.string().optional(),
    waf: WafSettingsSchema.optional(),
    geoRestrictions: z20.array(z20.string().length(2).toUpperCase()).default([]).describe("Specifies a blacklist of countries that should be blocked."),
    errors: z20.object({
      400: ErrorResponseSchema.describe("Customize a `400 Bad Request` response."),
      403: ErrorResponseSchema.describe("Customize a `403 Forbidden` response."),
      404: ErrorResponseSchema.describe("Customize a `404 Not Found` response."),
      405: ErrorResponseSchema.describe("Customize a `405 Method Not Allowed` response."),
      414: ErrorResponseSchema.describe("Customize a `414 Request-URI` response."),
      416: ErrorResponseSchema.describe("Customize a `416 Range Not` response."),
      500: ErrorResponseSchema.describe("Customize a `500 Internal Server` response."),
      501: ErrorResponseSchema.describe("Customize a `501 Not Implemented` response."),
      502: ErrorResponseSchema.describe("Customize a `502 Bad Gateway` response."),
      503: ErrorResponseSchema.describe("Customize a `503 Service Unavailable` response."),
      504: ErrorResponseSchema.describe("Customize a `504 Gateway Timeout` response.")
    }).optional().describe("Customize the error responses for specific HTTP status codes."),
    cors: z20.object({
      override: z20.boolean().default(false),
      maxAge: DurationSchema.default("365 days"),
      exposeHeaders: z20.string().array().optional(),
      credentials: z20.boolean().default(false),
      headers: z20.string().array().default(["*"]),
      origins: z20.string().array().default(["*"]),
      methods: z20.enum(["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "ALL"]).array().default(["ALL"])
    }).optional().describe("Specify the cors headers."),
    passwordAuth: z20.object({
      password: z20.string().describe("Password.")
    }).optional().describe(
      [
        "Enable password authentication for the router.",
        'You can authenicate by adding a "authorization" header with the value "Password [YOUR_PASSWORD]".'
      ].join("\n")
    ),
    basicAuth: z20.object({
      username: z20.string().describe("Basic auth username."),
      password: z20.string().describe("Basic auth password.")
    }).optional().describe("Enable basic authentication for the router."),
    // security: z
    // 	.object({
    // 		contentSecurityPolicy: z.object({
    // 			override: z.boolean().default(false),
    // 			policy: z.string(),
    // 		})
    // 		contentSecurityPolicy?: {
    // 			override?: boolean
    // 			contentSecurityPolicy: string
    // 		}
    // 		contentTypeOptions?: {
    // 			override?: boolean
    // 		}
    // 		frameOptions?: {
    // 			override?: boolean
    // 			frameOption?: 'deny' | 'same-origin'
    // 		}
    // 		referrerPolicy?: {
    // 			override?: boolean
    // 			referrerPolicy?: (
    // 				'no-referrer' |
    // 				'no-referrer-when-downgrade' |
    // 				'origin' |
    // 				'origin-when-cross-origin' |
    // 				'same-origin' |
    // 				'strict-origin' |
    // 				'strict-origin-when-cross-origin' |
    // 				'unsafe-url'
    // 			)
    // 		}
    // 		strictTransportSecurity?: {
    // 			maxAge?: Duration
    // 			includeSubdomains?: boolean
    // 			override?: boolean
    // 			preload?: boolean
    // 		}
    // 		xssProtection?: {
    // 			override?: boolean
    // 			enable?: boolean
    // 			modeBlock?: boolean
    // 			reportUri?: string
    // 		}
    // 	})
    // 	.optional()
    // 	.describe('Specify the security policy.'),
    cache: z20.object({
      cookies: z20.string().array().optional().describe("Specifies the cookies that CloudFront includes in the cache key."),
      headers: z20.string().array().optional().describe("Specifies the headers that CloudFront includes in the cache key."),
      queries: z20.string().array().optional().describe("Specifies the query values that CloudFront includes in the cache key.")
    }).optional().describe(
      "Specifies the cookies, headers, and query values that CloudFront includes in the cache key."
    )
  })
).optional().describe(`Define the global Router. Backed by AWS CloudFront.`);

// src/feature/rpc/schema.ts
var TimeoutSchema2 = DurationSchema.refine(durationMin(seconds3(10)), "Minimum timeout duration is 10 seconds").refine(durationMax(minutes4(5)), "Maximum timeout duration is 5 minutes").describe(
  [
    "The amount of time that the RPC lambda is allowed run before stopping it.",
    "You can specify a timeout from 10 second to 5 minutes.",
    "The timeouts of all inner RPC functions will be capped at 80% of this timeout."
  ].join(" ")
);
var RpcDefaultSchema = z21.record(
  ResourceIdSchema,
  z21.object({
    // domain: ResourceIdSchema.describe('The domain id to link your RPC API with.').optional(),
    // subDomain: z.string().optional(),
    //
    router: ResourceIdSchema.describe("The router id to link your RPC API with."),
    path: RouteSchema2.describe("The path inside the router to link your RPC API to."),
    auth: FunctionSchema.optional().describe("The authentication handler for your RPC API."),
    log: LogSchema.optional(),
    timeout: TimeoutSchema2.default("1 minutes")
  })
).describe(`Define the global RPC API's.`).optional();
var RpcSchema = z21.record(
  ResourceIdSchema,
  z21.record(
    z21.string(),
    z21.union([
      FunctionSchema.transform((f) => ({
        function: f,
        lock: false
      })),
      z21.object({
        function: FunctionSchema.describe("The RPC function to execute."),
        lock: z21.boolean().describe(
          [
            "Specify if the function should be locked on the `lockKey` returned from the auth function.",
            "An example would be returning the user ID as `lockKey`."
          ].join("\n")
        )
      })
    ])
  ).describe("The queries for your global RPC API.")
).describe("Define the schema in your stack for your global RPC API.").optional();

// src/feature/job/schema.ts
import { days as days4, toDays as toDays2 } from "@awsless/duration";
import { toMebibytes } from "@awsless/size";
import { z as z22 } from "zod";
var CpuSchema = z22.union([z22.literal(0.25), z22.literal(0.5), z22.literal(1), z22.literal(2), z22.literal(4), z22.literal(8), z22.literal(16)]).transform((v) => `${v} vCPU`).describe("The number of virtual CPU units (vCPU) used by the job. Valid values: 0.25, 0.5, 1, 2, 4, 8, 16 vCPU.");
var validMemorySize = [
  // 0.25 vCPU
  512,
  1024,
  2048,
  // 0.5 vCPU
  1024,
  2048,
  3072,
  4096,
  // 1 vCPU
  2048,
  3072,
  4096,
  5120,
  6144,
  7168,
  8192,
  // 2 vCPU
  4096,
  5120,
  6144,
  7168,
  8192,
  9216,
  10240,
  11264,
  12288,
  13312,
  14336,
  15360,
  16384
];
var MemorySizeSchema2 = SizeSchema.refine(
  (s) => validMemorySize.includes(toMebibytes(s)),
  `Invalid memory size. Allowed sizes: ${validMemorySize.join(", ")} MiB`
).describe("The amount of memory (in MiB) used by the job. Valid memory values depend on the CPU configuration.");
var EnvironmentSchema2 = z22.record(z22.string(), z22.string()).optional().describe("Environment variable key-value pairs.");
var ArchitectureSchema3 = z22.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the job supports.");
var ActionSchema2 = z22.string();
var ActionsSchema2 = z22.union([ActionSchema2.transform((v) => [v]), ActionSchema2.array()]);
var ArnSchema2 = z22.string().startsWith("arn:");
var WildcardSchema2 = z22.literal("*");
var ResourceSchema2 = z22.union([ArnSchema2, WildcardSchema2]);
var ResourcesSchema2 = z22.union([ResourceSchema2.transform((v) => [v]), ResourceSchema2.array()]);
var PermissionSchema2 = z22.object({
  effect: z22.enum(["allow", "deny"]).default("allow"),
  actions: ActionsSchema2,
  resources: ResourcesSchema2
});
var PermissionsSchema2 = z22.union([PermissionSchema2.transform((v) => [v]), PermissionSchema2.array()]).describe("Add IAM permissions to your job.");
var validLogRetentionDays2 = [
  ...[1, 3, 5, 7, 14, 30, 60, 90, 120, 150],
  ...[180, 365, 400, 545, 731, 1096, 1827, 2192],
  ...[2557, 2922, 3288, 3653]
];
var LogRetentionSchema2 = DurationSchema.refine(
  durationMin(days4(0)),
  "Minimum log retention is 0 day, which will disable logging."
).refine(
  (duration) => {
    return validLogRetentionDays2.includes(toDays2(duration));
  },
  `Invalid log retention. Valid days are: ${validLogRetentionDays2.map((days7) => `${days7}`).join(", ")}`
).describe("The log retention duration.");
var LogSchema2 = z22.union([
  z22.boolean().transform((enabled) => ({ retention: enabled ? days4(7) : days4(0) })),
  LogRetentionSchema2.transform((retention) => ({ retention })),
  z22.object({
    retention: LogRetentionSchema2.optional()
  })
]).describe("Enable logging to a CloudWatch log group. Providing a duration value will set the log retention time.");
var FileCodeSchema2 = z22.object({
  file: LocalFileSchema.describe("The file path of the job code.")
});
var CodeSchema2 = z22.union([
  LocalFileSchema.transform((file) => ({
    file
  })).pipe(FileCodeSchema2),
  FileCodeSchema2
]).describe("Specify the code of your job.");
var TimeoutSchema3 = DurationSchema.describe("The maximum time the job is allowed to run before being stopped.");
var ImageSchema = z22.string().describe("The URL of the container image to use. Default: public.ecr.aws/aws-cli/aws-cli:{architecture}");
var PersistentStorageSchema = z22.boolean().describe("Mount persistent storage for the job at a fixed internal path.");
var StartupCommandSchema = z22.union([z22.string().transform((v) => [v]), z22.string().array()]).describe("Optional shell commands to run before the job executable is downloaded and started.");
var ASchema = z22.object({
  code: CodeSchema2,
  image: ImageSchema.optional(),
  persistentStorage: PersistentStorageSchema.optional(),
  startupCommand: StartupCommandSchema.optional(),
  log: LogSchema2.optional(),
  cpu: CpuSchema.optional(),
  memorySize: MemorySizeSchema2.optional(),
  architecture: ArchitectureSchema3.optional(),
  environment: EnvironmentSchema2.optional(),
  permissions: PermissionsSchema2.optional(),
  timeout: TimeoutSchema3.default("30 minutes").describe("The maximum time the job is allowed to run before being stopped. Default: 30 minutes.")
});
var JobSchema = z22.union([
  LocalFileSchema.transform((code) => ({
    code
  })).pipe(ASchema),
  ASchema
]);
var JobsSchema = z22.record(ResourceIdSchema, JobSchema).optional().describe("Define the jobs in your stack.");
var JobDefaultSchema = z22.object({
  image: ImageSchema.optional(),
  persistentStorage: PersistentStorageSchema.optional(),
  cpu: CpuSchema.default(0.25),
  memorySize: MemorySizeSchema2.default("512 MB"),
  architecture: ArchitectureSchema3.default("arm64"),
  environment: EnvironmentSchema2.optional(),
  permissions: PermissionsSchema2.optional(),
  timeout: TimeoutSchema3.optional(),
  log: LogSchema2.default(true).transform((log) => ({
    retention: log.retention ?? days4(7)
  }))
}).default({});

// src/feature/instance/schema.ts
import { days as days5, toDays as toDays3 } from "@awsless/duration";
import { toMebibytes as toMebibytes2 } from "@awsless/size";
import { z as z23 } from "zod";
var CpuSchema2 = z23.union([z23.literal(0.25), z23.literal(0.5), z23.literal(1), z23.literal(2), z23.literal(4), z23.literal(8), z23.literal(16)]).transform((v) => `${v} vCPU`).describe(
  "The number of virtual CPU units (vCPU) used by the instance. Valid values: 0.25, 0.5, 1, 2, 4, 8, 16 vCPU."
);
var validMemorySize2 = [
  // 0.25 vCPU
  512,
  1024,
  2048,
  // 0.5 vCPU
  1024,
  2048,
  3072,
  4096,
  // 1 vCPU
  2048,
  3072,
  4096,
  5120,
  6144,
  7168,
  8192,
  // 2 vCPU
  4096,
  5120,
  6144,
  7168,
  8192,
  9216,
  10240,
  11264,
  12288,
  13312,
  14336,
  15360,
  16384
];
var MemorySizeSchema3 = SizeSchema.refine(
  (s) => validMemorySize2.includes(toMebibytes2(s)),
  `Invalid memory size. Allowed sizes: ${validMemorySize2.join(", ")} MiB`
).describe("The amount of memory (in MiB) used by the instance. Valid memory values depend on the CPU configuration.");
var HealthCheckSchema = z23.object({
  path: z23.string().describe("The path that the container runs to determine if it is healthy."),
  interval: DurationSchema.describe("The time period in seconds between each health check execution."),
  retries: z23.number().int().min(1).max(10).describe(
    "The number of times to retry a failed health check before the container is considered unhealthy."
  ),
  startPeriod: DurationSchema.describe(
    "The optional grace period to provide containers time to bootstrap before failed health checks count towards the maximum number of retries."
  ),
  timeout: DurationSchema.describe(
    "The time period in seconds to wait for a health check to succeed before it is considered a failure."
  )
}).describe("The health check command and associated configuration parameters for the container.");
var EnvironmentSchema3 = z23.record(z23.string(), z23.string()).optional().describe("Environment variable key-value pairs.");
var ArchitectureSchema4 = z23.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the instance supports.");
var ActionSchema3 = z23.string();
var ActionsSchema3 = z23.union([ActionSchema3.transform((v) => [v]), ActionSchema3.array()]);
var ArnSchema3 = z23.string().startsWith("arn:");
var WildcardSchema3 = z23.literal("*");
var ResourceSchema3 = z23.union([ArnSchema3, WildcardSchema3]);
var ResourcesSchema3 = z23.union([ResourceSchema3.transform((v) => [v]), ResourceSchema3.array()]);
var PermissionSchema3 = z23.object({
  effect: z23.enum(["allow", "deny"]).default("allow"),
  actions: ActionsSchema3,
  resources: ResourcesSchema3
});
var PermissionsSchema3 = z23.union([PermissionSchema3.transform((v) => [v]), PermissionSchema3.array()]).describe("Add IAM permissions to your instance.");
var DescriptionSchema2 = z23.string().describe("A description of the instance.");
var ImageSchema2 = z23.string().optional().describe("The URL of the container image to use. Default: public.ecr.aws/aws-cli/aws-cli:{architecture}");
var validLogRetentionDays3 = [
  ...[1, 3, 5, 7, 14, 30, 60, 90, 120, 150],
  ...[180, 365, 400, 545, 731, 1096, 1827, 2192],
  ...[2557, 2922, 3288, 3653]
];
var LogRetentionSchema3 = DurationSchema.refine(
  durationMin(days5(0)),
  "Minimum log retention is 0 day, which will disable logging."
).refine(
  (duration) => {
    return validLogRetentionDays3.includes(toDays3(duration));
  },
  `Invalid log retention. Valid days are: ${validLogRetentionDays3.map((days7) => `${days7}`).join(", ")}`
).describe("The log retention duration.");
var LogSchema3 = z23.union([
  z23.boolean().transform((enabled) => ({ retention: enabled ? days5(7) : days5(0) })),
  LogRetentionSchema3.transform((retention) => ({ retention })),
  z23.object({
    retention: LogRetentionSchema3.optional()
  })
]).describe("Enable logging to a CloudWatch log group. Providing a duration value will set the log retention time.");
var FileCodeSchema3 = z23.object({
  file: LocalFileSchema.describe("The file path of the instance code.")
});
var CodeSchema3 = z23.union([
  LocalFileSchema.transform((file) => ({
    file
  })).pipe(FileCodeSchema3),
  FileCodeSchema3
]).describe("Specify the code of your instance.");
var StartupCommandSchema2 = z23.union([z23.string().transform((v) => [v]), z23.string().array()]).describe("Optional shell commands to run before the instance program starts.");
var ISchema = z23.object({
  code: CodeSchema3,
  description: DescriptionSchema2.optional(),
  image: ImageSchema2.optional(),
  startupCommand: StartupCommandSchema2.optional(),
  log: LogSchema3.optional(),
  cpu: CpuSchema2.optional(),
  memorySize: MemorySizeSchema3.optional(),
  architecture: ArchitectureSchema4.optional(),
  environment: EnvironmentSchema3.optional(),
  permissions: PermissionsSchema3.optional(),
  healthCheck: HealthCheckSchema.optional()
  // restartPolicy: RestartPolicySchema.optional(),
});
var InstanceSchema = z23.union([
  LocalFileSchema.transform((code) => ({
    code
  })).pipe(ISchema),
  ISchema
]);
var InstancesSchema = z23.record(ResourceIdSchema, InstanceSchema).optional().describe("Define the instances in your stack.");
var InstanceDefaultSchema = z23.object({
  image: ImageSchema2.optional(),
  cpu: CpuSchema2.default(0.25),
  memorySize: MemorySizeSchema3.default("512 MB"),
  architecture: ArchitectureSchema4.default("arm64"),
  environment: EnvironmentSchema3.optional(),
  permissions: PermissionsSchema3.optional(),
  healthCheck: HealthCheckSchema.optional(),
  // restartPolicy: RestartPolicySchema.default({ enabled: true }),
  log: LogSchema3.default(true).transform((log) => ({
    retention: log.retention ?? days5(7)
  }))
}).default({});

// src/feature/topic/schema.ts
import { kebabCase as kebabCase3 } from "change-case";
import { z as z24 } from "zod";
var TopicNameSchema = z24.string().min(3).max(256).regex(/^[a-z0-9\-]+$/i, "Invalid topic name").transform((value) => kebabCase3(value)).describe("Define event topic name.");
var TopicsDefaultSchema = z24.array(TopicNameSchema).refine((topics) => {
  return topics.length === new Set(topics).size;
}, "Must be a list of unique topic names").optional().describe("Define the event topics for your app.");
var SubscribersSchema = z24.record(TopicNameSchema, TaskSchema).optional().describe("Define the event topics to subscribe too in your stack.");

// src/config/schema/region.ts
import { z as z25 } from "zod";
var US = ["us-east-2", "us-east-1", "us-west-1", "us-west-2"];
var AF = ["af-south-1"];
var AP = [
  "ap-east-1",
  "ap-south-2",
  "ap-southeast-3",
  "ap-southeast-4",
  "ap-south-1",
  "ap-northeast-3",
  "ap-northeast-2",
  "ap-southeast-1",
  "ap-southeast-2",
  "ap-northeast-1"
];
var CA = ["ca-central-1"];
var EU = [
  "eu-central-1",
  "eu-west-1",
  "eu-west-2",
  "eu-south-1",
  "eu-west-3",
  "eu-south-2",
  "eu-north-1",
  "eu-central-2"
];
var ME = ["me-south-1", "me-central-1"];
var SA = ["sa-east-1"];
var regions = [...US, ...AF, ...AP, ...CA, ...EU, ...ME, ...SA];
var RegionSchema = z25.enum(regions);

// src/config/app.ts
var AppSchema = z26.object({
  $schema: z26.string().optional(),
  name: ResourceIdSchema.describe("App name."),
  region: RegionSchema.describe("The AWS region to deploy to."),
  profile: z26.string().describe("The AWS profile to deploy to."),
  protect: z26.boolean().default(false).describe("Protect your app & stacks from being deleted."),
  removal: z26.enum(["remove", "retain"]).default("remove").describe(
    [
      "Configure how your resources are handled when they have to be removed.",
      "",
      "remove: Removes all underlying resources.",
      "retain: Retains the following resources: stores, tables, auth, searchs, and caches."
    ].join("\n")
  ),
  // stage: z
  // 	.string()
  // 	.regex(/^[a-z]+$/)
  // 	.default('prod')
  // 	.describe('The deployment stage.'),
  // onFailure: OnFailureSchema,
  defaults: z26.object({
    onFailure: OnFailureDefaultSchema,
    onErrorLog: OnErrorLogDefaultSchema,
    auth: AuthDefaultSchema,
    domains: DomainsDefaultSchema,
    function: FunctionDefaultSchema,
    instance: InstanceDefaultSchema,
    job: JobDefaultSchema,
    queue: QueueDefaultSchema,
    // graphql: GraphQLDefaultSchema,
    // http: HttpDefaultSchema,
    rest: RestDefaultSchema,
    rpc: RpcDefaultSchema,
    pubsub: PubSubDefaultSchema,
    // table: TableDefaultSchema,
    // store: StoreDefaultSchema,
    alerts: AlertsDefaultSchema,
    topics: TopicsDefaultSchema,
    layers: LayerSchema,
    router: RouterDefaultSchema
    // dataRetention: z.boolean().describe('Configure how your resources are handled on delete.').default(false),
  }).default({}).describe("Default properties")
});

// src/config/stack.ts
import { z as z41 } from "zod";

// src/feature/cache/schema.ts
import { gibibytes as gibibytes2 } from "@awsless/size";
import { z as z27 } from "zod";
var StorageSchema = SizeSchema.refine(sizeMin(gibibytes2(1)), "Minimum storage size is 1 GB").refine(
  sizeMax(gibibytes2(5e3)),
  "Maximum storage size is 5000 GB"
);
var MinimumStorageSchema = StorageSchema.describe(
  "The lower limit for data storage the cache is set to use. You can specify a size value from 1 GB to 5000 GB."
);
var MaximumStorageSchema = StorageSchema.describe(
  "The upper limit for data storage the cache is set to use. You can specify a size value from 1 GB to 5000 GB."
);
var EcpuSchema = z27.number().int().min(1e3).max(15e6);
var MinimumEcpuSchema = EcpuSchema.describe(
  "The minimum number of ECPUs the cache can consume per second. You can specify a integer from 1,000 to 15,000,000."
);
var MaximumEcpuSchema = EcpuSchema.describe(
  "The maximum number of ECPUs the cache can consume per second. You can specify a integer from 1,000 to 15,000,000."
);
var CachesSchema = z27.record(
  ResourceIdSchema,
  z27.object({
    minStorage: MinimumStorageSchema.optional(),
    maxStorage: MaximumStorageSchema.optional(),
    minECPU: MinimumEcpuSchema.optional(),
    maxECPU: MaximumEcpuSchema.optional(),
    snapshotRetentionLimit: z27.number().int().positive().default(1)
  })
).optional().describe("Define the caches in your stack. For access to the cache put your functions inside the global VPC.");

// src/feature/command/schema.ts
import { z as z28 } from "zod";
var CommandSchema = z28.union([
  z28.object({
    file: LocalFileSchema,
    handler: z28.string().default("default").describe("The name of the handler that needs to run"),
    description: z28.string().optional().describe("A description of the command")
    // options: z.record(ResourceIdSchema, OptionSchema).optional(),
    // arguments: z.record(ResourceIdSchema, ArgumentSchema).optional(),
  }),
  LocalFileSchema.transform((file) => ({
    file,
    handler: "default",
    description: void 0
  }))
]);
var CommandsSchema = z28.record(ResourceIdSchema, CommandSchema).optional().describe("Define the custom commands for your stack.");

// src/feature/config/schema.ts
import { z as z29 } from "zod";
var ConfigNameSchema = z29.string().regex(/[a-z0-9\-]/g, "Invalid config name");
var ConfigsSchema = z29.array(ConfigNameSchema).optional().describe("Define the config values for your stack.");

// src/feature/cron/schema/index.ts
import { z as z31 } from "zod";

// src/feature/cron/schema/schedule.ts
import { z as z30 } from "zod";
import { awsCronExpressionValidator } from "aws-cron-expression-validator";
var RateExpressionSchema = z30.custom(
  (value) => {
    return z30.string().regex(/^[0-9]+ (seconds?|minutes?|hours?|days?)$/).refine((rate) => {
      const [str] = rate.split(" ");
      const number = parseInt(str);
      return number > 0;
    }).safeParse(value).success;
  },
  { message: "Invalid rate expression" }
).transform((rate) => {
  const [str] = rate.split(" ");
  const number = parseInt(str);
  const more = rate.endsWith("s");
  if (more && number === 1) {
    return `rate(${rate.substring(0, rate.length - 1)})`;
  }
  return `rate(${rate})`;
});
var CronExpressionSchema = z30.custom(
  (value) => {
    return z30.string().safeParse(value).success;
  },
  { message: "Invalid cron expression" }
).superRefine((value, ctx) => {
  try {
    awsCronExpressionValidator(value);
  } catch (error) {
    if (error instanceof Error) {
      ctx.addIssue({
        code: z30.ZodIssueCode.custom,
        message: `Invalid cron expression: ${error.message}`
      });
    } else {
      ctx.addIssue({
        code: z30.ZodIssueCode.custom,
        message: "Invalid cron expression"
      });
    }
  }
}).transform((value) => {
  return `cron(${value.trim()})`;
});
var ScheduleExpressionSchema = RateExpressionSchema.or(CronExpressionSchema);

// src/feature/cron/schema/index.ts
var RetryAttemptsSchema3 = z31.number().int().min(0).max(2).describe(
  "The maximum number of times to retry when the function returns an error. You can specify a number from 0 to 2."
);
var CronsSchema = z31.record(
  ResourceIdSchema,
  z31.object({
    enabled: z31.boolean().default(true).describe("If the cron is enabled."),
    consumer: FunctionSchema.describe("The consuming lambda function properties."),
    schedule: ScheduleExpressionSchema.describe(
      'The scheduling expression.\n\nexample: "0 20 * * ? *"\nexample: "5 minutes"'
    ),
    payload: z31.unknown().optional().describe("The JSON payload that will be passed to the consumer."),
    retryAttempts: RetryAttemptsSchema3.default(2)
  })
).optional().describe(`Define the cron jobs in your stack.`);

// src/feature/search/schema.ts
import { gibibytes as gibibytes3 } from "@awsless/size";
import { z as z32 } from "zod";
var VersionSchema = z32.union([
  //
  z32.enum(["2.13", "2.11", "2.9", "2.7", "2.5", "2.3", "1.3"]),
  z32.string()
]).describe("Specify the OpenSearch engine version.");
var TypeSchema = z32.union([
  z32.enum([
    "t3.small",
    "t3.medium",
    "m3.medium",
    "m3.large",
    "m3.xlarge",
    "m3.2xlarge",
    "m4.large",
    "m4.xlarge",
    "m4.2xlarge",
    "m4.4xlarge",
    "m4.10xlarge",
    "m5.large",
    "m5.xlarge",
    "m5.2xlarge",
    "m5.4xlarge",
    "m5.12xlarge",
    "m5.24xlarge",
    "r5.large",
    "r5.xlarge",
    "r5.2xlarge",
    "r5.4xlarge",
    "r5.12xlarge",
    "r5.24xlarge",
    "c5.large",
    "c5.xlarge",
    "c5.2xlarge",
    "c5.4xlarge",
    "c5.9xlarge",
    "c5.18xlarge",
    "or1.medium",
    "or1.large",
    "or1.xlarge",
    "or1.2xlarge",
    "or1.4xlarge",
    "or1.8xlarge",
    "or1.12xlarge",
    "or1.16xlarge",
    "ultrawarm1.medium",
    "ultrawarm1.large",
    "ultrawarm1.xlarge",
    "r3.large",
    "r3.xlarge",
    "r3.2xlarge",
    "r3.4xlarge",
    "r3.8xlarge",
    "i2.xlarge",
    "i2.2xlarge",
    "i3.large",
    "i3.xlarge",
    "i3.2xlarge",
    "i3.4xlarge",
    "i3.8xlarge",
    "i3.16xlarge",
    "r6g.large",
    "r6g.xlarge",
    "r6g.2xlarge",
    "r6g.4xlarge",
    "r6g.8xlarge",
    "r6g.12xlarge",
    "m6g.large",
    "m6g.xlarge",
    "m6g.2xlarge",
    "m6g.4xlarge",
    "m6g.8xlarge",
    "m6g.12xlarge",
    "r6gd.large",
    "r6gd.xlarge",
    "r6gd.2xlarge",
    "r6gd.4xlarge",
    "r6gd.8xlarge",
    "r6gd.12xlarge",
    "r6gd.16xlarge"
  ]),
  z32.string()
]).describe("Instance type of data nodes in the cluster.");
var CountSchema = z32.number().int().min(1).describe("Number of instances in the cluster.");
var StorageSizeSchema = SizeSchema.refine(sizeMin(gibibytes3(10)), "Minimum storage size is 10 GB").refine(sizeMax(gibibytes3(100)), "Maximum storage size is 100 GB").describe("The size of the function's /tmp directory. You can specify a size value from 512 MB to 10 GiB.");
var SearchsSchema = z32.record(
  ResourceIdSchema,
  z32.object({
    type: TypeSchema.default("t3.small"),
    count: CountSchema.default(1),
    version: VersionSchema.default("2.13"),
    storage: StorageSizeSchema.default("10 GB")
    // vpc: z.boolean().default(false),
    // migration: FunctionSchema.optional(),
  })
).optional().describe("Define the search instances in your stack. Backed by OpenSearch.");

// src/feature/site/schema.ts
import { z as z34 } from "zod";

// src/config/schema/local-entry.ts
import { stat as stat3 } from "fs/promises";
import { z as z33 } from "zod";
var LocalEntrySchema = z33.union([
  RelativePathSchema.refine(async (path) => {
    try {
      const s = await stat3(path);
      return s.isFile() || s.isDirectory();
    } catch (error) {
      return false;
    }
  }, `File or directory doesn't exist`),
  z33.object({
    nocheck: RelativePathSchema.describe(
      "Specifies a local file or directory without checking if the file or directory exists."
    )
  }).transform((v) => v.nocheck)
]);

// src/feature/site/schema.ts
var SitesSchema = z34.record(
  ResourceIdSchema,
  z34.object({
    router: ResourceIdSchema.describe("The router id to link your site with."),
    path: RouteSchema2.describe("The path inside the router to link your site to."),
    build: z34.object({
      command: z34.string().describe(
        `Specifies the files and directories to generate the cache key for your custom build command.`
      ),
      cacheKey: z34.union([LocalEntrySchema.transform((v) => [v]), LocalEntrySchema.array()]).describe(
        `Specifies the files and directories to generate the cache key for your custom build command.`
      ),
      configs: z34.string().array().optional().describe("Define the config values for your build command.")
    }).optional().describe(`Specifies the build process for sites that need a build step.`),
    static: z34.union([LocalDirectorySchema, z34.boolean()]).optional().describe(
      "Specifies the path to the static files directory. Additionally you can also pass `true` when you don't have local static files, but still want to make an S3 bucket."
    ),
    ssr: FunctionSchema.optional().describe("Specifies the file that will render the site on the server.")
  })
).optional().describe("Define the sites in your stack.");

// src/feature/store/schema.ts
import { days as days6 } from "@awsless/duration";
import { z as z35 } from "zod";
var LifecycleRuleSchema = z35.object({
  prefix: z35.string().optional().describe("Object-key prefix this rule applies to. Omit to apply bucket-wide."),
  expiration: DurationSchema.refine(durationMin(days6(1)), "Minimum expiration is 1 day").describe(
    "How long objects matching this rule live before S3 deletes them."
  )
});
var StoresSchema = z35.union([
  z35.array(ResourceIdSchema).transform((list) => {
    const stores = {};
    for (const key of list) {
      stores[key] = {};
    }
    return stores;
  }),
  z35.record(
    ResourceIdSchema,
    z35.object({
      static: LocalDirectorySchema.optional().describe("Specifies the path to the static files directory."),
      versioning: z35.boolean().default(false).describe("Enable versioning of your store."),
      lifecycle: z35.array(LifecycleRuleSchema).optional().describe("S3 lifecycle rules for this store. Each rule expires objects matching an optional prefix."),
      events: z35.object({
        // create
        "created:*": TaskSchema.optional().describe(
          "Subscribe to notifications regardless of the API that was used to create an object."
        ),
        "created:put": TaskSchema.optional().describe(
          "Subscribe to notifications when an object is created using the PUT API operation."
        ),
        "created:post": TaskSchema.optional().describe(
          "Subscribe to notifications when an object is created using the POST API operation."
        ),
        "created:copy": TaskSchema.optional().describe(
          "Subscribe to notifications when an object is created using the COPY API operation."
        ),
        "created:upload": TaskSchema.optional().describe(
          "Subscribe to notifications when an object multipart upload has been completed."
        ),
        // remove
        "removed:*": TaskSchema.optional().describe(
          "Subscribe to notifications when an object is deleted or a delete marker for a versioned object is created."
        ),
        "removed:delete": TaskSchema.optional().describe(
          "Subscribe to notifications when an object is deleted"
        ),
        "removed:marker": TaskSchema.optional().describe(
          "Subscribe to notifications when a delete marker for a versioned object is created."
        )
      }).optional().describe("Describes the store events you want to subscribe too.")
    })
  )
]).optional().describe("Define the stores in your stack.");

// src/feature/icon/schema.ts
import { z as z36 } from "zod";
var staticOriginSchema = LocalDirectorySchema.describe(
  "Specifies the path to a local image directory that will be uploaded in S3."
);
var functionOriginSchema = FunctionSchema.describe(
  "Specifies the file that will be called when an image isn't found in the (cache) bucket."
);
var IconsSchema = z36.record(
  ResourceIdSchema,
  z36.object({
    // domain: ResourceIdSchema.describe('The domain id to link your site with.').optional(),
    // subDomain: z.string().optional(),
    router: ResourceIdSchema.describe("The router id to link your icon proxy."),
    path: RouteSchema2.describe("The path inside the router to link your icon proxy to."),
    log: LogSchema.optional(),
    cacheDuration: DurationSchema.optional().describe("The cache duration of the cached icons."),
    preserveIds: z36.boolean().optional().default(false).describe("Preserve the IDs of the icons."),
    symbols: z36.boolean().optional().default(false).describe(`Convert the SVG's to SVG symbols.`),
    origin: z36.union([
      z36.object({
        static: staticOriginSchema,
        function: functionOriginSchema.optional()
      }),
      z36.object({
        static: staticOriginSchema.optional(),
        function: functionOriginSchema
      })
      // z.object({
      // 	static: staticOriginSchema,
      // 	function: functionOriginSchema,
      // }),
    ]).describe(
      "Image transformation will be applied from a base image. Base images orginates from a local directory that will be uploaded to S3 or from a lambda function."
    )
    // cors: z
    // 	.object({
    // 		override: z.boolean().default(true),
    // 		maxAge: DurationSchema.default('365 days'),
    // 		exposeHeaders: z.string().array().optional(),
    // 		credentials: z.boolean().default(false),
    // 		headers: z.string().array().default(['*']),
    // 		origins: z.string().array().default(['*']),
    // 	})
    // 	.optional()
    // 	.describe('Specify the cors headers.'),
    // version: z.number().int().min(1).optional().describe('Version of the icon configuration.'),
  })
).optional().describe("Define an svg icon proxy in your stack. Store, optimize, and deliver svg icons at scale.");

// src/feature/image/schema.ts
import { z as z37 } from "zod";
var transformationOptionsSchema = z37.object({
  width: z37.number().int().positive().optional(),
  height: z37.number().int().positive().optional(),
  fit: z37.enum(["cover", "contain", "fill", "inside", "outside"]).optional(),
  position: z37.enum(["top", "right top", "right", "right bottom", "bottom", "left bottom", "left", "left top", "center"]).optional(),
  quality: z37.number().int().min(1).max(100).optional()
});
var staticOriginSchema2 = LocalDirectorySchema.describe(
  "Specifies the path to a local image directory that will be uploaded in S3."
);
var functionOriginSchema2 = FunctionSchema.describe(
  "Specifies the file that will be called when an image isn't found in the (cache) bucket."
);
var ImagesSchema = z37.record(
  ResourceIdSchema,
  z37.object({
    // domain: ResourceIdSchema.describe('The domain id to link your site with.').optional(),
    // subDomain: z.string().optional(),
    router: ResourceIdSchema.describe("The router id to link your image proxy."),
    path: RouteSchema2.describe("The path inside the router to link your image proxy to."),
    log: LogSchema.optional(),
    cacheDuration: DurationSchema.optional().describe("Cache duration of the cached images."),
    presets: z37.record(z37.string(), transformationOptionsSchema).describe("Named presets for image transformations"),
    extensions: z37.object({
      jpg: z37.object({
        mozjpeg: z37.boolean().optional(),
        progressive: z37.boolean().optional()
      }).optional(),
      webp: z37.object({
        effort: z37.number().int().min(1).max(10).default(7).optional(),
        lossless: z37.boolean().optional(),
        nearLossless: z37.boolean().optional()
      }).optional(),
      png: z37.object({
        compressionLevel: z37.number().int().min(0).max(9).default(6).optional()
      }).optional()
    }).refine((data) => {
      return Object.keys(data).length > 0;
    }, "At least one extension must be defined.").describe("Specify the allowed extensions."),
    origin: z37.union([
      z37.object({
        static: staticOriginSchema2,
        function: functionOriginSchema2.optional()
      }),
      z37.object({
        static: staticOriginSchema2.optional(),
        function: functionOriginSchema2
      })
      // z.object({
      // 	static: staticOriginSchema,
      // 	function: functionOriginSchema,
      // }),
    ]).describe(
      "Specify the origin of your images. Image transformation will be applied from a base image. Base images can be loaded from a S3 bucket (that is synced from a local directory) or dynamicly from a lambda function."
    )
  })
).optional().describe("Define an image proxy in your stack. Store, transform, optimize, and deliver images at scale.");

// src/feature/metric/schema.ts
import { z as z38 } from "zod";
var ops = {
  ">": "GreaterThanThreshold",
  ">=": "GreaterThanOrEqualToThreshold",
  "<": "LessThanThreshold",
  "<=": "LessThanOrEqualToThreshold"
};
var stats = {
  count: "SampleCount",
  avg: "Average",
  sum: "Sum",
  min: "Minimum",
  max: "Maximum"
};
var WhereSchema = z38.union([
  z38.string().regex(/(count|avg|sum|min|max) (>|>=|<|<=) (\d)/, "Invalid where query").transform((where) => {
    const [stat4, op, value] = where.split(" ");
    return { stat: stat4, op, value: parseFloat(value) };
  }),
  z38.object({
    stat: z38.enum(["count", "avg", "sum", "min", "max"]),
    op: z38.enum([">", ">=", "<", "<="]),
    value: z38.number()
  })
]).transform((where) => {
  return {
    stat: stats[where.stat],
    op: ops[where.op],
    value: where.value
  };
});
var AlarmSchema = z38.object({
  description: z38.string().optional(),
  where: WhereSchema,
  period: DurationSchema,
  minDataPoints: z38.number().int().default(1),
  trigger: z38.union([EmailSchema.transform((v) => [v]), EmailSchema.array(), FunctionSchema])
});
var MetricsSchema = z38.record(
  ResourceIdSchema,
  z38.object({
    type: z38.enum(["number", "size", "duration"]),
    alarms: AlarmSchema.array().optional()
  })
).optional().describe("Define the metrics in your stack.");

// src/feature/table/schema.ts
import { minutes as minutes5, seconds as seconds4 } from "@awsless/duration";
import { z as z39 } from "zod";
var KeySchema = z39.string().min(1).max(255);
var TablesSchema = z39.record(
  ResourceIdSchema,
  z39.object({
    hash: KeySchema.describe(
      "Specifies the name of the partition / hash key that makes up the primary key for the table."
    ),
    sort: KeySchema.optional().describe(
      "Specifies the name of the range / sort key that makes up the primary key for the table."
    ),
    fields: z39.record(z39.string(), z39.enum(["string", "number", "binary"])).optional().describe(
      'A list of attributes that describe the key schema for the table and indexes. If no attribute field is defined we default to "string".'
    ),
    class: z39.enum(["standard", "standard-infrequent-access"]).default("standard").describe("The table class of the table."),
    pointInTimeRecovery: z39.boolean().default(false).describe("Indicates whether point in time recovery is enabled on the table."),
    ttl: KeySchema.optional().describe(
      [
        "The name of the TTL attribute used to store the expiration time for items in the table.",
        "To update this property, you must first disable TTL and then enable TTL with the new attribute name."
      ].join("\n")
    ),
    // deletionProtection: DeletionProtectionSchema.optional(),
    stream: z39.object({
      type: z39.enum(["keys-only", "new-image", "old-image", "new-and-old-images"]).describe(
        [
          "When an item in the table is modified, you can determines what information is written to the stream for this table.",
          "Valid values are:",
          "- keys-only - Only the key attributes of the modified item are written to the stream.",
          "- new-image - The entire item, as it appears after it was modified, is written to the stream.",
          "- old-image - The entire item, as it appeared before it was modified, is written to the stream.",
          "- new-and-old-images - Both the new and the old item images of the item are written to the stream."
        ].join("\n")
      ),
      batchSize: z39.number().min(1).max(1e4).default(1).describe(
        [
          "The maximum number of records in each batch that Lambda pulls from your stream and sends to your function.",
          "Lambda passes all of the records in the batch to the function in a single call, up to the payload limit for synchronous invocation (6 MB).",
          "You can specify a number from 1 to 10000."
        ].join("\n")
      ),
      batchWindow: DurationSchema.refine(
        durationMin(seconds4(1)),
        "Minimum batch window duration is 1 second"
      ).refine(durationMax(minutes5(5)), "Maximum batch window duration is 5 minutes").optional().describe(
        [
          "The maximum amount of time that is spend gathering records before invoking the function.",
          "You can specify a duration from 1 seconds to 5 minutes."
        ].join("\n")
      ),
      // maxRecordAge: DurationSchema.refine(
      // 	durationMin(seconds(1)),
      // 	'Minimum record age duration is 1 second'
      // )
      // 	.refine(durationMax(minutes(1)), 'Maximum record age duration is 1 minute')
      // 	.default('60 seconds')
      // 	.describe(
      // 		[
      // 			'Discard records older than the specified age.',
      // 			'The maximum valid value for maximum record age is 60s.',
      // 			'The default value is 60s',
      // 		].join('\n')
      // 	),
      retryAttempts: z39.number().min(-1).max(1e4).default(2).describe(
        [
          "Discard records after the specified number of retries.",
          "-1 will sets the maximum number of retries to infinite.",
          "When maxRetryAttempts is infinite, Lambda retries failed records until the record expires in the event source.",
          "You can specify a number from -1 to 10000.",
          "The default value is 2"
        ].join("\n")
      ),
      concurrencyPerShard: z39.number().min(1).max(10).default(1).describe(
        [
          "The number of batches to process concurrently from each shard.",
          "You can specify a number from 1 to 10."
        ].join("\n")
      ),
      consumer: FunctionSchema.describe("The consuming lambda function for the stream")
    }).optional().describe(
      "The settings for the DynamoDB table stream, which capture changes to items stored in the table."
    ),
    indexes: z39.record(
      z39.string(),
      z39.object({
        hash: z39.union([KeySchema.transform((v) => [v]), KeySchema.array()]).describe(
          "Specifies the name of the partition / hash key that makes up the primary key for the global secondary index."
        ),
        sort: z39.union([KeySchema.transform((v) => [v]), KeySchema.array()]).optional().describe(
          "Specifies the name of the range / sort key that makes up the primary key for the global secondary index."
        ),
        projection: z39.enum(["all", "keys-only"]).default("all").describe(
          [
            "The set of attributes that are projected into the index:",
            "- all - All of the table attributes are projected into the index.",
            "- keys-only - Only the index and primary keys are projected into the index.",
            '@default "all"'
          ].join("\n")
        )
      })
    ).optional().describe("Specifies the global secondary indexes to be created on the table.")
  })
).optional().describe("Define the tables in your stack.");

// src/feature/test/schema.ts
import { z as z40 } from "zod";
var TestsSchema = z40.union([
  //
  LocalDirectorySchema.transform((v) => [v]),
  LocalDirectorySchema.array(),
  z40.literal(false)
]).describe("Define the location of your tests for your stack.").optional();

// src/config/stack.ts
var DependsSchema = ResourceIdSchema.array().optional().describe("Define the stacks that this stack is depended on.");
var NameSchema = ResourceIdSchema.refine((name) => !["base", "hostedzones"].includes(name), {
  message: `Stack name can't be a reserved name.`
}).describe("Stack name.");
var StackSchema = z41.object({
  $schema: z41.string().optional(),
  name: NameSchema,
  depends: DependsSchema,
  commands: CommandsSchema,
  // auth: AuthSchema,
  // http: HttpSchema,
  rest: RestSchema,
  rpc: RpcSchema,
  configs: ConfigsSchema,
  crons: CronsSchema,
  caches: CachesSchema,
  // topics: TopicsSchema,
  subscribers: SubscribersSchema,
  functions: FunctionsSchema,
  instances: InstancesSchema,
  jobs: JobsSchema,
  tasks: TasksSchema,
  tables: TablesSchema,
  stores: StoresSchema,
  // streams: StreamsSchema,
  queues: QueuesSchema,
  pubsub: PubSubSchema,
  searchs: SearchsSchema,
  sites: SitesSchema,
  tests: TestsSchema,
  images: ImagesSchema,
  icons: IconsSchema,
  metrics: MetricsSchema
});

// src/config/stage-patch-json-schema.ts
var clone = (value) => {
  return JSON.parse(JSON.stringify(value));
};
var escapePointerSegment = (value) => {
  return value.replaceAll("~", "~0").replaceAll("/", "~1");
};
var escapeRegexSegment = (value) => {
  return value.replace(/[|\\{}()[\]^$+*?.-]/g, "\\$&");
};
var makeExactPath = (prefix, segment) => {
  return `${prefix}/${escapePointerSegment(segment)}`;
};
var makeExactPattern = (path) => {
  return `^${path.split("/").map(escapeRegexSegment).join("/")}$`;
};
var makePatternPath = (prefix, segmentPattern) => {
  return prefix ? `${prefix}/${segmentPattern}` : `/${segmentPattern}`;
};
var appendExactPattern = (pattern, segment) => {
  const base = pattern.slice(1, -1);
  return `^${base}/${escapeRegexSegment(segment)}$`;
};
var appendRegexPattern = (pattern, segmentPattern) => {
  const base = pattern.slice(1, -1);
  return `^${base}/${segmentPattern}$`;
};
var mergeSchemas = (schemas) => {
  const list = schemas.map((schema) => clone(schema));
  if (list.length === 1) {
    return list[0];
  }
  return {
    anyOf: list
  };
};
var dereference = (schema, root) => {
  if (typeof schema.$ref !== "string" || !schema.$ref.startsWith("#/")) {
    return schema;
  }
  const target = schema.$ref.slice(2).split("/").map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~")).reduce((value, segment) => {
    if (typeof value === "object" && value !== null) {
      return value[segment];
    }
    return void 0;
  }, root);
  if (!target || typeof target !== "object") {
    return schema;
  }
  const { $ref: _, ...rest } = schema;
  return {
    ...clone(target),
    ...rest
  };
};
var listBranches = (schema) => {
  const groups = [schema.anyOf, schema.oneOf, schema.allOf].filter(Boolean);
  if (groups.length === 0) {
    return [schema];
  }
  return groups.flatMap((group) => group);
};
var childSegmentPattern = (schema) => {
  const propertyNameSchema = schema.propertyNames;
  if (propertyNameSchema && typeof propertyNameSchema.pattern === "string") {
    return propertyNameSchema.pattern;
  }
  const firstPattern = Object.keys(schema.patternProperties ?? {})[0];
  if (firstPattern) {
    return firstPattern;
  }
  return "[^/]+";
};
var joinEntries = (entries) => {
  const map = /* @__PURE__ */ new Map();
  for (const entry of entries) {
    const key = [entry.path, entry.pattern ?? "", entry.addOnly ? "1" : "0"].join("|");
    const previous = map.get(key);
    if (!previous) {
      map.set(key, {
        ...entry,
        schema: clone(entry.schema)
      });
      continue;
    }
    previous.schema = mergeSchemas([previous.schema, entry.schema]);
  }
  return [...map.values()];
};
var collectEntries = (schema, pointer = "", pattern = makeExactPattern(pointer), root = schema) => {
  const resolved = dereference(schema, root);
  const entries = [
    {
      path: pointer,
      pattern,
      schema: clone(resolved)
    }
  ];
  for (const branch of listBranches(resolved)) {
    const branchType = Array.isArray(branch.type) ? branch.type : branch.type ? [branch.type] : [];
    const isObject = branchType.includes("object") || branch.properties !== void 0 || branch.additionalProperties !== void 0 || branch.patternProperties !== void 0;
    const isArray = branchType.includes("array") || branch.items !== void 0 || branch.prefixItems !== void 0;
    if (isObject) {
      for (const [property, propertySchema] of Object.entries(branch.properties ?? {})) {
        const path = makeExactPath(pointer, property);
        entries.push(...collectEntries(propertySchema, path, appendExactPattern(pattern, property), root));
      }
      for (const [propertyPattern, propertySchema] of Object.entries(branch.patternProperties ?? {})) {
        const path = makePatternPath(pointer, propertyPattern);
        entries.push(...collectEntries(propertySchema, path, appendRegexPattern(pattern, propertyPattern), root));
      }
      if (branch.additionalProperties && typeof branch.additionalProperties === "object") {
        const segmentPattern = childSegmentPattern(branch);
        const path = makePatternPath(pointer, segmentPattern);
        entries.push(...collectEntries(branch.additionalProperties, path, appendRegexPattern(pattern, segmentPattern), root));
      }
    }
    if (isArray) {
      if (Array.isArray(branch.items)) {
        branch.items.forEach((itemSchema, index) => {
          entries.push(...collectEntries(itemSchema, `${pointer}/${index}`, appendExactPattern(pattern, `${index}`), root));
        });
      } else if (branch.items && typeof branch.items === "object") {
        entries.push(...collectEntries(branch.items, `${pointer}/\\d+`, appendRegexPattern(pattern, "\\d+"), root));
        entries.push({
          path: `${pointer}/-`,
          pattern: makeExactPattern(`${pointer}/-`),
          schema: clone(branch.items),
          addOnly: true
        });
      }
      for (const [index, itemSchema] of (branch.prefixItems ?? []).entries()) {
        entries.push(...collectEntries(itemSchema, `${pointer}/${index}`, appendExactPattern(pattern, `${index}`), root));
      }
    }
  }
  return joinEntries(entries);
};
var pathMatcherSchema = (entry) => {
  if (entry.pattern && entry.pattern !== makeExactPattern(entry.path)) {
    return {
      type: "string",
      pattern: entry.pattern
    };
  }
  return {
    type: "string",
    const: entry.path
  };
};
var objectSchema = (properties, required) => {
  return {
    type: "object",
    properties,
    required,
    additionalProperties: false
  };
};
var conditionalValueSchema = (entry) => {
  return {
    if: {
      type: "object",
      properties: {
        path: pathMatcherSchema(entry)
      },
      required: ["path"]
    },
    then: {
      properties: {
        value: clone(entry.schema)
      }
    }
  };
};
var matchersSchema = (entries) => {
  return {
    oneOf: entries.map(pathMatcherSchema)
  };
};
var patchOperationSchema = (op, entries) => {
  const props = {
    op: {
      type: "string",
      const: op
    },
    path: matchersSchema(entries)
  };
  const required = ["op", "path"];
  const schema = objectSchema(props, required);
  switch (op) {
    case "add":
    case "replace":
    case "test":
      schema.properties = {
        ...schema.properties,
        value: {}
      };
      schema.required = [...required, "value"];
      schema.allOf = entries.map(conditionalValueSchema);
      return schema;
    case "move":
    case "copy":
      schema.properties = {
        ...schema.properties,
        from: matchersSchema(entries)
      };
      schema.required = ["op", "from", "path"];
      return schema;
    default:
      return schema;
  }
};
var normalizeEntry = (entry) => {
  return {
    ...entry,
    pattern: entry.pattern ?? makeExactPattern(entry.path)
  };
};
var isSchemaMetadataPath = (entry) => {
  return entry.path === "/$schema" || entry.path.startsWith("/$schema/");
};
var createStagePatchJsonSchema = (baseSchema, title) => {
  const entries = collectEntries(baseSchema).map(normalizeEntry).filter((entry) => !isSchemaMetadataPath(entry));
  const standardEntries = entries.filter((entry) => !entry.addOnly);
  const addEntries = entries;
  const moveCopyEntries = standardEntries.filter((entry) => entry.path !== "");
  return {
    $schema: "http://json-schema.org/draft-07/schema#",
    title,
    type: "object",
    additionalProperties: false,
    properties: {
      $schema: {
        type: "string"
      },
      operations: {
        type: "array",
        items: {
          oneOf: [
            patchOperationSchema("add", addEntries),
            patchOperationSchema("remove", standardEntries),
            patchOperationSchema("replace", standardEntries),
            patchOperationSchema("move", moveCopyEntries),
            patchOperationSchema("copy", moveCopyEntries),
            patchOperationSchema("test", standardEntries)
          ]
        }
      }
    },
    required: ["operations"]
  };
};

// cli/build-json-schema.ts
var generateJsonSchema = (props) => {
  const file = join2(process.cwd(), `dist/${props.name}.json`);
  const schema = zodToJsonSchema(props.schema, {
    name: props.name,
    // errorMessages: true,
    markdownDescription: true,
    pipeStrategy: "input",
    $refStrategy: "none"
  });
  appendDefaults(schema);
  schema.title = props.title;
  writeFileSync(file, JSON.stringify(schema));
  return schema;
};
var appendDefaults = (object) => {
  if (Array.isArray(object)) {
    object.forEach(appendDefaults);
  }
  if (typeof object === "object" && object !== null) {
    if ("default" in object && "type" in object) {
      if ("description" in object) {
        object.description += `

@default ${JSON.stringify(object.default)}`;
      }
      if ("markdownDescription" in object) {
        object.markdownDescription += `

@default \`\`\`${JSON.stringify(object.default)}\`\`\``;
      }
    } else {
      Object.values(object).forEach(appendDefaults);
    }
  }
};
var appSchema = generateJsonSchema({
  schema: AppSchema,
  name: "app",
  title: "Awsless App Config"
});
var stackSchema = generateJsonSchema({
  schema: StackSchema,
  name: "stack",
  title: "Awsless Stack Config"
});
writeFileSync(
  join2(process.cwd(), "dist/app.stage.json"),
  JSON.stringify(createStagePatchJsonSchema(appSchema, "Awsless App Stage Patch Config"))
);
writeFileSync(
  join2(process.cwd(), "dist/stack.stage.json"),
  JSON.stringify(createStagePatchJsonSchema(stackSchema, "Awsless Stack Stage Patch Config"))
);
