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