@stripe/extensibility-dev-tools 0.23.5

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 (253) hide show
  1. package/LICENSE.md +19 -0
  2. package/dist/bin/build-custom-object-definitions.cjs +2111 -0
  3. package/dist/bin/build-custom-object-definitions.d.ts +11 -0
  4. package/dist/bin/build-custom-object-definitions.d.ts.map +1 -0
  5. package/dist/bin/build-custom-object-definitions.js +2088 -0
  6. package/dist/bin/create-upload-image.cjs +2136 -0
  7. package/dist/bin/create-upload-image.d.ts +17 -0
  8. package/dist/bin/create-upload-image.d.ts.map +1 -0
  9. package/dist/bin/create-upload-image.js +2113 -0
  10. package/dist/bin/dev-tools-rpc.cjs +3874 -0
  11. package/dist/bin/dev-tools-rpc.d.ts +3 -0
  12. package/dist/bin/dev-tools-rpc.d.ts.map +1 -0
  13. package/dist/bin/dev-tools-rpc.js +3864 -0
  14. package/dist/bin/gen-schemas.cjs +20739 -0
  15. package/dist/bin/gen-schemas.d.ts +8 -0
  16. package/dist/bin/gen-schemas.d.ts.map +1 -0
  17. package/dist/bin/gen-schemas.js +20715 -0
  18. package/dist/bin/gen-workspace.cjs +3847 -0
  19. package/dist/bin/gen-workspace.d.ts +8 -0
  20. package/dist/bin/gen-workspace.d.ts.map +1 -0
  21. package/dist/bin/gen-workspace.js +3841 -0
  22. package/dist/bin/manifest.cjs +686 -0
  23. package/dist/bin/manifest.d.ts +10 -0
  24. package/dist/bin/manifest.d.ts.map +1 -0
  25. package/dist/bin/manifest.js +663 -0
  26. package/dist/bin/rpc/dispatch.d.ts +10 -0
  27. package/dist/bin/rpc/dispatch.d.ts.map +1 -0
  28. package/dist/bin/rpc/handlers.d.ts +4 -0
  29. package/dist/bin/rpc/handlers.d.ts.map +1 -0
  30. package/dist/bin/rpc/types.d.ts +29 -0
  31. package/dist/bin/rpc/types.d.ts.map +1 -0
  32. package/dist/bin/template-info.cjs +1511 -0
  33. package/dist/bin/template-info.d.ts +9 -0
  34. package/dist/bin/template-info.d.ts.map +1 -0
  35. package/dist/bin/template-info.js +1488 -0
  36. package/dist/custom-objects/build-definitions.d.ts +98 -0
  37. package/dist/custom-objects/build-definitions.d.ts.map +1 -0
  38. package/dist/custom-objects/generated/proto/custom_objects/pub/api/app_api/object_definitions_app_service.pb.d.ts +191 -0
  39. package/dist/custom-objects/generated/proto/custom_objects/pub/api/app_api/object_definitions_app_service.pb.d.ts.map +1 -0
  40. package/dist/custom-objects/generated/proto/custom_objects/pub/api/common/schema.pb.d.ts +131 -0
  41. package/dist/custom-objects/generated/proto/custom_objects/pub/api/common/schema.pb.d.ts.map +1 -0
  42. package/dist/custom-objects/generated/proto/google/protobuf/descriptor.pb.d.ts +1482 -0
  43. package/dist/custom-objects/generated/proto/google/protobuf/descriptor.pb.d.ts.map +1 -0
  44. package/dist/custom-objects/generated/proto/google/protobuf/timestamp.pb.d.ts +167 -0
  45. package/dist/custom-objects/generated/proto/google/protobuf/timestamp.pb.d.ts.map +1 -0
  46. package/dist/custom-objects/generated/proto/proto/annotations.pb.d.ts +64 -0
  47. package/dist/custom-objects/generated/proto/proto/annotations.pb.d.ts.map +1 -0
  48. package/dist/custom-objects/generated/proto/proto/extensions.pb.d.ts +657 -0
  49. package/dist/custom-objects/generated/proto/proto/extensions.pb.d.ts.map +1 -0
  50. package/dist/custom-objects/generated/proto/vendor/metadata/pub/api/api_metadata.pb.d.ts +105 -0
  51. package/dist/custom-objects/generated/proto/vendor/metadata/pub/api/api_metadata.pb.d.ts.map +1 -0
  52. package/dist/custom-objects/generated/proto/vendor/net/idempotency/idempotency_model.pb.d.ts +79 -0
  53. package/dist/custom-objects/generated/proto/vendor/net/idempotency/idempotency_model.pb.d.ts.map +1 -0
  54. package/dist/custom-objects/generated/proto/vendor/publicapi/api_group_enum.pb.d.ts +129 -0
  55. package/dist/custom-objects/generated/proto/vendor/publicapi/api_group_enum.pb.d.ts.map +1 -0
  56. package/dist/custom-objects/generated/proto/vendor/publicapi/api_visibility.pb.d.ts +76 -0
  57. package/dist/custom-objects/generated/proto/vendor/publicapi/api_visibility.pb.d.ts.map +1 -0
  58. package/dist/custom-objects/generated/proto/vendor/publicapi/customize_dispatch_middleware_enum.pb.d.ts +78 -0
  59. package/dist/custom-objects/generated/proto/vendor/publicapi/customize_dispatch_middleware_enum.pb.d.ts.map +1 -0
  60. package/dist/custom-objects/generated/proto/vendor/publicapi/docs_namespace_group_enum.pb.d.ts +146 -0
  61. package/dist/custom-objects/generated/proto/vendor/publicapi/docs_namespace_group_enum.pb.d.ts.map +1 -0
  62. package/dist/custom-objects/generated/proto/vendor/publicapi/documented_enum.pb.d.ts +76 -0
  63. package/dist/custom-objects/generated/proto/vendor/publicapi/documented_enum.pb.d.ts.map +1 -0
  64. package/dist/custom-objects/generated/proto/vendor/publicapi/event_scope_enum.pb.d.ts +92 -0
  65. package/dist/custom-objects/generated/proto/vendor/publicapi/event_scope_enum.pb.d.ts.map +1 -0
  66. package/dist/custom-objects/generated/proto/vendor/publicapi/extension_interface.pb.d.ts +124 -0
  67. package/dist/custom-objects/generated/proto/vendor/publicapi/extension_interface.pb.d.ts.map +1 -0
  68. package/dist/custom-objects/generated/proto/vendor/publicapi/feature_enum.pb.d.ts +1070 -0
  69. package/dist/custom-objects/generated/proto/vendor/publicapi/feature_enum.pb.d.ts.map +1 -0
  70. package/dist/custom-objects/generated/proto/vendor/publicapi/field_validation_rules.pb.d.ts +279 -0
  71. package/dist/custom-objects/generated/proto/vendor/publicapi/field_validation_rules.pb.d.ts.map +1 -0
  72. package/dist/custom-objects/generated/proto/vendor/publicapi/flavor_enum.pb.d.ts +78 -0
  73. package/dist/custom-objects/generated/proto/vendor/publicapi/flavor_enum.pb.d.ts.map +1 -0
  74. package/dist/custom-objects/generated/proto/vendor/publicapi/http_error_status.pb.d.ts +102 -0
  75. package/dist/custom-objects/generated/proto/vendor/publicapi/http_error_status.pb.d.ts.map +1 -0
  76. package/dist/custom-objects/generated/proto/vendor/publicapi/method_kind_enum.pb.d.ts +86 -0
  77. package/dist/custom-objects/generated/proto/vendor/publicapi/method_kind_enum.pb.d.ts.map +1 -0
  78. package/dist/custom-objects/generated/proto/vendor/publicapi/method_priority.pb.d.ts +80 -0
  79. package/dist/custom-objects/generated/proto/vendor/publicapi/method_priority.pb.d.ts.map +1 -0
  80. package/dist/custom-objects/generated/proto/vendor/publicapi/permission_check_enum.pb.d.ts +74 -0
  81. package/dist/custom-objects/generated/proto/vendor/publicapi/permission_check_enum.pb.d.ts.map +1 -0
  82. package/dist/custom-objects/generated/proto/vendor/publicapi/redaction_enum.pb.d.ts +76 -0
  83. package/dist/custom-objects/generated/proto/vendor/publicapi/redaction_enum.pb.d.ts.map +1 -0
  84. package/dist/custom-objects/generated/proto/vendor/publicapi/region_routers.pb.d.ts +103 -0
  85. package/dist/custom-objects/generated/proto/vendor/publicapi/region_routers.pb.d.ts.map +1 -0
  86. package/dist/custom-objects/generated/proto/vendor/publicapi/rollout_configs.pb.d.ts +153 -0
  87. package/dist/custom-objects/generated/proto/vendor/publicapi/rollout_configs.pb.d.ts.map +1 -0
  88. package/dist/custom-objects/generated/proto/vendor/publicapi/v2ext.pb.d.ts +1111 -0
  89. package/dist/custom-objects/generated/proto/vendor/publicapi/v2ext.pb.d.ts.map +1 -0
  90. package/dist/custom-objects/generated/proto/vendor/vext/annotations.pb.d.ts +602 -0
  91. package/dist/custom-objects/generated/proto/vendor/vext/annotations.pb.d.ts.map +1 -0
  92. package/dist/custom-objects/generated/proto/vendor/vext/extensions.pb.d.ts +144 -0
  93. package/dist/custom-objects/generated/proto/vendor/vext/extensions.pb.d.ts.map +1 -0
  94. package/dist/custom-objects/generated/proto/vendor/vext/privacy_unified_annotations.pb.d.ts +851 -0
  95. package/dist/custom-objects/generated/proto/vendor/vext/privacy_unified_annotations.pb.d.ts.map +1 -0
  96. package/dist/custom-objects/generated/proto/vendor/vext/xml_annotations.pb.d.ts +125 -0
  97. package/dist/custom-objects/generated/proto/vendor/vext/xml_annotations.pb.d.ts.map +1 -0
  98. package/dist/custom-objects/to-proto-json.d.ts +17 -0
  99. package/dist/custom-objects/to-proto-json.d.ts.map +1 -0
  100. package/dist/dependencies/index.cjs +601 -0
  101. package/dist/dependencies/index.d.ts +320 -0
  102. package/dist/dependencies/index.d.ts.map +1 -0
  103. package/dist/dependencies/index.js +560 -0
  104. package/dist/extensibility-dev-tools-alpha.d.ts +199 -0
  105. package/dist/extensibility-dev-tools-beta.d.ts +199 -0
  106. package/dist/extensibility-dev-tools-dependencies-alpha.d.ts +51 -0
  107. package/dist/extensibility-dev-tools-dependencies-beta.d.ts +51 -0
  108. package/dist/extensibility-dev-tools-dependencies-internal.d.ts +372 -0
  109. package/dist/extensibility-dev-tools-dependencies-public.d.ts +51 -0
  110. package/dist/extensibility-dev-tools-internal.d.ts +1722 -0
  111. package/dist/extensibility-dev-tools-jsonschema-tools-alpha.d.ts +57 -0
  112. package/dist/extensibility-dev-tools-jsonschema-tools-beta.d.ts +57 -0
  113. package/dist/extensibility-dev-tools-jsonschema-tools-internal.d.ts +123 -0
  114. package/dist/extensibility-dev-tools-jsonschema-tools-public.d.ts +57 -0
  115. package/dist/extensibility-dev-tools-manifest-alpha.d.ts +31 -0
  116. package/dist/extensibility-dev-tools-manifest-beta.d.ts +31 -0
  117. package/dist/extensibility-dev-tools-manifest-internal.d.ts +461 -0
  118. package/dist/extensibility-dev-tools-manifest-public.d.ts +31 -0
  119. package/dist/extensibility-dev-tools-public.d.ts +199 -0
  120. package/dist/extensibility-dev-tools-schemas-alpha.d.ts +9 -0
  121. package/dist/extensibility-dev-tools-schemas-beta.d.ts +9 -0
  122. package/dist/extensibility-dev-tools-schemas-internal.d.ts +41 -0
  123. package/dist/extensibility-dev-tools-schemas-public.d.ts +9 -0
  124. package/dist/extensibility-dev-tools-templates-alpha.d.ts +67 -0
  125. package/dist/extensibility-dev-tools-templates-beta.d.ts +67 -0
  126. package/dist/extensibility-dev-tools-templates-internal.d.ts +554 -0
  127. package/dist/extensibility-dev-tools-templates-public.d.ts +67 -0
  128. package/dist/extensibility-dev-tools-workspace-alpha.d.ts +51 -0
  129. package/dist/extensibility-dev-tools-workspace-beta.d.ts +51 -0
  130. package/dist/extensibility-dev-tools-workspace-internal.d.ts +410 -0
  131. package/dist/extensibility-dev-tools-workspace-public.d.ts +51 -0
  132. package/dist/index.cjs +3810 -0
  133. package/dist/index.d.ts +18 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +3758 -0
  136. package/dist/jsonschema-tools.cjs +20451 -0
  137. package/dist/jsonschema-tools.d.ts +98 -0
  138. package/dist/jsonschema-tools.d.ts.map +1 -0
  139. package/dist/jsonschema-tools.js +20404 -0
  140. package/dist/manifest/index.cjs +610 -0
  141. package/dist/manifest/index.d.ts +8 -0
  142. package/dist/manifest/index.d.ts.map +1 -0
  143. package/dist/manifest/index.js +571 -0
  144. package/dist/manifest/manifest-v1.d.ts +102 -0
  145. package/dist/manifest/manifest-v1.d.ts.map +1 -0
  146. package/dist/manifest/manifest-v2.d.ts +253 -0
  147. package/dist/manifest/manifest-v2.d.ts.map +1 -0
  148. package/dist/manifest/stripe-app-manifest.d.ts +114 -0
  149. package/dist/manifest/stripe-app-manifest.d.ts.map +1 -0
  150. package/dist/schemas/index.cjs +20692 -0
  151. package/dist/schemas/index.d.ts +37 -0
  152. package/dist/schemas/index.d.ts.map +1 -0
  153. package/dist/schemas/index.js +20656 -0
  154. package/dist/templates/diff-viewer/diff-generator.d.ts +22 -0
  155. package/dist/templates/diff-viewer/diff-generator.d.ts.map +1 -0
  156. package/dist/templates/diff-viewer/diff-prompt.d.ts +13 -0
  157. package/dist/templates/diff-viewer/diff-prompt.d.ts.map +1 -0
  158. package/dist/templates/diff-viewer/index.d.ts +7 -0
  159. package/dist/templates/diff-viewer/index.d.ts.map +1 -0
  160. package/dist/templates/diff-viewer/terminal-renderer.d.ts +29 -0
  161. package/dist/templates/diff-viewer/terminal-renderer.d.ts.map +1 -0
  162. package/dist/templates/diff-viewer/types.d.ts +58 -0
  163. package/dist/templates/diff-viewer/types.d.ts.map +1 -0
  164. package/dist/templates/extensions/base.d.ts +23 -0
  165. package/dist/templates/extensions/base.d.ts.map +1 -0
  166. package/dist/templates/extensions/billing.bill.discount_calculation.d.ts +6 -0
  167. package/dist/templates/extensions/billing.bill.discount_calculation.d.ts.map +1 -0
  168. package/dist/templates/extensions/billing.customer_balance_application.d.ts +6 -0
  169. package/dist/templates/extensions/billing.customer_balance_application.d.ts.map +1 -0
  170. package/dist/templates/extensions/billing.invoice_collection_setting.d.ts +6 -0
  171. package/dist/templates/extensions/billing.invoice_collection_setting.d.ts.map +1 -0
  172. package/dist/templates/extensions/billing.prorations.d.ts +6 -0
  173. package/dist/templates/extensions/billing.prorations.d.ts.map +1 -0
  174. package/dist/templates/extensions/billing.recurring_billing_item_handling.d.ts +6 -0
  175. package/dist/templates/extensions/billing.recurring_billing_item_handling.d.ts.map +1 -0
  176. package/dist/templates/extensions/core.workflows.custom_action.d.ts +6 -0
  177. package/dist/templates/extensions/core.workflows.custom_action.d.ts.map +1 -0
  178. package/dist/templates/extensions/extend.objects.custom_objects.d.ts +6 -0
  179. package/dist/templates/extensions/extend.objects.custom_objects.d.ts.map +1 -0
  180. package/dist/templates/extensions/extend.workflows.custom_action.d.ts +6 -0
  181. package/dist/templates/extensions/extend.workflows.custom_action.d.ts.map +1 -0
  182. package/dist/templates/extensions/index.d.ts +13 -0
  183. package/dist/templates/extensions/index.d.ts.map +1 -0
  184. package/dist/templates/extensions/registry.d.ts +10 -0
  185. package/dist/templates/extensions/registry.d.ts.map +1 -0
  186. package/dist/templates/extensions/types.d.ts +104 -0
  187. package/dist/templates/extensions/types.d.ts.map +1 -0
  188. package/dist/templates/file-writer.d.ts +140 -0
  189. package/dist/templates/file-writer.d.ts.map +1 -0
  190. package/dist/templates/fs/_impl.d.ts +29 -0
  191. package/dist/templates/fs/_impl.d.ts.map +1 -0
  192. package/dist/templates/fs/filesystem.d.ts +8 -0
  193. package/dist/templates/fs/filesystem.d.ts.map +1 -0
  194. package/dist/templates/fs/in-memory.d.ts +9 -0
  195. package/dist/templates/fs/in-memory.d.ts.map +1 -0
  196. package/dist/templates/fs/index.d.ts +25 -0
  197. package/dist/templates/fs/index.d.ts.map +1 -0
  198. package/dist/templates/fs-utils.d.ts +17 -0
  199. package/dist/templates/fs-utils.d.ts.map +1 -0
  200. package/dist/templates/index.cjs +2248 -0
  201. package/dist/templates/index.d.ts +32 -0
  202. package/dist/templates/index.d.ts.map +1 -0
  203. package/dist/templates/index.js +2203 -0
  204. package/dist/templates/root/index.d.ts +60 -0
  205. package/dist/templates/root/index.d.ts.map +1 -0
  206. package/dist/templates/simple-templates.d.ts +8 -0
  207. package/dist/templates/simple-templates.d.ts.map +1 -0
  208. package/dist/templates/template-manager.d.ts +8 -0
  209. package/dist/templates/template-manager.d.ts.map +1 -0
  210. package/dist/templates/types.d.ts +9 -0
  211. package/dist/templates/types.d.ts.map +1 -0
  212. package/dist/tsconfig.build.tsbuildinfo +1 -0
  213. package/dist/workspace/index.cjs +3756 -0
  214. package/dist/workspace/index.d.ts +336 -0
  215. package/dist/workspace/index.d.ts.map +1 -0
  216. package/dist/workspace/index.js +3731 -0
  217. package/package.json +137 -0
  218. package/templates/extensions/billing.bill.discount_calculation/index.test.ts +15 -0
  219. package/templates/extensions/billing.bill.discount_calculation/index.ts +20 -0
  220. package/templates/extensions/billing.customer_balance_application/index.test.ts +15 -0
  221. package/templates/extensions/billing.customer_balance_application/index.ts +18 -0
  222. package/templates/extensions/billing.invoice_collection_setting/index.test.ts +15 -0
  223. package/templates/extensions/billing.invoice_collection_setting/index.ts +16 -0
  224. package/templates/extensions/billing.prorations/index.test.ts +15 -0
  225. package/templates/extensions/billing.prorations/index.ts +18 -0
  226. package/templates/extensions/billing.recurring_billing_item_handling/index.test.ts +15 -0
  227. package/templates/extensions/billing.recurring_billing_item_handling/index.ts +42 -0
  228. package/templates/extensions/common/.prettierignore +3 -0
  229. package/templates/extensions/common/eslint.config.mts.mustache +95 -0
  230. package/templates/extensions/common/package.json.mustache +26 -0
  231. package/templates/extensions/common/tsconfig.build.json.mustache +15 -0
  232. package/templates/extensions/common/tsconfig.json.mustache +16 -0
  233. package/templates/extensions/core.workflows.custom_action/custom_input.schema.json +6 -0
  234. package/templates/extensions/core.workflows.custom_action/index.test.ts +15 -0
  235. package/templates/extensions/core.workflows.custom_action/index.ts +31 -0
  236. package/templates/extensions/extend.workflows.custom_action/custom_input.schema.json +6 -0
  237. package/templates/extensions/extend.workflows.custom_action/index.test.ts +15 -0
  238. package/templates/extensions/extend.workflows.custom_action/index.ts +31 -0
  239. package/templates/root/.husky/pre-commit +1 -0
  240. package/templates/root/.prettierignore +5 -0
  241. package/templates/root/.prettierrc +7 -0
  242. package/templates/root/_gitignore +28 -0
  243. package/templates/root/custom-objects/package.json +20 -0
  244. package/templates/root/custom-objects/tsconfig.json +9 -0
  245. package/templates/root/eslint.config.mts +95 -0
  246. package/templates/root/package.json.mustache +32 -0
  247. package/templates/root/pnpm-workspace.yaml +7 -0
  248. package/templates/root/stripe-app.yaml.mustache +6 -0
  249. package/templates/root/tools/test.mts +38 -0
  250. package/templates/root/tsconfig.base.json +23 -0
  251. package/templates/root/tsconfig.json +15 -0
  252. package/templates/root/ui/package.json +17 -0
  253. package/templates/root/vitest.config.mts +47 -0
@@ -0,0 +1,3841 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/bin/gen-workspace.ts
4
+ import yargs from "yargs";
5
+ import { hideBin } from "yargs/helpers";
6
+ import {
7
+ _createLogger as _createLogger3,
8
+ _createCliContext as _createCliContext3,
9
+ _writeJsonOutput
10
+ } from "@stripe/extensibility-tool-utils";
11
+
12
+ // src/workspace/index.ts
13
+ import { z } from "zod";
14
+ import path4 from "path";
15
+ import { existsSync as existsSync2 } from "fs";
16
+ import { readFile as readFile4 } from "fs/promises";
17
+ import { execSync as execSync3 } from "child_process";
18
+
19
+ // src/dependencies/index.ts
20
+ import path from "path";
21
+ import fs from "fs";
22
+ import os from "os";
23
+ import { execSync } from "child_process";
24
+ import PackageJson from "@npmcli/package-json";
25
+ import * as semver from "semver";
26
+ import { load as parseToml } from "js-toml";
27
+ import { _createCliContext } from "@stripe/extensibility-tool-utils";
28
+ function _npmDep(name, version) {
29
+ return { type: "npm", name, version };
30
+ }
31
+ function _devNpmDep(name, version) {
32
+ return { type: "dev-npm", name, version };
33
+ }
34
+ function _detectPackageManager(cwd) {
35
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) {
36
+ return "pnpm";
37
+ }
38
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) {
39
+ return "yarn";
40
+ }
41
+ if (fs.existsSync(path.join(cwd, "package-lock.json"))) {
42
+ return "npm";
43
+ }
44
+ let currentDir = cwd;
45
+ const root = path.parse(currentDir).root;
46
+ while (currentDir !== root) {
47
+ const parentDir = path.dirname(currentDir);
48
+ if (parentDir === currentDir) break;
49
+ if (fs.existsSync(path.join(parentDir, "pnpm-lock.yaml"))) {
50
+ if (fs.existsSync(path.join(parentDir, "pnpm-workspace.yaml"))) {
51
+ return "pnpm";
52
+ }
53
+ }
54
+ if (fs.existsSync(path.join(parentDir, "yarn.lock"))) {
55
+ return "yarn";
56
+ }
57
+ if (fs.existsSync(path.join(parentDir, "package-lock.json"))) {
58
+ return "npm";
59
+ }
60
+ currentDir = parentDir;
61
+ }
62
+ return "npm";
63
+ }
64
+ var _NpmDependencyHandler = class {
65
+ cwd;
66
+ quiet;
67
+ devDependencies;
68
+ context;
69
+ constructor(options) {
70
+ this.cwd = options.cwd;
71
+ this.quiet = options.quiet;
72
+ this.devDependencies = options.devDependencies ?? false;
73
+ this.context = options.context ?? _createCliContext();
74
+ }
75
+ get dependencyKey() {
76
+ return this.devDependencies ? "devDependencies" : "dependencies";
77
+ }
78
+ get dependencyLabel() {
79
+ return this.devDependencies ? "devDependencies" : "dependencies";
80
+ }
81
+ /** Check whether the npm dependency is already present in package.json. */
82
+ async check(dep) {
83
+ const packageJsonPath = path.join(this.cwd, "package.json");
84
+ if (!fs.existsSync(packageJsonPath)) {
85
+ return {
86
+ satisfied: false,
87
+ message: `package.json not found at ${this.cwd}`
88
+ };
89
+ }
90
+ const pkgJson = await PackageJson.load(this.cwd);
91
+ const rawDeps = pkgJson.content[this.dependencyKey];
92
+ const deps = rawDeps ?? {};
93
+ const currentVersion = deps[dep.name];
94
+ if (currentVersion === void 0) {
95
+ return {
96
+ satisfied: false,
97
+ message: `${dep.name} not found in ${this.dependencyLabel}`
98
+ };
99
+ }
100
+ if (currentVersion === dep.version) {
101
+ return {
102
+ satisfied: true,
103
+ currentVersion,
104
+ message: `${dep.name}@${dep.version} already in ${this.dependencyLabel}`
105
+ };
106
+ }
107
+ if (this.versionsCompatible(currentVersion, dep.version)) {
108
+ return {
109
+ satisfied: true,
110
+ currentVersion,
111
+ message: `${dep.name}@${currentVersion} satisfies ${dep.version}`
112
+ };
113
+ }
114
+ return {
115
+ satisfied: false,
116
+ currentVersion,
117
+ message: `${dep.name}@${currentVersion} does not satisfy ${dep.version}`
118
+ };
119
+ }
120
+ /** Check whether the requested version conflicts with the currently installed version. */
121
+ async checkConflict(dep) {
122
+ const packageJsonPath = path.join(this.cwd, "package.json");
123
+ if (!fs.existsSync(packageJsonPath)) {
124
+ return { hasConflict: false };
125
+ }
126
+ const pkgJson = await PackageJson.load(this.cwd);
127
+ const rawDeps = pkgJson.content[this.dependencyKey];
128
+ const deps = rawDeps ?? {};
129
+ const existingVersion = deps[dep.name];
130
+ if (existingVersion === void 0) {
131
+ return { hasConflict: false };
132
+ }
133
+ if (existingVersion === dep.version) {
134
+ return { hasConflict: false };
135
+ }
136
+ const existingMajor = this.extractMajorVersion(existingVersion);
137
+ const requestedMajor = this.extractMajorVersion(dep.version);
138
+ if (existingMajor !== null && requestedMajor !== null && existingMajor !== requestedMajor) {
139
+ return {
140
+ hasConflict: true,
141
+ existingVersion,
142
+ requestedVersion: dep.version,
143
+ message: `Major version mismatch: existing ${existingVersion} vs requested ${dep.version}`
144
+ };
145
+ }
146
+ if (!this.versionsCompatible(existingVersion, dep.version)) {
147
+ return {
148
+ hasConflict: true,
149
+ existingVersion,
150
+ requestedVersion: dep.version,
151
+ message: `Incompatible version ranges: existing ${existingVersion} vs requested ${dep.version}`
152
+ };
153
+ }
154
+ return { hasConflict: false };
155
+ }
156
+ /** Add or update the npm dependency in package.json. */
157
+ async add(dep) {
158
+ const packageJsonPath = path.join(this.cwd, "package.json");
159
+ if (!fs.existsSync(packageJsonPath)) {
160
+ throw new Error(`package.json not found at ${this.cwd}`);
161
+ }
162
+ const pkgJson = await PackageJson.load(this.cwd);
163
+ const rawDeps = pkgJson.content[this.dependencyKey];
164
+ const deps = rawDeps ?? {};
165
+ const existingVersion = deps[dep.name];
166
+ const isUpdate = existingVersion !== void 0;
167
+ const update = {
168
+ [this.dependencyKey]: {
169
+ ...deps,
170
+ [dep.name]: dep.version
171
+ }
172
+ };
173
+ pkgJson.update(update);
174
+ await pkgJson.save();
175
+ const action = isUpdate ? "update" : "add";
176
+ const message = isUpdate ? `Updated ${dep.name} from ${existingVersion} to ${dep.version} in ${this.dependencyLabel}` : `Added ${dep.name}@${dep.version} to ${this.dependencyLabel}`;
177
+ if (!this.quiet) {
178
+ this.context.ux.log(`\u2713 ${message}`);
179
+ }
180
+ return { action, message };
181
+ }
182
+ /** Run the package manager install command in the working directory. */
183
+ install(_deps) {
184
+ const packageManager = _detectPackageManager(this.cwd);
185
+ if (!this.quiet) {
186
+ this.context.ux.log(`Running ${packageManager} install...`);
187
+ }
188
+ try {
189
+ execSync(`${packageManager} install`, {
190
+ cwd: this.cwd,
191
+ stdio: this.quiet ? "pipe" : "inherit"
192
+ });
193
+ } catch (error) {
194
+ const baseMessage = `Failed to run ${packageManager} install`;
195
+ if (error instanceof Error) {
196
+ return Promise.reject(new Error(`${baseMessage}: ${error.message}`));
197
+ }
198
+ return Promise.reject(new Error(`${baseMessage}: ${String(error)}`));
199
+ }
200
+ return Promise.resolve();
201
+ }
202
+ versionsCompatible(existing, requested) {
203
+ if (existing.startsWith("file:") || requested.startsWith("file:") || existing.startsWith("workspace:") || requested.startsWith("workspace:")) {
204
+ return existing === requested;
205
+ }
206
+ if (!semver.validRange(existing) || !semver.validRange(requested)) {
207
+ return existing === requested;
208
+ }
209
+ return semver.intersects(existing, requested);
210
+ }
211
+ extractMajorVersion(version) {
212
+ if (version.startsWith("file:") || version.startsWith("workspace:")) {
213
+ return null;
214
+ }
215
+ const coerced = semver.coerce(version);
216
+ if (coerced) {
217
+ return coerced.major;
218
+ }
219
+ return null;
220
+ }
221
+ };
222
+ var _StripeCliPluginHandler = class {
223
+ stripeConfigDir;
224
+ quiet;
225
+ context;
226
+ constructor(options) {
227
+ this.stripeConfigDir = options.stripeConfigDir;
228
+ this.quiet = options.quiet;
229
+ this.context = options.context ?? _createCliContext();
230
+ }
231
+ /** Check whether the Stripe CLI plugin is installed and meets the minimum version. */
232
+ check(dep) {
233
+ const pluginsTomlPath = path.join(this.stripeConfigDir, "plugins.toml");
234
+ if (!fs.existsSync(pluginsTomlPath)) {
235
+ return Promise.resolve({
236
+ satisfied: false,
237
+ message: `Stripe CLI plugin '${dep.name}' is not installed (plugins.toml not found)`
238
+ });
239
+ }
240
+ const pluginsContent = fs.readFileSync(pluginsTomlPath, "utf-8");
241
+ const installedPlugin = this.findPluginInToml(pluginsContent, dep.name);
242
+ if (!installedPlugin) {
243
+ return Promise.resolve({
244
+ satisfied: false,
245
+ message: `Stripe CLI plugin '${dep.name}' is not installed`
246
+ });
247
+ }
248
+ if (dep.minVersion && installedPlugin.version) {
249
+ if (!this.isVersionSatisfied(installedPlugin.version, dep.minVersion)) {
250
+ return Promise.resolve({
251
+ satisfied: false,
252
+ currentVersion: installedPlugin.version,
253
+ message: `Stripe CLI plugin '${dep.name}' version ${installedPlugin.version} is below minimum ${dep.minVersion}`
254
+ });
255
+ }
256
+ }
257
+ const result = {
258
+ satisfied: true,
259
+ message: `Stripe CLI plugin '${dep.name}' is installed${installedPlugin.version ? ` (version ${installedPlugin.version})` : ""}`
260
+ };
261
+ if (installedPlugin.version) {
262
+ result.currentVersion = installedPlugin.version;
263
+ }
264
+ return Promise.resolve(result);
265
+ }
266
+ /** Check whether the installed plugin version conflicts with the requested minimum. */
267
+ async checkConflict(dep) {
268
+ const checkResult = await this.check(dep);
269
+ if (checkResult.satisfied) {
270
+ return { hasConflict: false };
271
+ }
272
+ if (checkResult.currentVersion && dep.minVersion) {
273
+ return {
274
+ hasConflict: true,
275
+ existingVersion: checkResult.currentVersion,
276
+ requestedVersion: dep.minVersion,
277
+ message: `Installed version ${checkResult.currentVersion} is below minimum ${dep.minVersion}`
278
+ };
279
+ }
280
+ return { hasConflict: false };
281
+ }
282
+ /** Stage a Stripe CLI plugin for installation; the actual install happens in `install`. */
283
+ async add(dep) {
284
+ const checkResult = await this.check(dep);
285
+ const isUpdate = checkResult.currentVersion !== void 0;
286
+ const action = isUpdate ? "update" : "add";
287
+ const message = isUpdate ? `Will update Stripe CLI plugin '${dep.name}'` : `Will install Stripe CLI plugin '${dep.name}'`;
288
+ return { action, message };
289
+ }
290
+ /** Install Stripe CLI plugins using `stripe plugin install`. */
291
+ async install(deps) {
292
+ for (const dep of deps) {
293
+ const checkResult = await this.check(dep);
294
+ const isUpdate = checkResult.currentVersion !== void 0;
295
+ try {
296
+ execSync(`stripe plugin install ${dep.name}`, {
297
+ stdio: this.quiet ? "pipe" : "inherit"
298
+ });
299
+ const message = isUpdate ? `Updated Stripe CLI plugin '${dep.name}'` : `Installed Stripe CLI plugin '${dep.name}'`;
300
+ if (!this.quiet) {
301
+ this.context.ux.log(`\u2713 ${message}`);
302
+ }
303
+ } catch (error) {
304
+ const baseMessage = `Failed to install Stripe CLI plugin '${dep.name}'`;
305
+ if (error instanceof Error) {
306
+ throw new Error(`${baseMessage}: ${error.message}`);
307
+ }
308
+ throw new Error(`${baseMessage}: ${String(error)}`);
309
+ }
310
+ }
311
+ }
312
+ findPluginInToml(content, pluginName) {
313
+ try {
314
+ const parsed = parseToml(content);
315
+ const plugins = parsed.Plugin;
316
+ if (!plugins || !Array.isArray(plugins)) {
317
+ return null;
318
+ }
319
+ const plugin = plugins.find((p) => p.Shortname === pluginName);
320
+ if (!plugin) {
321
+ return null;
322
+ }
323
+ if (plugin.Release && Array.isArray(plugin.Release) && plugin.Release.length > 0) {
324
+ const currentArch = os.arch();
325
+ const currentOS = os.platform();
326
+ const normalizedArch = currentArch === "x64" ? "amd64" : currentArch;
327
+ const normalizedOS = currentOS === "win32" ? "windows" : currentOS;
328
+ const platformReleases = plugin.Release.filter(
329
+ (r) => r.Arch === normalizedArch && r.OS === normalizedOS
330
+ );
331
+ if (platformReleases.length === 0) {
332
+ return null;
333
+ }
334
+ const localBuildRelease = platformReleases.find(
335
+ (r) => r.Version === "local.build.dev"
336
+ );
337
+ if (localBuildRelease) {
338
+ return { version: "local.build.dev" };
339
+ }
340
+ const versions = platformReleases.map((r) => r.Version).filter((v) => v !== void 0);
341
+ if (versions.length === 0) {
342
+ return null;
343
+ }
344
+ const sortedVersions = versions.map((v) => ({ original: v, parsed: semver.coerce(v) })).filter(
345
+ (v) => v.parsed !== null
346
+ ).sort((a, b) => semver.rcompare(a.parsed, b.parsed));
347
+ if (sortedVersions.length === 0) {
348
+ return { version: versions[0] };
349
+ }
350
+ return { version: sortedVersions[0]?.original };
351
+ }
352
+ return { version: plugin.Version };
353
+ } catch {
354
+ return null;
355
+ }
356
+ }
357
+ /**
358
+ * Check if installed version satisfies the required minimum version.
359
+ *
360
+ * Permissive policy: Non-semver versions (e.g., "local.build.dev", "dev", "canary-abc123")
361
+ * always satisfy version requirements. This avoids forcing upgrades during local development
362
+ * when developers are using locally built plugins.
363
+ *
364
+ * For valid semver versions, uses the semver library for proper semantic version comparison.
365
+ *
366
+ * @param installed - The installed version string
367
+ * @param required - The required minimum version string
368
+ * @returns true if installed version satisfies requirement
369
+ */
370
+ isVersionSatisfied(installed, required) {
371
+ const installedSemver = semver.coerce(installed);
372
+ const requiredSemver = semver.coerce(required);
373
+ if (!installedSemver) {
374
+ return true;
375
+ }
376
+ if (!requiredSemver) {
377
+ return true;
378
+ }
379
+ return semver.gte(installedSemver, requiredSemver);
380
+ }
381
+ };
382
+ function dependencyKey(dep) {
383
+ return `${dep.type}:${dep.name}`;
384
+ }
385
+ var _DependencyManager = class {
386
+ cwd;
387
+ stripeConfigDir;
388
+ quiet;
389
+ context;
390
+ npmHandler;
391
+ devNpmHandler;
392
+ stripeCliPluginHandler;
393
+ /** Internal state: pending changes indexed by dependency key */
394
+ pendingChanges = /* @__PURE__ */ new Map();
395
+ /** Whether commit() has been called */
396
+ committed = false;
397
+ constructor(options = {}) {
398
+ this.cwd = options.cwd ?? process.cwd();
399
+ this.stripeConfigDir = options.stripeConfigDir ?? path.join(os.homedir(), ".config", "stripe");
400
+ this.quiet = options.quiet ?? false;
401
+ this.context = options.context ?? _createCliContext();
402
+ this.npmHandler = new _NpmDependencyHandler({
403
+ cwd: this.cwd,
404
+ quiet: this.quiet,
405
+ devDependencies: false,
406
+ context: this.context
407
+ });
408
+ this.devNpmHandler = new _NpmDependencyHandler({
409
+ cwd: this.cwd,
410
+ quiet: this.quiet,
411
+ devDependencies: true,
412
+ context: this.context
413
+ });
414
+ this.stripeCliPluginHandler = new _StripeCliPluginHandler({
415
+ stripeConfigDir: this.stripeConfigDir,
416
+ quiet: this.quiet,
417
+ context: this.context
418
+ });
419
+ }
420
+ /**
421
+ * Analyze dependencies and accumulate changes.
422
+ * Can be called multiple times before commit().
423
+ * Returns the changes for this specific call.
424
+ */
425
+ async ensureDependencies(input) {
426
+ if (this.committed) {
427
+ throw new Error("DependencyManager has already been committed");
428
+ }
429
+ const { required, optional = [] } = input;
430
+ const changes = [];
431
+ for (const dep of [...required, ...optional]) {
432
+ const change = await this.analyzeDependency(dep);
433
+ changes.push(change);
434
+ this.pendingChanges.set(dependencyKey(dep), change);
435
+ }
436
+ return changes;
437
+ }
438
+ /**
439
+ * Resolve a conflict by marking it for force install.
440
+ * Throws if the dependency is not in conflict state.
441
+ */
442
+ resolveConflict(dep) {
443
+ if (this.committed) {
444
+ throw new Error("DependencyManager has already been committed");
445
+ }
446
+ const key = dependencyKey(dep);
447
+ const change = this.pendingChanges.get(key);
448
+ if (!change) {
449
+ throw new Error(`Dependency '${dep.name}' not found in pending changes`);
450
+ }
451
+ if (change.action !== "conflict") {
452
+ throw new Error(
453
+ `Dependency '${dep.name}' is not in conflict (action: ${change.action})`
454
+ );
455
+ }
456
+ change.conflictResolved = true;
457
+ }
458
+ /**
459
+ * Get all pending changes (accumulated across all ensureDependencies calls).
460
+ */
461
+ getPendingChanges() {
462
+ return Array.from(this.pendingChanges.values());
463
+ }
464
+ /**
465
+ * Commit all accumulated changes.
466
+ * - For npm deps: updates package.json, optionally runs package manager install
467
+ * - For Stripe CLI deps: always installs (no separate add step)
468
+ *
469
+ * @param options - Commit options. `options.runInstall`: if true, run package manager install for npm deps (default: true)
470
+ * @returns Summary of changes made
471
+ * @throws If called more than once
472
+ */
473
+ async commit(options = {}) {
474
+ if (this.committed) {
475
+ throw new Error("DependencyManager has already been committed");
476
+ }
477
+ this.committed = true;
478
+ const { runInstall = true } = options;
479
+ let added = 0;
480
+ let updated = 0;
481
+ const npmDeps = [];
482
+ const stripeCliDeps = [];
483
+ for (const change of this.pendingChanges.values()) {
484
+ if (change.action === "already-satisfied") {
485
+ continue;
486
+ }
487
+ if (change.action === "conflict" && !change.conflictResolved) {
488
+ continue;
489
+ }
490
+ const dep = change.dependency;
491
+ if (dep.type === "npm" || dep.type === "dev-npm") {
492
+ npmDeps.push(dep);
493
+ } else {
494
+ stripeCliDeps.push(dep);
495
+ }
496
+ }
497
+ for (const dep of npmDeps) {
498
+ const handler = dep.type === "npm" ? this.npmHandler : this.devNpmHandler;
499
+ const result = await handler.add(dep);
500
+ if (result.action === "add") {
501
+ added++;
502
+ } else {
503
+ updated++;
504
+ }
505
+ }
506
+ if (runInstall && npmDeps.length > 0) {
507
+ await this.npmHandler.install(npmDeps);
508
+ }
509
+ if (stripeCliDeps.length > 0) {
510
+ await this.stripeCliPluginHandler.install(stripeCliDeps);
511
+ for (const dep of stripeCliDeps) {
512
+ const change = this.pendingChanges.get(dependencyKey(dep));
513
+ if (change?.action === "add" || change?.action === "conflict" && !change.previousVersion) {
514
+ added++;
515
+ } else {
516
+ updated++;
517
+ }
518
+ }
519
+ }
520
+ return { added, updated };
521
+ }
522
+ async analyzeDependency(dep) {
523
+ const handler = this.getHandler(dep);
524
+ const checkResult = await handler.check(dep);
525
+ if (checkResult.satisfied) {
526
+ return {
527
+ dependency: dep,
528
+ action: "already-satisfied",
529
+ message: checkResult.message
530
+ };
531
+ }
532
+ const conflictResult = await handler.checkConflict(dep);
533
+ if (conflictResult.hasConflict) {
534
+ const result2 = {
535
+ dependency: dep,
536
+ action: "conflict",
537
+ message: conflictResult.message ?? "Dependency conflict detected",
538
+ conflict: conflictResult
539
+ };
540
+ if (conflictResult.existingVersion) {
541
+ result2.previousVersion = conflictResult.existingVersion;
542
+ }
543
+ return result2;
544
+ }
545
+ const isUpdate = checkResult.currentVersion !== void 0;
546
+ const result = {
547
+ dependency: dep,
548
+ action: isUpdate ? "update" : "add",
549
+ message: isUpdate ? `Will update ${dep.name} from ${String(checkResult.currentVersion)}` : `Will add ${dep.name}`
550
+ };
551
+ if (checkResult.currentVersion) {
552
+ result.previousVersion = checkResult.currentVersion;
553
+ }
554
+ return result;
555
+ }
556
+ getHandler(dep) {
557
+ switch (dep.type) {
558
+ case "npm":
559
+ return this.npmHandler;
560
+ case "dev-npm":
561
+ return this.devNpmHandler;
562
+ case "stripe-cli-plugin":
563
+ return this.stripeCliPluginHandler;
564
+ }
565
+ }
566
+ };
567
+
568
+ // src/workspace/index.ts
569
+ import {
570
+ _customObjectGenerators,
571
+ _customObjectsWorkspaceGenerator
572
+ } from "@stripe/extensibility-custom-objects-tools/internal";
573
+ import {
574
+ _GeneratorRunner,
575
+ _createCliContext as _createCliContext2,
576
+ _toSnakeCase as _toSnakeCase2,
577
+ _openStripeAppManifest,
578
+ _beginTransaction
579
+ } from "@stripe/extensibility-tool-utils";
580
+
581
+ // src/manifest/stripe-app-manifest.ts
582
+ import { _toSnakeCase } from "@stripe/extensibility-tool-utils";
583
+
584
+ // src/manifest/manifest-v1.ts
585
+ import { readFileSync, writeFileSync, existsSync } from "fs";
586
+ function formatCustomObjectEntry(entry) {
587
+ return `${entry.filePath}#${entry.className}`;
588
+ }
589
+ function parseCustomObjectEntry(entryString) {
590
+ const parts = entryString.split("#");
591
+ if (parts.length !== 2) {
592
+ throw new Error(
593
+ `Invalid object entry format: ${entryString}. Expected format: "path/to/file.d.ts#ClassName"`
594
+ );
595
+ }
596
+ const [filePath, className] = parts;
597
+ if (!filePath || !className) {
598
+ throw new Error(
599
+ `Invalid object entry format: ${entryString}. Expected format: "path/to/file.d.ts#ClassName"`
600
+ );
601
+ }
602
+ return { filePath, className };
603
+ }
604
+ var _ManifestV1 = class __ManifestV1 {
605
+ constructor(filePath, data) {
606
+ this.filePath = filePath;
607
+ this.data = data;
608
+ }
609
+ /**
610
+ * Load stripe-app.json from disk
611
+ * @param filePath - Path to stripe-app.json
612
+ * @throws Error if file is invalid or cannot be read
613
+ */
614
+ static load(filePath) {
615
+ if (!existsSync(filePath)) {
616
+ throw new Error(`Manifest file not found: ${filePath}`);
617
+ }
618
+ const content = readFileSync(filePath, "utf-8");
619
+ const data = JSON.parse(content);
620
+ if (!data.id) {
621
+ throw new Error('Manifest must contain "id" field');
622
+ }
623
+ return new __ManifestV1(filePath, data);
624
+ }
625
+ /**
626
+ * Get the app ID from the manifest
627
+ */
628
+ getAppId() {
629
+ return this.data.id;
630
+ }
631
+ /**
632
+ * Get the app name from the manifest
633
+ */
634
+ getAppName() {
635
+ return this.data.name;
636
+ }
637
+ /**
638
+ * Get all custom objects as structured entries
639
+ */
640
+ getCustomObjects() {
641
+ const entries = [];
642
+ if (this.data.exported_custom_objects) {
643
+ for (const entry of this.data.exported_custom_objects) {
644
+ entries.push(parseCustomObjectEntry(entry));
645
+ }
646
+ }
647
+ return entries;
648
+ }
649
+ /**
650
+ * Check if a custom object entry exists in the manifest
651
+ */
652
+ hasCustomObject(entry) {
653
+ const objects = this.getCustomObjects();
654
+ return objects.some(
655
+ (existing) => existing.filePath === entry.filePath && existing.className === entry.className
656
+ );
657
+ }
658
+ /**
659
+ * Add a custom object entry to the manifest
660
+ * Does nothing if entry already exists
661
+ * @returns true if entry was added, false if it already existed
662
+ */
663
+ addCustomObject(entry) {
664
+ if (this.hasCustomObject(entry)) {
665
+ return false;
666
+ }
667
+ const entryString = formatCustomObjectEntry(entry);
668
+ this.data.exported_custom_objects ??= [];
669
+ this.data.exported_custom_objects.push(entryString);
670
+ return true;
671
+ }
672
+ /**
673
+ * Remove a custom object entry from the manifest
674
+ * @returns true if entry was removed, false if it didn't exist
675
+ */
676
+ removeCustomObject(entry) {
677
+ if (!this.data.exported_custom_objects) {
678
+ return false;
679
+ }
680
+ const entryString = formatCustomObjectEntry(entry);
681
+ const originalLength = this.data.exported_custom_objects.length;
682
+ this.data.exported_custom_objects = this.data.exported_custom_objects.filter(
683
+ (e) => e !== entryString
684
+ );
685
+ if (this.data.exported_custom_objects.length === 0) {
686
+ delete this.data.exported_custom_objects;
687
+ }
688
+ return this.data.exported_custom_objects?.length !== originalLength;
689
+ }
690
+ /**
691
+ * Get the raw manifest data (for reading other fields)
692
+ */
693
+ getRawData() {
694
+ return this.data;
695
+ }
696
+ /**
697
+ * Save changes back to disk
698
+ */
699
+ save() {
700
+ writeFileSync(this.filePath, JSON.stringify(this.data, null, 2) + "\n");
701
+ }
702
+ };
703
+
704
+ // src/manifest/manifest-v2.ts
705
+ import { readFile, writeFile } from "fs/promises";
706
+ import * as yaml from "yaml";
707
+ import { _toPascalCase } from "@stripe/extensibility-tool-utils";
708
+ function isNonEmptyString(value) {
709
+ return typeof value === "string" && value.trim().length > 0;
710
+ }
711
+ function isYamlObject(value) {
712
+ return typeof value === "object" && value !== null && !Array.isArray(value);
713
+ }
714
+ function validateManifestV2Data(data) {
715
+ if (!isNonEmptyString(data.id)) {
716
+ throw new Error('Manifest must contain non-empty "id" field');
717
+ }
718
+ if (!isNonEmptyString(data.name)) {
719
+ throw new Error('Manifest must contain non-empty "name" field');
720
+ }
721
+ if (!isNonEmptyString(data.version)) {
722
+ throw new Error('Manifest must contain non-empty "version" field');
723
+ }
724
+ if ("extensions" in data && !Array.isArray(data.extensions)) {
725
+ throw new Error('Manifest field "extensions" must be an array when provided');
726
+ }
727
+ if ("custom_object_definitions" in data && !isYamlObject(data.custom_object_definitions)) {
728
+ throw new Error(
729
+ 'Manifest field "custom_object_definitions" must be an object with a "definitions" array'
730
+ );
731
+ }
732
+ const coBlock = data.custom_object_definitions;
733
+ const definitions = isYamlObject(coBlock) ? coBlock.definitions : void 0;
734
+ if (!definitions) {
735
+ return;
736
+ }
737
+ if (!Array.isArray(definitions)) {
738
+ throw new Error(
739
+ 'Manifest field "custom_object_definitions.definitions" must be an array'
740
+ );
741
+ }
742
+ for (let i = 0; i < definitions.length; i++) {
743
+ const def = definitions[i];
744
+ const prefix = `custom_object_definitions.definitions[${String(i)}]`;
745
+ if (!isYamlObject(def) || !isNonEmptyString(def.id)) {
746
+ throw new Error(
747
+ `${prefix}: missing or invalid "id" field. Got: ${JSON.stringify(def)}`
748
+ );
749
+ }
750
+ if (!isYamlObject(def.specification)) {
751
+ throw new Error(
752
+ `${prefix}: missing or invalid "specification" field. Expected: { type: "typescript", content: "path/to/file.ts" }. Got: ${JSON.stringify(def)}`
753
+ );
754
+ }
755
+ if (!isNonEmptyString(def.specification.type)) {
756
+ throw new Error(
757
+ `${prefix}: missing or invalid "specification.type" field. Got: ${JSON.stringify(def)}`
758
+ );
759
+ }
760
+ if (!isNonEmptyString(def.specification.content)) {
761
+ throw new Error(
762
+ `${prefix}: missing or invalid "specification.content" field. Got: ${JSON.stringify(def)}`
763
+ );
764
+ }
765
+ }
766
+ }
767
+ var _ManifestV2 = class __ManifestV2 {
768
+ constructor(filePath, data) {
769
+ this.filePath = filePath;
770
+ this.data = data;
771
+ }
772
+ /**
773
+ * Load stripe-app.yaml from disk
774
+ * @param filePath - Path to stripe-app.yaml
775
+ * @throws Error if file is invalid or cannot be read
776
+ */
777
+ static async load(filePath) {
778
+ try {
779
+ const content = await readFile(filePath, "utf-8");
780
+ const parsed = yaml.parse(content);
781
+ if (!isYamlObject(parsed)) {
782
+ throw new Error("Invalid stripe-app.yaml format: root must be an object");
783
+ }
784
+ validateManifestV2Data(parsed);
785
+ const data = parsed;
786
+ data.extensions ??= [];
787
+ return new __ManifestV2(filePath, data);
788
+ } catch (err) {
789
+ if (err instanceof Error) {
790
+ throw new Error(`Error reading stripe-app.yaml: ${err.message}`);
791
+ }
792
+ throw new Error(`Error reading stripe-app.yaml: ${String(err)}`);
793
+ }
794
+ }
795
+ /**
796
+ * Get the app ID from the manifest
797
+ */
798
+ getAppId() {
799
+ return this.data.id;
800
+ }
801
+ /**
802
+ * Get the app name from the manifest
803
+ */
804
+ getAppName() {
805
+ return this.data.name;
806
+ }
807
+ // ============================================================
808
+ // Custom Objects
809
+ // ============================================================
810
+ /**
811
+ * Get all custom object definitions, parsed into internal format.
812
+ * Entries are guaranteed structurally valid by load-time validation.
813
+ */
814
+ getCustomObjects() {
815
+ const definitions = this.data.custom_object_definitions?.definitions;
816
+ if (!definitions || definitions.length === 0) {
817
+ return [];
818
+ }
819
+ return definitions.map((def) => ({
820
+ id: def.id,
821
+ type: def.specification.type,
822
+ path: def.specification.content,
823
+ name: _toPascalCase(def.id)
824
+ }));
825
+ }
826
+ /**
827
+ * Check if a custom object exists by id
828
+ */
829
+ hasCustomObject(id) {
830
+ const definitions = this.data.custom_object_definitions?.definitions;
831
+ if (!definitions) return false;
832
+ return definitions.some((def) => def.id === id);
833
+ }
834
+ /**
835
+ * Add a custom object definition.
836
+ *
837
+ * Identity is keyed on `id` alone. The export name is derived via
838
+ * `_toPascalCase(id)` at read time, so `id` should be valid snake_case
839
+ * (e.g., "device", "loyalty_card", "http_request").
840
+ *
841
+ * @param id - Object identifier (e.g., "device", "loyalty_card")
842
+ * @param content - Path to the definition file (e.g., "src/device.object.ts")
843
+ * @param type - Specification type, defaults to "typescript"
844
+ * @returns true if added, false if already exists
845
+ */
846
+ addCustomObject(id, content, type = "typescript") {
847
+ if (this.hasCustomObject(id)) {
848
+ return false;
849
+ }
850
+ this.data.custom_object_definitions ??= {};
851
+ this.data.custom_object_definitions.definitions ??= [];
852
+ this.data.custom_object_definitions.definitions.push({
853
+ id,
854
+ specification: { type, content }
855
+ });
856
+ return true;
857
+ }
858
+ /**
859
+ * Remove a custom object definition by id
860
+ * @param id - Object identifier to remove
861
+ * @returns true if removed, false if not found
862
+ */
863
+ removeCustomObject(id) {
864
+ const block = this.data.custom_object_definitions;
865
+ if (!block?.definitions) {
866
+ return false;
867
+ }
868
+ const originalLength = block.definitions.length;
869
+ block.definitions = block.definitions.filter((def) => def.id !== id);
870
+ const newLength = block.definitions.length;
871
+ if (newLength === 0) {
872
+ delete this.data.custom_object_definitions;
873
+ }
874
+ return newLength < originalLength;
875
+ }
876
+ // ============================================================
877
+ // Extensions
878
+ // ============================================================
879
+ /**
880
+ * Add a new extension or update an existing one by ID
881
+ * If an extension with the provided ID exists, it will be replaced entirely
882
+ * @param extension - Extension configuration with all required fields including id
883
+ * @returns The extension ID
884
+ */
885
+ addOrUpdateExtension(extension) {
886
+ const newExtension = {
887
+ id: extension.id,
888
+ name: extension.name,
889
+ interface_id: extension.interface_id,
890
+ version: extension.version,
891
+ ...extension.description !== void 0 && {
892
+ description: extension.description
893
+ },
894
+ ...extension.stripe_version !== void 0 && {
895
+ stripe_version: extension.stripe_version
896
+ },
897
+ ...extension.script_entry_point !== void 0 && {
898
+ script_entry_point: extension.script_entry_point
899
+ },
900
+ ...extension.script !== void 0 && { script: extension.script },
901
+ permissions: extension.permissions,
902
+ methods: extension.methods,
903
+ ...extension.configuration !== void 0 && {
904
+ configuration: extension.configuration
905
+ },
906
+ ...extension.endpoints !== void 0 && {
907
+ endpoints: extension.endpoints
908
+ }
909
+ };
910
+ this.data.extensions ??= [];
911
+ const existingIndex = this.data.extensions.findIndex(
912
+ (ext) => ext.id === extension.id
913
+ );
914
+ if (existingIndex !== -1) {
915
+ this.data.extensions[existingIndex] = newExtension;
916
+ } else {
917
+ this.data.extensions.push(newExtension);
918
+ }
919
+ return extension.id;
920
+ }
921
+ /**
922
+ * Get a read-only view of all extensions
923
+ */
924
+ getExtensions() {
925
+ return this.data.extensions ?? [];
926
+ }
927
+ /**
928
+ * Get the raw manifest data (for reading other fields)
929
+ */
930
+ getRawData() {
931
+ return this.data;
932
+ }
933
+ /**
934
+ * Save changes back to disk
935
+ * @throws Error if file cannot be written
936
+ */
937
+ async save() {
938
+ try {
939
+ const updatedContent = yaml.stringify(this.data);
940
+ await writeFile(this.filePath, updatedContent, "utf-8");
941
+ } catch (err) {
942
+ if (err instanceof Error) {
943
+ throw new Error(`Error writing stripe-app.yaml: ${err.message}`);
944
+ }
945
+ throw new Error(`Error writing stripe-app.yaml: ${String(err)}`);
946
+ }
947
+ }
948
+ };
949
+
950
+ // src/manifest/stripe-app-manifest.ts
951
+ var _StripeAppManifest = class __StripeAppManifest {
952
+ constructor(manifestPath, version, v1, v2) {
953
+ this.manifestPath = manifestPath;
954
+ this.version = version;
955
+ this.v1 = v1;
956
+ this.v2 = v2;
957
+ }
958
+ /**
959
+ * Load a manifest file, automatically detecting the version.
960
+ * @param manifestPath - Path to stripe-app.json or stripe-app.yaml
961
+ * @returns Loaded manifest instance
962
+ */
963
+ static async load(manifestPath) {
964
+ const version = __StripeAppManifest.detectVersion(manifestPath);
965
+ if (version === "v1") {
966
+ const reader = _ManifestV1.load(manifestPath);
967
+ return new __StripeAppManifest(manifestPath, version, reader, null);
968
+ } else {
969
+ const reader = await _ManifestV2.load(manifestPath);
970
+ return new __StripeAppManifest(manifestPath, version, null, reader);
971
+ }
972
+ }
973
+ /**
974
+ * Detect manifest version from file path.
975
+ * TODO: Add content-based detection if needed.
976
+ */
977
+ static detectVersion(manifestPath) {
978
+ const lowerPath = manifestPath.toLowerCase();
979
+ if (lowerPath.endsWith(".yaml") || lowerPath.endsWith(".yml")) {
980
+ return "v2";
981
+ }
982
+ if (lowerPath.endsWith(".json")) {
983
+ return "v1";
984
+ }
985
+ throw new Error(
986
+ `Cannot detect manifest version from path: ${manifestPath}. Expected .json (v1) or .yaml/.yml (v2) extension.`
987
+ );
988
+ }
989
+ /**
990
+ * Get the detected manifest version
991
+ */
992
+ getVersion() {
993
+ return this.version;
994
+ }
995
+ /**
996
+ * Get the manifest file path
997
+ */
998
+ getManifestPath() {
999
+ return this.manifestPath;
1000
+ }
1001
+ // ============================================================
1002
+ // App Metadata (supported by both V1 and V2)
1003
+ // ============================================================
1004
+ /**
1005
+ * Get the app ID from the manifest
1006
+ */
1007
+ getAppId() {
1008
+ if (this.v1) {
1009
+ return this.v1.getAppId();
1010
+ }
1011
+ if (this.v2) {
1012
+ return this.v2.getAppId();
1013
+ }
1014
+ return void 0;
1015
+ }
1016
+ /**
1017
+ * Get the app name from the manifest
1018
+ */
1019
+ getAppName() {
1020
+ if (this.v1) {
1021
+ return this.v1.getAppName();
1022
+ }
1023
+ if (this.v2) {
1024
+ return this.v2.getAppName();
1025
+ }
1026
+ return void 0;
1027
+ }
1028
+ // ============================================================
1029
+ // Custom Objects (supported by both V1 and V2)
1030
+ // ============================================================
1031
+ /**
1032
+ * Get all custom objects from the manifest
1033
+ */
1034
+ getCustomObjects() {
1035
+ if (this.v1) {
1036
+ return this.v1.getCustomObjects();
1037
+ }
1038
+ if (this.v2) {
1039
+ return this.v2.getCustomObjects().map((obj) => ({
1040
+ filePath: obj.path,
1041
+ className: obj.name
1042
+ }));
1043
+ }
1044
+ return [];
1045
+ }
1046
+ /**
1047
+ * Check if a custom object entry exists in the manifest.
1048
+ *
1049
+ * **V2 note:** Identity is keyed on `_toSnakeCase(className)` alone — `filePath`
1050
+ * is not considered. Two entries with the same class name but different file
1051
+ * paths are treated as the same object. The `_toSnakeCase` → `_toPascalCase`
1052
+ * round-trip is lossless for typical class names but lossy for consecutive
1053
+ * uppercase (e.g., `HTTPClient` → `http_client` → `HttpClient`). The manifest
1054
+ * `id` field is the source of truth; see `_CustomObjectDefinitionYaml` docs.
1055
+ */
1056
+ hasCustomObject(entry) {
1057
+ if (this.v1) {
1058
+ return this.v1.hasCustomObject(entry);
1059
+ }
1060
+ if (this.v2) {
1061
+ return this.v2.hasCustomObject(_toSnakeCase(entry.className));
1062
+ }
1063
+ return false;
1064
+ }
1065
+ /**
1066
+ * Add a custom object entry to the manifest.
1067
+ *
1068
+ * **V2 note:** The manifest `id` is derived as `_toSnakeCase(className)` and
1069
+ * `filePath` is stored as the specification `content` path. Identity/dedup
1070
+ * is based on `id` alone — see `hasCustomObject` for details.
1071
+ *
1072
+ * @param entry - The custom object entry to add
1073
+ * @returns true if entry was added, false if it already existed
1074
+ */
1075
+ addCustomObject(entry) {
1076
+ if (this.v1) {
1077
+ return this.v1.addCustomObject(entry);
1078
+ }
1079
+ if (this.v2) {
1080
+ return this.v2.addCustomObject(_toSnakeCase(entry.className), entry.filePath);
1081
+ }
1082
+ return false;
1083
+ }
1084
+ /**
1085
+ * Remove a custom object entry from the manifest.
1086
+ *
1087
+ * **V2 note:** Removal is keyed on `_toSnakeCase(className)` — `filePath` is
1088
+ * not considered. See `hasCustomObject` for identity semantics.
1089
+ *
1090
+ * @param entry - The custom object entry to remove
1091
+ * @returns true if entry was removed, false if it didn't exist
1092
+ */
1093
+ removeCustomObject(entry) {
1094
+ if (this.v1) {
1095
+ return this.v1.removeCustomObject(entry);
1096
+ }
1097
+ if (this.v2) {
1098
+ return this.v2.removeCustomObject(_toSnakeCase(entry.className));
1099
+ }
1100
+ return false;
1101
+ }
1102
+ // ============================================================
1103
+ // Extensions (V2 only)
1104
+ // ============================================================
1105
+ /**
1106
+ * Get all extensions from the manifest
1107
+ * @throws Error if manifest version doesn't support extensions
1108
+ */
1109
+ getExtensions() {
1110
+ if (this.v2) {
1111
+ return this.v2.getExtensions();
1112
+ }
1113
+ throw new Error("Extensions are not supported in V1 manifests (stripe-app.json)");
1114
+ }
1115
+ /**
1116
+ * Add or update an extension in the manifest.
1117
+ * If an extension with the same ID exists, it will be replaced.
1118
+ *
1119
+ * @param config - Full extension configuration
1120
+ * @returns The extension ID
1121
+ * @throws Error if manifest version doesn't support extensions
1122
+ */
1123
+ addOrUpdateExtension(config) {
1124
+ if (this.v2) {
1125
+ return this.v2.addOrUpdateExtension(config);
1126
+ }
1127
+ throw new Error("Extensions are not supported in V1 manifests (stripe-app.json)");
1128
+ }
1129
+ // ============================================================
1130
+ // Persistence
1131
+ // ============================================================
1132
+ /**
1133
+ * Save changes back to disk
1134
+ */
1135
+ async save() {
1136
+ if (this.v1) {
1137
+ this.v1.save();
1138
+ return;
1139
+ }
1140
+ if (this.v2) {
1141
+ await this.v2.save();
1142
+ return;
1143
+ }
1144
+ throw new Error("No reader loaded - this should never happen");
1145
+ }
1146
+ };
1147
+
1148
+ // src/templates/template-manager.ts
1149
+ import { _TemplateManager } from "@stripe/extensibility-tool-utils";
1150
+
1151
+ // src/templates/fs/in-memory.ts
1152
+ import { _createInMemoryTemplateFS } from "@stripe/extensibility-tool-utils";
1153
+
1154
+ // templates-virtual:./_impl.js
1155
+ var TEMPLATE_FS_IMAGE = [
1156
+ {
1157
+ path: "extensions/billing.bill.discount_calculation/index.test.ts",
1158
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1159
+
1160
+ import MyDiscountCalculation from './index.js';
1161
+
1162
+ describe('MyDiscountCalculation', () => {
1163
+ let instance: MyDiscountCalculation;
1164
+
1165
+ beforeEach(() => {
1166
+ instance = new MyDiscountCalculation();
1167
+ });
1168
+
1169
+ it('should be constructable', () => {
1170
+ expect(instance).toBeInstanceOf(MyDiscountCalculation);
1171
+ });
1172
+ });
1173
+ `
1174
+ },
1175
+ {
1176
+ path: "extensions/billing.bill.discount_calculation/index.ts",
1177
+ content: `import type { Billing } from '@stripe/extensibility-sdk/extensions';
1178
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
1179
+
1180
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1181
+ interface MyDiscountCalculationConfig extends Record<string, unknown> {}
1182
+
1183
+ export default class MyDiscountCalculation implements Billing.Bill
1184
+ .DiscountCalculation<MyDiscountCalculationConfig> {
1185
+ computeDiscounts(
1186
+ request: Billing.Bill.DiscountCalculation.DiscountableItem,
1187
+ _config: MyDiscountCalculationConfig,
1188
+ _context: Context
1189
+ ) {
1190
+ // TODO: implement your discount logic here
1191
+
1192
+ return {
1193
+ discount: { amount: request.grossAmount },
1194
+ };
1195
+ }
1196
+ }
1197
+ `
1198
+ },
1199
+ {
1200
+ path: "extensions/billing.customer_balance_application/index.test.ts",
1201
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1202
+
1203
+ import MyCustomerBalanceApplication from './index.js';
1204
+
1205
+ describe('MyCustomerBalanceApplication', () => {
1206
+ let instance: MyCustomerBalanceApplication;
1207
+
1208
+ beforeEach(() => {
1209
+ instance = new MyCustomerBalanceApplication();
1210
+ });
1211
+
1212
+ it('should be constructable', () => {
1213
+ expect(instance).toBeInstanceOf(MyCustomerBalanceApplication);
1214
+ });
1215
+ });
1216
+ `
1217
+ },
1218
+ {
1219
+ path: "extensions/billing.customer_balance_application/index.ts",
1220
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
1221
+
1222
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1223
+ interface MyCustomerBalanceApplicationConfig extends Record<string, unknown> {}
1224
+
1225
+ export default class MyCustomerBalanceApplication implements Billing.CustomerBalanceApplication<MyCustomerBalanceApplicationConfig> {
1226
+ computeAppliedCustomerBalance(
1227
+ request: Billing.CustomerBalanceApplication.CustomerBalanceApplicationInput,
1228
+ _config: MyCustomerBalanceApplicationConfig,
1229
+ _context: Context
1230
+ ) {
1231
+ // TODO: implement your customer balance logic here
1232
+
1233
+ return {
1234
+ appliedCustomerBalance: request.customerBalance,
1235
+ };
1236
+ }
1237
+ }
1238
+ `
1239
+ },
1240
+ {
1241
+ path: "extensions/billing.invoice_collection_setting/index.test.ts",
1242
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1243
+
1244
+ import MyInvoiceCollectionSetting from './index.js';
1245
+
1246
+ describe('MyInvoiceCollectionSetting', () => {
1247
+ let instance: MyInvoiceCollectionSetting;
1248
+
1249
+ beforeEach(() => {
1250
+ instance = new MyInvoiceCollectionSetting();
1251
+ });
1252
+
1253
+ it('should be constructable', () => {
1254
+ expect(instance).toBeInstanceOf(MyInvoiceCollectionSetting);
1255
+ });
1256
+ });
1257
+ `
1258
+ },
1259
+ {
1260
+ path: "extensions/billing.invoice_collection_setting/index.ts",
1261
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
1262
+
1263
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1264
+ interface MyInvoiceCollectionSettingConfig extends Record<string, unknown> {}
1265
+
1266
+ export default class MyInvoiceCollectionSetting implements Billing.InvoiceCollectionSetting<MyInvoiceCollectionSettingConfig> {
1267
+ collectionOverride(
1268
+ _request: Billing.InvoiceCollectionSetting.InvoiceCollectionRequest,
1269
+ _config: MyInvoiceCollectionSettingConfig,
1270
+ _context: Context
1271
+ ) {
1272
+ // TODO: implement your collection setting logic here
1273
+
1274
+ return {};
1275
+ }
1276
+ }
1277
+ `
1278
+ },
1279
+ {
1280
+ path: "extensions/billing.prorations/index.test.ts",
1281
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1282
+
1283
+ import MyProrations from './index.js';
1284
+
1285
+ describe('MyProrations', () => {
1286
+ let instance: MyProrations;
1287
+
1288
+ beforeEach(() => {
1289
+ instance = new MyProrations();
1290
+ });
1291
+
1292
+ it('should be constructable', () => {
1293
+ expect(instance).toBeInstanceOf(MyProrations);
1294
+ });
1295
+ });
1296
+ `
1297
+ },
1298
+ {
1299
+ path: "extensions/billing.prorations/index.ts",
1300
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
1301
+
1302
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1303
+ interface MyProrationsConfig extends Record<string, unknown> {}
1304
+
1305
+ export default class MyProrations implements Billing.Prorations<MyProrationsConfig> {
1306
+ prorateItems(
1307
+ _request: Billing.Prorations.ProrateItemsInput,
1308
+ _config: MyProrationsConfig,
1309
+ _context: Context
1310
+ ) {
1311
+ // TODO: implement your proration logic here
1312
+
1313
+ return {
1314
+ items: [],
1315
+ };
1316
+ }
1317
+ }
1318
+ `
1319
+ },
1320
+ {
1321
+ path: "extensions/billing.recurring_billing_item_handling/index.test.ts",
1322
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1323
+
1324
+ import MyRecurringBillingItemHandling from './index.js';
1325
+
1326
+ describe('MyRecurringBillingItemHandling', () => {
1327
+ let instance: MyRecurringBillingItemHandling;
1328
+
1329
+ beforeEach(() => {
1330
+ instance = new MyRecurringBillingItemHandling();
1331
+ });
1332
+
1333
+ it('should be constructable', () => {
1334
+ expect(instance).toBeInstanceOf(MyRecurringBillingItemHandling);
1335
+ });
1336
+ });
1337
+ `
1338
+ },
1339
+ {
1340
+ path: "extensions/billing.recurring_billing_item_handling/index.ts",
1341
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
1342
+
1343
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1344
+ interface MyRecurringBillingItemHandlingConfig extends Record<string, unknown> {}
1345
+
1346
+ export default class MyRecurringBillingItemHandling implements Billing.RecurringBillingItemHandling<MyRecurringBillingItemHandlingConfig> {
1347
+ beforeItemCreation(
1348
+ _request: Billing.RecurringBillingItemHandling.BeforeItemCreationInput,
1349
+ _config: MyRecurringBillingItemHandlingConfig,
1350
+ _context: Context
1351
+ ) {
1352
+ // TODO: implement your before-item-creation logic here
1353
+
1354
+ return {
1355
+ items: [],
1356
+ };
1357
+ }
1358
+
1359
+ filterItems(
1360
+ _request: Billing.RecurringBillingItemHandling.FilterItemsInput,
1361
+ _config: MyRecurringBillingItemHandlingConfig,
1362
+ _context: Context
1363
+ ) {
1364
+ // TODO: implement your filter-items logic here
1365
+
1366
+ return {
1367
+ items: [],
1368
+ };
1369
+ }
1370
+
1371
+ groupItems(
1372
+ _request: Billing.RecurringBillingItemHandling.GroupItemsInput,
1373
+ _config: MyRecurringBillingItemHandlingConfig,
1374
+ _context: Context
1375
+ ) {
1376
+ // TODO: implement your group-items logic here
1377
+
1378
+ return {
1379
+ groups: [],
1380
+ };
1381
+ }
1382
+ }
1383
+ `
1384
+ },
1385
+ {
1386
+ path: "extensions/common/.prettierignore",
1387
+ content: `dist
1388
+ generated
1389
+ node_modules
1390
+ `
1391
+ },
1392
+ {
1393
+ path: "extensions/common/eslint.config.mts.mustache",
1394
+ content: `import eslint from '@eslint/js';
1395
+ import { defineConfig } from 'eslint/config';
1396
+ import tseslint from 'typescript-eslint';
1397
+ import eslintConfigPrettier from 'eslint-config-prettier/flat';
1398
+
1399
+ import globals from 'globals';
1400
+
1401
+ import stripeAppsConfig from '@stripe/extensibility-eslint-plugin';
1402
+ import extensionTypeConfig from '@stripe/extensibility-eslint-plugin/{{extensionInterfaceId}}';
1403
+
1404
+ export default defineConfig([
1405
+ eslint.configs.recommended,
1406
+ ...tseslint.configs.recommended,
1407
+ ...stripeAppsConfig,
1408
+ ...extensionTypeConfig,
1409
+
1410
+ // Global ignores
1411
+ {
1412
+ ignores: ['dist', 'generated', 'node_modules'],
1413
+ },
1414
+
1415
+ // TypeScript source files (with type-checking)
1416
+ {
1417
+ name: 'sources',
1418
+ files: ['src/**/*.ts'],
1419
+ ignores: ['**/*.test.ts', '**/__tests__/**'],
1420
+ languageOptions: {
1421
+ globals: {
1422
+ ...globals.node,
1423
+ },
1424
+ parserOptions: {
1425
+ projectService: true,
1426
+ tsconfigRootDir: import.meta.dirname,
1427
+ },
1428
+ },
1429
+ },
1430
+
1431
+ // Test files (type-checking, relaxed rules)
1432
+ {
1433
+ name: 'tests',
1434
+ files: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts'],
1435
+ languageOptions: {
1436
+ globals: {
1437
+ ...globals.node,
1438
+ },
1439
+ parserOptions: {
1440
+ projectService: true,
1441
+ tsconfigRootDir: import.meta.dirname,
1442
+ },
1443
+ },
1444
+ rules: {
1445
+ '@typescript-eslint/no-explicit-any': 'off',
1446
+ '@typescript-eslint/no-unused-vars': 'off',
1447
+ 'no-console': 'off',
1448
+ },
1449
+ },
1450
+
1451
+ // Config files
1452
+ {
1453
+ name: 'ts-configs',
1454
+ files: ['*.config.m?ts', 'eslint.config.mts'],
1455
+ languageOptions: {
1456
+ globals: {
1457
+ ...globals.node,
1458
+ },
1459
+ parserOptions: {
1460
+ projectService: false,
1461
+ },
1462
+ },
1463
+ rules: {
1464
+ '@typescript-eslint/no-unused-vars': 'off',
1465
+ },
1466
+ },
1467
+
1468
+ // JavaScript/MJS files (scripts, configs)
1469
+ {
1470
+ name: 'js-configs',
1471
+ files: ['**/*.js', '**/*.mjs'],
1472
+ languageOptions: {
1473
+ globals: {
1474
+ ...globals.node,
1475
+ },
1476
+ parserOptions: {
1477
+ projectService: false,
1478
+ },
1479
+ },
1480
+ rules: {
1481
+ '@typescript-eslint/no-require-imports': 'off',
1482
+ '@typescript-eslint/no-unused-vars': 'off',
1483
+ 'no-unused-vars': 'off',
1484
+ },
1485
+ },
1486
+
1487
+ eslintConfigPrettier,
1488
+ ]);
1489
+ `
1490
+ },
1491
+ {
1492
+ path: "extensions/common/package.json.mustache",
1493
+ content: `{
1494
+ "name": "{{id}}",
1495
+ "version": "{{version}}",
1496
+ "description": "{{name}}",
1497
+ "private": true,
1498
+ "license": "~~proprietary~~",
1499
+ "type": "module",
1500
+ "scripts": {
1501
+ "build": "tsc -p tsconfig.build.json && pnpm build:schemas",
1502
+ "build:schemas": "gen-schemas --root ../.. --extension-id \\"$npm_package_name\\" --out-dir generated --schema-name config",
1503
+ "lint": "pnpm lint:types && pnpm lint:eslint && pnpm lint:format",
1504
+ "lint:types": "tsc -p tsconfig.build.json --noEmit && tsc -p tsconfig.json --noEmit",
1505
+ "lint:eslint": "eslint .",
1506
+ "lint:format": "prettier --check .",
1507
+ "fix:lint": "eslint --fix .",
1508
+ "fix:format": "prettier --write .",
1509
+ "test": "vitest --root ../.. run --project \\"$npm_package_name\\"",
1510
+ "test:watch": "pnpm test --watch",
1511
+ "dev": "concurrently -n build,lint,test -c blue,yellow,green 'tsc -p tsconfig.json -w --noEmit' 'chokidar \\"src/**/*.{ts,json}\\" -c \\"eslint .\\"' 'pnpm test --watch --no-clear-screen'",
1512
+ "stripe:regen": "gen-workspace --root ../.. --package-dir . --template-id {{extensionInterfaceId}}"
1513
+ },
1514
+ "lint-staged": {
1515
+ "*.{ts,mts,mjs,js}": ["eslint --fix", "prettier --write"],
1516
+ "*.{json,md,yaml}": "prettier --write"
1517
+ }
1518
+ }
1519
+ `
1520
+ },
1521
+ {
1522
+ path: "extensions/common/tsconfig.build.json.mustache",
1523
+ content: `{
1524
+ "extends": "../../tsconfig.base.json",
1525
+ "compilerOptions": {
1526
+ "lib": null,
1527
+ "noLib": true,
1528
+ "outDir": "./dist",
1529
+ "rootDir": "./src"
1530
+ },
1531
+ "include": [
1532
+ "src/**/*.ts",
1533
+ "node_modules/@stripe/extensibility-sdk/tslibs/5.9.3/lib.es2022.{{executionProfile}}.d.ts",
1534
+ "node_modules/@stripe/extensibility-sdk/tslibs/lib.{{executionProfile}}.globals.d.ts"
1535
+ ],
1536
+ "exclude": ["src/**/*.test.ts", "src/**/__tests__"]
1537
+ }
1538
+ `
1539
+ },
1540
+ {
1541
+ path: "extensions/common/tsconfig.json.mustache",
1542
+ content: `{
1543
+ "extends": "../../tsconfig.json",
1544
+ "compilerOptions": {
1545
+ "rootDir": ".",
1546
+ "plugins": [
1547
+ {
1548
+ "name": "@stripe/extensibility-language-server/plugin"
1549
+ }
1550
+ ]
1551
+ },
1552
+ "include": [
1553
+ "src/**/*.ts",
1554
+ "node_modules/@stripe/extensibility-sdk/tslibs/lib.{{executionProfile}}.globals.d.ts"
1555
+ ],
1556
+ "exclude": ["dist"]
1557
+ }
1558
+ `
1559
+ },
1560
+ {
1561
+ path: "extensions/core.workflows.custom_action/custom_input.schema.json",
1562
+ content: `{
1563
+ "$schema": "http://json-schema.org/draft-07/schema#",
1564
+ "type": "object",
1565
+ "properties": {},
1566
+ "additionalProperties": false
1567
+ }
1568
+ `
1569
+ },
1570
+ {
1571
+ path: "extensions/core.workflows.custom_action/index.test.ts",
1572
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1573
+
1574
+ import MyCustomAction from './index.js';
1575
+
1576
+ describe('MyCustomAction', () => {
1577
+ let instance: MyCustomAction;
1578
+
1579
+ beforeEach(() => {
1580
+ instance = new MyCustomAction();
1581
+ });
1582
+
1583
+ it('should be constructable', () => {
1584
+ expect(instance).toBeInstanceOf(MyCustomAction);
1585
+ });
1586
+ });
1587
+ `
1588
+ },
1589
+ {
1590
+ path: "extensions/core.workflows.custom_action/index.ts",
1591
+ content: `import type { Core } from '@stripe/extensibility-sdk/extensions';
1592
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
1593
+
1594
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1595
+ interface MyCustomActionConfig extends Record<string, unknown> {}
1596
+
1597
+ export default class MyCustomAction implements Core.Workflows
1598
+ .CustomAction<MyCustomActionConfig> {
1599
+ execute(
1600
+ _request: Core.Workflows.CustomAction.ExecuteCustomActionRequest,
1601
+ _config: MyCustomActionConfig,
1602
+ _context: Context
1603
+ ) {
1604
+ // TODO: implement your action logic here
1605
+
1606
+ return {};
1607
+ }
1608
+
1609
+ getFormState(
1610
+ _request: Core.Workflows.CustomAction.GetFormStateRequest,
1611
+ _config: MyCustomActionConfig,
1612
+ _context: Context
1613
+ ) {
1614
+ // TODO: implement your logic here
1615
+
1616
+ return {
1617
+ values: {},
1618
+ config: {},
1619
+ };
1620
+ }
1621
+ }
1622
+ `
1623
+ },
1624
+ {
1625
+ path: "extensions/extend.workflows.custom_action/custom_input.schema.json",
1626
+ content: `{
1627
+ "$schema": "http://json-schema.org/draft-07/schema#",
1628
+ "type": "object",
1629
+ "properties": {},
1630
+ "additionalProperties": false
1631
+ }
1632
+ `
1633
+ },
1634
+ {
1635
+ path: "extensions/extend.workflows.custom_action/index.test.ts",
1636
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
1637
+
1638
+ import MyCustomAction from './index.js';
1639
+
1640
+ describe('MyCustomAction', () => {
1641
+ let instance: MyCustomAction;
1642
+
1643
+ beforeEach(() => {
1644
+ instance = new MyCustomAction();
1645
+ });
1646
+
1647
+ it('should be constructable', () => {
1648
+ expect(instance).toBeInstanceOf(MyCustomAction);
1649
+ });
1650
+ });
1651
+ `
1652
+ },
1653
+ {
1654
+ path: "extensions/extend.workflows.custom_action/index.ts",
1655
+ content: `import type { Extend } from '@stripe/extensibility-sdk/extensions';
1656
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
1657
+
1658
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1659
+ interface MyCustomActionConfig extends Record<string, unknown> {}
1660
+
1661
+ export default class MyCustomAction implements Extend.Workflows
1662
+ .CustomAction<MyCustomActionConfig> {
1663
+ execute(
1664
+ _request: Extend.Workflows.CustomAction.ExecuteCustomActionRequest,
1665
+ _config: MyCustomActionConfig,
1666
+ _context: Context
1667
+ ) {
1668
+ // TODO: implement your action logic here
1669
+
1670
+ return {};
1671
+ }
1672
+
1673
+ getFormState(
1674
+ _request: Extend.Workflows.CustomAction.GetFormStateRequest,
1675
+ _config: MyCustomActionConfig,
1676
+ _context: Context
1677
+ ) {
1678
+ // TODO: implement your logic here
1679
+
1680
+ return {
1681
+ values: {},
1682
+ config: {},
1683
+ };
1684
+ }
1685
+ }
1686
+ `
1687
+ },
1688
+ {
1689
+ path: "root/.husky/pre-commit",
1690
+ content: `pnpm lint-staged
1691
+ `
1692
+ },
1693
+ {
1694
+ path: "root/.prettierignore",
1695
+ content: `dist
1696
+ generated
1697
+ node_modules
1698
+ pnpm-lock.yaml
1699
+ .build
1700
+ `
1701
+ },
1702
+ {
1703
+ path: "root/.prettierrc",
1704
+ content: `{
1705
+ "semi": true,
1706
+ "singleQuote": true,
1707
+ "tabWidth": 2,
1708
+ "trailingComma": "es5",
1709
+ "printWidth": 90
1710
+ }
1711
+ `
1712
+ },
1713
+ {
1714
+ path: "root/_gitignore",
1715
+ content: `# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
1716
+
1717
+ *~
1718
+
1719
+ # dependencies
1720
+ node_modules
1721
+ dist
1722
+
1723
+ # testing
1724
+ /coverage
1725
+
1726
+ # production
1727
+ /.build
1728
+
1729
+ # misc
1730
+ .DS_Store
1731
+ .env.local
1732
+ .env.development.local
1733
+ .env.test.local
1734
+ .env.production.local
1735
+
1736
+ npm-debug.log*
1737
+ yarn-debug.log*
1738
+ yarn-error.log*
1739
+ install-deps.log
1740
+
1741
+ # generated schemas
1742
+ generated
1743
+ `
1744
+ },
1745
+ {
1746
+ path: "root/custom-objects/package.json",
1747
+ content: `{
1748
+ "name": "custom-objects",
1749
+ "type": "module",
1750
+ "version": "0.0.1",
1751
+ "license": "UNLICENSED",
1752
+ "private": true,
1753
+ "scripts": {
1754
+ "build": "test -d src && custom-objects-build --input src --output dist || true",
1755
+ "lint:types": "test ! -d src || tsc --noEmit",
1756
+ "test": "vitest run"
1757
+ },
1758
+ "dependencies": {
1759
+ "@stripe/extensibility-custom-objects": "0.7.4",
1760
+ "@stripe/extensibility-sdk": "0.22.4"
1761
+ },
1762
+ "devDependencies": {
1763
+ "@stripe/extensibility-custom-objects-tools": "0.40.0",
1764
+ "@stripe/extensibility-test-helpers": "0.2.7"
1765
+ }
1766
+ }
1767
+ `
1768
+ },
1769
+ {
1770
+ path: "root/custom-objects/tsconfig.json",
1771
+ content: `{
1772
+ "extends": "../tsconfig.base.json",
1773
+ "compilerOptions": {
1774
+ "module": "ESNext",
1775
+ "moduleResolution": "bundler",
1776
+ "types": ["vitest/globals"]
1777
+ },
1778
+ "exclude": ["dist"]
1779
+ }
1780
+ `
1781
+ },
1782
+ {
1783
+ path: "root/eslint.config.mts",
1784
+ content: `import { readFileSync } from 'node:fs';
1785
+ import { dirname, resolve } from 'node:path';
1786
+ import { fileURLToPath } from 'node:url';
1787
+ import eslint from '@eslint/js';
1788
+ import { defineConfig } from 'eslint/config';
1789
+ import tseslint from 'typescript-eslint';
1790
+ import workspaces from 'eslint-plugin-workspaces';
1791
+ import eslintConfigPrettier from 'eslint-config-prettier/flat';
1792
+
1793
+ import globals from 'globals';
1794
+
1795
+ import stripeAppsConfig from '@stripe/extensibility-eslint-plugin';
1796
+
1797
+ // Read additional ignore globs from package.json (written by the generate plugin
1798
+ // to exclude generated SDK directories from linting).
1799
+ let stripeGlobsToIgnore: string[] = [];
1800
+ try {
1801
+ const configDir = dirname(fileURLToPath(import.meta.url));
1802
+ const packageJsonPath = resolve(configDir, './package.json');
1803
+ const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
1804
+ const globs = pkg?.stripe?.eslintIgnoreGlobs;
1805
+ if (Array.isArray(globs)) {
1806
+ stripeGlobsToIgnore = globs.filter(
1807
+ (g: unknown): g is string => typeof g === 'string'
1808
+ );
1809
+ }
1810
+ } catch {
1811
+ // package.json not found or unparseable \u2014 ignore
1812
+ }
1813
+
1814
+ export default defineConfig([
1815
+ eslint.configs.recommended,
1816
+ ...tseslint.configs.recommended,
1817
+ ...stripeAppsConfig,
1818
+
1819
+ // Global ignores
1820
+ {
1821
+ ignores: [
1822
+ '.build',
1823
+ '**/dist',
1824
+ '**/generated',
1825
+ '**/node_modules',
1826
+ 'extensions/**',
1827
+ 'custom-objects',
1828
+ 'ui',
1829
+ ...stripeGlobsToIgnore,
1830
+ ],
1831
+ },
1832
+
1833
+ // Common rules for all files
1834
+ {
1835
+ plugins: { workspaces },
1836
+ rules: {
1837
+ ...workspaces.configs.recommended.rules,
1838
+ },
1839
+ },
1840
+
1841
+ // Config files (vitest.config.ts, eslint.config.ts, etc.)
1842
+ {
1843
+ name: 'ts-configs',
1844
+ files: ['extensions/*/*.config.m?ts', '*.config.m?ts', 'eslint.config.mts'],
1845
+ languageOptions: {
1846
+ globals: {
1847
+ ...globals.node,
1848
+ },
1849
+ parserOptions: {
1850
+ projectService: false,
1851
+ },
1852
+ },
1853
+ rules: {
1854
+ '@typescript-eslint/no-unused-vars': 'off',
1855
+ },
1856
+ },
1857
+
1858
+ // JavaScript/MJS files (scripts, configs)
1859
+ {
1860
+ name: 'js-configs',
1861
+ files: ['**/*.js', '**/*.mjs'],
1862
+ languageOptions: {
1863
+ globals: {
1864
+ ...globals.node,
1865
+ },
1866
+ parserOptions: {
1867
+ projectService: false,
1868
+ },
1869
+ },
1870
+ rules: {
1871
+ '@typescript-eslint/no-require-imports': 'off',
1872
+ '@typescript-eslint/no-unused-vars': 'off',
1873
+ 'no-unused-vars': 'off',
1874
+ },
1875
+ },
1876
+
1877
+ eslintConfigPrettier,
1878
+ ]);
1879
+ `
1880
+ },
1881
+ {
1882
+ path: "root/package.json.mustache",
1883
+ content: `{
1884
+ "name": "{{ appId }}",
1885
+ "version": "{{ version }}",
1886
+ "description": "{{ appName }}",
1887
+ "private": true,
1888
+ "license": "~~proprietary~~",
1889
+ "engines": {
1890
+ "node": ">=20.0.0"
1891
+ },
1892
+ "packageManager": "pnpm@10.30.3",
1893
+ "scripts": {
1894
+ "build": "pnpm -r --if-present build",
1895
+ "lint": "pnpm lint:types && pnpm lint:eslint && pnpm lint:format",
1896
+ "lint:types": "pnpm -r --if-present lint:types",
1897
+ "lint:eslint": "eslint . --ignore-pattern 'extensions/**' && pnpm -r --filter './extensions/*' --if-present lint:eslint",
1898
+ "lint:format": "prettier --check .",
1899
+ "fix:lint": "eslint --fix . --ignore-pattern 'extensions/**' && pnpm -r --filter './extensions/*' --if-present fix:lint",
1900
+ "fix:format": "prettier --write .",
1901
+ "test": "tsx tools/test.mts",
1902
+ "test:watch": "vitest watch",
1903
+ "check": "pnpm build && pnpm lint && pnpm test",
1904
+ "prepare": "husky",
1905
+ "preimage": "pnpm install --lockfile-only && pnpm build && pnpm lint:types && pnpm lint:eslint && pnpm test",
1906
+ "image": "rm -rf .build && create-upload-image .build",
1907
+ "postimage": "cp pnpm-lock.yaml .build/",
1908
+ "stripe:regen": "gen-workspace --package-dir ."
1909
+ },
1910
+ "lint-staged": {
1911
+ "*.{ts,mts,mjs,js}": ["eslint --fix", "prettier --write"],
1912
+ "*.{json,md,yaml}": "prettier --write"
1913
+ }
1914
+ }
1915
+ `
1916
+ },
1917
+ {
1918
+ path: "root/pnpm-workspace.yaml",
1919
+ content: `packages:
1920
+ - extensions/*
1921
+ - custom-objects
1922
+ - ui
1923
+
1924
+ overrides:
1925
+ vite: ^6.0.0
1926
+ `
1927
+ },
1928
+ {
1929
+ path: "root/stripe-app.yaml.mustache",
1930
+ content: `$schema: https://stripe.com/stripe-app/v2.0.0/schema
1931
+ id: '{{ appId }}'
1932
+ name: '{{ appName }}'
1933
+ version: 0.0.1
1934
+ declarations:
1935
+ distribution_type: private
1936
+ `
1937
+ },
1938
+ {
1939
+ path: "root/tools/test.mts",
1940
+ content: `#!/usr/bin/env tsx
1941
+ /**
1942
+ * Runs tests across the workspace:
1943
+ * - vitest for script extensions and custom objects (extensions/*)
1944
+ * - jest for UI extensions (ui/)
1945
+ */
1946
+ import { existsSync, readdirSync } from 'node:fs';
1947
+ import { execSync } from 'node:child_process';
1948
+
1949
+ const hasExtensions =
1950
+ existsSync('extensions') &&
1951
+ readdirSync('extensions').some((name) => existsSync(\`extensions/\${name}/package.json\`));
1952
+
1953
+ const hasUI = existsSync('ui/package.json');
1954
+
1955
+ let exitCode = 0;
1956
+
1957
+ function run(cmd: string): void {
1958
+ try {
1959
+ execSync(cmd, { stdio: 'inherit' });
1960
+ } catch (e: unknown) {
1961
+ exitCode = (e as NodeJS.ErrnoException & { status?: number }).status ?? 1;
1962
+ }
1963
+ }
1964
+
1965
+ if (hasExtensions) {
1966
+ run('vitest run');
1967
+ }
1968
+
1969
+ if (hasUI) {
1970
+ try {
1971
+ execSync('pnpm --filter "./ui" test', { stdio: 'inherit' });
1972
+ } catch {
1973
+ // UI test failures are non-fatal
1974
+ }
1975
+ }
1976
+
1977
+ process.exit(exitCode);
1978
+ `
1979
+ },
1980
+ {
1981
+ path: "root/tsconfig.base.json",
1982
+ content: `{
1983
+ "compilerOptions": {
1984
+ "target": "ES2022",
1985
+ "module": "NodeNext",
1986
+ "moduleResolution": "NodeNext",
1987
+ "lib": ["ES2022"],
1988
+ "declaration": true,
1989
+ "declarationMap": true,
1990
+ "esModuleInterop": true,
1991
+ "exactOptionalPropertyTypes": false,
1992
+ "forceConsistentCasingInFileNames": true,
1993
+ "isolatedModules": true,
1994
+ "noFallthroughCasesInSwitch": true,
1995
+ "noImplicitReturns": true,
1996
+ "removeComments": false,
1997
+ "resolveJsonModule": true,
1998
+ "skipLibCheck": true,
1999
+ "sourceMap": true,
2000
+ "strict": true,
2001
+ "types": [],
2002
+ "verbatimModuleSyntax": true
2003
+ }
2004
+ }
2005
+ `
2006
+ },
2007
+ {
2008
+ path: "root/tsconfig.json",
2009
+ content: `{
2010
+ "extends": "./tsconfig.base.json",
2011
+ "compilerOptions": {
2012
+ "noEmit": true,
2013
+ "plugins": [
2014
+ {
2015
+ "name": "@stripe/extensibility-language-server/plugin"
2016
+ }
2017
+ ],
2018
+ "preserveWatchOutput": true,
2019
+ "types": ["vitest/globals", "node"]
2020
+ },
2021
+ "include": ["**/*.ts"],
2022
+ "exclude": ["**/node_modules", "**/dist"]
2023
+ }
2024
+ `
2025
+ },
2026
+ {
2027
+ path: "root/ui/package.json",
2028
+ content: `{
2029
+ "name": "ui",
2030
+ "version": "0.0.1",
2031
+ "license": "UNLICENSED",
2032
+ "private": true,
2033
+ "scripts": {
2034
+ "test": "jest --passWithNoTests"
2035
+ },
2036
+ "dependencies": {
2037
+ "@stripe/ui-extension-sdk": "^9.1.0"
2038
+ },
2039
+ "devDependencies": {
2040
+ "@stripe/ui-extension-tools": "^0.0.1",
2041
+ "@types/jest": "^27.5.2",
2042
+ "@types/react": "^17.0.2"
2043
+ }
2044
+ }
2045
+ `
2046
+ },
2047
+ {
2048
+ path: "root/vitest.config.mts",
2049
+ content: `import { defineConfig } from 'vitest/config';
2050
+ import { existsSync, readdirSync } from 'fs';
2051
+ import { dirname, resolve } from 'path';
2052
+ import { fileURLToPath } from 'url';
2053
+
2054
+ const rootDir = dirname(fileURLToPath(import.meta.url));
2055
+ const extensionsDir = resolve(rootDir, 'extensions');
2056
+
2057
+ const extensionProjects = existsSync(extensionsDir)
2058
+ ? readdirSync(extensionsDir)
2059
+ .filter((name) => existsSync(resolve(extensionsDir, name, 'package.json')))
2060
+ .map((name) => resolve(extensionsDir, name))
2061
+ : [];
2062
+
2063
+ const coProjects = existsSync(resolve(rootDir, 'custom-objects/package.json'))
2064
+ ? [resolve(rootDir, 'custom-objects')]
2065
+ : [];
2066
+
2067
+ const projects = [...extensionProjects, ...coProjects];
2068
+
2069
+ if (projects.length === 0) {
2070
+ console.debug(\`No vitest projects detected. This means either:
2071
+ - You have no extension projects defined, in which case this warning is expected.
2072
+ - There is an internal error detecting vitest projects relative to the project root
2073
+ \${rootDir}.
2074
+ \`);
2075
+ }
2076
+
2077
+ export default projects.length > 0
2078
+ ? defineConfig({
2079
+ test: {
2080
+ projects,
2081
+ passWithNoTests: true,
2082
+
2083
+ // Only run tests from src, not compiled dist
2084
+ exclude: ['**/node_modules', '**/dist'],
2085
+ // Place snapshots alongside test files instead of in __snapshots__
2086
+ snapshotFormat: {
2087
+ escapeString: false,
2088
+ printBasicPrototype: false,
2089
+ },
2090
+ resolveSnapshotPath: (testPath, snapExtension) => {
2091
+ return testPath.replace(/\\.test\\.ts$/, \`.test\${snapExtension}\`);
2092
+ },
2093
+ },
2094
+ })
2095
+ : defineConfig({ test: { passWithNoTests: true, include: [] } });
2096
+ `
2097
+ }
2098
+ ];
2099
+ var _fs = _createInMemoryTemplateFS(TEMPLATE_FS_IMAGE);
2100
+
2101
+ // src/templates/simple-templates.ts
2102
+ import {
2103
+ _createSimpleTemplate,
2104
+ _SingleTemplateManager,
2105
+ _createSimpleSingleFileTemplate
2106
+ } from "@stripe/extensibility-tool-utils";
2107
+
2108
+ // src/templates/file-writer.ts
2109
+ import path2 from "path";
2110
+ import { mkdir, writeFile as writeFile2, readFile as readFile2 } from "fs/promises";
2111
+ import { createInterface } from "readline";
2112
+ import { _createLogger } from "@stripe/extensibility-tool-utils";
2113
+
2114
+ // src/templates/fs-utils.ts
2115
+ import { stat } from "fs/promises";
2116
+ async function pathExists(filePath, predicate) {
2117
+ try {
2118
+ const stats = await stat(filePath);
2119
+ return predicate(stats);
2120
+ } catch (error) {
2121
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
2122
+ return false;
2123
+ }
2124
+ throw error;
2125
+ }
2126
+ }
2127
+ async function fileExists(filePath) {
2128
+ return pathExists(filePath, (stats) => stats.isFile());
2129
+ }
2130
+ async function directoryExists(dirPath) {
2131
+ return pathExists(dirPath, (stats) => stats.isDirectory());
2132
+ }
2133
+
2134
+ // src/templates/file-writer.ts
2135
+ var logger = _createLogger({ name: "file-writer" });
2136
+ async function _promptOverwrite(filePath) {
2137
+ const prompt = `${filePath} exists. Overwrite [yNaq]? `;
2138
+ if (!process.stdin.isTTY) {
2139
+ const rl = createInterface({
2140
+ input: process.stdin,
2141
+ output: process.stdout
2142
+ });
2143
+ return new Promise((resolve) => {
2144
+ rl.question(prompt, (answer) => {
2145
+ rl.close();
2146
+ const normalized = answer.toLowerCase().trim();
2147
+ switch (normalized) {
2148
+ case "y":
2149
+ case "yes":
2150
+ resolve("overwrite");
2151
+ break;
2152
+ case "n":
2153
+ case "no":
2154
+ case "":
2155
+ resolve("skip");
2156
+ break;
2157
+ case "a":
2158
+ case "all":
2159
+ resolve("overwrite-all");
2160
+ break;
2161
+ case "q":
2162
+ case "quit":
2163
+ resolve("abort");
2164
+ break;
2165
+ default:
2166
+ logger.warn("Invalid input '%s', treating as 'no'", answer);
2167
+ resolve("skip");
2168
+ }
2169
+ });
2170
+ });
2171
+ }
2172
+ process.stdout.write(prompt);
2173
+ return new Promise((resolve) => {
2174
+ const stdin = process.stdin;
2175
+ const wasRaw = stdin.isRaw;
2176
+ stdin.setRawMode(true);
2177
+ stdin.resume();
2178
+ const onData = (buffer) => {
2179
+ stdin.setRawMode(wasRaw || false);
2180
+ stdin.pause();
2181
+ stdin.removeListener("data", onData);
2182
+ const key = buffer.toString();
2183
+ const code = buffer[0];
2184
+ if (code === 3) {
2185
+ process.stdout.write("\nCancelled.\n");
2186
+ setTimeout(() => process.exit(0), 100);
2187
+ return;
2188
+ }
2189
+ if (code === 13 || code === 10) {
2190
+ process.stdout.write("n\n");
2191
+ resolve("skip");
2192
+ return;
2193
+ }
2194
+ const normalized = key.toLowerCase();
2195
+ let decision;
2196
+ switch (normalized) {
2197
+ case "y":
2198
+ process.stdout.write("y\n");
2199
+ decision = "overwrite";
2200
+ break;
2201
+ case "n":
2202
+ process.stdout.write("n\n");
2203
+ decision = "skip";
2204
+ break;
2205
+ case "a":
2206
+ process.stdout.write("a\n");
2207
+ decision = "overwrite-all";
2208
+ break;
2209
+ case "q":
2210
+ process.stdout.write("q\n");
2211
+ decision = "abort";
2212
+ break;
2213
+ default:
2214
+ process.stdout.write(`${key}
2215
+ `);
2216
+ logger.warn("Invalid input '%s', treating as 'no'", key);
2217
+ decision = "skip";
2218
+ }
2219
+ resolve(decision);
2220
+ };
2221
+ stdin.on("data", onData);
2222
+ });
2223
+ }
2224
+ async function _writeGeneratedFiles(files, options = {}) {
2225
+ const { cwd = process.cwd(), onFileWritten, onFileSkipped, onFileIdentical } = options;
2226
+ let write = options.write ?? "abort-if-existing";
2227
+ const existing = [];
2228
+ for (const file of files) {
2229
+ const fullPath = path2.join(cwd, file.path);
2230
+ if (await fileExists(fullPath)) {
2231
+ existing.push(file.path);
2232
+ }
2233
+ }
2234
+ if (existing.length > 0 && write === "abort-if-existing") {
2235
+ if (onFileSkipped) {
2236
+ for (const file of files) {
2237
+ if (existing.includes(file.path)) {
2238
+ onFileSkipped(file);
2239
+ }
2240
+ }
2241
+ }
2242
+ return {
2243
+ written: [],
2244
+ existing,
2245
+ skipped: true,
2246
+ aborted: false
2247
+ };
2248
+ }
2249
+ const written = [];
2250
+ for (const file of files) {
2251
+ const fullPath = path2.join(cwd, file.path);
2252
+ const fileDir = path2.dirname(fullPath);
2253
+ const isExisting = existing.includes(file.path);
2254
+ if (isExisting) {
2255
+ const existingContent = await readFile2(fullPath, "utf-8");
2256
+ if (existingContent === file.content) {
2257
+ if (onFileIdentical) {
2258
+ onFileIdentical(file);
2259
+ }
2260
+ continue;
2261
+ }
2262
+ }
2263
+ if (isExisting && (write === "if-missing" || file.precious)) {
2264
+ if (onFileSkipped) {
2265
+ onFileSkipped(file);
2266
+ }
2267
+ continue;
2268
+ }
2269
+ if (isExisting && typeof write === "function") {
2270
+ const decision = await write(file.path, cwd, file.content);
2271
+ switch (decision) {
2272
+ case "skip":
2273
+ if (onFileSkipped) {
2274
+ onFileSkipped(file);
2275
+ }
2276
+ continue;
2277
+ case "overwrite":
2278
+ break;
2279
+ case "overwrite-all":
2280
+ write = "overwrite-all";
2281
+ break;
2282
+ case "abort":
2283
+ return {
2284
+ written,
2285
+ existing,
2286
+ skipped: false,
2287
+ aborted: true
2288
+ };
2289
+ }
2290
+ }
2291
+ if (!await directoryExists(fileDir)) {
2292
+ await mkdir(fileDir, { recursive: true });
2293
+ }
2294
+ await writeFile2(fullPath, file.content, "utf-8");
2295
+ if (onFileWritten) {
2296
+ onFileWritten(file, isExisting);
2297
+ }
2298
+ written.push(file.path);
2299
+ }
2300
+ return {
2301
+ written,
2302
+ existing,
2303
+ // Always populated; write='abort-if-existing' returns early above
2304
+ skipped: false,
2305
+ aborted: false
2306
+ };
2307
+ }
2308
+
2309
+ // src/templates/diff-viewer/diff-prompt.ts
2310
+ import path3 from "path";
2311
+
2312
+ // src/templates/diff-viewer/diff-generator.ts
2313
+ import { createPatch } from "diff";
2314
+ import { readFile as readFile3 } from "fs/promises";
2315
+ async function generateDiff(filePath, oldContent, newContent, contextLines = 3) {
2316
+ if (isBinary(oldContent) || isBinary(newContent)) {
2317
+ return {
2318
+ lines: [{ type: "header", text: "Binary file changed" }],
2319
+ oldFileName: filePath,
2320
+ newFileName: filePath,
2321
+ isBinary: true
2322
+ };
2323
+ }
2324
+ const patch = createPatch(filePath, oldContent, newContent, "existing", "new", {
2325
+ context: contextLines
2326
+ });
2327
+ const lines = parsePatch(patch);
2328
+ return {
2329
+ lines,
2330
+ oldFileName: filePath,
2331
+ newFileName: filePath,
2332
+ isBinary: false
2333
+ };
2334
+ }
2335
+ function parsePatch(patch) {
2336
+ const lines = [];
2337
+ const patchLines = patch.split("\n");
2338
+ let oldLine = 0;
2339
+ let newLine = 0;
2340
+ for (const line of patchLines) {
2341
+ if (line.startsWith("@@")) {
2342
+ const match = line.match(/@@ -(\d+),?\d* \+(\d+),?\d* @@/);
2343
+ if (match !== null) {
2344
+ oldLine = parseInt(match[1], 10);
2345
+ newLine = parseInt(match[2], 10);
2346
+ lines.push({ type: "header", text: line });
2347
+ }
2348
+ } else if (line.startsWith("+")) {
2349
+ lines.push({ type: "add", text: line, newLine: newLine++ });
2350
+ } else if (line.startsWith("-")) {
2351
+ lines.push({ type: "remove", text: line, oldLine: oldLine++ });
2352
+ } else if (line.startsWith(" ")) {
2353
+ lines.push({
2354
+ type: "context",
2355
+ text: line,
2356
+ oldLine: oldLine++,
2357
+ newLine: newLine++
2358
+ });
2359
+ } else if (line.startsWith("\\")) {
2360
+ lines.push({ type: "context", text: line });
2361
+ }
2362
+ }
2363
+ return lines;
2364
+ }
2365
+ function isBinary(content) {
2366
+ return content.includes("\0");
2367
+ }
2368
+ async function readExistingFile(resolvedPath) {
2369
+ try {
2370
+ return await readFile3(resolvedPath, "utf-8");
2371
+ } catch (err) {
2372
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
2373
+ return "";
2374
+ }
2375
+ throw err;
2376
+ }
2377
+ }
2378
+
2379
+ // src/templates/diff-viewer/terminal-renderer.ts
2380
+ import { execSync as execSync2 } from "child_process";
2381
+ import stringWidth from "string-width";
2382
+ var ANSI = {
2383
+ // Colors
2384
+ RED: "\x1B[31m",
2385
+ GREEN: "\x1B[32m",
2386
+ CYAN: "\x1B[36m",
2387
+ GRAY: "\x1B[90m",
2388
+ RESET: "\x1B[0m",
2389
+ // Text styles
2390
+ BOLD: "\x1B[1m",
2391
+ DIM: "\x1B[2m"
2392
+ };
2393
+ var BOX_HORIZONTAL = "\u2500";
2394
+ function render(state, filePath, clearPrevious = false) {
2395
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
2396
+ const maxContentHeight = maxTotalHeight - 3;
2397
+ const contentHeight = state.diffLines.length;
2398
+ const windowHeight = Math.min(contentHeight, maxContentHeight);
2399
+ const visibleLines = state.diffLines.slice(
2400
+ state.scrollOffset,
2401
+ state.scrollOffset + windowHeight
2402
+ );
2403
+ const totalLines = state.diffLines.length;
2404
+ const startLine = state.scrollOffset + 1;
2405
+ const endLine = state.scrollOffset + visibleLines.length;
2406
+ if (clearPrevious && state.renderedHeight > 0) {
2407
+ clearPreviousRender(state.renderedHeight - 1);
2408
+ }
2409
+ let output = "";
2410
+ output += renderTopBar(filePath, state.terminalWidth) + "\n";
2411
+ for (const line of visibleLines) {
2412
+ output += colorize(line, state.terminalWidth) + "\n";
2413
+ }
2414
+ output += renderBottomBar(startLine, endLine, totalLines, state, state.terminalWidth) + "\n";
2415
+ output += "\n";
2416
+ output += `overwrite ${filePath} [yNaqd]? `;
2417
+ state.renderedHeight = 1 + visibleLines.length + 1 + 1 + 1;
2418
+ process.stdout.write(output);
2419
+ }
2420
+ function clearPreviousRender(lines) {
2421
+ process.stdout.write(`\x1B[${lines}A`);
2422
+ process.stdout.write("\r");
2423
+ process.stdout.write("\x1B[0J");
2424
+ }
2425
+ function renderTopBar(filePath, width) {
2426
+ const prefix = BOX_HORIZONTAL.repeat(3) + " ";
2427
+ const suffix = " " + BOX_HORIZONTAL.repeat(3);
2428
+ const availableWidth = width - stringWidth(prefix) - stringWidth(suffix);
2429
+ let displayName = filePath;
2430
+ if (stringWidth(displayName) + 1 > availableWidth) {
2431
+ while (stringWidth("..." + displayName) + 1 > availableWidth && displayName.length > 0) {
2432
+ displayName = displayName.slice(1);
2433
+ }
2434
+ displayName = "..." + displayName;
2435
+ }
2436
+ const paddingLength = Math.max(0, availableWidth - stringWidth(displayName) - 1);
2437
+ const padding = BOX_HORIZONTAL.repeat(paddingLength);
2438
+ return ANSI.CYAN + prefix + ANSI.BOLD + displayName + ANSI.RESET + " " + ANSI.CYAN + padding + suffix + ANSI.RESET;
2439
+ }
2440
+ function renderBottomBar(startLine, endLine, totalLines, _state, width) {
2441
+ const prefix = BOX_HORIZONTAL.repeat(3) + " ";
2442
+ const positionIndicator = `${startLine}-${endLine}/${totalLines}`;
2443
+ const content = positionIndicator;
2444
+ const suffix = " " + BOX_HORIZONTAL.repeat(3);
2445
+ const availableWidth = width - stringWidth(prefix) - stringWidth(suffix);
2446
+ const paddingLength = Math.max(0, availableWidth - stringWidth(content));
2447
+ const padding = BOX_HORIZONTAL.repeat(paddingLength);
2448
+ return ANSI.CYAN + prefix + ANSI.RESET + ANSI.DIM + content + ANSI.RESET + ANSI.CYAN + padding + suffix + ANSI.RESET;
2449
+ }
2450
+ function clearDiffWindow() {
2451
+ process.stdout.write("\n");
2452
+ }
2453
+ function colorize(line, terminalWidth) {
2454
+ const maxWidth = Math.max(10, terminalWidth - 3);
2455
+ const text = truncateLine(line.text, maxWidth);
2456
+ switch (line.type) {
2457
+ case "add":
2458
+ return ANSI.GREEN + text + ANSI.RESET;
2459
+ case "remove":
2460
+ return ANSI.RED + text + ANSI.RESET;
2461
+ case "header":
2462
+ return ANSI.CYAN + text + ANSI.RESET;
2463
+ case "context":
2464
+ return ANSI.GRAY + text + ANSI.RESET;
2465
+ default:
2466
+ return text;
2467
+ }
2468
+ }
2469
+ function truncateLine(text, maxWidth) {
2470
+ if (stringWidth(text) <= maxWidth) {
2471
+ return text;
2472
+ }
2473
+ let truncated = text;
2474
+ while (stringWidth(truncated + "...") > maxWidth && truncated.length > 0) {
2475
+ truncated = truncated.slice(0, -1);
2476
+ }
2477
+ return truncated + "...";
2478
+ }
2479
+ function getTerminalSize() {
2480
+ let columns = 80;
2481
+ let rows = 24;
2482
+ try {
2483
+ const sttyOutput = execSync2("stty size </dev/tty", {
2484
+ encoding: "utf-8",
2485
+ stdio: ["ignore", "pipe", "ignore"],
2486
+ timeout: 200,
2487
+ shell: "/bin/bash"
2488
+ }).trim();
2489
+ const parts = sttyOutput.split(/\s+/);
2490
+ if (parts.length === 2) {
2491
+ const sttyRows = parseInt(parts[0], 10);
2492
+ const sttyCols = parseInt(parts[1], 10);
2493
+ if (!isNaN(sttyRows) && sttyRows > 0) {
2494
+ rows = sttyRows;
2495
+ }
2496
+ if (!isNaN(sttyCols) && sttyCols > 0) {
2497
+ columns = sttyCols;
2498
+ }
2499
+ }
2500
+ } catch {
2501
+ try {
2502
+ const tputCols = execSync2("tput cols </dev/tty", {
2503
+ encoding: "utf-8",
2504
+ stdio: ["ignore", "pipe", "ignore"],
2505
+ timeout: 100,
2506
+ shell: "/bin/bash"
2507
+ }).trim();
2508
+ const cols = parseInt(tputCols, 10);
2509
+ if (!isNaN(cols) && cols > 0) {
2510
+ columns = cols;
2511
+ }
2512
+ } catch {
2513
+ }
2514
+ try {
2515
+ const tputRows = execSync2("tput lines </dev/tty", {
2516
+ encoding: "utf-8",
2517
+ stdio: ["ignore", "pipe", "ignore"],
2518
+ timeout: 100,
2519
+ shell: "/bin/bash"
2520
+ }).trim();
2521
+ const lns = parseInt(tputRows, 10);
2522
+ if (!isNaN(lns) && lns > 0) {
2523
+ rows = lns;
2524
+ }
2525
+ } catch {
2526
+ }
2527
+ }
2528
+ return { rows, columns };
2529
+ }
2530
+
2531
+ // src/templates/diff-viewer/diff-prompt.ts
2532
+ import { _createLogger as _createLogger2 } from "@stripe/extensibility-tool-utils";
2533
+ var logger2 = _createLogger2({ name: "diff-prompt" });
2534
+ function isInteractiveTerminal() {
2535
+ if (process.env["CI"] === "true" || process.env["CI"] === "1") {
2536
+ return false;
2537
+ }
2538
+ const term = process.env["TERM"];
2539
+ if (!term || term === "dumb") {
2540
+ return false;
2541
+ }
2542
+ if (typeof process.stdin.setRawMode !== "function") {
2543
+ return false;
2544
+ }
2545
+ const termSize = getTerminalSize();
2546
+ if (termSize.rows === 24 && termSize.columns === 80) {
2547
+ }
2548
+ return true;
2549
+ }
2550
+ async function _advancedDiffPrompt(filePath, cwd, newContent) {
2551
+ const resolvedPath = path3.resolve(cwd, filePath);
2552
+ if (!isInteractiveTerminal()) {
2553
+ return await _promptOverwrite(filePath);
2554
+ }
2555
+ try {
2556
+ const existingContent = await readExistingFile(resolvedPath);
2557
+ const diffResult = await generateDiff(filePath, existingContent, newContent);
2558
+ const termSize = getTerminalSize();
2559
+ if (termSize.rows < 20) {
2560
+ return await _promptOverwrite(filePath);
2561
+ }
2562
+ if (diffResult.lines.length > 5e3) {
2563
+ logger2.info("Diff too large to display comfortably");
2564
+ return await _promptOverwrite(filePath);
2565
+ }
2566
+ const wasRaw = process.stdin.isRaw ?? false;
2567
+ try {
2568
+ process.stdin.setRawMode(true);
2569
+ } catch {
2570
+ return await _promptOverwrite(filePath);
2571
+ }
2572
+ process.stdin.resume();
2573
+ const maxTotalHeight = Math.floor(termSize.rows * 0.75);
2574
+ const maxContentHeight = maxTotalHeight - 3;
2575
+ const windowHeight = Math.min(diffResult.lines.length, maxContentHeight);
2576
+ const state = {
2577
+ scrollOffset: 0,
2578
+ maxScroll: Math.max(0, diffResult.lines.length - windowHeight),
2579
+ diffLines: diffResult.lines,
2580
+ terminalHeight: termSize.rows,
2581
+ terminalWidth: termSize.columns,
2582
+ wasRaw,
2583
+ renderedHeight: 0,
2584
+ fullFileMode: false
2585
+ };
2586
+ render(state, filePath, false);
2587
+ return new Promise((resolve) => {
2588
+ const onExit = () => {
2589
+ cleanup(state.wasRaw, onData, onExit);
2590
+ };
2591
+ const onData = (buffer) => {
2592
+ handleKeypress(buffer, state, filePath, newContent, existingContent).then((result) => {
2593
+ if (result !== "continue") {
2594
+ cleanup(state.wasRaw, onData, onExit);
2595
+ resolve(result);
2596
+ }
2597
+ }).catch((err) => {
2598
+ cleanup(state.wasRaw, onData, onExit);
2599
+ logger2.error({ err }, "Error handling keypress");
2600
+ resolve("abort");
2601
+ });
2602
+ };
2603
+ process.stdin.on("data", onData);
2604
+ process.on("exit", onExit);
2605
+ });
2606
+ } catch (err) {
2607
+ logger2.warn({ err }, "Error displaying diff, using basic prompt");
2608
+ return await _promptOverwrite(filePath);
2609
+ }
2610
+ }
2611
+ async function handleKeypress(buffer, state, filePath, newContent, existingContent) {
2612
+ const code = buffer[0];
2613
+ const key = buffer.toString();
2614
+ if (code === 3) {
2615
+ process.stdout.write("\nCancelled.\n");
2616
+ return "abort";
2617
+ }
2618
+ switch (key.toLowerCase()) {
2619
+ case "y":
2620
+ return "overwrite";
2621
+ case "n":
2622
+ case "\r":
2623
+ case "\n":
2624
+ return "skip";
2625
+ case "a":
2626
+ return "overwrite-all";
2627
+ case "q":
2628
+ return "abort";
2629
+ case "d":
2630
+ await toggleDiffContext(state, filePath, newContent, existingContent);
2631
+ return "continue";
2632
+ }
2633
+ if (buffer.length >= 3 && buffer[0] === 27 && buffer[1] === 91) {
2634
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
2635
+ const maxContentHeight = maxTotalHeight - 3;
2636
+ const windowHeight = Math.min(state.diffLines.length, maxContentHeight);
2637
+ let scrollDelta = 0;
2638
+ if (buffer[2] === 65) {
2639
+ scrollDelta = -1;
2640
+ } else if (buffer[2] === 66) {
2641
+ scrollDelta = 1;
2642
+ } else if (buffer[2] === 53) {
2643
+ scrollDelta = -windowHeight;
2644
+ } else if (buffer[2] === 54) {
2645
+ scrollDelta = windowHeight;
2646
+ }
2647
+ const newScrollOffset = Math.max(
2648
+ 0,
2649
+ Math.min(state.maxScroll, state.scrollOffset + scrollDelta)
2650
+ );
2651
+ if (newScrollOffset !== state.scrollOffset) {
2652
+ state.scrollOffset = newScrollOffset;
2653
+ render(state, filePath, true);
2654
+ }
2655
+ }
2656
+ return "continue";
2657
+ }
2658
+ function cleanup(wasRaw, onData, onExit) {
2659
+ if (process.stdin.setRawMode !== void 0) {
2660
+ process.stdin.setRawMode(wasRaw);
2661
+ }
2662
+ process.stdin.pause();
2663
+ if (onData) {
2664
+ process.stdin.off("data", onData);
2665
+ }
2666
+ if (onExit) {
2667
+ process.off("exit", onExit);
2668
+ }
2669
+ clearDiffWindow();
2670
+ }
2671
+ async function toggleDiffContext(state, filePath, newContent, existingContent) {
2672
+ state.fullFileMode = !state.fullFileMode;
2673
+ const contextLines = state.fullFileMode ? 1e4 : 3;
2674
+ const visibleStartIndex = state.scrollOffset;
2675
+ let referenceLineFinder = null;
2676
+ let skippedLines = 0;
2677
+ for (let i = visibleStartIndex; i < state.diffLines.length; i++) {
2678
+ const line = state.diffLines[i];
2679
+ if (line !== void 0) {
2680
+ if (line.type === "header") {
2681
+ skippedLines++;
2682
+ continue;
2683
+ }
2684
+ if (line.newLine !== void 0) {
2685
+ const targetNewLine = line.newLine;
2686
+ referenceLineFinder = (dl) => dl.newLine !== void 0 && dl.newLine >= targetNewLine - skippedLines;
2687
+ break;
2688
+ } else if (line.oldLine !== void 0) {
2689
+ const targetOldLine = line.oldLine;
2690
+ referenceLineFinder = (dl) => dl.oldLine !== void 0 && dl.oldLine >= targetOldLine - skippedLines;
2691
+ break;
2692
+ }
2693
+ }
2694
+ }
2695
+ const diffResult = await generateDiff(
2696
+ filePath,
2697
+ existingContent,
2698
+ newContent,
2699
+ contextLines
2700
+ );
2701
+ state.diffLines = diffResult.lines;
2702
+ let newScrollOffset = 0;
2703
+ if (referenceLineFinder !== null) {
2704
+ const referenceIndex = diffResult.lines.findIndex(referenceLineFinder);
2705
+ if (referenceIndex !== -1) {
2706
+ newScrollOffset = Math.max(0, referenceIndex);
2707
+ }
2708
+ }
2709
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
2710
+ const maxContentHeight = maxTotalHeight - 3;
2711
+ const windowHeight = Math.min(diffResult.lines.length, maxContentHeight);
2712
+ state.maxScroll = Math.max(0, diffResult.lines.length - windowHeight);
2713
+ state.scrollOffset = Math.min(newScrollOffset, state.maxScroll);
2714
+ render(state, filePath, true);
2715
+ }
2716
+
2717
+ // src/templates/extensions/types.ts
2718
+ var _ExtensionTemplateManager = class extends _TemplateManager {
2719
+ /**
2720
+ * Get summary info for all registered extension templates
2721
+ */
2722
+ getTemplateInfo() {
2723
+ return this.getTemplateEntries().map(([key, t]) => ({
2724
+ key,
2725
+ description: t.description,
2726
+ deprecated: t.deprecated ?? false,
2727
+ hidden: t.hidden ?? false,
2728
+ methods: t.methods
2729
+ }));
2730
+ }
2731
+ };
2732
+
2733
+ // src/templates/extensions/base.ts
2734
+ import { _workspaceVersion } from "@stripe/extensibility-tool-utils";
2735
+ var SDK_PACKAGE_NAME = "@stripe/extensibility-sdk";
2736
+ var LANGUAGE_SERVER_PACKAGE_NAME = "@stripe/extensibility-language-server";
2737
+ var LANGUAGE_SERVER_PACKAGE_VERSION = "^0.2.0";
2738
+ function _createExtensionEslintConfigFile(params, context) {
2739
+ const { id, extensionInterfaceId } = params;
2740
+ const { fs: fs2 } = context;
2741
+ return {
2742
+ path: `extensions/${id}/eslint.config.mts`,
2743
+ content: fs2.mustache(
2744
+ { extensionInterfaceId },
2745
+ "common",
2746
+ "eslint.config.mts.mustache"
2747
+ ),
2748
+ precious: true
2749
+ };
2750
+ }
2751
+ function _createBaseOutput(params, context) {
2752
+ const { id } = params;
2753
+ const { fs: fs2 } = context;
2754
+ return {
2755
+ files: [
2756
+ {
2757
+ path: `extensions/${id}/package.json`,
2758
+ content: fs2.mustache(params, "common", "package.json.mustache")
2759
+ },
2760
+ {
2761
+ ..._createExtensionEslintConfigFile(params, context)
2762
+ },
2763
+ {
2764
+ path: `extensions/${id}/tsconfig.build.json`,
2765
+ content: fs2.mustache(params, "common", "tsconfig.build.json.mustache")
2766
+ },
2767
+ {
2768
+ path: `extensions/${id}/tsconfig.json`,
2769
+ content: fs2.mustache(params, "common", "tsconfig.json.mustache")
2770
+ },
2771
+ {
2772
+ path: `extensions/${id}/.prettierignore`,
2773
+ content: fs2.textFile("common", ".prettierignore")
2774
+ }
2775
+ ],
2776
+ methods: {},
2777
+ dependencies: {
2778
+ // Exact pin (no caret) — the SDK is tightly coupled to dev-tools and
2779
+ // must match the version that generated the extension scaffolding.
2780
+ runtime: [_npmDep(SDK_PACKAGE_NAME, _workspaceVersion(SDK_PACKAGE_NAME))],
2781
+ dev: [_devNpmDep(LANGUAGE_SERVER_PACKAGE_NAME, LANGUAGE_SERVER_PACKAGE_VERSION)]
2782
+ },
2783
+ postGenerationHooks: [
2784
+ {
2785
+ script: "build",
2786
+ description: "Build extension"
2787
+ },
2788
+ {
2789
+ exec: "prettier --write .",
2790
+ description: "Format generated files"
2791
+ }
2792
+ ]
2793
+ };
2794
+ }
2795
+
2796
+ // src/templates/extensions/core.workflows.custom_action.ts
2797
+ var EXTENSION_INTERFACE_ID = "core.workflows.custom_action";
2798
+ var customActionTemplate = {
2799
+ methods: {
2800
+ execute: { implementation_types: ["script", "remote-function"] },
2801
+ get_form_state: { implementation_types: ["script", "remote-function"] }
2802
+ },
2803
+ description: "Custom actions let your app define actions that users can add to their automated workflows. When a workflow triggers a custom action, Stripe calls your app to execute it.",
2804
+ generate: (params, context) => {
2805
+ const { id } = params;
2806
+ const { fs: fs2 } = context;
2807
+ const base = _createBaseOutput(
2808
+ {
2809
+ ...params,
2810
+ extensionInterfaceId: EXTENSION_INTERFACE_ID,
2811
+ executionProfile: "egress"
2812
+ },
2813
+ context
2814
+ );
2815
+ return {
2816
+ ...base,
2817
+ files: [
2818
+ {
2819
+ path: `extensions/${id}/src/index.ts`,
2820
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "index.ts"),
2821
+ precious: true
2822
+ },
2823
+ {
2824
+ path: `extensions/${id}/src/custom_input.schema.json`,
2825
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "custom_input.schema.json"),
2826
+ precious: true
2827
+ },
2828
+ {
2829
+ path: `extensions/${id}/src/index.test.ts`,
2830
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "index.test.ts"),
2831
+ precious: true
2832
+ },
2833
+ ...base.files
2834
+ ],
2835
+ methods: {
2836
+ execute: {
2837
+ implementation_type: "script",
2838
+ custom_input: {
2839
+ input_schema: {
2840
+ type: "json_schema",
2841
+ content: `extensions/${id}/src/custom_input.schema.json`
2842
+ }
2843
+ }
2844
+ },
2845
+ get_form_state: {
2846
+ implementation_type: "script"
2847
+ }
2848
+ }
2849
+ };
2850
+ }
2851
+ };
2852
+ var core_workflows_custom_action_default = {
2853
+ [EXTENSION_INTERFACE_ID]: customActionTemplate
2854
+ };
2855
+
2856
+ // src/templates/extensions/extend.objects.custom_objects.ts
2857
+ var EXTENSION_INTERFACE_ID2 = "extend.objects.custom_objects";
2858
+ var customObjectsTemplate = {
2859
+ methods: {
2860
+ execute_method: { implementation_types: ["script"] }
2861
+ },
2862
+ description: "Methods extension for custom object actions. Generated at build time \u2014 the transformed custom object class becomes the entry point.",
2863
+ hidden: true,
2864
+ generate: (params, context) => {
2865
+ const base = _createBaseOutput(
2866
+ {
2867
+ ...params,
2868
+ extensionInterfaceId: EXTENSION_INTERFACE_ID2,
2869
+ executionProfile: "egress"
2870
+ },
2871
+ context
2872
+ );
2873
+ return {
2874
+ ...base,
2875
+ methods: {
2876
+ execute_method: {
2877
+ implementation_type: "script"
2878
+ }
2879
+ }
2880
+ };
2881
+ }
2882
+ };
2883
+ var extend_objects_custom_objects_default = {
2884
+ [EXTENSION_INTERFACE_ID2]: customObjectsTemplate
2885
+ };
2886
+
2887
+ // src/templates/extensions/extend.workflows.custom_action.ts
2888
+ var EXTENSION_INTERFACE_ID3 = "extend.workflows.custom_action";
2889
+ var extendCustomActionTemplate = {
2890
+ methods: {
2891
+ execute: { implementation_types: ["script", "remote-function"] },
2892
+ get_form_state: { implementation_types: ["script", "remote-function"] }
2893
+ },
2894
+ description: "Custom actions let your app define actions that users can add to their automated workflows. When a workflow triggers a custom action, Stripe calls your app to execute it.",
2895
+ generate: (params, context) => {
2896
+ const { id } = params;
2897
+ const { fs: fs2 } = context;
2898
+ const base = _createBaseOutput(
2899
+ {
2900
+ ...params,
2901
+ extensionInterfaceId: EXTENSION_INTERFACE_ID3,
2902
+ executionProfile: "egress"
2903
+ },
2904
+ context
2905
+ );
2906
+ return {
2907
+ ...base,
2908
+ files: [
2909
+ {
2910
+ path: `extensions/${id}/src/index.ts`,
2911
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "index.ts"),
2912
+ precious: true
2913
+ },
2914
+ {
2915
+ path: `extensions/${id}/src/custom_input.schema.json`,
2916
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "custom_input.schema.json"),
2917
+ precious: true
2918
+ },
2919
+ {
2920
+ path: `extensions/${id}/src/index.test.ts`,
2921
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "index.test.ts"),
2922
+ precious: true
2923
+ },
2924
+ ...base.files
2925
+ ],
2926
+ methods: {
2927
+ execute: {
2928
+ implementation_type: "script",
2929
+ custom_input: {
2930
+ input_schema: {
2931
+ type: "json_schema",
2932
+ content: `extensions/${id}/src/custom_input.schema.json`
2933
+ }
2934
+ }
2935
+ },
2936
+ get_form_state: {
2937
+ implementation_type: "script"
2938
+ }
2939
+ }
2940
+ };
2941
+ }
2942
+ };
2943
+ var extend_workflows_custom_action_default = {
2944
+ [EXTENSION_INTERFACE_ID3]: extendCustomActionTemplate
2945
+ };
2946
+
2947
+ // src/templates/extensions/billing.customer_balance_application.ts
2948
+ var EXTENSION_INTERFACE_ID4 = "billing.customer_balance_application";
2949
+ var customerBalanceApplicationTemplate = {
2950
+ methods: {
2951
+ compute_applied_customer_balance: { implementation_types: ["script"] }
2952
+ },
2953
+ description: "Implement custom logic to control when and how much customer balance is applied to subscription invoices using scripts.",
2954
+ generate: (params, context) => {
2955
+ const { id } = params;
2956
+ const { fs: fs2 } = context;
2957
+ const base = _createBaseOutput(
2958
+ {
2959
+ ...params,
2960
+ extensionInterfaceId: EXTENSION_INTERFACE_ID4,
2961
+ executionProfile: "restricted"
2962
+ },
2963
+ context
2964
+ );
2965
+ return {
2966
+ ...base,
2967
+ files: [
2968
+ {
2969
+ path: `extensions/${id}/src/index.ts`,
2970
+ content: fs2.textFile(EXTENSION_INTERFACE_ID4, "index.ts"),
2971
+ precious: true
2972
+ },
2973
+ {
2974
+ path: `extensions/${id}/src/index.test.ts`,
2975
+ content: fs2.textFile(EXTENSION_INTERFACE_ID4, "index.test.ts"),
2976
+ precious: true
2977
+ },
2978
+ ...base.files
2979
+ ],
2980
+ methods: {
2981
+ compute_applied_customer_balance: {
2982
+ implementation_type: "script"
2983
+ }
2984
+ }
2985
+ };
2986
+ }
2987
+ };
2988
+ var billing_customer_balance_application_default = {
2989
+ [EXTENSION_INTERFACE_ID4]: customerBalanceApplicationTemplate
2990
+ };
2991
+
2992
+ // src/templates/extensions/billing.bill.discount_calculation.ts
2993
+ var EXTENSION_INTERFACE_ID5 = "billing.bill.discount_calculation";
2994
+ var discountCalculationTemplate = {
2995
+ hidden: true,
2996
+ methods: {
2997
+ compute_discounts: { implementation_types: ["script"] }
2998
+ },
2999
+ description: "Create coupons with custom scripting logic for dynamic discounts based on subscription attributes, customer metadata, and complex business rules.",
3000
+ generate: (params, context) => {
3001
+ const { id } = params;
3002
+ const { fs: fs2 } = context;
3003
+ const base = _createBaseOutput(
3004
+ {
3005
+ ...params,
3006
+ extensionInterfaceId: EXTENSION_INTERFACE_ID5,
3007
+ executionProfile: "restricted"
3008
+ },
3009
+ context
3010
+ );
3011
+ return {
3012
+ ...base,
3013
+ files: [
3014
+ {
3015
+ path: `extensions/${id}/src/index.ts`,
3016
+ content: fs2.textFile(EXTENSION_INTERFACE_ID5, "index.ts"),
3017
+ precious: true
3018
+ },
3019
+ {
3020
+ path: `extensions/${id}/src/index.test.ts`,
3021
+ content: fs2.textFile(EXTENSION_INTERFACE_ID5, "index.test.ts"),
3022
+ precious: true
3023
+ },
3024
+ ...base.files
3025
+ ],
3026
+ methods: {
3027
+ compute_discounts: {
3028
+ implementation_type: "script"
3029
+ }
3030
+ }
3031
+ };
3032
+ }
3033
+ };
3034
+ var billing_bill_discount_calculation_default = {
3035
+ [EXTENSION_INTERFACE_ID5]: discountCalculationTemplate
3036
+ };
3037
+
3038
+ // src/templates/extensions/billing.invoice_collection_setting.ts
3039
+ var EXTENSION_INTERFACE_ID6 = "billing.invoice_collection_setting";
3040
+ var invoiceCollectionSettingTemplate = {
3041
+ hidden: true,
3042
+ methods: {
3043
+ collection_override: { implementation_types: ["script"] }
3044
+ },
3045
+ description: "Use Stripe Scripts to create custom invoice collection logic that controls how your integration handles invoices generated from subscriptions.",
3046
+ generate: (params, context) => {
3047
+ const { id } = params;
3048
+ const { fs: fs2 } = context;
3049
+ const base = _createBaseOutput(
3050
+ {
3051
+ ...params,
3052
+ extensionInterfaceId: EXTENSION_INTERFACE_ID6,
3053
+ executionProfile: "restricted"
3054
+ },
3055
+ context
3056
+ );
3057
+ return {
3058
+ ...base,
3059
+ files: [
3060
+ {
3061
+ path: `extensions/${id}/src/index.ts`,
3062
+ content: fs2.textFile(EXTENSION_INTERFACE_ID6, "index.ts"),
3063
+ precious: true
3064
+ },
3065
+ {
3066
+ path: `extensions/${id}/src/index.test.ts`,
3067
+ content: fs2.textFile(EXTENSION_INTERFACE_ID6, "index.test.ts"),
3068
+ precious: true
3069
+ },
3070
+ ...base.files
3071
+ ],
3072
+ methods: {
3073
+ collection_override: {
3074
+ implementation_type: "script"
3075
+ }
3076
+ }
3077
+ };
3078
+ }
3079
+ };
3080
+ var billing_invoice_collection_setting_default = {
3081
+ [EXTENSION_INTERFACE_ID6]: invoiceCollectionSettingTemplate
3082
+ };
3083
+
3084
+ // src/templates/extensions/billing.prorations.ts
3085
+ var EXTENSION_INTERFACE_ID7 = "billing.prorations";
3086
+ var prorationsTemplate = {
3087
+ methods: {
3088
+ prorate_items: { implementation_types: ["script"] }
3089
+ },
3090
+ description: "Create custom proration logic for subscriptions using scripts to handle upgrades, downgrades, and mid-cycle changes.",
3091
+ generate: (params, context) => {
3092
+ const { id } = params;
3093
+ const { fs: fs2 } = context;
3094
+ const base = _createBaseOutput(
3095
+ {
3096
+ ...params,
3097
+ extensionInterfaceId: EXTENSION_INTERFACE_ID7,
3098
+ executionProfile: "restricted"
3099
+ },
3100
+ context
3101
+ );
3102
+ return {
3103
+ ...base,
3104
+ files: [
3105
+ {
3106
+ path: `extensions/${id}/src/index.ts`,
3107
+ content: fs2.textFile(EXTENSION_INTERFACE_ID7, "index.ts"),
3108
+ precious: true
3109
+ },
3110
+ {
3111
+ path: `extensions/${id}/src/index.test.ts`,
3112
+ content: fs2.textFile(EXTENSION_INTERFACE_ID7, "index.test.ts"),
3113
+ precious: true
3114
+ },
3115
+ ...base.files
3116
+ ],
3117
+ methods: {
3118
+ prorate_items: {
3119
+ implementation_type: "script"
3120
+ }
3121
+ }
3122
+ };
3123
+ }
3124
+ };
3125
+ var billing_prorations_default = {
3126
+ [EXTENSION_INTERFACE_ID7]: prorationsTemplate
3127
+ };
3128
+
3129
+ // src/templates/extensions/billing.recurring_billing_item_handling.ts
3130
+ var EXTENSION_INTERFACE_ID8 = "billing.recurring_billing_item_handling";
3131
+ var template = {
3132
+ methods: {
3133
+ before_item_creation: { implementation_types: ["script"] },
3134
+ filter_items: { implementation_types: ["script"] },
3135
+ group_items: { implementation_types: ["script"] }
3136
+ },
3137
+ description: "Customize how recurring billing items are filtered, grouped, and created during subscription billing runs.",
3138
+ generate: (params, context) => {
3139
+ const { id } = params;
3140
+ const { fs: fs2 } = context;
3141
+ const base = _createBaseOutput(
3142
+ {
3143
+ ...params,
3144
+ extensionInterfaceId: EXTENSION_INTERFACE_ID8,
3145
+ executionProfile: "restricted"
3146
+ },
3147
+ context
3148
+ );
3149
+ return {
3150
+ ...base,
3151
+ files: [
3152
+ {
3153
+ path: `extensions/${id}/src/index.ts`,
3154
+ content: fs2.textFile(EXTENSION_INTERFACE_ID8, "index.ts"),
3155
+ precious: true
3156
+ },
3157
+ {
3158
+ path: `extensions/${id}/src/index.test.ts`,
3159
+ content: fs2.textFile(EXTENSION_INTERFACE_ID8, "index.test.ts"),
3160
+ precious: true
3161
+ },
3162
+ ...base.files
3163
+ ],
3164
+ methods: {
3165
+ before_item_creation: {
3166
+ implementation_type: "script"
3167
+ },
3168
+ filter_items: {
3169
+ implementation_type: "script"
3170
+ },
3171
+ group_items: {
3172
+ implementation_type: "script"
3173
+ }
3174
+ }
3175
+ };
3176
+ }
3177
+ };
3178
+ var billing_recurring_billing_item_handling_default = {
3179
+ [EXTENSION_INTERFACE_ID8]: template
3180
+ };
3181
+
3182
+ // src/templates/extensions/registry.ts
3183
+ var DEFAULT_TEMPLATES = {
3184
+ ...core_workflows_custom_action_default,
3185
+ ...extend_objects_custom_objects_default,
3186
+ ...extend_workflows_custom_action_default,
3187
+ ...billing_customer_balance_application_default,
3188
+ ...billing_bill_discount_calculation_default,
3189
+ ...billing_invoice_collection_setting_default,
3190
+ ...billing_prorations_default,
3191
+ ...billing_recurring_billing_item_handling_default
3192
+ };
3193
+ var registry_default = DEFAULT_TEMPLATES;
3194
+
3195
+ // src/templates/extensions/index.ts
3196
+ var _templateManager = new _ExtensionTemplateManager(
3197
+ registry_default,
3198
+ _fs.scope("extensions")
3199
+ );
3200
+
3201
+ // src/templates/root/index.ts
3202
+ import { _workspaceVersion as _workspaceVersion2 } from "@stripe/extensibility-tool-utils";
3203
+ var EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME = "@stripe/extensibility-eslint-plugin";
3204
+ var EXTENSIBILITY_ESLINT_PLUGIN_VERSION = `^${_workspaceVersion2(EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME)}`;
3205
+ var _rootWorkspaceTemplate = {
3206
+ generate: (params, context) => {
3207
+ const { fs: fs2 } = context;
3208
+ return {
3209
+ files: [
3210
+ {
3211
+ path: "stripe-app.yaml",
3212
+ content: fs2.mustache(params, "stripe-app.yaml.mustache"),
3213
+ precious: true
3214
+ },
3215
+ {
3216
+ path: "package.json",
3217
+ content: fs2.mustache(params, "package.json.mustache")
3218
+ },
3219
+ {
3220
+ path: ".husky/pre-commit",
3221
+ content: fs2.textFile(".husky/pre-commit")
3222
+ },
3223
+ {
3224
+ path: "tsconfig.base.json",
3225
+ content: fs2.textFile("tsconfig.base.json")
3226
+ },
3227
+ {
3228
+ path: "tsconfig.json",
3229
+ content: fs2.textFile("tsconfig.json")
3230
+ },
3231
+ {
3232
+ path: "eslint.config.mts",
3233
+ content: fs2.textFile("eslint.config.mts")
3234
+ },
3235
+ {
3236
+ path: "vitest.config.mts",
3237
+ content: fs2.textFile("vitest.config.mts")
3238
+ },
3239
+ {
3240
+ path: ".gitignore",
3241
+ content: fs2.textFile("_gitignore")
3242
+ },
3243
+ {
3244
+ path: "pnpm-workspace.yaml",
3245
+ content: fs2.textFile("pnpm-workspace.yaml")
3246
+ },
3247
+ {
3248
+ path: ".prettierrc",
3249
+ content: fs2.textFile(".prettierrc")
3250
+ },
3251
+ {
3252
+ path: ".prettierignore",
3253
+ content: fs2.textFile(".prettierignore")
3254
+ },
3255
+ {
3256
+ path: "custom-objects/package.json",
3257
+ content: fs2.textFile("custom-objects/package.json"),
3258
+ precious: true
3259
+ },
3260
+ {
3261
+ path: "custom-objects/tsconfig.json",
3262
+ content: fs2.textFile("custom-objects/tsconfig.json"),
3263
+ precious: true
3264
+ },
3265
+ {
3266
+ path: "ui/package.json",
3267
+ content: fs2.textFile("ui/package.json"),
3268
+ precious: true
3269
+ },
3270
+ {
3271
+ path: "tools/test.mts",
3272
+ content: fs2.textFile("tools/test.mts")
3273
+ },
3274
+ {
3275
+ // temporarily add dummy JSON manifest until stripe apps plugin is fixed
3276
+ path: "stripe-app.json",
3277
+ content: "{}\n"
3278
+ }
3279
+ ],
3280
+ dependencies: {
3281
+ dev: [
3282
+ _devNpmDep("@eslint/js", "^9.0.0"),
3283
+ _devNpmDep(
3284
+ EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME,
3285
+ EXTENSIBILITY_ESLINT_PLUGIN_VERSION
3286
+ ),
3287
+ _devNpmDep(LANGUAGE_SERVER_PACKAGE_NAME, LANGUAGE_SERVER_PACKAGE_VERSION),
3288
+ _devNpmDep("@types/node", "^20.19.0"),
3289
+ _devNpmDep(
3290
+ "@stripe/extensibility-dev-tools",
3291
+ `^${_workspaceVersion2("@stripe/extensibility-dev-tools")}`
3292
+ ),
3293
+ _devNpmDep("concurrently", "^9.2.1"),
3294
+ _devNpmDep("eslint", "^9.0.0"),
3295
+ _devNpmDep("eslint-config-prettier", "^10.1.8"),
3296
+ _devNpmDep("eslint-plugin-workspaces", "^0.12.1"),
3297
+ _devNpmDep("globals", "^17.4.0"),
3298
+ _devNpmDep("husky", "^9.1.7"),
3299
+ _devNpmDep("jiti", "^2.6.1"),
3300
+ _devNpmDep("lint-staged", "^16.2.7"),
3301
+ _devNpmDep("chokidar-cli", "^3.0.0"),
3302
+ _devNpmDep("prettier", "^3.8.1"),
3303
+ _devNpmDep("ts-node", "^10.9.2"),
3304
+ _devNpmDep("tsx", "^4.21.0"),
3305
+ _devNpmDep("typescript", "^5.9.3"),
3306
+ _devNpmDep("typescript-eslint", "^8.54.0"),
3307
+ _devNpmDep("vitest", "^3.0.0")
3308
+ ]
3309
+ },
3310
+ postGenerationHooks: [
3311
+ {
3312
+ exec: "prettier --write .",
3313
+ description: "Format generated files"
3314
+ }
3315
+ ]
3316
+ };
3317
+ }
3318
+ };
3319
+ var _rootTemplateManager = new _SingleTemplateManager(_rootWorkspaceTemplate, _fs.scope("root"));
3320
+
3321
+ // src/workspace/index.ts
3322
+ var _regenWorkspaceOptionsSchema = z.object({
3323
+ /** Workspace template ID (e.g., 'core.workflows.custom_action', 'custom-objects'). Absence means root workspace mode. */
3324
+ templateId: z.string().optional(),
3325
+ /** Path to project root. Resolved relative to cwd. Defaults to cwd. */
3326
+ root: z.string().optional(),
3327
+ /** Path to directory containing package.json (resolved relative to cwd). Used for reading existing metadata. If undefined, package.json is not read. */
3328
+ packageDir: z.string().optional(),
3329
+ /** Workspace ID. Validated against package.json if both are present. */
3330
+ workspaceId: z.string().optional(),
3331
+ /** Workspace name. Overrides package.json description if provided. */
3332
+ workspaceName: z.string().optional(),
3333
+ /** Skip dependency installation */
3334
+ skipDependencies: z.boolean().optional(),
3335
+ /** Skip post-generation hooks */
3336
+ skipHooks: z.boolean().optional(),
3337
+ /** Force overwrite all files without prompting */
3338
+ force: z.boolean().optional(),
3339
+ /** Custom object name. Required when templateId is 'custom-object'. */
3340
+ name: z.string().optional(),
3341
+ /** Implementation type. When 'remote-function', only .schema.json files are written and dependencies/hooks are skipped. */
3342
+ implementationType: z.enum(["script", "remote-function"]).optional()
3343
+ });
3344
+ async function readPackageMetadata(dir) {
3345
+ const pkgPath = path4.join(dir, "package.json");
3346
+ try {
3347
+ const pkgContent = await readFile4(pkgPath, "utf-8");
3348
+ const pkg = JSON.parse(pkgContent);
3349
+ return {
3350
+ ...pkg.name !== void 0 && { id: pkg.name },
3351
+ ...pkg.description !== void 0 && { name: pkg.description },
3352
+ ...pkg.version !== void 0 && { version: pkg.version }
3353
+ };
3354
+ } catch {
3355
+ return null;
3356
+ }
3357
+ }
3358
+ async function _resolvePackageMetadata(providedId, providedName, packageDir) {
3359
+ let id = providedId;
3360
+ let name = providedName;
3361
+ let version = "0.0.1";
3362
+ if (packageDir !== void 0) {
3363
+ const pkgMetadata = await readPackageMetadata(packageDir);
3364
+ if (pkgMetadata) {
3365
+ if (id && pkgMetadata.id && id !== pkgMetadata.id) {
3366
+ throw new Error(
3367
+ `Workspace ID mismatch: --workspace-id "${id}" does not match package.json name "${pkgMetadata.id}"`
3368
+ );
3369
+ }
3370
+ id ??= pkgMetadata.id;
3371
+ name ??= pkgMetadata.name;
3372
+ if (pkgMetadata.version) {
3373
+ version = pkgMetadata.version;
3374
+ }
3375
+ }
3376
+ }
3377
+ if (!id) {
3378
+ throw new Error(
3379
+ "ID required: provide --workspace-id or ensure package.json has a name field"
3380
+ );
3381
+ }
3382
+ name ??= id;
3383
+ return { id, name, version };
3384
+ }
3385
+ function runPostGenerationHooks(hooks, workingDir, disabled = false, context = _createCliContext2()) {
3386
+ if (!hooks || hooks.length === 0 || disabled) {
3387
+ return Promise.resolve();
3388
+ }
3389
+ context.ux.log("\nRunning post-generation hooks...");
3390
+ for (const hook of hooks) {
3391
+ const description = hook.description ? ` (${hook.description})` : "";
3392
+ let command;
3393
+ let hookName;
3394
+ if ("script" in hook) {
3395
+ command = `pnpm run ${hook.script}`;
3396
+ hookName = hook.script;
3397
+ } else {
3398
+ command = `pnpm exec ${hook.exec}`;
3399
+ hookName = hook.exec;
3400
+ }
3401
+ context.ux.log(`
3402
+ Running: ${command}${description}`);
3403
+ try {
3404
+ execSync3(command, {
3405
+ cwd: workingDir,
3406
+ stdio: "inherit"
3407
+ });
3408
+ context.ux.log(`\u2713 Hook completed: ${hookName}`);
3409
+ } catch (error) {
3410
+ context.ux.error(`! Hook failed: ${hookName}`);
3411
+ if (error instanceof Error) {
3412
+ context.ux.error(` ${error.message}`);
3413
+ }
3414
+ }
3415
+ }
3416
+ return Promise.resolve();
3417
+ }
3418
+ async function installDependencies(services, cwd, dependencies, context) {
3419
+ if (dependencies.length === 0) {
3420
+ return;
3421
+ }
3422
+ const depManager = services.createDepManager({ cwd, context });
3423
+ const pendingChanges = await depManager.ensureDependencies({
3424
+ required: dependencies
3425
+ });
3426
+ for (const pendingChange of pendingChanges) {
3427
+ if (pendingChange.action === "conflict") {
3428
+ depManager.resolveConflict(pendingChange.dependency);
3429
+ }
3430
+ }
3431
+ await depManager.commit();
3432
+ }
3433
+ async function backfillMissingExtensionEslintConfigs(services, projectRoot) {
3434
+ const manifestPath = path4.join(projectRoot, "stripe-app.yaml");
3435
+ if (!existsSync2(manifestPath)) {
3436
+ return [];
3437
+ }
3438
+ const manifest = await services.loadManifest(manifestPath);
3439
+ const extensions = manifest.getExtensions();
3440
+ return extensions.flatMap((extension) => {
3441
+ const eslintConfigPath = `extensions/${extension.id}/eslint.config.mts`;
3442
+ if (existsSync2(path4.join(projectRoot, eslintConfigPath))) {
3443
+ return [];
3444
+ }
3445
+ return _createExtensionEslintConfigFile(
3446
+ {
3447
+ id: extension.id,
3448
+ extensionInterfaceId: extension.interface_id
3449
+ },
3450
+ { fs: _fs.scope("extensions") }
3451
+ );
3452
+ });
3453
+ }
3454
+ function resolveMode(options, projectRoot, packageDir) {
3455
+ if (!options.templateId) {
3456
+ return {
3457
+ label: "root",
3458
+ workspaceDir: () => packageDir ?? projectRoot,
3459
+ generate: (svc, meta) => svc.generateRoot({
3460
+ appId: meta.id,
3461
+ appName: meta.name,
3462
+ version: meta.version
3463
+ })
3464
+ };
3465
+ }
3466
+ if (options.templateId === "custom-objects") {
3467
+ return {
3468
+ label: "custom-objects",
3469
+ workspaceDir: () => packageDir ?? path4.join(projectRoot, "custom-objects"),
3470
+ generate: async (svc) => {
3471
+ const workspaceResult = await svc.generateCustomObjectsWorkspace({});
3472
+ return {
3473
+ ...workspaceResult,
3474
+ files: workspaceResult.files.map((f) => ({ ...f, precious: true }))
3475
+ };
3476
+ }
3477
+ };
3478
+ }
3479
+ if (options.templateId === "custom-object") {
3480
+ const objectName = options.name;
3481
+ if (!objectName) {
3482
+ throw new Error("--name is required when --template-id is 'custom-object'");
3483
+ }
3484
+ return {
3485
+ label: `custom-object:${objectName}`,
3486
+ workspaceDir: () => packageDir ?? path4.join(projectRoot, "custom-objects"),
3487
+ generate: async (svc) => {
3488
+ const customObjectsWorkspaceDir = packageDir ?? path4.join(projectRoot, "custom-objects");
3489
+ const workspaceExists = existsSync2(path4.join(customObjectsWorkspaceDir, "package.json")) && existsSync2(path4.join(customObjectsWorkspaceDir, "tsconfig.json"));
3490
+ const objectResult = await svc.generateCustomObject({ name: objectName });
3491
+ if (workspaceExists) {
3492
+ return objectResult;
3493
+ }
3494
+ const workspaceResult = await svc.generateCustomObjectsWorkspace({});
3495
+ return {
3496
+ ...objectResult,
3497
+ files: [
3498
+ ...workspaceResult.files.map((f) => ({ ...f, precious: true })),
3499
+ ...objectResult.files
3500
+ ]
3501
+ };
3502
+ },
3503
+ finalize: async (_svc, _meta, root, _output, context) => {
3504
+ context.ux.log("\nUpdating stripe-app.yaml...");
3505
+ const manifestPath = path4.join(root, "stripe-app.yaml");
3506
+ const manifest = await _openStripeAppManifest(manifestPath);
3507
+ const apiName = _toSnakeCase2(objectName);
3508
+ if (!manifest.hasCustomObject(apiName)) {
3509
+ manifest.addCustomObject(apiName, `custom-objects/src/${apiName}.object.ts`);
3510
+ const tx = _beginTransaction();
3511
+ tx.adopt(manifest);
3512
+ const report = await tx.commit();
3513
+ if (report.written.length > 0) {
3514
+ context.ux.log("\u2713 Updated stripe-app.yaml");
3515
+ }
3516
+ } else {
3517
+ context.ux.log("- Custom object already registered in stripe-app.yaml");
3518
+ }
3519
+ }
3520
+ };
3521
+ }
3522
+ const interfaceId = options.templateId;
3523
+ function buildRemoteFunctionMethodsAndEndpoints(extensionId, outputMethods) {
3524
+ const methods = {};
3525
+ const endpoints = Object.entries(outputMethods).map(([methodName, methodConfig]) => {
3526
+ const endpointId = `${extensionId}.${methodName}`;
3527
+ const customInput = typeof methodConfig === "object" && methodConfig !== null && "custom_input" in methodConfig ? Reflect.get(methodConfig, "custom_input") : void 0;
3528
+ methods[methodName] = {
3529
+ implementation_type: "remote_function",
3530
+ ...customInput !== void 0 && { custom_input: customInput },
3531
+ endpoint_id: endpointId
3532
+ };
3533
+ return {
3534
+ id: endpointId,
3535
+ type: "remote_function",
3536
+ live: { url: "https://example.com/" }
3537
+ };
3538
+ });
3539
+ return { methods, endpoints };
3540
+ }
3541
+ return {
3542
+ label: interfaceId,
3543
+ workspaceDir: (meta) => packageDir ?? path4.join(projectRoot, "extensions", meta.id),
3544
+ generate: (svc, meta) => svc.generateExtension(interfaceId, {
3545
+ id: meta.id,
3546
+ name: meta.name,
3547
+ version: meta.version
3548
+ }),
3549
+ finalize: async (svc, meta, root, output, context) => {
3550
+ if (!output.methods) return;
3551
+ context.ux.log("\nUpdating stripe-app.yaml...");
3552
+ const manifest = await svc.loadManifest(path4.join(root, "stripe-app.yaml"));
3553
+ const permissions = [];
3554
+ const baseConfig = {
3555
+ id: meta.id,
3556
+ name: meta.name,
3557
+ interface_id: interfaceId,
3558
+ version: meta.version,
3559
+ permissions
3560
+ };
3561
+ if (options.implementationType === "remote-function") {
3562
+ const { methods, endpoints } = buildRemoteFunctionMethodsAndEndpoints(
3563
+ meta.id,
3564
+ output.methods
3565
+ );
3566
+ manifest.addOrUpdateExtension({ ...baseConfig, methods, endpoints });
3567
+ } else {
3568
+ manifest.addOrUpdateExtension({
3569
+ ...baseConfig,
3570
+ script: {
3571
+ type: "typescript",
3572
+ content: `extensions/${meta.id}/src/index.ts`
3573
+ },
3574
+ methods: output.methods,
3575
+ configuration: {
3576
+ input_schema: {
3577
+ type: "json_schema",
3578
+ content: `extensions/${meta.id}/generated/config.schema.json`
3579
+ },
3580
+ ui_schema: {
3581
+ type: "jsonforms",
3582
+ content: `extensions/${meta.id}/generated/config.ui.json`
3583
+ }
3584
+ }
3585
+ });
3586
+ }
3587
+ await manifest.save();
3588
+ }
3589
+ };
3590
+ }
3591
+ var _defaultServices = {
3592
+ generateRoot: (vars) => _rootTemplateManager.generate(vars),
3593
+ generateExtension: (key, vars) => _templateManager.generate(key, vars),
3594
+ generateCustomObject: async (vars) => {
3595
+ const plan = await _customObjectGenerators.plan(vars, {
3596
+ scope: "project",
3597
+ projectRoot: process.cwd()
3598
+ });
3599
+ return {
3600
+ files: plan.files.map((f) => ({ path: f.path, content: f.content }))
3601
+ };
3602
+ },
3603
+ generateCustomObjectsWorkspace: async (vars) => {
3604
+ const runner = new _GeneratorRunner(_customObjectsWorkspaceGenerator);
3605
+ const plan = await runner.plan(vars, {
3606
+ scope: "project",
3607
+ projectRoot: process.cwd()
3608
+ });
3609
+ return {
3610
+ files: plan.files.map((f) => ({ path: f.path, content: f.content }))
3611
+ };
3612
+ },
3613
+ writeFiles: _writeGeneratedFiles,
3614
+ createDepManager: ({ cwd, context }) => new _DependencyManager({ cwd, ...context !== void 0 && { context } }),
3615
+ loadManifest: (manifestPath) => _StripeAppManifest.load(manifestPath),
3616
+ runHooks: runPostGenerationHooks
3617
+ };
3618
+ async function _regenAppProjectWorkspace(options, services = _defaultServices, context = _createCliContext2()) {
3619
+ const isCustomObjectMode = options.templateId === "custom-object";
3620
+ if (!isCustomObjectMode && !options.packageDir && !options.workspaceId) {
3621
+ throw new Error("At least one of packageDir or workspaceId is required");
3622
+ }
3623
+ const projectRoot = path4.resolve(options.root ?? ".");
3624
+ const packageDir = options.packageDir ? path4.resolve(options.packageDir) : void 0;
3625
+ const mode = resolveMode(options, projectRoot, packageDir);
3626
+ const metadata = isCustomObjectMode ? { id: "", name: "", version: "" } : await _resolvePackageMetadata(
3627
+ options.workspaceId,
3628
+ options.workspaceName,
3629
+ packageDir
3630
+ );
3631
+ const workspaceDir = mode.workspaceDir(metadata);
3632
+ const isRootRegen = options.templateId === void 0;
3633
+ context.ux.log(`Generating files from template: ${mode.label}...`);
3634
+ const templateOutput = await mode.generate(services, metadata);
3635
+ const allFiles = isRootRegen ? [
3636
+ ...templateOutput.files,
3637
+ ...await backfillMissingExtensionEslintConfigs(services, projectRoot)
3638
+ ] : templateOutput.files;
3639
+ const filesToWrite = options.implementationType === "remote-function" ? allFiles.filter((f) => f.path.endsWith(".schema.json")) : allFiles;
3640
+ if (isRootRegen) {
3641
+ const existingPkgPath = path4.join(projectRoot, "package.json");
3642
+ let existingOverrides;
3643
+ try {
3644
+ const existingPkg = JSON.parse(await readFile4(existingPkgPath, "utf-8"));
3645
+ existingOverrides = existingPkg.pnpm?.overrides;
3646
+ } catch {
3647
+ }
3648
+ if (existingOverrides && Object.keys(existingOverrides).length > 0) {
3649
+ const pkgFile = filesToWrite.find((f) => f.path === "package.json");
3650
+ if (pkgFile) {
3651
+ let newPkg;
3652
+ try {
3653
+ newPkg = JSON.parse(pkgFile.content);
3654
+ } catch (err) {
3655
+ throw new Error(
3656
+ `Failed to parse generated package.json while preserving pnpm.overrides: ${err instanceof Error ? err.message : String(err)}`
3657
+ );
3658
+ }
3659
+ newPkg.pnpm = {
3660
+ ...newPkg.pnpm,
3661
+ overrides: { ...newPkg.pnpm?.overrides, ...existingOverrides }
3662
+ };
3663
+ pkgFile.content = JSON.stringify(newPkg, null, 2) + "\n";
3664
+ }
3665
+ }
3666
+ }
3667
+ if (isRootRegen) {
3668
+ const existingPkgPath = path4.join(projectRoot, "package.json");
3669
+ try {
3670
+ const existingPkg = JSON.parse(await readFile4(existingPkgPath, "utf-8"));
3671
+ const existingOverrides = existingPkg.pnpm?.overrides;
3672
+ if (existingOverrides && Object.keys(existingOverrides).length > 0) {
3673
+ const pkgFile = filesToWrite.find((f) => f.path === "package.json");
3674
+ if (pkgFile) {
3675
+ const newPkg = JSON.parse(pkgFile.content);
3676
+ newPkg.pnpm = {
3677
+ ...newPkg.pnpm,
3678
+ overrides: { ...newPkg.pnpm?.overrides, ...existingOverrides }
3679
+ };
3680
+ pkgFile.content = JSON.stringify(newPkg, null, 2) + "\n";
3681
+ }
3682
+ }
3683
+ } catch {
3684
+ }
3685
+ }
3686
+ context.ux.log("Writing files...");
3687
+ const writeResult = await services.writeFiles(filesToWrite, {
3688
+ cwd: projectRoot,
3689
+ write: options.force ? "overwrite-all" : (path5, cwd, newContent) => _advancedDiffPrompt(path5, cwd, newContent),
3690
+ onFileWritten: (file, wasOverwrite) => {
3691
+ const verb = wasOverwrite ? "Updated" : "Wrote";
3692
+ context.ux.log(`\u2713 ${verb} ${file.path}`);
3693
+ },
3694
+ onFileSkipped: (file) => {
3695
+ context.ux.log(`- Skipped ${file.path}`);
3696
+ },
3697
+ onFileIdentical: (file) => {
3698
+ context.ux.log(`= Identical ${file.path}`);
3699
+ }
3700
+ });
3701
+ if (writeResult.aborted) {
3702
+ context.ux.log("\nAborted by user.");
3703
+ return;
3704
+ }
3705
+ if (options.implementationType !== "remote-function" && !options.skipDependencies && templateOutput.dependencies) {
3706
+ context.ux.log("\nInstalling dependencies...");
3707
+ const allDeps = [
3708
+ ...templateOutput.dependencies.runtime ?? [],
3709
+ ...templateOutput.dependencies.dev ?? []
3710
+ ];
3711
+ await installDependencies(services, workspaceDir, allDeps, context);
3712
+ }
3713
+ if (options.implementationType !== "remote-function" && !options.skipDependencies && !isRootRegen && !isCustomObjectMode) {
3714
+ await installDependencies(
3715
+ services,
3716
+ projectRoot,
3717
+ [
3718
+ _devNpmDep(
3719
+ EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME,
3720
+ EXTENSIBILITY_ESLINT_PLUGIN_VERSION
3721
+ )
3722
+ ],
3723
+ context
3724
+ );
3725
+ }
3726
+ await mode.finalize?.(services, metadata, projectRoot, templateOutput, context);
3727
+ if (options.implementationType !== "remote-function" && !options.skipHooks) {
3728
+ await services.runHooks(
3729
+ templateOutput.postGenerationHooks,
3730
+ workspaceDir,
3731
+ false,
3732
+ context
3733
+ );
3734
+ }
3735
+ context.ux.log("\n\u2713 Regeneration complete");
3736
+ }
3737
+
3738
+ // src/bin/gen-workspace.ts
3739
+ var logger3 = _createLogger3({ name: "gen-workspace" });
3740
+ async function main() {
3741
+ await yargs(hideBin(process.argv)).usage("Regenerate extension or root workspace files from templates").help().version(false).command(
3742
+ "$0",
3743
+ "Regenerate files from templates",
3744
+ (y) => y.option("root", {
3745
+ type: "string",
3746
+ description: "Path to project root (defaults to cwd)"
3747
+ }).option("template-id", {
3748
+ type: "string",
3749
+ description: "Workspace template ID (e.g. extend.workflows.custom_action, custom-objects); omit for root mode"
3750
+ }).option("extension-interface-id", {
3751
+ type: "string",
3752
+ description: "Deprecated alias for --template-id",
3753
+ hidden: true
3754
+ }).option("package-dir", {
3755
+ type: "string",
3756
+ description: "Path to directory containing package.json (relative to cwd)"
3757
+ }).option("workspace-id", {
3758
+ type: "string",
3759
+ description: "Workspace ID; validated against package.json if both present"
3760
+ }).option("workspace-name", {
3761
+ type: "string",
3762
+ description: "Workspace name (overrides package.json description)"
3763
+ }).option("skip-dependencies", {
3764
+ type: "boolean",
3765
+ description: "Skip dependency installation",
3766
+ default: false
3767
+ }).option("skip-hooks", {
3768
+ type: "boolean",
3769
+ description: "Skip post-generation hooks",
3770
+ default: false
3771
+ }).option("force", {
3772
+ type: "boolean",
3773
+ description: "Overwrite all files without prompting",
3774
+ default: false
3775
+ }).option("implementation-type", {
3776
+ type: "string",
3777
+ choices: ["script", "remote-function"],
3778
+ description: 'Implementation type. Use "remote-function" to write only .schema.json files and skip dependencies and hooks.'
3779
+ }).option("name", {
3780
+ type: "string",
3781
+ description: "Custom object name (required with --template-id custom-object)"
3782
+ }).option("output-path", {
3783
+ type: "string",
3784
+ description: "Write JSON result to this file instead of stdout"
3785
+ }).example(
3786
+ "gen-workspace --package-dir .",
3787
+ "Regenerate root workspace files (run from project root)"
3788
+ ).example(
3789
+ "gen-workspace --template-id extend.workflows.custom_action --workspace-id my-ext",
3790
+ "Create a new extension (run from project root)"
3791
+ ).example(
3792
+ "gen-workspace --root ../.. --package-dir . --template-id extend.workflows.custom_action",
3793
+ "Regenerate extension from its directory"
3794
+ ).example(
3795
+ "gen-workspace --package-dir extensions/my-ext --template-id extend.workflows.custom_action",
3796
+ "Regenerate extension from project root"
3797
+ ).example(
3798
+ "gen-workspace --template-id custom-object --name Device --root .",
3799
+ "Generate a new custom object definition and test"
3800
+ ),
3801
+ async (args) => {
3802
+ const ctx = _createCliContext3();
3803
+ const {
3804
+ root,
3805
+ templateId,
3806
+ extensionInterfaceId,
3807
+ packageDir,
3808
+ workspaceId,
3809
+ workspaceName,
3810
+ skipDependencies,
3811
+ skipHooks,
3812
+ force,
3813
+ implementationType,
3814
+ name,
3815
+ outputPath
3816
+ } = args;
3817
+ const resolvedTemplateId = templateId ?? extensionInterfaceId;
3818
+ await _regenAppProjectWorkspace(
3819
+ {
3820
+ ...resolvedTemplateId !== void 0 && { templateId: resolvedTemplateId },
3821
+ ...root !== void 0 && { root },
3822
+ ...packageDir !== void 0 && { packageDir },
3823
+ ...workspaceId !== void 0 && { workspaceId },
3824
+ ...workspaceName !== void 0 && { workspaceName },
3825
+ ...name !== void 0 && { name },
3826
+ skipDependencies,
3827
+ skipHooks,
3828
+ force,
3829
+ ...implementationType !== void 0 && { implementationType }
3830
+ },
3831
+ void 0,
3832
+ ctx
3833
+ );
3834
+ _writeJsonOutput(outputPath, { success: true });
3835
+ }
3836
+ ).parse();
3837
+ }
3838
+ main().catch((err) => {
3839
+ logger3.error({ err }, "Unexpected error");
3840
+ process.exit(1);
3841
+ });