@geekmidas/manifest 10.0.0-alpha.17 → 10.0.0-alpha.170

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.cjs CHANGED
@@ -33,6 +33,31 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
33
33
  * this.
34
34
  */
35
35
  const DEFAULT_POSTGRES_VERSION = 18;
36
+ /** Whether a declaration is built into a public bundle — a site or an app. */
37
+ function isPublicDeclaration(declaration) {
38
+ return declaration.kind === "site" || declaration.kind === "mobile-app";
39
+ }
40
+ /** A site's subdomain that means every subdomain — see `SiteDeclaration`. */
41
+ const WILDCARD_SUBDOMAIN = "*";
42
+ /**
43
+ * Whether a declaration is a site answering on every subdomain.
44
+ */
45
+ function isWildcardSite(declaration) {
46
+ return declaration?.kind === "site" && "subdomain" in declaration && declaration.subdomain === "*";
47
+ }
48
+ /**
49
+ * What a `Telemetry` node provides to each process with an edge to it.
50
+ *
51
+ * `OTEL_SERVICE_NAME` is resolved per process — the app's name — so it is
52
+ * listed here but composed by whichever target hands it over.
53
+ */
54
+ const TELEMETRY_KEYS = [
55
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
56
+ "OTEL_EXPORTER_OTLP_HEADERS",
57
+ "OTEL_SERVICE_NAME",
58
+ "OTEL_TRACES_SAMPLER",
59
+ "OTEL_TRACES_SAMPLER_ARG"
60
+ ];
36
61
  /**
37
62
  * What each kind may derive from.
38
63
  *
@@ -55,23 +80,29 @@ const DERIVES_FROM = {
55
80
  * can legitimately use any of them. A bucket's `url` presigns and stays private.
56
81
  */
57
82
  const PUBLIC = {
58
- objects: [],
83
+ objects: ["signedOrigin"],
59
84
  "file-server": ["url"],
60
- email: [],
85
+ email: ["inboxUrl"],
86
+ inbox: [],
61
87
  database: [],
62
88
  "database-reader": [],
63
89
  "database-schema": [],
64
90
  cache: [],
65
91
  secret: [],
66
92
  credential: [],
93
+ encryption: [],
67
94
  "rest-api": ["url"],
95
+ "websocket-api": ["url"],
68
96
  queue: [],
69
97
  topic: [],
70
98
  oidc: ["issuer", "audience"],
99
+ "external-api": [],
71
100
  function: [],
72
101
  cron: [],
102
+ "mobile-app": [],
73
103
  site: ["url"],
74
- worker: []
104
+ worker: [],
105
+ telemetry: []
75
106
  };
76
107
  //#endregion
77
108
  //#region src/errors.ts
@@ -846,7 +877,33 @@ function cookieDomain(urls) {
846
877
  * cannot catch anything.
847
878
  */
848
879
  function providedKeyFor(id, kind, role) {
849
- return kind === "secret" ? environmentCase(id) : provideKey(id, role);
880
+ if (kind === "secret") return environmentCase(id);
881
+ if (kind === "telemetry") return "OTEL_EXPORTER_OTLP_ENDPOINT";
882
+ if (kind === "file-server") return provideKey(fileServerName(id), role);
883
+ return provideKey(id, role);
884
+ }
885
+ /**
886
+ * What a file server's surface node adds to the construct's id. The bucket
887
+ * keeps the plain id, so serving a bucket you already have adds a node rather
888
+ * than renaming the one holding the data.
889
+ */
890
+ const FILE_SERVER_SUFFIX = "Server";
891
+ /**
892
+ * A file server's surface node id, from the construct's id.
893
+ *
894
+ * @example fileServerSurfaceId('Assets') // 'AssetsServer'
895
+ */
896
+ function fileServerSurfaceId(id) {
897
+ return `${id}${FILE_SERVER_SUFFIX}`;
898
+ }
899
+ /**
900
+ * The construct's id, from its surface node's: what its key and its host are
901
+ * named after.
902
+ *
903
+ * @example fileServerName('AssetsServer') // 'Assets'
904
+ */
905
+ function fileServerName(surfaceId) {
906
+ return surfaceId.endsWith("Server") && surfaceId.length > 6 ? surfaceId.slice(0, -6) : surfaceId;
850
907
  }
851
908
  //#endregion
852
909
  //#region src/derive.ts
@@ -907,12 +964,17 @@ function provisionOrder(manifest) {
907
964
  */
908
965
  function dependenciesOf(declaration) {
909
966
  const own = "dependencies" in declaration ? declaration.dependencies ?? [] : [];
910
- const calls = "calls" in declaration ? declaration.calls ?? [] : [];
911
- const nested = declaration.kind === "rest-api" ? declaration.endpoints.flatMap((endpoint) => endpoint.dependencies) : [];
967
+ const auth = (declaration.kind === "rest-api" || declaration.kind === "websocket-api") && declaration.auth ? [declaration.auth] : [];
968
+ const nested = declaration.kind === "rest-api" ? declaration.endpoints.flatMap((endpoint) => endpoint.dependencies) : declaration.kind === "websocket-api" ? (declaration.routes ?? []).flatMap((route) => route.dependencies) : [];
969
+ const telemetry = "telemetry" in declaration && typeof declaration.telemetry === "string" ? [{
970
+ target: declaration.telemetry,
971
+ kind: "telemetry"
972
+ }] : [];
912
973
  return [
913
974
  ...own,
914
- ...calls,
915
- ...nested
975
+ ...auth,
976
+ ...nested,
977
+ ...telemetry
916
978
  ];
917
979
  }
918
980
  /**
@@ -946,11 +1008,54 @@ function dependentsOf(manifest, id) {
946
1008
  const PUBLIC_PREFIX = {
947
1009
  static: "VITE_",
948
1010
  tanstack: "VITE_",
949
- next: "NEXT_PUBLIC_"
1011
+ next: "NEXT_PUBLIC_",
1012
+ expo: "EXPO_PUBLIC_"
950
1013
  };
951
1014
  /**
1015
+ * Every public value a site's or a mobile app's edges reach — the one walk of
1016
+ * its edges that every target makes, so what a bundle inlines cannot differ
1017
+ * between `gkm dev`, a compose build and the AWS target.
1018
+ *
1019
+ * Each edge's `PUBLIC` roles, and, because a bucket and the file server over
1020
+ * it are one construct to a page:
1021
+ *
1022
+ * - an edge to a bucket (a full-stack site's `.dependsOn([assets.server])`)
1023
+ * also reaches each file server over it — its objects are shown from there;
1024
+ * - an edge to a file server also reaches its bucket's public values — where
1025
+ * the bucket signs the links to its private objects.
1026
+ *
1027
+ * A bucket's connection is never one: `PUBLIC.objects` does not list it.
1028
+ */
1029
+ function publicValues(declaration, manifest) {
1030
+ const values = /* @__PURE__ */ new Map();
1031
+ const reach = (id) => {
1032
+ const target = manifest[id];
1033
+ if (!target) return;
1034
+ for (const role of PUBLIC[target.kind] ?? []) {
1035
+ const key = providedKeyFor(id, target.kind, role);
1036
+ values.set(key, {
1037
+ id,
1038
+ kind: target.kind,
1039
+ role,
1040
+ key
1041
+ });
1042
+ }
1043
+ };
1044
+ for (const edge of declaration.dependencies) {
1045
+ const target = manifest[edge.target];
1046
+ if (!target) continue;
1047
+ reach(edge.target);
1048
+ if (target.kind === "objects") {
1049
+ for (const [id, other] of Object.entries(manifest)) if (other.kind === "file-server" && other.of === edge.target) reach(id);
1050
+ }
1051
+ if (target.kind === "file-server") reach(target.of);
1052
+ }
1053
+ return [...values.values()];
1054
+ }
1055
+ /**
952
1056
  * The keys a site's bundle needs, mapped to the key each value comes from —
953
- * `{ VITE_API_URL: 'API_URL' }`.
1057
+ * `{ VITE_API_URL: 'API_URL' }` — its edges' public values, and a site's own
1058
+ * address (`{ VITE_WEB_URL: 'WEB_URL' }`).
954
1059
  *
955
1060
  * A rename, not a second derivation: `API_URL` is resolved once, by whatever
956
1061
  * resolved it for the server, and the site reads the same value under the name
@@ -969,47 +1074,625 @@ const PUBLIC_PREFIX = {
969
1074
  function publicEnvFor(declaration, manifest) {
970
1075
  const prefix = PUBLIC_PREFIX[declaration.variant];
971
1076
  const keys = {};
972
- for (const edge of declaration.dependencies) {
973
- const target = manifest[edge.target];
974
- if (!target) continue;
975
- for (const role of PUBLIC[target.kind] ?? []) {
976
- const key = provideKey(edge.target, role);
977
- keys[`${prefix}${key}`] = key;
978
- }
1077
+ if (declaration.kind === "site") {
1078
+ const own = providedKeyFor(declaration.id, "site", "url");
1079
+ keys[`${prefix}${own}`] = own;
979
1080
  }
1081
+ if (isWildcardSite(declaration)) for (const role of ["domain", "protectedSubdomains"]) {
1082
+ const key = providedKeyFor(declaration.id, "site", role);
1083
+ keys[`${prefix}${key}`] = key;
1084
+ }
1085
+ for (const { key } of publicValues(declaration, manifest)) keys[`${prefix}${key}`] = key;
980
1086
  return keys;
981
1087
  }
1088
+ /**
1089
+ * The key, under a site's public prefix, that lists every origin its pages
1090
+ * load files from: `NEXT_PUBLIC_GKM_IMAGE_ORIGINS`. Comma-separated.
1091
+ *
1092
+ * One composed key rather than a rule over names, because a file server's
1093
+ * `<ID>_URL` and an API's look the same: which of a bundle's addresses serve
1094
+ * files is a fact about the graph, so the graph says it.
1095
+ */
1096
+ const IMAGE_ORIGINS_KEY = "GKM_IMAGE_ORIGINS";
1097
+ /**
1098
+ * The keys whose values are the origins a site's pages load files from: each
1099
+ * file server it reaches, and where each bucket it reaches signs its links —
1100
+ * by either edge, read off {@link publicValues}. Sorted, so the
1101
+ * value composed from them does not churn.
1102
+ */
1103
+ function imageOriginSources(declaration, manifest) {
1104
+ return publicValues(declaration, manifest).filter(({ kind, role }) => kind === "file-server" && role === "url" || kind === "objects" && role === "signedOrigin").map(({ key }) => key).sort();
1105
+ }
1106
+ /**
1107
+ * {@link IMAGE_ORIGINS_KEY}'s value: the origin of each source that resolved,
1108
+ * de-duplicated and comma-separated. `undefined` when none did, so a site
1109
+ * that shows no files is built without the key at all.
1110
+ */
1111
+ function imageOrigins(sources, resolve) {
1112
+ const origins = /* @__PURE__ */ new Set();
1113
+ for (const source of sources) {
1114
+ const value = resolve(source);
1115
+ if (!value) continue;
1116
+ try {
1117
+ origins.add(new URL(value).origin);
1118
+ } catch {}
1119
+ }
1120
+ return origins.size > 0 ? [...origins].sort().join(",") : void 0;
1121
+ }
1122
+ //#endregion
1123
+ //#region src/derived.ts
1124
+ /** Where a processor keeps what it made, in the bucket it reads. */
1125
+ const DERIVED_PREFIX = ".gkm-derived/";
1126
+ /** How long a derivative is kept when its file server does not say. */
1127
+ const DEFAULT_DERIVED_DAYS = 30;
1128
+ /**
1129
+ * The days a bucket keeps what is under each prefix: what it declared, and —
1130
+ * when a file server over it has processors — the derived prefix, for the
1131
+ * longest any of those servers asked. `undefined` when it expires nothing.
1132
+ */
1133
+ function bucketExpiry(manifest, bucketId) {
1134
+ const expire = { ...manifest[bucketId]?.expire ?? {} };
1135
+ const processed = Object.values(manifest).filter((d) => d.kind === "file-server" && d.of === bucketId && (d.processors?.length ?? 0) > 0);
1136
+ if (processed.length > 0 && expire[".gkm-derived/"] === void 0) expire[DERIVED_PREFIX] = Math.max(...processed.map((s) => s.derivedDays ?? 30));
1137
+ return Object.keys(expire).length > 0 ? expire : void 0;
1138
+ }
1139
+ //#endregion
1140
+ //#region src/email.ts
1141
+ /** The local part mail is sent from when the construct names none. */
1142
+ const DEFAULT_SENDER = "noreply";
1143
+ /** `<local part>@<domain>` — `info@shop.example.com`, else `noreply@…`. */
1144
+ function senderAddress(email, domain) {
1145
+ return `${email.from ?? "noreply"}@${domain}`;
1146
+ }
1147
+ //#endregion
1148
+ //#region src/encryption.ts
1149
+ /**
1150
+ * The `kms://` URL an `Encryption` construct reads on AWS.
1151
+ *
1152
+ * Here because two packages meet on it: `@geekmidas/cloud` composes it from
1153
+ * the keys it provisioned, and `@geekmidas/constructs` parses it to reach
1154
+ * them. One function, so the two cannot disagree about a parameter's name.
1155
+ */
1156
+ const KMS_SCHEME = "kms:";
1157
+ /**
1158
+ * `kms://<region>?key=<key arn>&index=<hmac key arn>[&endpoint=<url>]`
1159
+ *
1160
+ * `endpoint` reaches an emulator instead of AWS — floci, locally and in tests —
1161
+ * the same parameter an `sns://` connection string carries for the same reason.
1162
+ */
1163
+ function kmsUrl(input) {
1164
+ const query = new URLSearchParams({
1165
+ key: input.key,
1166
+ index: input.index,
1167
+ ...input.endpoint ? { endpoint: input.endpoint } : {}
1168
+ });
1169
+ return `${KMS_SCHEME}//${input.region}?${query}`;
1170
+ }
1171
+ //#endregion
1172
+ //#region src/external.ts
1173
+ /** The key in a by-stage `url` that answers for every stage not listed. */
1174
+ const DEFAULT_STAGE_URL = "default";
1175
+ /**
1176
+ * Where an external API answers on a deployed stage.
1177
+ *
1178
+ * One URL answers every stage; a record answers by stage name, falling back
1179
+ * to `default`. Read at build and deploy, so a stage nobody gave a URL fails
1180
+ * there — with the stage named — rather than at the first request.
1181
+ *
1182
+ * @throws {NoUrlForStage} when a record names neither the stage nor a default.
1183
+ */
1184
+ function externalApiUrl(declaration, stage) {
1185
+ const { url } = declaration;
1186
+ if (typeof url === "string") return url;
1187
+ const resolved = url[stage] ?? url["default"];
1188
+ if (!resolved) throw new NoUrlForStage(declaration.id, stage, Object.keys(url));
1189
+ return resolved;
1190
+ }
1191
+ /** An external API's `url` record has nothing for the stage being deployed. */
1192
+ var NoUrlForStage = class extends Error {
1193
+ id;
1194
+ stage;
1195
+ stages;
1196
+ constructor(id, stage, stages) {
1197
+ super(`'${id}' has no URL for the stage '${stage}': its url names ${stages.length ? stages.map((s) => `'${s}'`).join(", ") : "no stages"}. Add '${stage}', or a '${DEFAULT_STAGE_URL}' for every stage not listed.`);
1198
+ this.id = id;
1199
+ this.stage = stage;
1200
+ this.stages = stages;
1201
+ this.name = "NoUrlForStage";
1202
+ }
1203
+ };
1204
+ //#endregion
1205
+ //#region src/headers.ts
1206
+ /**
1207
+ * Headers gkm reserves for its own services' calls to each other.
1208
+ *
1209
+ * Shared by `@geekmidas/constructs`, which sends and reads them, and
1210
+ * `@geekmidas/cli`, whose edges strip them from every request that arrives
1211
+ * from outside — so the two cannot name them differently.
1212
+ */
1213
+ /**
1214
+ * The address of the client a service-to-service call is made on behalf of.
1215
+ *
1216
+ * An API asking its auth server for a session sends the client's address in
1217
+ * this rather than `X-Forwarded-For`: a forwarding header marks a request as
1218
+ * outside traffic, which would start the auth server's span in a new trace,
1219
+ * and the address is still needed — Better Auth rate-limits per client.
1220
+ *
1221
+ * Reserved: the stack's edge (Caddy, Traefik, the `gkm dev` edge) removes it
1222
+ * from every request that does not carry the stack's token
1223
+ * ({@link EDGE_TOKEN_HEADER}), and the auth server ignores it on any request
1224
+ * that neither carries the token nor is an internal caller's, so it cannot be
1225
+ * spoofed from outside.
1226
+ */
1227
+ const CLIENT_IP_HEADER = "x-gkm-client-ip";
1228
+ /**
1229
+ * The token a service of a stack sends beside {@link CLIENT_IP_HEADER} when
1230
+ * it calls a sibling through the stack's edge, at its public address.
1231
+ *
1232
+ * A request carries a forwarding header once it has passed an edge, so the
1233
+ * peer alone no longer says it came from inside the stack. The token does:
1234
+ * it is derived from the stage's seed, handed to every process of the stack
1235
+ * as {@link EDGE_TOKEN_KEY}, and known to the edge. The edge keeps
1236
+ * `x-gkm-client-ip` only on a request carrying it, and strips the header from
1237
+ * every other; the auth server honours the header only from an internal
1238
+ * caller or a request carrying its own token. A browser never has it.
1239
+ */
1240
+ const EDGE_TOKEN_HEADER = "x-gkm-edge-token";
1241
+ /** Where a stack's processes read the token {@link EDGE_TOKEN_HEADER} carries. */
1242
+ const EDGE_TOKEN_KEY = "GKM_EDGE_TOKEN";
1243
+ //#endregion
1244
+ //#region src/hosts.ts
1245
+ /** Whether a declaration answers on a host of its own: a surface or a site. */
1246
+ function isHostedDeclaration(declaration) {
1247
+ return declaration?.kind === "rest-api" || declaration?.kind === "websocket-api" || declaration?.kind === "site";
1248
+ }
1249
+ /**
1250
+ * The one derivation of a construct's labels: its primary label, its
1251
+ * aliases and its redirects, in declared order.
1252
+ */
1253
+ function hostLabels(source) {
1254
+ return {
1255
+ primary: source.subdomain ?? kebabCase(source.id),
1256
+ aliases: [...source.aliases ?? []],
1257
+ redirects: [...source.redirects ?? []]
1258
+ };
1259
+ }
1260
+ /** One label of a DNS name: lowercase letters, digits and inner hyphens. */
1261
+ const LABEL$1 = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
1262
+ /** An alias or redirect that cannot be a label of its own under the domain. */
1263
+ var InvalidHostLabel = class extends Error {
1264
+ id;
1265
+ label;
1266
+ field;
1267
+ constructor(id, label, field) {
1268
+ super(`'${id}' lists '${label}' in ${field}, which is not a host label it can add: each entry is one lowercase label under the stage's domain ('rest', 'www') — no '*', no dots — listed once, and not the construct's own label. Fix or remove the entry.`);
1269
+ this.id = id;
1270
+ this.label = label;
1271
+ this.field = field;
1272
+ this.name = "InvalidHostLabel";
1273
+ }
1274
+ };
1275
+ /** A wildcard site with aliases or redirects. */
1276
+ var WildcardSiteCannotHaveAliases = class extends Error {
1277
+ id;
1278
+ constructor(id) {
1279
+ super(`'${id}' answers on every subdomain, so it has no single host for an alias to repeat or a redirect to point at. Drop \`aliases\` and \`redirects\`, or give the site a subdomain of its own.`);
1280
+ this.id = id;
1281
+ this.name = "WildcardSiteCannotHaveAliases";
1282
+ }
1283
+ };
1284
+ /** One label listed as both an alias and a redirect. */
1285
+ var HostLabelBothAliasAndRedirect = class extends Error {
1286
+ id;
1287
+ label;
1288
+ constructor(id, label) {
1289
+ super(`'${id}' lists '${label}' in both aliases and redirects, but a host either serves the site or sends the browser elsewhere. Keep it in one of the two.`);
1290
+ this.id = id;
1291
+ this.label = label;
1292
+ this.name = "HostLabelBothAliasAndRedirect";
1293
+ }
1294
+ };
1295
+ /**
1296
+ * What a construct's aliases and redirects have to be, checked where it is
1297
+ * constructed.
1298
+ *
1299
+ * @throws {WildcardSiteCannotHaveAliases} on a wildcard site with either
1300
+ * @throws {HostLabelBothAliasAndRedirect} when a label is in both lists
1301
+ * @throws {InvalidHostLabel} for `'*'`, a dot, a repeat, or its own label
1302
+ */
1303
+ function assertHostLabels(source) {
1304
+ const { primary, aliases, redirects } = hostLabels(source);
1305
+ if (aliases.length === 0 && redirects.length === 0) return;
1306
+ if (primary === "*") throw new WildcardSiteCannotHaveAliases(source.id);
1307
+ for (const label of aliases) if (redirects.includes(label)) throw new HostLabelBothAliasAndRedirect(source.id, label);
1308
+ const seen = /* @__PURE__ */ new Set([primary]);
1309
+ const check = (labels, field) => {
1310
+ for (const label of labels) {
1311
+ if (!LABEL$1.test(label) || seen.has(label)) throw new InvalidHostLabel(source.id, label, field);
1312
+ seen.add(label);
1313
+ }
1314
+ };
1315
+ check(aliases, "aliases");
1316
+ check(redirects, "redirects");
1317
+ }
1318
+ //#endregion
1319
+ //#region src/inbox.ts
1320
+ /** The event type a received message is announced as on its inbox's topic. */
1321
+ const INBOX_EVENT = "email.received";
1322
+ /**
1323
+ * Where an inbox's raw messages are kept in its bucket: SES's S3 action
1324
+ * writes `<prefix><message id>`, and `gkm dev` and the test mailbox write the
1325
+ * same layout.
1326
+ */
1327
+ const INBOX_MESSAGES_PREFIX = "messages/";
1328
+ /**
1329
+ * The recipient `address` is to `inbox` on `domain`, or `undefined` when the
1330
+ * inbox does not receive at it.
1331
+ *
1332
+ * - The local part is a declared address, or one with a `+tag` after it.
1333
+ * - Without `subdomains`, the domain is the stage's domain itself; with it,
1334
+ * exactly one label in front of the stage's domain — `acme.fixwell.example`
1335
+ * — and never the bare domain, whose mail would belong to no tenant.
1336
+ *
1337
+ * Case-insensitive, as mail addresses are in practice.
1338
+ */
1339
+ function inboxRecipient(address, inbox, domain) {
1340
+ const normalized = address.trim().toLowerCase();
1341
+ const at = normalized.lastIndexOf("@");
1342
+ if (at <= 0) return void 0;
1343
+ const localPart = normalized.slice(0, at);
1344
+ const host = normalized.slice(at + 1);
1345
+ const base = domain.toLowerCase();
1346
+ let subdomain;
1347
+ if (inbox.subdomains) {
1348
+ if (!host.endsWith(`.${base}`)) return void 0;
1349
+ subdomain = host.slice(0, -(base.length + 1));
1350
+ if (!subdomain || subdomain.includes(".")) return void 0;
1351
+ } else if (host !== base) return;
1352
+ const plus = localPart.indexOf("+");
1353
+ const local = plus === -1 ? localPart : localPart.slice(0, plus);
1354
+ const tag = plus === -1 ? void 0 : localPart.slice(plus + 1);
1355
+ if (!inbox.addresses.some((declared) => declared.toLowerCase() === local)) return;
1356
+ return {
1357
+ address: normalized,
1358
+ local,
1359
+ ...tag ? { tag } : {},
1360
+ ...subdomain ? { subdomain } : {}
1361
+ };
1362
+ }
1363
+ /**
1364
+ * The recipients a deployed receipt rule names for `inbox` on `domain`.
1365
+ *
1366
+ * Without `subdomains`, each address on the domain: SES matches an address
1367
+ * condition's `+label` variants too, so `requests@` takes `requests+t_8f3k@`.
1368
+ * With it, every subdomain (`.fixwell.example`): a condition cannot say
1369
+ * "`requests` on any subdomain", so the rule takes the subdomains' mail and
1370
+ * the decoder in front of the handler drops what {@link inboxRecipient} does
1371
+ * not match.
1372
+ */
1373
+ function receiptRecipients(inbox, domain) {
1374
+ const base = domain.toLowerCase();
1375
+ return inbox.subdomains ? [`.${base}`] : inbox.addresses.map((address) => `${address.toLowerCase()}@${base}`);
1376
+ }
1377
+ //#endregion
1378
+ //#region src/migrations.ts
1379
+ /** Where every construct's folder lives, from the project root. */
1380
+ const MIGRATIONS_ROOT = "db";
1381
+ /** The two folders a construct's folder holds, and nothing else. */
1382
+ const DATABASE_FOLDERS = ["migrations", "seeds"];
1383
+ /**
1384
+ * The constructs that take migrations, parents before the tenants inside them.
1385
+ *
1386
+ * A database and each schema tenant: every one has an owner role and a schema
1387
+ * of its own, and so a history of its own. A reader has neither — it reads its
1388
+ * parent's schema — and a cache's table is created by provisioning, not by a
1389
+ * migration anyone writes.
1390
+ */
1391
+ function migrationTargets(manifest) {
1392
+ return provisionOrder(manifest).flatMap((id) => {
1393
+ const declaration = manifest[id];
1394
+ if (!declaration) return [];
1395
+ if (declaration.kind === "database") return [target(id)];
1396
+ if (declaration.kind === "database-schema") return [{
1397
+ ...target(id),
1398
+ of: declaration.of
1399
+ }];
1400
+ return [];
1401
+ });
1402
+ }
1403
+ /**
1404
+ * A construct's folder, relative to the project root.
1405
+ *
1406
+ * Named by the construct — `AuthDatabase` is `db/auth-database` — in the case
1407
+ * every other name outside TypeScript takes. Lowercase, because a folder that
1408
+ * differs from another only in case is two folders on Linux and one on a Mac;
1409
+ * and `canonicalId` reads it back to the construct exactly, which is how a
1410
+ * folder naming nothing is caught rather than skipped.
1411
+ */
1412
+ function databaseFolder(id) {
1413
+ return `db/${kebabCase(id)}`;
1414
+ }
1415
+ /** Where a construct's migrations live: `db/auth-database/migrations`. */
1416
+ function migrationFolder(id) {
1417
+ return `${databaseFolder(id)}/migrations`;
1418
+ }
1419
+ /**
1420
+ * Where a construct's seeds live: `db/auth-database/seeds`.
1421
+ *
1422
+ * Reference data the app needs to run — a permission catalogue, roles, lookup
1423
+ * tables. Seeds are upserts run on every pass, after the migrations, so a
1424
+ * changed seed is applied by running it again. Sample data is factories'.
1425
+ */
1426
+ function seedFolder(id) {
1427
+ return `${databaseFolder(id)}/seeds`;
1428
+ }
1429
+ function target(id) {
1430
+ return {
1431
+ id,
1432
+ folder: databaseFolder(id),
1433
+ migrations: migrationFolder(id),
1434
+ seeds: seedFolder(id)
1435
+ };
1436
+ }
982
1437
  //#endregion
983
- //#region src/index.ts
984
- /** Flatten a manifest field (array or partitioned) into a plain array. */
985
- function flattenManifestField(field) {
986
- if (!field) return [];
987
- return Array.isArray(field) ? [...field] : Object.values(field).flat();
1438
+ //#region src/mobile.ts
1439
+ /**
1440
+ * How a mobile app is reached: its URL scheme, and the origins a surface trusts
1441
+ * for it.
1442
+ *
1443
+ * Stated once, here, because three targets ask — the local one (`gkm dev`,
1444
+ * `gkm test`), Dokploy and AWS — and a scheme one of them derived differently
1445
+ * would be an app whose sign-in callback the auth server refuses on exactly one
1446
+ * of them.
1447
+ */
1448
+ /**
1449
+ * An app's scheme: the one given, or the project's name made a valid scheme.
1450
+ *
1451
+ * One for every stage. A development build and the store build register the
1452
+ * same scheme, so the auth server of whichever stage a build talks to trusts
1453
+ * it, and nothing about the app differs between stages but its URLs.
1454
+ *
1455
+ * A scheme is a letter followed by letters, digits, `+`, `-` or `.` — so
1456
+ * `Corner Shop` becomes `corner-shop`, and a name that starts with a digit gets a
1457
+ * leading `app`.
1458
+ */
1459
+ function schemeBase(project, given) {
1460
+ const raw = (given ?? project).toLowerCase().replace(/[^a-z0-9+.-]+/g, "-").replace(/^-+|-+$/g, "");
1461
+ if (!raw) return "app";
1462
+ return /^[a-z]/.test(raw) ? raw : `app${raw}`;
1463
+ }
1464
+ /**
1465
+ * The origins a surface trusts for a mobile caller.
1466
+ *
1467
+ * Better Auth's Expo plugin sends the app's scheme as its origin
1468
+ * (`shop://`), and a link can carry a path after it (`shop://*`).
1469
+ * In development, Expo Go sends `exp://<host>:<port>` instead — so a local
1470
+ * stage adds the hosts a device actually reaches Metro on, and Metro's port
1471
+ * when the target placed it: a whole subnet is not trusted because one phone
1472
+ * is on it.
1473
+ */
1474
+ function mobileOrigins(scheme, metro) {
1475
+ return [
1476
+ `${scheme}://`,
1477
+ `${scheme}://*`,
1478
+ ...(metro?.hosts ?? []).flatMap((host) => [`exp://${host}:${metro?.port ?? "*"}`, `exp://${host}:${metro?.port ?? "*"}/**`])
1479
+ ];
1480
+ }
1481
+ /** Whether an origin is a web one — what a cookie domain is derived from. */
1482
+ function isWebOrigin(origin) {
1483
+ return origin.startsWith("http://") || origin.startsWith("https://");
1484
+ }
1485
+ //#endregion
1486
+ //#region src/origins.ts
1487
+ /**
1488
+ * Whether a request from `origin` comes from one of `trusted`.
1489
+ *
1490
+ * An entry matches exactly — scheme, host and port — or, written
1491
+ * `https://*.example.com`, matches any one label in place of the `*`:
1492
+ * `https://acme.example.com`, never `https://example.com` and never
1493
+ * `https://a.b.example.com`. That is the origin a wildcard site's tenants
1494
+ * call from, and it is as wide as a wildcard certificate, no wider.
1495
+ *
1496
+ * A bare `*` trusts nothing: a surface that answers any origin has not said
1497
+ * which sites are its own.
1498
+ */
1499
+ function trustsOrigin(origin, trusted) {
1500
+ const request = parse(origin);
1501
+ if (!request) return false;
1502
+ return trusted.some((entry) => {
1503
+ const allowed = parse(entry);
1504
+ if (!allowed) return false;
1505
+ if (allowed.scheme !== request.scheme) return false;
1506
+ if (allowed.port !== request.port) return false;
1507
+ const domain = wildcardDomainOf(allowed.host);
1508
+ if (domain === void 0) return allowed.host === request.host;
1509
+ const dot = request.host.indexOf(".");
1510
+ return dot > 0 && LABEL.test(request.host.slice(0, dot)) && request.host.slice(dot + 1) === domain;
1511
+ });
1512
+ }
1513
+ /**
1514
+ * The domain under a wildcard host — `example.com` for `*.example.com` — or
1515
+ * `undefined` for a host that is not one.
1516
+ */
1517
+ function wildcardDomainOf(host) {
1518
+ return host.startsWith("*.") ? host.slice(2) : void 0;
1519
+ }
1520
+ /** One DNS label, as a tenant's slug is. */
1521
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1522
+ function parse(origin) {
1523
+ if (!origin || origin === "*") return void 0;
1524
+ try {
1525
+ const url = new URL(origin);
1526
+ if (url.origin === "null") return void 0;
1527
+ return {
1528
+ scheme: url.protocol,
1529
+ host: url.hostname.toLowerCase(),
1530
+ port: url.port
1531
+ };
1532
+ } catch {
1533
+ return;
1534
+ }
1535
+ }
1536
+ //#endregion
1537
+ //#region src/secret.ts
1538
+ /**
1539
+ * What a generated secret looks like, and the one way every stage draws it.
1540
+ *
1541
+ * A server deploy draws from `crypto`, `gkm dev` and `gkm test` from a hash of
1542
+ * the project, stage and id, and an AWS deploy asks Pulumi for the same
1543
+ * alphabet. Sharing this is what keeps a password that passes a third party's
1544
+ * rules on one stage from failing them on the next.
1545
+ */
1546
+ /** 43 characters from 64 is 256 bits — as much as anything here needs. */
1547
+ const SECRET_LENGTH = 43;
1548
+ /**
1549
+ * Two symbols nothing has to escape — not a URL, a connection string, a shell
1550
+ * or a `.env` file — which with letters and digits is base64url's alphabet.
1551
+ */
1552
+ const SECRET_SYMBOLS = "-_";
1553
+ const LETTERS_AND_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1554
+ /**
1555
+ * A secret in `format`, each character chosen by `pick(n)` — an integer in
1556
+ * `[0, n)` from whatever source the caller trusts.
1557
+ *
1558
+ * When there are symbols, one is guaranteed: a rule that demands a symbol is
1559
+ * the reason anyone names them, and leaving it to chance fails it often —
1560
+ * about one draw in seven at 24 characters.
1561
+ */
1562
+ function drawSecret(pick, format = {}) {
1563
+ const length = format.length ?? 43;
1564
+ const symbols = [...new Set(format.symbols ?? "-_")].join("");
1565
+ const alphabet = LETTERS_AND_DIGITS + symbols;
1566
+ const chars = Array.from({ length }, () => alphabet[pick(alphabet.length)]);
1567
+ if (symbols && !chars.some((char) => symbols.includes(char))) chars[pick(length)] = symbols[pick(symbols.length)];
1568
+ return chars.join("");
1569
+ }
1570
+ //#endregion
1571
+ //#region src/websocket.ts
1572
+ /**
1573
+ * The `apigateway://` string a `WebSocketApi`'s publisher reads on AWS.
1574
+ *
1575
+ * Here because two packages meet on it: `@geekmidas/cloud` composes it from
1576
+ * the API Gateway WebSocket API and the connection table it provisioned, and
1577
+ * `@geekmidas/constructs` parses it to reach them. One codec, so the two
1578
+ * cannot disagree about a parameter's name.
1579
+ *
1580
+ * On a server stage the same key is a `redis://` string — whichever replica
1581
+ * holds the socket delivers. On AWS the gateway holds every socket: a send is
1582
+ * a call to its management API, and a broadcast reads the ids it would fan out
1583
+ * to from the table.
1584
+ */
1585
+ const API_GATEWAY_WEBSOCKET_SCHEME = "apigateway:";
1586
+ /**
1587
+ * `apigateway://<region>?endpoint=<management url>&table=<name>[&tableEndpoint=<url>]`
1588
+ */
1589
+ function apiGatewayWebSocketUrl(target) {
1590
+ const query = new URLSearchParams({
1591
+ endpoint: target.endpoint,
1592
+ table: target.table,
1593
+ ...target.tableEndpoint ? { tableEndpoint: target.tableEndpoint } : {}
1594
+ });
1595
+ return `${API_GATEWAY_WEBSOCKET_SCHEME}//${target.region}?${query}`;
1596
+ }
1597
+ /** An `apigateway://` string missing what a publisher needs to reach a socket. */
1598
+ var InvalidApiGatewayWebSocketUrl = class extends Error {
1599
+ missing;
1600
+ constructor(missing) {
1601
+ super(`An apigateway:// WebSocket publisher string needs its ${missing}. gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING on an AWS stage — read it from there rather than writing one by hand.`);
1602
+ this.missing = missing;
1603
+ this.name = "InvalidApiGatewayWebSocketUrl";
1604
+ }
1605
+ };
1606
+ /** What an `apigateway://` string names. */
1607
+ function parseApiGatewayWebSocketUrl(value) {
1608
+ const url = new URL(value);
1609
+ if (url.protocol !== "apigateway:" || !url.hostname) throw new InvalidApiGatewayWebSocketUrl("region");
1610
+ const endpoint = url.searchParams.get("endpoint");
1611
+ if (!endpoint) throw new InvalidApiGatewayWebSocketUrl("endpoint");
1612
+ const table = url.searchParams.get("table");
1613
+ if (!table) throw new InvalidApiGatewayWebSocketUrl("table");
1614
+ const tableEndpoint = url.searchParams.get("tableEndpoint");
1615
+ return {
1616
+ region: url.hostname,
1617
+ endpoint,
1618
+ table,
1619
+ ...tableEndpoint ? { tableEndpoint } : {}
1620
+ };
988
1621
  }
989
1622
  //#endregion
1623
+ exports.API_GATEWAY_WEBSOCKET_SCHEME = API_GATEWAY_WEBSOCKET_SCHEME;
1624
+ exports.CLIENT_IP_HEADER = CLIENT_IP_HEADER;
1625
+ exports.DATABASE_FOLDERS = DATABASE_FOLDERS;
1626
+ exports.DEFAULT_DERIVED_DAYS = DEFAULT_DERIVED_DAYS;
990
1627
  exports.DEFAULT_POSTGRES_VERSION = DEFAULT_POSTGRES_VERSION;
1628
+ exports.DEFAULT_SENDER = DEFAULT_SENDER;
1629
+ exports.DEFAULT_STAGE_URL = DEFAULT_STAGE_URL;
1630
+ exports.DERIVED_PREFIX = DERIVED_PREFIX;
991
1631
  exports.DERIVES_FROM = DERIVES_FROM;
1632
+ exports.EDGE_TOKEN_HEADER = EDGE_TOKEN_HEADER;
1633
+ exports.EDGE_TOKEN_KEY = EDGE_TOKEN_KEY;
1634
+ exports.FILE_SERVER_SUFFIX = FILE_SERVER_SUFFIX;
1635
+ exports.HostLabelBothAliasAndRedirect = HostLabelBothAliasAndRedirect;
1636
+ exports.IMAGE_ORIGINS_KEY = IMAGE_ORIGINS_KEY;
1637
+ exports.INBOX_EVENT = INBOX_EVENT;
1638
+ exports.INBOX_MESSAGES_PREFIX = INBOX_MESSAGES_PREFIX;
992
1639
  exports.IllegalDerivation = IllegalDerivation;
1640
+ exports.InvalidApiGatewayWebSocketUrl = InvalidApiGatewayWebSocketUrl;
993
1641
  exports.InvalidConstructId = InvalidConstructId;
1642
+ exports.InvalidHostLabel = InvalidHostLabel;
1643
+ exports.KMS_SCHEME = KMS_SCHEME;
1644
+ exports.MIGRATIONS_ROOT = MIGRATIONS_ROOT;
1645
+ exports.NoUrlForStage = NoUrlForStage;
994
1646
  exports.PUBLIC = PUBLIC;
995
1647
  exports.PUBLIC_PREFIX = PUBLIC_PREFIX;
1648
+ exports.SECRET_LENGTH = SECRET_LENGTH;
1649
+ exports.SECRET_SYMBOLS = SECRET_SYMBOLS;
1650
+ exports.TELEMETRY_KEYS = TELEMETRY_KEYS;
996
1651
  exports.UnknownParent = UnknownParent;
1652
+ exports.WILDCARD_SUBDOMAIN = WILDCARD_SUBDOMAIN;
1653
+ exports.WildcardSiteCannotHaveAliases = WildcardSiteCannotHaveAliases;
1654
+ exports.apiGatewayWebSocketUrl = apiGatewayWebSocketUrl;
997
1655
  exports.assertDerivations = assertDerivations;
1656
+ exports.assertHostLabels = assertHostLabels;
1657
+ exports.bucketExpiry = bucketExpiry;
998
1658
  exports.cacheTable = cacheTable;
999
1659
  exports.canonicalId = canonicalId;
1000
1660
  exports.cloudName = cloudName;
1001
1661
  exports.cookieDomain = cookieDomain;
1662
+ exports.databaseFolder = databaseFolder;
1002
1663
  exports.dependenciesOf = dependenciesOf;
1003
1664
  exports.dependentsOf = dependentsOf;
1665
+ exports.drawSecret = drawSecret;
1004
1666
  exports.environmentCase = environmentCase;
1005
- exports.flattenManifestField = flattenManifestField;
1667
+ exports.externalApiUrl = externalApiUrl;
1668
+ exports.fileServerName = fileServerName;
1669
+ exports.fileServerSurfaceId = fileServerSurfaceId;
1670
+ exports.hostLabels = hostLabels;
1671
+ exports.imageOriginSources = imageOriginSources;
1672
+ exports.imageOrigins = imageOrigins;
1673
+ exports.inboxRecipient = inboxRecipient;
1006
1674
  exports.isDerived = isDerived;
1675
+ exports.isHostedDeclaration = isHostedDeclaration;
1676
+ exports.isPublicDeclaration = isPublicDeclaration;
1677
+ exports.isWebOrigin = isWebOrigin;
1678
+ exports.isWildcardSite = isWildcardSite;
1007
1679
  exports.kebabCase = kebabCase;
1008
- exports.provideKey = provideKey;
1680
+ exports.kmsUrl = kmsUrl;
1681
+ exports.migrationFolder = migrationFolder;
1682
+ exports.migrationTargets = migrationTargets;
1683
+ exports.mobileOrigins = mobileOrigins;
1684
+ exports.parseApiGatewayWebSocketUrl = parseApiGatewayWebSocketUrl;
1009
1685
  exports.providedKeyFor = providedKeyFor;
1010
1686
  exports.provisionOrder = provisionOrder;
1011
1687
  exports.publicEnvFor = publicEnvFor;
1688
+ exports.publicValues = publicValues;
1689
+ exports.receiptRecipients = receiptRecipients;
1690
+ exports.schemeBase = schemeBase;
1012
1691
  exports.scopedName = scopedName;
1692
+ exports.seedFolder = seedFolder;
1693
+ exports.senderAddress = senderAddress;
1013
1694
  exports.serviceKey = serviceKey;
1695
+ exports.trustsOrigin = trustsOrigin;
1696
+ exports.wildcardDomainOf = wildcardDomainOf;
1014
1697
 
1015
1698
  //# sourceMappingURL=index.cjs.map