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