@geekmidas/cloud 10.0.0-alpha.98 → 10.0.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 (74) hide show
  1. package/README.md +6 -14
  2. package/dist/index-ByEJy40r.d.cts +56 -0
  3. package/dist/index-ByEJy40r.d.cts.map +1 -0
  4. package/dist/index-DZ0QrJQr.d.mts +56 -0
  5. package/dist/index-DZ0QrJQr.d.mts.map +1 -0
  6. package/dist/index.cjs +3 -3
  7. package/dist/index.d.cts +1 -1
  8. package/dist/index.d.mts +1 -1
  9. package/dist/index.mjs +3 -2
  10. package/dist/utils/index.cjs +5 -106
  11. package/dist/utils/index.d.cts +2 -62
  12. package/dist/utils/index.d.mts +2 -62
  13. package/dist/utils/index.mjs +2 -78
  14. package/dist/utils-BdKG20_m.mjs +83 -0
  15. package/dist/utils-BdKG20_m.mjs.map +1 -0
  16. package/dist/utils-CtMjuIMR.cjs +129 -0
  17. package/dist/utils-CtMjuIMR.cjs.map +1 -0
  18. package/package.json +9 -47
  19. package/src/sst/{aws/Api.ts → Api.ts} +47 -19
  20. package/src/sst/{aws/Cron.ts → Cron.ts} +46 -6
  21. package/src/sst/{aws/Function.ts → Function.ts} +41 -12
  22. package/src/sst/Queue.ts +46 -0
  23. package/src/sst/{aws/Storage.ts → Storage.ts} +3 -3
  24. package/src/sst/Topic.ts +37 -0
  25. package/src/sst/__tests__/LinkedEnvironment.spec.ts +1 -4
  26. package/src/sst/__type-tests__/authorizers.type-test.ts +2 -2
  27. package/src/sst/__type-tests__/manifest.type-test.ts +77 -0
  28. package/src/sst/__type-tests__/messaging.type-test.ts +3 -3
  29. package/src/sst/__type-tests__/storage.type-test.ts +2 -2
  30. package/src/sst/index.ts +7 -67
  31. package/src/sst/naming.ts +16 -37
  32. package/src/sst/tsconfig.json +2 -2
  33. package/dist/utils/index.cjs.map +0 -1
  34. package/dist/utils/index.d.cts.map +0 -1
  35. package/dist/utils/index.d.mts.map +0 -1
  36. package/dist/utils/index.mjs.map +0 -1
  37. package/src/dokploy/Application.ts +0 -306
  38. package/src/dokploy/__tests__/Application.provider.spec.ts +0 -206
  39. package/src/dokploy/__tests__/Application.spec.ts +0 -69
  40. package/src/dokploy/index.ts +0 -18
  41. package/src/sst/__tests__/api.spec.ts +0 -185
  42. package/src/sst/__tests__/backends.spec.ts +0 -249
  43. package/src/sst/__tests__/bootstrap.spec.ts +0 -140
  44. package/src/sst/__tests__/database.spec.ts +0 -119
  45. package/src/sst/__tests__/encryption.spec.ts +0 -90
  46. package/src/sst/__tests__/fromManifest.integration.spec.ts +0 -427
  47. package/src/sst/__tests__/fromManifest.spec.ts +0 -567
  48. package/src/sst/__tests__/function.spec.ts +0 -121
  49. package/src/sst/__tests__/links.spec.ts +0 -209
  50. package/src/sst/__tests__/provides.spec.ts +0 -107
  51. package/src/sst/__tests__/ses.spec.ts +0 -93
  52. package/src/sst/__tests__/surfaces.spec.ts +0 -149
  53. package/src/sst/__type-tests__/overrides.type-test.ts +0 -152
  54. package/src/sst/aws/Cache.ts +0 -259
  55. package/src/sst/aws/Credential.ts +0 -61
  56. package/src/sst/aws/Database.ts +0 -204
  57. package/src/sst/aws/DatabaseBootstrap.ts +0 -312
  58. package/src/sst/aws/DerivedDatabase.ts +0 -117
  59. package/src/sst/aws/Email.ts +0 -181
  60. package/src/sst/aws/Encryption.ts +0 -91
  61. package/src/sst/aws/ExternalApi.ts +0 -58
  62. package/src/sst/aws/FileServer.ts +0 -82
  63. package/src/sst/aws/ObjectStorage.ts +0 -76
  64. package/src/sst/aws/Queue.ts +0 -149
  65. package/src/sst/aws/RestApiSurface.ts +0 -114
  66. package/src/sst/aws/Secret.ts +0 -76
  67. package/src/sst/aws/StaticSite.ts +0 -92
  68. package/src/sst/aws/Topic.ts +0 -68
  69. package/src/sst/aws/bootstrap/handler.ts +0 -119
  70. package/src/sst/aws/ses.ts +0 -132
  71. package/src/sst/errors.ts +0 -65
  72. package/src/sst/fromManifest.ts +0 -1116
  73. package/src/sst/overrides.ts +0 -133
  74. package/src/sst/upstash.d.ts +0 -38
@@ -1,1116 +0,0 @@
1
- /**
2
- * Manifest → SST.
3
- *
4
- * Split deliberately into decisions and instantiation. The decisions —
5
- * which component provisions a kind, whether what it supplies matches what the
6
- * app declared — are pure functions, so they can be asserted as data. Only
7
- * {@link fromManifest} touches Pulumi, and it is thin enough that little is
8
- * hidden behind a runtime nothing can unit-test.
9
- *
10
- * Built for AWS. Extending to another provider means adding entries to
11
- * {@link PROVISIONERS}, not restructuring: the manifest names a *kind*, never a
12
- * cloud.
13
- */
14
-
15
- import { ownerRole, readerRole } from '@geekmidas/db/pg/roles';
16
- import { resolveEnvKeys } from '@geekmidas/envkit/sst';
17
- import type {
18
- ConstructManifest,
19
- Declaration,
20
- DeclarationKind,
21
- Dependency,
22
- SiteDeclaration,
23
- } from '@geekmidas/manifest';
24
- import {
25
- cacheTable,
26
- cookieDomain,
27
- DEFAULT_POSTGRES_VERSION,
28
- dependentsOf,
29
- mobileOrigins,
30
- PUBLIC,
31
- PUBLIC_PREFIX,
32
- providedKeyFor,
33
- provisionOrder,
34
- schemeBase,
35
- } from '@geekmidas/manifest';
36
- import {
37
- Cache,
38
- CacheIsAmbiguous,
39
- CacheNeedsDatabase,
40
- type CacheProps,
41
- withCacheTable,
42
- } from './aws/Cache';
43
- import { Credential } from './aws/Credential';
44
- import { Cron, type CronSchedule } from './aws/Cron';
45
- import { Database, DatabaseNeedsVpc, type DatabaseProps } from './aws/Database';
46
- import { DatabaseBootstrap } from './aws/DatabaseBootstrap';
47
- import { DatabaseReader, DatabaseSchema } from './aws/DerivedDatabase';
48
- import { Email, EmailNeedsSender } from './aws/Email';
49
- import { Encryption, type EncryptionProps } from './aws/Encryption';
50
- import { ExternalApi, type ExternalApiProps } from './aws/ExternalApi';
51
- import { FileServer } from './aws/FileServer';
52
- import { Function } from './aws/Function';
53
- import { ObjectStorage } from './aws/ObjectStorage';
54
- import { Queue } from './aws/Queue';
55
- import { RestApiSurface } from './aws/RestApiSurface';
56
- import { Secret } from './aws/Secret';
57
- import { StaticSite } from './aws/StaticSite';
58
- import { Topic } from './aws/Topic';
59
- import {
60
- ProvidesMismatch,
61
- UnknownDeclarationKind,
62
- UnresolvedDependency,
63
- } from './errors';
64
- import type { GkmLinkable } from './Linkable';
65
- import type { ManifestBackends, ManifestOverrides } from './overrides';
66
- import type { StackType } from './Stack';
67
-
68
- /**
69
- * A provisioned construct — the component, which *is* the linkable.
70
- *
71
- * `provides()` returns its values keyed by role. They reach the running code by
72
- * being spread into the link's properties, which SST injects and envkit's
73
- * resolvers flatten into env; keeping them behind a method is what lets the
74
- * contract be asserted at synth without a deploy.
75
- */
76
- export interface Provisioned extends GkmLinkable {
77
- provides(): Record<string, $util.Input<string>>;
78
- }
79
-
80
- /** Everything the manifest declared, keyed by id — the shape edges resolve against. */
81
- export type ProvisionedManifest = Record<string, Provisioned>;
82
-
83
- /**
84
- * What a provisioner can see beyond its own declaration.
85
- *
86
- * Two kinds need it, and both are consequences of decisions the design took
87
- * deliberately. A bucket has to know whether anything serves it, because the
88
- * file server is a construct of its own rather than a flag — the cost that
89
- * decision names, paid here by looking rather than by reading a flag. And a
90
- * derived node needs the component its parent became, since it provisions
91
- * nothing and resolves an address off that one.
92
- */
93
- export interface ProvisionContext {
94
- manifest: ConstructManifest;
95
- /** Everything already provisioned. Parents are present; siblings may not be. */
96
- provisioned: ProvisionedManifest;
97
- /**
98
- * The role bootstrap for each cluster, keyed by the cluster's id.
99
- *
100
- * Populated as tenants are provisioned and run once at the end: Pulumi can
101
- * generate a password and store it but cannot run `CREATE ROLE`, so the DDL
102
- * is a function invoked after everything it operates on exists.
103
- */
104
- bootstraps: Map<string, DatabaseBootstrap>;
105
- /**
106
- * Where a declared cache lives, and who delivers mail.
107
- *
108
- * Deployment choices rather than declarations, for the same reason the
109
- * event broker is: the same application code caches into any of them and
110
- * sends through any of them. They reach the provisioner here because it is
111
- * the only place that knows both the choice and the manifest.
112
- */
113
- cache?: 'upstash' | 'elasticache' | 'db';
114
- email?: 'resend' | 'ses' | 'smtp';
115
- /**
116
- * One deferred caller list per surface, resolved once everything exists.
117
- *
118
- * A surface's origins come from its *inbound* edges, and one of those is
119
- * usually a site whose own build needs this surface's address — so the values
120
- * are circular even though the resources are not. Deferring the value is
121
- * what breaks it; deferring the resource would deadlock.
122
- */
123
- callers?: Map<string, Deferred>;
124
- }
125
-
126
- /** A promise and the handle to settle it. */
127
- interface Deferred {
128
- promise: Promise<{ trustedOrigins: string; cookieDomain?: string }>;
129
- resolve: (
130
- value:
131
- | { trustedOrigins: string; cookieDomain?: string }
132
- | Promise<{ trustedOrigins: string; cookieDomain?: string }>,
133
- ) => void;
134
- }
135
-
136
- type Provisioner = (
137
- stack: StackType,
138
- declaration: Declaration,
139
- props: Record<string, unknown>,
140
- context: ProvisionContext,
141
- ) => Provisioned;
142
-
143
- /**
144
- * Which component provisions which kind.
145
- *
146
- * The extension point: a second provider adds entries here, and nothing above
147
- * this line changes.
148
- */
149
- const PROVISIONERS: Partial<Record<DeclarationKind, Provisioner>> = {
150
- objects: (stack, d, props, context) =>
151
- new ObjectStorage(stack, d.id, {
152
- // Neutral options the app declared, mapped to this provider's words.
153
- ...(d.kind === 'objects' && d.versioned ? { versioning: true } : {}),
154
- // A served bucket has to let CloudFront read it, and only the manifest
155
- // knows whether anything serves it — the cost of making the file
156
- // server its own construct, paid here rather than by a flag on the
157
- // bucket that every consumer would then branch on.
158
- ...(isServed(d.id, context.manifest) ? { access: 'cloudfront' } : {}),
159
- // Overrides win: they are the more specific statement, and the escape
160
- // hatch is worthless if it cannot override the general case.
161
- ...props,
162
- }),
163
-
164
- 'file-server': (stack, d, props, context) => {
165
- if (d.kind !== 'file-server') throw new UnknownDeclarationKind(d.kind, []);
166
-
167
- const origin = context.provisioned[d.of];
168
- if (!origin) {
169
- throw new UnresolvedDependency(d.of, Object.keys(context.provisioned));
170
- }
171
-
172
- return new FileServer(stack, d.id, {
173
- origin: origin as unknown as sst.aws.Bucket,
174
- ...props,
175
- });
176
- },
177
-
178
- site: (stack, d, props, context) => {
179
- if (d.kind !== 'site') throw new UnknownDeclarationKind(d.kind, []);
180
-
181
- return new StaticSite(stack, d.id, {
182
- path: d.app.path,
183
- variant: d.variant,
184
- environment: siteEnvironment(d, context),
185
- ...props,
186
- });
187
- },
188
-
189
- queue: (stack, d, props) =>
190
- new Queue(stack, d.id, {
191
- // FIFO is a neutral option — the app legitimately has an opinion about
192
- // ordering — and `fifo` is also what SST calls it.
193
- ...(d.kind === 'queue' && d.fifo ? { fifo: true } : {}),
194
- ...props,
195
- }),
196
-
197
- // A topic declares nothing beyond its id: which events it carries is the
198
- // producer's and subscribers' business, and SNS has no per-event
199
- // configuration to map it onto.
200
- topic: (stack, d, props) => new Topic(stack, d.id, props),
201
-
202
- database: (stack, d, props, context) => {
203
- if (d.kind !== 'database') throw new UnknownDeclarationKind(d.kind, []);
204
- // Required rather than defaulted: creating a VPC means creating a NAT
205
- // gateway, which is a monthly cost in an account whose networking may
206
- // already be someone else's decision.
207
- if (!('vpc' in props)) throw new DatabaseNeedsVpc(d.id);
208
-
209
- const cluster = new Database(stack, d.id, {
210
- ...(d.schema ? { schema: d.schema } : {}),
211
- // The declared major, so the cluster runs what the declaration says
212
- // rather than whatever Aurora defaults to that month. Local ran 18
213
- // while this ran 17.7, and neither was written down anywhere.
214
- version: String(d.version ?? DEFAULT_POSTGRES_VERSION),
215
- // `DatabaseProps`, not `sst.aws.PostgresArgs`: the database needs the
216
- // `Vpc` component itself (its bootstrap function runs in the same VPC
217
- // and needs the security groups too), where RDS would accept bare
218
- // subnet ids. TS 7 checks the spread; 6 let the wider type through.
219
- ...(props as unknown as Omit<DatabaseProps, 'schema'>),
220
- });
221
-
222
- // A database needs its own roles, not just its tenants'. Registering only
223
- // tenants left the *database* connecting as the cluster master and its
224
- // reader falling back to the same — so the split the local target
225
- // enforces was absent deployed, which is the worst shape a gap can take:
226
- // a developer sees it working and production silently does not have it.
227
- if (d.schema) {
228
- const bootstrap = bootstrapFor(cluster, d.id, context);
229
- const runtime = roleNameFor(d, context);
230
-
231
- const credentials = bootstrap?.add({
232
- id: d.id,
233
- schema: d.schema,
234
- runtime,
235
- owner: ownerRole(runtime),
236
- ownsDatabase: true,
237
- ...(hasReader(d.id, context) ? { reader: readerRole(runtime) } : {}),
238
- });
239
-
240
- // Registering the role was half of it: its handlers have to connect as
241
- // it too, or the DDL creates a role nothing uses and every handler
242
- // linked to the database still holds the master.
243
- if (credentials) {
244
- cluster.connectAs({ user: runtime, password: credentials.runtime });
245
- }
246
- }
247
-
248
- return cluster;
249
- },
250
-
251
- 'database-reader': (_stack, d, _props, context) =>
252
- derived(d, context, (id, parent) => {
253
- // A reader reads through the *parent's* read-only role: read-only is
254
- // enforced by the grants, which is what makes falling back to the
255
- // writer's endpoint safe where a cluster has no replica.
256
- const source = parentOf(d, context);
257
- const roles = context.bootstraps.get(rootId(source, context));
258
- const runtime = roleNameFor(source, context);
259
- const reader = roles?.readerFor(runtime);
260
-
261
- return new DatabaseReader(id, parent, reader);
262
- }),
263
-
264
- 'database-schema': (_stack, d, _props, context) => {
265
- if (d.kind !== 'database-schema')
266
- throw new UnknownDeclarationKind(d.kind, []);
267
-
268
- return derived(d, context, (id, parent) => {
269
- const bootstrap = bootstrapFor(parent, rootId(d, context), context);
270
- const runtime = roleNameFor(d, context);
271
-
272
- // Registering the tenant is what creates its passwords and its secret;
273
- // the DDL that uses them runs at the end, from one function.
274
- const credentials = bootstrap?.add({
275
- id,
276
- schema: d.schema,
277
- runtime,
278
- owner: ownerRole(runtime),
279
- ...(hasReader(d.id, context) ? { reader: readerRole(runtime) } : {}),
280
- });
281
-
282
- return new DatabaseSchema(
283
- id,
284
- parent,
285
- d.schema,
286
- credentials
287
- ? { user: runtime, password: credentials.runtime }
288
- : undefined,
289
- );
290
- });
291
- },
292
-
293
- cache: (stack, d, props, context) => {
294
- const backend = context.cache ?? 'upstash';
295
-
296
- // A cache that named a database is in *that* one, whatever the backend
297
- // config says — the declaration is the stronger statement. Without one,
298
- // the `db` backend resolves to the declared database, which is an answer
299
- // only while there is one of them: picking the first of two would put a
300
- // cache in a database nobody chose, and that surfaces as missing entries
301
- // long after the deploy reported success.
302
- const databases =
303
- d.kind === 'cache' && !d.of && backend === 'db'
304
- ? Object.entries(context.manifest)
305
- .filter(([, declaration]) => declaration.kind === 'database')
306
- .map(([id]) => id)
307
- : [];
308
-
309
- if (databases.length > 1) throw new CacheIsAmbiguous(d.id, databases);
310
-
311
- const parentId = d.kind === 'cache' && d.of ? d.of : databases[0];
312
-
313
- if (parentId) {
314
- const parent = context.provisioned[parentId];
315
- if (!parent) throw new CacheNeedsDatabase(d.id);
316
-
317
- // Same address, same role, one more table — which is what makes this
318
- // backend cost nothing to run. The table travels *in* the URL, because
319
- // two caches in one database resolve the same connection string and a
320
- // client built from the URL alone could not tell them apart.
321
- const table =
322
- (d.kind === 'cache' && d.table) || cacheTable(d.id as string);
323
-
324
- return new Cache(stack, d.id, {
325
- url: $util
326
- .output(parent.provides().url!)
327
- .apply((url) => withCacheTable(url, table)),
328
- });
329
- }
330
-
331
- const supplied = props as {
332
- url?: $util.Input<string>;
333
- vpc?: CacheProps['vpc'];
334
- region?: string;
335
- };
336
-
337
- // Both remaining backends create something, and both take a URL instead
338
- // for a cache that already exists.
339
- return new Cache(stack, d.id, {
340
- backend,
341
- ...(supplied.url ? { url: supplied.url } : {}),
342
- ...(supplied.vpc ? { vpc: supplied.vpc } : {}),
343
- ...(supplied.region ? { region: supplied.region } : {}),
344
- });
345
- },
346
-
347
- email: (stack, d, props, context) => {
348
- const backend = context.email ?? 'ses';
349
- const supplied = props as {
350
- url?: $util.Input<string>;
351
- region?: $util.Input<string>;
352
- from?: $util.Input<string>;
353
- };
354
-
355
- // Not defaultable: every provider rejects an unverified sender, so a
356
- // guess deploys cleanly and fails at the first send.
357
- if (!supplied.from) throw new EmailNeedsSender(d.id);
358
-
359
- return new Email(stack, d.id, {
360
- backend,
361
- from: supplied.from,
362
- ...(supplied.url ? { url: supplied.url } : {}),
363
- // SES derives its own credential and needs to know which region's
364
- // endpoint to derive it for; the others were handed a URL already.
365
- region: supplied.region ?? $app.providers?.aws?.region ?? 'us-east-1',
366
- });
367
- },
368
-
369
- /**
370
- * The surface, without its routes yet.
371
- *
372
- * Its address is what a site inlines as `VITE_API_URL`, what an auth server
373
- * puts on its trusted-origin list, and what the cookie domain derives from —
374
- * so it is provisioned in order, and its endpoints are mounted by
375
- * {@link mountRoutes} once everything they link to exists.
376
- */
377
- 'rest-api': (stack, d, props, context) =>
378
- new RestApiSurface(stack, d.id, {
379
- ...(props as sst.aws.ApiGatewayV2Args),
380
- callers: context.callers?.get(d.id)?.promise,
381
- }),
382
-
383
- secret: (stack, d, props) => new Secret(stack, d.id, props),
384
-
385
- // The same storage as a secret, under a different role — see the component.
386
- credential: (stack, d, props) => new Credential(stack, d.id, props),
387
-
388
- // In the stage's region, as mail is: a key in another region is a key
389
- // every call crosses the world to reach.
390
- encryption: (stack, d, props) =>
391
- new Encryption(stack, d.id, {
392
- ...(props as Partial<EncryptionProps>),
393
- region:
394
- (props as Partial<EncryptionProps>).region ??
395
- $app.providers?.aws?.region ??
396
- 'us-east-1',
397
- }),
398
-
399
- // Nothing to provision: the URL this stage calls, and the credentials kept
400
- // as a secret.
401
- 'external-api': (stack, d, props) => {
402
- if (d.kind !== 'external-api') {
403
- throw new UnknownDeclarationKind(d.kind, []);
404
- }
405
-
406
- return new ExternalApi(stack, d.id, {
407
- ...(props as Partial<ExternalApiProps>),
408
- url: d.url,
409
- });
410
- },
411
- };
412
-
413
- /**
414
- * A site's build-time environment: the actual values, under the names its
415
- * bundler inlines.
416
- *
417
- * The names come from the shared derivation, so a site built by `gkm dev` and
418
- * the same site built here inline the same keys. The *values* can only come
419
- * from the provisioned components — a static site has no server half to read a
420
- * link at runtime, so an address it needs has to be an input to its build.
421
- *
422
- * @throws {UnresolvedDependency} when an edge names something not provisioned.
423
- * Silently emitting a smaller environment would produce a frontend that builds
424
- * and then fails against `http:///`, with nothing to point at.
425
- */
426
- export function siteEnvironment(
427
- declaration: SiteDeclaration,
428
- context: ProvisionContext,
429
- ): Record<string, $util.Input<string>> {
430
- const prefix = PUBLIC_PREFIX[declaration.variant];
431
- const environment: Record<string, $util.Input<string>> = {};
432
-
433
- for (const edge of declaration.dependencies) {
434
- const target = context.manifest[edge.target];
435
- if (!target) continue;
436
-
437
- const roles = PUBLIC[target.kind] ?? [];
438
- if (roles.length === 0) continue;
439
-
440
- const component = context.provisioned[edge.target];
441
- if (!component) {
442
- throw new UnresolvedDependency(
443
- edge.target,
444
- Object.keys(context.provisioned),
445
- );
446
- }
447
-
448
- const provided = component.provides();
449
- for (const role of roles) {
450
- const value = provided[role as string];
451
- if (value === undefined) continue;
452
-
453
- environment[
454
- `${prefix}${providedKeyFor(edge.target, target.kind, role as string)}`
455
- ] = value;
456
- }
457
- }
458
-
459
- return environment;
460
- }
461
-
462
- /**
463
- * Resolve a derived database node against the cluster its parent became.
464
- *
465
- * A reader and a schema tenant provision nothing, so the whole of their
466
- * provisioning is finding the parent — which `provisionOrder` guarantees is
467
- * already there, and `assertDerivations` guarantees exists at all.
468
- *
469
- * @throws {UnresolvedDependency} if neither guarantee held, which would mean the
470
- * manifest reached here without its own validation having run.
471
- */
472
- function derived(
473
- declaration: Declaration,
474
- context: ProvisionContext,
475
- build: (id: string, parent: Database) => Provisioned,
476
- ): Provisioned {
477
- if (!('of' in declaration)) {
478
- throw new UnknownDeclarationKind(declaration.kind, []);
479
- }
480
-
481
- const parent = context.provisioned[declaration.of];
482
- if (!parent) {
483
- throw new UnresolvedDependency(
484
- declaration.of,
485
- Object.keys(context.provisioned),
486
- );
487
- }
488
-
489
- // A tenant may derive from another tenant, and what both ultimately need is
490
- // the cluster underneath. `DerivedDatabase` holds its parent, so walking up
491
- // is following the same chain `provisionOrder` walked to get here.
492
- return build(declaration.id, rootCluster(parent));
493
- }
494
-
495
- /** The declaration a derived node hangs off. */
496
- function parentOf(
497
- declaration: Declaration,
498
- context: ProvisionContext,
499
- ): Declaration {
500
- if (!('of' in declaration)) return declaration;
501
-
502
- return context.manifest[declaration.of] ?? declaration;
503
- }
504
-
505
- /**
506
- * The id of the cluster at the bottom of a chain of derived nodes.
507
- *
508
- * A tenant may derive from another tenant, and what both ultimately live in is
509
- * one database — so this follows `of` to the end rather than reading the
510
- * immediate parent.
511
- */
512
- function rootId(declaration: Declaration, context: ProvisionContext): string {
513
- let current = declaration;
514
-
515
- while ('of' in current) {
516
- const parent = context.manifest[current.of];
517
- if (!parent) break;
518
- current = parent;
519
- }
520
-
521
- return current.id;
522
- }
523
-
524
- /**
525
- * The runtime role a node connects as: its own id, lowercased.
526
- *
527
- * The same rule the local target uses, so a role a developer sees in `\du` is
528
- * the role that exists in production. Roles are cluster-scoped, so two stages
529
- * sharing a cluster would collide — which is why a deployed stage gets its own.
530
- */
531
- function roleNameFor(
532
- declaration: Declaration,
533
- _context: ProvisionContext,
534
- ): string {
535
- return declaration.id.toLowerCase();
536
- }
537
-
538
- /** Whether anything in the manifest reads through this node. */
539
- function hasReader(id: string, context: ProvisionContext): boolean {
540
- return Object.values(context.manifest).some(
541
- (declaration) =>
542
- declaration.kind === 'database-reader' && declaration.of === id,
543
- );
544
- }
545
-
546
- /**
547
- * The bootstrap for a cluster, created on first use.
548
- *
549
- * One per cluster rather than one per tenant: the DDL for every tenant runs on
550
- * the same connection, as the same master, so a function each would be the same
551
- * work done N times with N cold starts.
552
- */
553
- function bootstrapFor(
554
- cluster: Database,
555
- clusterId: string,
556
- context: ProvisionContext,
557
- ): DatabaseBootstrap | undefined {
558
- // `roles: false` is the documented downgrade: no roles, and both URLs fall
559
- // back to the master. Nothing to bootstrap.
560
- const declaration = context.manifest[clusterId];
561
- if (declaration && 'roles' in declaration && declaration.roles === false) {
562
- return undefined;
563
- }
564
-
565
- const existing = context.bootstraps.get(clusterId);
566
- if (existing) return existing;
567
-
568
- const created = new DatabaseBootstrap(clusterId, cluster);
569
- context.bootstraps.set(clusterId, created);
570
-
571
- return created;
572
- }
573
-
574
- /** The `Database` at the bottom of a chain of derived nodes. */
575
- function rootCluster(component: Provisioned): Database {
576
- const parent = (component as { parent?: Provisioned }).parent;
577
-
578
- return parent ? rootCluster(parent) : (component as unknown as Database);
579
- }
580
-
581
- /**
582
- * Every route and exactly what it depends on, as lines to print.
583
- *
584
- * The design's central claim is that a function is linked to the constructs it
585
- * declared and nothing else — least privilege falling out of the graph rather
586
- * than out of discipline. That is easy to assert in a test and invisible during
587
- * a deploy, which is the moment somebody would want to check it. So it is
588
- * printed: one line per route, naming what it can reach.
589
- *
590
- * A surface with no routes says so rather than printing nothing, because "no
591
- * routes" and "this printed nothing" look identical otherwise.
592
- *
593
- * Pure, so what gets printed can be asserted without a deploy.
594
- */
595
- export function describeRoutes(manifest: ConstructManifest): string[] {
596
- const lines: string[] = [];
597
-
598
- for (const [id, declaration] of Object.entries(manifest)) {
599
- if (declaration.kind !== 'rest-api') continue;
600
-
601
- lines.push(`${id}:`);
602
-
603
- if (declaration.endpoints.length === 0) {
604
- // Empty is now genuinely empty: the build folds discovered routes into
605
- // the surface that serves them, so a surface with none has none.
606
- lines.push(' (no routes)');
607
- }
608
-
609
- for (const endpoint of declaration.endpoints) {
610
- const reaches = endpoint.dependencies
611
- .map((edge) => `${edge.target} (${edge.kind})`)
612
- .join(', ');
613
-
614
- lines.push(
615
- ` ${endpoint.method} ${endpoint.path} → ${reaches || 'nothing'}`,
616
- );
617
- }
618
-
619
- // A caller relationship, printed apart from the routes because it grants
620
- // nothing — see `RestApiDeclaration.calls`.
621
- if (declaration.calls?.length) {
622
- lines.push(
623
- ` calls ${declaration.calls.map((edge) => edge.target).join(', ')} (origin only; grants nothing)`,
624
- );
625
- }
626
- }
627
-
628
- return lines;
629
- }
630
-
631
- /** A promise with its settle function, for a value that arrives later. */
632
- function defer(): Deferred {
633
- let resolve!: Deferred['resolve'];
634
- const promise = new Promise<{
635
- trustedOrigins: string;
636
- cookieDomain?: string;
637
- }>((settle) => {
638
- resolve = settle;
639
- });
640
-
641
- return { promise, resolve };
642
- }
643
-
644
- /**
645
- * Who may call one surface, and the domain they can share a cookie on.
646
- *
647
- * The same derivation the local target runs, from the same two functions —
648
- * `dependentsOf` reads the graph backwards and `cookieDomain` finds the shared
649
- * parent. What differs is only where an address comes from: a published port
650
- * there, a provisioned component here.
651
- *
652
- * A surface is left off its own origin list: it does not need permission to call
653
- * itself, and adding it would make every surface trust every other one sharing a
654
- * host.
655
- */
656
- async function callersOf(
657
- id: string,
658
- manifest: ConstructManifest,
659
- provisioned: ProvisionedManifest,
660
- /** The app's name — a mobile caller's scheme base when it gives none. */
661
- project: string,
662
- ): Promise<{ trustedOrigins: string; cookieDomain?: string }> {
663
- // Every address here is a Pulumi output, not a string — a CloudFront domain
664
- // and an API Gateway endpoint are both known only after their resource
665
- // exists. An earlier version filtered for `typeof url === 'string'` and so
666
- // filtered out *everything*, which deployed cleanly with an empty
667
- // trusted-origin list: the failure mode this whole derivation exists to
668
- // avoid, arrived at by a type guard that looked defensive.
669
- const urls = await Promise.all(
670
- dependentsOf(manifest, id).map((caller) =>
671
- resolved(provisioned[caller]?.provides().url),
672
- ),
673
- );
674
-
675
- const origins = [
676
- ...new Set(
677
- urls
678
- .map((url) => (url ? originOf(url) : undefined))
679
- .filter((origin): origin is string => Boolean(origin)),
680
- ),
681
- ].sort();
682
-
683
- const own = await resolved(provisioned[id]?.provides().url);
684
- const domain = cookieDomain([...(own ? [own] : []), ...origins]);
685
-
686
- // A mobile caller is reached by its scheme — the bare one, deployed: what
687
- // the store build registers.
688
- const schemes = dependentsOf(manifest, id).flatMap((caller) => {
689
- const app = manifest[caller];
690
- return app?.kind === 'mobile-app'
691
- ? mobileOrigins(schemeBase(project, app.scheme))
692
- : [];
693
- });
694
-
695
- return {
696
- trustedOrigins: [...origins, ...schemes].join(','),
697
- ...(domain ? { cookieDomain: domain } : {}),
698
- };
699
- }
700
-
701
- /**
702
- * A Pulumi input as the string it eventually is.
703
- *
704
- * `$util.output(…).apply()` is how a value is read, and the promise it returns
705
- * is what makes the caller list resolvable at all — the whole reason a surface's
706
- * origins are deferred rather than computed at construction.
707
- */
708
- function resolved(
709
- value: $util.Input<string> | undefined,
710
- ): Promise<string | undefined> {
711
- if (value === undefined) return Promise.resolve(undefined);
712
- if (typeof value === 'string') return Promise.resolve(value);
713
-
714
- return new Promise((settle) => {
715
- $util.output(value).apply((url) => {
716
- settle(url);
717
- return url;
718
- });
719
- });
720
- }
721
-
722
- /** An address reduced to the origin a browser compares against. */
723
- function originOf(address: string): string | undefined {
724
- try {
725
- return new URL(address).origin;
726
- } catch {
727
- return undefined;
728
- }
729
- }
730
-
731
- /**
732
- * Whether anything in the manifest serves this bucket.
733
- *
734
- * The question the design's chosen shape makes you ask. Under a `cdn: true`
735
- * flag you read one declaration; here you find whoever points at it — which is
736
- * a real regression in auditability, answered by making the lookup one function
737
- * that every consumer shares rather than something each caller re-derives.
738
- */
739
- export function isServed(id: string, manifest: ConstructManifest): boolean {
740
- return Object.values(manifest).some(
741
- (declaration) =>
742
- declaration.kind === 'file-server' && declaration.of === id,
743
- );
744
- }
745
-
746
- /**
747
- * Kinds the in-order pass skips.
748
- *
749
- * - `mobile-app` ships through EAS and the stores. It is in the manifest for
750
- * what it makes the surfaces trust, which `callersOf` reads off the graph.
751
- * - `worker` is a process, not a resource: what it runs is provisioned as
752
- * what it is — a queue's consumer by {@link subscribeConsumers}.
753
- * - `cron` and `function` are Lambdas linked to what they depend on, so they
754
- * are provisioned once all of it exists, by {@link provisionCompute}.
755
- * - `telemetry` provisions nothing: where it goes is the stage's
756
- * `deploy.telemetry`, a provider somebody else runs.
757
- */
758
- export const PROVISIONED_ELSEWHERE: ReadonlySet<DeclarationKind> =
759
- new Set<DeclarationKind>([
760
- 'mobile-app',
761
- 'worker',
762
- 'cron',
763
- 'function',
764
- 'telemetry',
765
- ]);
766
-
767
- /**
768
- * Every function and cron: a Lambda running the handler the build wrote,
769
- * linked to exactly what it depends on, in the database's network when it
770
- * reaches one. A cron is that Lambda on its schedule; a function is reached
771
- * at its URL, which only callers granted IAM access can invoke.
772
- *
773
- * After everything else is provisioned, because each links to things
774
- * `provisionOrder` does not order before it.
775
- */
776
- export function provisionCompute(
777
- stack: StackType,
778
- manifest: ConstructManifest,
779
- provisioned: ProvisionedManifest,
780
- ): Cron[] {
781
- const crons: Cron[] = [];
782
-
783
- for (const [id, declaration] of Object.entries(manifest)) {
784
- if (declaration?.kind !== 'function' && declaration?.kind !== 'cron') {
785
- continue;
786
- }
787
-
788
- const { link } = resolveEdges(declaration.dependencies, provisioned);
789
- const vpc = vpcFor(link);
790
- const lambda = new Function(
791
- stack,
792
- declaration.kind === 'cron' ? `${id}Function` : id,
793
- {
794
- name: stack.logicalPrefixedName(id),
795
- handler: declaration.handler,
796
- link,
797
- ...(vpc ? { vpc } : {}),
798
- ...(declaration.kind === 'function'
799
- ? { url: { authorization: 'iam' } }
800
- : {}),
801
- },
802
- );
803
-
804
- if (declaration.kind === 'cron') {
805
- crons.push(
806
- new Cron(stack, id, {
807
- processor: lambda,
808
- schedule: declaration.schedule as CronSchedule,
809
- }),
810
- );
811
- continue;
812
- }
813
-
814
- assertProvides(
815
- id,
816
- declaration.provides,
817
- Object.keys(lambda.provides()).map((role) =>
818
- providedKeyFor(id, declaration.kind, role),
819
- ),
820
- );
821
- provisioned[id] = lambda;
822
- }
823
-
824
- return crons;
825
- }
826
-
827
- /** A provisioned queue: what {@link subscribeConsumers} subscribes through. */
828
- interface Consumable {
829
- consume(consumer: {
830
- handler: string;
831
- link?: unknown[];
832
- vpc?: sst.aws.Vpc;
833
- }): unknown;
834
- }
835
-
836
- /**
837
- * The network a function has to run in to reach what it links to.
838
- *
839
- * A database is private to its VPC, so a handler linked to one — or to a
840
- * schema tenant or reader of one — runs inside it, or its connection times out.
841
- */
842
- export function vpcFor(link: readonly Provisioned[]): sst.aws.Vpc | undefined {
843
- for (const component of link) {
844
- const cluster = rootCluster(component);
845
- if (cluster instanceof Database) return cluster.vpc;
846
- }
847
-
848
- return undefined;
849
- }
850
-
851
- /**
852
- * Mount every surface's endpoints — the handlers the build wrote, each linked
853
- * to exactly what that endpoint depends on.
854
- *
855
- * After every construct is provisioned, for the reason consumers are: an
856
- * endpoint links to things `provisionOrder` does not order before its surface.
857
- */
858
- export function mountRoutes(
859
- manifest: ConstructManifest,
860
- provisioned: ProvisionedManifest,
861
- ): void {
862
- for (const [id, declaration] of Object.entries(manifest)) {
863
- if (declaration?.kind !== 'rest-api') continue;
864
-
865
- const surface = provisioned[id];
866
- if (!(surface instanceof RestApiSurface)) continue;
867
-
868
- for (const endpoint of declaration.endpoints) {
869
- const { link } = resolveEdges(endpoint.dependencies, provisioned);
870
- const vpc = vpcFor(link);
871
- surface.mount({
872
- method: endpoint.method,
873
- path: endpoint.path,
874
- handler: endpoint.handler,
875
- link,
876
- ...(vpc ? { vpc } : {}),
877
- ...(endpoint.authorizer ? { authorizer: endpoint.authorizer } : {}),
878
- });
879
- }
880
- }
881
- }
882
-
883
- /**
884
- * Subscribe every queue's one consumer — the handler the build wrote for it,
885
- * linked to what that consumer depends on.
886
- *
887
- * After every construct is provisioned, because a consumer links to things
888
- * that `provisionOrder` does not order before the queue.
889
- */
890
- export function subscribeConsumers(
891
- manifest: ConstructManifest,
892
- provisioned: ProvisionedManifest,
893
- ): void {
894
- for (const [id, declaration] of Object.entries(manifest)) {
895
- if (declaration?.kind !== 'queue') continue;
896
-
897
- const queue = provisioned[id] as unknown as Consumable | undefined;
898
- if (!queue) continue;
899
-
900
- const { link } = resolveEdges(declaration.worker.dependencies, provisioned);
901
- const vpc = vpcFor(link);
902
- queue.consume({
903
- handler: declaration.worker.handler,
904
- link,
905
- ...(vpc ? { vpc } : {}),
906
- });
907
- }
908
- }
909
-
910
- /** The provisioner for a kind. Pure — the lookup is testable without Pulumi. */
911
- export function provisionerFor(kind: DeclarationKind): Provisioner {
912
- const provisioner = PROVISIONERS[kind];
913
- if (!provisioner) {
914
- throw new UnknownDeclarationKind(kind, Object.keys(PROVISIONERS));
915
- }
916
- return provisioner;
917
- }
918
-
919
- /**
920
- * Assert that a link yields exactly the env keys the app declared.
921
- *
922
- * `supplied` comes from `resolveEnvKeys`, which derives the keys a resource type
923
- * produces — the same derivation that runs for real. The app↔infra contract is
924
- * the one guarantee spanning two packages, two build phases, and two authors,
925
- * and the one a JavaScript consumer gets no compiler help with, so it is checked
926
- * at synth rather than trusted.
927
- */
928
- export function assertProvides(
929
- id: string,
930
- declared: readonly string[] = [],
931
- supplied: readonly string[] = [],
932
- ): void {
933
- const missing = declared.filter((key) => !supplied.includes(key));
934
- const extra = supplied.filter((key) => !declared.includes(key));
935
-
936
- if (missing.length || extra.length) {
937
- throw new ProvidesMismatch(id, missing, extra);
938
- }
939
- }
940
-
941
- /**
942
- * Provision everything the manifest declares.
943
- *
944
- * In `provisionOrder`, which puts every parent before its children — a schema
945
- * tenant, a read replica, and the surface over a bucket all resolve an address
946
- * off something else, and a pass in map order would find it half the time.
947
- */
948
- export function fromManifest<
949
- const M extends ConstructManifest,
950
- const B extends ManifestBackends = {},
951
- >(
952
- stack: StackType,
953
- manifest: M,
954
- /**
955
- * Provider-specific props, per construct id — typed from the manifest, so
956
- * only its ids are keys, each takes what its kind's component reads, and
957
- * what the synth cannot guess (a database's `vpc`, mail's `from`) is
958
- * required. See {@link ManifestOverrides}.
959
- *
960
- * Neutral options — `versioned`, `fifo` — travel in the declaration,
961
- * because the app legitimately has an opinion about them. Anything with S3
962
- * in its name does not belong in application code, so it is supplied here.
963
- * A third escape hatch needs no API: the components are returned, so
964
- * `provisioned.Uploads.nodes.bucket` is reachable for anything else.
965
- */
966
- overrides: ManifestOverrides<M, B>,
967
- /**
968
- * The backend choices that are config rather than declaration.
969
- *
970
- * Defaulted the same way the local target defaults them, so a stage deployed
971
- * without saying gets the same backend a developer ran against. Typed
972
- * literally, because the backend decides what is required above: an
973
- * ElastiCache cache needs a `vpc`, Resend or SMTP mail a `url`.
974
- */
975
- backends: B = {} as B,
976
- ): ProvisionedManifest {
977
- const provisioned: ProvisionedManifest = {};
978
-
979
- // In provisioning order, so a derived node finds the component its parent
980
- // became. `assertDerivations` has already ruled out a missing parent, so the
981
- // order is total rather than best-effort.
982
- //
983
- // Sites come last, and separately, because `provisionOrder` orders `of` and
984
- // not `dependencies` — a site needs its edges' *values* at construction
985
- // time, since a static site has no server half to read a link at runtime.
986
- // It is a pure consumer of addresses, so building it after everything else
987
- // is enough; the day a kind needs a site's URL at construction, this needs a
988
- // real topological sort rather than a second pass.
989
- const order = provisionOrder(manifest);
990
- const sites = order.filter((id) => manifest[id]?.kind === 'site');
991
- const rest = order.filter((id) => manifest[id]?.kind !== 'site');
992
-
993
- // One per surface, created up front so a surface can be handed its own before
994
- // the things that call it exist.
995
- const callers = new Map<string, Deferred>();
996
- for (const [id, declaration] of Object.entries(manifest)) {
997
- if (declaration.kind === 'rest-api') callers.set(id, defer());
998
- }
999
-
1000
- const context: ProvisionContext = {
1001
- manifest,
1002
- provisioned,
1003
- callers,
1004
- bootstraps: new Map<string, DatabaseBootstrap>(),
1005
- ...(backends.cache ? { cache: backends.cache } : {}),
1006
- ...(backends.email ? { email: backends.email } : {}),
1007
- };
1008
-
1009
- for (const id of [...rest, ...sites]) {
1010
- const declaration = manifest[id];
1011
- if (!declaration) continue;
1012
- if (PROVISIONED_ELSEWHERE.has(declaration.kind)) continue;
1013
-
1014
- const component = provisionerFor(declaration.kind)(
1015
- stack,
1016
- declaration,
1017
- (overrides as Record<string, Record<string, unknown>>)[id] ?? {},
1018
- context,
1019
- );
1020
-
1021
- assertProvides(
1022
- id,
1023
- declaration.provides,
1024
- // A role becomes the env key the app declared: `url` → `UPLOADS_URL`.
1025
- // Through the shared derivation, not a local copy of it — a secret's
1026
- // name *is* its key, and a check that derived it differently from the
1027
- // thing being checked would pass on drift instead of catching it.
1028
- Object.keys(component.provides()).map((role) =>
1029
- providedKeyFor(id, declaration.kind, role),
1030
- ),
1031
- );
1032
-
1033
- provisioned[id] = component;
1034
- }
1035
-
1036
- // The functions and crons, each queue's one consumer and each surface's
1037
- // endpoints, once everything they link to exists.
1038
- provisionCompute(stack, manifest, provisioned);
1039
- subscribeConsumers(manifest, provisioned);
1040
- mountRoutes(manifest, provisioned);
1041
-
1042
- for (const line of describeRoutes(manifest)) console.log(line);
1043
-
1044
- // Now everything exists, so every surface's callers can be resolved — the
1045
- // site's address included, which is what the deferral was for.
1046
- for (const [id, deferred] of callers) {
1047
- // Resolved with the promise itself: the addresses it needs are Pulumi
1048
- // outputs, so the answer arrives when they do.
1049
- deferred.resolve(callersOf(id, manifest, provisioned, $app.name));
1050
- }
1051
-
1052
- // Last, and only now: the roles exist as passwords and secrets from the
1053
- // moment each tenant was provisioned, but nothing has run `CREATE ROLE`.
1054
- // Pulumi cannot — so one function per cluster does, inside the VPC, invoked
1055
- // with an input that changes only when the roles or the cluster do.
1056
- for (const [clusterId, bootstrap] of context.bootstraps) {
1057
- const cluster = provisioned[clusterId] as unknown as Database | undefined;
1058
- if (cluster) bootstrap.run(cluster.vpc);
1059
- }
1060
-
1061
- return provisioned;
1062
- }
1063
-
1064
- /** What one function receives from its edges. */
1065
- export interface ResolvedEdges {
1066
- /** The components it may reach. SST turns these into IAM *and* injects their
1067
- * properties, so this is the whole delivery mechanism. */
1068
- link: Provisioned[];
1069
- /**
1070
- * The env keys those links yield.
1071
- *
1072
- * Not values: the values are injected at runtime by the link, and a map of
1073
- * key→placeholder would be a lie that ships. Keys are what the adapter needs,
1074
- * so a function's `requires` can be checked against what its own edges cover.
1075
- */
1076
- envKeys: string[];
1077
- }
1078
-
1079
- /**
1080
- * Resolve one function's dependencies into what it is given.
1081
- *
1082
- * A function is linked to exactly the constructs it declared, never the app's
1083
- * full set — so least privilege falls out of the edges rather than out of
1084
- * discipline. Adding an unrelated construct to the manifest cannot widen what
1085
- * an existing function can reach, which is the property worth testing as an
1086
- * exclusion.
1087
- *
1088
- * Pure: given a provisioned map, this is data in and data out, so the whole
1089
- * filtering rule is assertable without a deploy.
1090
- */
1091
- export function resolveEdges(
1092
- dependencies: readonly Dependency[] = [],
1093
- provisioned: ProvisionedManifest,
1094
- ): ResolvedEdges {
1095
- const link: Provisioned[] = [];
1096
- const envKeys = new Set<string>();
1097
-
1098
- for (const dependency of dependencies) {
1099
- const component = provisioned[dependency.target];
1100
- if (!component) {
1101
- throw new UnresolvedDependency(
1102
- dependency.target,
1103
- Object.keys(provisioned),
1104
- );
1105
- }
1106
-
1107
- link.push(component);
1108
- for (const key of resolveEnvKeys({
1109
- [dependency.target]: { type: component._type as string },
1110
- })) {
1111
- envKeys.add(key);
1112
- }
1113
- }
1114
-
1115
- return { link, envKeys: [...envKeys].sort() };
1116
- }