@ericminassian/platform-core 0.1.0 → 0.3.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.
Files changed (45) hide show
  1. package/dist/api.d.ts +947 -209
  2. package/dist/api.js +335 -1
  3. package/dist/api.js.map +1 -1
  4. package/dist/auth.d.ts +19 -0
  5. package/dist/auth.js +29 -0
  6. package/dist/auth.js.map +1 -1
  7. package/dist/bindings.d.ts +8 -2
  8. package/dist/bindings.js.map +1 -1
  9. package/dist/cloudfront-function.js +6 -0
  10. package/dist/cloudfront-function.js.map +1 -1
  11. package/dist/config.d.ts +11 -1
  12. package/dist/config.js +7 -0
  13. package/dist/config.js.map +1 -1
  14. package/dist/constants.d.ts +11 -0
  15. package/dist/constants.js.map +1 -1
  16. package/dist/manifest.d.ts +203 -90
  17. package/dist/manifest.js +129 -93
  18. package/dist/manifest.js.map +1 -1
  19. package/dist/naming.d.ts +13 -2
  20. package/dist/naming.js +12 -1
  21. package/dist/naming.js.map +1 -1
  22. package/dist/platform-api.d.ts +5337 -0
  23. package/dist/platform-api.js +343 -0
  24. package/dist/platform-api.js.map +1 -0
  25. package/dist/router/decide.d.ts +5 -1
  26. package/dist/router/decide.js +7 -2
  27. package/dist/router.d.ts +1 -1
  28. package/dist/telemetry.d.ts +236 -74
  29. package/dist/telemetry.js +97 -0
  30. package/dist/telemetry.js.map +1 -1
  31. package/package.json +12 -6
  32. package/src/api.ts +427 -231
  33. package/src/auth.ts +33 -0
  34. package/src/bindings.ts +8 -2
  35. package/src/cloudfront-function.ts +6 -0
  36. package/src/config.ts +10 -2
  37. package/src/constants.ts +12 -0
  38. package/src/manifest.ts +280 -113
  39. package/src/naming.ts +13 -2
  40. package/src/platform-api.ts +504 -0
  41. package/src/router/decide.d.ts +5 -1
  42. package/src/router/decide.js +7 -2
  43. package/src/router.ts +1 -1
  44. package/src/telemetry.ts +107 -85
  45. package/platform.schema.json +0 -213
@@ -1,101 +1,214 @@
1
- import { z } from 'zod';
2
- declare const WebSchema: z.ZodObject<{
3
- server: z.ZodOptional<z.ZodString>;
4
- static: z.ZodOptional<z.ZodString>;
5
- build: z.ZodOptional<z.ZodString>;
6
- dev: z.ZodOptional<z.ZodObject<{
7
- command: z.ZodString;
8
- port: z.ZodNumber;
9
- }, z.core.$strip>>;
10
- spa: z.ZodDefault<z.ZodBoolean>;
11
- serverRoutes: z.ZodDefault<z.ZodArray<z.ZodString>>;
12
- timeoutSeconds: z.ZodDefault<z.ZodNumber>;
13
- concurrency: z.ZodDefault<z.ZodNumber>;
14
- }, z.core.$strip>;
15
- declare const WorkerSchema: z.ZodObject<{
16
- entry: z.ZodDefault<z.ZodString>;
17
- timeoutSeconds: z.ZodDefault<z.ZodNumber>;
18
- memoryMb: z.ZodDefault<z.ZodNumber>;
19
- }, z.core.$strip>;
20
- declare const QueueSchema: z.ZodObject<{
21
- batchSize: z.ZodDefault<z.ZodNumber>;
22
- visibilityTimeoutSeconds: z.ZodOptional<z.ZodNumber>;
23
- maxReceiveCount: z.ZodDefault<z.ZodNumber>;
24
- concurrency: z.ZodOptional<z.ZodNumber>;
25
- }, z.core.$strip>;
26
- export declare const ManifestSchema: z.ZodObject<{
27
- $schema: z.ZodOptional<z.ZodString>;
28
- name: z.ZodString;
29
- description: z.ZodOptional<z.ZodString>;
30
- web: z.ZodOptional<z.ZodObject<{
31
- server: z.ZodOptional<z.ZodString>;
32
- static: z.ZodOptional<z.ZodString>;
33
- build: z.ZodOptional<z.ZodString>;
34
- dev: z.ZodOptional<z.ZodObject<{
35
- command: z.ZodString;
36
- port: z.ZodNumber;
37
- }, z.core.$strip>>;
38
- spa: z.ZodDefault<z.ZodBoolean>;
39
- serverRoutes: z.ZodDefault<z.ZodArray<z.ZodString>>;
40
- timeoutSeconds: z.ZodDefault<z.ZodNumber>;
41
- concurrency: z.ZodDefault<z.ZodNumber>;
42
- }, z.core.$strip>>;
43
- worker: z.ZodOptional<z.ZodObject<{
44
- entry: z.ZodDefault<z.ZodString>;
45
- timeoutSeconds: z.ZodDefault<z.ZodNumber>;
46
- memoryMb: z.ZodDefault<z.ZodNumber>;
47
- }, z.core.$strip>>;
48
- auth: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
49
- required: z.ZodDefault<z.ZodBoolean>;
50
- }, z.core.$strip>]>>;
51
- db: z.ZodDefault<z.ZodBoolean>;
52
- queues: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
53
- batchSize: z.ZodDefault<z.ZodNumber>;
54
- visibilityTimeoutSeconds: z.ZodOptional<z.ZodNumber>;
55
- maxReceiveCount: z.ZodDefault<z.ZodNumber>;
56
- concurrency: z.ZodOptional<z.ZodNumber>;
57
- }, z.core.$strip>>>;
58
- events: z.ZodDefault<z.ZodArray<z.ZodString>>;
59
- crons: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
60
- schedule: z.ZodString;
61
- timezone: z.ZodOptional<z.ZodString>;
62
- }, z.core.$strip>]>>>;
63
- storage: z.ZodDefault<z.ZodArray<z.ZodString>>;
64
- secrets: z.ZodDefault<z.ZodArray<z.ZodString>>;
65
- env: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
66
- }, z.core.$strip>;
67
- export type ManifestInput = z.input<typeof ManifestSchema>;
68
- export type Manifest = z.output<typeof ManifestSchema>;
69
- /** Manifest with defaults applied and derived fields normalized. */
70
- export interface ResolvedManifest {
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * The app's config file, at the app root. `plat` evaluates it and sends the
4
+ * result to the platform as JSON; the control plane never runs app code.
5
+ */
6
+ export declare const APP_CONFIG_FILE = "plat.config.ts";
7
+ export declare const ManifestSchema: Schema.Struct<{
8
+ readonly name: Schema.String;
9
+ readonly description: Schema.optional<Schema.String>;
10
+ readonly web: Schema.optional<Schema.Struct<{
11
+ readonly server: Schema.optional<Schema.String>;
12
+ readonly static: Schema.optional<Schema.String>;
13
+ readonly build: Schema.optional<Schema.String>;
14
+ readonly dev: Schema.optional<Schema.Struct<{
15
+ readonly command: Schema.String;
16
+ readonly port: Schema.optional<Schema.Int>;
17
+ }>>;
18
+ readonly spa: Schema.withDecodingDefault<Schema.Boolean, never>;
19
+ readonly serverRoutes: Schema.withDecodingDefault<Schema.$Array<Schema.String>, never>;
20
+ readonly timeoutSeconds: Schema.withDecodingDefault<Schema.Int, never>;
21
+ readonly concurrency: Schema.withDecodingDefault<Schema.Int, never>;
22
+ }>>;
23
+ readonly worker: Schema.optional<Schema.Struct<{
24
+ readonly entry: Schema.withDecodingDefault<Schema.String, never>;
25
+ readonly timeoutSeconds: Schema.withDecodingDefault<Schema.Int, never>;
26
+ readonly memoryMb: Schema.withDecodingDefault<Schema.Int, never>;
27
+ }>>;
28
+ readonly auth: Schema.withDecodingDefault<Schema.Union<readonly [Schema.Boolean, Schema.Struct<{
29
+ readonly required: Schema.withDecodingDefault<Schema.Boolean, never>;
30
+ }>]>, never>;
31
+ readonly db: Schema.withDecodingDefault<Schema.Boolean, never>;
32
+ readonly queues: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Struct<{
33
+ readonly batchSize: Schema.withDecodingDefault<Schema.Int, never>;
34
+ readonly visibilityTimeoutSeconds: Schema.optional<Schema.Int>;
35
+ readonly maxReceiveCount: Schema.withDecodingDefault<Schema.Int, never>;
36
+ readonly concurrency: Schema.optional<Schema.Int>;
37
+ }>>, never>;
38
+ readonly events: Schema.withDecodingDefault<Schema.Union<readonly [Schema.$Array<Schema.String>, Schema.$Record<Schema.String, Schema.Struct<{}>>]>, never>;
39
+ readonly crons: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Struct<{
40
+ readonly schedule: Schema.String;
41
+ readonly timezone: Schema.optional<Schema.String>;
42
+ }>]>>, never>;
43
+ readonly storage: Schema.withDecodingDefault<Schema.$Array<Schema.String>, never>;
44
+ readonly secrets: Schema.withDecodingDefault<Schema.$Array<Schema.String>, never>;
45
+ readonly env: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.String>, never>;
46
+ }>;
47
+ /** The evaluated config as JSON: what the CLI sends and deployments store. */
48
+ export type ManifestInput = typeof ManifestSchema.Encoded;
49
+ export type Manifest = typeof ManifestSchema.Type;
50
+ /** Type-only marker for a queue's message body or an event's detail. Never set at runtime. */
51
+ declare const payloadType: unique symbol;
52
+ type Payload<T> = {
53
+ readonly [payloadType]?: T;
54
+ };
55
+ /** The message or detail type declared with `queue<T>()` / `event<T>()`; `unknown` if none. */
56
+ export type PayloadOf<D> = D extends Payload<infer T> ? (unknown extends T ? unknown : T) : unknown;
57
+ export interface WebConfig {
58
+ /** Entry module whose default export is `toFetchHandler(...)` from `@ericminassian/platform`. */
59
+ server?: string;
60
+ /** Directory of built static assets, served from the edge. */
61
+ static?: string;
62
+ /** Shell command that builds `static` (run by `plat build`). */
63
+ build?: string;
64
+ /**
65
+ * Dev server for the frontend, proxied by `plat dev` (e.g. Vite). The command
66
+ * listens on the port `plat dev` passes in `PLATFORM_DEV_WEB_PORT` (and `PORT`):
67
+ * `port` when it is free, otherwise any free port.
68
+ */
69
+ dev?: {
70
+ command: string;
71
+ port?: number;
72
+ };
73
+ /** Serve `index.html` for unknown non-file paths (client-side routing). Default `true`. */
74
+ spa?: boolean;
75
+ /** When both `server` and `static` exist, path prefixes handled by the server. Default `['/api/']`. */
76
+ serverRoutes?: readonly string[];
77
+ /** 3-900. Default 30. */
78
+ timeoutSeconds?: number;
79
+ /** Max concurrent requests per Web Function environment, 1-128. Default 64. */
80
+ concurrency?: number;
81
+ }
82
+ export interface WorkerConfig {
83
+ /** Module whose default export is `defineWorker(...)`. Default `src/worker.ts`. */
84
+ entry?: string;
85
+ /** 1-900. Default 60. */
86
+ timeoutSeconds?: number;
87
+ /** 128-10240. Default 512. */
88
+ memoryMb?: number;
89
+ }
90
+ /** Declare one with `queue<Body>({ ... })` to type what is sent and received. */
91
+ export interface QueueConfig<Body = unknown> extends Payload<Body> {
92
+ /** Messages per worker invocation, 1-10. Default 10. */
93
+ batchSize?: number;
94
+ /** Defaults to 6x the worker timeout, as AWS recommends for Lambda consumers. */
95
+ visibilityTimeoutSeconds?: number;
96
+ /** Deliveries before a message moves to the dead-letter queue, 1-1000. Default 5. */
97
+ maxReceiveCount?: number;
98
+ /** Max concurrent worker invocations draining this queue, 2-1000. */
99
+ concurrency?: number;
100
+ }
101
+ /** Declare one with `event<Detail>()` to type what is published and handled. */
102
+ export type EventConfig<Detail = unknown> = Payload<Detail>;
103
+ /** 5-field cron in UTC (`0 3 * * *`) or `rate(5 minutes)`. */
104
+ export type CronConfig = string | {
105
+ schedule: string;
106
+ timezone?: string;
107
+ };
108
+ export interface AppConfig {
109
+ /** 3-30 chars of a-z, 0-9 and single hyphens; also the app's host name. */
71
110
  name: string;
72
111
  description?: string;
73
- web?: z.output<typeof WebSchema>;
74
- /** Present when any queue, event subscription or cron exists. */
75
- worker?: z.output<typeof WorkerSchema>;
76
- auth: {
77
- enabled: boolean;
78
- required: boolean;
112
+ web?: WebConfig;
113
+ /** Present automatically when any queue, event or cron exists. */
114
+ worker?: WorkerConfig;
115
+ /** Sign-in with the shared user pool. `{ required: true }` guards every non-platform route. */
116
+ auth?: boolean | {
117
+ required?: boolean;
118
+ };
119
+ /** One document database per stage; collections are declared in code. */
120
+ db?: boolean;
121
+ /** Keys are 1-20 chars of a-z, 0-9 and hyphens. Each needs a handler in the worker. */
122
+ queues?: {
123
+ readonly [name: string]: QueueConfig;
124
+ };
125
+ /** Event types the worker subscribes to, e.g. `order.created`. Each needs a handler in the worker. */
126
+ events?: readonly string[] | {
127
+ readonly [type: string]: EventConfig;
128
+ };
129
+ /** Scheduled jobs. Each needs a handler in the worker. */
130
+ crons?: {
131
+ readonly [name: string]: CronConfig;
132
+ };
133
+ /** Named file stores. */
134
+ storage?: readonly string[];
135
+ /** Secret names like `STRIPE_KEY`; values are set with `plat secrets set`. */
136
+ secrets?: readonly string[];
137
+ /** Plain, non-secret configuration exposed as environment variables. */
138
+ env?: {
139
+ readonly [name: string]: string;
79
140
  };
80
- db: boolean;
81
- queues: Record<string, z.output<typeof QueueSchema> & {
82
- visibilityTimeoutSeconds: number;
83
- }>;
84
- events: string[];
85
- crons: Record<string, {
86
- schedule: string;
87
- timezone?: string;
88
- }>;
89
- storage: string[];
90
- secrets: string[];
91
- env: Record<string, string>;
92
141
  }
142
+ /**
143
+ * Maps every key `T` has but `Shape` doesn't to `never`, recursively, so a
144
+ * misspelled field is a type error. `defineApp` needs this because a generic
145
+ * parameter (which keeps the literal names) skips excess-property checks.
146
+ */
147
+ type Exact<T, Shape> = Shape extends readonly (infer S)[] ? T extends readonly (infer E)[] ? readonly Exact<E, S>[] : Shape : Shape extends object ? T extends object ? {
148
+ [K in keyof T]: K extends keyof Shape ? Exact<T[K], Shape[K]> : never;
149
+ } : Shape : Shape;
150
+ /**
151
+ * The default export of `plat.config.ts`. Returns the config unchanged with
152
+ * its literal names, which `Register` hands to the SDK so queue, event, cron,
153
+ * store and secret names (and payload types) are checked in app code.
154
+ */
155
+ export declare function defineApp<const T extends AppConfig>(config: T & Exact<T, AppConfig>): T;
156
+ /** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ batchSize: 5 }) }`. */
157
+ export declare function queue<Body>(options?: QueueConfig): QueueConfig<Body>;
158
+ /** An event subscription whose detail is `Detail`: `events: { 'todo.created': event<TodoCreated>() }`. */
159
+ export declare function event<Detail>(): EventConfig<Detail>;
160
+ /**
161
+ * Manifest with defaults applied and derived fields normalized: what
162
+ * deployments store. Decoding fills defaults for fields added since a stored
163
+ * manifest was written, so earlier deployments keep decoding.
164
+ */
165
+ export declare const ResolvedManifest: Schema.Struct<{
166
+ readonly name: Schema.String;
167
+ readonly description: Schema.optional<Schema.String>;
168
+ readonly web: Schema.optional<Schema.Struct<{
169
+ readonly server: Schema.optional<Schema.String>;
170
+ readonly static: Schema.optional<Schema.String>;
171
+ readonly build: Schema.optional<Schema.String>;
172
+ readonly dev: Schema.optional<Schema.Struct<{
173
+ readonly command: Schema.String;
174
+ readonly port: Schema.optional<Schema.Int>;
175
+ }>>;
176
+ readonly spa: Schema.withDecodingDefault<Schema.Boolean, never>;
177
+ readonly serverRoutes: Schema.withDecodingDefault<Schema.$Array<Schema.String>, never>;
178
+ readonly timeoutSeconds: Schema.withDecodingDefault<Schema.Int, never>;
179
+ readonly concurrency: Schema.withDecodingDefault<Schema.Int, never>;
180
+ }>>;
181
+ /** Present when any queue, event subscription or cron exists. */
182
+ readonly worker: Schema.optional<Schema.Struct<{
183
+ readonly entry: Schema.withDecodingDefault<Schema.String, never>;
184
+ readonly timeoutSeconds: Schema.withDecodingDefault<Schema.Int, never>;
185
+ readonly memoryMb: Schema.withDecodingDefault<Schema.Int, never>;
186
+ }>>;
187
+ readonly auth: Schema.Struct<{
188
+ readonly enabled: Schema.Boolean;
189
+ readonly required: Schema.Boolean;
190
+ }>;
191
+ readonly db: Schema.Boolean;
192
+ readonly queues: Schema.$Record<Schema.String, Schema.Struct<{
193
+ readonly batchSize: Schema.withDecodingDefault<Schema.Int, never>;
194
+ readonly maxReceiveCount: Schema.withDecodingDefault<Schema.Int, never>;
195
+ readonly concurrency: Schema.optional<Schema.Int>;
196
+ readonly visibilityTimeoutSeconds: Schema.Finite;
197
+ }>>;
198
+ readonly events: Schema.$Array<Schema.String>;
199
+ readonly crons: Schema.$Record<Schema.String, Schema.Struct<{
200
+ readonly schedule: Schema.String;
201
+ readonly timezone: Schema.optional<Schema.String>;
202
+ }>>;
203
+ readonly storage: Schema.$Array<Schema.String>;
204
+ readonly secrets: Schema.$Array<Schema.String>;
205
+ readonly env: Schema.$Record<Schema.String, Schema.String>;
206
+ }>;
207
+ export type ResolvedManifest = typeof ResolvedManifest.Type;
93
208
  export declare class ManifestError extends Error {
94
209
  readonly issues: string[];
95
210
  constructor(issues: string[]);
96
211
  }
97
212
  export declare function parseManifest(input: unknown): ResolvedManifest;
98
213
  export declare function resolveManifest(m: Manifest): ResolvedManifest;
99
- /** JSON Schema URL apps reference for editor completion. */
100
- export declare const MANIFEST_SCHEMA_URL = "https://raw.githubusercontent.com/eric-minassian/platform/main/packages/core/platform.schema.json";
101
214
  export {};
package/dist/manifest.js CHANGED
@@ -1,114 +1,152 @@
1
- import { z } from 'zod';
1
+ import { Effect, Schema } from 'effect';
2
2
  import { validateCron } from './cron.js';
3
3
  import { APP_NAME_PATTERN, ENV_NAME_PATTERN, EVENT_TYPE_PATTERN, RESOURCE_KEY_PATTERN } from './naming.js';
4
4
  /**
5
- * `platform.json`: everything an app needs, in cloud-neutral terms. This is the
6
- * whole contract between an app repo and the platform; apps contain no
7
- * infrastructure code. Keep this schema small and stable.
5
+ * The app's config file, at the app root. `plat` evaluates it and sends the
6
+ * result to the platform as JSON; the control plane never runs app code.
8
7
  */
9
- const resourceKey = z.string().regex(RESOURCE_KEY_PATTERN, 'must be 1-20 chars of a-z, 0-9, hyphens');
10
- const WebSchema = z
11
- .object({
12
- /** Entry module whose default export is a fetch handler (`{ fetch }` or a Hono app). */
13
- server: z.string().optional(),
14
- /** Directory of built static assets (served from the edge). */
15
- static: z.string().optional(),
16
- /** Shell command that builds `static` (run by `plat build`). */
17
- build: z.string().optional(),
18
- /** Dev server for the frontend, proxied by `plat dev` (e.g. Vite). */
19
- dev: z.object({ command: z.string(), port: z.number().int().positive() }).optional(),
20
- /** Serve `index.html` for unknown non-file paths (client-side routing). */
21
- spa: z.boolean().default(true),
22
- /** When both `server` and `static` exist, path prefixes handled by the server. */
23
- serverRoutes: z.array(z.string().startsWith('/')).default(['/api/']),
24
- timeoutSeconds: z.number().int().min(3).max(900).default(30),
25
- /** Max concurrent requests per Web Function environment. */
26
- concurrency: z.number().int().min(1).max(128).default(64),
27
- })
28
- .refine((w) => w.server || w.static, { message: 'web needs a server, a static directory, or both' });
29
- const WorkerSchema = z.object({
30
- entry: z.string().default('src/worker.ts'),
31
- timeoutSeconds: z.number().int().min(1).max(900).default(60),
32
- memoryMb: z.number().int().min(128).max(10240).default(512),
8
+ export const APP_CONFIG_FILE = 'plat.config.ts';
9
+ /**
10
+ * What `plat.config.ts` declares: everything an app needs, in cloud-neutral
11
+ * terms. This is the whole contract between an app repo and the platform;
12
+ * apps contain no infrastructure code. Keep this schema small and stable.
13
+ *
14
+ * `ManifestSchema` validates the evaluated config (CLI and API); `AppConfig`
15
+ * below is the same shape written for authors. `test/manifest-types.test.ts`
16
+ * keeps the two in step.
17
+ */
18
+ const RESOURCE_KEY_MESSAGE = 'must be 1-20 chars of a-z, 0-9, hyphens';
19
+ const resourceKey = Schema.String.check(Schema.isPattern(RESOURCE_KEY_PATTERN, { message: RESOURCE_KEY_MESSAGE }));
20
+ const eventType = Schema.String.check(Schema.isPattern(EVENT_TYPE_PATTERN));
21
+ const envName = Schema.String.check(Schema.isPattern(ENV_NAME_PATTERN));
22
+ /**
23
+ * A record whose keys must match `pattern`. `Schema.Record` drops keys that fail
24
+ * its key schema, which would make a misnamed queue silently disappear, so
25
+ * keys are checked here and reported at their path instead.
26
+ */
27
+ const recordOf = (pattern, value, message = `must match ${pattern}`) => Schema.Record(Schema.String, value).check(Schema.makeFilter((record) => Object.keys(record)
28
+ .filter((key) => !pattern.test(key))
29
+ .map((key) => ({ path: [key], issue: message }))));
30
+ const intBetween = (minimum, maximum) => Schema.Int.check(Schema.isBetween({ minimum, maximum }));
31
+ /** Absent (or `undefined`) decodes to `value`. */
32
+ const orElse = (value) => (schema) => schema.pipe(Schema.withDecodingDefault(Effect.succeed(value)));
33
+ const WebSchema = Schema.Struct({
34
+ server: Schema.optional(Schema.String),
35
+ static: Schema.optional(Schema.String),
36
+ build: Schema.optional(Schema.String),
37
+ dev: Schema.optional(Schema.Struct({ command: Schema.String, port: Schema.optional(intBetween(1, 65535)) })),
38
+ spa: Schema.Boolean.pipe(orElse(true)),
39
+ serverRoutes: Schema.Array(Schema.String.check(Schema.isStartingWith('/'))).pipe(orElse(['/api/'])),
40
+ timeoutSeconds: intBetween(3, 900).pipe(orElse(30)),
41
+ concurrency: intBetween(1, 128).pipe(orElse(64)),
42
+ }).check(Schema.makeFilter((w) => w.server || w.static ? undefined : 'web needs a server, a static directory, or both'));
43
+ const WorkerSchema = Schema.Struct({
44
+ entry: Schema.String.pipe(orElse('src/worker.ts')),
45
+ timeoutSeconds: intBetween(1, 900).pipe(orElse(60)),
46
+ memoryMb: intBetween(128, 10240).pipe(orElse(512)),
33
47
  });
34
- const QueueSchema = z.object({
35
- batchSize: z.number().int().min(1).max(10).default(10),
36
- /** Defaults to 6x the worker timeout, as AWS recommends for Lambda consumers. */
37
- visibilityTimeoutSeconds: z.number().int().min(0).max(43200).optional(),
38
- maxReceiveCount: z.number().int().min(1).max(1000).default(5),
39
- /** Max concurrent worker invocations draining this queue. */
40
- concurrency: z.number().int().min(2).max(1000).optional(),
48
+ const QueueSchema = Schema.Struct({
49
+ batchSize: intBetween(1, 10).pipe(orElse(10)),
50
+ visibilityTimeoutSeconds: Schema.optional(intBetween(0, 43200)),
51
+ maxReceiveCount: intBetween(1, 1000).pipe(orElse(5)),
52
+ concurrency: Schema.optional(intBetween(2, 1000)),
41
53
  });
42
- const CronSchema = z.union([z.string(), z.object({ schedule: z.string(), timezone: z.string().optional() })]);
43
- const AuthSchema = z.union([
44
- z.boolean(),
45
- z.object({
46
- /** Require a signed-in user for every non-platform route (`/__platform/*` stays open). */
47
- required: z.boolean().default(false),
48
- }),
54
+ const CronSchema = Schema.Union([
55
+ Schema.String,
56
+ Schema.Struct({ schedule: Schema.String, timezone: Schema.optional(Schema.String) }),
57
+ ]).check(Schema.makeFilter((cron) => validateCron(typeof cron === 'string' ? cron : cron.schedule) ?? undefined));
58
+ const AuthSchema = Schema.Union([
59
+ Schema.Boolean,
60
+ Schema.Struct({ required: Schema.Boolean.pipe(orElse(false)) }),
49
61
  ]);
50
- export const ManifestSchema = z
51
- .object({
52
- $schema: z.string().optional(),
53
- name: z
54
- .string()
55
- // Reserved names are enforced when an app is registered (API), not here:
56
- // the control plane itself is the app named `platform`.
57
- .regex(APP_NAME_PATTERN, 'must be 3-30 chars of a-z, 0-9, single hyphens'),
58
- description: z.string().max(200).optional(),
59
- web: WebSchema.optional(),
60
- worker: WorkerSchema.optional(),
61
- auth: AuthSchema.default(false),
62
- /** One document database per stage; collections are declared in code. */
63
- db: z.boolean().default(false),
64
- queues: z.record(resourceKey, QueueSchema).default({}),
65
- /** Event types the worker subscribes to (anything can be published). */
66
- events: z.array(z.string().regex(EVENT_TYPE_PATTERN)).default([]),
67
- crons: z.record(resourceKey, CronSchema).default({}),
68
- /** Named file stores. */
69
- storage: z.array(resourceKey).default([]),
70
- /** Secret names; values are set with `plat secrets set`. */
71
- secrets: z.array(z.string().regex(ENV_NAME_PATTERN)).default([]),
72
- /** Plain, non-secret configuration exposed as environment variables. */
73
- env: z.record(z.string().regex(ENV_NAME_PATTERN), z.string()).default({}),
74
- })
75
- .superRefine((m, ctx) => {
76
- for (const [key, cron] of Object.entries(m.crons)) {
77
- const err = validateCron(typeof cron === 'string' ? cron : cron.schedule);
78
- if (err)
79
- ctx.addIssue({ code: 'custom', path: ['crons', key], message: err });
80
- }
62
+ export const ManifestSchema = Schema.Struct({
63
+ // Reserved names are enforced when an app is registered (API), not here:
64
+ // the control plane itself is the app named `platform`.
65
+ name: Schema.String.check(Schema.isPattern(APP_NAME_PATTERN, { message: 'must be 3-30 chars of a-z, 0-9, single hyphens' })),
66
+ description: Schema.optional(Schema.String.check(Schema.isMaxLength(200))),
67
+ web: Schema.optional(WebSchema),
68
+ worker: Schema.optional(WorkerSchema),
69
+ auth: AuthSchema.pipe(orElse(false)),
70
+ db: Schema.Boolean.pipe(orElse(false)),
71
+ queues: recordOf(RESOURCE_KEY_PATTERN, QueueSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
72
+ // The array form predates typed event payloads; deployments recorded
73
+ // before then still store it.
74
+ events: Schema.Union([Schema.Array(eventType), recordOf(EVENT_TYPE_PATTERN, Schema.Struct({}))]).pipe(orElse([])),
75
+ crons: recordOf(RESOURCE_KEY_PATTERN, CronSchema, RESOURCE_KEY_MESSAGE).pipe(orElse({})),
76
+ storage: Schema.Array(resourceKey).pipe(orElse([])),
77
+ secrets: Schema.Array(envName).pipe(orElse([])),
78
+ env: recordOf(ENV_NAME_PATTERN, Schema.String).pipe(orElse({})),
79
+ });
80
+ /**
81
+ * The default export of `plat.config.ts`. Returns the config unchanged with
82
+ * its literal names, which `Register` hands to the SDK so queue, event, cron,
83
+ * store and secret names (and payload types) are checked in app code.
84
+ */
85
+ export function defineApp(config) {
86
+ return config;
87
+ }
88
+ /** A queue whose messages are `Body`: `queues: { emails: queue<EmailJob>({ batchSize: 5 }) }`. */
89
+ export function queue(options = {}) {
90
+ return options;
91
+ }
92
+ /** An event subscription whose detail is `Detail`: `events: { 'todo.created': event<TodoCreated>() }`. */
93
+ export function event() {
94
+ return {};
95
+ }
96
+ // ---------------------------------------------------------------------------
97
+ /**
98
+ * Manifest with defaults applied and derived fields normalized: what
99
+ * deployments store. Decoding fills defaults for fields added since a stored
100
+ * manifest was written, so earlier deployments keep decoding.
101
+ */
102
+ export const ResolvedManifest = Schema.Struct({
103
+ name: Schema.String,
104
+ description: Schema.optional(Schema.String),
105
+ web: Schema.optional(WebSchema),
106
+ /** Present when any queue, event subscription or cron exists. */
107
+ worker: Schema.optional(WorkerSchema),
108
+ auth: Schema.Struct({ enabled: Schema.Boolean, required: Schema.Boolean }),
109
+ db: Schema.Boolean,
110
+ queues: Schema.Record(Schema.String, Schema.Struct({ ...QueueSchema.fields, visibilityTimeoutSeconds: Schema.Finite })),
111
+ events: Schema.Array(Schema.String),
112
+ crons: Schema.Record(Schema.String, Schema.Struct({ schedule: Schema.String, timezone: Schema.optional(Schema.String) })),
113
+ storage: Schema.Array(Schema.String),
114
+ secrets: Schema.Array(Schema.String),
115
+ env: Schema.Record(Schema.String, Schema.String),
81
116
  });
82
117
  export class ManifestError extends Error {
83
118
  issues;
84
119
  constructor(issues) {
85
- super(`Invalid platform.json:\n - ${issues.join('\n - ')}`);
120
+ super(`Invalid ${APP_CONFIG_FILE}:\n - ${issues.join('\n - ')}`);
86
121
  this.issues = issues;
87
122
  }
88
123
  }
124
+ const validateManifest = Schema.toStandardSchemaV1(ManifestSchema, { parseOptions: { errors: 'all' } })['~standard'].validate;
89
125
  export function parseManifest(input) {
90
- const parsed = ManifestSchema.safeParse(input);
91
- if (!parsed.success) {
92
- throw new ManifestError(parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`));
126
+ const result = validateManifest(input);
127
+ // The schema has no asynchronous checks, so validation is synchronous.
128
+ if (result instanceof Promise)
129
+ throw new Error('manifest validation must be synchronous');
130
+ if (result.issues) {
131
+ throw new ManifestError(result.issues.map((i) => {
132
+ const path = (i.path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
133
+ return `${path || '(root)'}: ${i.message}`;
134
+ }));
93
135
  }
94
- return resolveManifest(parsed.data);
136
+ return resolveManifest(result.value);
95
137
  }
96
138
  export function resolveManifest(m) {
97
- const needsWorker = Object.keys(m.queues).length > 0 || m.events.length > 0 || Object.keys(m.crons).length > 0;
98
- const worker = m.worker ?? (needsWorker ? WorkerSchema.parse({}) : undefined);
139
+ const events = Array.isArray(m.events) ? m.events : Object.keys(m.events);
140
+ const needsWorker = Object.keys(m.queues).length > 0 || events.length > 0 || Object.keys(m.crons).length > 0;
141
+ const worker = m.worker ?? (needsWorker ? Schema.decodeUnknownSync(WorkerSchema)({}) : undefined);
99
142
  const auth = typeof m.auth === 'boolean'
100
143
  ? { enabled: m.auth, required: false }
101
144
  : { enabled: true, required: m.auth.required };
102
- const queues = {};
103
- for (const [key, q] of Object.entries(m.queues)) {
104
- queues[key] = {
105
- ...q,
106
- visibilityTimeoutSeconds: q.visibilityTimeoutSeconds ?? (worker?.timeoutSeconds ?? 60) * 6,
107
- };
108
- }
109
- const crons = {};
110
- for (const [key, c] of Object.entries(m.crons))
111
- crons[key] = typeof c === 'string' ? { schedule: c } : c;
145
+ const queues = Object.fromEntries(Object.entries(m.queues).map(([key, q]) => [
146
+ key,
147
+ { ...q, visibilityTimeoutSeconds: q.visibilityTimeoutSeconds ?? (worker?.timeoutSeconds ?? 60) * 6 },
148
+ ]));
149
+ const crons = Object.fromEntries(Object.entries(m.crons).map(([key, c]) => [key, typeof c === 'string' ? { schedule: c } : c]));
112
150
  return {
113
151
  name: m.name,
114
152
  ...(m.description ? { description: m.description } : {}),
@@ -117,13 +155,11 @@ export function resolveManifest(m) {
117
155
  auth,
118
156
  db: m.db,
119
157
  queues,
120
- events: [...new Set(m.events)],
158
+ events: [...new Set(events)],
121
159
  crons,
122
160
  storage: [...new Set(m.storage)],
123
161
  secrets: [...new Set(m.secrets)],
124
162
  env: m.env,
125
163
  };
126
164
  }
127
- /** JSON Schema URL apps reference for editor completion. */
128
- export const MANIFEST_SCHEMA_URL = 'https://raw.githubusercontent.com/eric-minassian/platform/main/packages/core/platform.schema.json';
129
165
  //# sourceMappingURL=manifest.js.map