@cosmicdrift/kumiko-bundled-features 0.404.1 → 0.406.0

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 (134) hide show
  1. package/dist/auth-email-password/mail-notifications.d.ts +3 -3
  2. package/dist/auth-email-password/mail-notifications.js +10 -34
  3. package/dist/auth-email-password/web/default-topbar-actions.d.ts +6 -1
  4. package/dist/auth-email-password/web/default-topbar-actions.js +2 -2
  5. package/dist/auth-email-password/web/index.d.ts +2 -0
  6. package/dist/auth-email-password/web/index.js +1 -0
  7. package/dist/auth-email-password/web/invite-accept-screen.js +6 -41
  8. package/dist/auth-email-password/web/tenant-label.d.ts +2 -0
  9. package/dist/auth-email-password/web/tenant-label.js +10 -0
  10. package/dist/auth-email-password/web/tenant-menu-items.js +2 -7
  11. package/dist/auth-email-password/web/tenant-switcher.js +5 -12
  12. package/dist/auth-email-password/web/use-redirect-authed-from-login.d.ts +7 -0
  13. package/dist/auth-email-password/web/use-redirect-authed-from-login.js +30 -0
  14. package/dist/auth-foundation/feature.js +8 -21
  15. package/dist/auth-mfa/handlers/reencrypt.job.js +7 -15
  16. package/dist/auth-mfa/hmac-token-codec.d.ts +6 -1
  17. package/dist/auth-mfa/hmac-token-codec.js +8 -10
  18. package/dist/auth-mfa/mfa-challenge-token.js +2 -8
  19. package/dist/auth-mfa/mfa-preauth-setup-token.js +2 -8
  20. package/dist/auth-mfa/mfa-setup-token.d.ts +2 -8
  21. package/dist/auth-mfa/mfa-setup-token.js +8 -45
  22. package/dist/billing-foundation/consumer-protection/termination-revoke.js +3 -11
  23. package/dist/billing-foundation/feature.js +1 -5
  24. package/dist/billing-foundation/handlers/process-event.write.js +2 -6
  25. package/dist/billing-foundation/handlers/process-payment-event.write.js +2 -6
  26. package/dist/billing-foundation/index.d.ts +2 -0
  27. package/dist/billing-foundation/index.js +2 -0
  28. package/dist/billing-foundation/projection.js +12 -21
  29. package/dist/billing-foundation/provider-event-seen.d.ts +5 -0
  30. package/dist/billing-foundation/provider-event-seen.js +7 -0
  31. package/dist/billing-foundation/provider-shared.d.ts +11 -0
  32. package/dist/billing-foundation/provider-shared.js +44 -0
  33. package/dist/billing-foundation/tenant-destroy-hook.js +5 -4
  34. package/dist/channel-email/feature.js +1 -1
  35. package/dist/config/handlers/reencrypt.job.js +7 -15
  36. package/dist/delivery/delivery-service.js +2 -8
  37. package/dist/file-derivatives/feature.js +9 -21
  38. package/dist/file-foundation/feature.js +2 -6
  39. package/dist/files-tenant-data/hooks.js +1 -6
  40. package/dist/folders/feature.js +2 -9
  41. package/dist/folders/web/folder-manager.js +7 -26
  42. package/dist/folders/web/folder-section.js +5 -24
  43. package/dist/form-draft/handlers/save.write.d.ts +9 -0
  44. package/dist/form-draft/handlers/save.write.js +3 -7
  45. package/dist/inbound-mail-foundation/feature.js +2 -6
  46. package/dist/inbound-mail-foundation/oauth-state.js +5 -13
  47. package/dist/inbound-mail-foundation/tenant-destroy-hook.d.ts +1 -1
  48. package/dist/inbound-mail-foundation/tenant-destroy-hook.js +3 -18
  49. package/dist/jobs/handlers/tenant-failures.query.js +1 -15
  50. package/dist/jobs/handlers/tenant-runs.query.js +1 -14
  51. package/dist/jobs/job-run-logger.js +19 -23
  52. package/dist/jobs/parse-subject.d.ts +1 -0
  53. package/dist/jobs/parse-subject.js +15 -0
  54. package/dist/ledger/feature.js +2 -8
  55. package/dist/mail-foundation/feature.js +3 -7
  56. package/dist/managed-pages/render-page-body.js +4 -12
  57. package/dist/notes-history/feature.js +2 -9
  58. package/dist/personal-access-tokens/handlers/list.query.js +1 -9
  59. package/dist/personal-access-tokens/hash.js +2 -2
  60. package/dist/personal-access-tokens/parse-scope-names.d.ts +1 -0
  61. package/dist/personal-access-tokens/parse-scope-names.js +10 -0
  62. package/dist/personal-access-tokens/resolver.js +1 -9
  63. package/dist/renderer-foundation/feature.js +3 -14
  64. package/dist/secrets/handlers/rotate.job.js +7 -18
  65. package/dist/shared/collect-extension-options.d.ts +4 -0
  66. package/dist/shared/collect-extension-options.js +8 -0
  67. package/dist/shared/hmac-signature.d.ts +2 -0
  68. package/dist/shared/hmac-signature.js +10 -0
  69. package/dist/shared/index.d.ts +6 -0
  70. package/dist/shared/index.js +6 -0
  71. package/dist/shared/is-unique-constraint-failure.d.ts +2 -0
  72. package/dist/shared/is-unique-constraint-failure.js +7 -0
  73. package/dist/shared/mail-locale-templates.d.ts +12 -0
  74. package/dist/shared/mail-locale-templates.js +36 -0
  75. package/dist/shared/resolve-feature-access.d.ts +7 -0
  76. package/dist/shared/resolve-feature-access.js +8 -0
  77. package/dist/shared/signed-token.js +4 -14
  78. package/dist/shared/single-use-token-store.js +2 -2
  79. package/dist/shared/stream-tenant-derived-state.js +1 -5
  80. package/dist/shared/tenant-db-cache.d.ts +3 -0
  81. package/dist/shared/tenant-db-cache.js +14 -0
  82. package/dist/shared/web/status-banner.d.ts +15 -0
  83. package/dist/shared/web/status-banner.js +13 -0
  84. package/dist/shared/web/use-dispatched-writes.d.ts +8 -0
  85. package/dist/shared/web/use-dispatched-writes.js +29 -0
  86. package/dist/subscription-paddle/feature.js +2 -15
  87. package/dist/subscription-paddle/price-methods.d.ts +2 -5
  88. package/dist/subscription-paddle/price-methods.js +5 -26
  89. package/dist/subscription-paddle/runtime.d.ts +1 -1
  90. package/dist/subscription-paddle/runtime.js +3 -16
  91. package/dist/subscription-stripe/feature.js +2 -17
  92. package/dist/subscription-stripe/plugin-methods.d.ts +2 -5
  93. package/dist/subscription-stripe/plugin-methods.js +3 -18
  94. package/dist/subscription-stripe/runtime.js +3 -19
  95. package/dist/tags/feature.js +2 -9
  96. package/dist/tags/web/tag-manager.js +5 -24
  97. package/dist/tags/web/tag-section.js +3 -12
  98. package/dist/template-resolver/handlers/tenant-overrides.query.js +3 -9
  99. package/dist/tenant/handlers/decrypt-member-users.d.ts +10 -0
  100. package/dist/tenant/handlers/decrypt-member-users.js +17 -0
  101. package/dist/tenant/handlers/members.query.js +2 -17
  102. package/dist/tenant/handlers/team-list.query.js +4 -17
  103. package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.d.ts +5 -0
  104. package/dist/tenant-lifecycle/archive-and-delete-tenant-rows.js +20 -0
  105. package/dist/tenant-lifecycle/constants.d.ts +1 -0
  106. package/dist/tenant-lifecycle/constants.js +5 -0
  107. package/dist/tenant-lifecycle/events.d.ts +2 -0
  108. package/dist/tenant-lifecycle/events.js +2 -0
  109. package/dist/tenant-lifecycle/feature.js +1 -1
  110. package/dist/tenant-lifecycle/index.d.ts +2 -1
  111. package/dist/tenant-lifecycle/index.js +2 -1
  112. package/dist/tenant-lifecycle/run-tenant-destroy.d.ts +2 -0
  113. package/dist/tenant-lifecycle/run-tenant-destroy.js +42 -7
  114. package/dist/tenant-lifecycle/stages.d.ts +1 -0
  115. package/dist/tenant-lifecycle/stages.js +4 -1
  116. package/dist/tier-engine/feature.js +1 -1
  117. package/dist/user-data-rights/build-hook-db.d.ts +11 -0
  118. package/dist/user-data-rights/build-hook-db.js +22 -0
  119. package/dist/user-data-rights/handlers/request-export.write.js +2 -12
  120. package/dist/user-data-rights/mail-notifications.d.ts +3 -3
  121. package/dist/user-data-rights/mail-notifications.js +10 -34
  122. package/dist/user-data-rights/run-forget-cleanup.d.ts +1 -1
  123. package/dist/user-data-rights/run-forget-cleanup.js +2 -21
  124. package/dist/user-data-rights/run-user-export.d.ts +1 -1
  125. package/dist/user-data-rights/run-user-export.js +2 -21
  126. package/dist/user-data-rights/token-helpers.js +2 -14
  127. package/dist/user-data-rights/web/privacy-center-screen.js +1 -11
  128. package/dist/user-profile/web/profile-screen.js +1 -11
  129. package/package.json +20 -20
  130. package/src/auth-email-password/changes.json +6 -0
  131. package/src/auth-mfa/changes.json +6 -0
  132. package/src/billing-foundation/changes.json +6 -0
  133. package/src/shared/changes.json +6 -0
  134. package/src/tenant-lifecycle/changes.json +18 -0
@@ -0,0 +1,8 @@
1
+ // `access` wins over the `roles` shorthand; neither set falls back to the feature default.
2
+ export function resolveFeatureAccess(opts, defaultAccess) {
3
+ if (opts.access !== undefined)
4
+ return opts.access;
5
+ if (opts.roles !== undefined)
6
+ return { roles: opts.roles };
7
+ return defaultAccess;
8
+ }
@@ -11,18 +11,15 @@
11
11
  //
12
12
  // Timing-safe comparison on verify so a valid-length forgery can't leak
13
13
  // signal through a short-circuit.
14
- import { createHmac, timingSafeEqual } from "node:crypto";
15
14
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
16
- function sign(input, secret) {
17
- return createHmac("sha256", secret).update(input).digest("base64url");
18
- }
15
+ import { hmacSignatureMatches, signHmacSha256Base64Url } from "./hmac-signature.js";
19
16
  function payload(purpose, userId, expiresAtMs) {
20
17
  return `${purpose}:${userId}.${expiresAtMs}`;
21
18
  }
22
19
  export function signToken(userId, purpose, ttlMinutes, secret, now = Temporal.Now.instant()) {
23
20
  const expiresAt = now.add({ minutes: ttlMinutes });
24
21
  const expiresAtMs = expiresAt.epochMilliseconds;
25
- const signature = sign(payload(purpose, userId, expiresAtMs), secret);
22
+ const signature = signHmacSha256Base64Url(payload(purpose, userId, expiresAtMs), secret);
26
23
  return {
27
24
  token: `${userId}.${expiresAtMs}.${signature}`,
28
25
  expiresAt,
@@ -56,15 +53,8 @@ export function verifyToken(token, purpose, secret, now = Temporal.Now.instant()
56
53
  if (!Number.isFinite(expiresAtMs) || String(expiresAtMs) !== expiresAtRaw) {
57
54
  return { ok: false, reason: "malformed" };
58
55
  }
59
- const expected = sign(payload(purpose, userId, expiresAtMs), secret);
60
- const expectedBuf = Buffer.from(expected, "base64url");
61
- const providedBuf = Buffer.from(providedSig, "base64url");
62
- // Length mismatch fails BEFORE timingSafeEqual, which throws on different
63
- // lengths — but that throw itself leaks via timing. Explicit length check
64
- // keeps the path uniform.
65
- if (expectedBuf.length !== providedBuf.length)
66
- return { ok: false, reason: "bad_signature" };
67
- if (!timingSafeEqual(expectedBuf, providedBuf))
56
+ const expected = signHmacSha256Base64Url(payload(purpose, userId, expiresAtMs), secret);
57
+ if (!hmacSignatureMatches(expected, providedSig))
68
58
  return { ok: false, reason: "bad_signature" };
69
59
  if (Temporal.Instant.compare(now, Temporal.Instant.fromEpochMilliseconds(expiresAtMs)) > 0) {
70
60
  return { ok: false, reason: "expired" };
@@ -37,12 +37,12 @@
37
37
  // gets "already-used". TTL is 1h (short enough that the burn-key doesn't
38
38
  // permanently tax Redis, long enough to catch replays inside any realistic
39
39
  // race window).
40
- import { createHash } from "node:crypto";
40
+ import { hashOpaqueTokenSync } from "@cosmicdrift/kumiko-framework/crypto";
41
41
  // Exported so a caller that needs a byte-compatible key in a sibling Redis
42
42
  // namespace (e.g. a token↔binding side-mapping) can derive it without
43
43
  // re-implementing sha256-of-token — see auth-email-password/signup-token-store.ts.
44
44
  export function hashSingleUseToken(token) {
45
- return createHash("sha256").update(token).digest("hex");
45
+ return hashOpaqueTokenSync(token);
46
46
  }
47
47
  export function createSingleUseTokenStore(prefixes) {
48
48
  function tokenKey(token) {
@@ -3,7 +3,7 @@
3
3
  // in stream-tenant-backfill.ts; this part is repeatable and safe to run without moves.
4
4
  import { SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
5
5
  import { rebuildProjection } from "@cosmicdrift/kumiko-framework/pipeline";
6
- import { reindexEntity } from "@cosmicdrift/kumiko-framework/search";
6
+ import { isEntitySearchable, reindexEntity, } from "@cosmicdrift/kumiko-framework/search";
7
7
  export function createSearchBucketCleanup(searchAdapter, entityType) {
8
8
  let cleaned = 0;
9
9
  return {
@@ -56,10 +56,6 @@ export async function rebuildAndReindex(deps) {
56
56
  }
57
57
  return { projectionsRebuilt, reindexedRows, failures };
58
58
  }
59
- function isEntitySearchable(registry, entityName) {
60
- return (registry.getSearchableFields(entityName).length > 0 ||
61
- registry.getSearchPayloadExtensions(entityName).length > 0);
62
- }
63
59
  export function stepFailures(step, failed) {
64
60
  return failed.map((f) => ({ ...f, step }));
65
61
  }
@@ -0,0 +1,3 @@
1
+ import type { TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
+ import type { TenantId } from "@cosmicdrift/kumiko-framework/engine";
3
+ export declare function createTenantDbCache(create: (tenantId: TenantId) => TenantDb): (tenantId: TenantId) => TenantDb;
@@ -0,0 +1,14 @@
1
+ // One TenantDb per tenant, so a job touching many rows of the same tenant does
2
+ // not rebuild the wrapper per row. The caller builds the TenantDb itself, so
3
+ // its createTenantDb call keeps the literal system-mode reason the guard needs.
4
+ export function createTenantDbCache(create) {
5
+ const cache = new Map();
6
+ return (tenantId) => {
7
+ let existing = cache.get(tenantId);
8
+ if (!existing) {
9
+ existing = create(tenantId);
10
+ cache.set(tenantId, existing);
11
+ }
12
+ return existing;
13
+ };
14
+ }
@@ -0,0 +1,15 @@
1
+ import type { ReactNode } from "react";
2
+ export type SectionStatus = {
3
+ kind: "idle";
4
+ } | {
5
+ kind: "submitting";
6
+ } | {
7
+ kind: "success";
8
+ messageKey: string;
9
+ } | {
10
+ kind: "error";
11
+ messageKey: string;
12
+ };
13
+ export declare function StatusBanner({ status }: {
14
+ readonly status: SectionStatus;
15
+ }): ReactNode;
@@ -0,0 +1,13 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { usePrimitives, useTranslation } from "@cosmicdrift/kumiko-renderer";
3
+ export function StatusBanner({ status }) {
4
+ const t = useTranslation();
5
+ const { Banner } = usePrimitives();
6
+ if (status.kind === "success") {
7
+ return _jsx(Banner, { variant: "info", children: t(status.messageKey) });
8
+ }
9
+ if (status.kind === "error") {
10
+ return _jsx(Banner, { variant: "error", children: t(status.messageKey) });
11
+ }
12
+ return null;
13
+ }
@@ -0,0 +1,8 @@
1
+ export declare function useDispatchedWrites(onWriteSucceeded?: () => Promise<void> | void): {
2
+ busy: boolean;
3
+ setBusy: import("react").Dispatch<import("react").SetStateAction<boolean>>;
4
+ errorKey: string | null;
5
+ setErrorKey: import("react").Dispatch<import("react").SetStateAction<string | null>>;
6
+ writeOk: (type: string, payload: Record<string, unknown>) => Promise<boolean>;
7
+ apply: (write: () => Promise<boolean>) => Promise<void>;
8
+ };
@@ -0,0 +1,29 @@
1
+ import { useDispatcher } from "@cosmicdrift/kumiko-renderer";
2
+ import { useState } from "react";
3
+ // Busy flag + error key shared by the folders/tags management surfaces: every
4
+ // write goes through the dispatcher and a failed one surfaces its i18n key.
5
+ export function useDispatchedWrites(onWriteSucceeded) {
6
+ const dispatcher = useDispatcher();
7
+ const [busy, setBusy] = useState(false);
8
+ const [errorKey, setErrorKey] = useState(null);
9
+ const writeOk = async (type, payload) => {
10
+ const result = await dispatcher.write(type, payload);
11
+ if (!result.isSuccess) {
12
+ setErrorKey(result.error.i18nKey);
13
+ return false;
14
+ }
15
+ return true;
16
+ };
17
+ const apply = async (write) => {
18
+ setBusy(true);
19
+ setErrorKey(null);
20
+ try {
21
+ if (await write())
22
+ await onWriteSucceeded?.();
23
+ }
24
+ finally {
25
+ setBusy(false);
26
+ }
27
+ };
28
+ return { busy, setBusy, errorKey, setErrorKey, writeOk, apply };
29
+ }
@@ -5,6 +5,7 @@
5
5
  // the API environment (sandbox | live) are config keys resolved at call time, like
6
6
  // subscription-stripe. The `apiKey` / `webhookSecret` / `tenantBindingKey` /
7
7
  // `clientToken` options are env→config bridge fallbacks.
8
+ import { validateOneOffPriceIds, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
8
9
  import { access, createSystemConfig, defineFeature, } from "@cosmicdrift/kumiko-framework/engine";
9
10
  import { featureWithEnvSchema } from "@cosmicdrift/kumiko-framework/env";
10
11
  import { egress } from "@cosmicdrift/kumiko-framework/http";
@@ -60,22 +61,8 @@ export function paddleEnvSchema(options) {
60
61
  ]));
61
62
  return z.object({ ...subscriptionPaddleEnvSchema.shape, ...priceShape });
62
63
  }
63
- // Validated once at feature-build time so a typo fails app startup instead of
64
- // silently widening or narrowing the one-off allowlist at request time.
65
- function validateOneOffPriceIds(priceIds) {
66
- const seen = new Set();
67
- for (const priceId of priceIds) {
68
- if (priceId.length === 0) {
69
- throw new Error("subscription-paddle: oneOffPriceIds must not contain an empty string");
70
- }
71
- if (seen.has(priceId)) {
72
- throw new Error(`subscription-paddle: duplicate oneOffPriceIds entry "${priceId}"`);
73
- }
74
- seen.add(priceId);
75
- }
76
- }
77
64
  export function createSubscriptionPaddleFeature(options = {}) {
78
- validateOneOffPriceIds(options.oneOffPriceIds ?? []);
65
+ validateOneOffPriceIds("subscription-paddle", options.oneOffPriceIds ?? []);
79
66
  const now = options.now ?? (() => Temporal.Now.instant().epochMilliseconds);
80
67
  const feature = defineFeature(SUBSCRIPTION_PADDLE_FEATURE, (r) => {
81
68
  r.describe('Paddle Billing provider plugin for `billing-foundation`. Paddle acts as merchant of record: it sells to the customer and issues invoice and VAT, so the consumer-protection texts for this provider come from `consumerProtection.providerTexts`. Reads its API key, webhook secret and tenant binding key from system config keys with `backing:"secrets"` (envelope-encrypted in the secrets store under the system tenant), the public Paddle.js `client-token`, a `billingLive` master switch and an `environment` key (sandbox | live). `environment` is its own key because Paddle serves sandbox and live from different API hosts and a live key must never hit the sandbox host or the other way round; `billingLive` only decides whether checkouts are offered at all. All of them are runtime config, so keys rotate and prod goes live without a redeploy, and the `mask` on each derives the sysadmin settings screen and nav. Mount via `createSubscriptionPaddleFeature({ priceToTier })`; the optional `apiKey`/`webhookSecret`/`tenantBindingKey`/`clientToken` options are env to config bridge fallbacks (`PADDLE_API_KEY`, `PADDLE_WEBHOOK_SECRET`, `PADDLE_TENANT_BINDING_KEY`, `PADDLE_CLIENT_TOKEN`). The plugin always mounts; `createCheckoutSession` throws `feature_disabled` unless `billingLive` is true, and billing counts as enabled only with API key and binding key present. Webhooks arrive at `/webhooks/subscription/paddle` when mounted through the server-runtime `billing.paddle` boot option, or at `/api/subscription/webhook/paddle` when `createSubscriptionWebhookRoute` is mounted by hand and are verified with the `Paddle-Signature` header (HMAC-SHA256 over `ts:rawBody` keyed with the raw secret, any `h1` may match, 5 minute tolerance). Paddle.js can open checkouts with arbitrary `customData` from the browser, so `custom_data.tenantId` is only trusted together with `tenantBinding`, an HMAC of the tenant id under the binding key; events without a valid binding, for prices outside `priceToTier` or without a tenant are dropped. Rotating the binding key makes the webhooks of existing subscriptions fail that check until they are re-bound. Paddle has no hosted checkout page, so the feature serves the Default Payment Link itself at `/billing/paddle-checkout` (the Default Payment Link in the Paddle dashboard must point to `<APP_BASE_URL>/billing/paddle-checkout`; it is the only source, because checkouts are created without a `checkout.url`). Create subscription prices in the Paddle catalog with quantity minimum and maximum 1; for one-off packs set the quantity limits on purpose, because the payment event carries `quantity` and the app has to multiply its credits by it: an anonymous page with its own CSP that loads Paddle.js from cdn.paddle.com, the one external script this framework allows, and opens the overlay for the transaction. Implements checkout, customer portal, cancel and resume, `retrievePrices` (batched, 10-minute TTL cache), `retrieveSubscription` for the sync job, and an in-app plan switch: `previewPlanSwitch` shows the proration before the customer confirms, `applyPlanSwitch` changes the plan without a hosted page and waits for the `subscription.updated` webhook to move the tier.');
@@ -1,12 +1,9 @@
1
- import { type ProviderPrice } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
1
+ import { type ProviderPrice, type TtlPriceCache } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
2
2
  import * as z from "zod";
3
3
  import type { PaddleCtxRuntime, PaddlePluginMethod } from "./runtime.ts";
4
4
  /** Paddle sends amounts as integer strings in the smallest currency unit. */
5
5
  export declare const paddleAmountSchema: z.ZodString;
6
- export type PaddlePriceCache = {
7
- readonly get: (priceId: string) => ProviderPrice | undefined;
8
- readonly set: (priceId: string, price: ProviderPrice) => void;
9
- };
6
+ export type PaddlePriceCache = TtlPriceCache<ProviderPrice>;
10
7
  export type PaddlePriceCacheOptions = {
11
8
  readonly ttlMs?: number;
12
9
  readonly now?: () => number;
@@ -1,6 +1,7 @@
1
1
  // Paddle price lookup for the billing-plans catalog: one batched request for all
2
2
  // cache misses, cached per price id.
3
- import { KNOWN_RECURRING_INTERVALS, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
3
+ import { createTtlPriceCache, KNOWN_RECURRING_INTERVALS, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
4
+ import { chunk } from "@cosmicdrift/kumiko-framework/utils";
4
5
  import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
5
6
  import * as z from "zod";
6
7
  const PRICES_PER_REQUEST = 200;
@@ -49,34 +50,12 @@ function mapPaddlePrice(price) {
49
50
  // Keyed by price id alone: ids are unique per account and a cache hit must not
50
51
  // trigger an audited secret read on every billing-plans render. Failed lookups
51
52
  // are never cached.
52
- export function createPaddlePriceCache({ ttlMs = 600_000, now = () => Temporal.Now.instant().epochMilliseconds, } = {}) {
53
- const store = new Map();
54
- return {
55
- get: (priceId) => {
56
- const entry = store.get(priceId);
57
- if (!entry)
58
- return undefined;
59
- if (entry.expiresAt <= now()) {
60
- store.delete(priceId);
61
- return undefined;
62
- }
63
- return entry.price;
64
- },
65
- set: (priceId, price) => {
66
- store.set(priceId, { price, expiresAt: now() + ttlMs });
67
- },
68
- };
69
- }
70
- function chunked(items, size) {
71
- const chunks = [];
72
- for (let start = 0; start < items.length; start += size) {
73
- chunks.push(items.slice(start, start + size));
74
- }
75
- return chunks;
53
+ export function createPaddlePriceCache({ ttlMs, now = () => Temporal.Now.instant().epochMilliseconds, } = {}) {
54
+ return createTtlPriceCache({ ttlMs, now });
76
55
  }
77
56
  async function fillPriceCache(runtime, cache, ctx, priceIds) {
78
57
  const misses = [...new Set(priceIds.filter((priceId) => cache.get(priceId) === undefined))];
79
- const settled = await Promise.allSettled(chunked(misses, PRICES_PER_REQUEST).map(async (ids) => pricesResponseSchema.parse(await runtime.call(ctx, {
58
+ const settled = await Promise.allSettled(chunk(misses, PRICES_PER_REQUEST).map(async (ids) => pricesResponseSchema.parse(await runtime.call(ctx, {
80
59
  method: "GET",
81
60
  path: "/prices",
82
61
  query: {
@@ -1,4 +1,4 @@
1
- import type { SubscriptionProviderPlugin } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
1
+ import { type SubscriptionProviderPlugin } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
2
2
  import { type ConfigKeyHandle, type HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import type { SecretsContext } from "@cosmicdrift/kumiko-framework/secrets";
4
4
  import { type PaddleRequest, type PaddleSend } from "./client.ts";
@@ -6,25 +6,12 @@
6
6
  // Two read paths: post-tenant handlers read the key audited through the
7
7
  // HandlerContext; the pre-tenant webhook reads secrets un-audited from the
8
8
  // system SecretsContext the foundation passes in.
9
+ import { parseStoredSecret, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
9
10
  import { requireSecretsContext } from "@cosmicdrift/kumiko-bundled-features/secrets";
10
11
  import { SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
11
12
  import { FeatureDisabledError, UnconfiguredError } from "@cosmicdrift/kumiko-framework/errors";
12
- import { parseJsonSafe } from "@cosmicdrift/kumiko-framework/utils";
13
13
  import { createPaddleHttp } from "./client.js";
14
14
  import { PADDLE_BASE_URLS, PaddleEnvironments, SUBSCRIPTION_PADDLE_FEATURE, } from "./constants.js";
15
- // backing:"secrets" values are stored JSON-serialized, so the store read has to
16
- // be parsed back; the env fallback is a plain string and stays raw. The error
17
- // must not carry the input: the JSON parser's own message would repeat the
18
- // credential into logs and, for webhooks, into the 401 body.
19
- function parseStoredSecret(raw) {
20
- if (raw === undefined || raw.length === 0)
21
- return undefined;
22
- const parsed = parseJsonSafe(raw, undefined);
23
- if (parsed === undefined) {
24
- throw new Error("subscription-paddle credential (backing:secrets) is not valid JSON");
25
- }
26
- return typeof parsed === "string" && parsed.length > 0 ? parsed : undefined;
27
- }
28
15
  function hintFor(shortName) {
29
16
  return `Set it via config:write:set on \`${SUBSCRIPTION_PADDLE_FEATURE}:config:${shortName}\` (or seed it from the matching PADDLE_* variable during the env bridge).`;
30
17
  }
@@ -37,7 +24,7 @@ export function createPaddleRuntimes(deps) {
37
24
  let value;
38
25
  if (ctx.services.secrets) {
39
26
  const got = await requireSecretsContext({ secrets: ctx.services.secrets, user: ctx.user }, SUBSCRIPTION_PADDLE_FEATURE).get(SYSTEM_TENANT_ID, handle.name);
40
- value = parseStoredSecret(got?.reveal());
27
+ value = parseStoredSecret("subscription-paddle", got?.reveal());
41
28
  }
42
29
  if (!value && fallback && fallback.length > 0)
43
30
  value = fallback;
@@ -54,7 +41,7 @@ export function createPaddleRuntimes(deps) {
54
41
  if (systemSecrets) {
55
42
  // No auditCtx: every webhook would otherwise spam the audit trail.
56
43
  const got = await systemSecrets.get(SYSTEM_TENANT_ID, handle.name);
57
- const stored = parseStoredSecret(got?.reveal());
44
+ const stored = parseStoredSecret("subscription-paddle", got?.reveal());
58
45
  if (stored)
59
46
  return stored;
60
47
  }
@@ -31,6 +31,7 @@
31
31
  // SecretsContext as the third argument, from which the plugin reads the
32
32
  // api key + webhook secret without auditing (a sanctioned framework-internal
33
33
  // read).
34
+ import { validateOneOffPriceIds, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
34
35
  import { access, createSystemConfig, defineFeature, } from "@cosmicdrift/kumiko-framework/engine";
35
36
  import { featureWithEnvSchema } from "@cosmicdrift/kumiko-framework/env";
36
37
  import * as z from "zod";
@@ -76,22 +77,6 @@ export function stripeEnvSchema(options) {
76
77
  ]));
77
78
  return z.object({ ...subscriptionStripeEnvSchema.shape, ...priceShape });
78
79
  }
79
- // Validated once at feature-build time (not per-request) so a config typo
80
- // (a pasted-twice priceId, a blank string from a bad env-join) fails app
81
- // startup instead of silently widening — or narrowing — the one-off
82
- // allowlist at request time. Mirrors legal-pages' validateRoutes.
83
- function validateOneOffPriceIds(priceIds) {
84
- const seen = new Set();
85
- for (const priceId of priceIds) {
86
- if (priceId.length === 0) {
87
- throw new Error("subscription-stripe: oneOffPriceIds must not contain an empty string");
88
- }
89
- if (seen.has(priceId)) {
90
- throw new Error(`subscription-stripe: duplicate oneOffPriceIds entry "${priceId}"`);
91
- }
92
- seen.add(priceId);
93
- }
94
- }
95
80
  /**
96
81
  * Factory for the subscription-stripe feature. Always mounts (no
97
82
  * key-presence guard) — activity is gated at runtime through config/secrets
@@ -100,7 +85,7 @@ function validateOneOffPriceIds(priceIds) {
100
85
  * extension with entityName "stripe".
101
86
  */
102
87
  export function createSubscriptionStripeFeature(options = {}) {
103
- validateOneOffPriceIds(options.oneOffPriceIds ?? []);
88
+ validateOneOffPriceIds("subscription-stripe", options.oneOffPriceIds ?? []);
104
89
  const feature = defineFeature(SUBSCRIPTION_STRIPE_FEATURE, (r) => {
105
90
  r.describe('Stripe payment provider plugin for `billing-foundation`. Reads its Stripe API key + webhook secret from system config keys with `backing:"secrets"` (envelope-encrypted in the secrets store under the system tenant) and a `billingLive` **system config** flag — all at runtime, so keys rotate and prod goes live without a redeploy. The `mask` on each key derives the sysadmin settings screen + nav, so no app wires a hand-written config UI. Mount via `createSubscriptionStripeFeature({ priceToTier })`; the optional `apiKey`/`webhookSecret` options are env→secrets bridge fallbacks. The plugin always mounts — `createCheckoutSession` throws `feature_disabled` unless `billingLive` is true, so sk_test_ keys in prod never produce a live checkout. Implements webhook verify, checkout, portal, cancel, `retrievePrices` (10-minute TTL-cached price lookup for the billing-plans catalog), `createPlanSwitchSession` (auto-provisions a Customer-Portal configuration for switching an existing subscription to another plan tier — each tier needs its own Stripe product), `retrieveSubscription` (live provider-side snapshot for the `sync-subscriptions` backfill job, mapped identically to the webhook path), plus `isBillingEnabled` (billingLive + an api-key existence probe, no secret read).');
106
91
  r.uiHints({
@@ -1,4 +1,4 @@
1
- import { type ProviderPrice, type ProviderSubscriptionSnapshot, type SubscriptionProviderPlugin } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
1
+ import { type ProviderPrice, type ProviderSubscriptionSnapshot, type SubscriptionProviderPlugin, type TtlPriceCache } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
2
2
  import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
3
3
  import Stripe from "stripe";
4
4
  import type { StripeCtxRuntime } from "./runtime.ts";
@@ -25,10 +25,7 @@ export type StripeRetrieveSubscriptionOptions = {
25
25
  readonly priceToTier: Readonly<Record<string, string>>;
26
26
  };
27
27
  export declare function createStripeRetrieveSubscription(runtime: StripeCtxRuntime, { priceToTier }: StripeRetrieveSubscriptionOptions): (ctx: HandlerContext, providerSubscriptionId: string) => Promise<ProviderSubscriptionSnapshot | null>;
28
- export type StripePriceCache = {
29
- readonly get: (priceId: string) => Stripe.Price | undefined;
30
- readonly set: (priceId: string, price: Stripe.Price) => void;
31
- };
28
+ export type StripePriceCache = TtlPriceCache<Stripe.Price>;
32
29
  export type StripePriceCacheOptions = {
33
30
  readonly ttlMs?: number;
34
31
  readonly now?: () => number;
@@ -15,7 +15,7 @@
15
15
  // contract (for example, with a new optional field), the Stripe plugin detects
16
16
  // it at TypeScript compile time rather than at runtime.
17
17
  import { createHash } from "node:crypto";
18
- import { KNOWN_RECURRING_INTERVALS, SubscriptionCancelTimings, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
18
+ import { createTtlPriceCache, KNOWN_RECURRING_INTERVALS, SubscriptionCancelTimings, } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
19
19
  import { ConflictError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
20
20
  import Stripe from "stripe";
21
21
  import { isResourceMissingStripeError, mapStripeSubscriptionState } from "./verify-webhook.js";
@@ -236,23 +236,8 @@ function mapStripePrice(price) {
236
236
  metadata: price.metadata ?? {},
237
237
  };
238
238
  }
239
- export function createStripePriceCache({ ttlMs = 600_000, now = () => Date.now(), } = {}) {
240
- const store = new Map();
241
- return {
242
- get: (priceId) => {
243
- const entry = store.get(priceId);
244
- if (!entry)
245
- return undefined;
246
- if (entry.expiresAt <= now()) {
247
- store.delete(priceId);
248
- return undefined;
249
- }
250
- return entry.price;
251
- },
252
- set: (priceId, price) => {
253
- store.set(priceId, { price, expiresAt: now() + ttlMs });
254
- },
255
- };
239
+ export function createStripePriceCache({ ttlMs, now = () => Date.now(), } = {}) {
240
+ return createTtlPriceCache({ ttlMs, now });
256
241
  }
257
242
  /** Fills `cache` for every priceId not already resolved — the only place
258
243
  * that ever calls `stripe.prices.retrieve`, shared by retrievePrices and
@@ -24,10 +24,10 @@
24
24
  // `SecretsContext.get(SYSTEM_TENANT_ID, handle)` (the sanctioned
25
25
  // un-audited framework-internal path). The foundation builds and passes
26
26
  // this SecretsContext as the 3rd webhook arg.
27
+ import { parseStoredSecret } from "@cosmicdrift/kumiko-bundled-features/billing-foundation";
27
28
  import { requireSecretsContext } from "@cosmicdrift/kumiko-bundled-features/secrets";
28
29
  import { SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
29
30
  import { FeatureDisabledError, UnconfiguredError } from "@cosmicdrift/kumiko-framework/errors";
30
- import { parseJsonSafe } from "@cosmicdrift/kumiko-framework/utils";
31
31
  import Stripe from "stripe";
32
32
  import { SUBSCRIPTION_STRIPE_FEATURE } from "./constants.js";
33
33
  const API_KEY_HINT = "Set the Stripe API key via config:write:set on `subscription-stripe:config:api-key` (or seed it from STRIPE_API_KEY during the env bridge).";
@@ -47,29 +47,13 @@ export function createStripeClientCache() {
47
47
  return client;
48
48
  };
49
49
  }
50
- // backing:"secrets" config keys store their value JSON-serialized in the
51
- // secrets store (config:write:set → JSON.stringify). A raw SecretsContext.get
52
- // (the un-audited webhook path + the audited ctx read here) therefore returns
53
- // the JSON-quoted string and must parse it back. The factory fallback is a
54
- // plain env string and stays raw — so parsing is applied only to the store
55
- // read, never to the fallback. The error must not carry the input: the JSON
56
- // parser's own message would repeat the credential into logs and the 401 body.
57
- function parseStoredSecret(raw) {
58
- if (raw === undefined || raw.length === 0)
59
- return undefined;
60
- const parsed = parseJsonSafe(raw, undefined);
61
- if (parsed === undefined) {
62
- throw new Error("subscription-stripe credential (backing:secrets) is not valid JSON");
63
- }
64
- return typeof parsed === "string" && parsed.length > 0 ? parsed : undefined;
65
- }
66
50
  export function createStripeRuntimes(deps) {
67
51
  const clientFor = createStripeClientCache();
68
52
  async function ctxApiKey(ctx) {
69
53
  let key;
70
54
  if (ctx.services.secrets) {
71
55
  const got = await requireSecretsContext({ secrets: ctx.services.secrets, user: ctx.user }, SUBSCRIPTION_STRIPE_FEATURE).get(SYSTEM_TENANT_ID, deps.apiKeyHandle.name);
72
- key = parseStoredSecret(got?.reveal());
56
+ key = parseStoredSecret("subscription-stripe", got?.reveal());
73
57
  }
74
58
  if (!key && deps.fallback.apiKey && deps.fallback.apiKey.length > 0) {
75
59
  key = deps.fallback.apiKey;
@@ -88,7 +72,7 @@ export function createStripeRuntimes(deps) {
88
72
  // No auditCtx → un-audited framework-internal read (every webhook would
89
73
  // otherwise spam the audit trail). This is the sanctioned no-ctx path.
90
74
  const got = await systemSecrets.get(SYSTEM_TENANT_ID, handle.name);
91
- const value = parseStoredSecret(got?.reveal());
75
+ const value = parseStoredSecret("subscription-stripe", got?.reveal());
92
76
  if (value && value.length > 0)
93
77
  return value;
94
78
  }
@@ -18,7 +18,7 @@
18
18
  // entityList/entityEdit catalog screens (legacy QNs stay for TagManager).
19
19
  // Deferred: optional host-projection decoration (`wireTagsFor`), search indexing.
20
20
  import { defineEntityDetailHandler, defineEntityListHandler, defineEntityUpdateHandler, defineFeature, } from "@cosmicdrift/kumiko-framework/engine";
21
- import { assertNoWhereRuleInOwnershipWrite } from "../shared/index.js";
21
+ import { assertNoWhereRuleInOwnershipWrite, resolveFeatureAccess } from "../shared/index.js";
22
22
  import { createTagAssignmentEntity, tagEntity } from "./entity.js";
23
23
  import { createTagAssignmentExecutor } from "./executor.js";
24
24
  import { createAssignTagHandler } from "./handlers/assign-tag.write.js";
@@ -86,13 +86,6 @@ function registerTags(r, access, toggleable, ownership, parents) {
86
86
  r.translations({ keys: TAGS_FEATURE_I18N });
87
87
  }
88
88
  const defaultTagsFeature = defineFeature(TAGS_FEATURE_NAME, (r) => registerTags(r, DEFAULT_TAG_ACCESS, undefined, undefined, undefined));
89
- function resolveAccess(opts) {
90
- if (opts.access !== undefined)
91
- return opts.access;
92
- if (opts.roles !== undefined)
93
- return { roles: opts.roles };
94
- return DEFAULT_TAG_ACCESS;
95
- }
96
89
  // Backwards-compat / options wrapper. Without options returns the module-level
97
90
  // singleton (no rebuild). access/roles/toggleable/ownership build a fresh
98
91
  // feature-definition.
@@ -111,6 +104,6 @@ export function createTagsFeature(opts = {}) {
111
104
  "admissible as a host instead.");
112
105
  }
113
106
  assertNoWhereRuleInOwnershipWrite("createTagsFeature", opts.ownership?.write);
114
- const access = resolveAccess(opts);
107
+ const access = resolveFeatureAccess(opts, DEFAULT_TAG_ACCESS);
115
108
  return defineFeature(TAGS_FEATURE_NAME, (r) => registerTags(r, access, opts.toggleable, opts.ownership, opts.parents));
116
109
  }
@@ -12,6 +12,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
12
12
  import { useDispatcher, usePrimitives, useQuery, useTranslation, } from "@cosmicdrift/kumiko-renderer";
13
13
  import { pluralKey } from "@cosmicdrift/kumiko-renderer/headless";
14
14
  import { useState } from "react";
15
+ import { useDispatchedWrites } from "../../shared/web/use-dispatched-writes.js";
15
16
  import { TagsHandlers, TagsQueries } from "./constants.js";
16
17
  import { TagChip } from "./tag-chip.js";
17
18
  // A small fixed palette so labels stay visually distinct without a color-wheel
@@ -54,8 +55,10 @@ export function TagManager({ entityType, selection, }) {
54
55
  const [editColor, setEditColor] = useState("");
55
56
  const [editScope, setEditScope] = useState("");
56
57
  const [deleting, setDeleting] = useState(null);
57
- const [busy, setBusy] = useState(false);
58
- const [errorKey, setErrorKey] = useState(null);
58
+ const refetch = async () => {
59
+ await Promise.all([catalog.refetch(), assignments.refetch()]);
60
+ };
61
+ const { busy, errorKey, setErrorKey, writeOk, apply } = useDispatchedWrites(refetch);
59
62
  if (catalog.loading && catalog.data === null) {
60
63
  return (_jsx(Banner, { variant: "loading", testId: "tag-manager-loading", children: _jsx(Text, { children: t("tags.section.loading") }) }));
61
64
  }
@@ -75,28 +78,6 @@ export function TagManager({ entityType, selection, }) {
75
78
  return scope === "" || scope === entityType;
76
79
  })
77
80
  : allTags;
78
- const refetch = async () => {
79
- await Promise.all([catalog.refetch(), assignments.refetch()]);
80
- };
81
- const apply = async (writes) => {
82
- setBusy(true);
83
- setErrorKey(null);
84
- try {
85
- if (await writes())
86
- await refetch();
87
- }
88
- finally {
89
- setBusy(false);
90
- }
91
- };
92
- const writeOk = async (type, payload) => {
93
- const result = await dispatcher.write(type, payload);
94
- if (!result.isSuccess) {
95
- setErrorKey(result.error.i18nKey);
96
- return false;
97
- }
98
- return true;
99
- };
100
81
  const createTag = () => {
101
82
  const name = newName.trim();
102
83
  if (name === "")
@@ -11,8 +11,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
11
11
  // - extension: a screen-schema section with
12
12
  // component: { react: { __component: TAGS_SECTION_EXTENSION_NAME } }
13
13
  // (RenderEdit passes { entityName, entityId }).
14
- import { useDispatcher, usePrimitives, useQuery, useTranslation, } from "@cosmicdrift/kumiko-renderer";
14
+ import { usePrimitives, useQuery, useTranslation } from "@cosmicdrift/kumiko-renderer";
15
15
  import { useState } from "react";
16
+ import { useDispatchedWrites } from "../../shared/web/use-dispatched-writes.js";
16
17
  import { TagsHandlers, TagsQueries } from "./constants.js";
17
18
  import { TagChip } from "./tag-chip.js";
18
19
  import { TagPicker } from "./tag-picker.js";
@@ -28,7 +29,6 @@ export function tagSelectionDelta(prev, next) {
28
29
  export function TagSection({ entityName, entityId, }) {
29
30
  const { Banner, Button, Text } = usePrimitives();
30
31
  const t = useTranslation();
31
- const dispatcher = useDispatcher();
32
32
  const enabled = entityId !== null;
33
33
  const catalog = useQuery(TagsQueries.tagList, {}, { enabled });
34
34
  // entityType server-side, not just entityId: it collapses the parent-ref
@@ -40,8 +40,7 @@ export function TagSection({ entityName, entityId, }) {
40
40
  ],
41
41
  }, { enabled });
42
42
  const [pickerOpen, setPickerOpen] = useState(false);
43
- const [busy, setBusy] = useState(false);
44
- const [errorKey, setErrorKey] = useState(null);
43
+ const { busy, setBusy, errorKey, setErrorKey, writeOk } = useDispatchedWrites();
45
44
  if (entityId === null) {
46
45
  return (_jsx(Banner, { variant: "info", testId: "tags-section-create-mode", children: _jsx(Text, { children: t("tags.section.createMode") }) }));
47
46
  }
@@ -58,14 +57,6 @@ export function TagSection({ entityName, entityId, }) {
58
57
  const refetch = async () => {
59
58
  await Promise.all([catalog.refetch(), assignments.refetch()]);
60
59
  };
61
- const writeOk = async (type, payload) => {
62
- const result = await dispatcher.write(type, payload);
63
- if (!result.isSuccess) {
64
- setErrorKey(result.error.i18nKey);
65
- return false;
66
- }
67
- return true;
68
- };
69
60
  const onPicked = (next) => {
70
61
  const { added, removed } = tagSelectionDelta(assignedIds, next);
71
62
  if (added.length === 0 && removed.length === 0)
@@ -1,5 +1,6 @@
1
1
  import { selectMany } from "@cosmicdrift/kumiko-framework/db";
2
2
  import { defineQueryHandler, MAX_LIST_LIMIT, SYSTEM_TENANT_ID, } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { chunk } from "@cosmicdrift/kumiko-framework/utils";
3
4
  import * as z from "zod";
4
5
  import { TenantQueries } from "../../tenant/index.js";
5
6
  import { templateResourcesTable } from "../table.js";
@@ -10,18 +11,11 @@ import { loadEnabledTenantIds, pickBestRowPerTenant, TENANT_OVERRIDES_REASON, }
10
11
  const directorySchema = z.object({
11
12
  rows: z.array(z.object({ id: z.string(), label: z.string() })),
12
13
  });
13
- function chunksOf(items, size) {
14
- const chunks = [];
15
- for (let start = 0; start < items.length; start += size) {
16
- chunks.push(items.slice(start, start + size));
17
- }
18
- return chunks;
19
- }
20
14
  // Looks up only the ids the overrides need, so labels never depend on the directory's default cap.
21
15
  async function labelsFor(ctx, queryName, ids) {
22
16
  const labels = new Map();
23
- for (const chunk of chunksOf([...ids], MAX_LIST_LIMIT)) {
24
- const raw = await ctx.dispatch.query(queryName, { ids: chunk });
17
+ for (const idChunk of chunk([...ids], MAX_LIST_LIMIT)) {
18
+ const raw = await ctx.dispatch.query(queryName, { ids: idChunk });
25
19
  for (const row of directorySchema.parse(raw).rows)
26
20
  labels.set(row.id, row.label);
27
21
  }