effortless-aws 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -188,7 +188,8 @@ type ResolveParams<P> = {
188
188
  * }
189
189
  * ```
190
190
  */
191
- declare const param: <T = string>(key: string, transform?: (raw: string) => T) => ParamRef<T>;
191
+ declare function param(key: string): ParamRef<string>;
192
+ declare function param<T>(key: string, transform: (raw: string) => T): ParamRef<T>;
192
193
 
193
194
  type AnyTableHandler$1 = TableHandler<any, any, any, any, any, any>;
194
195
  /** Maps a deps declaration to resolved runtime client types */
@@ -639,13 +640,13 @@ type HttpHandler<T = undefined, C = undefined, D = undefined, P = undefined, S e
639
640
  declare const defineHttp: <T = undefined, C = undefined, D extends Record<string, AnyTableHandler> | undefined = undefined, P extends Record<string, AnyParamRef> | undefined = undefined, S extends string[] | undefined = undefined>(options: DefineHttpOptions<T, C, D, P, S>) => HttpHandler<T, C, D, P, S>;
640
641
 
641
642
  /**
642
- * Configuration for a static site handler (serializable, extracted at build time)
643
+ * Configuration for a Lambda-served static site (API Gateway + Lambda)
643
644
  */
644
- type SiteConfig = {
645
+ type AppConfig = {
645
646
  /** Handler name. Defaults to export name if not specified */
646
647
  name?: string;
647
648
  /** Base URL path the site is served under (e.g., "/app") */
648
- path: string;
649
+ path?: string;
649
650
  /** Directory containing the static site files, relative to project root */
650
651
  dir: string;
651
652
  /** Default file for directory requests (default: "index.html") */
@@ -662,38 +663,79 @@ type SiteConfig = {
662
663
  observe?: boolean;
663
664
  };
664
665
  /**
665
- * Internal handler object created by defineSite
666
+ * Internal handler object created by defineApp
666
667
  * @internal
667
668
  */
668
- type SiteHandler = {
669
- readonly __brand: "effortless-site";
670
- readonly config: SiteConfig;
669
+ type AppHandler = {
670
+ readonly __brand: "effortless-app";
671
+ readonly config: AppConfig;
671
672
  };
672
673
  /**
673
- * Define a static site endpoint that serves files from a directory via Lambda
674
+ * Deploy a static site via Lambda + API Gateway.
675
+ * Files are bundled into the Lambda ZIP and served with auto-detected content types.
676
+ *
677
+ * For CDN-backed sites (S3 + CloudFront), use {@link defineStaticSite} instead.
674
678
  *
675
679
  * @param options - Site configuration: path, directory, optional SPA mode
676
680
  * @returns Handler object used by the deployment system
677
681
  *
678
682
  * @example Basic static site
679
683
  * ```typescript
680
- * export const app = defineSite({
684
+ * export const app = defineApp({
681
685
  * path: "/app",
682
686
  * dir: "src/webapp",
683
687
  * });
684
688
  * ```
689
+ */
690
+ declare const defineApp: (options: AppConfig) => AppHandler;
691
+
692
+ /**
693
+ * Configuration for a static site handler (S3 + CloudFront)
694
+ */
695
+ type StaticSiteConfig = {
696
+ /** Handler name. Defaults to export name if not specified */
697
+ name?: string;
698
+ /** Directory containing the static site files, relative to project root */
699
+ dir: string;
700
+ /** Default file for directory requests (default: "index.html") */
701
+ index?: string;
702
+ /** SPA mode: serve index.html for all paths that don't match a file (default: false) */
703
+ spa?: boolean;
704
+ /** Shell command to run before deploy to generate site content (e.g., "npx astro build") */
705
+ build?: string;
706
+ };
707
+ /**
708
+ * Internal handler object created by defineStaticSite
709
+ * @internal
710
+ */
711
+ type StaticSiteHandler = {
712
+ readonly __brand: "effortless-static-site";
713
+ readonly config: StaticSiteConfig;
714
+ };
715
+ /**
716
+ * Deploy a static site via S3 + CloudFront CDN.
685
717
  *
686
- * @example Astro site with build step
718
+ * @param options - Static site configuration: directory, optional SPA mode, build command
719
+ * @returns Handler object used by the deployment system
720
+ *
721
+ * @example Documentation site
687
722
  * ```typescript
688
- * export const dashboard = defineSite({
689
- * path: "/dashboard",
723
+ * export const docs = defineStaticSite({
690
724
  * dir: "dist",
691
725
  * build: "npx astro build",
726
+ * });
727
+ * ```
728
+ *
729
+ * @example SPA with client-side routing
730
+ * ```typescript
731
+ * export const app = defineStaticSite({
732
+ * dir: "dist",
692
733
  * spa: true,
734
+ * build: "npm run build",
693
735
  * });
694
736
  * ```
695
737
  */
696
- declare const defineSite: (options: SiteConfig) => SiteHandler;
738
+ declare const defineStaticSite: (options: StaticSiteConfig) => StaticSiteHandler;
697
739
 
698
740
  type BasePlatformEntity = {
699
741
  pk: string;
@@ -725,8 +767,8 @@ type ExecutionLogEntity = BasePlatformEntity & {
725
767
  type PlatformEntity = ExecutionLogEntity;
726
768
 
727
769
  type PlatformClient = {
728
- appendExecution(handlerName: string, handlerType: "http" | "table" | "site", entry: ExecutionEntry): Promise<void>;
729
- appendError(handlerName: string, handlerType: "http" | "table" | "site", entry: ErrorEntry): Promise<void>;
770
+ appendExecution(handlerName: string, handlerType: "http" | "table" | "app", entry: ExecutionEntry): Promise<void>;
771
+ appendError(handlerName: string, handlerType: "http" | "table" | "app", entry: ErrorEntry): Promise<void>;
730
772
  get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined>;
731
773
  query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]>;
732
774
  put(entity: PlatformEntity): Promise<void>;
@@ -734,4 +776,4 @@ type PlatformClient = {
734
776
  };
735
777
  declare const createPlatformClient: () => PlatformClient | undefined;
736
778
 
737
- export { type BasePlatformEntity, type ContentType, type DefineHttpOptions, type DefineTableOptions, type EffortlessConfig, type ErrorEntry, type ExecutionEntry, type ExecutionLogEntity, type FailedRecord, type HttpConfig, type HttpHandler, type HttpHandlerFn, type HttpMethod, type HttpRequest, type HttpResponse, type KeyType, type ParamRef, type PlatformClient, type PlatformEntity, type QueryParams, type ResolveDeps, type ResolveParams, type SiteConfig, type SiteHandler, type StreamView, type TableBatchCompleteFn, type TableBatchFn, type TableClient, type TableConfig, type TableHandler, type TableKey, type TableRecord, type TableRecordFn, createPlatformClient, defineConfig, defineHttp, defineSite, defineTable, param };
779
+ export { type AppConfig, type AppHandler, type BasePlatformEntity, type ContentType, type DefineHttpOptions, type DefineTableOptions, type EffortlessConfig, type ErrorEntry, type ExecutionEntry, type ExecutionLogEntity, type FailedRecord, type HttpConfig, type HttpHandler, type HttpHandlerFn, type HttpMethod, type HttpRequest, type HttpResponse, type KeyType, type ParamRef, type PlatformClient, type PlatformEntity, type QueryParams, type ResolveDeps, type ResolveParams, type StaticSiteConfig, type StaticSiteHandler, type StreamView, type TableBatchCompleteFn, type TableBatchFn, type TableClient, type TableConfig, type TableHandler, type TableKey, type TableRecord, type TableRecordFn, createPlatformClient, defineApp, defineConfig, defineHttp, defineStaticSite, defineTable, param };
package/dist/index.js CHANGED
@@ -35,19 +35,27 @@ var defineTable = (options) => {
35
35
  };
36
36
  };
37
37
 
38
- // src/handlers/define-site.ts
39
- var defineSite = (options) => ({
40
- __brand: "effortless-site",
38
+ // src/handlers/define-app.ts
39
+ var defineApp = (options) => ({
40
+ __brand: "effortless-app",
41
41
  config: options
42
42
  });
43
43
 
44
- // src/handlers/param.ts
45
- var param = (key, transform) => ({
46
- __brand: "effortless-param",
47
- key,
48
- ...transform ? { transform } : {}
44
+ // src/handlers/define-static-site.ts
45
+ var defineStaticSite = (options) => ({
46
+ __brand: "effortless-static-site",
47
+ config: options
49
48
  });
50
49
 
50
+ // src/handlers/param.ts
51
+ function param(key, transform) {
52
+ return {
53
+ __brand: "effortless-param",
54
+ key,
55
+ ...transform ? { transform } : {}
56
+ };
57
+ }
58
+
51
59
  // src/runtime/platform-client.ts
52
60
  import { DynamoDB } from "@aws-sdk/client-dynamodb";
53
61
  import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
@@ -140,9 +148,10 @@ var createPlatformClient = () => {
140
148
  };
141
149
  export {
142
150
  createPlatformClient,
151
+ defineApp,
143
152
  defineConfig,
144
153
  defineHttp,
145
- defineSite,
154
+ defineStaticSite,
146
155
  defineTable,
147
156
  param
148
157
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config.ts","../src/handlers/define-http.ts","../src/handlers/define-table.ts","../src/handlers/define-site.ts","../src/handlers/param.ts","../src/runtime/platform-client.ts","../src/runtime/platform-types.ts"],"sourcesContent":["/**\n * Configuration for an Effortless project.\n *\n * @example\n * ```typescript\n * // effortless.config.ts\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport type EffortlessConfig = {\n /**\n * Project name used for resource naming and tagging.\n * This becomes part of Lambda function names, IAM roles, etc.\n */\n name: string;\n\n /**\n * Default AWS region for all handlers.\n * Can be overridden per-handler or via CLI `--region` flag.\n * @default \"eu-central-1\"\n */\n region?: string;\n\n /**\n * Deployment stage (e.g., \"dev\", \"staging\", \"prod\").\n * Used for resource isolation and tagging.\n * @default \"dev\"\n */\n stage?: string;\n\n /**\n * Glob patterns or directory paths to scan for handlers.\n * Used by `eff deploy` (without file argument) to auto-discover handlers.\n *\n * @example\n * ```typescript\n * // Single directory - scans for all .ts files\n * handlers: \"src\"\n *\n * // Glob patterns\n * handlers: [\"src/**\\/*.ts\", \"lib/**\\/*.handler.ts\"]\n * ```\n */\n handlers?: string | string[];\n\n /**\n * Default settings applied to all handlers unless overridden.\n */\n defaults?: {\n /**\n * Lambda memory in MB.\n * @default 256\n */\n memory?: number;\n\n /**\n * Lambda timeout as a human-readable string.\n * @example \"30 seconds\", \"5 minutes\"\n */\n timeout?: string;\n\n /**\n * Lambda runtime.\n * @default \"nodejs22.x\"\n */\n runtime?: string;\n };\n};\n\n/**\n * Helper function for type-safe configuration.\n * Returns the config object as-is, but provides TypeScript autocompletion.\n *\n * @example\n * ```typescript\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport const defineConfig = (config: EffortlessConfig): EffortlessConfig => config;\n","import type { Permission } from \"./permissions\";\nimport type { TableHandler } from \"./define-table\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\nexport type ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\n\n/** HTTP methods supported by API Gateway */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/** Short content-type aliases for common response formats */\nexport type ContentType = \"json\" | \"html\" | \"text\" | \"css\" | \"js\" | \"xml\" | \"csv\" | \"svg\";\n\n/**\n * Incoming HTTP request object passed to the handler\n */\nexport type HttpRequest = {\n /** HTTP method (GET, POST, etc.) */\n method: string;\n /** Request path (e.g., \"/users/123\") */\n path: string;\n /** Request headers */\n headers: Record<string, string | undefined>;\n /** Query string parameters */\n query: Record<string, string | undefined>;\n /** Path parameters extracted from route (e.g., {id} -> params.id) */\n params: Record<string, string | undefined>;\n /** Parsed request body (JSON parsed if Content-Type is application/json) */\n body: unknown;\n /** Raw unparsed request body */\n rawBody?: string;\n};\n\n/**\n * HTTP response returned from the handler\n */\nexport type HttpResponse = {\n /** HTTP status code (e.g., 200, 404, 500) */\n status: number;\n /** Response body — JSON-serialized by default, or sent as string when contentType is set */\n body?: unknown;\n /**\n * Short content-type alias. Resolves to full MIME type automatically:\n * - `\"json\"` → `application/json` (default if omitted)\n * - `\"html\"` → `text/html; charset=utf-8`\n * - `\"text\"` → `text/plain; charset=utf-8`\n * - `\"css\"` → `text/css; charset=utf-8`\n * - `\"js\"` → `application/javascript; charset=utf-8`\n * - `\"xml\"` → `application/xml; charset=utf-8`\n * - `\"csv\"` → `text/csv; charset=utf-8`\n * - `\"svg\"` → `image/svg+xml; charset=utf-8`\n */\n contentType?: ContentType;\n /** Response headers (use for custom content-types not covered by contentType) */\n headers?: Record<string, string>;\n};\n\n/**\n * Configuration options extracted from DefineHttpOptions (without onRequest callback)\n */\nexport type HttpConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** HTTP method for the route */\n method: HttpMethod;\n /** Route path (e.g., \"/api/users\", \"/api/users/{id}\") */\n path: string;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Enable observability logging to platform table (default: true) */\n observe?: boolean;\n};\n\n/**\n * Handler function type for HTTP endpoints\n *\n * @typeParam T - Type of the validated request body (from schema function)\n * @typeParam C - Type of the context/dependencies (from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type HttpHandlerFn<T = undefined, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { req: HttpRequest }\n & ([T] extends [undefined] ? {} : { data: T })\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<HttpResponse>;\n\n/**\n * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => C | Promise<C>;\n\n/**\n * Options for defining an HTTP endpoint\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies returned by context function\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type DefineHttpOptions<\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> = HttpConfig & {\n /**\n * Decode/validate function for the request body.\n * Called with the parsed body; should return typed data or throw on validation failure.\n * When provided, the handler receives validated `data` and invalid requests get a 400 response.\n *\n * Works with any validation library:\n * - Effect: `S.decodeUnknownSync(MySchema)`\n * - Zod: `(body) => myZodSchema.parse(body)`\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when schema validation or onRequest throws.\n * Receives the error and request, returns an HttpResponse.\n * If not provided, defaults to 400 for validation errors and 500 for handler errors.\n */\n onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n /**\n * Factory function to create context/dependencies for the request handler.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n */\n deps?: D;\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n * Typed values are injected into the handler via the `params` argument.\n */\n params?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `readStatic` callback argument.\n */\n static?: S;\n /** HTTP request handler function */\n onRequest: HttpHandlerFn<T, C, D, P, S>;\n};\n\n/**\n * Internal handler object created by defineHttp\n * @internal\n */\nexport type HttpHandler<T = undefined, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = {\n readonly __brand: \"effortless-http\";\n readonly config: HttpConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly static?: string[];\n readonly onRequest: HttpHandlerFn<T, C, D, P, S>;\n};\n\n/**\n * Define an HTTP endpoint that creates an API Gateway route + Lambda function\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies (inferred from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n * @param options - Configuration, optional schema, optional context factory, and request handler\n * @returns Handler object used by the deployment system\n *\n * @example Basic GET endpoint\n * ```typescript\n * export const hello = defineHttp({\n * method: \"GET\",\n * path: \"/hello\",\n * onRequest: async ({ req }) => ({\n * status: 200,\n * body: { message: \"Hello World!\" }\n * })\n * });\n * ```\n *\n * @example With SSM parameters\n * ```typescript\n * import { param } from \"effortless-aws\";\n *\n * export const api = defineHttp({\n * method: \"GET\",\n * path: \"/orders\",\n * params: {\n * dbUrl: param(\"database-url\"),\n * },\n * context: async ({ params }) => ({\n * pool: createPool(params.dbUrl),\n * }),\n * onRequest: async ({ req, ctx, params }) => ({\n * status: 200,\n * body: { dbUrl: params.dbUrl }\n * })\n * });\n * ```\n */\nexport const defineHttp = <\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineHttpOptions<T, C, D, P, S>\n): HttpHandler<T, C, D, P, S> => {\n const { onRequest, onError, context, schema, deps, params, static: staticFiles, ...config } = options;\n return {\n __brand: \"effortless-http\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n onRequest\n } as HttpHandler<T, C, D, P, S>;\n};\n","import type { Permission } from \"./permissions\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\ntype ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\n\n/** DynamoDB attribute types for keys */\nexport type KeyType = \"string\" | \"number\" | \"binary\";\n\n/**\n * DynamoDB table key definition\n */\nexport type TableKey = {\n /** Attribute name */\n name: string;\n /** Attribute type */\n type: KeyType;\n};\n\n/** DynamoDB Streams view type - determines what data is captured in stream records */\nexport type StreamView = \"NEW_AND_OLD_IMAGES\" | \"NEW_IMAGE\" | \"OLD_IMAGE\" | \"KEYS_ONLY\";\n\n/**\n * Configuration options extracted from DefineTableOptions (without onRecord/context)\n */\nexport type TableConfig = {\n /** Table/handler name. Defaults to export name if not specified */\n name?: string;\n /** Partition key definition */\n pk: TableKey;\n /** Sort key definition (optional) */\n sk?: TableKey;\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** TTL attribute name for automatic item expiration */\n ttlAttribute?: string;\n /** Stream view type - what data to include in stream records (default: \"NEW_AND_OLD_IMAGES\") */\n streamView?: StreamView;\n /** Number of records to process in each Lambda invocation (1-10000, default: 100) */\n batchSize?: number;\n /** Maximum time in seconds to gather records before invoking (0-300, default: 2) */\n batchWindow?: number;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Enable observability logging to platform table (default: true) */\n observe?: boolean;\n};\n\n/**\n * DynamoDB stream record passed to onRecord callback\n *\n * @typeParam T - Type of the table items (new/old values)\n */\nexport type TableRecord<T = Record<string, unknown>> = {\n /** Type of modification: INSERT, MODIFY, or REMOVE */\n eventName: \"INSERT\" | \"MODIFY\" | \"REMOVE\";\n /** New item value (present for INSERT and MODIFY) */\n new?: T;\n /** Old item value (present for MODIFY and REMOVE) */\n old?: T;\n /** Primary key of the affected item */\n keys: Record<string, unknown>;\n /** Sequence number for ordering */\n sequenceNumber?: string;\n /** Approximate timestamp when the modification occurred */\n timestamp?: number;\n};\n\n/**\n * Information about a failed record during batch processing\n *\n * @typeParam T - Type of the table items\n */\nexport type FailedRecord<T = Record<string, unknown>> = {\n /** The record that failed to process */\n record: TableRecord<T>;\n /** The error that occurred */\n error: unknown;\n};\n\n/**\n * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => C | Promise<C>;\n\n/**\n * Callback function type for processing a single DynamoDB stream record\n */\nexport type TableRecordFn<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { record: TableRecord<T>; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<R>;\n\n/**\n * Callback function type for processing accumulated batch results\n */\nexport type TableBatchCompleteFn<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { results: R[]; failures: FailedRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<void>;\n\n/**\n * Callback function type for processing all records in a batch at once\n */\nexport type TableBatchFn<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { records: TableRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<void>;\n\n/** Base options shared by all defineTable variants */\ntype DefineTableBase<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = TableConfig & {\n /**\n * Decode/validate function for stream record items (new/old images).\n * Called with the unmarshalled DynamoDB item; should return typed data or throw on validation failure.\n * When provided, T is inferred from the return type — no need to specify generic parameters.\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when onRecord, onBatch, or onBatchComplete throws.\n * Receives the error. If not provided, defaults to `console.error`.\n */\n onError?: (error: unknown) => void;\n /**\n * Factory function to create context/dependencies for callbacks.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n */\n deps?: D;\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n * Typed values are injected into the handler via the `params` argument.\n */\n params?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `readStatic` callback argument.\n */\n static?: S;\n};\n\n/** Per-record processing: onRecord with optional onBatchComplete */\ntype DefineTableWithOnRecord<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onRecord: TableRecordFn<T, C, R, D, P, S>;\n onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P, S>;\n onBatch?: never;\n};\n\n/** Batch processing: onBatch processes all records at once */\ntype DefineTableWithOnBatch<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onBatch: TableBatchFn<T, C, D, P, S>;\n onRecord?: never;\n onBatchComplete?: never;\n};\n\n/** Resource-only: no handler, just creates the table */\ntype DefineTableResourceOnly<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onRecord?: never;\n onBatch?: never;\n onBatchComplete?: never;\n};\n\nexport type DefineTableOptions<\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> =\n | DefineTableWithOnRecord<T, C, R, D, P, S>\n | DefineTableWithOnBatch<T, C, D, P, S>\n | DefineTableResourceOnly<T, C, D, P, S>;\n\n/**\n * Internal handler object created by defineTable\n * @internal\n */\nexport type TableHandler<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> = {\n readonly __brand: \"effortless-table\";\n readonly config: TableConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly static?: string[];\n readonly onRecord?: TableRecordFn<T, C, R, D, P, S>;\n readonly onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P, S>;\n readonly onBatch?: TableBatchFn<T, C, D, P, S>;\n};\n\n/**\n * Define a DynamoDB table with optional stream handler\n *\n * Creates:\n * - DynamoDB table with specified key schema\n * - (If onRecord or onBatch provided) DynamoDB Stream + Lambda + Event Source Mapping\n *\n * @example Table with stream handler (typed)\n * ```typescript\n * type Order = { id: string; amount: number; status: string };\n *\n * export const orders = defineTable<Order>({\n * pk: { name: \"id\", type: \"string\" },\n * streamView: \"NEW_AND_OLD_IMAGES\",\n * batchSize: 10,\n * onRecord: async ({ record }) => {\n * if (record.eventName === \"INSERT\") {\n * console.log(\"New order:\", record.new?.amount);\n * }\n * }\n * });\n * ```\n *\n * @example Table only (no Lambda)\n * ```typescript\n * export const users = defineTable({\n * pk: { name: \"id\", type: \"string\" },\n * sk: { name: \"email\", type: \"string\" }\n * });\n * ```\n */\nexport const defineTable = <\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineTableOptions<T, C, R, D, P, S>\n): TableHandler<T, C, R, D, P, S> => {\n const { onRecord, onBatchComplete, onBatch, onError, schema, context, deps, params, static: staticFiles, ...config } = options;\n return {\n __brand: \"effortless-table\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n ...(onRecord ? { onRecord } : {}),\n ...(onBatchComplete ? { onBatchComplete } : {}),\n ...(onBatch ? { onBatch } : {})\n } as TableHandler<T, C, R, D, P, S>;\n};\n","/**\n * Configuration for a static site handler (serializable, extracted at build time)\n */\nexport type SiteConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** Base URL path the site is served under (e.g., \"/app\") */\n path: string;\n /** Directory containing the static site files, relative to project root */\n dir: string;\n /** Default file for directory requests (default: \"index.html\") */\n index?: string;\n /** SPA mode: serve index.html for all paths that don't match a file (default: false) */\n spa?: boolean;\n /** Shell command to run before deploy to generate site content (e.g., \"npx astro build\") */\n build?: string;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 5) */\n timeout?: number;\n /** Enable observability logging to platform table (default: false) */\n observe?: boolean;\n};\n\n/**\n * Internal handler object created by defineSite\n * @internal\n */\nexport type SiteHandler = {\n readonly __brand: \"effortless-site\";\n readonly config: SiteConfig;\n};\n\n/**\n * Define a static site endpoint that serves files from a directory via Lambda\n *\n * @param options - Site configuration: path, directory, optional SPA mode\n * @returns Handler object used by the deployment system\n *\n * @example Basic static site\n * ```typescript\n * export const app = defineSite({\n * path: \"/app\",\n * dir: \"src/webapp\",\n * });\n * ```\n *\n * @example Astro site with build step\n * ```typescript\n * export const dashboard = defineSite({\n * path: \"/dashboard\",\n * dir: \"dist\",\n * build: \"npx astro build\",\n * spa: true,\n * });\n * ```\n */\nexport const defineSite = (options: SiteConfig): SiteHandler => ({\n __brand: \"effortless-site\",\n config: options,\n});\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyParamRef = ParamRef<any>;\n\n/**\n * Reference to an SSM Parameter Store parameter.\n *\n * @typeParam T - The resolved type after optional transform (default: string)\n */\nexport type ParamRef<T = string> = {\n readonly __brand: \"effortless-param\";\n readonly key: string;\n readonly transform?: (raw: string) => T;\n};\n\n/**\n * Maps a params declaration to resolved value types.\n *\n * @typeParam P - Record of param names to ParamRef instances\n */\nexport type ResolveParams<P> = {\n [K in keyof P]: P[K] extends ParamRef<infer T> ? T : never;\n};\n\n/**\n * Declare an SSM Parameter Store parameter.\n *\n * The key is combined with project and stage at deploy time to form the full\n * SSM path: `/${project}/${stage}/${key}`.\n *\n * @param key - Parameter key (e.g., \"database-url\")\n * @param transform - Optional function to transform the raw string value\n * @returns A ParamRef used by the deployment and runtime systems\n *\n * @example Simple string parameter\n * ```typescript\n * params: {\n * dbUrl: param(\"database-url\"),\n * }\n * ```\n *\n * @example With transform (e.g., TOML parsing)\n * ```typescript\n * import TOML from \"smol-toml\";\n *\n * params: {\n * config: param(\"app-config\", TOML.parse),\n * }\n * ```\n */\nexport const param = <T = string>(\n key: string,\n transform?: (raw: string) => T\n): ParamRef<T> => ({\n __brand: \"effortless-param\",\n key,\n ...(transform ? { transform } : {}),\n});\n","import { DynamoDB } from \"@aws-sdk/client-dynamodb\";\nimport { marshall, unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport type {\n PlatformEntity,\n ExecutionEntry,\n ErrorEntry,\n} from \"./platform-types\";\nimport {\n ENV_PLATFORM_TABLE,\n dateBucket,\n computeTtl,\n} from \"./platform-types\";\n\nexport type PlatformClient = {\n appendExecution(handlerName: string, handlerType: \"http\" | \"table\" | \"site\", entry: ExecutionEntry): Promise<void>;\n appendError(handlerName: string, handlerType: \"http\" | \"table\" | \"site\", entry: ErrorEntry): Promise<void>;\n get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined>;\n query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]>;\n put(entity: PlatformEntity): Promise<void>;\n tableName: string;\n};\n\nexport const createPlatformClient = (): PlatformClient | undefined => {\n const tableName = process.env[ENV_PLATFORM_TABLE];\n if (!tableName) return undefined;\n\n let client: DynamoDB | null = null;\n const getClient = () => (client ??= new DynamoDB({}));\n\n const appendToList = async (\n handlerName: string,\n handlerType: \"http\" | \"table\" | \"site\",\n listAttr: \"executions\" | \"errors\",\n entry: ExecutionEntry | ErrorEntry\n ): Promise<void> => {\n const sk = `EXEC#${dateBucket()}`;\n\n try {\n await getClient().updateItem({\n TableName: tableName,\n Key: marshall({ pk: `HANDLER#${handlerName}`, sk }),\n UpdateExpression:\n \"SET #list = list_append(if_not_exists(#list, :empty), :entry), \" +\n \"#type = :type, #hn = :hn, #ht = :ht, #ttl = :ttl\",\n ExpressionAttributeNames: {\n \"#list\": listAttr,\n \"#type\": \"type\",\n \"#hn\": \"handlerName\",\n \"#ht\": \"handlerType\",\n \"#ttl\": \"ttl\",\n },\n ExpressionAttributeValues: marshall(\n {\n \":entry\": [entry],\n \":empty\": [],\n \":type\": \"execution-log\",\n \":hn\": handlerName,\n \":ht\": handlerType,\n \":ttl\": computeTtl(),\n },\n { removeUndefinedValues: true }\n ),\n });\n } catch (err) {\n console.error(\"[effortless] Failed to write platform record:\", err);\n }\n };\n\n return {\n tableName,\n\n async appendExecution(handlerName, handlerType, entry) {\n await appendToList(handlerName, handlerType, \"executions\", entry);\n },\n\n async appendError(handlerName, handlerType, entry) {\n await appendToList(handlerName, handlerType, \"errors\", entry);\n },\n\n async get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined> {\n const result = await getClient().getItem({\n TableName: tableName,\n Key: marshall({ pk, sk }),\n });\n return result.Item ? (unmarshall(result.Item) as T) : undefined;\n },\n\n async query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]> {\n const names: Record<string, string> = { \"#pk\": \"pk\" };\n const values: Record<string, unknown> = { \":pk\": pk };\n let keyCondition = \"#pk = :pk\";\n\n if (skPrefix) {\n names[\"#sk\"] = \"sk\";\n values[\":sk\"] = skPrefix;\n keyCondition += \" AND begins_with(#sk, :sk)\";\n }\n\n const result = await getClient().query({\n TableName: tableName,\n KeyConditionExpression: keyCondition,\n ExpressionAttributeNames: names,\n ExpressionAttributeValues: marshall(values, { removeUndefinedValues: true }),\n });\n\n return (result.Items ?? []).map(item => unmarshall(item) as T);\n },\n\n async put(entity: PlatformEntity) {\n try {\n await getClient().putItem({\n TableName: tableName,\n Item: marshall(entity as Record<string, unknown>, { removeUndefinedValues: true }),\n });\n } catch (err) {\n console.error(\"[effortless] Failed to write platform record:\", err);\n }\n },\n };\n};\n","export const ENV_PLATFORM_TABLE = \"EFF_PLATFORM_TABLE\";\n\nexport const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days\n\n// ============ Base ============\n\nexport type BasePlatformEntity = {\n pk: string;\n sk: string;\n type: string;\n ttl?: number;\n};\n\n// ============ Execution Log ============\n\nexport type ExecutionEntry = {\n id: string;\n ts: string;\n ms: number;\n in: unknown;\n out?: unknown;\n};\n\nexport type ErrorEntry = {\n id: string;\n ts: string;\n ms: number;\n in: unknown;\n err: string;\n};\n\nexport type ExecutionLogEntity = BasePlatformEntity & {\n type: \"execution-log\";\n handlerName: string;\n handlerType: \"http\" | \"table\";\n executions: ExecutionEntry[];\n errors: ErrorEntry[];\n};\n\n// ============ Discriminated Union ============\n\nexport type PlatformEntity =\n | ExecutionLogEntity;\n // future: | IdempotencyEntity | HandlerMetaEntity\n\n// ============ Helpers ============\n\nexport const truncateForStorage = (value: unknown, maxLength = 4096): unknown => {\n if (value === undefined || value === null) return value;\n const str = typeof value === \"string\" ? value : JSON.stringify(value);\n if (str.length <= maxLength) return value;\n return str.slice(0, maxLength) + \"...[truncated]\";\n};\n\nexport const dateBucket = (date = new Date()): string =>\n date.toISOString().slice(0, 10);\n\nexport const computeTtl = (ttlSeconds = DEFAULT_TTL_SECONDS): number =>\n Math.floor(Date.now() / 1000) + ttlSeconds;\n"],"mappings":";AA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 {"version":3,"sources":["../src/config.ts","../src/handlers/define-http.ts","../src/handlers/define-table.ts","../src/handlers/define-app.ts","../src/handlers/define-static-site.ts","../src/handlers/param.ts","../src/runtime/platform-client.ts","../src/runtime/platform-types.ts"],"sourcesContent":["/**\n * Configuration for an Effortless project.\n *\n * @example\n * ```typescript\n * // effortless.config.ts\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport type EffortlessConfig = {\n /**\n * Project name used for resource naming and tagging.\n * This becomes part of Lambda function names, IAM roles, etc.\n */\n name: string;\n\n /**\n * Default AWS region for all handlers.\n * Can be overridden per-handler or via CLI `--region` flag.\n * @default \"eu-central-1\"\n */\n region?: string;\n\n /**\n * Deployment stage (e.g., \"dev\", \"staging\", \"prod\").\n * Used for resource isolation and tagging.\n * @default \"dev\"\n */\n stage?: string;\n\n /**\n * Glob patterns or directory paths to scan for handlers.\n * Used by `eff deploy` (without file argument) to auto-discover handlers.\n *\n * @example\n * ```typescript\n * // Single directory - scans for all .ts files\n * handlers: \"src\"\n *\n * // Glob patterns\n * handlers: [\"src/**\\/*.ts\", \"lib/**\\/*.handler.ts\"]\n * ```\n */\n handlers?: string | string[];\n\n /**\n * Default settings applied to all handlers unless overridden.\n */\n defaults?: {\n /**\n * Lambda memory in MB.\n * @default 256\n */\n memory?: number;\n\n /**\n * Lambda timeout as a human-readable string.\n * @example \"30 seconds\", \"5 minutes\"\n */\n timeout?: string;\n\n /**\n * Lambda runtime.\n * @default \"nodejs22.x\"\n */\n runtime?: string;\n };\n};\n\n/**\n * Helper function for type-safe configuration.\n * Returns the config object as-is, but provides TypeScript autocompletion.\n *\n * @example\n * ```typescript\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport const defineConfig = (config: EffortlessConfig): EffortlessConfig => config;\n","import type { Permission } from \"./permissions\";\nimport type { TableHandler } from \"./define-table\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\nexport type ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\n\n/** HTTP methods supported by API Gateway */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n\n/** Short content-type aliases for common response formats */\nexport type ContentType = \"json\" | \"html\" | \"text\" | \"css\" | \"js\" | \"xml\" | \"csv\" | \"svg\";\n\n/**\n * Incoming HTTP request object passed to the handler\n */\nexport type HttpRequest = {\n /** HTTP method (GET, POST, etc.) */\n method: string;\n /** Request path (e.g., \"/users/123\") */\n path: string;\n /** Request headers */\n headers: Record<string, string | undefined>;\n /** Query string parameters */\n query: Record<string, string | undefined>;\n /** Path parameters extracted from route (e.g., {id} -> params.id) */\n params: Record<string, string | undefined>;\n /** Parsed request body (JSON parsed if Content-Type is application/json) */\n body: unknown;\n /** Raw unparsed request body */\n rawBody?: string;\n};\n\n/**\n * HTTP response returned from the handler\n */\nexport type HttpResponse = {\n /** HTTP status code (e.g., 200, 404, 500) */\n status: number;\n /** Response body — JSON-serialized by default, or sent as string when contentType is set */\n body?: unknown;\n /**\n * Short content-type alias. Resolves to full MIME type automatically:\n * - `\"json\"` → `application/json` (default if omitted)\n * - `\"html\"` → `text/html; charset=utf-8`\n * - `\"text\"` → `text/plain; charset=utf-8`\n * - `\"css\"` → `text/css; charset=utf-8`\n * - `\"js\"` → `application/javascript; charset=utf-8`\n * - `\"xml\"` → `application/xml; charset=utf-8`\n * - `\"csv\"` → `text/csv; charset=utf-8`\n * - `\"svg\"` → `image/svg+xml; charset=utf-8`\n */\n contentType?: ContentType;\n /** Response headers (use for custom content-types not covered by contentType) */\n headers?: Record<string, string>;\n};\n\n/**\n * Configuration options extracted from DefineHttpOptions (without onRequest callback)\n */\nexport type HttpConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** HTTP method for the route */\n method: HttpMethod;\n /** Route path (e.g., \"/api/users\", \"/api/users/{id}\") */\n path: string;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Enable observability logging to platform table (default: true) */\n observe?: boolean;\n};\n\n/**\n * Handler function type for HTTP endpoints\n *\n * @typeParam T - Type of the validated request body (from schema function)\n * @typeParam C - Type of the context/dependencies (from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type HttpHandlerFn<T = undefined, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { req: HttpRequest }\n & ([T] extends [undefined] ? {} : { data: T })\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<HttpResponse>;\n\n/**\n * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => C | Promise<C>;\n\n/**\n * Options for defining an HTTP endpoint\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies returned by context function\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type DefineHttpOptions<\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> = HttpConfig & {\n /**\n * Decode/validate function for the request body.\n * Called with the parsed body; should return typed data or throw on validation failure.\n * When provided, the handler receives validated `data` and invalid requests get a 400 response.\n *\n * Works with any validation library:\n * - Effect: `S.decodeUnknownSync(MySchema)`\n * - Zod: `(body) => myZodSchema.parse(body)`\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when schema validation or onRequest throws.\n * Receives the error and request, returns an HttpResponse.\n * If not provided, defaults to 400 for validation errors and 500 for handler errors.\n */\n onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n /**\n * Factory function to create context/dependencies for the request handler.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n */\n deps?: D;\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n * Typed values are injected into the handler via the `params` argument.\n */\n params?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `readStatic` callback argument.\n */\n static?: S;\n /** HTTP request handler function */\n onRequest: HttpHandlerFn<T, C, D, P, S>;\n};\n\n/**\n * Internal handler object created by defineHttp\n * @internal\n */\nexport type HttpHandler<T = undefined, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = {\n readonly __brand: \"effortless-http\";\n readonly config: HttpConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly static?: string[];\n readonly onRequest: HttpHandlerFn<T, C, D, P, S>;\n};\n\n/**\n * Define an HTTP endpoint that creates an API Gateway route + Lambda function\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies (inferred from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n * @param options - Configuration, optional schema, optional context factory, and request handler\n * @returns Handler object used by the deployment system\n *\n * @example Basic GET endpoint\n * ```typescript\n * export const hello = defineHttp({\n * method: \"GET\",\n * path: \"/hello\",\n * onRequest: async ({ req }) => ({\n * status: 200,\n * body: { message: \"Hello World!\" }\n * })\n * });\n * ```\n *\n * @example With SSM parameters\n * ```typescript\n * import { param } from \"effortless-aws\";\n *\n * export const api = defineHttp({\n * method: \"GET\",\n * path: \"/orders\",\n * params: {\n * dbUrl: param(\"database-url\"),\n * },\n * context: async ({ params }) => ({\n * pool: createPool(params.dbUrl),\n * }),\n * onRequest: async ({ req, ctx, params }) => ({\n * status: 200,\n * body: { dbUrl: params.dbUrl }\n * })\n * });\n * ```\n */\nexport const defineHttp = <\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineHttpOptions<T, C, D, P, S>\n): HttpHandler<T, C, D, P, S> => {\n const { onRequest, onError, context, schema, deps, params, static: staticFiles, ...config } = options;\n return {\n __brand: \"effortless-http\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n onRequest\n } as HttpHandler<T, C, D, P, S>;\n};\n","import type { Permission } from \"./permissions\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\ntype ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\n\n/** DynamoDB attribute types for keys */\nexport type KeyType = \"string\" | \"number\" | \"binary\";\n\n/**\n * DynamoDB table key definition\n */\nexport type TableKey = {\n /** Attribute name */\n name: string;\n /** Attribute type */\n type: KeyType;\n};\n\n/** DynamoDB Streams view type - determines what data is captured in stream records */\nexport type StreamView = \"NEW_AND_OLD_IMAGES\" | \"NEW_IMAGE\" | \"OLD_IMAGE\" | \"KEYS_ONLY\";\n\n/**\n * Configuration options extracted from DefineTableOptions (without onRecord/context)\n */\nexport type TableConfig = {\n /** Table/handler name. Defaults to export name if not specified */\n name?: string;\n /** Partition key definition */\n pk: TableKey;\n /** Sort key definition (optional) */\n sk?: TableKey;\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** TTL attribute name for automatic item expiration */\n ttlAttribute?: string;\n /** Stream view type - what data to include in stream records (default: \"NEW_AND_OLD_IMAGES\") */\n streamView?: StreamView;\n /** Number of records to process in each Lambda invocation (1-10000, default: 100) */\n batchSize?: number;\n /** Maximum time in seconds to gather records before invoking (0-300, default: 2) */\n batchWindow?: number;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Enable observability logging to platform table (default: true) */\n observe?: boolean;\n};\n\n/**\n * DynamoDB stream record passed to onRecord callback\n *\n * @typeParam T - Type of the table items (new/old values)\n */\nexport type TableRecord<T = Record<string, unknown>> = {\n /** Type of modification: INSERT, MODIFY, or REMOVE */\n eventName: \"INSERT\" | \"MODIFY\" | \"REMOVE\";\n /** New item value (present for INSERT and MODIFY) */\n new?: T;\n /** Old item value (present for MODIFY and REMOVE) */\n old?: T;\n /** Primary key of the affected item */\n keys: Record<string, unknown>;\n /** Sequence number for ordering */\n sequenceNumber?: string;\n /** Approximate timestamp when the modification occurred */\n timestamp?: number;\n};\n\n/**\n * Information about a failed record during batch processing\n *\n * @typeParam T - Type of the table items\n */\nexport type FailedRecord<T = Record<string, unknown>> = {\n /** The record that failed to process */\n record: TableRecord<T>;\n /** The error that occurred */\n error: unknown;\n};\n\n/**\n * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => C | Promise<C>;\n\n/**\n * Callback function type for processing a single DynamoDB stream record\n */\nexport type TableRecordFn<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { record: TableRecord<T>; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<R>;\n\n/**\n * Callback function type for processing accumulated batch results\n */\nexport type TableBatchCompleteFn<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { results: R[]; failures: FailedRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<void>;\n\n/**\n * Callback function type for processing all records in a batch at once\n */\nexport type TableBatchFn<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { records: TableRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n & ([S] extends [undefined] ? {} : { readStatic: (path: string) => string })\n ) => Promise<void>;\n\n/** Base options shared by all defineTable variants */\ntype DefineTableBase<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = TableConfig & {\n /**\n * Decode/validate function for stream record items (new/old images).\n * Called with the unmarshalled DynamoDB item; should return typed data or throw on validation failure.\n * When provided, T is inferred from the return type — no need to specify generic parameters.\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when onRecord, onBatch, or onBatchComplete throws.\n * Receives the error. If not provided, defaults to `console.error`.\n */\n onError?: (error: unknown) => void;\n /**\n * Factory function to create context/dependencies for callbacks.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n */\n deps?: D;\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n * Typed values are injected into the handler via the `params` argument.\n */\n params?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `readStatic` callback argument.\n */\n static?: S;\n};\n\n/** Per-record processing: onRecord with optional onBatchComplete */\ntype DefineTableWithOnRecord<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onRecord: TableRecordFn<T, C, R, D, P, S>;\n onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P, S>;\n onBatch?: never;\n};\n\n/** Batch processing: onBatch processes all records at once */\ntype DefineTableWithOnBatch<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onBatch: TableBatchFn<T, C, D, P, S>;\n onRecord?: never;\n onBatchComplete?: never;\n};\n\n/** Resource-only: no handler, just creates the table */\ntype DefineTableResourceOnly<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onRecord?: never;\n onBatch?: never;\n onBatchComplete?: never;\n};\n\nexport type DefineTableOptions<\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> =\n | DefineTableWithOnRecord<T, C, R, D, P, S>\n | DefineTableWithOnBatch<T, C, D, P, S>\n | DefineTableResourceOnly<T, C, D, P, S>;\n\n/**\n * Internal handler object created by defineTable\n * @internal\n */\nexport type TableHandler<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> = {\n readonly __brand: \"effortless-table\";\n readonly config: TableConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly static?: string[];\n readonly onRecord?: TableRecordFn<T, C, R, D, P, S>;\n readonly onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P, S>;\n readonly onBatch?: TableBatchFn<T, C, D, P, S>;\n};\n\n/**\n * Define a DynamoDB table with optional stream handler\n *\n * Creates:\n * - DynamoDB table with specified key schema\n * - (If onRecord or onBatch provided) DynamoDB Stream + Lambda + Event Source Mapping\n *\n * @example Table with stream handler (typed)\n * ```typescript\n * type Order = { id: string; amount: number; status: string };\n *\n * export const orders = defineTable<Order>({\n * pk: { name: \"id\", type: \"string\" },\n * streamView: \"NEW_AND_OLD_IMAGES\",\n * batchSize: 10,\n * onRecord: async ({ record }) => {\n * if (record.eventName === \"INSERT\") {\n * console.log(\"New order:\", record.new?.amount);\n * }\n * }\n * });\n * ```\n *\n * @example Table only (no Lambda)\n * ```typescript\n * export const users = defineTable({\n * pk: { name: \"id\", type: \"string\" },\n * sk: { name: \"email\", type: \"string\" }\n * });\n * ```\n */\nexport const defineTable = <\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineTableOptions<T, C, R, D, P, S>\n): TableHandler<T, C, R, D, P, S> => {\n const { onRecord, onBatchComplete, onBatch, onError, schema, context, deps, params, static: staticFiles, ...config } = options;\n return {\n __brand: \"effortless-table\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n ...(onRecord ? { onRecord } : {}),\n ...(onBatchComplete ? { onBatchComplete } : {}),\n ...(onBatch ? { onBatch } : {})\n } as TableHandler<T, C, R, D, P, S>;\n};\n","/**\n * Configuration for a Lambda-served static site (API Gateway + Lambda)\n */\nexport type AppConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** Base URL path the site is served under (e.g., \"/app\") */\n path?: string;\n /** Directory containing the static site files, relative to project root */\n dir: string;\n /** Default file for directory requests (default: \"index.html\") */\n index?: string;\n /** SPA mode: serve index.html for all paths that don't match a file (default: false) */\n spa?: boolean;\n /** Shell command to run before deploy to generate site content (e.g., \"npx astro build\") */\n build?: string;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 5) */\n timeout?: number;\n /** Enable observability logging to platform table (default: false) */\n observe?: boolean;\n};\n\n/**\n * Internal handler object created by defineApp\n * @internal\n */\nexport type AppHandler = {\n readonly __brand: \"effortless-app\";\n readonly config: AppConfig;\n};\n\n/**\n * Deploy a static site via Lambda + API Gateway.\n * Files are bundled into the Lambda ZIP and served with auto-detected content types.\n *\n * For CDN-backed sites (S3 + CloudFront), use {@link defineStaticSite} instead.\n *\n * @param options - Site configuration: path, directory, optional SPA mode\n * @returns Handler object used by the deployment system\n *\n * @example Basic static site\n * ```typescript\n * export const app = defineApp({\n * path: \"/app\",\n * dir: \"src/webapp\",\n * });\n * ```\n */\nexport const defineApp = (options: AppConfig): AppHandler => ({\n __brand: \"effortless-app\",\n config: options,\n});\n","/**\n * Configuration for a static site handler (S3 + CloudFront)\n */\nexport type StaticSiteConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** Directory containing the static site files, relative to project root */\n dir: string;\n /** Default file for directory requests (default: \"index.html\") */\n index?: string;\n /** SPA mode: serve index.html for all paths that don't match a file (default: false) */\n spa?: boolean;\n /** Shell command to run before deploy to generate site content (e.g., \"npx astro build\") */\n build?: string;\n};\n\n/**\n * Internal handler object created by defineStaticSite\n * @internal\n */\nexport type StaticSiteHandler = {\n readonly __brand: \"effortless-static-site\";\n readonly config: StaticSiteConfig;\n};\n\n/**\n * Deploy a static site via S3 + CloudFront CDN.\n *\n * @param options - Static site configuration: directory, optional SPA mode, build command\n * @returns Handler object used by the deployment system\n *\n * @example Documentation site\n * ```typescript\n * export const docs = defineStaticSite({\n * dir: \"dist\",\n * build: \"npx astro build\",\n * });\n * ```\n *\n * @example SPA with client-side routing\n * ```typescript\n * export const app = defineStaticSite({\n * dir: \"dist\",\n * spa: true,\n * build: \"npm run build\",\n * });\n * ```\n */\nexport const defineStaticSite = (options: StaticSiteConfig): StaticSiteHandler => ({\n __brand: \"effortless-static-site\",\n config: options,\n});\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyParamRef = ParamRef<any>;\n\n/**\n * Reference to an SSM Parameter Store parameter.\n *\n * @typeParam T - The resolved type after optional transform (default: string)\n */\nexport type ParamRef<T = string> = {\n readonly __brand: \"effortless-param\";\n readonly key: string;\n readonly transform?: (raw: string) => T;\n};\n\n/**\n * Maps a params declaration to resolved value types.\n *\n * @typeParam P - Record of param names to ParamRef instances\n */\nexport type ResolveParams<P> = {\n [K in keyof P]: P[K] extends ParamRef<infer T> ? T : never;\n};\n\n/**\n * Declare an SSM Parameter Store parameter.\n *\n * The key is combined with project and stage at deploy time to form the full\n * SSM path: `/${project}/${stage}/${key}`.\n *\n * @param key - Parameter key (e.g., \"database-url\")\n * @param transform - Optional function to transform the raw string value\n * @returns A ParamRef used by the deployment and runtime systems\n *\n * @example Simple string parameter\n * ```typescript\n * params: {\n * dbUrl: param(\"database-url\"),\n * }\n * ```\n *\n * @example With transform (e.g., TOML parsing)\n * ```typescript\n * import TOML from \"smol-toml\";\n *\n * params: {\n * config: param(\"app-config\", TOML.parse),\n * }\n * ```\n */\nexport function param(key: string): ParamRef<string>;\nexport function param<T>(key: string, transform: (raw: string) => T): ParamRef<T>;\nexport function param<T = string>(\n key: string,\n transform?: (raw: string) => T\n): ParamRef<T> {\n return {\n __brand: \"effortless-param\",\n key,\n ...(transform ? { transform } : {}),\n } as ParamRef<T>;\n}\n","import { DynamoDB } from \"@aws-sdk/client-dynamodb\";\nimport { marshall, unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport type {\n PlatformEntity,\n ExecutionEntry,\n ErrorEntry,\n} from \"./platform-types\";\nimport {\n ENV_PLATFORM_TABLE,\n dateBucket,\n computeTtl,\n} from \"./platform-types\";\n\nexport type PlatformClient = {\n appendExecution(handlerName: string, handlerType: \"http\" | \"table\" | \"app\", entry: ExecutionEntry): Promise<void>;\n appendError(handlerName: string, handlerType: \"http\" | \"table\" | \"app\", entry: ErrorEntry): Promise<void>;\n get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined>;\n query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]>;\n put(entity: PlatformEntity): Promise<void>;\n tableName: string;\n};\n\nexport const createPlatformClient = (): PlatformClient | undefined => {\n const tableName = process.env[ENV_PLATFORM_TABLE];\n if (!tableName) return undefined;\n\n let client: DynamoDB | null = null;\n const getClient = () => (client ??= new DynamoDB({}));\n\n const appendToList = async (\n handlerName: string,\n handlerType: \"http\" | \"table\" | \"app\",\n listAttr: \"executions\" | \"errors\",\n entry: ExecutionEntry | ErrorEntry\n ): Promise<void> => {\n const sk = `EXEC#${dateBucket()}`;\n\n try {\n await getClient().updateItem({\n TableName: tableName,\n Key: marshall({ pk: `HANDLER#${handlerName}`, sk }),\n UpdateExpression:\n \"SET #list = list_append(if_not_exists(#list, :empty), :entry), \" +\n \"#type = :type, #hn = :hn, #ht = :ht, #ttl = :ttl\",\n ExpressionAttributeNames: {\n \"#list\": listAttr,\n \"#type\": \"type\",\n \"#hn\": \"handlerName\",\n \"#ht\": \"handlerType\",\n \"#ttl\": \"ttl\",\n },\n ExpressionAttributeValues: marshall(\n {\n \":entry\": [entry],\n \":empty\": [],\n \":type\": \"execution-log\",\n \":hn\": handlerName,\n \":ht\": handlerType,\n \":ttl\": computeTtl(),\n },\n { removeUndefinedValues: true }\n ),\n });\n } catch (err) {\n console.error(\"[effortless] Failed to write platform record:\", err);\n }\n };\n\n return {\n tableName,\n\n async appendExecution(handlerName, handlerType, entry) {\n await appendToList(handlerName, handlerType, \"executions\", entry);\n },\n\n async appendError(handlerName, handlerType, entry) {\n await appendToList(handlerName, handlerType, \"errors\", entry);\n },\n\n async get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined> {\n const result = await getClient().getItem({\n TableName: tableName,\n Key: marshall({ pk, sk }),\n });\n return result.Item ? (unmarshall(result.Item) as T) : undefined;\n },\n\n async query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]> {\n const names: Record<string, string> = { \"#pk\": \"pk\" };\n const values: Record<string, unknown> = { \":pk\": pk };\n let keyCondition = \"#pk = :pk\";\n\n if (skPrefix) {\n names[\"#sk\"] = \"sk\";\n values[\":sk\"] = skPrefix;\n keyCondition += \" AND begins_with(#sk, :sk)\";\n }\n\n const result = await getClient().query({\n TableName: tableName,\n KeyConditionExpression: keyCondition,\n ExpressionAttributeNames: names,\n ExpressionAttributeValues: marshall(values, { removeUndefinedValues: true }),\n });\n\n return (result.Items ?? []).map(item => unmarshall(item) as T);\n },\n\n async put(entity: PlatformEntity) {\n try {\n await getClient().putItem({\n TableName: tableName,\n Item: marshall(entity as Record<string, unknown>, { removeUndefinedValues: true }),\n });\n } catch (err) {\n console.error(\"[effortless] Failed to write platform record:\", err);\n }\n },\n };\n};\n","export const ENV_PLATFORM_TABLE = \"EFF_PLATFORM_TABLE\";\n\nexport const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days\n\n// ============ Base ============\n\nexport type BasePlatformEntity = {\n pk: string;\n sk: string;\n type: string;\n ttl?: number;\n};\n\n// ============ Execution Log ============\n\nexport type ExecutionEntry = {\n id: string;\n ts: string;\n ms: number;\n in: unknown;\n out?: unknown;\n};\n\nexport type ErrorEntry = {\n id: string;\n ts: string;\n ms: number;\n in: unknown;\n err: string;\n};\n\nexport type ExecutionLogEntity = BasePlatformEntity & {\n type: \"execution-log\";\n handlerName: string;\n handlerType: \"http\" | \"table\";\n executions: ExecutionEntry[];\n errors: ErrorEntry[];\n};\n\n// ============ Discriminated Union ============\n\nexport type PlatformEntity =\n | ExecutionLogEntity;\n // future: | IdempotencyEntity | HandlerMetaEntity\n\n// ============ Helpers ============\n\nexport const truncateForStorage = (value: unknown, maxLength = 4096): unknown => {\n if (value === undefined || value === null) return value;\n const str = typeof value === \"string\" ? value : JSON.stringify(value);\n if (str.length <= maxLength) return value;\n return str.slice(0, maxLength) + \"...[truncated]\";\n};\n\nexport const dateBucket = (date = new Date()): string =>\n date.toISOString().slice(0, 10);\n\nexport const computeTtl = (ttlSeconds = DEFAULT_TTL_SECONDS): number =>\n Math.floor(Date.now() / 1000) + ttlSeconds;\n"],"mappings":";AA0FO,IAAM,eAAe,CAAC,WAA+C;;;ACwIrE,IAAM,aAAa,CAOxB,YAC+B;AAC/B,QAAM,EAAE,WAAW,SAAS,SAAS,QAAQ,MAAM,QAAQ,QAAQ,aAAa,GAAG,OAAO,IAAI;AAC9F,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3B,GAA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aAAa,aAAa,OAAO;AACjD,YAAM,aAAa,aAAa,aAAa,UAAU,KAAK;AAAA,IAC9D;AAAA,IAEA,MAAM,IAA8B,IAAY,IAAoC;AAClF,YAAM,SAAS,MAAM,UAAU,EAAE,QAAQ;AAAA,QACvC,WAAW;AAAA,QACX,KAAK,SAAS,EAAE,IAAI,GAAG,CAAC;AAAA,MAC1B,CAAC;AACD,aAAO,OAAO,OAAQ,WAAW,OAAO,IAAI,IAAU;AAAA,IACxD;AAAA,IAEA,MAAM,MAAgC,IAAY,UAAiC;AACjF,YAAM,QAAgC,EAAE,OAAO,KAAK;AACpD,YAAM,SAAkC,EAAE,OAAO,GAAG;AACpD,UAAI,eAAe;AAEnB,UAAI,UAAU;AACZ,cAAM,KAAK,IAAI;AACf,eAAO,KAAK,IAAI;AAChB,wBAAgB;AAAA,MAClB;AAEA,YAAM,SAAS,MAAM,UAAU,EAAE,MAAM;AAAA,QACrC,WAAW;AAAA,QACX,wBAAwB;AAAA,QACxB,0BAA0B;AAAA,QAC1B,2BAA2B,SAAS,QAAQ,EAAE,uBAAuB,KAAK,CAAC;AAAA,MAC7E,CAAC;AAED,cAAQ,OAAO,SAAS,CAAC,GAAG,IAAI,UAAQ,WAAW,IAAI,CAAM;AAAA,IAC/D;AAAA,IAEA,MAAM,IAAI,QAAwB;AAChC,UAAI;AACF,cAAM,UAAU,EAAE,QAAQ;AAAA,UACxB,WAAW;AAAA,UACX,MAAM,SAAS,QAAmC,EAAE,uBAAuB,KAAK,CAAC;AAAA,QACnF,CAAC;AAAA,MACH,SAAS,KAAK;AACZ,gBAAQ,MAAM,iDAAiD,GAAG;AAAA,MACpE;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  createHandlerRuntime
3
3
  } from "../chunk-AHRNISIY.js";
4
4
 
5
- // src/runtime/wrap-site.ts
5
+ // src/runtime/wrap-app.ts
6
6
  import { readFileSync, existsSync } from "fs";
7
7
  import { join, extname, resolve } from "path";
8
8
  var CONTENT_TYPES = {
@@ -59,9 +59,9 @@ var TEXT_EXTENSIONS = /* @__PURE__ */ new Set([
59
59
  ".svg",
60
60
  ".map"
61
61
  ]);
62
- var wrapSite = (handler) => {
62
+ var wrapApp = (handler) => {
63
63
  const { dir, index: indexFile = "index.html", spa = false } = handler.config;
64
- const rt = createHandlerRuntime({}, "site");
64
+ const rt = createHandlerRuntime({}, "app");
65
65
  const baseDir = join(process.cwd(), dir);
66
66
  return async (event) => {
67
67
  const startTime = Date.now();
@@ -119,5 +119,5 @@ function serveFile(fullPath, filePath, rt, startTime) {
119
119
  };
120
120
  }
121
121
  export {
122
- wrapSite
122
+ wrapApp
123
123
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effortless-aws",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Code-first AWS Lambda framework",
@@ -33,10 +33,12 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@aws-sdk/client-apigatewayv2": "^3.975.0",
36
+ "@aws-sdk/client-cloudfront": "^3.989.0",
36
37
  "@aws-sdk/client-dynamodb": "^3.975.0",
37
38
  "@aws-sdk/client-iam": "^3.975.0",
38
39
  "@aws-sdk/client-lambda": "^3.975.0",
39
40
  "@aws-sdk/client-resource-groups-tagging-api": "^3.975.0",
41
+ "@aws-sdk/client-s3": "^3.989.0",
40
42
  "@aws-sdk/client-ssm": "^3.985.0",
41
43
  "@aws-sdk/util-dynamodb": "^3.975.0",
42
44
  "archiver": "^7.0.1",