@geekmidas/manifest 10.0.0-alpha.2 → 10.0.0-alpha.200

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
@@ -1,13 +1,12 @@
1
- //#region rolldown:runtime
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
11
10
  var __copyProps = (to, from, except, desc) => {
12
11
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
12
  key = keys[i];
@@ -18,13 +17,11 @@ var __copyProps = (to, from, except, desc) => {
18
17
  }
19
18
  return to;
20
19
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
22
21
  value: mod,
23
22
  enumerable: true
24
23
  }) : target, mod));
25
-
26
24
  //#endregion
27
-
28
25
  //#region src/declaration.ts
29
26
  /**
30
27
  * The version used when a database names none.
@@ -36,32 +33,31 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
33
  * this.
37
34
  */
38
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 = "*";
39
42
  /**
40
- * How the process serving a declaration is built and run.
41
- *
42
- * The half of an application that a graph genuinely cannot derive. *What*
43
- * exists — a surface, a site, the edges between them — is declared and read
44
- * back from the manifest. *Where its source lives and which globs find its
45
- * code* is not derivable from anything: it is a fact about a directory.
46
- *
47
- * It lives on the declaration rather than in a config `apps` block because the
48
- * two were the same list written twice, and the copy in config was the one that
49
- * could disagree. A site declared `path: 'apps/web'` and an app entry declared
50
- * `path: 'apps/web'`, and nothing checked them against each other; a surface
51
- * that config had no entry for simply never deployed.
52
- *
53
- * Only the declaration that *is* an app carries one. Two surfaces in one
54
- * process means one of them has the spec and the other collapses onto it —
55
- * which is the same rule that decides deploy units, now stated once.
43
+ * Whether a declaration is a site answering on every subdomain.
56
44
  */
45
+ function isWildcardSite(declaration) {
46
+ return declaration?.kind === "site" && "subdomain" in declaration && declaration.subdomain === "*";
47
+ }
57
48
  /**
58
- * Where an app's code lives when nobody says otherwise.
49
+ * What a `Telemetry` node provides to each process with an edge to it.
59
50
  *
60
- * One glob, every kind — the same rule the `constructs` glob follows. A handler
61
- * in one of these directories is found; anywhere else needs a `code` glob, and
62
- * saying so is the whole reason the field still exists.
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.
63
53
  */
64
- const DEFAULT_APP_CODE = "./{endpoints,functions,crons,queues,topics,subscribers}/**/*.ts";
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
+ ];
65
61
  /**
66
62
  * What each kind may derive from.
67
63
  *
@@ -84,25 +80,35 @@ const DERIVES_FROM = {
84
80
  * can legitimately use any of them. A bucket's `url` presigns and stays private.
85
81
  */
86
82
  const PUBLIC = {
87
- objects: [],
83
+ objects: ["signedOrigin"],
88
84
  "file-server": ["url"],
89
- email: [],
85
+ email: ["inboxUrl"],
86
+ inbox: [],
90
87
  database: [],
91
88
  "database-reader": [],
92
89
  "database-schema": [],
93
90
  cache: [],
91
+ maps: [
92
+ "browserKey",
93
+ "androidKey",
94
+ "iosKey"
95
+ ],
94
96
  secret: [],
95
97
  credential: [],
98
+ encryption: [],
96
99
  "rest-api": ["url"],
100
+ "websocket-api": ["url"],
97
101
  queue: [],
98
102
  topic: [],
99
103
  oidc: ["issuer", "audience"],
104
+ "external-api": [],
100
105
  function: [],
101
106
  cron: [],
107
+ "mobile-app": [],
102
108
  site: ["url"],
103
- worker: []
109
+ worker: [],
110
+ telemetry: []
104
111
  };
105
-
106
112
  //#endregion
107
113
  //#region src/errors.ts
108
114
  /**
@@ -161,20 +167,9 @@ var IllegalDerivation = class extends Error {
161
167
  this.allowed = allowed;
162
168
  }
163
169
  };
164
-
165
170
  //#endregion
166
- //#region ../../node_modules/.pnpm/lodash.snakecase@4.1.1/node_modules/lodash.snakecase/index.js
167
- var require_lodash = __commonJS({ "../../node_modules/.pnpm/lodash.snakecase@4.1.1/node_modules/lodash.snakecase/index.js"(exports, module) {
168
- /**
169
- * lodash (Custom Build) <https://lodash.com/>
170
- * Build: `lodash modularize exports="npm" -o ./`
171
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
172
- * Released under MIT license <https://lodash.com/license>
173
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
174
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
175
- */
176
- /** Used as references for various `Number` constants. */
177
- var INFINITY = Infinity;
171
+ //#region src/naming.ts
172
+ var import_lodash_snakecase = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
178
173
  /** `Object#toString` result references. */
179
174
  var symbolTag = "[object Symbol]";
180
175
  /** Used to match words composed of alphanumeric characters. */
@@ -182,15 +177,46 @@ var require_lodash = __commonJS({ "../../node_modules/.pnpm/lodash.snakecase@4.1
182
177
  /** Used to match Latin Unicode letters (excluding mathematical operators). */
183
178
  var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
184
179
  /** Used to compose unicode character classes. */
185
- var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23", rsComboSymbolsRange = "\\u20d0-\\u20f0", rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
180
+ var rsAstralRange = "\\ud800-\\udfff";
181
+ var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
182
+ var rsComboSymbolsRange = "\\u20d0-\\u20f0";
183
+ var rsDingbatRange = "\\u2700-\\u27bf";
184
+ var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
185
+ var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
186
+ var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
187
+ var rsPunctuationRange = "\\u2000-\\u206f";
188
+ var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
189
+ var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
190
+ var rsVarRange = "\\ufe0e\\ufe0f";
191
+ var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
186
192
  /** Used to compose unicode capture groups. */
187
- var rsApos = "['’]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d";
193
+ var rsApos = "['’]";
194
+ var rsBreak = "[" + rsBreakRange + "]";
195
+ var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
196
+ var rsDigits = "\\d+";
197
+ var rsDingbat = "[" + rsDingbatRange + "]";
198
+ var rsLower = "[" + rsLowerRange + "]";
199
+ var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
200
+ var rsModifier = "(?:" + rsCombo + "|\\ud83c[\\udffb-\\udfff])";
201
+ var rsNonAstral = "[^" + rsAstralRange + "]";
202
+ var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
203
+ var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
204
+ var rsUpper = "[" + rsUpperRange + "]";
205
+ var rsZWJ = "\\u200d";
188
206
  /** Used to compose unicode regexes. */
189
- var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")", rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [
207
+ var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
208
+ var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
209
+ var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
210
+ var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
211
+ var reOptMod = rsModifier + "?";
212
+ var rsOptVar = "[" + rsVarRange + "]?";
213
+ var rsOptJoin = "(?:" + rsZWJ + "(?:" + [
190
214
  rsNonAstral,
191
215
  rsRegional,
192
216
  rsSurrPair
193
- ].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [
217
+ ].join("|") + ")" + rsOptVar + reOptMod + ")*";
218
+ var rsSeq = rsOptVar + reOptMod + rsOptJoin;
219
+ var rsEmoji = "(?:" + [
194
220
  rsDingbat,
195
221
  rsRegional,
196
222
  rsSurrPair
@@ -489,18 +515,17 @@ var require_lodash = __commonJS({ "../../node_modules/.pnpm/lodash.snakecase@4.1
489
515
  function unicodeWords(string) {
490
516
  return string.match(reUnicodeWord) || [];
491
517
  }
492
- /** Used for built-in method references. */
493
- var objectProto = Object.prototype;
494
518
  /**
495
519
  * Used to resolve the
496
520
  * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
497
521
  * of values.
498
522
  */
499
- var objectToString = objectProto.toString;
523
+ var objectToString = Object.prototype.toString;
500
524
  /** Built-in value references. */
501
525
  var Symbol = root.Symbol;
502
526
  /** Used to convert symbols to primitives and strings. */
503
- var symbolProto = Symbol ? Symbol.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
527
+ var symbolProto = Symbol ? Symbol.prototype : void 0;
528
+ var symbolToString = symbolProto ? symbolProto.toString : void 0;
504
529
  /**
505
530
  * The base implementation of `_.toString` which doesn't convert nullish
506
531
  * values to empty strings.
@@ -513,7 +538,7 @@ var require_lodash = __commonJS({ "../../node_modules/.pnpm/lodash.snakecase@4.1
513
538
  if (typeof value == "string") return value;
514
539
  if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : "";
515
540
  var result = value + "";
516
- return result == "0" && 1 / value == -INFINITY ? "-0" : result;
541
+ return result == "0" && 1 / value == -Infinity ? "-0" : result;
517
542
  }
518
543
  /**
519
544
  * Creates a function like `_.camelCase`.
@@ -670,11 +695,7 @@ var require_lodash = __commonJS({ "../../node_modules/.pnpm/lodash.snakecase@4.1
670
695
  return string.match(pattern) || [];
671
696
  }
672
697
  module.exports = snakeCase;
673
- } });
674
-
675
- //#endregion
676
- //#region src/naming.ts
677
- var import_lodash = __toESM(require_lodash(), 1);
698
+ })))(), 1);
678
699
  /**
679
700
  * `UPPER_SNAKE_CASE`, with numbers kept against the word they follow.
680
701
  *
@@ -686,7 +707,7 @@ var import_lodash = __toESM(require_lodash(), 1);
686
707
  * @example environmentCase('api2') // 'API2' (digit joins its word)
687
708
  */
688
709
  function environmentCase(name) {
689
- return (0, import_lodash.default)(name).toUpperCase().replace(/_\d+/g, (r) => r.replace("_", ""));
710
+ return (0, import_lodash_snakecase.default)(name).toUpperCase().replace(/_\d+/g, (r) => r.replace("_", ""));
690
711
  }
691
712
  /**
692
713
  * The env key a construct provides for one of its roles.
@@ -711,7 +732,7 @@ function provideKey(id, role) {
711
732
  * @example canonicalId('user-uploads') // 'UserUploads'
712
733
  */
713
734
  function canonicalId(input) {
714
- const id = (0, import_lodash.default)(input).split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
735
+ const id = (0, import_lodash_snakecase.default)(input).split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
715
736
  if (!VALID_ID.test(id)) throw new InvalidConstructId(input, id);
716
737
  return id;
717
738
  }
@@ -861,9 +882,88 @@ function cookieDomain(urls) {
861
882
  * cannot catch anything.
862
883
  */
863
884
  function providedKeyFor(id, kind, role) {
864
- return kind === "secret" ? environmentCase(id) : provideKey(id, role);
885
+ if (kind === "secret") return environmentCase(id);
886
+ if (kind === "telemetry") return "OTEL_EXPORTER_OTLP_ENDPOINT";
887
+ if (kind === "file-server") return provideKey(fileServerName(id), role);
888
+ return provideKey(id, role);
889
+ }
890
+ /**
891
+ * What a file server's surface node adds to the construct's id. The bucket
892
+ * keeps the plain id, so serving a bucket you already have adds a node rather
893
+ * than renaming the one holding the data.
894
+ */
895
+ const FILE_SERVER_SUFFIX = "Server";
896
+ /**
897
+ * A file server's surface node id, from the construct's id.
898
+ *
899
+ * @example fileServerSurfaceId('Assets') // 'AssetsServer'
900
+ */
901
+ function fileServerSurfaceId(id) {
902
+ return `${id}${FILE_SERVER_SUFFIX}`;
903
+ }
904
+ /**
905
+ * The construct's id, from its surface node's: what its key and its host are
906
+ * named after.
907
+ *
908
+ * @example fileServerName('AssetsServer') // 'Assets'
909
+ */
910
+ function fileServerName(surfaceId) {
911
+ return surfaceId.endsWith("Server") && surfaceId.length > 6 ? surfaceId.slice(0, -6) : surfaceId;
912
+ }
913
+ //#endregion
914
+ //#region src/maps.ts
915
+ /** Every role, in the order a provider creates them. */
916
+ const MAPS_ROLES = [
917
+ "apiKey",
918
+ "browserKey",
919
+ "androidKey",
920
+ "iosKey"
921
+ ];
922
+ /**
923
+ * The roles a caller of `kind` holds: a site the browser key, a mobile app
924
+ * one per platform, anything else — a process on a server — the server key.
925
+ */
926
+ function mapsRolesFor(kind) {
927
+ if (kind === "site") return ["browserKey"];
928
+ if (kind === "mobile-app") return ["androidKey", "iosKey"];
929
+ return ["apiKey"];
930
+ }
931
+ /** Between a role's name and the caller a stored key is its: `_`. */
932
+ const CALLER_SEPARATOR = "_";
933
+ /**
934
+ * Where the stage's secrets keep the key `caller` holds of the `Maps`
935
+ * construct `maps` in `role` — `MAPS_BROWSER_KEY_WEB` for the site `Web`.
936
+ */
937
+ function mapsKeyOf(maps, role, caller) {
938
+ return `${providedKeyFor(maps, "maps", role)}${CALLER_SEPARATOR}${environmentCase(caller)}`;
939
+ }
940
+ /** The role `key` names of the `Maps` construct `maps`, as its callers read it. */
941
+ function mapsRoleOf(maps, key) {
942
+ return MAPS_ROLES.find((role) => providedKeyFor(maps, "maps", role) === key);
943
+ }
944
+ /**
945
+ * The caller `key` keeps a key of the `Maps` construct `maps` for — `Web` of
946
+ * `MAPS_BROWSER_KEY_WEB` — read against each role's name exactly: the rest
947
+ * after it and one `_`, never a split on underscores. `undefined` for a key
948
+ * that is no caller's, in its environment case (`WEB`, `ADMIN_APP`).
949
+ */
950
+ function mapsCallerOf(maps, key) {
951
+ for (const role of MAPS_ROLES) {
952
+ const prefix = `${providedKeyFor(maps, "maps", role)}${CALLER_SEPARATOR}`;
953
+ if (key.startsWith(prefix) && key.length > prefix.length) return {
954
+ role,
955
+ caller: key.slice(prefix.length)
956
+ };
957
+ }
958
+ }
959
+ /**
960
+ * Whether `key` is where a caller's own key of one of the manifest's `Maps`
961
+ * constructs is kept — a value only that caller is handed, under the role's
962
+ * name, and never a stage key every process reads.
963
+ */
964
+ function isMapsCallerKey(manifest, key) {
965
+ return Object.values(manifest).some((declaration) => declaration.kind === "maps" && mapsCallerOf(declaration.id, key) !== void 0);
865
966
  }
866
-
867
967
  //#endregion
868
968
  //#region src/derive.ts
869
969
  /** Whether a declaration names a parent. */
@@ -923,12 +1023,17 @@ function provisionOrder(manifest) {
923
1023
  */
924
1024
  function dependenciesOf(declaration) {
925
1025
  const own = "dependencies" in declaration ? declaration.dependencies ?? [] : [];
926
- const calls = "calls" in declaration ? declaration.calls ?? [] : [];
927
- const nested = declaration.kind === "rest-api" ? declaration.endpoints.flatMap((endpoint) => endpoint.dependencies) : [];
1026
+ const auth = (declaration.kind === "rest-api" || declaration.kind === "websocket-api") && declaration.auth ? [declaration.auth] : [];
1027
+ const nested = declaration.kind === "rest-api" ? declaration.endpoints.flatMap((endpoint) => endpoint.dependencies) : declaration.kind === "websocket-api" ? (declaration.routes ?? []).flatMap((route) => route.dependencies) : [];
1028
+ const telemetry = "telemetry" in declaration && typeof declaration.telemetry === "string" ? [{
1029
+ target: declaration.telemetry,
1030
+ kind: "telemetry"
1031
+ }] : [];
928
1032
  return [
929
1033
  ...own,
930
- ...calls,
931
- ...nested
1034
+ ...auth,
1035
+ ...nested,
1036
+ ...telemetry
932
1037
  ];
933
1038
  }
934
1039
  /**
@@ -962,11 +1067,84 @@ function dependentsOf(manifest, id) {
962
1067
  const PUBLIC_PREFIX = {
963
1068
  static: "VITE_",
964
1069
  tanstack: "VITE_",
965
- next: "NEXT_PUBLIC_"
1070
+ next: "NEXT_PUBLIC_",
1071
+ expo: "EXPO_PUBLIC_"
966
1072
  };
967
1073
  /**
1074
+ * The key a frontend's build reads its stage under — `NEXT_PUBLIC_STAGE`,
1075
+ * `VITE_STAGE`, `EXPO_PUBLIC_STAGE`: the build-time counterpart of the
1076
+ * `STAGE` every deployed process is handed.
1077
+ *
1078
+ * Inlined, so it is the stage the bundle was *built* for: an image promoted
1079
+ * to another stage carries it along. A stage secret of the same name wins —
1080
+ * it is how a stage said its name to the bundle before gkm did.
1081
+ */
1082
+ function publicStageKey(declaration) {
1083
+ return `${PUBLIC_PREFIX[declaration.variant]}STAGE`;
1084
+ }
1085
+ /** Every key a frontend's stage can be inlined under, one per prefix. */
1086
+ const PUBLIC_STAGE_KEYS = [...new Set(Object.values(PUBLIC_PREFIX).map((prefix) => `${prefix}STAGE`))];
1087
+ /**
1088
+ * Every public value a site's or a mobile app's edges reach — the one walk of
1089
+ * its edges that every target makes, so what a bundle inlines cannot differ
1090
+ * between `gkm dev`, a compose build and the AWS target.
1091
+ *
1092
+ * Each edge's `PUBLIC` roles, and, because a bucket and the file server over
1093
+ * it are one construct to a page:
1094
+ *
1095
+ * - an edge to a bucket (a full-stack site's `.dependsOn([assets.server])`)
1096
+ * also reaches each file server over it — its objects are shown from there;
1097
+ * - an edge to a file server also reaches its bucket's public values — where
1098
+ * the bucket signs the links to its private objects.
1099
+ *
1100
+ * A bucket's connection is never one: `PUBLIC.objects` does not list it.
1101
+ */
1102
+ function publicValues(declaration, manifest) {
1103
+ const values = /* @__PURE__ */ new Map();
1104
+ const reach = (id) => {
1105
+ const target = manifest[id];
1106
+ if (!target) return;
1107
+ for (const role of PUBLIC[target.kind] ?? []) {
1108
+ if (target.kind === "maps" && !mapsRolesFor(declaration.kind).includes(role)) continue;
1109
+ const key = providedKeyFor(id, target.kind, role);
1110
+ values.set(key, {
1111
+ id,
1112
+ kind: target.kind,
1113
+ role,
1114
+ key
1115
+ });
1116
+ }
1117
+ };
1118
+ for (const edge of declaration.dependencies) {
1119
+ const target = manifest[edge.target];
1120
+ if (!target) continue;
1121
+ reach(edge.target);
1122
+ if (target.kind === "objects") {
1123
+ for (const [id, other] of Object.entries(manifest)) if (other.kind === "file-server" && other.of === edge.target) reach(id);
1124
+ }
1125
+ if (target.kind === "file-server") reach(target.of);
1126
+ }
1127
+ return [...values.values()];
1128
+ }
1129
+ /**
1130
+ * Whether an edge hands its caller what a server holds of the target — a
1131
+ * bucket's connection and the key pair that signs for it — or only the
1132
+ * target's public values.
1133
+ *
1134
+ * A server process's edge always does: it presigns and writes. A site's or a
1135
+ * mobile app's does only when it named the server half
1136
+ * (`.dependsOn([documents.server])`), for a server half that uploads or
1137
+ * presigns. Its plain edge to a bucket is to where the bucket's links are
1138
+ * signed (`<T>_SIGNED_ORIGIN`): a page that shows presigned links needs to
1139
+ * allow their host, and nothing that writes to the bucket.
1140
+ */
1141
+ function reachesServerHalf(caller, edge) {
1142
+ return !isPublicDeclaration(caller) || edge.server === true;
1143
+ }
1144
+ /**
968
1145
  * The keys a site's bundle needs, mapped to the key each value comes from —
969
- * `{ VITE_API_URL: 'API_URL' }`.
1146
+ * `{ VITE_API_URL: 'API_URL' }` — its edges' public values, and a site's own
1147
+ * address (`{ VITE_WEB_URL: 'WEB_URL' }`).
970
1148
  *
971
1149
  * A rename, not a second derivation: `API_URL` is resolved once, by whatever
972
1150
  * resolved it for the server, and the site reads the same value under the name
@@ -985,49 +1163,689 @@ const PUBLIC_PREFIX = {
985
1163
  function publicEnvFor(declaration, manifest) {
986
1164
  const prefix = PUBLIC_PREFIX[declaration.variant];
987
1165
  const keys = {};
988
- for (const edge of declaration.dependencies) {
989
- const target = manifest[edge.target];
990
- if (!target) continue;
991
- for (const role of PUBLIC[target.kind] ?? []) {
992
- const key = provideKey(edge.target, role);
993
- keys[`${prefix}${key}`] = key;
994
- }
1166
+ if (declaration.kind === "site") {
1167
+ const own = providedKeyFor(declaration.id, "site", "url");
1168
+ keys[`${prefix}${own}`] = own;
995
1169
  }
1170
+ if (isWildcardSite(declaration)) for (const role of ["domain", "protectedSubdomains"]) {
1171
+ const key = providedKeyFor(declaration.id, "site", role);
1172
+ keys[`${prefix}${key}`] = key;
1173
+ }
1174
+ for (const { key } of publicValues(declaration, manifest)) keys[`${prefix}${key}`] = key;
996
1175
  return keys;
997
1176
  }
998
-
1177
+ /**
1178
+ * The key, under a site's public prefix, that lists every origin its pages
1179
+ * load files from: `NEXT_PUBLIC_GKM_IMAGE_ORIGINS`. Comma-separated.
1180
+ *
1181
+ * One composed key rather than a rule over names, because a file server's
1182
+ * `<ID>_URL` and an API's look the same: which of a bundle's addresses serve
1183
+ * files is a fact about the graph, so the graph says it.
1184
+ */
1185
+ const IMAGE_ORIGINS_KEY = "GKM_IMAGE_ORIGINS";
1186
+ /**
1187
+ * The keys whose values are the origins a site's pages load files from: each
1188
+ * file server it reaches, and where each bucket it reaches signs its links —
1189
+ * by either edge, read off {@link publicValues}. Sorted, so the
1190
+ * value composed from them does not churn.
1191
+ */
1192
+ function imageOriginSources(declaration, manifest) {
1193
+ return publicValues(declaration, manifest).filter(({ kind, role }) => kind === "file-server" && role === "url" || kind === "objects" && role === "signedOrigin").map(({ key }) => key).sort();
1194
+ }
1195
+ /**
1196
+ * {@link IMAGE_ORIGINS_KEY}'s value: the origin of each source that resolved,
1197
+ * de-duplicated and comma-separated. `undefined` when none did, so a site
1198
+ * that shows no files is built without the key at all.
1199
+ */
1200
+ function imageOrigins(sources, resolve) {
1201
+ const origins = /* @__PURE__ */ new Set();
1202
+ for (const source of sources) {
1203
+ const value = resolve(source);
1204
+ if (!value) continue;
1205
+ try {
1206
+ origins.add(new URL(value).origin);
1207
+ } catch {}
1208
+ }
1209
+ return origins.size > 0 ? [...origins].sort().join(",") : void 0;
1210
+ }
1211
+ /**
1212
+ * Where a frontend lists the origins its pages load files from: the
1213
+ * {@link IMAGE_ORIGINS_KEY} under its public prefix
1214
+ * (`NEXT_PUBLIC_GKM_IMAGE_ORIGINS`), and the keys whose origins make it up
1215
+ * ({@link imageOriginSources}). `undefined` for one that shows no files —
1216
+ * then it is handed no such key at all.
1217
+ *
1218
+ * The one place the key is named for a declaration: the dev env, a process's
1219
+ * keys and an image build's arguments all read it from here.
1220
+ */
1221
+ function imageOriginsFor(declaration, manifest) {
1222
+ const sources = imageOriginSources(declaration, manifest);
1223
+ if (sources.length === 0) return void 0;
1224
+ return {
1225
+ key: `${PUBLIC_PREFIX[declaration.variant]}${IMAGE_ORIGINS_KEY}`,
1226
+ sources
1227
+ };
1228
+ }
999
1229
  //#endregion
1000
- //#region src/index.ts
1001
- /** Flatten a manifest field (array or partitioned) into a plain array. */
1002
- function flattenManifestField(field) {
1003
- if (!field) return [];
1004
- return Array.isArray(field) ? [...field] : Object.values(field).flat();
1230
+ //#region src/derived.ts
1231
+ /** Where a processor keeps what it made, in the bucket it reads. */
1232
+ const DERIVED_PREFIX = ".gkm-derived/";
1233
+ /** How long a derivative is kept when its file server does not say. */
1234
+ const DEFAULT_DERIVED_DAYS = 30;
1235
+ /**
1236
+ * The days a bucket keeps what is under each prefix: what it declared, and —
1237
+ * when a file server over it has processors — the derived prefix, for the
1238
+ * longest any of those servers asked. `undefined` when it expires nothing.
1239
+ */
1240
+ function bucketExpiry(manifest, bucketId) {
1241
+ const expire = { ...manifest[bucketId]?.expire ?? {} };
1242
+ const processed = Object.values(manifest).filter((d) => d.kind === "file-server" && d.of === bucketId && (d.processors?.length ?? 0) > 0);
1243
+ if (processed.length > 0 && expire[".gkm-derived/"] === void 0) expire[DERIVED_PREFIX] = Math.max(...processed.map((s) => s.derivedDays ?? 30));
1244
+ return Object.keys(expire).length > 0 ? expire : void 0;
1245
+ }
1246
+ //#endregion
1247
+ //#region src/email.ts
1248
+ /** The local part mail is sent from when the construct names none. */
1249
+ const DEFAULT_SENDER = "noreply";
1250
+ /**
1251
+ * The domain `email` sends from, of the stage's `domain`: the domain itself,
1252
+ * or with a `subdomain`, that label in front of it — `mail.shop.example.com`.
1253
+ */
1254
+ function senderDomain(email, domain) {
1255
+ return email.subdomain ? `${email.subdomain}.${domain}` : domain;
1256
+ }
1257
+ /**
1258
+ * `<local part>@<sending domain>` — `info@shop.example.com`, else
1259
+ * `noreply@…`; `info@mail.shop.example.com` with `subdomain: 'mail'`.
1260
+ */
1261
+ function senderAddress(email, domain) {
1262
+ return `${email.from ?? "noreply"}@${senderDomain(email, domain)}`;
1263
+ }
1264
+ //#endregion
1265
+ //#region src/encryption.ts
1266
+ /**
1267
+ * The `kms://` URL an `Encryption` construct reads on AWS.
1268
+ *
1269
+ * Here because two packages meet on it: `@geekmidas/cloud` composes it from
1270
+ * the keys it provisioned, and `@geekmidas/constructs` parses it to reach
1271
+ * them. One function, so the two cannot disagree about a parameter's name.
1272
+ */
1273
+ const KMS_SCHEME = "kms:";
1274
+ /**
1275
+ * `kms://<region>?key=<key arn>&index=<hmac key arn>[&endpoint=<url>]`
1276
+ *
1277
+ * `endpoint` reaches an emulator instead of AWS — floci, locally and in tests —
1278
+ * the same parameter an `sns://` connection string carries for the same reason.
1279
+ */
1280
+ function kmsUrl(input) {
1281
+ const query = new URLSearchParams({
1282
+ key: input.key,
1283
+ index: input.index,
1284
+ ...input.endpoint ? { endpoint: input.endpoint } : {}
1285
+ });
1286
+ return `${KMS_SCHEME}//${input.region}?${query}`;
1005
1287
  }
1006
-
1007
1288
  //#endregion
1008
- exports.DEFAULT_APP_CODE = DEFAULT_APP_CODE;
1289
+ //#region src/external.ts
1290
+ /** The key in a by-stage `url` that answers for every stage not listed. */
1291
+ const DEFAULT_STAGE_URL = "default";
1292
+ /**
1293
+ * Where an external API answers on a deployed stage.
1294
+ *
1295
+ * One URL answers every stage; a record answers by stage name, falling back
1296
+ * to `default`. Read at build and deploy, so a stage nobody gave a URL fails
1297
+ * there — with the stage named — rather than at the first request.
1298
+ *
1299
+ * @throws {NoUrlForStage} when a record names neither the stage nor a default.
1300
+ */
1301
+ function externalApiUrl(declaration, stage) {
1302
+ const { url } = declaration;
1303
+ if (typeof url === "string") return url;
1304
+ const resolved = url[stage] ?? url["default"];
1305
+ if (!resolved) throw new NoUrlForStage(declaration.id, stage, Object.keys(url));
1306
+ return resolved;
1307
+ }
1308
+ /** An external API's `url` record has nothing for the stage being deployed. */
1309
+ var NoUrlForStage = class extends Error {
1310
+ id;
1311
+ stage;
1312
+ stages;
1313
+ constructor(id, stage, stages) {
1314
+ 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.`);
1315
+ this.id = id;
1316
+ this.stage = stage;
1317
+ this.stages = stages;
1318
+ this.name = "NoUrlForStage";
1319
+ }
1320
+ };
1321
+ //#endregion
1322
+ //#region src/headers.ts
1323
+ /**
1324
+ * Headers gkm reserves for its own services' calls to each other.
1325
+ *
1326
+ * Shared by `@geekmidas/constructs`, which sends and reads them, and
1327
+ * `@geekmidas/cli`, whose edges strip them from every request that arrives
1328
+ * from outside — so the two cannot name them differently.
1329
+ */
1330
+ /**
1331
+ * The address of the client a service-to-service call is made on behalf of.
1332
+ *
1333
+ * An API asking its auth server for a session sends the client's address in
1334
+ * this rather than `X-Forwarded-For`: a forwarding header marks a request as
1335
+ * outside traffic, which would start the auth server's span in a new trace,
1336
+ * and the address is still needed — Better Auth rate-limits per client.
1337
+ *
1338
+ * Reserved: the stack's edge (Caddy, Traefik, the `gkm dev` edge) removes it
1339
+ * from every request that does not carry the stack's token
1340
+ * ({@link EDGE_TOKEN_HEADER}), and the auth server ignores it on any request
1341
+ * that neither carries the token nor is an internal caller's, so it cannot be
1342
+ * spoofed from outside.
1343
+ */
1344
+ const CLIENT_IP_HEADER = "x-gkm-client-ip";
1345
+ /**
1346
+ * The token a service of a stack sends beside {@link CLIENT_IP_HEADER} when
1347
+ * it calls a sibling through the stack's edge, at its public address.
1348
+ *
1349
+ * A request carries a forwarding header once it has passed an edge, so the
1350
+ * peer alone no longer says it came from inside the stack. The token does:
1351
+ * it is derived from the stage's seed, handed to every process of the stack
1352
+ * as {@link EDGE_TOKEN_KEY}, and known to the edge. The edge keeps
1353
+ * `x-gkm-client-ip` only on a request carrying it, and strips the header from
1354
+ * every other; the auth server honours the header only from an internal
1355
+ * caller or a request carrying its own token. A browser never has it.
1356
+ */
1357
+ const EDGE_TOKEN_HEADER = "x-gkm-edge-token";
1358
+ /** Where a stack's processes read the token {@link EDGE_TOKEN_HEADER} carries. */
1359
+ const EDGE_TOKEN_KEY = "GKM_EDGE_TOKEN";
1360
+ //#endregion
1361
+ //#region src/hosts.ts
1362
+ /** Whether a declaration answers on a host of its own: a surface or a site. */
1363
+ function isHostedDeclaration(declaration) {
1364
+ return declaration?.kind === "rest-api" || declaration?.kind === "websocket-api" || declaration?.kind === "site";
1365
+ }
1366
+ /**
1367
+ * The one derivation of a construct's labels: its primary label, its
1368
+ * aliases and its redirects, in declared order.
1369
+ */
1370
+ function hostLabels(source) {
1371
+ return {
1372
+ primary: source.subdomain ?? kebabCase(source.id),
1373
+ aliases: [...source.aliases ?? []],
1374
+ redirects: [...source.redirects ?? []]
1375
+ };
1376
+ }
1377
+ /** One label of a DNS name: lowercase letters, digits and inner hyphens. */
1378
+ const LABEL$1 = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
1379
+ /**
1380
+ * A `subdomain`, alias or redirect that cannot be a label of its own under
1381
+ * the domain.
1382
+ */
1383
+ var InvalidHostLabel = class extends Error {
1384
+ id;
1385
+ label;
1386
+ field;
1387
+ constructor(id, label, field) {
1388
+ super(field === "subdomain" ? `'${id}' has subdomain: '${label}', which is not a host label: it is one lowercase label under the stage's domain ('telemetry', 'logs') — letters, digits and inner hyphens, no '*' and no dots.` : `'${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.`);
1389
+ this.id = id;
1390
+ this.label = label;
1391
+ this.field = field;
1392
+ this.name = "InvalidHostLabel";
1393
+ }
1394
+ };
1395
+ /**
1396
+ * A construct's own `subdomain`, checked where it is constructed: one label,
1397
+ * never a wildcard — for a construct that cannot answer on every subdomain.
1398
+ *
1399
+ * @throws {InvalidHostLabel} for `'*'`, a dot, or anything not a DNS label
1400
+ */
1401
+ function assertSubdomainLabel(id, subdomain) {
1402
+ if (!LABEL$1.test(subdomain)) throw new InvalidHostLabel(id, subdomain, "subdomain");
1403
+ }
1404
+ /** A wildcard site with aliases or redirects. */
1405
+ var WildcardSiteCannotHaveAliases = class extends Error {
1406
+ id;
1407
+ constructor(id) {
1408
+ 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.`);
1409
+ this.id = id;
1410
+ this.name = "WildcardSiteCannotHaveAliases";
1411
+ }
1412
+ };
1413
+ /** One label listed as both an alias and a redirect. */
1414
+ var HostLabelBothAliasAndRedirect = class extends Error {
1415
+ id;
1416
+ label;
1417
+ constructor(id, label) {
1418
+ 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.`);
1419
+ this.id = id;
1420
+ this.label = label;
1421
+ this.name = "HostLabelBothAliasAndRedirect";
1422
+ }
1423
+ };
1424
+ /**
1425
+ * What a construct's aliases and redirects have to be, checked where it is
1426
+ * constructed.
1427
+ *
1428
+ * @throws {WildcardSiteCannotHaveAliases} on a wildcard site with either
1429
+ * @throws {HostLabelBothAliasAndRedirect} when a label is in both lists
1430
+ * @throws {InvalidHostLabel} for `'*'`, a dot, a repeat, or its own label
1431
+ */
1432
+ function assertHostLabels(source) {
1433
+ const { primary, aliases, redirects } = hostLabels(source);
1434
+ if (aliases.length === 0 && redirects.length === 0) return;
1435
+ if (primary === "*") throw new WildcardSiteCannotHaveAliases(source.id);
1436
+ for (const label of aliases) if (redirects.includes(label)) throw new HostLabelBothAliasAndRedirect(source.id, label);
1437
+ const seen = /* @__PURE__ */ new Set([primary]);
1438
+ const check = (labels, field) => {
1439
+ for (const label of labels) {
1440
+ if (!LABEL$1.test(label) || seen.has(label)) throw new InvalidHostLabel(source.id, label, field);
1441
+ seen.add(label);
1442
+ }
1443
+ };
1444
+ check(aliases, "aliases");
1445
+ check(redirects, "redirects");
1446
+ }
1447
+ //#endregion
1448
+ //#region src/inbox.ts
1449
+ /** The event type a received message is announced as on its inbox's topic. */
1450
+ const INBOX_EVENT = "email.received";
1451
+ /**
1452
+ * Where an inbox's raw messages are kept in its bucket: SES's S3 action
1453
+ * writes `<prefix><message id>`, and `gkm dev` and the test mailbox write the
1454
+ * same layout.
1455
+ */
1456
+ const INBOX_MESSAGES_PREFIX = "messages/";
1457
+ /**
1458
+ * The recipient `address` is to `inbox` on `domain`, or `undefined` when the
1459
+ * inbox does not receive at it.
1460
+ *
1461
+ * - The local part is a declared address, or one with a `+tag` after it.
1462
+ * - Without `subdomains`, the domain is the stage's domain itself; with it,
1463
+ * exactly one label in front of the stage's domain — `acme.fixwell.example`
1464
+ * — and never the bare domain, whose mail would belong to no tenant.
1465
+ *
1466
+ * Case-insensitive, as mail addresses are in practice.
1467
+ */
1468
+ function inboxRecipient(address, inbox, domain) {
1469
+ const normalized = address.trim().toLowerCase();
1470
+ const at = normalized.lastIndexOf("@");
1471
+ if (at <= 0) return void 0;
1472
+ const localPart = normalized.slice(0, at);
1473
+ const host = normalized.slice(at + 1);
1474
+ const base = domain.toLowerCase();
1475
+ let subdomain;
1476
+ if (inbox.subdomains) {
1477
+ if (!host.endsWith(`.${base}`)) return void 0;
1478
+ subdomain = host.slice(0, -(base.length + 1));
1479
+ if (!subdomain || subdomain.includes(".")) return void 0;
1480
+ } else if (host !== base) return;
1481
+ const plus = localPart.indexOf("+");
1482
+ const local = plus === -1 ? localPart : localPart.slice(0, plus);
1483
+ const tag = plus === -1 ? void 0 : localPart.slice(plus + 1);
1484
+ if (!inbox.addresses.some((declared) => declared.toLowerCase() === local)) return;
1485
+ return {
1486
+ address: normalized,
1487
+ local,
1488
+ ...tag ? { tag } : {},
1489
+ ...subdomain ? { subdomain } : {}
1490
+ };
1491
+ }
1492
+ /**
1493
+ * The domain `inbox` receives on, of the stage's `domain`: the domain itself,
1494
+ * or with a fixed `subdomain`, that label in front of it — `in.fixwell.example`.
1495
+ *
1496
+ * The one place an inbox's domain is derived. Every target writes it as the
1497
+ * inbox's `<ID>_DOMAIN`, and everything downstream — the receipt rule, the MX
1498
+ * record, the identity, the decoder, `gkm dev`'s receiver — reads that.
1499
+ */
1500
+ function inboxDomain(inbox, domain) {
1501
+ return inbox.subdomain ? `${inbox.subdomain}.${domain}` : domain;
1502
+ }
1503
+ /**
1504
+ * The recipients a deployed receipt rule names for `inbox` on `domain`.
1505
+ *
1506
+ * Without `subdomains`, each address on the domain: SES matches an address
1507
+ * condition's `+label` variants too, so `requests@` takes `requests+t_8f3k@`.
1508
+ * With it, every subdomain (`.fixwell.example`): a condition cannot say
1509
+ * "`requests` on any subdomain", so the rule takes the subdomains' mail and
1510
+ * the decoder in front of the handler drops what {@link inboxRecipient} does
1511
+ * not match.
1512
+ */
1513
+ function receiptRecipients(inbox, domain) {
1514
+ const base = domain.toLowerCase();
1515
+ return inbox.subdomains ? [`.${base}`] : inbox.addresses.map((address) => `${address.toLowerCase()}@${base}`);
1516
+ }
1517
+ //#endregion
1518
+ //#region src/migrations.ts
1519
+ /** Where every construct's folder lives, from the project root. */
1520
+ const MIGRATIONS_ROOT = "db";
1521
+ /** The two folders a construct's folder holds, and nothing else. */
1522
+ const DATABASE_FOLDERS = ["migrations", "seeds"];
1523
+ /**
1524
+ * The constructs that take migrations, parents before the tenants inside them.
1525
+ *
1526
+ * A database and each schema tenant: every one has an owner role and a schema
1527
+ * of its own, and so a history of its own. A reader has neither — it reads its
1528
+ * parent's schema — and a cache's table is created by provisioning, not by a
1529
+ * migration anyone writes.
1530
+ */
1531
+ function migrationTargets(manifest) {
1532
+ return provisionOrder(manifest).flatMap((id) => {
1533
+ const declaration = manifest[id];
1534
+ if (!declaration) return [];
1535
+ if (declaration.kind === "database") return [target(id)];
1536
+ if (declaration.kind === "database-schema") return [{
1537
+ ...target(id),
1538
+ of: declaration.of
1539
+ }];
1540
+ return [];
1541
+ });
1542
+ }
1543
+ /**
1544
+ * A construct's folder, relative to the project root.
1545
+ *
1546
+ * Named by the construct — `AuthDatabase` is `db/auth-database` — in the case
1547
+ * every other name outside TypeScript takes. Lowercase, because a folder that
1548
+ * differs from another only in case is two folders on Linux and one on a Mac;
1549
+ * and `canonicalId` reads it back to the construct exactly, which is how a
1550
+ * folder naming nothing is caught rather than skipped.
1551
+ */
1552
+ function databaseFolder(id) {
1553
+ return `db/${kebabCase(id)}`;
1554
+ }
1555
+ /** Where a construct's migrations live: `db/auth-database/migrations`. */
1556
+ function migrationFolder(id) {
1557
+ return `${databaseFolder(id)}/migrations`;
1558
+ }
1559
+ /**
1560
+ * Where a construct's seeds live: `db/auth-database/seeds`.
1561
+ *
1562
+ * Reference data the app needs to run — a permission catalogue, roles, lookup
1563
+ * tables. Seeds are upserts run on every pass, after the migrations, so a
1564
+ * changed seed is applied by running it again. Sample data is factories'.
1565
+ */
1566
+ function seedFolder(id) {
1567
+ return `${databaseFolder(id)}/seeds`;
1568
+ }
1569
+ function target(id) {
1570
+ return {
1571
+ id,
1572
+ folder: databaseFolder(id),
1573
+ migrations: migrationFolder(id),
1574
+ seeds: seedFolder(id)
1575
+ };
1576
+ }
1577
+ //#endregion
1578
+ //#region src/mobile.ts
1579
+ /**
1580
+ * How a mobile app is reached: its URL scheme, and the origins a surface trusts
1581
+ * for it.
1582
+ *
1583
+ * Stated once, here, because three targets ask — the local one (`gkm dev`,
1584
+ * `gkm test`), Dokploy and AWS — and a scheme one of them derived differently
1585
+ * would be an app whose sign-in callback the auth server refuses on exactly one
1586
+ * of them.
1587
+ */
1588
+ /**
1589
+ * An app's scheme: the one given, or the project's name made a valid scheme.
1590
+ *
1591
+ * One for every stage. A development build and the store build register the
1592
+ * same scheme, so the auth server of whichever stage a build talks to trusts
1593
+ * it, and nothing about the app differs between stages but its URLs.
1594
+ *
1595
+ * A scheme is a letter followed by letters, digits, `+`, `-` or `.` — so
1596
+ * `Corner Shop` becomes `corner-shop`, and a name that starts with a digit gets a
1597
+ * leading `app`.
1598
+ */
1599
+ function schemeBase(project, given) {
1600
+ const raw = (given ?? project).toLowerCase().replace(/[^a-z0-9+.-]+/g, "-").replace(/^-+|-+$/g, "");
1601
+ if (!raw) return "app";
1602
+ return /^[a-z]/.test(raw) ? raw : `app${raw}`;
1603
+ }
1604
+ /**
1605
+ * The origins a surface trusts for a mobile caller.
1606
+ *
1607
+ * Better Auth's Expo plugin sends the app's scheme as its origin
1608
+ * (`shop://`), and a link can carry a path after it (`shop://*`).
1609
+ * In development, Expo Go sends `exp://<host>:<port>` instead — so a local
1610
+ * stage adds the hosts a device actually reaches Metro on, and Metro's port
1611
+ * when the target placed it: a whole subnet is not trusted because one phone
1612
+ * is on it.
1613
+ */
1614
+ function mobileOrigins(scheme, metro) {
1615
+ return [
1616
+ `${scheme}://`,
1617
+ `${scheme}://*`,
1618
+ ...(metro?.hosts ?? []).flatMap((host) => [`exp://${host}:${metro?.port ?? "*"}`, `exp://${host}:${metro?.port ?? "*"}/**`])
1619
+ ];
1620
+ }
1621
+ /** Whether an origin is a web one — what a cookie domain is derived from. */
1622
+ function isWebOrigin(origin) {
1623
+ return origin.startsWith("http://") || origin.startsWith("https://");
1624
+ }
1625
+ //#endregion
1626
+ //#region src/origins.ts
1627
+ /**
1628
+ * Whether a request from `origin` comes from one of `trusted`.
1629
+ *
1630
+ * An entry matches exactly — scheme, host and port — or, written
1631
+ * `https://*.example.com`, matches any one label in place of the `*`:
1632
+ * `https://acme.example.com`, never `https://example.com` and never
1633
+ * `https://a.b.example.com`. That is the origin a wildcard site's tenants
1634
+ * call from, and it is as wide as a wildcard certificate, no wider.
1635
+ *
1636
+ * A bare `*` trusts nothing: a surface that answers any origin has not said
1637
+ * which sites are its own.
1638
+ */
1639
+ function trustsOrigin(origin, trusted) {
1640
+ const request = parse(origin);
1641
+ if (!request) return false;
1642
+ return trusted.some((entry) => {
1643
+ const allowed = parse(entry);
1644
+ if (!allowed) return false;
1645
+ if (allowed.scheme !== request.scheme) return false;
1646
+ if (allowed.port !== request.port) return false;
1647
+ const domain = wildcardDomainOf(allowed.host);
1648
+ if (domain === void 0) return allowed.host === request.host;
1649
+ const dot = request.host.indexOf(".");
1650
+ return dot > 0 && LABEL.test(request.host.slice(0, dot)) && request.host.slice(dot + 1) === domain;
1651
+ });
1652
+ }
1653
+ /**
1654
+ * The domain under a wildcard host — `example.com` for `*.example.com` — or
1655
+ * `undefined` for a host that is not one.
1656
+ */
1657
+ function wildcardDomainOf(host) {
1658
+ return host.startsWith("*.") ? host.slice(2) : void 0;
1659
+ }
1660
+ /** One DNS label, as a tenant's slug is. */
1661
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1662
+ function parse(origin) {
1663
+ if (!origin || origin === "*") return void 0;
1664
+ try {
1665
+ const url = new URL(origin);
1666
+ if (url.origin === "null") return void 0;
1667
+ return {
1668
+ scheme: url.protocol,
1669
+ host: url.hostname.toLowerCase(),
1670
+ port: url.port
1671
+ };
1672
+ } catch {
1673
+ return;
1674
+ }
1675
+ }
1676
+ //#endregion
1677
+ //#region src/secret.ts
1678
+ /**
1679
+ * What a generated secret looks like, and the one way every stage draws it.
1680
+ *
1681
+ * A server deploy draws from `crypto`, `gkm dev` and `gkm test` from a hash of
1682
+ * the project, stage and id, and an AWS deploy asks Pulumi for the same
1683
+ * alphabet. Sharing this is what keeps a password that passes a third party's
1684
+ * rules on one stage from failing them on the next.
1685
+ */
1686
+ /** 43 characters from 64 is 256 bits — as much as anything here needs. */
1687
+ const SECRET_LENGTH = 43;
1688
+ /**
1689
+ * Two symbols nothing has to escape — not a URL, a connection string, a shell
1690
+ * or a `.env` file — which with letters and digits is base64url's alphabet.
1691
+ */
1692
+ const SECRET_SYMBOLS = "-_";
1693
+ const LETTERS_AND_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1694
+ /**
1695
+ * A secret in `format`, each character chosen by `pick(n)` — an integer in
1696
+ * `[0, n)` from whatever source the caller trusts.
1697
+ *
1698
+ * When there are symbols, one is guaranteed: a rule that demands a symbol is
1699
+ * the reason anyone names them, and leaving it to chance fails it often —
1700
+ * about one draw in seven at 24 characters.
1701
+ */
1702
+ function drawSecret(pick, format = {}) {
1703
+ const length = format.length ?? 43;
1704
+ const symbols = [...new Set(format.symbols ?? "-_")].join("");
1705
+ const alphabet = LETTERS_AND_DIGITS + symbols;
1706
+ const chars = Array.from({ length }, () => alphabet[pick(alphabet.length)]);
1707
+ if (symbols && !chars.some((char) => symbols.includes(char))) chars[pick(length)] = symbols[pick(symbols.length)];
1708
+ return chars.join("");
1709
+ }
1710
+ //#endregion
1711
+ //#region src/websocket.ts
1712
+ /**
1713
+ * The `apigateway://` string a `WebSocketApi`'s publisher reads on AWS.
1714
+ *
1715
+ * Here because two packages meet on it: `@geekmidas/cloud` composes it from
1716
+ * the API Gateway WebSocket API and the connection table it provisioned, and
1717
+ * `@geekmidas/constructs` parses it to reach them. One codec, so the two
1718
+ * cannot disagree about a parameter's name.
1719
+ *
1720
+ * On a server stage the same key is a `redis://` string — whichever replica
1721
+ * holds the socket delivers. On AWS the gateway holds every socket: a send is
1722
+ * a call to its management API, and a broadcast reads the ids it would fan out
1723
+ * to from the table.
1724
+ */
1725
+ const API_GATEWAY_WEBSOCKET_SCHEME = "apigateway:";
1726
+ /**
1727
+ * `apigateway://<region>?endpoint=<management url>&table=<name>[&tableEndpoint=<url>]`
1728
+ */
1729
+ function apiGatewayWebSocketUrl(target) {
1730
+ const query = new URLSearchParams({
1731
+ endpoint: target.endpoint,
1732
+ table: target.table,
1733
+ ...target.tableEndpoint ? { tableEndpoint: target.tableEndpoint } : {}
1734
+ });
1735
+ return `${API_GATEWAY_WEBSOCKET_SCHEME}//${target.region}?${query}`;
1736
+ }
1737
+ /** An `apigateway://` string missing what a publisher needs to reach a socket. */
1738
+ var InvalidApiGatewayWebSocketUrl = class extends Error {
1739
+ missing;
1740
+ constructor(missing) {
1741
+ 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.`);
1742
+ this.missing = missing;
1743
+ this.name = "InvalidApiGatewayWebSocketUrl";
1744
+ }
1745
+ };
1746
+ /** What an `apigateway://` string names. */
1747
+ function parseApiGatewayWebSocketUrl(value) {
1748
+ const url = new URL(value);
1749
+ if (url.protocol !== "apigateway:" || !url.hostname) throw new InvalidApiGatewayWebSocketUrl("region");
1750
+ const endpoint = url.searchParams.get("endpoint");
1751
+ if (!endpoint) throw new InvalidApiGatewayWebSocketUrl("endpoint");
1752
+ const table = url.searchParams.get("table");
1753
+ if (!table) throw new InvalidApiGatewayWebSocketUrl("table");
1754
+ const tableEndpoint = url.searchParams.get("tableEndpoint");
1755
+ return {
1756
+ region: url.hostname,
1757
+ endpoint,
1758
+ table,
1759
+ ...tableEndpoint ? { tableEndpoint } : {}
1760
+ };
1761
+ }
1762
+ //#endregion
1763
+ exports.API_GATEWAY_WEBSOCKET_SCHEME = API_GATEWAY_WEBSOCKET_SCHEME;
1764
+ exports.CLIENT_IP_HEADER = CLIENT_IP_HEADER;
1765
+ exports.DATABASE_FOLDERS = DATABASE_FOLDERS;
1766
+ exports.DEFAULT_DERIVED_DAYS = DEFAULT_DERIVED_DAYS;
1009
1767
  exports.DEFAULT_POSTGRES_VERSION = DEFAULT_POSTGRES_VERSION;
1768
+ exports.DEFAULT_SENDER = DEFAULT_SENDER;
1769
+ exports.DEFAULT_STAGE_URL = DEFAULT_STAGE_URL;
1770
+ exports.DERIVED_PREFIX = DERIVED_PREFIX;
1010
1771
  exports.DERIVES_FROM = DERIVES_FROM;
1772
+ exports.EDGE_TOKEN_HEADER = EDGE_TOKEN_HEADER;
1773
+ exports.EDGE_TOKEN_KEY = EDGE_TOKEN_KEY;
1774
+ exports.FILE_SERVER_SUFFIX = FILE_SERVER_SUFFIX;
1775
+ exports.HostLabelBothAliasAndRedirect = HostLabelBothAliasAndRedirect;
1776
+ exports.IMAGE_ORIGINS_KEY = IMAGE_ORIGINS_KEY;
1777
+ exports.INBOX_EVENT = INBOX_EVENT;
1778
+ exports.INBOX_MESSAGES_PREFIX = INBOX_MESSAGES_PREFIX;
1011
1779
  exports.IllegalDerivation = IllegalDerivation;
1780
+ exports.InvalidApiGatewayWebSocketUrl = InvalidApiGatewayWebSocketUrl;
1012
1781
  exports.InvalidConstructId = InvalidConstructId;
1782
+ exports.InvalidHostLabel = InvalidHostLabel;
1783
+ exports.KMS_SCHEME = KMS_SCHEME;
1784
+ exports.MAPS_ROLES = MAPS_ROLES;
1785
+ exports.MIGRATIONS_ROOT = MIGRATIONS_ROOT;
1786
+ exports.NoUrlForStage = NoUrlForStage;
1013
1787
  exports.PUBLIC = PUBLIC;
1014
1788
  exports.PUBLIC_PREFIX = PUBLIC_PREFIX;
1789
+ exports.PUBLIC_STAGE_KEYS = PUBLIC_STAGE_KEYS;
1790
+ exports.SECRET_LENGTH = SECRET_LENGTH;
1791
+ exports.SECRET_SYMBOLS = SECRET_SYMBOLS;
1792
+ exports.TELEMETRY_KEYS = TELEMETRY_KEYS;
1015
1793
  exports.UnknownParent = UnknownParent;
1794
+ exports.WILDCARD_SUBDOMAIN = WILDCARD_SUBDOMAIN;
1795
+ exports.WildcardSiteCannotHaveAliases = WildcardSiteCannotHaveAliases;
1796
+ exports.apiGatewayWebSocketUrl = apiGatewayWebSocketUrl;
1016
1797
  exports.assertDerivations = assertDerivations;
1798
+ exports.assertHostLabels = assertHostLabels;
1799
+ exports.assertSubdomainLabel = assertSubdomainLabel;
1800
+ exports.bucketExpiry = bucketExpiry;
1017
1801
  exports.cacheTable = cacheTable;
1018
1802
  exports.canonicalId = canonicalId;
1019
1803
  exports.cloudName = cloudName;
1020
1804
  exports.cookieDomain = cookieDomain;
1805
+ exports.databaseFolder = databaseFolder;
1021
1806
  exports.dependenciesOf = dependenciesOf;
1022
1807
  exports.dependentsOf = dependentsOf;
1808
+ exports.drawSecret = drawSecret;
1023
1809
  exports.environmentCase = environmentCase;
1024
- exports.flattenManifestField = flattenManifestField;
1810
+ exports.externalApiUrl = externalApiUrl;
1811
+ exports.fileServerName = fileServerName;
1812
+ exports.fileServerSurfaceId = fileServerSurfaceId;
1813
+ exports.hostLabels = hostLabels;
1814
+ exports.imageOriginSources = imageOriginSources;
1815
+ exports.imageOrigins = imageOrigins;
1816
+ exports.imageOriginsFor = imageOriginsFor;
1817
+ exports.inboxDomain = inboxDomain;
1818
+ exports.inboxRecipient = inboxRecipient;
1025
1819
  exports.isDerived = isDerived;
1820
+ exports.isHostedDeclaration = isHostedDeclaration;
1821
+ exports.isMapsCallerKey = isMapsCallerKey;
1822
+ exports.isPublicDeclaration = isPublicDeclaration;
1823
+ exports.isWebOrigin = isWebOrigin;
1824
+ exports.isWildcardSite = isWildcardSite;
1026
1825
  exports.kebabCase = kebabCase;
1027
- exports.provideKey = provideKey;
1826
+ exports.kmsUrl = kmsUrl;
1827
+ exports.mapsCallerOf = mapsCallerOf;
1828
+ exports.mapsKeyOf = mapsKeyOf;
1829
+ exports.mapsRoleOf = mapsRoleOf;
1830
+ exports.mapsRolesFor = mapsRolesFor;
1831
+ exports.migrationFolder = migrationFolder;
1832
+ exports.migrationTargets = migrationTargets;
1833
+ exports.mobileOrigins = mobileOrigins;
1834
+ exports.parseApiGatewayWebSocketUrl = parseApiGatewayWebSocketUrl;
1028
1835
  exports.providedKeyFor = providedKeyFor;
1029
1836
  exports.provisionOrder = provisionOrder;
1030
1837
  exports.publicEnvFor = publicEnvFor;
1838
+ exports.publicStageKey = publicStageKey;
1839
+ exports.publicValues = publicValues;
1840
+ exports.reachesServerHalf = reachesServerHalf;
1841
+ exports.receiptRecipients = receiptRecipients;
1842
+ exports.schemeBase = schemeBase;
1031
1843
  exports.scopedName = scopedName;
1844
+ exports.seedFolder = seedFolder;
1845
+ exports.senderAddress = senderAddress;
1846
+ exports.senderDomain = senderDomain;
1032
1847
  exports.serviceKey = serviceKey;
1848
+ exports.trustsOrigin = trustsOrigin;
1849
+ exports.wildcardDomainOf = wildcardDomainOf;
1850
+
1033
1851
  //# sourceMappingURL=index.cjs.map