@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 316 lines 10.9 KB
Raw
1 import * as androidpublisher from "@distilled.cloud/gcp/androidpublisher_v3";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_REGIONS_VERSION,
12 defaultSubscriptionListings,
13 getSubscription,
14 jsonEqual,
15 publicBasePlans,
16 toDisplayName,
17 toProductId,
18 updateMaskOf,
19 } from "./internal.ts";
20
21 export type MonetizationSubscriptionProps = {
22 /**
23 * Play package name of the parent app (for example `com.example.app`).
24 * Immutable — changing it replaces the subscription.
25 */
26 packageName: string;
27 /**
28 * Unique product id within the app. Lower-case letters, numbers,
29 * underscores, and dots; 1-40 characters. If omitted, a unique id is
30 * generated. Immutable — changing it replaces the subscription.
31 */
32 productId?: string;
33 /**
34 * Localized store listings. Must include the app's default language; an
35 * `en-US` listing titled after the product id is used when omitted.
36 */
37 listings?: androidpublisher.SubscriptionListing[];
38 /**
39 * Base plans (prices and billing periods). Draft until activated.
40 */
41 basePlans?: androidpublisher.BasePlan[];
42 /**
43 * Tax and legal-compliance settings.
44 */
45 taxAndComplianceSettings?: androidpublisher.SubscriptionTaxAndComplianceSettings;
46 /**
47 * Countries where purchase is restricted to payment methods registered
48 * in the same country.
49 */
50 restrictedPaymentCountries?: androidpublisher.RestrictedPaymentCountries;
51 /**
52 * Regions-version string used when creating or updating regional
53 * prices (for example `2025/01`).
54 * @default "2025/01"
55 */
56 regionsVersion?: string;
57 /**
58 * Propagation latency tolerance for product updates.
59 */
60 latencyTolerance?:
61 | androidpublisher.PatchMonetizationSubscriptionsLatencyToleranceEnum
62 | (string & {});
63 };
64
65 export type MonetizationSubscription = Resource<
66 "GCP.AndroidPublisher.MonetizationSubscription",
67 MonetizationSubscriptionProps,
68 {
69 /** Play package name. */
70 packageName: string;
71 /** Product id. */
72 productId: string;
73 /** Project id used when the subscription was reconciled. */
74 project: string;
75 /** Localized store listings. */
76 listings: androidpublisher.SubscriptionListing[] | undefined;
77 /** Base plans (output-only state omitted from equality). */
78 basePlans: androidpublisher.BasePlan[] | undefined;
79 /** Tax and compliance settings. */
80 taxAndComplianceSettings: androidpublisher.SubscriptionTaxAndComplianceSettings | undefined;
81 /** Payment-country restrictions. */
82 restrictedPaymentCountries: androidpublisher.RestrictedPaymentCountries | undefined;
83 /** Whether the subscription is archived. */
84 archived: boolean | undefined;
85 },
86 never,
87 Providers
88 >;
89
90 /**
91 * A Google Play subscription product (`monetization.subscriptions`).
92 *
93 * Subscriptions have no labels field, so ownership rests on the
94 * deterministic product id: `read` reports a subscription it finds without
95 * prior state as unowned (adopt it with `--adopt`). `packageName` and
96 * `productId` are identity — changing either replaces the subscription.
97 * Listings, base plans, tax settings, and payment-country restrictions
98 * update in place. A subscription can only be deleted while every base
99 * plan is still a draft.
100 *
101 * ### Creating a Subscription
102 * **Example:** Generated product id
103 * ```typescript
104 * const subscription = yield* GCP.AndroidPublisher.MonetizationSubscription(
105 * "Premium",
106 * {
107 * packageName: "com.example.app",
108 * listings: [{ languageCode: "en-US", title: "Premium" }],
109 * },
110 * );
111 * ```
112 *
113 * **Example:** Explicit id and monthly base plan
114 * ```typescript
115 * const subscription = yield* GCP.AndroidPublisher.MonetizationSubscription(
116 * "Premium",
117 * {
118 * packageName: "com.example.app",
119 * productId: "premium",
120 * listings: [{ languageCode: "en-US", title: "Premium" }],
121 * basePlans: [
122 * {
123 * basePlanId: "monthly",
124 * autoRenewingBasePlanType: { billingPeriodDuration: "P1M" },
125 * regionalConfigs: [
126 * {
127 * regionCode: "US",
128 * newSubscriberAvailability: true,
129 * price: { currencyCode: "USD", units: "5" },
130 * },
131 * ],
132 * },
133 * ],
134 * },
135 * );
136 * ```
137 *
138 * ### Updating a Subscription
139 * **Example:** Change the listing title
140 * ```typescript
141 * // Same logical id as before; only the listing changes.
142 * const subscription = yield* GCP.AndroidPublisher.MonetizationSubscription(
143 * "Premium",
144 * {
145 * packageName: "com.example.app",
146 * listings: [{ languageCode: "en-US", title: "Premium Plus" }],
147 * },
148 * );
149 * ```
150 *
151 * @resource
152 * @category AndroidPublisher
153 */
154 export const MonetizationSubscription = Resource<MonetizationSubscription>(
155 "GCP.AndroidPublisher.MonetizationSubscription",
156 );
157
158 export class MonetizationSubscriptionNotResolved extends Data.TaggedError(
159 "GCP.AndroidPublisher.MonetizationSubscriptionNotResolved",
160 )<{
161 packageName: string;
162 productId: string;
163 }> {}
164
165 const toAttrs = (subscription: androidpublisher.Subscription, project: string) => ({
166 packageName: subscription.packageName ?? "",
167 productId: subscription.productId ?? "",
168 project,
169 listings: subscription.listings,
170 basePlans: publicBasePlans(subscription.basePlans),
171 taxAndComplianceSettings: subscription.taxAndComplianceSettings,
172 restrictedPaymentCountries: subscription.restrictedPaymentCountries,
173 archived: subscription.archived,
174 });
175
176 const desiredBody = (input: {
177 packageName: string;
178 productId: string;
179 listings: androidpublisher.SubscriptionListing[];
180 news: MonetizationSubscriptionProps;
181 }): androidpublisher.Subscription => ({
182 packageName: input.packageName,
183 productId: input.productId,
184 listings: input.listings,
185 basePlans: input.news.basePlans,
186 taxAndComplianceSettings: input.news.taxAndComplianceSettings,
187 restrictedPaymentCountries: input.news.restrictedPaymentCountries,
188 });
189
190 const needsSync = (
191 current: androidpublisher.Subscription,
192 desired: androidpublisher.Subscription,
193 ) =>
194 !jsonEqual(current.listings, desired.listings) ||
195 (desired.basePlans !== undefined &&
196 !jsonEqual(publicBasePlans(current.basePlans), publicBasePlans(desired.basePlans))) ||
197 (desired.taxAndComplianceSettings !== undefined &&
198 !jsonEqual(current.taxAndComplianceSettings, desired.taxAndComplianceSettings)) ||
199 (desired.restrictedPaymentCountries !== undefined &&
200 !jsonEqual(current.restrictedPaymentCountries, desired.restrictedPaymentCountries));
201
202 const syncMask = (current: androidpublisher.Subscription, desired: androidpublisher.Subscription) =>
203 updateMaskOf(
204 !jsonEqual(current.listings, desired.listings) ? "listings" : undefined,
205 desired.basePlans !== undefined &&
206 !jsonEqual(publicBasePlans(current.basePlans), publicBasePlans(desired.basePlans))
207 ? "basePlans"
208 : undefined,
209 desired.taxAndComplianceSettings !== undefined &&
210 !jsonEqual(current.taxAndComplianceSettings, desired.taxAndComplianceSettings)
211 ? "taxAndComplianceSettings"
212 : undefined,
213 desired.restrictedPaymentCountries !== undefined &&
214 !jsonEqual(current.restrictedPaymentCountries, desired.restrictedPaymentCountries)
215 ? "restrictedPaymentCountries"
216 : undefined,
217 );
218
219 export const MonetizationSubscriptionProvider = () =>
220 Provider.succeed(MonetizationSubscription, {
221 stables: ["packageName", "productId", "project"],
222
223 diff: Effect.fn(function* ({ news, olds, output }) {
224 if (!isResolved(news)) return undefined;
225 const previousPackage = olds?.packageName ?? output?.packageName;
226 if (previousPackage !== undefined && news.packageName !== previousPackage) {
227 return { action: "replace" as const, deleteFirst: false };
228 }
229 const previousId = olds?.productId ?? output?.productId;
230 if (
231 previousId !== undefined &&
232 news.productId !== undefined &&
233 news.productId !== previousId
234 ) {
235 return { action: "replace" as const, deleteFirst: true };
236 }
237 return undefined;
238 }),
239
240 read: Effect.fn(function* ({ id, olds, output, previous }) {
241 const env = yield* GcpEnvironment.current;
242 const packageName = olds?.packageName ?? output?.packageName ?? "";
243 const productId = yield* toProductId(id, olds?.productId, output?.productId);
244 const existing = yield* getSubscription(packageName, productId);
245 if (existing === undefined) return undefined;
246 const attrs = toAttrs(existing, env.project);
247 // No labels field: without prior state the subscription may not be ours.
248 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "productId");
249 }),
250
251 reconcile: Effect.fn(function* ({ id, news, output }) {
252 const env = yield* GcpEnvironment.current;
253 const packageName = news.packageName;
254 const productId = yield* toProductId(id, news.productId, output?.productId);
255 const title = yield* toDisplayName(
256 id,
257 news.listings?.[0]?.title,
258 output?.listings?.[0]?.title,
259 );
260 const listings = defaultSubscriptionListings(news.listings, title);
261 const regionsVersion = news.regionsVersion ?? DEFAULT_REGIONS_VERSION;
262 const desired = desiredBody({
263 packageName,
264 productId,
265 listings,
266 news,
267 });
268
269 let current = yield* getSubscription(packageName, productId);
270
271 if (current === undefined) {
272 const created = yield* androidpublisher
273 .createMonetizationSubscriptions({
274 packageName,
275 productId,
276 "regionsVersion.version": regionsVersion,
277 body: desired,
278 })
279 .pipe(Effect.catchTag("Conflict", () => getSubscription(packageName, productId)));
280 current = created ?? undefined;
281 }
282
283 if (current === undefined) {
284 return yield* new MonetizationSubscriptionNotResolved({
285 packageName,
286 productId,
287 });
288 }
289
290 if (needsSync(current, desired)) {
291 const updateMask = syncMask(current, desired);
292 if (updateMask.length > 0) {
293 current = yield* androidpublisher.patchMonetizationSubscriptions({
294 packageName,
295 productId: current.productId ?? productId,
296 updateMask,
297 "regionsVersion.version": regionsVersion,
298 latencyTolerance: news.latencyTolerance,
299 body: desired,
300 });
301 }
302 }
303
304 return toAttrs(current, env.project);
305 }),
306
307 delete: Effect.fn(function* ({ output }) {
308 if (!output.packageName || !output.productId) return;
309 yield* androidpublisher
310 .deleteMonetizationSubscriptions({
311 packageName: output.packageName,
312 productId: output.productId,
313 })
314 .pipe(Effect.catchTag("NotFound", () => Effect.void));
315 }),
316 });