@aglyn/aglyn 1.11.0 → 1.13.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 (86) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/account-preferences.d.ts +15 -13
  3. package/src/lib/app-utils/account-preferences.js +20 -20
  4. package/src/lib/app-utils/account-preferences.js.map +1 -1
  5. package/src/lib/app-utils/crm.d.ts +3 -1
  6. package/src/lib/app-utils/crm.js +6 -3
  7. package/src/lib/app-utils/crm.js.map +1 -1
  8. package/src/lib/app-utils/docs-help-sections.generated.js +10 -4
  9. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  10. package/src/lib/app-utils/docs-help.generated.d.ts +2 -2
  11. package/src/lib/app-utils/docs-help.generated.js +8 -0
  12. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  13. package/src/lib/app-utils/docs-index.generated.js +117 -96
  14. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  15. package/src/lib/app-utils/host-permissions.d.ts +12 -0
  16. package/src/lib/app-utils/host-permissions.js +26 -1
  17. package/src/lib/app-utils/host-permissions.js.map +1 -1
  18. package/src/lib/app-utils/markdown-lite.js +8 -1
  19. package/src/lib/app-utils/markdown-lite.js.map +1 -1
  20. package/src/lib/app-utils/media-asset-facts.d.ts +2 -2
  21. package/src/lib/app-utils/media-asset-facts.js +4 -3
  22. package/src/lib/app-utils/media-asset-facts.js.map +1 -1
  23. package/src/lib/app-utils/media-cdn-scope.d.ts +19 -4
  24. package/src/lib/app-utils/media-cdn-scope.js +19 -5
  25. package/src/lib/app-utils/media-cdn-scope.js.map +1 -1
  26. package/src/lib/app-utils/media-ref.d.ts +10 -6
  27. package/src/lib/app-utils/media-ref.js +34 -8
  28. package/src/lib/app-utils/media-ref.js.map +1 -1
  29. package/src/lib/app-utils/org-permissions.d.ts +7 -0
  30. package/src/lib/app-utils/org-permissions.js +2 -0
  31. package/src/lib/app-utils/org-permissions.js.map +1 -1
  32. package/src/lib/app-utils/org-role-grants.d.ts +13 -0
  33. package/src/lib/app-utils/org-role-grants.js +9 -5
  34. package/src/lib/app-utils/org-role-grants.js.map +1 -1
  35. package/src/lib/app-utils/person-erasure.d.ts +8 -0
  36. package/src/lib/app-utils/person-erasure.js +6 -0
  37. package/src/lib/app-utils/person-erasure.js.map +1 -1
  38. package/src/lib/app-utils/scope-tokens.d.ts +132 -3
  39. package/src/lib/app-utils/scope-tokens.js +276 -3
  40. package/src/lib/app-utils/scope-tokens.js.map +1 -1
  41. package/src/lib/app-utils/site-placement.d.ts +56 -0
  42. package/src/lib/app-utils/site-placement.js +88 -0
  43. package/src/lib/app-utils/site-placement.js.map +1 -0
  44. package/src/lib/app-utils/site-preview.d.ts +6 -2
  45. package/src/lib/app-utils/site-preview.js +5 -3
  46. package/src/lib/app-utils/site-preview.js.map +1 -1
  47. package/src/lib/app-utils/site-unavailable.d.ts +4 -7
  48. package/src/lib/app-utils/site-unavailable.js +4 -8
  49. package/src/lib/app-utils/site-unavailable.js.map +1 -1
  50. package/src/lib/app-utils/transfer-launcher-context.d.ts +17 -1
  51. package/src/lib/app-utils/transfer-launcher-context.js.map +1 -1
  52. package/src/lib/data-transfer/access.d.ts +10 -18
  53. package/src/lib/data-transfer/access.js +21 -25
  54. package/src/lib/data-transfer/access.js.map +1 -1
  55. package/src/lib/data-transfer/resource.d.ts +13 -14
  56. package/src/lib/data-transfer/resource.js +9 -10
  57. package/src/lib/data-transfer/resource.js.map +1 -1
  58. package/src/lib/foundation/definitions/org-billing.types.js +2 -2
  59. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  60. package/src/lib/foundation/definitions/platform.types.d.ts +1 -1
  61. package/src/lib/foundation/definitions/platform.types.js.map +1 -1
  62. package/src/lib/foundation/definitions/write-deny-coverage.util.d.ts +1 -1
  63. package/src/lib/foundation/definitions/write-deny-coverage.util.js +1 -1
  64. package/src/lib/foundation/definitions/write-deny-coverage.util.js.map +1 -1
  65. package/src/lib/plugin-manager/first-party-plugins.generated.js +4 -5
  66. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  67. package/src/lib/plugin-manager/plugin-contact-capture.d.ts +18 -0
  68. package/src/lib/plugin-manager/plugin-contact-capture.js +26 -0
  69. package/src/lib/plugin-manager/plugin-contact-capture.js.map +1 -1
  70. package/src/lib/plugin-manager/plugin-entitlements.d.ts +12 -0
  71. package/src/lib/plugin-manager/plugin-entitlements.js +3 -1
  72. package/src/lib/plugin-manager/plugin-entitlements.js.map +1 -1
  73. package/src/lib/plugin-manager/plugin-person-erasure-notes.d.ts +61 -0
  74. package/src/lib/plugin-manager/plugin-person-erasure-notes.js +114 -0
  75. package/src/lib/plugin-manager/plugin-person-erasure-notes.js.map +1 -0
  76. package/src/lib/plugin-manager/plugin-scope-sharing.d.ts +52 -0
  77. package/src/lib/plugin-manager/plugin-scope-sharing.generated.d.ts +10 -0
  78. package/src/lib/plugin-manager/plugin-scope-sharing.generated.js +82 -0
  79. package/src/lib/plugin-manager/plugin-scope-sharing.generated.js.map +1 -0
  80. package/src/lib/plugin-manager/plugin-scope-sharing.js +85 -0
  81. package/src/lib/plugin-manager/plugin-scope-sharing.js.map +1 -0
  82. package/src/lib/plugin-manager/plugin-site-starters.d.ts +7 -0
  83. package/src/lib/plugin-manager/plugin-site-starters.js.map +1 -1
  84. package/src/lib/plugin-manager/plugin-transfer-resources.d.ts +56 -1
  85. package/src/lib/plugin-manager/plugin-transfer-resources.js +13 -0
  86. package/src/lib/plugin-manager/plugin-transfer-resources.js.map +1 -1
@@ -252,9 +252,9 @@ export declare function scopeCovers(target: readonly string[] | undefined | null
252
252
  * Rewrites an org media CDN path so it names the site using the asset
253
253
  * (AGL-1043/1045).
254
254
  *
255
- * `/api/media/cdn/org:{orgId}/{mediaId}` serves ORG-WIDE assets only. A
256
- * restricted asset has to be requested through the form that names the
257
- * site — `org:{orgId}:{hostId}` — because the CDN is unauthenticated and
255
+ * `/api/media/cdn/org:{orgId}/{mediaId}` serves org-wide assets, and assets
256
+ * shared with all sites except some. An asset shared with chosen sites has to
257
+ * be requested through the form that names the site — `org:{orgId}:{hostId}` — because the CDN is unauthenticated and
258
258
  * the URL is the only thing it can decide from.
259
259
  *
260
260
  * Returns the path untouched when there is nothing to do: an org-wide
@@ -289,3 +289,132 @@ export declare function heldByHost(doc: Readonly<Record<string, unknown>> | null
289
289
  * every read that predates sharing keeps exactly the rows it had.
290
290
  */
291
291
  export declare function seenOnlyThroughGrant(doc: Readonly<Record<string, unknown>> | null | undefined, hostId: string): boolean;
292
+ /** The `scopeMode` a document kept up by the sweep carries. */
293
+ export declare const SCOPE_MODE_ALL_EXCEPT: "allExcept";
294
+ /**
295
+ * What a sharing choice writes. A `null` marker field means the document must
296
+ * not carry it, which a server write spells as a field delete, so a document
297
+ * moved back to All sites or to chosen sites keeps no stale marker.
298
+ */
299
+ export interface ScopeSharingFields {
300
+ visibleTo: ScopeToken[];
301
+ scopeMode: typeof SCOPE_MODE_ALL_EXCEPT | null;
302
+ scopeExcept: ScopeToken[] | null;
303
+ }
304
+ /** How a document is shared, as a person would choose it. */
305
+ export type ScopeSharing = {
306
+ mode: 'all';
307
+ } | {
308
+ mode: 'selected';
309
+ hostIds: string[];
310
+ } | {
311
+ mode: 'allExcept';
312
+ exceptHostIds: string[];
313
+ includedHostIds: string[];
314
+ } | {
315
+ mode: 'none';
316
+ };
317
+ /** What a person picked: the input to {@link sharingFromChoice}. */
318
+ export type ScopeSharingChoice = {
319
+ mode: 'all';
320
+ } | {
321
+ mode: 'selected';
322
+ hostIds: readonly string[];
323
+ } | {
324
+ mode: 'allExcept';
325
+ exceptHostIds: readonly string[];
326
+ };
327
+ /**
328
+ * How a document is shared. Reads the marker only where it agrees with what
329
+ * readers enforce: a document carrying `'org'` is shared with all sites
330
+ * whatever a marker beside it says, and a damaged marker reads as the chosen
331
+ * sites `visibleTo` names.
332
+ */
333
+ export declare function scopeSharingOf(doc: Readonly<Record<string, unknown>> | null | undefined): ScopeSharing;
334
+ /**
335
+ * What a sharing choice writes, or why it cannot be written.
336
+ *
337
+ * `orgHostIds` is the workspace's sites as the writer read them. An exclusion
338
+ * naming a site that is no longer there is dropped, not refused: the person
339
+ * asked for that site to stay out, and it is out. Excluding nothing is
340
+ * refused, since that choice is All sites; excluding everything is refused,
341
+ * since it would hide the document from every site.
342
+ *
343
+ * An all-except list is not held to `MAX_SCOPE_HOSTS`, which limits what a
344
+ * QUERY can ask for and never what a document stores. A collection whose
345
+ * stored fields multiply by site passes its own `maxIncluded`. `keepHostIds`
346
+ * are sites that stay on the list even if excluded, such as a site that
347
+ * captured the person a record is about.
348
+ */
349
+ export declare function sharingFromChoice(choice: ScopeSharingChoice, orgHostIds: readonly string[], options?: {
350
+ maxIncluded?: number | null;
351
+ keepHostIds?: readonly string[];
352
+ }): {
353
+ fields: ScopeSharingFields;
354
+ problem: null;
355
+ } | {
356
+ fields: null;
357
+ problem: string;
358
+ };
359
+ /** What keeping an all-except document up to date came to. */
360
+ export interface AllExceptReconcile {
361
+ /**
362
+ * - `unmarked`: not an all-except document; nothing to do.
363
+ * - `current`: already says what it should.
364
+ * - `changed`: write `fields`.
365
+ * - `capped`: it should reach more sites than `maxIncluded`, so it stopped
366
+ * widening. Any `fields` only take away sites that are gone.
367
+ * - `invalid`: a marker this module cannot act on, or one beside `'org'`.
368
+ * Left alone and reported, because either guess moves who can see it.
369
+ */
370
+ status: 'unmarked' | 'current' | 'changed' | 'capped' | 'invalid';
371
+ fields: ScopeSharingFields | null;
372
+ }
373
+ /**
374
+ * What an all-except document should say, given the workspace's sites today.
375
+ *
376
+ * Pure and idempotent, which is what lets every trigger and the drift report
377
+ * ask the same question: a second run over its own answer says `current`.
378
+ *
379
+ * - A new site joins `visibleTo`, unless it is excluded.
380
+ * - A site that left the workspace leaves `visibleTo` and `scopeExcept`.
381
+ * - Once no exclusion is left the document IS All sites, so it collapses to
382
+ * `['org']` and drops its marker.
383
+ * - When every remaining site is excluded `visibleTo` is empty and the marker
384
+ * stays: no site sees it until a new one joins. The data is kept, which is
385
+ * why {@link isSiteOnlyScope} answers false for a marked document.
386
+ * - A site in `sharing.added` stays, since a person shared the document with
387
+ * it. So do `keepHostIds`. Both only while the site is in the workspace.
388
+ */
389
+ export declare function reconcileAllExcept(doc: Readonly<Record<string, unknown>> | null | undefined, orgHostIds: readonly string[], options?: {
390
+ maxIncluded?: number | null;
391
+ keepHostIds?: readonly string[];
392
+ }): AllExceptReconcile;
393
+ /**
394
+ * The sentence the console shows for how a document is shared:
395
+ * {@link describeScope}, plus the all-except wording. Sites are named only
396
+ * where `hostNames` has them, so a reader who cannot see a site's name is told
397
+ * how many sites, never an id.
398
+ */
399
+ export declare function describeSharing(doc: Readonly<Record<string, unknown>> | null | undefined, hostNames?: Readonly<Record<string, string>>): string;
400
+ /**
401
+ * Whether a document belongs to this site alone: what deciding to erase it
402
+ * with the site asks, so the three copies of that question share one answer.
403
+ *
404
+ * FALSE FOR ANY MARKED DOCUMENT, and that is the reason this exists. A site
405
+ * can be the last one an all-except document still reaches, with `visibleTo`
406
+ * naming it and nothing else, and the document is still the workspace's.
407
+ * Reading that as "this site's own" would erase the data with the site.
408
+ */
409
+ export declare function isSiteOnlyScope(doc: Readonly<Record<string, unknown>> | null | undefined, hostId: string): boolean;
410
+ /**
411
+ * {@link scopeCovers} for whole documents: whether `target` stays visible
412
+ * everywhere `source` is, which a cross-dataset reference needs.
413
+ *
414
+ * Today's tokens are not enough once either side is all-except, because the
415
+ * two lists move when a site is added: a chosen-sites target cannot cover an
416
+ * all-except source however it looks today (the next new site gets the source
417
+ * and not the target), and an all-except target covers an all-except source
418
+ * only when it leaves out no site the source includes.
419
+ */
420
+ export declare function sharingCovers(target: Readonly<Record<string, unknown>> | null | undefined, source: Readonly<Record<string, unknown>> | null | undefined): boolean;
@@ -313,9 +313,9 @@ export function isScopeToken(value) {
313
313
  * Rewrites an org media CDN path so it names the site using the asset
314
314
  * (AGL-1043/1045).
315
315
  *
316
- * `/api/media/cdn/org:{orgId}/{mediaId}` serves ORG-WIDE assets only. A
317
- * restricted asset has to be requested through the form that names the
318
- * site — `org:{orgId}:{hostId}` — because the CDN is unauthenticated and
316
+ * `/api/media/cdn/org:{orgId}/{mediaId}` serves org-wide assets, and assets
317
+ * shared with all sites except some. An asset shared with chosen sites has to
318
+ * be requested through the form that names the site — `org:{orgId}:{hostId}` — because the CDN is unauthenticated and
319
319
  * the URL is the only thing it can decide from.
320
320
  *
321
321
  * Returns the path untouched when there is nothing to do: an org-wide
@@ -402,5 +402,278 @@ export function isScopeToken(value) {
402
402
  */ export function seenOnlyThroughGrant(doc, hostId) {
403
403
  return grantedScopeTokens(doc).length > 0 && !heldByHost(doc, hostId);
404
404
  }
405
+ /*==========================================
406
+ * ALL SITES EXCEPT… (AGL-4047).
407
+ *
408
+ * A third way to share, beside "All sites" and "these sites". Neither
409
+ * enforcement layer can read an exclusion: Firestore has no "does not
410
+ * contain", `not-in` cannot sit beside `array-contains-any`, and a rule that
411
+ * refused on one would fail every scoped member's whole list. So what readers
412
+ * enforce stays what it has always been, a flat `visibleTo` of the sites that
413
+ * ARE included, and the choice that produced it sits beside it as a marker:
414
+ *
415
+ * visibleTo: ['host:b', 'host:c'] the only field a reader looks at
416
+ * scopeMode: 'allExcept' says new sites join
417
+ * scopeExcept: ['host:a'] the sites that stay out
418
+ *
419
+ * `visibleTo` is therefore a list that has to be kept up: a new site joins it
420
+ * and a deleted one leaves it. {@link reconcileAllExcept} is the one answer to
421
+ * what it should hold; the sweep (`scope-sharing-sweep.ts`) applies it.
422
+ *
423
+ * `visibleTo` always wins over the marker when they disagree, because it is
424
+ * what the database enforces. A helper describing a document some other way
425
+ * would be describing something no reader does.
426
+ *=========================================*/ /** The `scopeMode` a document kept up by the sweep carries. */ export const SCOPE_MODE_ALL_EXCEPT = 'allExcept';
427
+ const uniqueStrings = (values)=>[
428
+ ...new Set(values.filter((value)=>typeof value === 'string' && value))
429
+ ];
430
+ /**
431
+ * The excluded sites a marker names, or null when the marker is not one this
432
+ * module can act on: anything but an array of host tokens. Null is what keeps
433
+ * a damaged marker from being read as "except nothing", which means All sites.
434
+ */ function markerExceptHostIds(doc) {
435
+ if ((doc == null ? void 0 : doc['scopeMode']) !== SCOPE_MODE_ALL_EXCEPT) return null;
436
+ const except = doc['scopeExcept'];
437
+ if (!Array.isArray(except)) return null;
438
+ const ids = [];
439
+ for (const token of except){
440
+ const parsed = typeof token === 'string' ? parseScopeToken(token) : null;
441
+ if ((parsed == null ? void 0 : parsed.kind) !== 'host') return null;
442
+ ids.push(parsed.hostId);
443
+ }
444
+ return uniqueStrings(ids);
445
+ }
446
+ /**
447
+ * How a document is shared. Reads the marker only where it agrees with what
448
+ * readers enforce: a document carrying `'org'` is shared with all sites
449
+ * whatever a marker beside it says, and a damaged marker reads as the chosen
450
+ * sites `visibleTo` names.
451
+ */ export function scopeSharingOf(doc) {
452
+ const visibleTo = doc == null ? void 0 : doc['visibleTo'];
453
+ const tokens = Array.isArray(visibleTo) ? visibleTo.filter((token)=>typeof token === 'string') : null;
454
+ if (tokens == null ? void 0 : tokens.includes(ORG_SCOPE_TOKEN)) return {
455
+ mode: 'all'
456
+ };
457
+ const included = uniqueStrings(hostIdsFromScope(tokens != null ? tokens : []));
458
+ const except = tokens ? markerExceptHostIds(doc) : null;
459
+ if (except) {
460
+ return {
461
+ mode: 'allExcept',
462
+ exceptHostIds: except,
463
+ includedHostIds: included
464
+ };
465
+ }
466
+ return included.length ? {
467
+ mode: 'selected',
468
+ hostIds: included
469
+ } : {
470
+ mode: 'none'
471
+ };
472
+ }
473
+ /**
474
+ * What a sharing choice writes, or why it cannot be written.
475
+ *
476
+ * `orgHostIds` is the workspace's sites as the writer read them. An exclusion
477
+ * naming a site that is no longer there is dropped, not refused: the person
478
+ * asked for that site to stay out, and it is out. Excluding nothing is
479
+ * refused, since that choice is All sites; excluding everything is refused,
480
+ * since it would hide the document from every site.
481
+ *
482
+ * An all-except list is not held to `MAX_SCOPE_HOSTS`, which limits what a
483
+ * QUERY can ask for and never what a document stores. A collection whose
484
+ * stored fields multiply by site passes its own `maxIncluded`. `keepHostIds`
485
+ * are sites that stay on the list even if excluded, such as a site that
486
+ * captured the person a record is about.
487
+ */ export function sharingFromChoice(choice, orgHostIds, options = {}) {
488
+ if (choice.mode === 'all') {
489
+ return {
490
+ fields: {
491
+ visibleTo: [
492
+ ORG_SCOPE_TOKEN
493
+ ],
494
+ scopeMode: null,
495
+ scopeExcept: null
496
+ },
497
+ problem: null
498
+ };
499
+ }
500
+ if (choice.mode === 'selected') {
501
+ const stored = scopeToStore(choice.hostIds.map(hostScopeToken));
502
+ return stored.scope ? {
503
+ fields: {
504
+ visibleTo: stored.scope,
505
+ scopeMode: null,
506
+ scopeExcept: null
507
+ },
508
+ problem: null
509
+ } : {
510
+ fields: null,
511
+ problem: stored.problem
512
+ };
513
+ }
514
+ const org = uniqueStrings(orgHostIds);
515
+ const except = uniqueStrings(choice.exceptHostIds).filter((id)=>org.includes(id));
516
+ if (!except.length) {
517
+ return {
518
+ fields: null,
519
+ problem: 'Choose at least one site to leave out, or share with All sites.'
520
+ };
521
+ }
522
+ const included = includedHostIds(org, except, options.keepHostIds);
523
+ if (!included.length) {
524
+ return {
525
+ fields: null,
526
+ problem: 'Keep at least one site in, or choose the sites.'
527
+ };
528
+ }
529
+ if (options.maxIncluded != null && included.length > options.maxIncluded) {
530
+ return {
531
+ fields: null,
532
+ problem: `This can reach ${options.maxIncluded === 1 ? '1 site' : `${options.maxIncluded} sites`} at most. Leave out more sites, or choose the sites.`
533
+ };
534
+ }
535
+ return {
536
+ fields: {
537
+ visibleTo: included.map(hostScopeToken),
538
+ scopeMode: SCOPE_MODE_ALL_EXCEPT,
539
+ scopeExcept: except.map(hostScopeToken)
540
+ },
541
+ problem: null
542
+ };
543
+ }
544
+ /** The workspace's sites minus the excluded ones, plus the kept, sorted. */ function includedHostIds(org, except, keep) {
545
+ const out = new Set(except);
546
+ const kept = new Set(keep != null ? keep : []);
547
+ return org.filter((id)=>!out.has(id) || kept.has(id)).sort();
548
+ }
549
+ /**
550
+ * What an all-except document should say, given the workspace's sites today.
551
+ *
552
+ * Pure and idempotent, which is what lets every trigger and the drift report
553
+ * ask the same question: a second run over its own answer says `current`.
554
+ *
555
+ * - A new site joins `visibleTo`, unless it is excluded.
556
+ * - A site that left the workspace leaves `visibleTo` and `scopeExcept`.
557
+ * - Once no exclusion is left the document IS All sites, so it collapses to
558
+ * `['org']` and drops its marker.
559
+ * - When every remaining site is excluded `visibleTo` is empty and the marker
560
+ * stays: no site sees it until a new one joins. The data is kept, which is
561
+ * why {@link isSiteOnlyScope} answers false for a marked document.
562
+ * - A site in `sharing.added` stays, since a person shared the document with
563
+ * it. So do `keepHostIds`. Both only while the site is in the workspace.
564
+ */ export function reconcileAllExcept(doc, orgHostIds, options = {}) {
565
+ var _options_keepHostIds;
566
+ if ((doc == null ? void 0 : doc['scopeMode']) === undefined || doc['scopeMode'] === null) {
567
+ return {
568
+ status: 'unmarked',
569
+ fields: null
570
+ };
571
+ }
572
+ const storedExcept = markerExceptHostIds(doc);
573
+ const visibleTo = doc['visibleTo'];
574
+ if (!storedExcept || !Array.isArray(visibleTo) || visibleTo.includes(ORG_SCOPE_TOKEN)) {
575
+ return {
576
+ status: 'invalid',
577
+ fields: null
578
+ };
579
+ }
580
+ const org = uniqueStrings(orgHostIds);
581
+ const except = storedExcept.filter((id)=>org.includes(id));
582
+ if (!except.length) {
583
+ return {
584
+ status: 'changed',
585
+ fields: {
586
+ visibleTo: [
587
+ ORG_SCOPE_TOKEN
588
+ ],
589
+ scopeMode: null,
590
+ scopeExcept: null
591
+ }
592
+ };
593
+ }
594
+ const current = uniqueStrings(hostIdsFromScope(visibleTo));
595
+ const keep = [
596
+ ...(_options_keepHostIds = options.keepHostIds) != null ? _options_keepHostIds : [],
597
+ ...hostIdsFromScope(grantedScopeTokens(doc))
598
+ ];
599
+ let included = includedHostIds(org, except, keep);
600
+ let capped = false;
601
+ if (options.maxIncluded != null && included.length > options.maxIncluded && included.some((id)=>!current.includes(id))) {
602
+ capped = true;
603
+ included = current.filter((id)=>org.includes(id)).sort();
604
+ }
605
+ const same = included.length === current.length && included.every((id)=>current.includes(id)) && except.length === storedExcept.length;
606
+ const fields = same ? null : {
607
+ visibleTo: included.map(hostScopeToken),
608
+ scopeMode: SCOPE_MODE_ALL_EXCEPT,
609
+ scopeExcept: except.map(hostScopeToken)
610
+ };
611
+ if (capped) return {
612
+ status: 'capped',
613
+ fields
614
+ };
615
+ return fields ? {
616
+ status: 'changed',
617
+ fields
618
+ } : {
619
+ status: 'current',
620
+ fields: null
621
+ };
622
+ }
623
+ /**
624
+ * The sentence the console shows for how a document is shared:
625
+ * {@link describeScope}, plus the all-except wording. Sites are named only
626
+ * where `hostNames` has them, so a reader who cannot see a site's name is told
627
+ * how many sites, never an id.
628
+ */ export function describeSharing(doc, hostNames = {}) {
629
+ const sharing = scopeSharingOf(doc);
630
+ if (sharing.mode !== 'allExcept') {
631
+ return describeScope(doc == null ? void 0 : doc['visibleTo'], hostNames);
632
+ }
633
+ if (!sharing.includedHostIds.length) return 'No sites';
634
+ const names = sharing.exceptHostIds.map((id)=>hostNames[id]);
635
+ const count = names.length;
636
+ if (count === 1) return `All sites except ${names[0] || '1 site'}`;
637
+ if (count === 2 && names.every(Boolean)) {
638
+ return `All sites except ${names[0]} and ${names[1]}`;
639
+ }
640
+ return `All sites except ${count} sites`;
641
+ }
642
+ /**
643
+ * Whether a document belongs to this site alone: what deciding to erase it
644
+ * with the site asks, so the three copies of that question share one answer.
645
+ *
646
+ * FALSE FOR ANY MARKED DOCUMENT, and that is the reason this exists. A site
647
+ * can be the last one an all-except document still reaches, with `visibleTo`
648
+ * naming it and nothing else, and the document is still the workspace's.
649
+ * Reading that as "this site's own" would erase the data with the site.
650
+ */ export function isSiteOnlyScope(doc, hostId) {
651
+ if ((doc == null ? void 0 : doc['scopeMode']) !== undefined && (doc == null ? void 0 : doc['scopeMode']) !== null) return false;
652
+ const visibleTo = doc == null ? void 0 : doc['visibleTo'];
653
+ const token = hostScopeToken(hostId);
654
+ return Array.isArray(visibleTo) && visibleTo.length > 0 && visibleTo.every((entry)=>entry === token);
655
+ }
656
+ /**
657
+ * {@link scopeCovers} for whole documents: whether `target` stays visible
658
+ * everywhere `source` is, which a cross-dataset reference needs.
659
+ *
660
+ * Today's tokens are not enough once either side is all-except, because the
661
+ * two lists move when a site is added: a chosen-sites target cannot cover an
662
+ * all-except source however it looks today (the next new site gets the source
663
+ * and not the target), and an all-except target covers an all-except source
664
+ * only when it leaves out no site the source includes.
665
+ */ export function sharingCovers(target, source) {
666
+ const targetTokens = target == null ? void 0 : target['visibleTo'];
667
+ const sourceTokens = source == null ? void 0 : source['visibleTo'];
668
+ const targetSharing = scopeSharingOf(target);
669
+ const sourceSharing = scopeSharingOf(source);
670
+ if (sourceSharing.mode === 'allExcept') {
671
+ if (targetSharing.mode === 'all') return true;
672
+ if (targetSharing.mode !== 'allExcept') return false;
673
+ const sourceExcept = new Set(sourceSharing.exceptHostIds);
674
+ if (!targetSharing.exceptHostIds.every((id)=>sourceExcept.has(id))) return false;
675
+ }
676
+ return scopeCovers(targetTokens, sourceTokens);
677
+ }
405
678
 
406
679
  //# sourceMappingURL=scope-tokens.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/scope-tokens.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Scoped sharing (AGL-1037): org-owned resources — datasets, media assets,\n * media folders — carry a `visibleTo` array naming who may see them, so an\n * agency can keep an internal dataset off its client sites without forking\n * storage into a second host-scoped collection (see AGL-237, which moved\n * these the other way).\n *\n * The shape is dictated by what both enforcement layers can evaluate:\n * Firestore rules have no `.map()`, so the caller's read set is denormalized\n * onto their member doc (AGL-1038) and matched with `list.hasAny(list)`;\n * clients match the same field with `array-contains-any`. A flat array of\n * strings is the only shape both primitives accept — the friendlier\n * `{ kind, hostIds }` form is a presentation concern and lives in\n * `describeScope` below, never on the doc.\n */\n\nimport type { ScopeToken } from '../foundation'\n\n// The type itself lives in foundation (app-utils imports foundation, never\n// the reverse) so the media doc interfaces can reference it; re-exported\n// here so callers get the type and its helpers from one place.\nexport type { ScopeToken }\n\n/** Everyone in the owning org, and every host it owns. */\nexport const ORG_SCOPE_TOKEN = 'org' as const satisfies ScopeToken\n\nconst HOST_TOKEN_PREFIX = 'host:'\n\n/**\n * `array-contains-any` and `hasAny` both cap at 30 values. That caps a\n * selected-sites scope at 30 hosts, and a collaborator's read query at 29\n * hosts plus `'org'`. Wider than that is the `['org']` case.\n */\nexport const MAX_SCOPE_HOSTS = 30\n\n/** `host:{hostId}` — the token naming a single site. */\nexport function hostScopeToken(hostId: string): ScopeToken {\n return `${HOST_TOKEN_PREFIX}${hostId}`\n}\n\nexport function isScopeToken(value: unknown): value is ScopeToken {\n if (typeof value !== 'string') return false\n if (value === ORG_SCOPE_TOKEN) return true\n return (\n value.startsWith(HOST_TOKEN_PREFIX) &&\n value.length > HOST_TOKEN_PREFIX.length\n )\n}\n\n/** Reads a token back apart; null when it isn't one. */\nexport function parseScopeToken(\n token: string\n): { kind: 'org' } | { kind: 'host'; hostId: string } | null {\n if (token === ORG_SCOPE_TOKEN) return { kind: 'org' }\n if (!isScopeToken(token)) return null\n return { kind: 'host', hostId: token.slice(HOST_TOKEN_PREFIX.length) }\n}\n\n/** Every host id named by a scope, in order; `['org']` names none. */\nexport function hostIdsFromScope(\n visibleTo: readonly string[] | undefined\n): string[] {\n const ids: string[] = []\n for (const token of visibleTo ?? []) {\n const parsed = parseScopeToken(token)\n if (parsed?.kind === 'host') ids.push(parsed.hostId)\n }\n return ids\n}\n\n/**\n * The read set for one site: what a server read path or a scoped client\n * query passes to `array-contains-any`. `'org'` is included because an\n * org-wide resource is visible to every host in the org.\n */\nexport function scopeTokensForHost(hostId: string): ScopeToken[] {\n return [ORG_SCOPE_TOKEN, hostScopeToken(hostId)]\n}\n\n/**\n * Whether a host may see a resource.\n *\n * ## A missing `visibleTo` is visible to NOBODY\n *\n * It once read as org-wide, so that documents predating the scope backfill\n * stayed visible until it reached them. That default is the shape of failure\n * this codebase keeps paying for: **a read that cannot see a value answered\n * the same as a value that is absent.** \"This document was never scoped\" and\n * \"this document is shared with every site\" are different facts, and one\n * unscoped document under an agency account was one client's data on every\n * other client's site — silently, because the permissive answer is the one\n * nothing complains about.\n *\n * Both enforcement layers below this function already fail CLOSED on the\n * missing field: `array-contains-any` matches nothing on a document that\n * lacks the array, and the rules' `hasAny` is false for the same reason. So\n * the permissive default was never a policy either of them agreed with — it\n * was one TypeScript helper disagreeing with the database, which is what made\n * AGL-1466 invisible for three weeks.\n *\n * The migration is `tools/scripts/backfill-consent-host.mjs`, which stamps\n * `['org']` on the documents that should carry it. Until a document is\n * stamped it is hidden, and hiding is the recoverable direction.\n *\n * An **empty array** answers the same and always did.\n */\nexport function visibleToHost(\n visibleTo: readonly string[] | undefined | null,\n hostId: string\n): boolean {\n if (visibleTo == null) return false\n if (visibleTo.includes(ORG_SCOPE_TOKEN)) return true\n return visibleTo.includes(hostScopeToken(hostId))\n}\n\n/**\n * Whether a caller holding `scopeTokens` (AGL-1038) may see a resource.\n * The TypeScript twin of the rules' `visibleTo.hasAny(scopeTokens)`, for\n * the Admin-SDK paths that never evaluate rules at all.\n *\n * A missing `visibleTo` is visible to nobody, for the reason\n * {@link visibleToHost} gives — and here the twinning is the argument on its\n * own: `hasAny` over a missing field is false in the rules, so a helper that\n * answered `true` was not a twin of anything.\n */\nexport function visibleToTokens(\n visibleTo: readonly string[] | undefined | null,\n scopeTokens: readonly string[] | undefined | null\n): boolean {\n if (visibleTo == null) return false\n if (!scopeTokens?.length) return false\n return visibleTo.some((token) => scopeTokens.includes(token))\n}\n\n/**\n * The scope a document ACTUALLY carries — `null` when it carries none\n * (AGL-1466/AGL-1480).\n *\n * Every helper above this line answers \"may this be seen\", and answers it\n * the way both enforcement layers do: a missing `visibleTo` is seen by\n * nobody.\n *\n * An **editor** asks a different question — \"what did somebody choose\" —\n * and it still needs its own answer, because \"nobody chose\" and \"somebody\n * chose nobody\" are the same to an editor and different on the document.\n * Four call sites across two files each wrote their own\n *\n * ```ts\n * Array.isArray(doc.visibleTo) ? doc.visibleTo : [ORG_SCOPE_TOKEN]\n * ```\n *\n * and every one of them rendered \"All sites\" over a document no site could\n * see. That inversion is why AGL-1466 went three weeks unnoticed with the\n * folder tree missing from every host, and AGL-1480 is the third and fourth\n * copies of it turning up at the surface people use most.\n *\n * So: one function, the same lesson `newMediaFolderDoc` drew on the write\n * side. A caller that wants a display default may still `?? []` or\n * `?? [ORG_SCOPE_TOKEN]` — but it has to say so, in one visible place,\n * instead of a ternary that reads like a null check.\n *\n * An empty array answers `null` too. On the document the two differ, and\n * `newResourceScopeFields` refuses to WRITE one; to an editor they are the\n * same fact — nobody chose this — and both must offer the choice rather\n * than pre-fill an answer.\n *\n * Not normalized, deliberately. `normalizeVisibleTo` collapses for STORAGE;\n * doing it here would make an untouched editor differ from the document it\n * was seeded from, and the save gates compare exactly those two to decide\n * whether to write at all.\n */\nexport function storedScope(\n visibleTo: readonly string[] | undefined | null\n): string[] | null {\n return Array.isArray(visibleTo) && visibleTo.length ? [...visibleTo] : null\n}\n\n/**\n * Cleans a scope for storage: drops junk, dedupes, and collapses to\n * `['org']` when org-wide is present, since that already implies every\n * host. Returns null when the result is unusable — empty, or over\n * `MAX_SCOPE_HOSTS` — so the caller decides rather than this silently\n * dropping hosts (losing access) or widening to org (leaking).\n */\nexport function normalizeVisibleTo(\n input: readonly string[] | undefined | null\n): ScopeToken[] | null {\n const tokens = (input ?? []).filter(isScopeToken)\n if (!tokens.length) return null\n if (tokens.includes(ORG_SCOPE_TOKEN)) return [ORG_SCOPE_TOKEN]\n const unique = [...new Set(tokens)]\n if (unique.length > MAX_SCOPE_HOSTS) return null\n return unique\n}\n\n/**\n * The scope a save writes, or why the selection cannot be written.\n *\n * {@link normalizeVisibleTo} answers null for a selection it cannot store, and\n * a save has no safe substitute for that null: the org token shares the\n * resource with every site, and dropping tokens takes access from sites\n * somebody picked. So a caller refuses the save and shows `problem`.\n */\nexport function scopeToStore(\n input: readonly string[] | undefined | null\n): { scope: ScopeToken[]; problem: null } | { scope: null; problem: string } {\n const scope = normalizeVisibleTo(input)\n if (scope) return { scope, problem: null }\n return {\n scope: null,\n problem: (input ?? []).some(isScopeToken)\n ? `Choose ${MAX_SCOPE_HOSTS} sites or fewer, or share with All sites.`\n : 'Choose at least one site, or share with All sites.',\n }\n}\n\n/** A scope covering exactly the given hosts; null when unusable. */\nexport function scopeForHosts(\n hostIds: readonly string[]\n): ScopeToken[] | null {\n return normalizeVisibleTo(hostIds.map(hostScopeToken))\n}\n\n/**\n * Whether a scope is the org-wide one.\n *\n * An absent scope is NOT org-wide — see {@link visibleToHost}. That is the\n * whole correction: this predicate is what `describeScope` renders and what\n * `scopeCovers` and `narrowsScope` reason from, and while it answered `true`\n * for a document nothing could see, the console said \"All sites\" over it.\n */\nexport function isOrgWideScope(\n visibleTo: readonly string[] | undefined | null\n): boolean {\n return visibleTo != null && visibleTo.includes(ORG_SCOPE_TOKEN)\n}\n\n/**\n * Whether moving from `before` to `after` takes visibility away from any\n * host — the direction that can break a published page, and the one the\n * console confirms before saving (AGL-1044/AGL-1045).\n */\nexport function narrowsScope(\n before: readonly string[] | undefined | null,\n after: readonly string[] | undefined | null\n): boolean {\n if (isOrgWideScope(before)) return !isOrgWideScope(after)\n if (isOrgWideScope(after)) return false\n const kept = new Set(after ?? [])\n return (before ?? []).some((token) => !kept.has(token))\n}\n\n/**\n * The sentence the console shows. `hostNames` maps host id → display name;\n * ids missing from it fall back to the count wording, since a name we\n * can't resolve is worse than no name.\n */\nexport function describeScope(\n visibleTo: readonly string[] | undefined | null,\n hostNames: Readonly<Record<string, string>> = {}\n): string {\n if (isOrgWideScope(visibleTo)) return 'All sites'\n const hostIds = hostIdsFromScope(visibleTo ?? [])\n if (!hostIds.length) return 'No sites'\n if (hostIds.length === 1) {\n const name = hostNames[hostIds[0]]\n return name ? `${name} only` : '1 site'\n }\n return `${hostIds.length} sites`\n}\n\n/**\n * The scope a newly created resource starts with (AGL-1048).\n *\n * Honours the org's default — `defaultResourceScope` for a dataset,\n * `defaultMediaScopeOf(org)` for media, passed in the same option — but\n * only when a site is\n * actually in context: created from the org Media or Data page there is no\n * host to scope to, and inventing one would hide the resource from the\n * page that just created it.\n */\nexport function defaultScopeForNewResource(options: {\n defaultResourceScope?: 'org' | 'host'\n hostId?: string | null\n}): ScopeToken[] {\n return options.defaultResourceScope === 'host' && options.hostId\n ? [hostScopeToken(options.hostId)]\n : [ORG_SCOPE_TOKEN]\n}\n\n/**\n * The org's default sharing for new MEDIA — uploads and folders (AGL-3662).\n *\n * `defaultMediaScope` when the org has set it, otherwise\n * `defaultResourceScope`: until the two were split one field decided both,\n * so an org that chose \"only the site they were created in\" before the split\n * keeps that choice for media until it sets media on its own. Datasets read\n * `defaultResourceScope` directly.\n */\nexport function defaultMediaScopeOf(\n org:\n | {\n defaultMediaScope?: 'org' | 'host'\n defaultResourceScope?: 'org' | 'host'\n }\n | null\n | undefined,\n): 'org' | 'host' | undefined {\n return org?.defaultMediaScope ?? org?.defaultResourceScope\n}\n\n/**\n * The scope fields a document being CREATED in a scoped collection carries\n * (AGL-1478), as a spreadable object.\n *\n * The argument is REQUIRED and has no default, which is the whole point.\n * AGL-1466 was two call sites that each built a `mediaFolders` document\n * inline and each forgot `visibleTo`; `newMediaFolderDoc` fixed that one\n * collection by making the input mandatory, and this is the same guarantee\n * for the collections that have no document constructor of their own —\n * `datasets`, `media`, `contacts`, `contactSegments`. A creator that has\n * not decided cannot compile.\n *\n * Three inputs, three meanings:\n *\n * - **tokens** — stamp them.\n * - **`null`** — this collection is NOT scoped (a `hosts/{hostId}`\n * subcollection is private by construction), so store nothing. Saying it\n * out loud is what distinguishes \"not applicable\" from \"forgotten\".\n * - **`[]`** — throws. Unlike a missing field, a stored empty array is a\n * written \"visible to nobody\": the backfill leaves it alone by design and\n * no read path treats it as legacy, so it is permanent where absent is\n * repairable. Getting here means a caller computed a scope and came back\n * with nothing, which is worth a stack trace.\n */\nexport function newResourceScopeFields(\n visibleTo: readonly ScopeToken[] | null\n): { visibleTo?: ScopeToken[] } {\n if (visibleTo && !visibleTo.length) {\n throw new Error('A scoped resource cannot be created with an empty scope')\n }\n return visibleTo ? { visibleTo: [...visibleTo] } : {}\n}\n\n/**\n * Whether `target` is visible everywhere `source` is — the condition a\n * cross-dataset REFERENCE has to satisfy (AGL-1044).\n *\n * A reference field on dataset A pointing at dataset B is only resolvable\n * on the sites that can see BOTH. If A is shared with a site that cannot\n * see B, a page there resolves the reference to nothing: the row renders\n * with a blank where the linked value should be, and nothing says why. So\n * B's scope must COVER A's.\n *\n * Org-wide covers everything. A missing scope is seen by nobody and\n * therefore covers nothing, matching the rest of this module.\n */\nexport function scopeCovers(\n target: readonly string[] | undefined | null,\n source: readonly string[] | undefined | null,\n): boolean {\n if (isOrgWideScope(target)) return true\n // The target is restricted; an org-wide source reaches sites it cannot.\n if (isOrgWideScope(source)) return false\n const reach = new Set(target ?? [])\n return (source ?? []).every((token) => reach.has(token))\n}\n\n/**\n * Rewrites an org media CDN path so it names the site using the asset\n * (AGL-1043/1045).\n *\n * `/api/media/cdn/org:{orgId}/{mediaId}` serves ORG-WIDE assets only. A\n * restricted asset has to be requested through the form that names the\n * site — `org:{orgId}:{hostId}` — because the CDN is unauthenticated and\n * the URL is the only thing it can decide from.\n *\n * Returns the path untouched when there is nothing to do: an org-wide\n * asset, a host-library asset, no host context, or a path that is not an\n * org CDN URL. That keeps it safe to apply blindly at every pick site.\n */\nexport function hostQualifiedCdnPath(\n cdnPath: string | undefined | null,\n visibleTo: readonly string[] | undefined | null,\n hostId: string | undefined | null,\n): string | undefined {\n if (!cdnPath) return cdnPath ?? undefined\n if (!hostId || isOrgWideScope(visibleTo)) return cdnPath\n // `/api/media/cdn/{scope}/{mediaId}[/{hash}]`\n const marker = '/api/media/cdn/'\n const at = cdnPath.indexOf(marker)\n if (at === -1) return cdnPath\n const head = cdnPath.slice(0, at + marker.length)\n const rest = cdnPath.slice(at + marker.length)\n const [scopeSegment, ...tail] = rest.split('/')\n // Only the bare `org:{orgId}` form is rewritten; an already-qualified\n // scope is left alone rather than gaining a second host.\n if (!scopeSegment.startsWith('org:') || scopeSegment.includes(':', 4)) {\n return cdnPath\n }\n return [`${head}${scopeSegment}:${hostId}`, ...tail].join('/')\n}\n\n/*==========================================\n * SEEN, AND HELD (AGL-3336).\n *\n * `visibleTo` answers one question, \"who may see this\", because it is the\n * one field both enforcement layers can evaluate. A visibility GRANT — an\n * org manager sharing a record with another site, by hand or by a rule —\n * has to widen exactly that field, or the other site's lists, which are\n * real `array-contains-any` queries, could never return the record.\n *\n * But a site a record was shared with does not HOLD it. It did not capture\n * the person, it holds no consent from them, and letting go of the record\n * is not its decision. So a document that carries a grant records which of\n * its tokens the grant added, under `sharing.added`, and every question\n * about holding — who may delete it, whose audience it joins, which site's\n * list it enters — reads {@link heldScopeTokens} instead of `visibleTo`.\n *\n * A document without the field is held by everything that sees it, which\n * is every document written before grants existed.\n *=========================================*/\n\n/** The map a scoped document records its visibility grants under. */\nexport const SCOPE_GRANTS_FIELD = 'sharing'\n\n/** The tokens a grant ADDED to `visibleTo`: seen through, never held. */\nexport function grantedScopeTokens(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n): string[] {\n const grants = (doc ?? {})[SCOPE_GRANTS_FIELD]\n if (!grants || typeof grants !== 'object' || Array.isArray(grants)) return []\n const added = (grants as Record<string, unknown>)['added']\n return Array.isArray(added)\n ? added.filter((token): token is string => typeof token === 'string')\n : []\n}\n\n/**\n * The tokens that HOLD a document: `visibleTo` without the ones a grant\n * added. Missing `visibleTo` is held by nobody, as it is seen by nobody.\n *\n * A site that created the document (`hostId`) or captured the person on it\n * (`capturedByHostIds`) holds its token whatever the grants say: a record\n * shared with a site that then captures the person itself is that site's\n * own from the capture on, before anything re-evaluates the grants.\n */\nexport function heldScopeTokens(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n): string[] {\n const visibleTo = (doc ?? {})['visibleTo']\n if (!Array.isArray(visibleTo)) return []\n const granted = new Set(grantedScopeTokens(doc))\n const capturing = new Set<string>()\n const hostId = (doc ?? {})['hostId']\n if (typeof hostId === 'string' && hostId) capturing.add(hostScopeToken(hostId))\n const captured = (doc ?? {})['capturedByHostIds']\n if (Array.isArray(captured)) {\n for (const id of captured) if (typeof id === 'string' && id) capturing.add(hostScopeToken(id))\n }\n return visibleTo.filter(\n (token): token is string =>\n typeof token === 'string' && (!granted.has(token) || capturing.has(token)),\n )\n}\n\n/**\n * Whether a site HOLDS a document rather than only seeing it through a\n * grant. The question a marketing audience, a list rule, a sequence and a\n * holder count ask; {@link visibleToHost} is the one a reader asks.\n */\nexport function heldByHost(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n hostId: string,\n): boolean {\n return visibleToHost(heldScopeTokens(doc), hostId)\n}\n\n/**\n * Whether a site sees a document ONLY through a grant: it carries grants and\n * the site does not hold it. The filter an audience sweep applies to what\n * its scoped query returned — a document with no grants answers `false`, so\n * every read that predates sharing keeps exactly the rows it had.\n */\nexport function seenOnlyThroughGrant(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n hostId: string,\n): boolean {\n return grantedScopeTokens(doc).length > 0 && !heldByHost(doc, hostId)\n}\n"],"names":["ORG_SCOPE_TOKEN","HOST_TOKEN_PREFIX","MAX_SCOPE_HOSTS","hostScopeToken","hostId","isScopeToken","value","startsWith","length","parseScopeToken","token","kind","slice","hostIdsFromScope","visibleTo","ids","parsed","push","scopeTokensForHost","visibleToHost","includes","visibleToTokens","scopeTokens","some","storedScope","Array","isArray","normalizeVisibleTo","input","tokens","filter","unique","Set","scopeToStore","scope","problem","scopeForHosts","hostIds","map","isOrgWideScope","narrowsScope","before","after","kept","has","describeScope","hostNames","name","defaultScopeForNewResource","options","defaultResourceScope","defaultMediaScopeOf","org","defaultMediaScope","newResourceScopeFields","Error","scopeCovers","target","source","reach","every","hostQualifiedCdnPath","cdnPath","undefined","marker","at","indexOf","head","rest","scopeSegment","tail","split","join","SCOPE_GRANTS_FIELD","grantedScopeTokens","doc","grants","added","heldScopeTokens","granted","capturing","add","captured","id","heldByHost","seenOnlyThroughGrant"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GASD,wDAAwD,GACxD,OAAO,MAAMA,kBAAkB,MAAmC;AAElE,MAAMC,oBAAoB;AAE1B;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,GAAE;AAEjC,sDAAsD,GACtD,OAAO,SAASC,eAAeC,MAAc;IAC3C,OAAO,GAAGH,oBAAoBG,QAAQ;AACxC;AAEA,OAAO,SAASC,aAAaC,KAAc;IACzC,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,IAAIA,UAAUN,iBAAiB,OAAO;IACtC,OACEM,MAAMC,UAAU,CAACN,sBACjBK,MAAME,MAAM,GAAGP,kBAAkBO,MAAM;AAE3C;AAEA,sDAAsD,GACtD,OAAO,SAASC,gBACdC,KAAa;IAEb,IAAIA,UAAUV,iBAAiB,OAAO;QAAEW,MAAM;IAAM;IACpD,IAAI,CAACN,aAAaK,QAAQ,OAAO;IACjC,OAAO;QAAEC,MAAM;QAAQP,QAAQM,MAAME,KAAK,CAACX,kBAAkBO,MAAM;IAAE;AACvE;AAEA,oEAAoE,GACpE,OAAO,SAASK,iBACdC,SAAwC;IAExC,MAAMC,MAAgB,EAAE;IACxB,KAAK,MAAML,SAASI,oBAAAA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C,OAAO,CAACwD,WAAW;QAC3B,KAAK,MAAMC,MAAMD,SAAU,IAAI,OAAOC,OAAO,YAAYA,IAAIH,UAAUC,GAAG,CAAC9E,eAAegF;IAC5F;IACA,OAAOrE,UAAUgB,MAAM,CACrB,CAACpB,QACC,OAAOA,UAAU,YAAa,CAAA,CAACqE,QAAQnC,GAAG,CAAClC,UAAUsE,UAAUpC,GAAG,CAAClC,MAAK;AAE9E;AAEA;;;;CAIC,GACD,OAAO,SAAS0E,WACdT,GAAyD,EACzDvE,MAAc;IAEd,OAAOe,cAAc2D,gBAAgBH,MAAMvE;AAC7C;AAEA;;;;;CAKC,GACD,OAAO,SAASiF,qBACdV,GAAyD,EACzDvE,MAAc;IAEd,OAAOsE,mBAAmBC,KAAKnE,MAAM,GAAG,KAAK,CAAC4E,WAAWT,KAAKvE;AAChE"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/scope-tokens.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Scoped sharing (AGL-1037): org-owned resources — datasets, media assets,\n * media folders — carry a `visibleTo` array naming who may see them, so an\n * agency can keep an internal dataset off its client sites without forking\n * storage into a second host-scoped collection (see AGL-237, which moved\n * these the other way).\n *\n * The shape is dictated by what both enforcement layers can evaluate:\n * Firestore rules have no `.map()`, so the caller's read set is denormalized\n * onto their member doc (AGL-1038) and matched with `list.hasAny(list)`;\n * clients match the same field with `array-contains-any`. A flat array of\n * strings is the only shape both primitives accept — the friendlier\n * `{ kind, hostIds }` form is a presentation concern and lives in\n * `describeScope` below, never on the doc.\n */\n\nimport type { ScopeToken } from '../foundation'\n\n// The type itself lives in foundation (app-utils imports foundation, never\n// the reverse) so the media doc interfaces can reference it; re-exported\n// here so callers get the type and its helpers from one place.\nexport type { ScopeToken }\n\n/** Everyone in the owning org, and every host it owns. */\nexport const ORG_SCOPE_TOKEN = 'org' as const satisfies ScopeToken\n\nconst HOST_TOKEN_PREFIX = 'host:'\n\n/**\n * `array-contains-any` and `hasAny` both cap at 30 values. That caps a\n * selected-sites scope at 30 hosts, and a collaborator's read query at 29\n * hosts plus `'org'`. Wider than that is the `['org']` case.\n */\nexport const MAX_SCOPE_HOSTS = 30\n\n/** `host:{hostId}` — the token naming a single site. */\nexport function hostScopeToken(hostId: string): ScopeToken {\n return `${HOST_TOKEN_PREFIX}${hostId}`\n}\n\nexport function isScopeToken(value: unknown): value is ScopeToken {\n if (typeof value !== 'string') return false\n if (value === ORG_SCOPE_TOKEN) return true\n return (\n value.startsWith(HOST_TOKEN_PREFIX) &&\n value.length > HOST_TOKEN_PREFIX.length\n )\n}\n\n/** Reads a token back apart; null when it isn't one. */\nexport function parseScopeToken(\n token: string\n): { kind: 'org' } | { kind: 'host'; hostId: string } | null {\n if (token === ORG_SCOPE_TOKEN) return { kind: 'org' }\n if (!isScopeToken(token)) return null\n return { kind: 'host', hostId: token.slice(HOST_TOKEN_PREFIX.length) }\n}\n\n/** Every host id named by a scope, in order; `['org']` names none. */\nexport function hostIdsFromScope(\n visibleTo: readonly string[] | undefined\n): string[] {\n const ids: string[] = []\n for (const token of visibleTo ?? []) {\n const parsed = parseScopeToken(token)\n if (parsed?.kind === 'host') ids.push(parsed.hostId)\n }\n return ids\n}\n\n/**\n * The read set for one site: what a server read path or a scoped client\n * query passes to `array-contains-any`. `'org'` is included because an\n * org-wide resource is visible to every host in the org.\n */\nexport function scopeTokensForHost(hostId: string): ScopeToken[] {\n return [ORG_SCOPE_TOKEN, hostScopeToken(hostId)]\n}\n\n/**\n * Whether a host may see a resource.\n *\n * ## A missing `visibleTo` is visible to NOBODY\n *\n * It once read as org-wide, so that documents predating the scope backfill\n * stayed visible until it reached them. That default is the shape of failure\n * this codebase keeps paying for: **a read that cannot see a value answered\n * the same as a value that is absent.** \"This document was never scoped\" and\n * \"this document is shared with every site\" are different facts, and one\n * unscoped document under an agency account was one client's data on every\n * other client's site — silently, because the permissive answer is the one\n * nothing complains about.\n *\n * Both enforcement layers below this function already fail CLOSED on the\n * missing field: `array-contains-any` matches nothing on a document that\n * lacks the array, and the rules' `hasAny` is false for the same reason. So\n * the permissive default was never a policy either of them agreed with — it\n * was one TypeScript helper disagreeing with the database, which is what made\n * AGL-1466 invisible for three weeks.\n *\n * The migration is `tools/scripts/backfill-consent-host.mjs`, which stamps\n * `['org']` on the documents that should carry it. Until a document is\n * stamped it is hidden, and hiding is the recoverable direction.\n *\n * An **empty array** answers the same and always did.\n */\nexport function visibleToHost(\n visibleTo: readonly string[] | undefined | null,\n hostId: string\n): boolean {\n if (visibleTo == null) return false\n if (visibleTo.includes(ORG_SCOPE_TOKEN)) return true\n return visibleTo.includes(hostScopeToken(hostId))\n}\n\n/**\n * Whether a caller holding `scopeTokens` (AGL-1038) may see a resource.\n * The TypeScript twin of the rules' `visibleTo.hasAny(scopeTokens)`, for\n * the Admin-SDK paths that never evaluate rules at all.\n *\n * A missing `visibleTo` is visible to nobody, for the reason\n * {@link visibleToHost} gives — and here the twinning is the argument on its\n * own: `hasAny` over a missing field is false in the rules, so a helper that\n * answered `true` was not a twin of anything.\n */\nexport function visibleToTokens(\n visibleTo: readonly string[] | undefined | null,\n scopeTokens: readonly string[] | undefined | null\n): boolean {\n if (visibleTo == null) return false\n if (!scopeTokens?.length) return false\n return visibleTo.some((token) => scopeTokens.includes(token))\n}\n\n/**\n * The scope a document ACTUALLY carries — `null` when it carries none\n * (AGL-1466/AGL-1480).\n *\n * Every helper above this line answers \"may this be seen\", and answers it\n * the way both enforcement layers do: a missing `visibleTo` is seen by\n * nobody.\n *\n * An **editor** asks a different question — \"what did somebody choose\" —\n * and it still needs its own answer, because \"nobody chose\" and \"somebody\n * chose nobody\" are the same to an editor and different on the document.\n * Four call sites across two files each wrote their own\n *\n * ```ts\n * Array.isArray(doc.visibleTo) ? doc.visibleTo : [ORG_SCOPE_TOKEN]\n * ```\n *\n * and every one of them rendered \"All sites\" over a document no site could\n * see. That inversion is why AGL-1466 went three weeks unnoticed with the\n * folder tree missing from every host, and AGL-1480 is the third and fourth\n * copies of it turning up at the surface people use most.\n *\n * So: one function, the same lesson `newMediaFolderDoc` drew on the write\n * side. A caller that wants a display default may still `?? []` or\n * `?? [ORG_SCOPE_TOKEN]` — but it has to say so, in one visible place,\n * instead of a ternary that reads like a null check.\n *\n * An empty array answers `null` too. On the document the two differ, and\n * `newResourceScopeFields` refuses to WRITE one; to an editor they are the\n * same fact — nobody chose this — and both must offer the choice rather\n * than pre-fill an answer.\n *\n * Not normalized, deliberately. `normalizeVisibleTo` collapses for STORAGE;\n * doing it here would make an untouched editor differ from the document it\n * was seeded from, and the save gates compare exactly those two to decide\n * whether to write at all.\n */\nexport function storedScope(\n visibleTo: readonly string[] | undefined | null\n): string[] | null {\n return Array.isArray(visibleTo) && visibleTo.length ? [...visibleTo] : null\n}\n\n/**\n * Cleans a scope for storage: drops junk, dedupes, and collapses to\n * `['org']` when org-wide is present, since that already implies every\n * host. Returns null when the result is unusable — empty, or over\n * `MAX_SCOPE_HOSTS` — so the caller decides rather than this silently\n * dropping hosts (losing access) or widening to org (leaking).\n */\nexport function normalizeVisibleTo(\n input: readonly string[] | undefined | null\n): ScopeToken[] | null {\n const tokens = (input ?? []).filter(isScopeToken)\n if (!tokens.length) return null\n if (tokens.includes(ORG_SCOPE_TOKEN)) return [ORG_SCOPE_TOKEN]\n const unique = [...new Set(tokens)]\n if (unique.length > MAX_SCOPE_HOSTS) return null\n return unique\n}\n\n/**\n * The scope a save writes, or why the selection cannot be written.\n *\n * {@link normalizeVisibleTo} answers null for a selection it cannot store, and\n * a save has no safe substitute for that null: the org token shares the\n * resource with every site, and dropping tokens takes access from sites\n * somebody picked. So a caller refuses the save and shows `problem`.\n */\nexport function scopeToStore(\n input: readonly string[] | undefined | null\n): { scope: ScopeToken[]; problem: null } | { scope: null; problem: string } {\n const scope = normalizeVisibleTo(input)\n if (scope) return { scope, problem: null }\n return {\n scope: null,\n problem: (input ?? []).some(isScopeToken)\n ? `Choose ${MAX_SCOPE_HOSTS} sites or fewer, or share with All sites.`\n : 'Choose at least one site, or share with All sites.',\n }\n}\n\n/** A scope covering exactly the given hosts; null when unusable. */\nexport function scopeForHosts(\n hostIds: readonly string[]\n): ScopeToken[] | null {\n return normalizeVisibleTo(hostIds.map(hostScopeToken))\n}\n\n/**\n * Whether a scope is the org-wide one.\n *\n * An absent scope is NOT org-wide — see {@link visibleToHost}. That is the\n * whole correction: this predicate is what `describeScope` renders and what\n * `scopeCovers` and `narrowsScope` reason from, and while it answered `true`\n * for a document nothing could see, the console said \"All sites\" over it.\n */\nexport function isOrgWideScope(\n visibleTo: readonly string[] | undefined | null\n): boolean {\n return visibleTo != null && visibleTo.includes(ORG_SCOPE_TOKEN)\n}\n\n/**\n * Whether moving from `before` to `after` takes visibility away from any\n * host — the direction that can break a published page, and the one the\n * console confirms before saving (AGL-1044/AGL-1045).\n */\nexport function narrowsScope(\n before: readonly string[] | undefined | null,\n after: readonly string[] | undefined | null\n): boolean {\n if (isOrgWideScope(before)) return !isOrgWideScope(after)\n if (isOrgWideScope(after)) return false\n const kept = new Set(after ?? [])\n return (before ?? []).some((token) => !kept.has(token))\n}\n\n/**\n * The sentence the console shows. `hostNames` maps host id → display name;\n * ids missing from it fall back to the count wording, since a name we\n * can't resolve is worse than no name.\n */\nexport function describeScope(\n visibleTo: readonly string[] | undefined | null,\n hostNames: Readonly<Record<string, string>> = {}\n): string {\n if (isOrgWideScope(visibleTo)) return 'All sites'\n const hostIds = hostIdsFromScope(visibleTo ?? [])\n if (!hostIds.length) return 'No sites'\n if (hostIds.length === 1) {\n const name = hostNames[hostIds[0]]\n return name ? `${name} only` : '1 site'\n }\n return `${hostIds.length} sites`\n}\n\n/**\n * The scope a newly created resource starts with (AGL-1048).\n *\n * Honours the org's default — `defaultResourceScope` for a dataset,\n * `defaultMediaScopeOf(org)` for media, passed in the same option — but\n * only when a site is\n * actually in context: created from the org Media or Data page there is no\n * host to scope to, and inventing one would hide the resource from the\n * page that just created it.\n */\nexport function defaultScopeForNewResource(options: {\n defaultResourceScope?: 'org' | 'host'\n hostId?: string | null\n}): ScopeToken[] {\n return options.defaultResourceScope === 'host' && options.hostId\n ? [hostScopeToken(options.hostId)]\n : [ORG_SCOPE_TOKEN]\n}\n\n/**\n * The org's default sharing for new MEDIA — uploads and folders (AGL-3662).\n *\n * `defaultMediaScope` when the org has set it, otherwise\n * `defaultResourceScope`: until the two were split one field decided both,\n * so an org that chose \"only the site they were created in\" before the split\n * keeps that choice for media until it sets media on its own. Datasets read\n * `defaultResourceScope` directly.\n */\nexport function defaultMediaScopeOf(\n org:\n | {\n defaultMediaScope?: 'org' | 'host'\n defaultResourceScope?: 'org' | 'host'\n }\n | null\n | undefined,\n): 'org' | 'host' | undefined {\n return org?.defaultMediaScope ?? org?.defaultResourceScope\n}\n\n/**\n * The scope fields a document being CREATED in a scoped collection carries\n * (AGL-1478), as a spreadable object.\n *\n * The argument is REQUIRED and has no default, which is the whole point.\n * AGL-1466 was two call sites that each built a `mediaFolders` document\n * inline and each forgot `visibleTo`; `newMediaFolderDoc` fixed that one\n * collection by making the input mandatory, and this is the same guarantee\n * for the collections that have no document constructor of their own —\n * `datasets`, `media`, `contacts`, `contactSegments`. A creator that has\n * not decided cannot compile.\n *\n * Three inputs, three meanings:\n *\n * - **tokens** — stamp them.\n * - **`null`** — this collection is NOT scoped (a `hosts/{hostId}`\n * subcollection is private by construction), so store nothing. Saying it\n * out loud is what distinguishes \"not applicable\" from \"forgotten\".\n * - **`[]`** — throws. Unlike a missing field, a stored empty array is a\n * written \"visible to nobody\": the backfill leaves it alone by design and\n * no read path treats it as legacy, so it is permanent where absent is\n * repairable. Getting here means a caller computed a scope and came back\n * with nothing, which is worth a stack trace.\n */\nexport function newResourceScopeFields(\n visibleTo: readonly ScopeToken[] | null\n): { visibleTo?: ScopeToken[] } {\n if (visibleTo && !visibleTo.length) {\n throw new Error('A scoped resource cannot be created with an empty scope')\n }\n return visibleTo ? { visibleTo: [...visibleTo] } : {}\n}\n\n/**\n * Whether `target` is visible everywhere `source` is — the condition a\n * cross-dataset REFERENCE has to satisfy (AGL-1044).\n *\n * A reference field on dataset A pointing at dataset B is only resolvable\n * on the sites that can see BOTH. If A is shared with a site that cannot\n * see B, a page there resolves the reference to nothing: the row renders\n * with a blank where the linked value should be, and nothing says why. So\n * B's scope must COVER A's.\n *\n * Org-wide covers everything. A missing scope is seen by nobody and\n * therefore covers nothing, matching the rest of this module.\n */\nexport function scopeCovers(\n target: readonly string[] | undefined | null,\n source: readonly string[] | undefined | null,\n): boolean {\n if (isOrgWideScope(target)) return true\n // The target is restricted; an org-wide source reaches sites it cannot.\n if (isOrgWideScope(source)) return false\n const reach = new Set(target ?? [])\n return (source ?? []).every((token) => reach.has(token))\n}\n\n/**\n * Rewrites an org media CDN path so it names the site using the asset\n * (AGL-1043/1045).\n *\n * `/api/media/cdn/org:{orgId}/{mediaId}` serves org-wide assets, and assets\n * shared with all sites except some. An asset shared with chosen sites has to\n * be requested through the form that names the site — `org:{orgId}:{hostId}` — because the CDN is unauthenticated and\n * the URL is the only thing it can decide from.\n *\n * Returns the path untouched when there is nothing to do: an org-wide\n * asset, a host-library asset, no host context, or a path that is not an\n * org CDN URL. That keeps it safe to apply blindly at every pick site.\n */\nexport function hostQualifiedCdnPath(\n cdnPath: string | undefined | null,\n visibleTo: readonly string[] | undefined | null,\n hostId: string | undefined | null,\n): string | undefined {\n if (!cdnPath) return cdnPath ?? undefined\n if (!hostId || isOrgWideScope(visibleTo)) return cdnPath\n // `/api/media/cdn/{scope}/{mediaId}[/{hash}]`\n const marker = '/api/media/cdn/'\n const at = cdnPath.indexOf(marker)\n if (at === -1) return cdnPath\n const head = cdnPath.slice(0, at + marker.length)\n const rest = cdnPath.slice(at + marker.length)\n const [scopeSegment, ...tail] = rest.split('/')\n // Only the bare `org:{orgId}` form is rewritten; an already-qualified\n // scope is left alone rather than gaining a second host.\n if (!scopeSegment.startsWith('org:') || scopeSegment.includes(':', 4)) {\n return cdnPath\n }\n return [`${head}${scopeSegment}:${hostId}`, ...tail].join('/')\n}\n\n/*==========================================\n * SEEN, AND HELD (AGL-3336).\n *\n * `visibleTo` answers one question, \"who may see this\", because it is the\n * one field both enforcement layers can evaluate. A visibility GRANT — an\n * org manager sharing a record with another site, by hand or by a rule —\n * has to widen exactly that field, or the other site's lists, which are\n * real `array-contains-any` queries, could never return the record.\n *\n * But a site a record was shared with does not HOLD it. It did not capture\n * the person, it holds no consent from them, and letting go of the record\n * is not its decision. So a document that carries a grant records which of\n * its tokens the grant added, under `sharing.added`, and every question\n * about holding — who may delete it, whose audience it joins, which site's\n * list it enters — reads {@link heldScopeTokens} instead of `visibleTo`.\n *\n * A document without the field is held by everything that sees it, which\n * is every document written before grants existed.\n *=========================================*/\n\n/** The map a scoped document records its visibility grants under. */\nexport const SCOPE_GRANTS_FIELD = 'sharing'\n\n/** The tokens a grant ADDED to `visibleTo`: seen through, never held. */\nexport function grantedScopeTokens(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n): string[] {\n const grants = (doc ?? {})[SCOPE_GRANTS_FIELD]\n if (!grants || typeof grants !== 'object' || Array.isArray(grants)) return []\n const added = (grants as Record<string, unknown>)['added']\n return Array.isArray(added)\n ? added.filter((token): token is string => typeof token === 'string')\n : []\n}\n\n/**\n * The tokens that HOLD a document: `visibleTo` without the ones a grant\n * added. Missing `visibleTo` is held by nobody, as it is seen by nobody.\n *\n * A site that created the document (`hostId`) or captured the person on it\n * (`capturedByHostIds`) holds its token whatever the grants say: a record\n * shared with a site that then captures the person itself is that site's\n * own from the capture on, before anything re-evaluates the grants.\n */\nexport function heldScopeTokens(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n): string[] {\n const visibleTo = (doc ?? {})['visibleTo']\n if (!Array.isArray(visibleTo)) return []\n const granted = new Set(grantedScopeTokens(doc))\n const capturing = new Set<string>()\n const hostId = (doc ?? {})['hostId']\n if (typeof hostId === 'string' && hostId) capturing.add(hostScopeToken(hostId))\n const captured = (doc ?? {})['capturedByHostIds']\n if (Array.isArray(captured)) {\n for (const id of captured) if (typeof id === 'string' && id) capturing.add(hostScopeToken(id))\n }\n return visibleTo.filter(\n (token): token is string =>\n typeof token === 'string' && (!granted.has(token) || capturing.has(token)),\n )\n}\n\n/**\n * Whether a site HOLDS a document rather than only seeing it through a\n * grant. The question a marketing audience, a list rule, a sequence and a\n * holder count ask; {@link visibleToHost} is the one a reader asks.\n */\nexport function heldByHost(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n hostId: string,\n): boolean {\n return visibleToHost(heldScopeTokens(doc), hostId)\n}\n\n/**\n * Whether a site sees a document ONLY through a grant: it carries grants and\n * the site does not hold it. The filter an audience sweep applies to what\n * its scoped query returned — a document with no grants answers `false`, so\n * every read that predates sharing keeps exactly the rows it had.\n */\nexport function seenOnlyThroughGrant(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n hostId: string,\n): boolean {\n return grantedScopeTokens(doc).length > 0 && !heldByHost(doc, hostId)\n}\n\n/*==========================================\n * ALL SITES EXCEPT… (AGL-4047).\n *\n * A third way to share, beside \"All sites\" and \"these sites\". Neither\n * enforcement layer can read an exclusion: Firestore has no \"does not\n * contain\", `not-in` cannot sit beside `array-contains-any`, and a rule that\n * refused on one would fail every scoped member's whole list. So what readers\n * enforce stays what it has always been, a flat `visibleTo` of the sites that\n * ARE included, and the choice that produced it sits beside it as a marker:\n *\n * visibleTo: ['host:b', 'host:c'] the only field a reader looks at\n * scopeMode: 'allExcept' says new sites join\n * scopeExcept: ['host:a'] the sites that stay out\n *\n * `visibleTo` is therefore a list that has to be kept up: a new site joins it\n * and a deleted one leaves it. {@link reconcileAllExcept} is the one answer to\n * what it should hold; the sweep (`scope-sharing-sweep.ts`) applies it.\n *\n * `visibleTo` always wins over the marker when they disagree, because it is\n * what the database enforces. A helper describing a document some other way\n * would be describing something no reader does.\n *=========================================*/\n\n/** The `scopeMode` a document kept up by the sweep carries. */\nexport const SCOPE_MODE_ALL_EXCEPT = 'allExcept' as const\n\n/**\n * What a sharing choice writes. A `null` marker field means the document must\n * not carry it, which a server write spells as a field delete, so a document\n * moved back to All sites or to chosen sites keeps no stale marker.\n */\nexport interface ScopeSharingFields {\n visibleTo: ScopeToken[]\n scopeMode: typeof SCOPE_MODE_ALL_EXCEPT | null\n scopeExcept: ScopeToken[] | null\n}\n\n/** How a document is shared, as a person would choose it. */\nexport type ScopeSharing =\n | { mode: 'all' }\n | { mode: 'selected'; hostIds: string[] }\n | { mode: 'allExcept'; exceptHostIds: string[]; includedHostIds: string[] }\n | { mode: 'none' }\n\n/** What a person picked: the input to {@link sharingFromChoice}. */\nexport type ScopeSharingChoice =\n | { mode: 'all' }\n | { mode: 'selected'; hostIds: readonly string[] }\n | { mode: 'allExcept'; exceptHostIds: readonly string[] }\n\nconst uniqueStrings = (values: readonly string[]): string[] => [\n ...new Set(values.filter((value) => typeof value === 'string' && value)),\n]\n\n/**\n * The excluded sites a marker names, or null when the marker is not one this\n * module can act on: anything but an array of host tokens. Null is what keeps\n * a damaged marker from being read as \"except nothing\", which means All sites.\n */\nfunction markerExceptHostIds(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n): string[] | null {\n if (doc?.['scopeMode'] !== SCOPE_MODE_ALL_EXCEPT) return null\n const except = doc['scopeExcept']\n if (!Array.isArray(except)) return null\n const ids: string[] = []\n for (const token of except) {\n const parsed = typeof token === 'string' ? parseScopeToken(token) : null\n if (parsed?.kind !== 'host') return null\n ids.push(parsed.hostId)\n }\n return uniqueStrings(ids)\n}\n\n/**\n * How a document is shared. Reads the marker only where it agrees with what\n * readers enforce: a document carrying `'org'` is shared with all sites\n * whatever a marker beside it says, and a damaged marker reads as the chosen\n * sites `visibleTo` names.\n */\nexport function scopeSharingOf(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n): ScopeSharing {\n const visibleTo = doc?.['visibleTo']\n const tokens = Array.isArray(visibleTo)\n ? visibleTo.filter((token): token is string => typeof token === 'string')\n : null\n if (tokens?.includes(ORG_SCOPE_TOKEN)) return { mode: 'all' }\n const included = uniqueStrings(hostIdsFromScope(tokens ?? []))\n const except = tokens ? markerExceptHostIds(doc) : null\n if (except) {\n return { mode: 'allExcept', exceptHostIds: except, includedHostIds: included }\n }\n return included.length ? { mode: 'selected', hostIds: included } : { mode: 'none' }\n}\n\n/**\n * What a sharing choice writes, or why it cannot be written.\n *\n * `orgHostIds` is the workspace's sites as the writer read them. An exclusion\n * naming a site that is no longer there is dropped, not refused: the person\n * asked for that site to stay out, and it is out. Excluding nothing is\n * refused, since that choice is All sites; excluding everything is refused,\n * since it would hide the document from every site.\n *\n * An all-except list is not held to `MAX_SCOPE_HOSTS`, which limits what a\n * QUERY can ask for and never what a document stores. A collection whose\n * stored fields multiply by site passes its own `maxIncluded`. `keepHostIds`\n * are sites that stay on the list even if excluded, such as a site that\n * captured the person a record is about.\n */\nexport function sharingFromChoice(\n choice: ScopeSharingChoice,\n orgHostIds: readonly string[],\n options: { maxIncluded?: number | null; keepHostIds?: readonly string[] } = {},\n): { fields: ScopeSharingFields; problem: null } | { fields: null; problem: string } {\n if (choice.mode === 'all') {\n return {\n fields: { visibleTo: [ORG_SCOPE_TOKEN], scopeMode: null, scopeExcept: null },\n problem: null,\n }\n }\n if (choice.mode === 'selected') {\n const stored = scopeToStore(choice.hostIds.map(hostScopeToken))\n return stored.scope\n ? { fields: { visibleTo: stored.scope, scopeMode: null, scopeExcept: null }, problem: null }\n : { fields: null, problem: stored.problem }\n }\n const org = uniqueStrings(orgHostIds)\n const except = uniqueStrings(choice.exceptHostIds).filter((id) => org.includes(id))\n if (!except.length) {\n return {\n fields: null,\n problem: 'Choose at least one site to leave out, or share with All sites.',\n }\n }\n const included = includedHostIds(org, except, options.keepHostIds)\n if (!included.length) {\n return { fields: null, problem: 'Keep at least one site in, or choose the sites.' }\n }\n if (options.maxIncluded != null && included.length > options.maxIncluded) {\n return {\n fields: null,\n problem: `This can reach ${options.maxIncluded === 1 ? '1 site' : `${options.maxIncluded} sites`} at most. Leave out more sites, or choose the sites.`,\n }\n }\n return {\n fields: {\n visibleTo: included.map(hostScopeToken),\n scopeMode: SCOPE_MODE_ALL_EXCEPT,\n scopeExcept: except.map(hostScopeToken),\n },\n problem: null,\n }\n}\n\n/** The workspace's sites minus the excluded ones, plus the kept, sorted. */\nfunction includedHostIds(\n org: readonly string[],\n except: readonly string[],\n keep: readonly string[] | undefined,\n): string[] {\n const out = new Set(except)\n const kept = new Set(keep ?? [])\n return org.filter((id) => !out.has(id) || kept.has(id)).sort()\n}\n\n/** What keeping an all-except document up to date came to. */\nexport interface AllExceptReconcile {\n /**\n * - `unmarked`: not an all-except document; nothing to do.\n * - `current`: already says what it should.\n * - `changed`: write `fields`.\n * - `capped`: it should reach more sites than `maxIncluded`, so it stopped\n * widening. Any `fields` only take away sites that are gone.\n * - `invalid`: a marker this module cannot act on, or one beside `'org'`.\n * Left alone and reported, because either guess moves who can see it.\n */\n status: 'unmarked' | 'current' | 'changed' | 'capped' | 'invalid'\n fields: ScopeSharingFields | null\n}\n\n/**\n * What an all-except document should say, given the workspace's sites today.\n *\n * Pure and idempotent, which is what lets every trigger and the drift report\n * ask the same question: a second run over its own answer says `current`.\n *\n * - A new site joins `visibleTo`, unless it is excluded.\n * - A site that left the workspace leaves `visibleTo` and `scopeExcept`.\n * - Once no exclusion is left the document IS All sites, so it collapses to\n * `['org']` and drops its marker.\n * - When every remaining site is excluded `visibleTo` is empty and the marker\n * stays: no site sees it until a new one joins. The data is kept, which is\n * why {@link isSiteOnlyScope} answers false for a marked document.\n * - A site in `sharing.added` stays, since a person shared the document with\n * it. So do `keepHostIds`. Both only while the site is in the workspace.\n */\nexport function reconcileAllExcept(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n orgHostIds: readonly string[],\n options: { maxIncluded?: number | null; keepHostIds?: readonly string[] } = {},\n): AllExceptReconcile {\n if (doc?.['scopeMode'] === undefined || doc['scopeMode'] === null) {\n return { status: 'unmarked', fields: null }\n }\n const storedExcept = markerExceptHostIds(doc)\n const visibleTo = doc['visibleTo']\n if (\n !storedExcept ||\n !Array.isArray(visibleTo) ||\n visibleTo.includes(ORG_SCOPE_TOKEN)\n ) {\n return { status: 'invalid', fields: null }\n }\n const org = uniqueStrings(orgHostIds)\n const except = storedExcept.filter((id) => org.includes(id))\n if (!except.length) {\n return {\n status: 'changed',\n fields: { visibleTo: [ORG_SCOPE_TOKEN], scopeMode: null, scopeExcept: null },\n }\n }\n const current = uniqueStrings(hostIdsFromScope(visibleTo as string[]))\n const keep = [\n ...(options.keepHostIds ?? []),\n ...hostIdsFromScope(grantedScopeTokens(doc)),\n ]\n let included = includedHostIds(org, except, keep)\n let capped = false\n if (\n options.maxIncluded != null &&\n included.length > options.maxIncluded &&\n included.some((id) => !current.includes(id))\n ) {\n capped = true\n included = current.filter((id) => org.includes(id)).sort()\n }\n const same =\n included.length === current.length &&\n included.every((id) => current.includes(id)) &&\n except.length === storedExcept.length\n const fields: ScopeSharingFields | null = same\n ? null\n : {\n visibleTo: included.map(hostScopeToken),\n scopeMode: SCOPE_MODE_ALL_EXCEPT,\n scopeExcept: except.map(hostScopeToken),\n }\n if (capped) return { status: 'capped', fields }\n return fields ? { status: 'changed', fields } : { status: 'current', fields: null }\n}\n\n/**\n * The sentence the console shows for how a document is shared:\n * {@link describeScope}, plus the all-except wording. Sites are named only\n * where `hostNames` has them, so a reader who cannot see a site's name is told\n * how many sites, never an id.\n */\nexport function describeSharing(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n hostNames: Readonly<Record<string, string>> = {},\n): string {\n const sharing = scopeSharingOf(doc)\n if (sharing.mode !== 'allExcept') {\n return describeScope(doc?.['visibleTo'] as readonly string[] | undefined, hostNames)\n }\n if (!sharing.includedHostIds.length) return 'No sites'\n const names = sharing.exceptHostIds.map((id) => hostNames[id])\n const count = names.length\n if (count === 1) return `All sites except ${names[0] || '1 site'}`\n if (count === 2 && names.every(Boolean)) {\n return `All sites except ${names[0]} and ${names[1]}`\n }\n return `All sites except ${count} sites`\n}\n\n/**\n * Whether a document belongs to this site alone: what deciding to erase it\n * with the site asks, so the three copies of that question share one answer.\n *\n * FALSE FOR ANY MARKED DOCUMENT, and that is the reason this exists. A site\n * can be the last one an all-except document still reaches, with `visibleTo`\n * naming it and nothing else, and the document is still the workspace's.\n * Reading that as \"this site's own\" would erase the data with the site.\n */\nexport function isSiteOnlyScope(\n doc: Readonly<Record<string, unknown>> | null | undefined,\n hostId: string,\n): boolean {\n if (doc?.['scopeMode'] !== undefined && doc?.['scopeMode'] !== null) return false\n const visibleTo = doc?.['visibleTo']\n const token = hostScopeToken(hostId)\n return (\n Array.isArray(visibleTo) &&\n visibleTo.length > 0 &&\n visibleTo.every((entry) => entry === token)\n )\n}\n\n/**\n * {@link scopeCovers} for whole documents: whether `target` stays visible\n * everywhere `source` is, which a cross-dataset reference needs.\n *\n * Today's tokens are not enough once either side is all-except, because the\n * two lists move when a site is added: a chosen-sites target cannot cover an\n * all-except source however it looks today (the next new site gets the source\n * and not the target), and an all-except target covers an all-except source\n * only when it leaves out no site the source includes.\n */\nexport function sharingCovers(\n target: Readonly<Record<string, unknown>> | null | undefined,\n source: Readonly<Record<string, unknown>> | null | undefined,\n): boolean {\n const targetTokens = target?.['visibleTo'] as readonly string[] | undefined\n const sourceTokens = source?.['visibleTo'] as readonly string[] | undefined\n const targetSharing = scopeSharingOf(target)\n const sourceSharing = scopeSharingOf(source)\n if (sourceSharing.mode === 'allExcept') {\n if (targetSharing.mode === 'all') return true\n if (targetSharing.mode !== 'allExcept') return false\n const sourceExcept = new Set(sourceSharing.exceptHostIds)\n if (!targetSharing.exceptHostIds.every((id) => sourceExcept.has(id))) return false\n }\n return scopeCovers(targetTokens, sourceTokens)\n}\n"],"names":["ORG_SCOPE_TOKEN","HOST_TOKEN_PREFIX","MAX_SCOPE_HOSTS","hostScopeToken","hostId","isScopeToken","value","startsWith","length","parseScopeToken","token","kind","slice","hostIdsFromScope","visibleTo","ids","parsed","push","scopeTokensForHost","visibleToHost","includes","visibleToTokens","scopeTokens","some","storedScope","Array","isArray","normalizeVisibleTo","input","tokens","filter","unique","Set","scopeToStore","scope","problem","scopeForHosts","hostIds","map","isOrgWideScope","narrowsScope","before","after","kept","has","describeScope","hostNames","name","defaultScopeForNewResource","options","defaultResourceScope","defaultMediaScopeOf","org","defaultMediaScope","newResourceScopeFields","Error","scopeCovers","target","source","reach","every","hostQualifiedCdnPath","cdnPath","undefined","marker","at","indexOf","head","rest","scopeSegment","tail","split","join","SCOPE_GRANTS_FIELD","grantedScopeTokens","doc","grants","added","heldScopeTokens","granted","capturing","add","captured","id","heldByHost","seenOnlyThroughGrant","SCOPE_MODE_ALL_EXCEPT","uniqueStrings","values","markerExceptHostIds","except","scopeSharingOf","mode","included","exceptHostIds","includedHostIds","sharingFromChoice","choice","orgHostIds","fields","scopeMode","scopeExcept","stored","keepHostIds","maxIncluded","keep","out","sort","reconcileAllExcept","status","storedExcept","current","capped","same","describeSharing","sharing","names","count","Boolean","isSiteOnlyScope","entry","sharingCovers","targetTokens","sourceTokens","targetSharing","sourceSharing","sourceExcept"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;CAcC,GASD,wDAAwD,GACxD,OAAO,MAAMA,kBAAkB,MAAmC;AAElE,MAAMC,oBAAoB;AAE1B;;;;CAIC,GACD,OAAO,MAAMC,kBAAkB,GAAE;AAEjC,sDAAsD,GACtD,OAAO,SAASC,eAAeC,MAAc;IAC3C,OAAO,GAAGH,oBAAoBG,QAAQ;AACxC;AAEA,OAAO,SAASC,aAAaC,KAAc;IACzC,IAAI,OAAOA,UA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