@marktiderman/genesis-product 0.0.0-stage → 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mark Tiderman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,171 @@
1
- # Temporary Holding Version
1
+ # @marktiderman/genesis-product
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The product system for a Genesis repo, first version: what is being built now, next and later,
4
+ what people are asking for, and release notes that tell them when it shipped.
5
+
6
+ Status: experimental, published so apps made from the RN starter can install it (its product
7
+ demo is off by default). This repo uses it on itself first.
8
+
9
+ - **The catalog is `features.ts`.** Features, their status, `horizon` (now, next, later) and
10
+ `claimedBy` come from the registry's generated `features.json`. There is no second list.
11
+ - **Signals are the evidence.** An idea, a piece of feedback or a bug, linked to a FeatureId, with
12
+ an importance (1 to 3) and votes. They come from a `SignalSource`: GitHub issues today, a
13
+ database later, with nothing above it changing.
14
+ - **Demand** is each open signal's importance (1 when unset) plus its votes. Closed signals don't
15
+ count, so demand falls as asks are answered.
16
+
17
+ ## Use it on a repo
18
+
19
+ People ask through the issue forms in `.github/ISSUE_TEMPLATE` (Idea, Feedback or bug). A 👍 on
20
+ an issue is a vote: one per person, not counting the issue's author or bots.
21
+
22
+ To triage an issue, a triager links it to a feature with a `feature:<id>` label. The id a sender
23
+ types under **Feature** is only a suggestion, shown in the triage inbox: anyone can open an issue,
24
+ so only a label (which only triagers can add) counts toward demand or lets a release close it.
25
+ `importance:low|medium|high` sets its weight.
26
+
27
+ ```bash
28
+ pnpm product board # print the board: Now / Next / Later, top ideas, triage inbox
29
+ pnpm product board --issue # write it to the repo's "Product board" issue (GITHUB_TOKEN)
30
+ pnpm product release --from <tag> # draft release notes for what reached beta or live since <tag>
31
+ pnpm product release --from <tag> --notify # list the idea issues it answers (a dry run)
32
+ pnpm product release --from <tag> --notify --yes # close them and comment on each (GITHUB_TOKEN)
33
+ ```
34
+
35
+ A release closes only ideas: feedback and bugs linked to a shipped feature stay open. A `--from`
36
+ ref that doesn't exist is an error, and more than 10 changed features need `--force`, so a wrong
37
+ ref can't close everything.
38
+
39
+ Reading a public repo needs no token, though an anonymous read is rate-limited. If the issues
40
+ can't be read, the board shows the catalog only. A write (`--issue`, `--notify --yes`) never runs
41
+ on a partial read.
42
+
43
+ The `product-board` workflow refreshes the board issue (labelled `product-board`, opened by the
44
+ workflow) every day and on demand. Scheduled and manual runs use the default branch, so it starts
45
+ once this is on main.
46
+
47
+ ## Core
48
+
49
+ ```ts
50
+ import { buildBoard, renderBoard, diffRelease, renderRelease, answeredBy } from "@marktiderman/genesis-product";
51
+ import { readCatalog, githubSignals, catalogAt } from "@marktiderman/genesis-product/node";
52
+
53
+ const board = buildBoard(readCatalog(), await githubSignals({ repo: "owner/repo" }).list());
54
+ const markdown = renderBoard(board, { date: "2026-10-25" });
55
+ ```
56
+
57
+ The core (`.`) has no React and no I/O. `/node` reads the catalog from a file or a git ref, maps
58
+ GitHub issues to signals, and writes the board issue and the "shipped" comments.
59
+
60
+ ## On this repo's releases
61
+
62
+ Release (`.github/workflows/release.yml`, its Release notes job) runs `release` around each
63
+ publish: draft notes as a comment on the open version PR, then, after a successful publish, a
64
+ `release/<YYYY-MM-DD>` tag whose GitHub release holds the notes (when a feature changed), and
65
+ `--notify --yes` to close the ideas it answered. The
66
+ diff starts from the previous `release/*` tag (the first time, the last version packages merge),
67
+ so the job checks out with `fetch-depth: 0`. See docs/RELEASING.md, "Release notes".
68
+
69
+ ## Telling people it shipped (an app's own database)
70
+
71
+ On a repo whose ideas are GitHub issues, `--notify --yes` is the notice: its "Shipped in release …"
72
+ comment tells the issue's author and everyone subscribed. Don't also call `notify()` there.
73
+
74
+ An app whose ideas live in its own database (people with logins or emails) tells them through
75
+ genesis-notifications. The app owns its registry and spreads in product's fragment, the way it
76
+ composes features: type `product.idea_shipped` in category `product_updates`, not critical and not
77
+ transactional, so preferences, quiet hours and the unsubscribe link apply. In the feed and by
78
+ email by default, with push offered as an opt-in.
79
+
80
+ ```ts
81
+ import { defineNotifications } from "@marktiderman/genesis-notifications";
82
+ import { notify, cancelNotification } from "@marktiderman/genesis-notifications/server";
83
+ import { productNotifications, notifyShipped, cancelShipped } from "@marktiderman/genesis-product/server";
84
+
85
+ export const notifications = defineNotifications({
86
+ categories: { ...productNotifications.categories, /* the app's own */ },
87
+ types: { ...productNotifications.types, /* the app's own */ },
88
+ });
89
+
90
+ // Once per shipped feature, to everyone who asked for or voted on it (deduplicated, 1,000 a call).
91
+ await notifyShipped((input) => notify(supabase, input, { registry: notifications }), {
92
+ release: "2026-10-26",
93
+ feature, // a CatalogFeature: its tagline (or summary) is the body
94
+ recipients: askers, // user ids, { userId }, or { email, name }
95
+ url: "/whats-new", // a path on the app; anything else throws (the notifier would drop it)
96
+ });
97
+
98
+ // The release was withdrawn: stop what hasn't gone out, and take it out of the feed (archive is on by default).
99
+ await cancelShipped((input) => cancelNotification(supabase, input), { release: "2026-10-26", featureId: feature.id });
100
+ ```
101
+
102
+ Run genesis-notifications' `syncNotificationTypes` after adding the fragment (on deploy), or
103
+ `notify` refuses the type. The key is `shipped:<release>:<feature>` (neither may contain `:`), so
104
+ a re-run sends nobody a second one, and the same feature shipped again under a new release name
105
+ notifies again. A cancel stops only what is still waiting: email goes as soon as the runner picks
106
+ it up, so most of it has usually gone. The sent rows stay, so re-publish a withdrawn release under
107
+ a new name; under the same one nobody is told again. Pass a `tenantId` (a uuid) to both calls, or
108
+ to neither. `/server` and the core (`.`) export
109
+ the same things: the registry is imported by the web and the phone too, and neither does I/O.
110
+ This package doesn't depend on genesis-notifications; the shapes are structural and tested against
111
+ it.
112
+
113
+ ## Native screens (`/native`)
114
+
115
+ The idea board, the Now / Next / Later roadmap and "what's new" for a React Native app, made of
116
+ genesis-ui-native only (`InboxPage`, `NativeSegmentedControl`, `NativeSheet`). React, React Native
117
+ and genesis-ui-native are optional peers; native modules are passed in, never imported.
118
+
119
+ ```tsx
120
+ import * as Haptics from "expo-haptics";
121
+ import AsyncStorage from "@react-native-async-storage/async-storage";
122
+ import NetInfo from "@react-native-community/netinfo";
123
+ import { IdeaBoardScreen, RoadmapScreen, createVoteQueue, storageVoteQueueStore } from "@marktiderman/genesis-product/native";
124
+
125
+ // Once, outside render: votes are kept on the phone until they reach the source.
126
+ const votes = createVoteQueue({ source, store: storageVoteQueueStore(AsyncStorage) });
127
+
128
+ <IdeaBoardScreen source={source} queue={votes} haptics={Haptics}
129
+ onReconnect={(run) => NetInfo.addEventListener((s) => { if (s.isConnected) run(); })} />
130
+ <RoadmapScreen source={source} haptics={Haptics} />
131
+ ```
132
+
133
+ - **Data** comes through a `ProductSource` (`ideas`, `vote`, `unvote`, `roadmap`, `whatsNew`). There
134
+ is no Supabase source yet; `memoryProductSource(seed)` is for tests and demos, and
135
+ `roadmapFromBoard(buildBoard(...))` turns the board into roadmap rows: only `public`, `customer` and
136
+ unset visibility, never `internal` or a `client:<name>` feature unless you pass that `{ client }`.
137
+ - **Idea board** (`useIdeaBoard` for InboxPage props, or `IdeaBoardScreen`): each row shows "N votes"
138
+ and a vote button at its end; swipe, long press and screen readers get the same vote. A vote shows
139
+ at once with a light haptic and goes through the vote queue: saved, sent on start, after each vote
140
+ and on reconnect, and toggling back before it is sent sends nothing. A refusal that retrying won't
141
+ fix (`VoteRefusedError`, or an HTTP 4xx other than 408 and 429) is dropped and rolled back, with an
142
+ error haptic, screen readers hear `copy.ideas.refused`, and `onRefused(ids)` lets the app show a
143
+ toast; anything else waits for the next flush. The vote button says which idea it is for and
144
+ whether it is cast (`accessibilityState.selected`), and a cast vote reads "You voted" on the row.
145
+ - **Roadmap** (`useRoadmap`, `RoadmapScreen`): a segmented control over the rows; a tap opens the
146
+ item in a sheet.
147
+ - **What's new** (`createProductWhatsNew`, `ProductWhatsNew`): once per app version plus over-the-air
148
+ update (`whatsNewKey`, e.g. `1.4.0+3f2a…` or `1.4.0+embedded`). A first install remembers the key
149
+ and shows nothing; a new key fetches its notes then, never from the bundle, and opens the sheet
150
+ when there are any. The last 20 keys seen are remembered, so falling back to the embedded code
151
+ after a failed update shows nothing again. An app that adds this to a build that didn't have it
152
+ starts like a first install: nothing shows until the next version or update. To hang it off genesis-native's updates block, turn the block's own sheet off
153
+ and render this one with the same modules:
154
+
155
+ ```tsx
156
+ createUpdates({ whatsNew: false, application: Application, updates: Updates, … });
157
+ const whatsNew = createProductWhatsNew({ source, storage: AsyncStorage,
158
+ key: whatsNewKey({ application: Application, updates: Updates }) });
159
+ <ProductWhatsNew store={whatsNew} /> // inside GenesisNativeApp
160
+ ```
161
+
162
+ The RN starter has a demo behind `productDemo` (off by default) in `starter.config.ts`.
163
+
164
+ ## Not yet
165
+
166
+ - Not on npm: an app installs it once the owner publishes it (see Status above).
167
+
168
+ - No database source and no insights captured from support reports. The board issue is markdown;
169
+ the native screens read an injected source (no web screens yet).
170
+ - Nothing calls `notifyShipped` yet: the askers come from a database source, which isn't built.
171
+ - Demand counts votes once per person per issue, but not yet once per person per feature.
@@ -0,0 +1,397 @@
1
+ // src/model.ts
2
+ var SIGNAL_KINDS = ["idea", "feedback", "bug"];
3
+ function memorySignals(signals) {
4
+ return { list: async () => [...signals] };
5
+ }
6
+
7
+ // src/board.ts
8
+ function demand(signals) {
9
+ return signals.filter((s) => s.state === "open").reduce((sum, s) => sum + (s.importance ?? 1) + s.votes, 0);
10
+ }
11
+ function byPriority(a, b) {
12
+ const building = Number(b.feature.status === "building") - Number(a.feature.status === "building");
13
+ return building || b.demand - a.demand || a.feature.name.localeCompare(b.feature.name);
14
+ }
15
+ function buildBoard(features, signals) {
16
+ const owner = /* @__PURE__ */ new Map();
17
+ for (const f of features) for (const name of [f.id, ...f.aliases ?? []]) owner.set(name, f);
18
+ const linked = /* @__PURE__ */ new Map();
19
+ const untriaged = [];
20
+ const unknown = [];
21
+ for (const s of signals) {
22
+ if (s.state !== "open") continue;
23
+ if (!s.featureId) untriaged.push(s);
24
+ else {
25
+ const f = owner.get(s.featureId);
26
+ if (!f) unknown.push(s);
27
+ else linked.set(f.id, [...linked.get(f.id) ?? [], s]);
28
+ }
29
+ }
30
+ const board = { now: [], next: [], later: [], ideas: [], untriaged, unknown };
31
+ for (const f of features) {
32
+ const own = linked.get(f.id) ?? [];
33
+ const item = { feature: f, signals: own, demand: demand(own) };
34
+ if (f.status === "idea") board.ideas.push(item);
35
+ else if (f.status === "planned" || f.status === "building") board[f.horizon ?? "now"].push(item);
36
+ }
37
+ for (const column of [board.now, board.next, board.later, board.ideas]) column.sort(byPriority);
38
+ const newest = (a, b) => b.createdAt.localeCompare(a.createdAt);
39
+ untriaged.sort(newest);
40
+ unknown.sort(newest);
41
+ return board;
42
+ }
43
+ var cell = (text) => text.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim();
44
+ var quoted = (text) => `\`${text.replace(/\s+/g, " ").trim().replace(/`/g, "'") || " "}\``;
45
+ var ref = (s) => s.url ? `[${s.id.replace(/^github/, "")}](${s.url})` : s.id;
46
+ function table(items) {
47
+ if (!items.length) return "_Nothing here._\n";
48
+ const rows = items.map(
49
+ (i) => `| ${cell(i.feature.name)} (\`${i.feature.id}\`) | ${i.feature.status} | ${cell(i.feature.claimedBy ?? i.feature.owner)} | ${i.demand} | ${i.signals.map(ref).join(" ")} |`
50
+ );
51
+ return ["| Feature | Status | Who | Demand | Asks |", "| --- | --- | --- | ---: | --- |", ...rows].join("\n") + "\n";
52
+ }
53
+ function list(signals) {
54
+ if (!signals.length) return "_Nothing to triage._\n";
55
+ return signals.map((s) => {
56
+ const named = s.featureId ?? s.suggestedFeatureId;
57
+ return `- ${ref(s)} ${s.kind}: ${quoted(s.title)}${named ? ` (${s.featureId ? "linked to" : "suggests"} \`${named}\`)` : ""}`;
58
+ }).join("\n") + "\n";
59
+ }
60
+ function renderBoard(board, options) {
61
+ const ideas = board.ideas.slice(0, options.ideas ?? 15);
62
+ return [
63
+ "# Product board",
64
+ "",
65
+ `Generated ${options.date} by \`genesis-product board\` from \`features.ts\` and the idea and feedback issues. Don't edit it: change \`features.ts\`, or open an issue. A \u{1F44D} on an issue is a vote.`,
66
+ "",
67
+ "Demand counts each open ask linked to a feature (its importance, 1 to 3) plus its \u{1F44D}.",
68
+ "",
69
+ `## Now (${board.now.length})`,
70
+ "",
71
+ table(board.now),
72
+ `## Next (${board.next.length})`,
73
+ "",
74
+ table(board.next),
75
+ `## Later (${board.later.length})`,
76
+ "",
77
+ table(board.later),
78
+ `## Ideas (top ${ideas.length} of ${board.ideas.length} by demand)`,
79
+ "",
80
+ table(ideas),
81
+ `## To triage (${board.untriaged.length})`,
82
+ "",
83
+ "Link each to a feature by adding the `feature:<id>` label. The id a sender suggests counts only once a triager adds the label.",
84
+ "",
85
+ list(board.untriaged),
86
+ ...board.unknown.length ? [`## Unknown feature ids (${board.unknown.length})`, "", list(board.unknown)] : []
87
+ ].join("\n");
88
+ }
89
+
90
+ // src/release.ts
91
+ function diffRelease(before, after) {
92
+ const was = new Map(before.map((f) => [f.id, f.status]));
93
+ const changes = [];
94
+ for (const f of after) {
95
+ if (f.visibility === "internal") continue;
96
+ const from = was.get(f.id);
97
+ if (from === f.status) continue;
98
+ if (f.status === "live") changes.push({ feature: f, change: "live", from });
99
+ else if (f.status === "beta" && from !== "live") changes.push({ feature: f, change: "beta", from });
100
+ }
101
+ return changes.sort((a, b) => a.change.localeCompare(b.change) || a.feature.name.localeCompare(b.feature.name));
102
+ }
103
+ function answeredBy(changes, signals) {
104
+ const shipped = new Set(changes.flatMap((c) => [c.feature.id, ...c.feature.aliases ?? []]));
105
+ return signals.filter((s) => s.kind === "idea" && s.state === "open" && s.featureId !== void 0 && shipped.has(s.featureId));
106
+ }
107
+ function renderRelease(changes, signals, options) {
108
+ const answered = answeredBy(changes, signals);
109
+ const section = (title, kind) => {
110
+ const own = changes.filter((c) => c.change === kind);
111
+ if (!own.length) return [];
112
+ return [
113
+ `## ${title}`,
114
+ "",
115
+ ...own.map((c) => {
116
+ const asks = answered.filter((s) => s.featureId === c.feature.id || c.feature.aliases?.includes(s.featureId));
117
+ const thanks = asks.length ? ` Asked for in ${asks.map((s) => s.url ? `[${s.id.replace(/^github/, "")}](${s.url})` : s.id).join(", ")}.` : "";
118
+ return `- **${c.feature.name}**: ${c.feature.tagline ?? c.feature.summary}${thanks}`;
119
+ }),
120
+ ""
121
+ ];
122
+ };
123
+ const body = [...section("Shipped", "live"), ...section("In beta", "beta")];
124
+ return [`# Release ${options.name}`, "", ...body.length ? body : ["_No feature reached beta or live in this range._", ""]].join("\n");
125
+ }
126
+
127
+ // src/app.ts
128
+ var VoteRefusedError = class extends Error {
129
+ permanent = true;
130
+ constructor(message = "This vote was refused.") {
131
+ super(message);
132
+ this.name = "VoteRefusedError";
133
+ }
134
+ };
135
+ function isPermanentVoteError(error) {
136
+ if (!error || typeof error !== "object") return false;
137
+ const e = error;
138
+ if (e.permanent === true) return true;
139
+ return typeof e.status === "number" && e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 429;
140
+ }
141
+ function roadmapFromBoard(board, options = {}) {
142
+ const visible = (v) => v === void 0 || v === "public" || v === "customer" || options.client !== void 0 && v === `client:${options.client}`;
143
+ return ["now", "next", "later"].flatMap(
144
+ (horizon) => board[horizon].filter((item) => visible(item.feature.visibility)).map((item) => ({
145
+ id: item.feature.id,
146
+ title: item.feature.name,
147
+ summary: item.feature.tagline ?? item.feature.summary,
148
+ horizon,
149
+ status: item.feature.status,
150
+ votes: item.demand
151
+ }))
152
+ );
153
+ }
154
+ function memoryProductSource(seed = {}) {
155
+ let ideas = (seed.ideas ?? []).map((i) => ({ ...i }));
156
+ const set = (ideaId, voted) => {
157
+ const idea = ideas.find((i) => i.id === ideaId);
158
+ if (!idea) throw new VoteRefusedError(`No idea ${ideaId}.`);
159
+ if (idea.voted === voted) return;
160
+ ideas = ideas.map((i) => i.id === ideaId ? { ...i, voted, votes: Math.max(0, i.votes + (voted ? 1 : -1)) } : i);
161
+ };
162
+ return {
163
+ ideas: async () => ideas.map((i) => ({ ...i })).sort((a, b) => b.votes - a.votes || a.title.localeCompare(b.title)),
164
+ vote: async (id) => set(id, true),
165
+ unvote: async (id) => set(id, false),
166
+ roadmap: async () => (seed.roadmap ?? []).map((r) => ({ ...r })),
167
+ whatsNew: async (key) => [...seed.whatsNew?.[key] ?? seed.whatsNew?.["*"] ?? []]
168
+ };
169
+ }
170
+ function memoryVoteQueueStore(initial = []) {
171
+ let saved = initial.map((v) => ({ ...v }));
172
+ return {
173
+ load: async () => saved.map((v) => ({ ...v })),
174
+ save: async (queue) => void (saved = queue.map((v) => ({ ...v })))
175
+ };
176
+ }
177
+ function storageVoteQueueStore(storage, key = "genesis:product:votes") {
178
+ return {
179
+ async load() {
180
+ const raw = JSON.parse(await storage.getItem(key) ?? "[]");
181
+ if (!Array.isArray(raw)) return [];
182
+ return raw.filter(
183
+ (v) => !!v && typeof v === "object" && typeof v.ideaId === "string" && typeof v.voted === "boolean" && typeof v.base === "boolean"
184
+ );
185
+ },
186
+ save: (queue) => storage.setItem(key, JSON.stringify(queue))
187
+ };
188
+ }
189
+ function createVoteQueue(options) {
190
+ const store = options.store ?? memoryVoteQueueStore();
191
+ const queue = /* @__PURE__ */ new Map();
192
+ const inFlight = /* @__PURE__ */ new Set();
193
+ const listeners = /* @__PURE__ */ new Set();
194
+ let loading = null;
195
+ let running = null;
196
+ let again = false;
197
+ const report = (error, ideaId) => {
198
+ try {
199
+ options.onError?.(error, ideaId);
200
+ } catch {
201
+ }
202
+ };
203
+ const changed = () => {
204
+ for (const l of [...listeners]) l();
205
+ };
206
+ const save = async () => {
207
+ try {
208
+ await store.save([...queue.values()].map((v) => ({ ...v })));
209
+ } catch (error) {
210
+ report(error);
211
+ }
212
+ };
213
+ const sendAll = async () => {
214
+ const result = { sent: [], refused: [], failed: [] };
215
+ for (const ideaId of [...queue.keys()]) {
216
+ const entry = queue.get(ideaId);
217
+ if (!entry) continue;
218
+ const sent = { ...entry };
219
+ inFlight.add(ideaId);
220
+ try {
221
+ await (sent.voted ? options.source.vote(sent.ideaId) : options.source.unvote(sent.ideaId));
222
+ const now = queue.get(sent.ideaId);
223
+ if (now) {
224
+ if (now.voted === sent.voted) queue.delete(sent.ideaId);
225
+ else now.base = sent.voted;
226
+ }
227
+ result.sent.push({ ideaId: sent.ideaId, voted: sent.voted });
228
+ } catch (error) {
229
+ report(error, sent.ideaId);
230
+ if (isPermanentVoteError(error)) {
231
+ const now = queue.get(sent.ideaId);
232
+ if (now && now.voted === sent.voted) queue.delete(sent.ideaId);
233
+ result.refused.push(sent.ideaId);
234
+ } else result.failed.push(sent.ideaId);
235
+ } finally {
236
+ inFlight.delete(sent.ideaId);
237
+ }
238
+ }
239
+ if (result.sent.length || result.refused.length) {
240
+ await save();
241
+ changed();
242
+ }
243
+ return result;
244
+ };
245
+ const self = {
246
+ load() {
247
+ loading ??= (async () => {
248
+ try {
249
+ const stored = await store.load();
250
+ for (const v of stored) if (!queue.has(v.ideaId)) queue.set(v.ideaId, { ...v });
251
+ if (queue.size !== stored.length) await save();
252
+ } catch (error) {
253
+ report(error);
254
+ }
255
+ changed();
256
+ })();
257
+ return loading;
258
+ },
259
+ pending: () => [...queue.values()].map((v) => ({ ...v })),
260
+ apply(ideas) {
261
+ return ideas.map((idea) => {
262
+ const q = queue.get(idea.id);
263
+ if (!q || q.voted === idea.voted) return idea;
264
+ return { ...idea, voted: q.voted, votes: Math.max(0, idea.votes + (q.voted ? 1 : -1)) };
265
+ });
266
+ },
267
+ async toggle(idea) {
268
+ await self.load();
269
+ const q = queue.get(idea.id);
270
+ const base = q?.base ?? idea.voted;
271
+ const voted = !(q?.voted ?? idea.voted);
272
+ if (voted === base && !inFlight.has(idea.id)) queue.delete(idea.id);
273
+ else queue.set(idea.id, { ideaId: idea.id, voted, base });
274
+ changed();
275
+ await save();
276
+ },
277
+ flush() {
278
+ if (running) {
279
+ again = true;
280
+ return running;
281
+ }
282
+ running = (async () => {
283
+ await self.load();
284
+ let result = await sendAll();
285
+ while (again) {
286
+ again = false;
287
+ const next = await sendAll();
288
+ result = { sent: [...result.sent, ...next.sent], refused: [...result.refused, ...next.refused], failed: next.failed };
289
+ }
290
+ return result;
291
+ })().finally(() => {
292
+ running = null;
293
+ });
294
+ return running;
295
+ },
296
+ subscribe(listener) {
297
+ listeners.add(listener);
298
+ return () => void listeners.delete(listener);
299
+ }
300
+ };
301
+ return self;
302
+ }
303
+ function whatsNewKey(input) {
304
+ const version = input.application?.nativeApplicationVersion;
305
+ if (!version) return null;
306
+ const u = input.updates;
307
+ const update = u && u.isEnabled && !u.isEmbeddedLaunch && u.updateId ? u.updateId : "embedded";
308
+ return `${version}+${update}`;
309
+ }
310
+ var MAX_SEEN_KEYS = 20;
311
+ function parseSeen(raw) {
312
+ if (raw === null) return [];
313
+ try {
314
+ const list2 = JSON.parse(raw);
315
+ if (Array.isArray(list2)) return list2.filter((k) => typeof k === "string").slice(-MAX_SEEN_KEYS);
316
+ } catch {
317
+ }
318
+ return [raw];
319
+ }
320
+ function createProductWhatsNew(options) {
321
+ const { source, key, storage, storageKey = "genesis:product:whats-new" } = options;
322
+ let state = { status: "loading", notes: [] };
323
+ const listeners = /* @__PURE__ */ new Set();
324
+ const set = (next) => {
325
+ state = next;
326
+ for (const l of [...listeners]) l();
327
+ };
328
+ const report = (error) => {
329
+ try {
330
+ options.onError?.(error);
331
+ } catch {
332
+ }
333
+ };
334
+ let seen = [];
335
+ const remember = () => {
336
+ if (!storage || !key) return;
337
+ seen = [...seen.filter((k) => k !== key), key].slice(-MAX_SEEN_KEYS);
338
+ const value = JSON.stringify(seen);
339
+ Promise.resolve().then(() => storage.setItem(storageKey, value)).catch(report);
340
+ };
341
+ let dismissed = false;
342
+ let fetches = 0;
343
+ const fetchNotes = async (rememberWhenEmpty) => {
344
+ if (!key) return set({ status: "hidden", notes: [] });
345
+ const mine = ++fetches;
346
+ set({ status: "fetching", notes: [] });
347
+ let notes = [];
348
+ try {
349
+ notes = await source.whatsNew(key);
350
+ if (!notes.length && rememberWhenEmpty) remember();
351
+ } catch (error) {
352
+ report(error);
353
+ }
354
+ if (mine !== fetches || state.status !== "fetching") return;
355
+ set(notes.length ? { status: "showing", notes } : { status: "hidden", notes: [] });
356
+ };
357
+ let loading = null;
358
+ return {
359
+ getState: () => state,
360
+ subscribe(listener) {
361
+ listeners.add(listener);
362
+ return () => void listeners.delete(listener);
363
+ },
364
+ load() {
365
+ loading ??= (async () => {
366
+ if (!storage || !key) return set({ status: "hidden", notes: [] });
367
+ let raw;
368
+ try {
369
+ raw = await storage.getItem(storageKey);
370
+ } catch (error) {
371
+ report(error);
372
+ return set({ status: "hidden", notes: [] });
373
+ }
374
+ seen = parseSeen(raw);
375
+ if (dismissed) return;
376
+ if (raw === null) {
377
+ remember();
378
+ return set({ status: "hidden", notes: [] });
379
+ }
380
+ if (seen.includes(key)) return set({ status: "hidden", notes: [] });
381
+ await fetchNotes(true);
382
+ })();
383
+ return loading;
384
+ },
385
+ open: () => fetchNotes(false),
386
+ dismiss() {
387
+ fetches++;
388
+ dismissed = true;
389
+ remember();
390
+ set({ status: "hidden", notes: [] });
391
+ }
392
+ };
393
+ }
394
+
395
+ export { SIGNAL_KINDS, VoteRefusedError, answeredBy, buildBoard, createProductWhatsNew, createVoteQueue, demand, diffRelease, isPermanentVoteError, memoryProductSource, memorySignals, memoryVoteQueueStore, renderBoard, renderRelease, roadmapFromBoard, storageVoteQueueStore, whatsNewKey };
396
+ //# sourceMappingURL=chunk-TJ5YBFJJ.js.map
397
+ //# sourceMappingURL=chunk-TJ5YBFJJ.js.map