@wix/himalaya-cli 0.1673.0 → 0.1675.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.
@@ -38,9 +38,14 @@ This is not a whole-command migration: other CAPTCHA failures retain their legac
38
38
  | `device_access_denied` | The owner pressed Deny on the approve page. Exit 1. |
39
39
  | `device_code_expired` | The issuer reported the code expired before approval. Exit 1. |
40
40
  | `device_login_failed` | Any other poll failure; `status` and `error` carry the issuer's answer. Exit 1. |
41
+ | `device_not_started` | `himi login --device --resume` found no pending device login for the target: none was started with `--no-wait`, or it already succeeded, was denied or expired. Start one with `himi login --device --no-wait`. Exit 1. |
42
+ | `device_superseded` | `himi login --device --resume` was approved, or still pending, for a grant that is no longer the stored one: a newer `--no-wait`, another login or `himi logout` replaced it meanwhile. Nothing is stored and the newer pending login is left as it is. Run `--resume` again for the current one. Exit 1. |
43
+ | `device_pending` | Not a failure. `himi login --device --resume` used up its `--timeout` before the owner approved. Printed on **stdout** with `ok: false`, `pending: true`, `userCode`, `verificationUri`, `verificationUriComplete`, `expiresAt`, `interval`, `retryAfterSec` and `resume` (the command to run again). **Exit 3.** |
41
44
 
42
45
  A `429` while polling is not a failure: the CLI backs off by the plane's `retryAfterSec` and keeps waiting.
43
46
 
47
+ `himi login --device --no-wait` prints `{ ok: true, pending: true, via: "device", target, verificationUri, verificationUriComplete, userCode, expiresAt, interval, resume }` on stdout and exits 0 without waiting; its start failures carry the codes above. `--resume` then polls with the same backoff and codes and exits 0 with the usual success envelope, 3 with `device_pending`, or 1. With `--resume`, `device_code_expired` also means the code's lifetime passed locally, and `device_code_expired` and `device_access_denied` remove the pending login. Usage errors (`--resume` with `--no-wait`, `--site` or `--redirect-uri`; `--timeout` without `--resume` or outside 1–600 seconds) exit 2.
48
+
44
49
  ### `himi login --device --site`: `site.error` codes
45
50
 
46
51
  With `--site <msid>`, the success envelope (exit 0) carries a `site` block. On success it is
@@ -148,6 +153,21 @@ This local planning command never claims or publishes. Every failure includes
148
153
  `ok: true` means the measured draft plus its reserve fits. It does not certify
149
154
  publication readiness or bound metadata not yet supplied to the final push.
150
155
 
156
+ Every measurement (success or `publish_body_too_large`) also carries `compressedUpload`, for
157
+ planning only:
158
+
159
+ | Field | Meaning |
160
+ | --- | --- |
161
+ | `transport` | `plain` or `gzip`: what `himi push` would send for this body. Gzip only between the two limits. |
162
+ | `wireBytes` | Bytes push would upload for this body. Equals `bodyBytes` when `transport` is `plain`. |
163
+ | `wireLimit` / `decodedLimit` | 8,388,608 bytes on the wire; 33,554,432 bytes decoded. |
164
+ | `planningWireBytes` | `wireBytes` plus the uncompressed reserve: an upper estimate. |
165
+ | `fitsIfEligible` | The planned body would fit both limits if the publisher credential is eligible. |
166
+ | `eligibility` | Always `not_evaluated`: the command reads no credential. |
167
+
168
+ The exit code and `withinMeasuredBudget` stay on the plain limit. Only `himi push` decides
169
+ whether a gzip upload is admitted, from the credential it actually uses.
170
+
151
171
  ## `himi one-app validate-payments` codes
152
172
 
153
173
  | Code | Meaning |
@@ -218,7 +238,8 @@ worker's bundle. These names are stable.
218
238
  | `control_token_expired` | The selected control token has expired. |
219
239
  | `app_source_contains_secrets` | Source archiving detected a possible credential. |
220
240
  | `app_source_too_large` | The encoded source archive exceeds its limit. |
221
- | `publish_body_too_large` | The complete publish request exceeds its limit. |
241
+ | `publish_body_too_large` | The complete publish request exceeds its limit. `bodyBytes` is the plain JSON and `limit` the 8,388,608-byte plain limit, as before. Added: `overageBytes`, `decodedLimit` (33,554,432), `decodedOverageBytes`; when push would gzip the body, `wireBytes`, `wireLimit` and `wireOverageBytes`; and `compressedUpload`, why the gzip upload was not admitted: `decoded_limit_exceeded`, `self_serve_credential`, `credential_unverified` (a static or opaque credential the CLI cannot read as a provisioned token) or `wire_limit_exceeded`. `appSourceBytes` and `breakdown` are unchanged. No credential or payload content is included. |
242
+ | `compressed_publish_unsupported` | The body went out gzipped and the publishing service would not take it compressed: it predates compressed publish bodies, or it treats the credential as self-serve. Carries `status`, `sentBytes`, and `planeCountedBytes` when the service named it. Nothing was written. |
222
243
  | `needs_vpn` | Full-push request to the publishing service could not complete (existing reachability code). This is not proof that VPN is the cause; read the target-aware error. |
223
244
  | `serve_unreachable` | A partial-push upload could not reach the publishing service. |
224
245
  | `no_serve_plane` | A loopback service answering a partial push is not a himi publishing service. |
@@ -1720,8 +1720,22 @@ metadata must fit within the remaining bytes. A changed slug changes both app fi
1720
1720
  the limit, unknown owner metadata cannot rescue the build. A passing size check is
1721
1721
  conditional on those remaining bytes; the final push still measures its exact envelope
1722
1722
  and runs every evidence gate. The push command has no size-only dry run; use the
1723
- measurement command for probes. Transport compression is not evidence that the current push guard accepts
1724
- an oversized JSON body.
1723
+ measurement command for probes.
1724
+
1725
+ The report's `compressedUpload` gives the gzip size push would send (`wireBytes`) and
1726
+ `fitsIfEligible`. It is a provisional, credential-free figure and **not** a pass:
1727
+
1728
+ - `himi push` sends a body over 8,388,608 bytes gzipped only for a provisioned control
1729
+ token it can read as not self-serve, within 33,554,432 bytes decoded and 8,388,608
1730
+ bytes on the wire.
1731
+ - The hosted migration worker publishes through its restricted draft broker with an
1732
+ opaque credential, and the broker forwards a plain body under a self-serve site token.
1733
+ On that path the plain **8,388,608-byte** limit applies. Plan for it: treat `bodyBytes`
1734
+ and `planningBytes`, not `wireBytes`, as the budget.
1735
+
1736
+ Measure early, then let the final push remeasure. The push measures the exact final
1737
+ envelope (slug, label, notes, attestation and migration metadata) before it claims or
1738
+ uploads anything, and again if the claim changes the slug.
1725
1739
 
1726
1740
  Init-generated `.agents/`, `.claude/` and `HIMALAYA.md` are already excluded by the
1727
1741
  source archive policy shown in `himi push --help`.
@@ -1886,7 +1900,8 @@ bytes. It is about base64(source archive + worker bundles + assets + icons) plus
1886
1900
  descriptor JSON, so a large app can exceed it: one 33-page migration measured
1887
1901
  11,259,935 bytes. Measure early, not at the end, with `himi publish-size` (see
1888
1902
  "Check the publish budget before final evidence"). `himi push` refuses an oversized body locally, before it sends anything,
1889
- with `publish_body_too_large`; its `breakdown`
1903
+ with `publish_body_too_large`. `compressedUpload` says why a gzip upload did not apply
1904
+ (`credential_unverified` on the hosted worker's broker), and `wireBytes` gives its size. Its `breakdown`
1890
1905
  gives each part's bytes (`appSource`, `screens`, `bundles`, `assets`, `icon`, `other`)
1891
1906
  and the largest entries by name. Reduce it in this order, and repeat affected
1892
1907
  validation after each step:
@@ -1355,8 +1355,14 @@ himi dist --app <app> --platform android --aab --wait --target bo
1355
1355
  `store_build_invalid`, `attempt_id_required`, `store_id_invalid`); its builds count per site in the
1356
1356
  self-serve tier, and `HIMI_DIST_SELFSERVE=0` closes them too. The caller reads
1357
1357
  (`GET /v1/admin/dist/<job>`), lists (`?app=`, each job with its `attemptId`) and cancels only the
1358
- jobs it started (`403 forbidden_cross_tenant` otherwise), and a settled job carries
1359
- `storeBuildResult`, the result the service used to be sent. A request with a control token is the
1358
+ jobs it started (`403 forbidden_cross_tenant` otherwise). A job carries `storeBuildResult`, the
1359
+ result the service used to be sent, only once nothing can change it, and then never changes it:
1360
+ Job Service has ended the job (it retries a failed attempt before it writes FAILURE, so a pool's
1361
+ FAILURE alone isn't final), a SUCCESS has the pool's own report with the file, an App Store build's
1362
+ TestFlight upload has settled, or the caller's cancel went through. Each read of a terminal job
1363
+ asks Job Service whether it ended it, until it has, and the read that writes the result logs
1364
+ `store_build.settled` (MOBPUB-1253). The caller learns the job ended from Job Service's own
1365
+ `wix.mre.v1.Job` domain events and then reads the job. A request with a control token is the
1360
1366
  path above, unchanged, and both stay: the Containers server picks one per site. MOBPUB-1241.
1361
1367
  - **A store build ships under the owner's App name and icon.** Both store builds above (a Containers
1362
1368
  app's `--aab` and its TestFlight build) need `appName` and `appIconUrl` on `POST /v1/admin/dist`
@@ -258,8 +258,16 @@ A bundle patch must repoint a screen at the new bytes (`push --only bundle:<name
258
258
  while screens still name the key they were built with — so bytes published alone land where
259
259
  nothing reads them.
260
260
 
261
- Caps are enforced at the door (413 `item_too_large`): a screen descriptor 256 KiB, a bundle 4 MiB,
262
- tokens and app-config 64 KiB each, and the whole body 8 MiB.
261
+ Caps are enforced at the door (413 `item_too_large`): a screen descriptor 256 KiB, a bundle, an
262
+ asset or the icon 4 MiB, tokens and app-config 64 KiB each, and the manifest 256 KiB as stored
263
+ (label 1 KiB, notes 16 KiB). The whole body is capped at 8 MiB (413 `payload_too_large`), except a
264
+ whole-release publish from an operator credential, which may be up to 32 MiB: `himi-serve` sends a
265
+ body over 8 MiB gzipped. A self-serve credential keeps the 8 MiB limit. A template's catalog view
266
+ (`source`, or `sourceGz` once inflated) may be up to 32 MiB only when an operator credential
267
+ publishes a reserved `himi-template-*` app; any other release that carries a catalog view keeps
268
+ 8 MiB (413 `item_too_large` for a plain view over it, `source_gz_inflated_too_large` for a
269
+ compressed one). `himi template publish` sends the view compressed, inside a gzip body, when that is the
270
+ only way the template fits.
263
271
 
264
272
  ## Consume (what a device / agent reads)
265
273
 
@@ -28969,8 +28969,8 @@
28969
28969
  {
28970
28970
  "name": "joinProgram",
28971
28971
  "kind": "function",
28972
- "jsdoc": "/**\n * Join as the signed-in member through Join Applications. Read the current\n * application first so an existing application is resumed without another create.\n * Approved paid applications prepare\n * SINGLE_PAYMENT and return the Wix Payments order as paymentPendingOptions.orderId.\n * mayPreparePayment rechecks the caller's checkout guard before creating that order.\n * beforeWrite lets a resumed caller revalidate its confirmed member after asynchronous reads.\n * @scope member\n */",
28973
- "decl": "export async function joinProgram(programId: string, options?: { mayPreparePayment?: () => boolean; beforeWrite?: () => Promise<void> }): Promise<WixJoinProgramResponse>;",
28972
+ "jsdoc": "/**\n * Join as the signed-in member through Join Applications. Read the current\n * application first so an existing application is resumed without another create.\n * Approved paid applications prepare\n * SINGLE_PAYMENT and return the Wix Payments order as paymentPendingOptions.orderId.\n * mayPreparePayment rechecks the caller's checkout guard before creating that order.\n * beforeWrite lets a resumed caller revalidate its confirmed member after asynchronous reads.\n * withdrawnParticipantId names a participation the caller freshly verified as withdrawn.\n * Only its matching historical application is replaced; another current participant is resumed.\n * @scope member\n */",
28973
+ "decl": "export async function joinProgram(programId: string, options?: { mayPreparePayment?: () => boolean; beforeWrite?: () => Promise<void>; withdrawnParticipantId?: string; resumeExistingParticipant?: boolean }): Promise<WixJoinProgramResponse>;",
28974
28974
  "scope": "member",
28975
28975
  "verificationChecked": true
28976
28976
  },
package/guides/skill.md CHANGED
@@ -185,6 +185,7 @@ and is also served at the public URL above. No repository access is required.
185
185
  - **Your platform already holds the owner's Wix session or token** (they connected their Wix account to it): that token **is** the owner. Any valid Wix token can manage that account's apps, publishing included. Pipe it in — `printf '%s' "$TOKEN" | himi login --wix --wix-token-stdin --target wix` — or set `WIX_TOKEN` and run `himi login --wix --target wix`. Never put a token on the command line (argv shows in `ps` and transcripts) or in a file you commit, and never print it.
186
186
  - **A server or CI job** with an account API key: `WIX_API_KEY` + `himi login --wix --target wix`.
187
187
  - **You hold no token at all:** run `himi login --device --target wix`. It prints a link and a short code. Show the owner both, ask them to open the link on any device where they are signed in to wix.com, check the code matches and approve, then wait: the command returns once they approve (up to 10 minutes). **If the app needs the owner's live site data, add `--site <msid>`** (and `--redirect-uri <uri>` when the app signs members in with its own redirect): the owner picks or confirms that site on the same approve page, and the result's `site` block carries the site's Headless client id (`site.clientId`, a public value — no Wix token reaches you). It is kept per site, so `himi site client list --site <msid>` answers with it afterwards. If `site` carries an `error` instead, the sign-in still worked: give the owner `site.fallbackUrl` to copy the client id from their dashboard.
188
+ - **If your environment can't run a command for about 10 minutes, or only shows a command's output once it exits,** don't run the waiting form. Run `himi login --device --no-wait --target wix` (with `--site` / `--redirect-uri` if you need them): it prints the link, the code and when the code expires, and exits at once. Show the owner the link and the code with whatever your environment uses to ask the user to act (a message, a "needs you" item), then run `himi login --device --resume --target wix` until it succeeds. Each resume waits at most 50 seconds (`--timeout <seconds>` changes that). Exit 3 with `code: "device_pending"` means the owner has not approved yet, so run it again; exit 0 means you are signed in. `device_code_expired`, `device_access_denied` or `device_not_started` mean start again with `--no-wait` and a new code.
188
189
  - **None of these:** stop and say exactly what is missing. Do not improvise another route to a himi token.
189
190
 
190
191
  This replaces only the sign-in. The approval gates above still apply to every side effect.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/himalaya-cli",
3
- "version": "0.1673.0",
3
+ "version": "0.1675.0",
4
4
  "type": "module",
5
5
  "description": "himi — the Himalaya authoring CLI. Build a Tier-5 content package on your own machine, push it to the production serve as a draft, preview it on web + Himi Player, and read worker logs back — the remote dev loop. Wraps @himalaya/serve-cli for transport.",
6
6
  "keywords": [
@@ -79,5 +79,5 @@
79
79
  "artifactId": "himalaya-cli"
80
80
  }
81
81
  },
82
- "falconPackageHash": "b49b090208e4ab091f45a960751972875090445b37a5d4203c79e429"
82
+ "falconPackageHash": "30a7effff0aeb33c17640f41975edfbd1c0aa870dd62faabbf2abe67"
83
83
  }
@@ -5,6 +5,12 @@ import type { WixJoinApplication, WixParticipant } from "@himalaya/wix-online-pr
5
5
  export type Standing = "none" | "joined" | "completed" | "finished" | "suspended" | "pending" | "approved" | "invited";
6
6
 
7
7
  export function standingOf(ended: boolean, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing {
8
+ // A withdrawn participant is history even if its old progress says completed.
9
+ // Only its matching admitted application is history too; newer requests remain visible.
10
+ if (["LEFT", "REMOVED", "AUTO_REMOVED"].includes((participant?.enrollmentStatus ?? "").toUpperCase())) {
11
+ if (participant?.id && application?.participantId === participant.id && application.status?.toUpperCase() === "APPROVED") application = undefined;
12
+ participant = undefined;
13
+ }
8
14
  if (participant) {
9
15
  const progress = (participant.progressStatus ?? "").toUpperCase();
10
16
  const enrollment = (participant.enrollmentStatus ?? "").toUpperCase();
@@ -14,7 +14,7 @@
14
14
  // ProgressBar and two filters. The shared query controller is reused as it is.
15
15
  import { defineService as register, navigate } from "@himalaya/state";
16
16
  import {
17
- queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories,
17
+ queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories, searchMemberParticipation, participationsByProgram,
18
18
  type WixProgram, type WixProgramFull, type WixParticipant, type WixJoinApplication, type WixProgramCategory,
19
19
  } from "@himalaya/wix-online-programs";
20
20
  import { getMyMember } from "@himalaya/wix-members";
@@ -356,19 +356,47 @@ async function participationsFor(scope: Scope, firstPage: boolean, required: boo
356
356
  }
357
357
 
358
358
  /** Only where an application can exist: an unjoined PRIVATE, SECRET (invite-only) or priced program, for a member. */
359
- async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; unknown: Set<string> }> {
359
+ async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; reconciled: Participations; unknown: Set<string> }> {
360
360
  const result = new Map<string, WixJoinApplication>();
361
+ const reconciled: Participations = new Map();
361
362
  // A failed read is not "no application": those programs make no join claim (see programContent).
362
363
  const unknown = new Set<string>();
363
- if (!scope.memberId) return { map: result, unknown };
364
+ if (!scope.memberId) return { map: result, reconciled, unknown };
364
365
  const candidates = programs.filter((p) => !participations.has(p.id) && (accessType(p) === "PRIVATE" || accessType(p) === "SECRET" || !!commercePriceOf(p)));
365
- const settled = await Promise.allSettled(candidates.map((p) => getCurrentJoinApplication(p.id)));
366
+ const settled = await Promise.allSettled(candidates.map(async (p) => {
367
+ const response = await getCurrentJoinApplication(p.id);
368
+ const application = response?.joinApplication;
369
+ // A successful empty envelope is the API's documented "never applied" answer.
370
+ // An application object that is present still needs its full identity below.
371
+ if (response && typeof response === "object" && !Array.isArray(response) && application === undefined) return;
372
+ if (typeof application?.id !== "string" || !application.id || application.programId !== p.id
373
+ || typeof application.status !== "string" || !application.status
374
+ || (application.memberId && application.memberId !== scope.memberId)) {
375
+ throw new Error("Current application identity is unknown");
376
+ }
377
+ result.set(p.id, application);
378
+ if (application.status.toUpperCase() !== "APPROVED" || !application.participantId) return;
379
+ // The batch roster omits withdrawals. Only admitted applications absent from it
380
+ // need this scoped read (at most one per candidate on this page), so the shared
381
+ // standing fold can distinguish current access from a matching historical join.
382
+ try {
383
+ const response = await searchMemberParticipation(p.id, scope.memberId);
384
+ const participant = Array.isArray(response.participants) ? response.participants[0] : undefined;
385
+ if (!participant?.id || participant.memberId !== scope.memberId || participant.programId !== p.id
386
+ || (!participationsByProgram([participant]).has(p.id) && participant.id !== application.participantId)) {
387
+ throw new Error("Current participation is unknown");
388
+ }
389
+ reconciled.set(p.id, participant);
390
+ } catch {
391
+ result.delete(p.id);
392
+ unknown.add(p.id);
393
+ }
394
+ }));
366
395
  settled.forEach((outcome, i) => {
367
396
  // 404 / NOT_FOUND is the endpoint's "this member never applied"; any other rejection is unknown.
368
397
  if (outcome.status === "rejected") { if (!isNotFoundError(outcome.reason)) unknown.add(candidates[i].id); }
369
- else if (outcome.value.joinApplication?.status) result.set(candidates[i].id, outcome.value.joinApplication);
370
398
  });
371
- return { map: result, unknown };
399
+ return { map: result, reconciled, unknown };
372
400
  }
373
401
 
374
402
  async function statsFor(programs: WixProgram[]): Promise<Map<string, number>> {
@@ -453,7 +481,8 @@ async function fetchPage(filter: string, cursor: string): Promise<CollectionPage
453
481
  return { items: [], nextCursor: "", metadata };
454
482
  }
455
483
  const [counts, applications] = await Promise.all([statsFor(programs), applicationsFor(programs, participations, scope)]);
456
- const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
484
+ if (!sameScope(scope, await resolveScope())) throw memberAccessChanged();
485
+ const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id) ?? applications.reconciled.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
457
486
  // A revalidating load publishes nothing until it settles, so page 1 records the scope its later pages
458
487
  // are read under here, not only from the published snapshot.
459
488
  if (!cursor) pageScope = scope;
@@ -212,6 +212,7 @@ async function fetchProgram(id: string): Promise<WixProgram | undefined> {
212
212
  /** Whether the existing commerce flow may start (before the join) and continue (before the Wix
213
213
  * payment): a price refresh can move the program onto a route this flow must not charge. */
214
214
  interface CommerceGuards {
215
+ withdrawnParticipantId?: string;
215
216
  assertMember(): Promise<void>;
216
217
  mayStart(): boolean;
217
218
  mayContinue(): boolean;
@@ -222,7 +223,7 @@ async function enrollmentMessage(id: string, name: string, guards: CommerceGuard
222
223
  if (!guards.mayStart()) return blocked();
223
224
  let preparationWithdrawn = false;
224
225
  try {
225
- const joined = await joinProgram(id, { beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
+ const joined = await joinProgram(id, { withdrawnParticipantId: guards.withdrawnParticipantId, resumeExistingParticipant: false, beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
227
  if (!guards.mayContinue()) preparationWithdrawn = true;
227
228
  return !preparationWithdrawn;
228
229
  } });
@@ -396,7 +397,7 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
396
397
  // Authority stays in the host until the last asynchronous prerequisite completes:
397
398
  // expiry, cancellation or an intervening account switch can still revoke it.
398
399
  const permit = await continuation("consume", id);
399
- if (permit?.confirmed && permit.account) await enroll(permit.account);
400
+ if (inputId() === id && permit?.confirmed && permit.account) await enroll(permit.account, id);
400
401
  }
401
402
  }
402
403
  void resumeCommerce();
@@ -479,7 +480,7 @@ async function readStanding(id: string, seq: number): Promise<StandingRead | und
479
480
  }
480
481
  sameCancelledStanding = cancelledRow && !participant;
481
482
  feedbackKnown ||= applicationKnown || !!participant;
482
- next = standingOf(programEnded, participant, application);
483
+ next = standingOf(programEnded, participant ?? scoped[0], application);
483
484
  if (next !== "none") owner = member;
484
485
  if (failedFeedback && (applicationKnown || participant)) {
485
486
  failedFeedbackInvalidated ||= !!participant || applicationRead?.id !== failedFeedback.id
@@ -618,8 +619,9 @@ async function priceProgram(): Promise<void> {
618
619
  void svc.pricingPublish();
619
620
  }
620
621
 
621
- async function enroll(afterAuthAccount = ""): Promise<undefined> {
622
- const id = inputId();
622
+ async function enroll(afterAuthAccount = "", targetId = inputId()): Promise<undefined> {
623
+ const id = targetId;
624
+ if (id !== inputId()) return undefined;
623
625
  const reference = programReference();
624
626
  const context = standingContext;
625
627
  if (!reference || enrollmentInFlight || !standingForInput()) return undefined;
@@ -641,6 +643,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
641
643
  if (afterAuthAccount && member.email !== afterAuthAccount) return undefined;
642
644
  if (!member.email) {
643
645
  const request = await continuation("begin", id);
646
+ if (!ownsStanding(context, await memberAccess(), id)) {
647
+ if (request?.token) await continuation("cancel", id, request.token);
648
+ return undefined;
649
+ }
644
650
  if (request?.supported !== true || !request.token) {
645
651
  actionMessage = copyParam("program.signInUpdateRequired", "Update the app to sign in and continue enrollment.");
646
652
  return undefined;
@@ -658,9 +664,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
658
664
  return undefined;
659
665
  }
660
666
  await assertMemberAccess(member);
661
- if (afterAuthAccount) {
662
- // Branded's initPhase refetches participation after NOW_LOGGED_IN, before
663
- // joining. A settled participant need not have a current Join Application.
667
+ let rejoinParticipantId = "";
668
+ {
669
+ // Every join verifies current participation, including after a route change. A
670
+ // display snapshot never authorizes resuming an old admitted application.
664
671
  const memberId = (await getMyMember()).member?.id;
665
672
  if (!memberId) throw new Error("Current member unavailable");
666
673
  const response = await searchMemberParticipation(id, memberId);
@@ -670,15 +677,19 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
670
677
  const participant = response.participants[0];
671
678
  if (participant) {
672
679
  if (participant.memberId !== memberId || participant.programId !== id) throw new Error("Participation identity changed");
673
- const status = (participant.enrollmentStatus ?? "").toUpperCase();
674
- const progress = (participant.progressStatus ?? "").toUpperCase();
675
- if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
676
- actionMessage = ["COMPLETED", "FAILED"].includes(progress)
677
- ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
678
- : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
679
- return undefined;
680
- }
681
- if (!["LEFT", "REMOVED"].includes(status)) {
680
+ // Withdrawal wins over old completion/failure progress, including AUTO_REMOVED.
681
+ if (!participationsByProgram([participant]).has(id)) {
682
+ if (!participant.id) throw new Error("Withdrawn participant identity unavailable");
683
+ rejoinParticipantId = participant.id;
684
+ } else {
685
+ const status = (participant.enrollmentStatus ?? "").toUpperCase();
686
+ const progress = (participant.progressStatus ?? "").toUpperCase();
687
+ if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
688
+ actionMessage = ["COMPLETED", "FAILED"].includes(progress)
689
+ ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
690
+ : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
691
+ return undefined;
692
+ }
682
693
  actionMessage = copyParam("program.participationUnavailable", "Your current participation cannot be enrolled again.");
683
694
  return undefined;
684
695
  }
@@ -687,8 +698,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
687
698
  // joinProgram refreshes the current Join Application before creating anything. Its
688
699
  // existing-participant/private/paid and pending-payment guards remain authoritative.
689
700
  const message = await enrollmentMessage(id, content.name, {
701
+ withdrawnParticipantId: rejoinParticipantId || undefined,
690
702
  assertMember: async () => {
691
703
  await assertMemberAccess(member);
704
+ if (id !== inputId()) throw new Error("Program changed");
692
705
  if (!connectivity().online) throw new Error(offlineWriteMessage);
693
706
  },
694
707
  mayStart: () => id === inputId() && pricing.checkoutGuard(reference).allowed,
@@ -5,6 +5,12 @@ import type { WixJoinApplication, WixParticipant } from "@himalaya/wix-online-pr
5
5
  export type Standing = "none" | "joined" | "completed" | "finished" | "suspended" | "pending" | "approved" | "invited";
6
6
 
7
7
  export function standingOf(ended: boolean, participant: WixParticipant | undefined, application: WixJoinApplication | undefined): Standing {
8
+ // A withdrawn participant is history even if its old progress says completed.
9
+ // Only its matching admitted application is history too; newer requests remain visible.
10
+ if (["LEFT", "REMOVED", "AUTO_REMOVED"].includes((participant?.enrollmentStatus ?? "").toUpperCase())) {
11
+ if (participant?.id && application?.participantId === participant.id && application.status?.toUpperCase() === "APPROVED") application = undefined;
12
+ participant = undefined;
13
+ }
8
14
  if (participant) {
9
15
  const progress = (participant.progressStatus ?? "").toUpperCase();
10
16
  const enrollment = (participant.enrollmentStatus ?? "").toUpperCase();
@@ -14,7 +14,7 @@
14
14
  // ProgressBar and two filters. The shared query controller is reused as it is.
15
15
  import { defineService as register, navigate } from "@himalaya/state";
16
16
  import {
17
- queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories,
17
+ queryPrograms, getParticipationStats, queryMemberParticipants, getCurrentJoinApplication, listProgramCategories, searchMemberParticipation, participationsByProgram,
18
18
  type WixProgram, type WixProgramFull, type WixParticipant, type WixJoinApplication, type WixProgramCategory,
19
19
  } from "@himalaya/wix-online-programs";
20
20
  import { getMyMember } from "@himalaya/wix-members";
@@ -356,19 +356,47 @@ async function participationsFor(scope: Scope, firstPage: boolean, required: boo
356
356
  }
357
357
 
358
358
  /** Only where an application can exist: an unjoined PRIVATE, SECRET (invite-only) or priced program, for a member. */
359
- async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; unknown: Set<string> }> {
359
+ async function applicationsFor(programs: WixProgram[], participations: Participations, scope: Scope): Promise<{ map: Map<string, WixJoinApplication>; reconciled: Participations; unknown: Set<string> }> {
360
360
  const result = new Map<string, WixJoinApplication>();
361
+ const reconciled: Participations = new Map();
361
362
  // A failed read is not "no application": those programs make no join claim (see programContent).
362
363
  const unknown = new Set<string>();
363
- if (!scope.memberId) return { map: result, unknown };
364
+ if (!scope.memberId) return { map: result, reconciled, unknown };
364
365
  const candidates = programs.filter((p) => !participations.has(p.id) && (accessType(p) === "PRIVATE" || accessType(p) === "SECRET" || !!commercePriceOf(p)));
365
- const settled = await Promise.allSettled(candidates.map((p) => getCurrentJoinApplication(p.id)));
366
+ const settled = await Promise.allSettled(candidates.map(async (p) => {
367
+ const response = await getCurrentJoinApplication(p.id);
368
+ const application = response?.joinApplication;
369
+ // A successful empty envelope is the API's documented "never applied" answer.
370
+ // An application object that is present still needs its full identity below.
371
+ if (response && typeof response === "object" && !Array.isArray(response) && application === undefined) return;
372
+ if (typeof application?.id !== "string" || !application.id || application.programId !== p.id
373
+ || typeof application.status !== "string" || !application.status
374
+ || (application.memberId && application.memberId !== scope.memberId)) {
375
+ throw new Error("Current application identity is unknown");
376
+ }
377
+ result.set(p.id, application);
378
+ if (application.status.toUpperCase() !== "APPROVED" || !application.participantId) return;
379
+ // The batch roster omits withdrawals. Only admitted applications absent from it
380
+ // need this scoped read (at most one per candidate on this page), so the shared
381
+ // standing fold can distinguish current access from a matching historical join.
382
+ try {
383
+ const response = await searchMemberParticipation(p.id, scope.memberId);
384
+ const participant = Array.isArray(response.participants) ? response.participants[0] : undefined;
385
+ if (!participant?.id || participant.memberId !== scope.memberId || participant.programId !== p.id
386
+ || (!participationsByProgram([participant]).has(p.id) && participant.id !== application.participantId)) {
387
+ throw new Error("Current participation is unknown");
388
+ }
389
+ reconciled.set(p.id, participant);
390
+ } catch {
391
+ result.delete(p.id);
392
+ unknown.add(p.id);
393
+ }
394
+ }));
366
395
  settled.forEach((outcome, i) => {
367
396
  // 404 / NOT_FOUND is the endpoint's "this member never applied"; any other rejection is unknown.
368
397
  if (outcome.status === "rejected") { if (!isNotFoundError(outcome.reason)) unknown.add(candidates[i].id); }
369
- else if (outcome.value.joinApplication?.status) result.set(candidates[i].id, outcome.value.joinApplication);
370
398
  });
371
- return { map: result, unknown };
399
+ return { map: result, reconciled, unknown };
372
400
  }
373
401
 
374
402
  async function statsFor(programs: WixProgram[]): Promise<Map<string, number>> {
@@ -453,7 +481,8 @@ async function fetchPage(filter: string, cursor: string): Promise<CollectionPage
453
481
  return { items: [], nextCursor: "", metadata };
454
482
  }
455
483
  const [counts, applications] = await Promise.all([statsFor(programs), applicationsFor(programs, participations, scope)]);
456
- const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
484
+ if (!sameScope(scope, await resolveScope())) throw memberAccessChanged();
485
+ const items = programs.map((p) => programContent({ program: p, participant: participations.get(p.id) ?? applications.reconciled.get(p.id), application: applications.map.get(p.id), applicationUnknown: applications.unknown.has(p.id), participationsUnknown: !participationsKnown, participants: counts.get(p.id), member: !!scope.memberId, now }));
457
486
  // A revalidating load publishes nothing until it settles, so page 1 records the scope its later pages
458
487
  // are read under here, not only from the published snapshot.
459
488
  if (!cursor) pageScope = scope;
@@ -212,6 +212,7 @@ async function fetchProgram(id: string): Promise<WixProgram | undefined> {
212
212
  /** Whether the existing commerce flow may start (before the join) and continue (before the Wix
213
213
  * payment): a price refresh can move the program onto a route this flow must not charge. */
214
214
  interface CommerceGuards {
215
+ withdrawnParticipantId?: string;
215
216
  assertMember(): Promise<void>;
216
217
  mayStart(): boolean;
217
218
  mayContinue(): boolean;
@@ -222,7 +223,7 @@ async function enrollmentMessage(id: string, name: string, guards: CommerceGuard
222
223
  if (!guards.mayStart()) return blocked();
223
224
  let preparationWithdrawn = false;
224
225
  try {
225
- const joined = await joinProgram(id, { beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
+ const joined = await joinProgram(id, { withdrawnParticipantId: guards.withdrawnParticipantId, resumeExistingParticipant: false, beforeWrite: guards.assertMember, mayPreparePayment: () => {
226
227
  if (!guards.mayContinue()) preparationWithdrawn = true;
227
228
  return !preparationWithdrawn;
228
229
  } });
@@ -396,7 +397,7 @@ async function load(state: State, arg?: unknown): Promise<undefined> {
396
397
  // Authority stays in the host until the last asynchronous prerequisite completes:
397
398
  // expiry, cancellation or an intervening account switch can still revoke it.
398
399
  const permit = await continuation("consume", id);
399
- if (permit?.confirmed && permit.account) await enroll(permit.account);
400
+ if (inputId() === id && permit?.confirmed && permit.account) await enroll(permit.account, id);
400
401
  }
401
402
  }
402
403
  void resumeCommerce();
@@ -479,7 +480,7 @@ async function readStanding(id: string, seq: number): Promise<StandingRead | und
479
480
  }
480
481
  sameCancelledStanding = cancelledRow && !participant;
481
482
  feedbackKnown ||= applicationKnown || !!participant;
482
- next = standingOf(programEnded, participant, application);
483
+ next = standingOf(programEnded, participant ?? scoped[0], application);
483
484
  if (next !== "none") owner = member;
484
485
  if (failedFeedback && (applicationKnown || participant)) {
485
486
  failedFeedbackInvalidated ||= !!participant || applicationRead?.id !== failedFeedback.id
@@ -618,8 +619,9 @@ async function priceProgram(): Promise<void> {
618
619
  void svc.pricingPublish();
619
620
  }
620
621
 
621
- async function enroll(afterAuthAccount = ""): Promise<undefined> {
622
- const id = inputId();
622
+ async function enroll(afterAuthAccount = "", targetId = inputId()): Promise<undefined> {
623
+ const id = targetId;
624
+ if (id !== inputId()) return undefined;
623
625
  const reference = programReference();
624
626
  const context = standingContext;
625
627
  if (!reference || enrollmentInFlight || !standingForInput()) return undefined;
@@ -641,6 +643,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
641
643
  if (afterAuthAccount && member.email !== afterAuthAccount) return undefined;
642
644
  if (!member.email) {
643
645
  const request = await continuation("begin", id);
646
+ if (!ownsStanding(context, await memberAccess(), id)) {
647
+ if (request?.token) await continuation("cancel", id, request.token);
648
+ return undefined;
649
+ }
644
650
  if (request?.supported !== true || !request.token) {
645
651
  actionMessage = copyParam("program.signInUpdateRequired", "Update the app to sign in and continue enrollment.");
646
652
  return undefined;
@@ -658,9 +664,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
658
664
  return undefined;
659
665
  }
660
666
  await assertMemberAccess(member);
661
- if (afterAuthAccount) {
662
- // Branded's initPhase refetches participation after NOW_LOGGED_IN, before
663
- // joining. A settled participant need not have a current Join Application.
667
+ let rejoinParticipantId = "";
668
+ {
669
+ // Every join verifies current participation, including after a route change. A
670
+ // display snapshot never authorizes resuming an old admitted application.
664
671
  const memberId = (await getMyMember()).member?.id;
665
672
  if (!memberId) throw new Error("Current member unavailable");
666
673
  const response = await searchMemberParticipation(id, memberId);
@@ -670,15 +677,19 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
670
677
  const participant = response.participants[0];
671
678
  if (participant) {
672
679
  if (participant.memberId !== memberId || participant.programId !== id) throw new Error("Participation identity changed");
673
- const status = (participant.enrollmentStatus ?? "").toUpperCase();
674
- const progress = (participant.progressStatus ?? "").toUpperCase();
675
- if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
676
- actionMessage = ["COMPLETED", "FAILED"].includes(progress)
677
- ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
678
- : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
679
- return undefined;
680
- }
681
- if (!["LEFT", "REMOVED"].includes(status)) {
680
+ // Withdrawal wins over old completion/failure progress, including AUTO_REMOVED.
681
+ if (!participationsByProgram([participant]).has(id)) {
682
+ if (!participant.id) throw new Error("Withdrawn participant identity unavailable");
683
+ rejoinParticipantId = participant.id;
684
+ } else {
685
+ const status = (participant.enrollmentStatus ?? "").toUpperCase();
686
+ const progress = (participant.progressStatus ?? "").toUpperCase();
687
+ if (status === "JOINED" || ["COMPLETED", "FAILED"].includes(progress)) {
688
+ actionMessage = ["COMPLETED", "FAILED"].includes(progress)
689
+ ? copyTemplate("program.participationRecordedMessage", "Your participation in {name} is already recorded.", { name: content.name })
690
+ : copyTemplate("program.joinedMessage", "You're enrolled in {name}.", { name: content.name });
691
+ return undefined;
692
+ }
682
693
  actionMessage = copyParam("program.participationUnavailable", "Your current participation cannot be enrolled again.");
683
694
  return undefined;
684
695
  }
@@ -687,8 +698,10 @@ async function enroll(afterAuthAccount = ""): Promise<undefined> {
687
698
  // joinProgram refreshes the current Join Application before creating anything. Its
688
699
  // existing-participant/private/paid and pending-payment guards remain authoritative.
689
700
  const message = await enrollmentMessage(id, content.name, {
701
+ withdrawnParticipantId: rejoinParticipantId || undefined,
690
702
  assertMember: async () => {
691
703
  await assertMemberAccess(member);
704
+ if (id !== inputId()) throw new Error("Program changed");
692
705
  if (!connectivity().online) throw new Error(offlineWriteMessage);
693
706
  },
694
707
  mayStart: () => id === inputId() && pricing.checkoutGuard(reference).allowed,