@openhi/platform 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/lib/{openhi.d.ts → index.d.mts} +42 -16
  2. package/lib/index.d.ts +195 -2
  3. package/lib/index.js +825 -17
  4. package/lib/index.js.map +1 -0
  5. package/lib/index.mjs +818 -0
  6. package/lib/index.mjs.map +1 -0
  7. package/package.json +33 -24
  8. package/lib/openhi.js +0 -108
  9. package/lib/service.d.ts +0 -36
  10. package/lib/service.js +0 -203
  11. package/lib/templates/generate-templates.d.ts +0 -5
  12. package/lib/templates/generate-templates.js +0 -45
  13. package/lib/templates/service-template.d.ts +0 -33
  14. package/lib/templates/service-template.js +0 -42
  15. package/lib/templates/src/README.md.d.ts +0 -5
  16. package/lib/templates/src/README.md.js +0 -19
  17. package/lib/templates/src/app-test.d.ts +0 -5
  18. package/lib/templates/src/app-test.js +0 -61
  19. package/lib/templates/src/app.d.ts +0 -5
  20. package/lib/templates/src/app.js +0 -27
  21. package/lib/templates/src/config.d.ts +0 -5
  22. package/lib/templates/src/config.js +0 -23
  23. package/lib/templates/src/data/README.md.d.ts +0 -5
  24. package/lib/templates/src/data/README.md.js +0 -19
  25. package/lib/templates/src/data/models/README.md.d.ts +0 -5
  26. package/lib/templates/src/data/models/README.md.js +0 -19
  27. package/lib/templates/src/infrastructure/README.md.d.ts +0 -5
  28. package/lib/templates/src/infrastructure/README.md.js +0 -19
  29. package/lib/templates/src/integrations/README.md.d.ts +0 -5
  30. package/lib/templates/src/integrations/README.md.js +0 -19
  31. package/lib/templates/src/main.d.ts +0 -5
  32. package/lib/templates/src/main.js +0 -15
  33. package/lib/templates/src/workflows/README.md.d.ts +0 -5
  34. package/lib/templates/src/workflows/README.md.js +0 -19
  35. package/lib/workflows/aws-teardown-workflow.d.ts +0 -13
  36. package/lib/workflows/aws-teardown-workflow.js +0 -222
  37. package/lib/workflows/build-dev-workflow.d.ts +0 -12
  38. package/lib/workflows/build-dev-workflow.js +0 -48
  39. package/lib/workflows/build-stage-workflow.d.ts +0 -12
  40. package/lib/workflows/build-stage-workflow.js +0 -60
package/lib/index.mjs ADDED
@@ -0,0 +1,818 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../config/lib/open-hi-config.js
28
+ var require_open_hi_config = __commonJS({
29
+ "../config/lib/open-hi-config.js"(exports) {
30
+ "use strict";
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.OPEN_HI_DEPLOYMENT_TARGET_ROLE = exports.OPEN_HI_STAGE = void 0;
33
+ exports.OPEN_HI_STAGE = {
34
+ /**
35
+ * Development environment, typically used for testing and development.
36
+ */
37
+ DEV: "dev",
38
+ /**
39
+ * Staging environment, used for pre-production testing.
40
+ */
41
+ STAGE: "stage",
42
+ /**
43
+ * Production environment, used for live deployments.
44
+ */
45
+ PROD: "prod"
46
+ };
47
+ exports.OPEN_HI_DEPLOYMENT_TARGET_ROLE = {
48
+ /**
49
+ * The primary deployment target for this stage (main account/region).
50
+ * For example, the base DynamoDB region for global tables.
51
+ */
52
+ PRIMARY: "primary",
53
+ /**
54
+ * A secondary deployment target for this stage (additional account/region).
55
+ * For example, a replica region for a global DynamoDB table, or another cell in the same region.
56
+ */
57
+ SECONDARY: "secondary"
58
+ };
59
+ }
60
+ });
61
+
62
+ // ../config/lib/index.js
63
+ var require_lib = __commonJS({
64
+ "../config/lib/index.js"(exports) {
65
+ "use strict";
66
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
67
+ if (k2 === void 0) k2 = k;
68
+ var desc = Object.getOwnPropertyDescriptor(m, k);
69
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
70
+ desc = { enumerable: true, get: function() {
71
+ return m[k];
72
+ } };
73
+ }
74
+ Object.defineProperty(o, k2, desc);
75
+ }) : (function(o, m, k, k2) {
76
+ if (k2 === void 0) k2 = k;
77
+ o[k2] = m[k];
78
+ }));
79
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
80
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
81
+ };
82
+ Object.defineProperty(exports, "__esModule", { value: true });
83
+ __exportStar(require_open_hi_config(), exports);
84
+ }
85
+ });
86
+
87
+ // src/openhi.ts
88
+ import { merge } from "ts-deepmerge";
89
+
90
+ // src/service.ts
91
+ var import_config2 = __toESM(require_lib());
92
+ import { sep as sep2 } from "path";
93
+ import {
94
+ AwsDeploymentTarget,
95
+ TurboRepo,
96
+ VERSION
97
+ } from "@codedrifters/configulator";
98
+ import { paramCase, pascalCase } from "change-case";
99
+ import { awscdk } from "projen";
100
+ import { NodePackageManager, Transform } from "projen/lib/javascript";
101
+
102
+ // src/templates/service-template.ts
103
+ import { existsSync, unlinkSync } from "fs";
104
+ import { sep } from "path";
105
+ import { SampleFile } from "projen";
106
+ var ServiceTemplate = class {
107
+ constructor(service, options) {
108
+ this.service = service;
109
+ this.options = options;
110
+ this.fullFilePath = [
111
+ this.service.project.outdir,
112
+ this.options.filePath
113
+ ].join(sep);
114
+ this.createTemplate();
115
+ }
116
+ createTemplate() {
117
+ if (this.options.overwrite) {
118
+ this.overwriteTemplate();
119
+ }
120
+ this.file = new SampleFile(this.service.project, this.options.filePath, {
121
+ contents: this.options.contents.join("\n")
122
+ });
123
+ }
124
+ overwriteTemplate() {
125
+ if (existsSync(this.fullFilePath)) {
126
+ unlinkSync(this.fullFilePath);
127
+ }
128
+ this.file = void 0;
129
+ }
130
+ };
131
+
132
+ // src/templates/src/app.ts
133
+ var SrcApp = class extends ServiceTemplate {
134
+ constructor(service, options) {
135
+ super(service, {
136
+ ...options,
137
+ filePath: "src/app.ts",
138
+ contents: [
139
+ `import { OpenHiApp, ${service.constructName} } from "@openhi/constructs";`,
140
+ `import { CONFIG } from "./config";`,
141
+ ``,
142
+ `const app = new OpenHiApp({ config: CONFIG });`,
143
+ ``,
144
+ `const stacks = app.environments.map((e) => {`,
145
+ ` return new ${service.constructName}(e, { config: e.config });`,
146
+ `});`,
147
+ ``,
148
+ `export { app, stacks };`,
149
+ ``
150
+ ]
151
+ });
152
+ }
153
+ };
154
+
155
+ // src/templates/src/app-test.ts
156
+ var SrcAppTest = class extends ServiceTemplate {
157
+ constructor(service, options) {
158
+ super(service, {
159
+ ...options,
160
+ filePath: "src/app.test.ts",
161
+ contents: [
162
+ `import { Template } from "aws-cdk-lib/assertions";`,
163
+ `import { Code, type CodeConfig } from "aws-cdk-lib/aws-lambda";`,
164
+ `import { stacks } from "./app"`,
165
+ ``,
166
+ `/** Replace volatile CDK asset S3 keys/buckets with static values for snapshot stability. */`,
167
+ `function normalizeTemplateForSnapshot(template: Record<string, unknown>): Record<string, unknown> {`,
168
+ ` const staticBucket = "mock-assets-bucket";`,
169
+ ` const staticKey = "mock-asset-key.zip";`,
170
+ ` const json = JSON.stringify(template);`,
171
+ ` const normalized = json`,
172
+ ` .replace(/"S3Key":\\s*"[^"]+\\.zip"/g, \\\`"S3Key": "\${staticKey}"\\\`)`,
173
+ ` .replace(/"S3Bucket":\\s*"[^"]+"/g, \\\`"S3Bucket": "\${staticBucket}"\\\`);`,
174
+ ` return JSON.parse(normalized) as Record<string, unknown>;`,
175
+ `}`,
176
+ ``,
177
+ `let fromAssetMock: jest.SpyInstance;`,
178
+ ``,
179
+ `beforeAll(() => {`,
180
+ ` fromAssetMock = jest.spyOn(Code, "fromAsset").mockReturnValue({`,
181
+ ` isInline: false,`,
182
+ ` bind: (): CodeConfig => ({`,
183
+ ` s3Location: {`,
184
+ ` bucketName: "mock-assets-bucket",`,
185
+ ` objectKey: "mock-asset-key.zip",`,
186
+ ` },`,
187
+ ` }),`,
188
+ ` bindToResource: () => {`,
189
+ ` return;`,
190
+ ` },`,
191
+ ` } as any);`,
192
+ `});`,
193
+ ``,
194
+ `afterAll(() => {`,
195
+ ` fromAssetMock?.mockRestore();`,
196
+ `});`,
197
+ ``,
198
+ `describe("Smoke Test", () => {`,
199
+ ` it("should match previous snapshots", () => {`,
200
+ ` stacks.forEach((s) => {`,
201
+ ` const template = Template.fromStack(s).toJSON();`,
202
+ ` expect(normalizeTemplateForSnapshot(template)).toMatchSnapshot();`,
203
+ ` });`,
204
+ ` });`,
205
+ `});`,
206
+ ``
207
+ ]
208
+ });
209
+ }
210
+ };
211
+
212
+ // src/templates/src/config.ts
213
+ import { SourceCode } from "projen";
214
+ var SrcConfig = class extends SourceCode {
215
+ constructor(service) {
216
+ super(service.project, "src/config.ts");
217
+ this.line(`import { OpenHiConfig } from "@openhi/config";`);
218
+ this.line("");
219
+ const start = "export const CONFIG: OpenHiConfig = ";
220
+ const mid = JSON.stringify(service.options?.config, null, 2);
221
+ const end = " as const;";
222
+ this.line(`${start}${mid}${end}`);
223
+ }
224
+ };
225
+
226
+ // src/templates/src/data/models/README.md.ts
227
+ var DataModelsReadMe = class extends ServiceTemplate {
228
+ constructor(service, options) {
229
+ super(service, {
230
+ ...options,
231
+ filePath: "src/data/models/README.md",
232
+ contents: [
233
+ `# ${service.serviceName}: Data Models`,
234
+ ``,
235
+ `This directory contains data model definitions and other related files for the ${service.serviceName} service.`
236
+ ]
237
+ });
238
+ }
239
+ };
240
+
241
+ // src/templates/src/data/README.md.ts
242
+ var DataReadMe = class extends ServiceTemplate {
243
+ constructor(service, options) {
244
+ super(service, {
245
+ ...options,
246
+ filePath: "src/data/README.md",
247
+ contents: [
248
+ `# ${service.serviceName}: Data`,
249
+ ``,
250
+ `This directory contains data models and other related files for the ${service.serviceName} service.`
251
+ ]
252
+ });
253
+ }
254
+ };
255
+
256
+ // src/templates/src/infrastructure/README.md.ts
257
+ var InfrastructureReadMe = class extends ServiceTemplate {
258
+ constructor(service, options) {
259
+ super(service, {
260
+ ...options,
261
+ filePath: "src/infrastructure/README.md",
262
+ contents: [
263
+ `# ${service.serviceName}: Infrastructure`,
264
+ ``,
265
+ `This directory contains infrastructure definitions and other related files for the ${service.serviceName} service.`
266
+ ]
267
+ });
268
+ }
269
+ };
270
+
271
+ // src/templates/src/integrations/README.md.ts
272
+ var IntegrationsReadMe = class extends ServiceTemplate {
273
+ constructor(service, options) {
274
+ super(service, {
275
+ ...options,
276
+ filePath: "src/integrations/README.md",
277
+ contents: [
278
+ `# ${service.serviceName}: Integrations`,
279
+ ``,
280
+ `This directory contains integration definitions and other related files for the ${service.serviceName} service.`
281
+ ]
282
+ });
283
+ }
284
+ };
285
+
286
+ // src/templates/src/main.ts
287
+ var SrcMain = class extends ServiceTemplate {
288
+ constructor(service, options) {
289
+ super(service, {
290
+ ...options,
291
+ filePath: "src/main.ts",
292
+ contents: [`import { app } from "./app";`, ``, `app.synth();`, ``]
293
+ });
294
+ }
295
+ };
296
+
297
+ // src/templates/src/README.md.ts
298
+ var SrcReadMe = class extends ServiceTemplate {
299
+ constructor(service, options) {
300
+ super(service, {
301
+ ...options,
302
+ filePath: "src/README.md",
303
+ contents: [
304
+ `# ${service.serviceName}: Service Overview`,
305
+ ``,
306
+ `This directory contains the main entry point for the ${service.serviceName} service.`
307
+ ]
308
+ });
309
+ }
310
+ };
311
+
312
+ // src/templates/src/workflows/README.md.ts
313
+ var WorkflowsReadMe = class extends ServiceTemplate {
314
+ constructor(service, options) {
315
+ super(service, {
316
+ ...options,
317
+ filePath: "src/workflows/README.md",
318
+ contents: [
319
+ `# ${service.serviceName}: Workflows`,
320
+ ``,
321
+ `This directory contains workflow definitions and other related files for the ${service.serviceName} service.`
322
+ ]
323
+ });
324
+ }
325
+ };
326
+
327
+ // src/templates/generate-templates.ts
328
+ var GenerateTemplates = class {
329
+ constructor(service) {
330
+ this.service = service;
331
+ new SrcApp(this.service);
332
+ new SrcAppTest(this.service);
333
+ new SrcConfig(this.service);
334
+ new SrcMain(this.service);
335
+ new SrcReadMe(this.service);
336
+ new DataReadMe(this.service);
337
+ new DataModelsReadMe(this.service);
338
+ new InfrastructureReadMe(this.service);
339
+ new IntegrationsReadMe(this.service);
340
+ new WorkflowsReadMe(this.service);
341
+ }
342
+ };
343
+
344
+ // src/service.ts
345
+ var OPEN_HI_SERVICE_TYPE = {
346
+ AUTH: "auth",
347
+ DATA_SERVICE: "data",
348
+ GLOBAL: "global",
349
+ INTEGRATION: "integration",
350
+ REST_API: "rest-api"
351
+ };
352
+ var OpenHiService = class {
353
+ constructor(openHi, id, options) {
354
+ this.openHi = openHi;
355
+ this.id = id;
356
+ this.options = options;
357
+ this.addDeploymentTarget = (awsStageType, awsEnvironmentType, envConfig) => {
358
+ new AwsDeploymentTarget(this.project, {
359
+ account: envConfig.account,
360
+ region: envConfig.region,
361
+ awsStageType,
362
+ awsEnvironmentType,
363
+ localDeployment: true,
364
+ localDeploymentConfig: {
365
+ stackPattern: `${awsStageType}/${awsEnvironmentType}/*-${envConfig.account}-${envConfig.region}`,
366
+ roleName: "poweruseraccess"
367
+ },
368
+ ciDeployment: true,
369
+ ciDeploymentConfig: {
370
+ roleArn: `arn:aws:iam::${envConfig.account}:role/GitHubOpenHiDeployer`,
371
+ stackPattern: `${awsStageType}/${awsEnvironmentType}/*-${envConfig.account}-${envConfig.region}`
372
+ },
373
+ branches: awsStageType === import_config2.OPEN_HI_STAGE.DEV ? [
374
+ {
375
+ branch: "feat/*",
376
+ description: [
377
+ "Feature branches for OpenHI (short form).",
378
+ "These branches are used for developing new features."
379
+ ]
380
+ },
381
+ {
382
+ branch: "feature/*",
383
+ description: [
384
+ "Feature branches for OpenHI.",
385
+ "These branches are used for developing new features."
386
+ ]
387
+ },
388
+ {
389
+ branch: "fix/*",
390
+ description: [
391
+ "Fix branches for OpenHI.",
392
+ "This branch pattern is used when a developer is working on a fix on the project."
393
+ ]
394
+ }
395
+ ] : [
396
+ {
397
+ branch: "main",
398
+ description: [
399
+ "Main branch for OpenHI.",
400
+ "This branch is used for the main branch."
401
+ ]
402
+ }
403
+ ]
404
+ });
405
+ };
406
+ this.project = new awscdk.AwsCdkTypeScriptApp({
407
+ /**
408
+ * Top level project config options
409
+ */
410
+ defaultReleaseBranch: "main",
411
+ name: this.serviceName,
412
+ outdir: this.outDir,
413
+ parent: this.openHi.rootProject,
414
+ cdkVersion: this.options?.config?.versions?.cdk?.cdkLibVersion ?? VERSION.AWS_CDK_LIB_VERSION,
415
+ cdkCliVersion: this.options?.config?.versions?.cdk?.cdkCliVersion ?? VERSION.AWS_CDK_CLI_VERSION,
416
+ /**
417
+ * Packaging options
418
+ *
419
+ * TODO: Figure out license for monorepo vs per package?
420
+ */
421
+ licensed: false,
422
+ /**
423
+ * Node configs
424
+ */
425
+ packageManager: NodePackageManager.PNPM,
426
+ /**
427
+ * Turn on prettier formatting
428
+ */
429
+ prettier: true,
430
+ /**
431
+ * Don't generate sample code.
432
+ */
433
+ sampleCode: false,
434
+ /**
435
+ * Make sure jest config is stored outside of package.json and use SWC
436
+ * for faster tests.
437
+ */
438
+ jestOptions: {
439
+ configFilePath: "jest.config.json",
440
+ jestConfig: {
441
+ transform: {
442
+ ["^.+\\.[t]sx?$"]: new Transform("@swc/jest")
443
+ }
444
+ }
445
+ },
446
+ /**
447
+ * SWC for faster testing
448
+ */
449
+ devDeps: ["@swc/jest", "@swc/core"],
450
+ /**
451
+ * Don't package test files.
452
+ */
453
+ npmIgnoreOptions: {
454
+ ignorePatterns: ["*.spec.*", "*.test.*"]
455
+ }
456
+ });
457
+ this.project.deps.removeDependency("ts-jest");
458
+ this.project.addDeps(
459
+ "@openhi/config@workspace:*",
460
+ "@openhi/constructs@workspace:*"
461
+ );
462
+ new TurboRepo(this.project);
463
+ new GenerateTemplates(this);
464
+ [import_config2.OPEN_HI_STAGE.DEV, import_config2.OPEN_HI_STAGE.STAGE, import_config2.OPEN_HI_STAGE.PROD].forEach(
465
+ (stage) => {
466
+ const targets = this.options?.config?.deploymentTargets?.[stage];
467
+ if (targets?.primary) {
468
+ this.addDeploymentTarget(
469
+ stage,
470
+ import_config2.OPEN_HI_DEPLOYMENT_TARGET_ROLE.PRIMARY,
471
+ targets.primary
472
+ );
473
+ }
474
+ targets?.secondary?.forEach((env) => {
475
+ this.addDeploymentTarget(
476
+ stage,
477
+ import_config2.OPEN_HI_DEPLOYMENT_TARGET_ROLE.SECONDARY,
478
+ env
479
+ );
480
+ });
481
+ }
482
+ );
483
+ }
484
+ get constructName() {
485
+ return pascalCase(["open", "hi", this.id, "service"].join("-"));
486
+ }
487
+ get outDir() {
488
+ return [paramCase(this.openHi.id), paramCase(this.id)].join(sep2);
489
+ }
490
+ get serviceName() {
491
+ return [paramCase(this.openHi.id), paramCase(this.id)].join("-");
492
+ }
493
+ };
494
+
495
+ // src/workflows/aws-teardown-workflow.ts
496
+ var import_config3 = __toESM(require_lib());
497
+ import {
498
+ AwsDeploymentConfig,
499
+ MonorepoProject
500
+ } from "@codedrifters/configulator";
501
+ import { Component } from "projen";
502
+ import { GitHub, GithubWorkflow } from "projen/lib/github";
503
+ import { JobPermission } from "projen/lib/github/workflows-model";
504
+ var AwsTeardownWorkflow = class extends Component {
505
+ constructor(rootProject, options) {
506
+ super(rootProject);
507
+ this.rootProject = rootProject;
508
+ const { openhi } = options;
509
+ if (!(rootProject instanceof MonorepoProject)) {
510
+ throw new Error(
511
+ "AwsTeardownWorkflow requires the root project to be a MonorepoProject"
512
+ );
513
+ }
514
+ const github = GitHub.of(this.rootProject);
515
+ if (!github) {
516
+ throw new Error(
517
+ "AwsTeardownWorkflow requires a GitHub component in the root project"
518
+ );
519
+ }
520
+ const devTargetsFor = (service) => AwsDeploymentConfig.of(service.project)?.awsDeploymentTargets.filter(
521
+ (target) => target.awsStageType === import_config3.OPEN_HI_STAGE.DEV && target.ciDeployment
522
+ ) ?? [];
523
+ const awsDestructionTargets = devTargetsFor(openhi.global);
524
+ const workflow = new GithubWorkflow(github, "teardown-dev");
525
+ workflow.on({
526
+ workflowDispatch: {},
527
+ schedule: [
528
+ {
529
+ cron: "32 6 * * *"
530
+ // Every Sunday at 6:32 AM UTC
531
+ }
532
+ ],
533
+ delete: {
534
+ branches: ["feature/*", "feat/*", "fix/*"]
535
+ }
536
+ /* for debugging
537
+ push: {
538
+ branches: ["feature/*"],
539
+ },
540
+ */
541
+ });
542
+ awsDestructionTargets.forEach((target) => {
543
+ const {
544
+ awsStageType,
545
+ awsEnvironmentType,
546
+ account,
547
+ region,
548
+ ciDeploymentConfig
549
+ } = target;
550
+ const { roleArn } = ciDeploymentConfig ?? {};
551
+ workflow.addJob(`teardown-${account}-${region}`.toLowerCase(), {
552
+ name: `Teardown Stacks in ${target.account}/${target.region}`,
553
+ //if: "github.event.ref_type == 'branch'",
554
+ runsOn: ["ubuntu-latest"],
555
+ permissions: {
556
+ contents: JobPermission.READ,
557
+ idToken: JobPermission.WRITE
558
+ },
559
+ env: {
560
+ REPO: "${{ github.repository }}",
561
+ REGIONS: [region].join(" ")
562
+ },
563
+ steps: [
564
+ /**
565
+ * Configure AWS creds.
566
+ */
567
+ {
568
+ name: `AWS Creds ${awsStageType}/${awsEnvironmentType}/${account}/${region}`,
569
+ uses: "aws-actions/configure-aws-credentials@v4",
570
+ with: {
571
+ "role-to-assume": roleArn,
572
+ "aws-region": region,
573
+ "role-duration-seconds": 900
574
+ // 15 minutes
575
+ }
576
+ },
577
+ /**
578
+ * Fetch all branch names in the repo
579
+ */
580
+ {
581
+ name: "Fetch All Branches",
582
+ id: "fetch_branches",
583
+ uses: "actions/github-script@v7",
584
+ with: {
585
+ script: [
586
+ "const all = await github.paginate(github.rest.repos.listBranches, {",
587
+ " owner: context.repo.owner,",
588
+ " repo: context.repo.repo,",
589
+ " per_page: 100",
590
+ "});",
591
+ "const names = all.map(b => b.name);",
592
+ "console.log(`Found branches: ${names}`);",
593
+ 'core.setOutput("json", JSON.stringify(names));'
594
+ ].join("\n")
595
+ }
596
+ },
597
+ /**
598
+ * Save branches to a file
599
+ */
600
+ {
601
+ name: "Save Branches to File",
602
+ run: [
603
+ 'echo "Saving branches to file"',
604
+ "echo '${{ steps.fetch_branches.outputs.json }}' | jq -r '.[]' | sort -u > branches.txt",
605
+ 'echo "Branches:"',
606
+ "cat branches.txt"
607
+ ].join("\n")
608
+ },
609
+ /**
610
+ * Find all stacks tagged with a stage of dev. for this repo. return
611
+ * tag and resource arn.
612
+ */
613
+ {
614
+ name: "Find Stacks by Tag",
615
+ id: "find_stacks",
616
+ run: [
617
+ "set -euo pipefail",
618
+ ": > candidates.txt # columns: arn region branchTag",
619
+ "# Build tag filters",
620
+ 'TAG_FILTERS=( "Key=openhi:repo-name,Values=$REPO" )',
621
+ `TAG_FILTERS+=( "Key=openhi:stage-type,Values=${import_config3.OPEN_HI_STAGE.DEV}" )`,
622
+ "for r in $REGIONS; do",
623
+ ` echo "Scanning region: $r"`,
624
+ " aws resourcegroupstaggingapi get-resources \\",
625
+ ' --region "$r" \\',
626
+ ' --resource-type-filters "cloudformation:stack" \\',
627
+ ' --tag-filters "${TAG_FILTERS[@]}" \\',
628
+ ` | jq -r --arg r "$r" '`,
629
+ " .ResourceTagMappingList[]",
630
+ " | . as $res",
631
+ ' | ($res.Tags[] | select(.Key=="openhi:branch-name") | .Value) as $branch',
632
+ ' | [$res.ResourceARN, $r, ($branch // "")]',
633
+ " | @tsv",
634
+ " ' >> candidates.txt",
635
+ "done",
636
+ "echo 'Tagged stacks:'",
637
+ `(echo -e "ARN\\tREGION\\tBRANCH"; cat candidates.txt) | column -t -s $'\\t'`
638
+ ].join("\n")
639
+ },
640
+ /**
641
+ * Determine which stacks are orphans that no longer have a matching branch.
642
+ * Save those to a file for the next step.
643
+ */
644
+ {
645
+ name: "Determine Orphan Stacks (No Matching Branch)",
646
+ run: [
647
+ "set -euo pipefail",
648
+ ": > orphans.txt # arn region branch",
649
+ "while IFS=$'\\t' read -r arn region branch; do",
650
+ ' [ -z "$arn" ] && continue',
651
+ ' if [ -z "$branch" ]; then',
652
+ " # If no Branch tag, treat as not-a-preview; skip (or flip to delete if you want)",
653
+ " continue",
654
+ " fi",
655
+ ' if ! grep -Fxq "$branch" branches.txt; then',
656
+ ' echo -e "$arn\\t$region\\t$branch" >> orphans.txt',
657
+ " fi",
658
+ "done < candidates.txt",
659
+ "",
660
+ "if [ -s orphans.txt ]; then",
661
+ ' echo "Orphan stacks (no matching branch):"',
662
+ ` (echo -e "ARN\\tREGION\\tBRANCH"; cat orphans.txt) | column -t -s $'\\t'`,
663
+ "else",
664
+ ' echo "No orphan stacks found."',
665
+ "fi"
666
+ ].join("\n")
667
+ },
668
+ /**
669
+ * Delete orphan stacks.
670
+ */
671
+ {
672
+ name: "Delete Orphan Stacks",
673
+ if: "hashFiles('orphans.txt') != ''",
674
+ run: [
675
+ "set -euo pipefail",
676
+ "while IFS=$'\\t' read -r arn region branch; do",
677
+ ' [ -z "$arn" ] && continue',
678
+ ` stack_name=$(cut -d'/' -f2 <<<"$arn")`,
679
+ ' echo "Deleting $stack_name (branch=$branch) in $region"',
680
+ ' aws cloudformation delete-stack --region "$region" --stack-name "$stack_name" || true',
681
+ "done < orphans.txt"
682
+ ].join("\n")
683
+ }
684
+ ]
685
+ });
686
+ });
687
+ }
688
+ };
689
+
690
+ // src/workflows/build-dev-workflow.ts
691
+ import { AwsDeployWorkflow } from "@codedrifters/configulator";
692
+ import { Component as Component2 } from "projen";
693
+ var BuildDevelopmentWorkflow = class extends Component2 {
694
+ constructor(parent, options) {
695
+ super(parent, "dev-workflow");
696
+ const { openhi } = options;
697
+ const { awsDeploymentTargets: globalTargets } = new AwsDeployWorkflow(
698
+ openhi.global.project,
699
+ {
700
+ buildWorkflow: parent.buildWorkflow
701
+ }
702
+ );
703
+ const { awsDeploymentTargets: authTargets } = new AwsDeployWorkflow(
704
+ openhi.auth.project,
705
+ {
706
+ buildWorkflow: parent.buildWorkflow,
707
+ deployAfterTargets: [...globalTargets]
708
+ }
709
+ );
710
+ const { awsDeploymentTargets: dataTargets } = new AwsDeployWorkflow(
711
+ openhi.data.project,
712
+ {
713
+ buildWorkflow: parent.buildWorkflow,
714
+ deployAfterTargets: [...globalTargets, ...authTargets]
715
+ }
716
+ );
717
+ new AwsDeployWorkflow(openhi.restApi.project, {
718
+ buildWorkflow: parent.buildWorkflow,
719
+ deployAfterTargets: [...globalTargets, ...authTargets, ...dataTargets]
720
+ });
721
+ }
722
+ };
723
+
724
+ // src/workflows/build-stage-workflow.ts
725
+ var import_config4 = __toESM(require_lib());
726
+ import { AwsDeployWorkflow as AwsDeployWorkflow2 } from "@codedrifters/configulator";
727
+ import { Component as Component3 } from "projen";
728
+ var BuildStageWorkflow = class extends Component3 {
729
+ constructor(parent, options) {
730
+ super(parent, "stage-workflow");
731
+ const { openhi } = options;
732
+ const { awsDeploymentTargets: globalTargets, buildWorkflow } = new AwsDeployWorkflow2(openhi.global.project, {
733
+ awsStageType: import_config4.OPEN_HI_STAGE.STAGE,
734
+ buildWorkflowOptions: {
735
+ name: "deploy-stage",
736
+ workflowTriggers: {
737
+ push: {
738
+ branches: ["main"]
739
+ },
740
+ workflowDispatch: {}
741
+ }
742
+ }
743
+ });
744
+ const { awsDeploymentTargets: authTargets } = new AwsDeployWorkflow2(
745
+ openhi.auth.project,
746
+ {
747
+ awsStageType: import_config4.OPEN_HI_STAGE.STAGE,
748
+ buildWorkflow,
749
+ deployAfterTargets: [...globalTargets]
750
+ }
751
+ );
752
+ const { awsDeploymentTargets: dataTargets } = new AwsDeployWorkflow2(
753
+ openhi.data.project,
754
+ {
755
+ awsStageType: import_config4.OPEN_HI_STAGE.STAGE,
756
+ buildWorkflow,
757
+ deployAfterTargets: [...globalTargets, ...authTargets]
758
+ }
759
+ );
760
+ new AwsDeployWorkflow2(openhi.restApi.project, {
761
+ awsStageType: import_config4.OPEN_HI_STAGE.STAGE,
762
+ buildWorkflow,
763
+ deployAfterTargets: [...globalTargets, ...authTargets, ...dataTargets]
764
+ });
765
+ }
766
+ };
767
+
768
+ // src/openhi.ts
769
+ var OpenHi = class {
770
+ constructor(options = {}) {
771
+ this.options = merge({ name: "openhi" }, options);
772
+ this.rootProject = this.options.rootProject;
773
+ this.id = this.options.rootProject?.name ?? "openhi";
774
+ if (!this.rootProject) {
775
+ throw new Error(
776
+ "OpenHi requires a MonorepoProject to be passed in via the rootProject option"
777
+ );
778
+ }
779
+ const rootProject = this.rootProject;
780
+ this.global = new OpenHiService(this, "global", {
781
+ type: OPEN_HI_SERVICE_TYPE.GLOBAL,
782
+ config: merge(
783
+ this.options?.defaultConfig ?? {},
784
+ this.options?.globalServiceConfig ?? {}
785
+ )
786
+ });
787
+ this.auth = new OpenHiService(this, "auth", {
788
+ type: OPEN_HI_SERVICE_TYPE.AUTH,
789
+ config: merge(
790
+ this.options?.defaultConfig ?? {},
791
+ this.options?.authServiceConfig ?? {}
792
+ )
793
+ });
794
+ this.restApi = new OpenHiService(this, "rest-api", {
795
+ type: OPEN_HI_SERVICE_TYPE.REST_API,
796
+ config: merge(
797
+ this.options?.defaultConfig ?? {},
798
+ this.options?.restApiServiceConfig ?? {}
799
+ )
800
+ });
801
+ this.data = new OpenHiService(this, "data", {
802
+ type: OPEN_HI_SERVICE_TYPE.DATA_SERVICE,
803
+ config: merge(
804
+ this.options?.defaultConfig ?? {},
805
+ this.options?.dataServiceConfig ?? {}
806
+ )
807
+ });
808
+ new BuildDevelopmentWorkflow(rootProject, { openhi: this });
809
+ new BuildStageWorkflow(rootProject, { openhi: this });
810
+ new AwsTeardownWorkflow(rootProject, { openhi: this });
811
+ }
812
+ };
813
+ export {
814
+ OPEN_HI_SERVICE_TYPE,
815
+ OpenHi,
816
+ OpenHiService
817
+ };
818
+ //# sourceMappingURL=index.mjs.map