@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.5 → 6.2.2-dev.51

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 (103) hide show
  1. package/dist/browser/assets/{entry-Cvoo4_c9.js → entry-CHj7_KqV.js} +3 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-Deqa5Gd1.js} +4 -4
  3. package/dist/browser/{linting-Dn6pXRkK.js → button-CuO8Gh3v.js} +20 -6
  4. package/dist/browser/button-CuO8Gh3v.js.map +1 -0
  5. package/dist/browser/{connect-CV-z3DqA.js → connect-MB8tpoQw.js} +916 -200
  6. package/dist/browser/connect-MB8tpoQw.js.map +1 -0
  7. package/dist/browser/{dist-CXoKspdx.js → dist-B4FWbuEM.js} +10 -2
  8. package/dist/browser/{dist-CXoKspdx.js.map → dist-B4FWbuEM.js.map} +1 -1
  9. package/dist/{node/dist-BeZaEP6S.mjs → browser/dist-BAJ5nRDl.js} +21 -2
  10. package/dist/browser/{dist-D8H48e8N.js.map → dist-BAJ5nRDl.js.map} +1 -1
  11. package/dist/browser/{dist-BEs8jMgM.js → dist-BesM2uPE.js} +1559 -1292
  12. package/dist/browser/dist-BesM2uPE.js.map +1 -0
  13. package/dist/browser/{document-drive-sTKoi6L4.js → document-drive-CJz0STcj.js} +1077 -122
  14. package/dist/browser/document-drive-CJz0STcj.js.map +1 -0
  15. package/dist/browser/document-models/index.js +1 -1
  16. package/dist/browser/{documents-D4ek7Ubv.js → documents-J_l59mSV.js} +5 -604
  17. package/dist/browser/documents-J_l59mSV.js.map +1 -0
  18. package/dist/browser/{editor-Cw38euRs.js → editor-BDpW8vq8.js} +671 -236
  19. package/dist/browser/editor-BDpW8vq8.js.map +1 -0
  20. package/dist/browser/editor-DQ49fg9m.js +25 -0
  21. package/dist/browser/editor-DQ49fg9m.js.map +1 -0
  22. package/dist/browser/editors/document-model-editor/module.js +1 -1
  23. package/dist/browser/editors/generic-drive-explorer/index.js +5 -5
  24. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  25. package/dist/{node/folder-view-DjKO1mAh.mjs → browser/folder-view-BG4n0zgH.js} +73 -46
  26. package/dist/browser/folder-view-BG4n0zgH.js.map +1 -0
  27. package/dist/browser/{graphql-editor-B-dNI5hD.js → graphql-editor-gWZAjvBa.js} +8 -7
  28. package/dist/browser/{graphql-editor-B-dNI5hD.js.map → graphql-editor-gWZAjvBa.js.map} +1 -1
  29. package/dist/browser/{hooks-CORHBNHb.js → hooks-KKcNp2X0.js} +2 -2
  30. package/dist/browser/{hooks-CORHBNHb.js.map → hooks-KKcNp2X0.js.map} +1 -1
  31. package/dist/browser/index.js +378 -9
  32. package/dist/browser/index.js.map +1 -1
  33. package/dist/browser/{json-editor-v_MnzQVs.js → json-editor-DCA4V_DS.js} +4 -4
  34. package/dist/browser/{json-editor-v_MnzQVs.js.map → json-editor-DCA4V_DS.js.map} +1 -1
  35. package/dist/browser/{lib-C-f3izXz.js → lib-V-A4Y98b.js} +12 -2
  36. package/dist/browser/lib-V-A4Y98b.js.map +1 -0
  37. package/dist/browser/printer-CEYr4JOg.js +604 -0
  38. package/dist/browser/printer-CEYr4JOg.js.map +1 -0
  39. package/dist/browser/{schema-context-DY-GEGnY.js → schema-context-ZyeclQwy.js} +2 -2
  40. package/dist/browser/{schema-context-DY-GEGnY.js.map → schema-context-ZyeclQwy.js.map} +1 -1
  41. package/dist/browser/{state-schemas-65Tp0ZuG.js → state-schemas-oLJnYfWV.js} +8 -18
  42. package/dist/browser/state-schemas-oLJnYfWV.js.map +1 -0
  43. package/dist/node/{linting-Dx50GuLN.mjs → button-Da7CxMn7.mjs} +20 -7
  44. package/dist/node/button-Da7CxMn7.mjs.map +1 -0
  45. package/dist/node/{connect-Bbi5wHyR.mjs → connect-Cdie59_O.mjs} +916 -200
  46. package/dist/node/connect-Cdie59_O.mjs.map +1 -0
  47. package/dist/node/{dist-8nCvrie2.mjs → dist-BIdl6Tbq.mjs} +1564 -1292
  48. package/dist/node/dist-BIdl6Tbq.mjs.map +1 -0
  49. package/dist/{browser/dist-D8H48e8N.js → node/dist-CzYOpeXN.mjs} +21 -2
  50. package/dist/node/{dist-BeZaEP6S.mjs.map → dist-CzYOpeXN.mjs.map} +1 -1
  51. package/dist/node/{dist-fA4EItr0.mjs → dist-DT7jI9ol.mjs} +10 -2
  52. package/dist/node/{dist-fA4EItr0.mjs.map → dist-DT7jI9ol.mjs.map} +1 -1
  53. package/dist/node/{document-drive-DjL9iikf.mjs → document-drive-BgHPyTwW.mjs} +1077 -122
  54. package/dist/node/document-drive-BgHPyTwW.mjs.map +1 -0
  55. package/dist/node/document-models/index.mjs +1 -1
  56. package/dist/node/{documents-BFBPmyw1.mjs → documents-DCf53bzO.mjs} +3 -3
  57. package/dist/node/{documents-BFBPmyw1.mjs.map → documents-DCf53bzO.mjs.map} +1 -1
  58. package/dist/node/editor-C_RkuhbJ.mjs +25 -0
  59. package/dist/node/editor-C_RkuhbJ.mjs.map +1 -0
  60. package/dist/node/{editor-DkT0krRE.mjs → editor-CyRFyoHM.mjs} +672 -237
  61. package/dist/node/editor-CyRFyoHM.mjs.map +1 -0
  62. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  63. package/dist/node/editors/generic-drive-explorer/index.mjs +5 -5
  64. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  65. package/dist/{browser/folder-view-BQWrt8wh.js → node/folder-view-jO8_grQ6.mjs} +73 -46
  66. package/dist/node/folder-view-jO8_grQ6.mjs.map +1 -0
  67. package/dist/node/{graphql-DskHmkMe.mjs → graphql-BfAoPeWM.mjs} +2 -2
  68. package/dist/node/{graphql-DskHmkMe.mjs.map → graphql-BfAoPeWM.mjs.map} +1 -1
  69. package/dist/node/{graphql-editor-x-d_DoqN.mjs → graphql-editor-DyuSPAfc.mjs} +7 -7
  70. package/dist/node/{graphql-editor-x-d_DoqN.mjs.map → graphql-editor-DyuSPAfc.mjs.map} +1 -1
  71. package/dist/node/{hooks-DJrjfVaS.mjs → hooks-D0DcS3MV.mjs} +2 -2
  72. package/dist/node/{hooks-DJrjfVaS.mjs.map → hooks-D0DcS3MV.mjs.map} +1 -1
  73. package/dist/node/index.mjs +378 -9
  74. package/dist/node/index.mjs.map +1 -1
  75. package/dist/node/{json-editor-D8QbP3jl.mjs → json-editor-DtNAniwW.mjs} +4 -4
  76. package/dist/node/{json-editor-D8QbP3jl.mjs.map → json-editor-DtNAniwW.mjs.map} +1 -1
  77. package/dist/node/{main-D82dkD7g.mjs → main-C2GlZ2Rh.mjs} +14 -4
  78. package/dist/node/main-C2GlZ2Rh.mjs.map +1 -0
  79. package/dist/node/{schema-context-CX5ml_9t.mjs → schema-context-DL8jhi_d.mjs} +3 -3
  80. package/dist/node/{schema-context-CX5ml_9t.mjs.map → schema-context-DL8jhi_d.mjs.map} +1 -1
  81. package/dist/node/{state-schemas-BwvZVEhR.mjs → state-schemas-CeAvAzja.mjs} +10 -20
  82. package/dist/{browser/state-schemas-65Tp0ZuG.js.map → node/state-schemas-CeAvAzja.mjs.map} +1 -1
  83. package/package.json +7 -6
  84. package/dist/browser/connect-CV-z3DqA.js.map +0 -1
  85. package/dist/browser/dist-BEs8jMgM.js.map +0 -1
  86. package/dist/browser/document-drive-sTKoi6L4.js.map +0 -1
  87. package/dist/browser/documents-D4ek7Ubv.js.map +0 -1
  88. package/dist/browser/editor-Cw38euRs.js.map +0 -1
  89. package/dist/browser/editor-DY3JsQJ3.js +0 -29
  90. package/dist/browser/editor-DY3JsQJ3.js.map +0 -1
  91. package/dist/browser/folder-view-BQWrt8wh.js.map +0 -1
  92. package/dist/browser/lib-C-f3izXz.js.map +0 -1
  93. package/dist/browser/linting-Dn6pXRkK.js.map +0 -1
  94. package/dist/node/connect-Bbi5wHyR.mjs.map +0 -1
  95. package/dist/node/dist-8nCvrie2.mjs.map +0 -1
  96. package/dist/node/document-drive-DjL9iikf.mjs.map +0 -1
  97. package/dist/node/editor-BH2gCDjt.mjs +0 -29
  98. package/dist/node/editor-BH2gCDjt.mjs.map +0 -1
  99. package/dist/node/editor-DkT0krRE.mjs.map +0 -1
  100. package/dist/node/folder-view-DjKO1mAh.mjs.map +0 -1
  101. package/dist/node/linting-Dx50GuLN.mjs.map +0 -1
  102. package/dist/node/main-D82dkD7g.mjs.map +0 -1
  103. package/dist/node/state-schemas-BwvZVEhR.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { E as __commonJSMin, _ as string, c as any, f as lazy, h as object, k as __toESM, l as array, m as number, n as constantCase, o as _enum, p as literal, r as pascalCase, u as boolean, v as union, x as ZodError, y as unknown } from "./dist-CXoKspdx.js";
1
+ import { A as __toESM, D as __commonJSMin, S as ZodError, _ as strictObject, b as unknown, c as any, f as lazy, g as record, h as object, l as array, m as number, n as constantCase, o as _enum, p as literal, r as pascalCase, u as boolean, v as string, y as union } from "./dist-B4FWbuEM.js";
2
2
  //#endregion
3
3
  //#region ../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/esm/wrapper.js
4
4
  var import_safe_stable_stringify = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -589,7 +589,7 @@ function isBE() {
589
589
  return new Uint8Array(new Uint16Array([65279]).buffer)[0] === 254;
590
590
  }
591
591
  //#endregion
592
- //#region ../shared/dist/utils-DKOFCM0Q.js
592
+ //#region ../shared/dist/utils-CTt1XRn-.js
593
593
  const hashBrowser = (data, algorithm = "sha1", encoding = "base64", _params) => {
594
594
  if (!["sha1"].includes(algorithm)) throw new Error(`Hashing algorithm not supported: "${algorithm}". Available: sha1`);
595
595
  if (!["base64", "hex"].includes(encoding)) throw new Error(`Hash encoding not supported: "${encoding}". Available: base64, hex`);
@@ -636,6 +636,40 @@ function ab2hex(ab) {
636
636
  const view = ArrayBuffer.isView(ab) ? ab : new Uint8Array(ab);
637
637
  return Array.prototype.map.call(view, (x) => ("00" + x.toString(16)).slice(-2)).join("");
638
638
  }
639
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
640
+ /**
641
+ * Decodes a base58btc (Bitcoin/IPFS alphabet) string to bytes. Returns null on
642
+ * any character outside the alphabet.
643
+ */
644
+ function base58Decode(input) {
645
+ const bytes = [];
646
+ for (const ch of input) {
647
+ let carry = BASE58_ALPHABET.indexOf(ch);
648
+ if (carry === -1) return null;
649
+ for (let i = 0; i < bytes.length; i++) {
650
+ carry += bytes[i] * 58;
651
+ bytes[i] = carry & 255;
652
+ carry >>= 8;
653
+ }
654
+ while (carry > 0) {
655
+ bytes.push(carry & 255);
656
+ carry >>= 8;
657
+ }
658
+ }
659
+ for (let k = 0; k < input.length && input[k] === "1"; k++) bytes.push(0);
660
+ return Uint8Array.from(bytes.reverse());
661
+ }
662
+ /** Decodes a base64url string to bytes (portable across node, browsers, workers). */
663
+ function base64UrlToBytes(input) {
664
+ const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
665
+ const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
666
+ let binary;
667
+ if (typeof atob === "function") binary = atob(padded);
668
+ else binary = Buffer.from(padded, "base64").toString("binary");
669
+ const bytes = new Uint8Array(binary.length);
670
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
671
+ return bytes;
672
+ }
639
673
  function generateId(method) {
640
674
  if (method && method.toString() !== "UUIDv4") throw new Error(`Id generation method not supported: "${method.toString()}"`);
641
675
  return globalThis.crypto.randomUUID();
@@ -2978,6 +3012,75 @@ var DowngradeNotSupportedError = class extends Error {
2978
3012
  this.toVersion = toVersion;
2979
3013
  }
2980
3014
  };
3015
+ /**
3016
+ * Thrown when INITIALIZE_AUTH is applied to an already-initialized auth scope.
3017
+ * The genesis action is valid only at auth revision zero.
3018
+ */
3019
+ var AuthAlreadyInitializedError = class extends Error {
3020
+ documentId;
3021
+ constructor(documentId) {
3022
+ super(`Auth scope already initialized for document ${documentId}: INITIALIZE_AUTH is valid only at auth revision zero`);
3023
+ this.name = "AuthAlreadyInitializedError";
3024
+ this.documentId = documentId;
3025
+ }
3026
+ };
3027
+ /**
3028
+ * Thrown when INITIALIZE_AUTH is not signed by the document creator (its signer
3029
+ * does not match `header.sig.publicKey`), so it cannot set the auth policy.
3030
+ */
3031
+ var AuthInitializerNotCreatorError = class extends Error {
3032
+ documentId;
3033
+ constructor(documentId) {
3034
+ super(`INITIALIZE_AUTH for document ${documentId} must be signed by the document creator`);
3035
+ this.name = "AuthInitializerNotCreatorError";
3036
+ this.documentId = documentId;
3037
+ }
3038
+ };
3039
+ /**
3040
+ * Thrown when INITIALIZE_AUTH carries a version below 1. Version 0 is reserved
3041
+ * for the uninitialized auth scope.
3042
+ */
3043
+ var InvalidAuthVersionError = class extends Error {
3044
+ documentId;
3045
+ version;
3046
+ constructor(documentId, version) {
3047
+ super(`Invalid auth policy version ${version} for document ${documentId}: INITIALIZE_AUTH requires an integer version >= 1`);
3048
+ this.name = "InvalidAuthVersionError";
3049
+ this.documentId = documentId;
3050
+ this.version = version;
3051
+ }
3052
+ };
3053
+ /** Thrown when a duplicate would lose the source policy's version or creator binding. */
3054
+ var AuthPolicyNotPreservedError = class extends Error {
3055
+ documentId;
3056
+ constructor(documentId) {
3057
+ super(`Duplicating document ${documentId} would not preserve its auth policy: the copy loses the policy version or its creator binding`);
3058
+ this.name = "AuthPolicyNotPreservedError";
3059
+ this.documentId = documentId;
3060
+ }
3061
+ };
3062
+ /**
3063
+ * Thrown when a grant referenced by REMOVE_GRANT or MOVE_GRANT does not exist.
3064
+ */
3065
+ var GrantNotFoundError = class extends Error {
3066
+ grantId;
3067
+ constructor(grantId) {
3068
+ super(`Grant not found in auth scope: ${grantId}`);
3069
+ this.name = "GrantNotFoundError";
3070
+ this.grantId = grantId;
3071
+ }
3072
+ };
3073
+ /**
3074
+ * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
3075
+ */
3076
+ var AuthActionNotAllowedError = class extends Error {
3077
+ actionType;
3078
+ constructor(actionType) {
3079
+ super(`${actionType} is not permitted on the auth scope`);
3080
+ this.name = "AuthActionNotAllowedError";
3081
+ this.actionType = actionType;
3082
+ }
3083
+ };
2981
3084
  var HashMismatchError = class extends Error {
2982
3085
  _scope;
2983
3086
  _document;
@@ -3004,6 +3107,25 @@ var HashMismatchError = class extends Error {
3004
3107
  return this._operation;
3005
3108
  }
3006
3109
  };
3110
+ /**
3111
+ * Thrown when replay or import requires a document model version that is not
3112
+ * registered. Carries the data the UI needs to explain the mismatch.
3113
+ */
3114
+ var UnsupportedDocumentModelVersionError = class extends Error {
3115
+ documentType;
3116
+ requiredVersion;
3117
+ availableVersions;
3118
+ constructor(documentType, requiredVersion, availableVersions) {
3119
+ super(`No reducer registered for document version ${requiredVersion}. Available versions: ${availableVersions.join(", ")}`);
3120
+ this.name = "UnsupportedDocumentModelVersionError";
3121
+ this.documentType = documentType;
3122
+ this.requiredVersion = requiredVersion;
3123
+ this.availableVersions = availableVersions;
3124
+ }
3125
+ static isError(error) {
3126
+ return Error.isError(error) && error.name === "UnsupportedDocumentModelVersionError";
3127
+ }
3128
+ };
3007
3129
  const isDefinedNonNullAny$1 = (v) => v !== void 0 && v !== null;
3008
3130
  any().refine((v) => isDefinedNonNullAny$1(v));
3009
3131
  const Load_StateSchema = _enum(["LOAD_STATE"]);
@@ -3444,17 +3566,101 @@ const ConfigEntrySchema = object({
3444
3566
  required: boolean().optional(),
3445
3567
  default: boolean().optional()
3446
3568
  });
3569
+ const PwaUrlPatternSchema = union([string(), strictObject({
3570
+ source: string(),
3571
+ flags: string().optional()
3572
+ }).refine((p) => {
3573
+ try {
3574
+ new RegExp(p.source, p.flags);
3575
+ return true;
3576
+ } catch {
3577
+ return false;
3578
+ }
3579
+ }, { message: "source/flags do not compile to a valid RegExp" })]);
3580
+ const PwaRuntimeCachingSchema = strictObject({
3581
+ urlPattern: PwaUrlPatternSchema,
3582
+ handler: _enum([
3583
+ "CacheFirst",
3584
+ "CacheOnly",
3585
+ "NetworkFirst",
3586
+ "NetworkOnly",
3587
+ "StaleWhileRevalidate"
3588
+ ]),
3589
+ method: _enum([
3590
+ "GET",
3591
+ "POST",
3592
+ "PUT",
3593
+ "DELETE",
3594
+ "HEAD",
3595
+ "PATCH"
3596
+ ]).optional(),
3597
+ options: strictObject({
3598
+ cacheName: string().optional(),
3599
+ networkTimeoutSeconds: number().optional(),
3600
+ expiration: strictObject({
3601
+ maxEntries: number().optional(),
3602
+ maxAgeSeconds: number().optional()
3603
+ }).optional(),
3604
+ cacheableResponse: strictObject({
3605
+ statuses: array(number()).optional(),
3606
+ headers: record(string(), string()).optional()
3607
+ }).optional()
3608
+ }).optional()
3609
+ });
3610
+ const PwaIconSchema = strictObject({
3611
+ src: string(),
3612
+ sizes: string().optional(),
3613
+ type: string().optional(),
3614
+ purpose: string().optional()
3615
+ });
3616
+ const PwaFileHandlerSchema = strictObject({
3617
+ accept: record(string(), array(string().regex(/^\./, "file extensions must start with '.'"))),
3618
+ icons: array(PwaIconSchema).optional(),
3619
+ launch_type: _enum(["single-client", "multiple-clients"]).optional()
3620
+ });
3621
+ const PwaConfigSchema = strictObject({
3622
+ manifest: strictObject({
3623
+ name: string().optional(),
3624
+ short_name: string().optional(),
3625
+ description: string().optional(),
3626
+ theme_color: string().optional(),
3627
+ background_color: string().optional(),
3628
+ display: _enum([
3629
+ "fullscreen",
3630
+ "standalone",
3631
+ "minimal-ui",
3632
+ "browser"
3633
+ ]).optional(),
3634
+ start_url: string().optional(),
3635
+ scope: string().optional(),
3636
+ icons: array(PwaIconSchema).optional(),
3637
+ file_handlers: array(PwaFileHandlerSchema).optional(),
3638
+ launch_handler: strictObject({ client_mode: _enum([
3639
+ "auto",
3640
+ "focus-existing",
3641
+ "navigate-existing",
3642
+ "navigate-new"
3643
+ ]) }).optional()
3644
+ }).optional(),
3645
+ globPatterns: array(string()).optional(),
3646
+ globIgnores: array(string()).optional(),
3647
+ maximumFileSizeToCacheInBytes: number().optional(),
3648
+ runtimeCaching: array(PwaRuntimeCachingSchema).optional(),
3649
+ navigateFallbackDenylist: array(PwaUrlPatternSchema).optional()
3650
+ });
3447
3651
  object({
3448
3652
  name: string(),
3449
3653
  description: string().optional(),
3450
3654
  category: string().optional(),
3655
+ image: string().optional(),
3451
3656
  publisher: PublisherSchema.optional(),
3452
3657
  documentModels: PowerhouseModulesSchema,
3453
3658
  apps: PowerhouseModulesSchema,
3454
3659
  editors: PowerhouseModulesSchema,
3455
3660
  processors: PowerhouseModulesSchema,
3456
3661
  subgraphs: PowerhouseModulesSchema,
3457
- config: array(ConfigEntrySchema).optional()
3662
+ config: array(ConfigEntrySchema).optional(),
3663
+ pwa: PwaConfigSchema.optional()
3458
3664
  });
3459
3665
  /**
3460
3666
  * Cancels the last `count` operations.
@@ -3725,6 +3931,505 @@ const actions = {
3725
3931
  ...baseActions,
3726
3932
  ...documentModelActions
3727
3933
  };
3934
+ const documentModelDocumentType = "powerhouse/document-model";
3935
+ /**
3936
+ * Thrown when a grant violates the v1 validation rules. The message is stored
3937
+ * on error operations, so it must be a pure function of the input.
3938
+ */
3939
+ var InvalidGrantError = class extends Error {
3940
+ grantId;
3941
+ constructor(grantId, problem) {
3942
+ super(`Invalid grant "${grantId}": ${problem}`);
3943
+ this.name = "InvalidGrantError";
3944
+ this.grantId = grantId;
3945
+ }
3946
+ };
3947
+ /** Thrown for a `{ group }` principal on a group document: references never chain. */
3948
+ var GroupPrincipalNotAllowedError = class extends Error {
3949
+ grantId;
3950
+ constructor(grantId) {
3951
+ super(`Grant "${grantId}" uses a group principal on a group document: a group's auth scope cannot reference other groups`);
3952
+ this.name = "GroupPrincipalNotAllowedError";
3953
+ this.grantId = grantId;
3954
+ }
3955
+ };
3956
+ /**
3957
+ * Thrown when a change would leave a creator-less policy with no grant
3958
+ * permitting execute on the auth scope. Without the creator carve-out no
3959
+ * subject could ever administer such a policy again.
3960
+ */
3961
+ var AuthAdministrationLockoutError = class extends Error {
3962
+ grantId;
3963
+ constructor(grantId) {
3964
+ super(`Change to grant "${grantId}" would leave no reachable grant permitting execute on the auth scope: a policy with no creator must always retain one`);
3965
+ this.name = "AuthAdministrationLockoutError";
3966
+ this.grantId = grantId;
3967
+ }
3968
+ };
3969
+ /**
3970
+ * Thrown when INITIALIZE_AUTH would create a creator-less policy with no grant
3971
+ * permitting execute on the auth scope. Such a policy would be born with no
3972
+ * subject able to administer it.
3973
+ */
3974
+ var AuthAdministrationMissingError = class extends Error {
3975
+ constructor() {
3976
+ super("Initial grants include no reachable grant permitting execute on the auth scope: a policy with no creator must always include one");
3977
+ this.name = "AuthAdministrationMissingError";
3978
+ }
3979
+ };
3980
+ const GRANT_KEYS = new Set([
3981
+ "id",
3982
+ "description",
3983
+ "effect",
3984
+ "principal",
3985
+ "capability",
3986
+ "where"
3987
+ ]);
3988
+ const PRINCIPAL_KINDS = new Set([
3989
+ "anyone",
3990
+ "address",
3991
+ "group",
3992
+ "match"
3993
+ ]);
3994
+ const COMPARISON_CONDITION_KINDS = new Set([
3995
+ "eq",
3996
+ "ne",
3997
+ "lt",
3998
+ "lte",
3999
+ "gt",
4000
+ "gte"
4001
+ ]);
4002
+ function isPlainValue(value) {
4003
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4004
+ }
4005
+ function operandProblem(value, capabilityScope, budget) {
4006
+ budget.nodes -= 1;
4007
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
4008
+ if (!isPlainValue(value)) return "operand must be an object";
4009
+ const keys = Object.keys(value);
4010
+ if (keys.length !== 1) return "operand must have exactly one of attr or lit";
4011
+ if (keys[0] === "attr") {
4012
+ const attr = value.attr;
4013
+ if (typeof attr !== "string" || attr.length === 0) return "attr must be a non-empty string";
4014
+ if (capabilityScope !== void 0 && capabilityScope !== "*" && attr.startsWith("doc.")) {
4015
+ const pathScope = attr.split(".")[1] ?? "";
4016
+ if (pathScope !== capabilityScope) return `condition path "${attr}" reads scope "${pathScope}" but the capability covers only scope "${capabilityScope}"`;
4017
+ }
4018
+ return null;
4019
+ }
4020
+ if (keys[0] === "lit") {
4021
+ const lit = value.lit;
4022
+ if (lit !== null && typeof lit !== "string" && typeof lit !== "number" && typeof lit !== "boolean") return "lit must be a string, number, boolean, or null";
4023
+ if (typeof lit === "number" && !Number.isFinite(lit)) return "lit must be a finite number";
4024
+ if (typeof lit === "number" && Object.is(lit, -0)) return "lit must not be negative zero";
4025
+ return null;
4026
+ }
4027
+ return `unknown operand kind "${keys[0]}"`;
4028
+ }
4029
+ function conditionProblem(value, capabilityScope, depth, budget) {
4030
+ if (depth > 10) return `condition exceeds depth 10`;
4031
+ budget.nodes -= 1;
4032
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
4033
+ if (!isPlainValue(value)) return "condition must be an object";
4034
+ const keys = Object.keys(value);
4035
+ if (keys.length !== 1) return "condition must have exactly one operator";
4036
+ const kind = keys[0];
4037
+ const body = value[kind];
4038
+ if (COMPARISON_CONDITION_KINDS.has(kind)) {
4039
+ if (!Array.isArray(body) || body.length !== 2) return `${kind} requires a pair of operands`;
4040
+ for (const operand of body) {
4041
+ const problem = operandProblem(operand, capabilityScope, budget);
4042
+ if (problem !== null) return problem;
4043
+ }
4044
+ return null;
4045
+ }
4046
+ if (kind === "in" || kind === "notIn") {
4047
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return `${kind} requires an operand and an operand list`;
4048
+ const first = operandProblem(body[0], capabilityScope, budget);
4049
+ if (first !== null) return first;
4050
+ for (const operand of body[1]) {
4051
+ const problem = operandProblem(operand, capabilityScope, budget);
4052
+ if (problem !== null) return problem;
4053
+ }
4054
+ return null;
4055
+ }
4056
+ if (kind === "exists") return operandProblem(body, capabilityScope, budget);
4057
+ if (kind === "and" || kind === "or") {
4058
+ if (!Array.isArray(body)) return `${kind} requires a condition list`;
4059
+ for (const child of body) {
4060
+ const problem = conditionProblem(child, capabilityScope, depth + 1, budget);
4061
+ if (problem !== null) return problem;
4062
+ }
4063
+ return null;
4064
+ }
4065
+ if (kind === "not") return conditionProblem(body, capabilityScope, depth + 1, budget);
4066
+ return `unknown condition operator "${kind}"`;
4067
+ }
4068
+ function principalProblem(value, capabilityScope) {
4069
+ if (!isPlainValue(value)) return "principal must be an object";
4070
+ const keys = Object.keys(value);
4071
+ if (keys.length !== 1 || !PRINCIPAL_KINDS.has(keys[0])) return "principal must have exactly one of anyone, address, group, or match";
4072
+ const kind = keys[0];
4073
+ if (kind === "anyone" && value.anyone !== true) return "anyone must be true";
4074
+ if (kind === "address") {
4075
+ const address = value.address;
4076
+ if (typeof address !== "string" || address.length === 0) return "address must be a non-empty string";
4077
+ }
4078
+ if (kind === "group") {
4079
+ const group = value.group;
4080
+ if (typeof group !== "string" || group.length === 0) return "group must be a non-empty string";
4081
+ }
4082
+ if (kind === "match") return conditionProblem(value.match, capabilityScope, 1, { nodes: 100 });
4083
+ return null;
4084
+ }
4085
+ function capabilityProblem(value) {
4086
+ if (!isPlainValue(value)) return "capability must be an object";
4087
+ const can = value.can;
4088
+ if (can !== "read" && can !== "execute") return "capability.can must be read or execute";
4089
+ const allowedKeys = can === "execute" ? [
4090
+ "can",
4091
+ "scope",
4092
+ "operation"
4093
+ ] : ["can", "scope"];
4094
+ const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
4095
+ if (unknownKeys.length > 0) return `unknown capability key "${unknownKeys[0]}"`;
4096
+ if (value.scope !== void 0) {
4097
+ if (typeof value.scope !== "string" || value.scope.length === 0) return "capability.scope must be a non-empty string";
4098
+ }
4099
+ if (can === "execute" && value.operation !== void 0) {
4100
+ const operation = value.operation;
4101
+ if (!Array.isArray(operation)) return "capability.operation must be an array";
4102
+ if (operation.length > 100) return `capability.operation exceeds 100 entries`;
4103
+ for (const entry of operation) if (typeof entry !== "string" || entry.length === 0) return "capability.operation entries must be non-empty strings";
4104
+ }
4105
+ return null;
4106
+ }
4107
+ /** Returns the first v1-rule violation, or null. Pure, total, deterministic. */
4108
+ function grantProblem(value) {
4109
+ if (!isPlainValue(value)) return "grant must be an object";
4110
+ const unknownKeys = Object.keys(value).filter((key) => !GRANT_KEYS.has(key)).sort();
4111
+ if (unknownKeys.length > 0) return `unknown grant key "${unknownKeys[0]}"`;
4112
+ if (typeof value.id !== "string" || value.id.length === 0) return "id must be a non-empty string";
4113
+ if (typeof value.description !== "string") return "description must be a string";
4114
+ if (value.effect !== "allow" && value.effect !== "deny") return "effect must be allow or deny";
4115
+ const capabilityValue = value.capability;
4116
+ const capability = capabilityProblem(capabilityValue);
4117
+ if (capability !== null) return capability;
4118
+ const capabilityScope = capabilityValue.scope;
4119
+ const principal = principalProblem(value.principal, capabilityScope);
4120
+ if (principal !== null) return principal;
4121
+ if (value.where !== void 0) return conditionProblem(value.where, capabilityScope, 1, { nodes: 100 });
4122
+ return null;
4123
+ }
4124
+ /** V1 shape rules plus the group-document group-principal ban. */
4125
+ function assertValidGrant(grant, documentType) {
4126
+ const grantId = isPlainValue(grant) && typeof grant.id === "string" ? grant.id : "";
4127
+ const problem = grantProblem(grant);
4128
+ if (problem !== null) throw new InvalidGrantError(grantId, problem);
4129
+ if (documentType === "powerhouse/reactor-group" && "group" in grant.principal) throw new GroupPrincipalNotAllowedError(grantId);
4130
+ }
4131
+ /**
4132
+ * Validates an initial grant list: the count cap, every grant, and — on a
4133
+ * creator-less policy — that some grant keeps the auth scope administrable.
4134
+ */
4135
+ function assertValidInitialGrants(grants, documentType, creator) {
4136
+ if (grants.length > 100) throw new InvalidGrantError("", `policy exceeds 100 grants`);
4137
+ for (const grant of grants) assertValidGrant(grant, documentType);
4138
+ if (creator === void 0 && !administrationReachable(grants)) throw new AuthAdministrationMissingError();
4139
+ }
4140
+ /**
4141
+ * Validates a grant upsert: the grant itself, the count cap on append, and
4142
+ * administration retention. Retention is checked on an append as well as an
4143
+ * in-place replace, because a grant appended after the administration grant can
4144
+ * shadow it (evaluation is last-applicable-grant-wins) and so take
4145
+ * administration away without removing anything.
4146
+ */
4147
+ function assertValidGrantUpsert(grant, existing, documentType, creator) {
4148
+ assertValidGrant(grant, documentType);
4149
+ const exists = existing.some((g) => g.id === grant.id);
4150
+ if (!exists && existing.length >= 100) throw new InvalidGrantError(grant.id, `policy exceeds 100 grants`);
4151
+ assertAuthAdministrationRetained(creator, existing, exists ? existing.map((g) => g.id === grant.id ? grant : g) : [...existing, grant], grant.id);
4152
+ }
4153
+ /**
4154
+ * The request whose coverage keeps a policy administrable: a subject who may
4155
+ * SET_GRANT can upsert any grant, so every other repair stays reachable.
4156
+ */
4157
+ const AUTH_ADMINISTRATION_REQUEST = {
4158
+ verb: "execute",
4159
+ scope: "auth",
4160
+ operation: "SET_GRANT"
4161
+ };
4162
+ /**
4163
+ * Whether some subject can still administer the auth scope under this grant list.
4164
+ *
4165
+ * Asks the evaluator rather than pattern-matching a single grant: evaluation is
4166
+ * last-applicable-grant-wins, so an allow that some later deny shadows keeps
4167
+ * nothing reachable even though it is still present in the list. Only anyone and
4168
+ * address principals are candidates, because those are the ones v1 can match at
4169
+ * all; a `where` condition or a group or match principal never applies.
4170
+ */
4171
+ function administrationReachable(grants) {
4172
+ return grants.some((grant) => {
4173
+ const subject = administrationCandidate(grant);
4174
+ if (subject === void 0) return false;
4175
+ return evaluateGrantStack(grants, subject, AUTH_ADMINISTRATION_REQUEST).decision === "allow";
4176
+ });
4177
+ }
4178
+ /**
4179
+ * The subject to test this grant with, or undefined when the grant could never
4180
+ * carry administration for anyone.
4181
+ */
4182
+ function administrationCandidate(grant) {
4183
+ if (grant.effect !== "allow" || grant.where !== void 0 || !capabilityCovers(grant.capability, AUTH_ADMINISTRATION_REQUEST)) return;
4184
+ if ("address" in grant.principal) return {
4185
+ address: grant.principal.address,
4186
+ key: void 0
4187
+ };
4188
+ if ("anyone" in grant.principal) return {
4189
+ address: void 0,
4190
+ key: void 0
4191
+ };
4192
+ }
4193
+ /**
4194
+ * A creator-less policy must always retain a grant permitting execute on the
4195
+ * auth scope; on a signed document the creator carve-out keeps administration
4196
+ * reachable instead. Rejects a change that takes the last such grant away. A
4197
+ * policy already without one is left alone: the change is not what locks it.
4198
+ */
4199
+ function assertAuthAdministrationRetained(creator, previous, next, grantId) {
4200
+ if (creator !== void 0) return;
4201
+ if (administrationReachable(previous) && !administrationReachable(next)) throw new AuthAdministrationLockoutError(grantId);
4202
+ }
4203
+ /**
4204
+ * An operand whose shape validation would have rejected. Distinguished from
4205
+ * an unresolved path so a structurally malformed operand poisons its whole
4206
+ * condition to false rather than reading as "absent", which `not` would
4207
+ * otherwise widen to true.
4208
+ */
4209
+ const INVALID_OPERAND = Symbol("invalid-operand");
4210
+ /**
4211
+ * Narrows to the values conditions compare. An object, array, or non-finite
4212
+ * number resolves to undefined, and every comparison involving undefined is
4213
+ * false.
4214
+ */
4215
+ function asConditionValue(value) {
4216
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4217
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4218
+ }
4219
+ /**
4220
+ * Resolves one operand. Attr roots: `subject.*`, `doc.<scope>.*` where the
4221
+ * scope must be the executing scope (validation already rejects any other,
4222
+ * but resolution stays total), and `action.input.*`. Path steps read own
4223
+ * properties only, so prototype members can never influence a verdict.
4224
+ */
4225
+ function resolveOperand(operand, subject, request, conditions) {
4226
+ if (!isPlainValue(operand)) return INVALID_OPERAND;
4227
+ const keys = Object.keys(operand);
4228
+ if (keys.length !== 1) return INVALID_OPERAND;
4229
+ if (keys[0] === "lit") {
4230
+ const value = asConditionValue(operand.lit);
4231
+ return value === void 0 ? INVALID_OPERAND : value;
4232
+ }
4233
+ if (keys[0] !== "attr") return INVALID_OPERAND;
4234
+ const attr = operand.attr;
4235
+ if (typeof attr !== "string" || attr.length === 0) return INVALID_OPERAND;
4236
+ const path = attr.split(".");
4237
+ let value;
4238
+ let rest;
4239
+ if (path[0] === "subject") {
4240
+ value = subject;
4241
+ rest = path.slice(1);
4242
+ } else if (path[0] === "doc") {
4243
+ if (path[1] !== request.scope) return;
4244
+ value = conditions.scopeState;
4245
+ rest = path.slice(2);
4246
+ } else if (path[0] === "action" && path[1] === "input") {
4247
+ value = conditions.actionInput;
4248
+ rest = path.slice(2);
4249
+ } else return;
4250
+ for (const segment of rest) {
4251
+ if (!isPlainValue(value) || !Object.hasOwn(value, segment)) return;
4252
+ value = value[segment];
4253
+ }
4254
+ return asConditionValue(value);
4255
+ }
4256
+ /**
4257
+ * Total order within one type: numbers numerically, strings by code point.
4258
+ * Everything else, including mixed types, does not order.
4259
+ */
4260
+ function compareValues(left, right) {
4261
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
4262
+ if (typeof left === "string" && typeof right === "string") {
4263
+ const leftPoints = Array.from(left);
4264
+ const rightPoints = Array.from(right);
4265
+ const shared = Math.min(leftPoints.length, rightPoints.length);
4266
+ for (let i = 0; i < shared; i++) {
4267
+ const a = leftPoints[i].codePointAt(0) ?? 0;
4268
+ const b = rightPoints[i].codePointAt(0) ?? 0;
4269
+ if (a !== b) return a < b ? -1 : 1;
4270
+ }
4271
+ return leftPoints.length === rightPoints.length ? 0 : leftPoints.length < rightPoints.length ? -1 : 1;
4272
+ }
4273
+ }
4274
+ /**
4275
+ * Tri-state evaluation: undefined marks a structurally invalid node, which
4276
+ * poisons the whole tree to false at the top — and a structurally malformed
4277
+ * operand poisons its condition the same way. Both are distinct from an
4278
+ * operand whose path fails to resolve, which is a valid comparison that is
4279
+ * false. The distinction keeps `not` from widening over malformed input.
4280
+ */
4281
+ function evaluateNode(node, subject, request, conditions) {
4282
+ if (!isPlainValue(node)) return;
4283
+ const keys = Object.keys(node);
4284
+ if (keys.length !== 1) return;
4285
+ const kind = keys[0];
4286
+ const body = node[kind];
4287
+ switch (kind) {
4288
+ case "eq":
4289
+ case "ne":
4290
+ case "lt":
4291
+ case "lte":
4292
+ case "gt":
4293
+ case "gte": {
4294
+ if (!Array.isArray(body) || body.length !== 2) return;
4295
+ const left = resolveOperand(body[0], subject, request, conditions);
4296
+ const right = resolveOperand(body[1], subject, request, conditions);
4297
+ if (left === INVALID_OPERAND || right === INVALID_OPERAND) return;
4298
+ if (left === void 0 || right === void 0) return false;
4299
+ if (kind === "eq") return left === right;
4300
+ if (kind === "ne") return left !== right;
4301
+ const order = compareValues(left, right);
4302
+ if (order === void 0) return false;
4303
+ switch (kind) {
4304
+ case "lt": return order < 0;
4305
+ case "lte": return order <= 0;
4306
+ case "gt": return order > 0;
4307
+ case "gte": return order >= 0;
4308
+ }
4309
+ return;
4310
+ }
4311
+ case "in":
4312
+ case "notIn": {
4313
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return;
4314
+ const left = resolveOperand(body[0], subject, request, conditions);
4315
+ if (left === INVALID_OPERAND) return;
4316
+ const elements = body[1].map((element) => resolveOperand(element, subject, request, conditions));
4317
+ if (elements.some((value) => value === INVALID_OPERAND)) return;
4318
+ if (left === void 0) return false;
4319
+ const found = elements.some((value) => value !== void 0 && value === left);
4320
+ return kind === "in" ? found : !found;
4321
+ }
4322
+ case "exists": {
4323
+ const value = resolveOperand(body, subject, request, conditions);
4324
+ if (value === INVALID_OPERAND) return;
4325
+ return value !== void 0;
4326
+ }
4327
+ case "and":
4328
+ case "or": {
4329
+ if (!Array.isArray(body)) return;
4330
+ let result = kind === "and";
4331
+ for (const child of body) {
4332
+ const value = evaluateNode(child, subject, request, conditions);
4333
+ if (value === void 0) return;
4334
+ if (kind === "and") result = result && value;
4335
+ else result = result || value;
4336
+ }
4337
+ return result;
4338
+ }
4339
+ case "not": {
4340
+ const value = evaluateNode(body, subject, request, conditions);
4341
+ return value === void 0 ? void 0 : !value;
4342
+ }
4343
+ default: return;
4344
+ }
4345
+ }
4346
+ /**
4347
+ * Evaluates a version-1 condition. Deterministic, total, and pure: any input
4348
+ * shape yields a boolean and never throws, and a malformed condition is
4349
+ * false. These are consensus semantics, versioned by `PHAuthState.version`;
4350
+ * changing them requires a new version.
4351
+ */
4352
+ function evaluateCondition(condition, subject, request, conditions) {
4353
+ return evaluateNode(condition, subject, request, conditions) === true;
4354
+ }
4355
+ /** Whether a capability's scope reaches the requested one. */
4356
+ function scopeCovers(scope, requested) {
4357
+ return scope === void 0 || scope === "*" || scope === requested;
4358
+ }
4359
+ /**
4360
+ * Whether one grant answers this request.
4361
+ *
4362
+ * A grant allowing execute on a scope also allows reading it: executing an
4363
+ * operation means reading the state it applies to, so permitting the write while
4364
+ * withholding the read would describe an access nobody could use. The converse
4365
+ * does not hold -- a read grant confers no write.
4366
+ *
4367
+ * Only an allow carries across. A deny on execute withholds the write and says
4368
+ * nothing about the read, so a policy locking writes down does not silently
4369
+ * revoke a read grant sitting before it. The operation list is not consulted
4370
+ * either: it restricts which operations may be executed, not whether the scope
4371
+ * is visible, and a read carries no operation to match against.
4372
+ *
4373
+ * Reads are not consensus -- no replica records a read, and the two read call
4374
+ * sites are both inside the read gate -- so this rule is not part of what makes
4375
+ * an operation valid, and does not need a policy version of its own.
4376
+ */
4377
+ function grantAnswers(grant, request) {
4378
+ if (capabilityCovers(grant.capability, request)) return true;
4379
+ return request.verb === "read" && grant.effect === "allow" && grant.capability.can === "execute" && scopeCovers(grant.capability.scope, request.scope);
4380
+ }
4381
+ function capabilityCovers(capability, request) {
4382
+ if (capability.can !== request.verb) return false;
4383
+ if (!scopeCovers(capability.scope, request.scope)) return false;
4384
+ if (capability.can === "execute") {
4385
+ if (capability.operation === void 0) return true;
4386
+ return request.operation !== void 0 && capability.operation.includes(request.operation);
4387
+ }
4388
+ return true;
4389
+ }
4390
+ function principalMatches(principal, subject, request, groups, conditions) {
4391
+ if ("anyone" in principal) return true;
4392
+ if ("address" in principal) return subject.address !== void 0 && subject.address.toLowerCase() === principal.address.toLowerCase();
4393
+ if ("group" in principal) {
4394
+ if (groups === void 0 || subject.address === void 0) return false;
4395
+ const group = groups[principal.group];
4396
+ if (group === void 0 || !Array.isArray(group.members)) return false;
4397
+ const address = subject.address.toLowerCase();
4398
+ return group.members.some((member) => member.toLowerCase() === address);
4399
+ }
4400
+ if ("match" in principal) {
4401
+ if (conditions === void 0) return false;
4402
+ return evaluateCondition(principal.match, subject, request, conditions);
4403
+ }
4404
+ return false;
4405
+ }
4406
+ /**
4407
+ * Evaluates a v1 grant stack: default deny, last applicable grant wins, and
4408
+ * reports which grant decided it. Group principals match only against a
4409
+ * supplied groups map, and `where` clauses and { match } principals evaluate
4410
+ * only against a supplied condition context; a grant that uses an unsupplied
4411
+ * feature never applies.
4412
+ */
4413
+ function evaluateGrantStack(grants, subject, request, groups, conditions) {
4414
+ let applicable;
4415
+ for (const grant of grants) {
4416
+ if (grant.where !== void 0) {
4417
+ if (conditions === void 0) continue;
4418
+ if (!evaluateCondition(grant.where, subject, request, conditions)) continue;
4419
+ }
4420
+ if (grantAnswers(grant, request) && principalMatches(grant.principal, subject, request, groups, conditions)) applicable = grant;
4421
+ }
4422
+ if (applicable === void 0) return {
4423
+ decision: "deny",
4424
+ refusal: "no-applicable-grant"
4425
+ };
4426
+ if (applicable.effect === "deny") return {
4427
+ decision: "deny",
4428
+ refusal: "denied-by-grant",
4429
+ grantId: applicable.id
4430
+ };
4431
+ return { decision: "allow" };
4432
+ }
3728
4433
  const documentModelFileExtension = "phdm";
3729
4434
  const documentModelInitialLocalState = {};
3730
4435
  const documentModelInitialGlobalState = {
@@ -4306,7 +5011,306 @@ const documentModelGlobalState = {
4306
5011
  };
4307
5012
  const HASH_ALGORITHM_SHA1 = "sha1";
4308
5013
  const HASH_ENCODING_BASE64 = "base64";
4309
- const documentModelDocumentType = "powerhouse/document-model";
5014
+ /**
5015
+ * Creates a default PHAuthState
5016
+ */
5017
+ function defaultAuthState() {
5018
+ return {
5019
+ version: 0,
5020
+ grants: []
5021
+ };
5022
+ }
5023
+ /**
5024
+ * Creates a default PHDocumentState
5025
+ */
5026
+ function defaultDocumentState() {
5027
+ return {
5028
+ version: 0,
5029
+ hash: {
5030
+ algorithm: HASH_ALGORITHM_SHA1,
5031
+ encoding: HASH_ENCODING_BASE64
5032
+ }
5033
+ };
5034
+ }
5035
+ /**
5036
+ * Creates a default PHBaseState with auth and document properties
5037
+ */
5038
+ function defaultBaseState() {
5039
+ return {
5040
+ auth: defaultAuthState(),
5041
+ document: defaultDocumentState()
5042
+ };
5043
+ }
5044
+ /**
5045
+ * Creates a PHAuthState with the given properties
5046
+ */
5047
+ function createAuthState(auth) {
5048
+ return {
5049
+ ...defaultAuthState(),
5050
+ ...auth
5051
+ };
5052
+ }
5053
+ /**
5054
+ * Creates a PHDocumentState with the given properties
5055
+ */
5056
+ function createDocumentState(document) {
5057
+ return {
5058
+ ...defaultDocumentState(),
5059
+ ...document
5060
+ };
5061
+ }
5062
+ /**
5063
+ * Creates a PHBaseState with the given auth and document properties
5064
+ */
5065
+ function createBaseState(auth, document) {
5066
+ return {
5067
+ auth: createAuthState(auth),
5068
+ document: createDocumentState(document)
5069
+ };
5070
+ }
5071
+ /**
5072
+ * Backfills the auth scope to the default for legacy documents serialized with
5073
+ * an empty `auth`. Replaces only `state.auth`. Idempotent.
5074
+ */
5075
+ function backfillAuthState(state) {
5076
+ return {
5077
+ ...state,
5078
+ auth: createAuthState(state.auth)
5079
+ };
5080
+ }
5081
+ function defaultGlobalState() {
5082
+ return {
5083
+ ...defaultBaseState(),
5084
+ author: {
5085
+ name: "",
5086
+ website: ""
5087
+ },
5088
+ description: "",
5089
+ extension: "",
5090
+ id: "",
5091
+ name: "",
5092
+ specifications: []
5093
+ };
5094
+ }
5095
+ function defaultLocalState() {
5096
+ return {};
5097
+ }
5098
+ function createGlobalState(state) {
5099
+ return {
5100
+ ...defaultGlobalState(),
5101
+ ...state || {}
5102
+ };
5103
+ }
5104
+ function createLocalState(state) {
5105
+ return {
5106
+ ...defaultLocalState(),
5107
+ ...state || {}
5108
+ };
5109
+ }
5110
+ function createState(baseState, globalState, localState) {
5111
+ return {
5112
+ ...createBaseState(baseState?.auth, baseState?.document),
5113
+ global: createGlobalState(globalState),
5114
+ local: createLocalState(localState)
5115
+ };
5116
+ }
5117
+ /**
5118
+ * Destructuring a null input (reachable via raw synced operations) would
5119
+ * store an engine-specific TypeError message on the error operation.
5120
+ */
5121
+ function assertActionInputShape(input) {
5122
+ if (!isPlainValue(input)) throw new InvalidActionInputError({ input: "must be an object" });
5123
+ }
5124
+ function withGrants(document, grants) {
5125
+ return {
5126
+ ...document,
5127
+ state: {
5128
+ ...document.state,
5129
+ auth: {
5130
+ ...document.state.auth,
5131
+ grants
5132
+ }
5133
+ }
5134
+ };
5135
+ }
5136
+ const P256_PUBKEY_MULTICODEC = [128, 36];
5137
+ const DID_KEY_PREFIX = "did:key:z";
5138
+ function bytesEqual(a, b) {
5139
+ if (a.length !== b.length) return false;
5140
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
5141
+ return true;
5142
+ }
5143
+ /**
5144
+ * True when `signerKey` (an ActionSigner app key, a did:key) identifies the same
5145
+ * key recorded as the document creator. Returns false
5146
+ * when there is no creator (empty JWK) or no signer key.
5147
+ */
5148
+ function isDocumentCreator(creatorKey, signerKey) {
5149
+ if (!creatorKey?.x || !creatorKey.y) return false;
5150
+ if (!signerKey || !signerKey.startsWith(DID_KEY_PREFIX)) return false;
5151
+ const decoded = base58Decode(signerKey.slice(9));
5152
+ if (!decoded || decoded.length !== 35) return false;
5153
+ if (decoded[0] !== P256_PUBKEY_MULTICODEC[0] || decoded[1] !== P256_PUBKEY_MULTICODEC[1]) return false;
5154
+ const parityPrefix = decoded[2];
5155
+ if (parityPrefix !== 2 && parityPrefix !== 3) return false;
5156
+ const didX = decoded.subarray(3, 35);
5157
+ const jwkX = base64UrlToBytes(creatorKey.x);
5158
+ const jwkY = base64UrlToBytes(creatorKey.y);
5159
+ if (jwkX.length !== 32 || jwkY.length !== 32) return false;
5160
+ if (!bytesEqual(didX, jwkX)) return false;
5161
+ return (jwkY[31] & 1) === 1 === (parityPrefix === 3);
5162
+ }
5163
+ /**
5164
+ * Sets the initial policy. Valid only while the auth scope is uninitialized
5165
+ * (version 0). The input version is the policy language version and must be an
5166
+ * integer >= 1; 0 is reserved for the uninitialized state. On a signed-header
5167
+ * document it must be signed by the document creator (`header.sig.publicKey`).
5168
+ * A creator-less policy must include a grant permitting execute on the auth
5169
+ * scope, or it would be born locked out.
5170
+ */
5171
+ function applyInitializeAuthAction(document, action) {
5172
+ assertActionInputShape(action.input);
5173
+ const { version, grants } = action.input;
5174
+ if (!Number.isInteger(version) || version < 1) throw new InvalidAuthVersionError(document.header.id, version);
5175
+ if (document.state.auth.version !== 0) throw new AuthAlreadyInitializedError(document.header.id);
5176
+ if (!Array.isArray(grants)) throw new InvalidActionInputError({ grants: "must be an array" });
5177
+ const creatorKey = document.header.sig.publicKey;
5178
+ const signerKey = action.context?.signer?.app.key;
5179
+ const hasCreator = Boolean(creatorKey.kty || creatorKey.x || creatorKey.y);
5180
+ if (hasCreator && !isDocumentCreator(creatorKey, signerKey)) throw new AuthInitializerNotCreatorError(document.header.id);
5181
+ const creator = hasCreator ? signerKey : void 0;
5182
+ assertValidInitialGrants(grants, document.header.documentType, creator);
5183
+ return {
5184
+ ...document,
5185
+ state: {
5186
+ ...document.state,
5187
+ auth: createAuthState(creator ? {
5188
+ version,
5189
+ grants,
5190
+ creator
5191
+ } : {
5192
+ version,
5193
+ grants
5194
+ })
5195
+ }
5196
+ };
5197
+ }
5198
+ /** Upserts a grant by id: replaces in place if present, otherwise appends. */
5199
+ function applySetGrantAction(document, action) {
5200
+ assertActionInputShape(action.input);
5201
+ const { grant } = action.input;
5202
+ const grants = document.state.auth.grants;
5203
+ assertValidGrantUpsert(grant, grants, document.header.documentType, document.state.auth.creator);
5204
+ return withGrants(document, grants.some((g) => g.id === grant.id) ? grants.map((g) => g.id === grant.id ? grant : g) : [...grants, grant]);
5205
+ }
5206
+ /**
5207
+ * Removes a grant by id; throws if the id is not present or if the removal
5208
+ * would leave a creator-less policy with no auth-administration grant.
5209
+ */
5210
+ function applyRemoveGrantAction(document, action) {
5211
+ assertActionInputShape(action.input);
5212
+ const { id } = action.input;
5213
+ const { grants, creator } = document.state.auth;
5214
+ if (!grants.some((g) => g.id === id)) throw new GrantNotFoundError(id);
5215
+ const next = grants.filter((g) => g.id !== id);
5216
+ assertAuthAdministrationRetained(creator, grants, next, id);
5217
+ return withGrants(document, next);
5218
+ }
5219
+ /**
5220
+ * Moves a grant by id to a new index. Order is load-bearing (the last
5221
+ * applicable grant wins), so the relative order of the other grants is kept.
5222
+ * The target index is clamped to the valid range; an unknown id throws.
5223
+ *
5224
+ * Order alone decides which grant wins, so a move can take administration away
5225
+ * without changing the list's contents. It carries the same retention rule as
5226
+ * the two mutation paths.
5227
+ */
5228
+ function applyMoveGrantAction(document, action) {
5229
+ assertActionInputShape(action.input);
5230
+ const { id, index } = action.input;
5231
+ const { grants, creator } = document.state.auth;
5232
+ const from = grants.findIndex((g) => g.id === id);
5233
+ if (from === -1) throw new GrantNotFoundError(id);
5234
+ const next = [...grants];
5235
+ const [moved] = next.splice(from, 1);
5236
+ const to = Math.max(0, Math.min(index, next.length));
5237
+ next.splice(to, 0, moved);
5238
+ assertAuthAdministrationRetained(creator, grants, next, id);
5239
+ return withGrants(document, next);
5240
+ }
5241
+ /**
5242
+ * Dispatches an auth-scope action to its handler. This is the auth scope's
5243
+ * dedicated reducer: it is applied by the base reducer instead of the model
5244
+ * reducer, mirroring the document-scope platform handlers. Unknown types are a
5245
+ * no-op, matching the model-reducer default.
5246
+ */
5247
+ function applyAuthAction(document, action) {
5248
+ switch (action.type) {
5249
+ case "INITIALIZE_AUTH": return applyInitializeAuthAction(document, action);
5250
+ case "SET_GRANT": return applySetGrantAction(document, action);
5251
+ case "REMOVE_GRANT": return applyRemoveGrantAction(document, action);
5252
+ case "MOVE_GRANT": return applyMoveGrantAction(document, action);
5253
+ default: return document;
5254
+ }
5255
+ }
5256
+ /**
5257
+ * Because only creators can initialize auth scopes, we must verify that either
5258
+ * the document has no auth or the version and creator match.
5259
+ */
5260
+ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
5261
+ if (!source || source.version === 0) return;
5262
+ if (duplicated === void 0 || duplicated.version !== source.version || duplicated.creator !== source.creator) throw new AuthPolicyNotPreservedError(documentId);
5263
+ }
5264
+ /**
5265
+ * The auth scope a state snapshot may install, given the policy already there.
5266
+ *
5267
+ * `applyAuthAction` is the validated door onto `state.auth`, but a whole-state
5268
+ * snapshot (UPGRADE_DOCUMENT's `initialState`, LOAD_STATE's `data`) replaces the
5269
+ * scope wholesale and is authorized as a `document`-scope write. Without this,
5270
+ * a subject holding `execute` on `document` and no auth grant at all can install
5271
+ * a policy of its choosing, name itself `creator` (which exempts the policy from
5272
+ * the retention rule for good), or wipe an existing policy by carrying the
5273
+ * default uninitialized one.
5274
+ *
5275
+ * Three cases:
5276
+ *
5277
+ * - the snapshot carries no policy, or an uninitialized one: the document
5278
+ * keeps the policy it has, so a default-state upgrade cannot reset it;
5279
+ * - the document is uninitialized and the snapshot carries a policy: the
5280
+ * policy is installed after the same validation genesis applies, so it
5281
+ * cannot be born locked out;
5282
+ * - both carry a policy: they must agree. A duplicate preserves its source's
5283
+ * policy (see {@link assertAuthPreservedOnDuplicate}), and anything else is
5284
+ * an attempt to replace one policy with another.
5285
+ */
5286
+ function resolveSnapshotAuth(documentId, documentType, current, incoming) {
5287
+ const currentAuth = current ?? createAuthState({
5288
+ version: 0,
5289
+ grants: []
5290
+ });
5291
+ if (!incoming || !incoming.version) return currentAuth;
5292
+ if (currentAuth.version !== 0) {
5293
+ if (stringify$1(incoming) !== stringify$1(currentAuth)) throw new AuthPolicyNotPreservedError(documentId);
5294
+ return incoming;
5295
+ }
5296
+ if (!Array.isArray(incoming.grants)) throw new InvalidActionInputError({ grants: "must be an array" });
5297
+ assertValidInitialGrants(incoming.grants, documentType, incoming.creator);
5298
+ return incoming;
5299
+ }
5300
+ /** UNDO, REDO and PRUNE are rejected on the auth scope. */
5301
+ function assertAuthScopeActionAllowed(action) {
5302
+ if (action.scope === "auth" && [
5303
+ "UNDO",
5304
+ "REDO",
5305
+ "PRUNE"
5306
+ ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
5307
+ }
5308
+ /**
5309
+ * True iff authorization rejected the action.
5310
+ */
5311
+ function isDenied(operation) {
5312
+ return operation.deniedReason !== void 0;
5313
+ }
4310
5314
  const BaseDocumentHeaderSchema = object({
4311
5315
  id: string(),
4312
5316
  name: string(),
@@ -4437,6 +5441,7 @@ function createDocumentScopeOperations(header, state) {
4437
5441
  function baseCreateDocument(createState, initialState, documentType = "") {
4438
5442
  const state = createState(initialState);
4439
5443
  const header = createPresignedHeader(generateId(), documentType);
5444
+ header.protocolVersions = { "base-reducer": 2 };
4440
5445
  return {
4441
5446
  header,
4442
5447
  state,
@@ -4460,6 +5465,18 @@ function hashDocumentStateForScope(document, scope = "global") {
4460
5465
  * Uses the V2 model where consecutive NOOPs form chains.
4461
5466
  * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.
4462
5467
  */
5468
+ /**
5469
+ * The base-reducer protocol version a document is written against. Every
5470
+ * document carries one, set from the CREATE_DOCUMENT input. A header without
5471
+ * one was built outside that path, and choosing a version on its behalf would
5472
+ * replay the document through a reducer it was not written for, so it is an
5473
+ * error rather than a default.
5474
+ */
5475
+ function baseReducerVersion(header) {
5476
+ const version = header.protocolVersions?.["base-reducer"];
5477
+ if (typeof version !== "number") throw new Error(`Document ${header.id} carries no base-reducer protocol version`);
5478
+ return version;
5479
+ }
4463
5480
  function garbageCollectV2(sortedOperations) {
4464
5481
  const result = [];
4465
5482
  let noopChainLength = 0;
@@ -4476,9 +5493,26 @@ function garbageCollectV2(sortedOperations) {
4476
5493
  const defaultCreateState = (state) => {
4477
5494
  return state;
4478
5495
  };
5496
+ /**
5497
+ * Records an operation in the history without applying it, which is what a
5498
+ * denied operation needs: it occupies its index and contributes no state.
5499
+ *
5500
+ * The scope defaults to the action's own, and is passed explicitly by a rebuild
5501
+ * that is walking one stream and does not want to trust the action's copy.
5502
+ */
5503
+ function appendWithoutApplying(document, operation, scope = operation.action.scope) {
5504
+ return {
5505
+ ...document,
5506
+ operations: {
5507
+ ...document.operations,
5508
+ [scope]: [...document.operations[scope] ?? [], operation]
5509
+ }
5510
+ };
5511
+ }
4479
5512
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
4480
5513
  const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
4481
- let documentState = initialState;
5514
+ const backfilledInitialState = backfillAuthState(initialState);
5515
+ let documentState = backfilledInitialState;
4482
5516
  const operationsToReplay = [];
4483
5517
  const allScopes = new Set([
4484
5518
  ...Object.keys(operations),
@@ -4513,12 +5547,13 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
4513
5547
  const document = {
4514
5548
  header,
4515
5549
  state: defaultCreateState(documentState),
4516
- initialState,
5550
+ initialState: backfilledInitialState,
4517
5551
  operations: initialOperations,
4518
5552
  clipboard: []
4519
5553
  };
4520
5554
  let result = document;
4521
5555
  if (operationsToReplay.length) result = operationsToReplay.reduce((document, operation) => {
5556
+ if (isDenied(operation)) return updateHeaderRevision(appendWithoutApplying(document, operation), operation.action.scope, operation.timestampUtcMs);
4522
5557
  return reducer(document, operation.action, dispatch, {
4523
5558
  ignoreSkipOperations: true,
4524
5559
  checkHashes,
@@ -4800,13 +5835,15 @@ function redoOperation(document, action, skip) {
4800
5835
  });
4801
5836
  }
4802
5837
  function loadStateOperation(document, action) {
5838
+ const loaded = backfillAuthState(action.state.data);
5839
+ loaded.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, loaded.auth);
4803
5840
  return {
4804
5841
  ...document,
4805
5842
  header: {
4806
5843
  ...document.header,
4807
5844
  name: action.state.name
4808
5845
  },
4809
- state: action.state.data
5846
+ state: loaded
4810
5847
  };
4811
5848
  }
4812
5849
  function replayOperations(initialState, clearedOperations, stateReducer, header, dispatch, documentReducer = baseReducer, skipHeaderOperations = {}, options) {
@@ -4980,12 +6017,13 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
4980
6017
  function baseReducer(document, action, customReducer, dispatch, options = {}) {
4981
6018
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
4982
6019
  let _action = actionFromAction(action);
6020
+ assertAuthScopeActionAllowed(_action);
4983
6021
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
4984
6022
  let newDocument = { ...document };
4985
6023
  let reuseLastOperationIndex = false;
4986
6024
  const shouldProcessSkipOperation = !ignoreSkipOperations && skipValue > 0;
4987
6025
  if (isUndoRedo(_action)) {
4988
- const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? 1);
6026
+ const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? baseReducerVersion(document.header));
4989
6027
  _action = transformedAction;
4990
6028
  skipValue = calculatedSkip;
4991
6029
  newDocument = processedDocument;
@@ -5001,7 +6039,7 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5001
6039
  branch
5002
6040
  };
5003
6041
  newDocument = updateDocument(newDocument, _action, reuseLastOperationIndex, skipValue, operationContext, options.replayOptions?.operation, options.skipIndexValidation);
5004
- const protocolVersion = options.protocolVersion ?? 1;
6042
+ const protocolVersion = options.protocolVersion ?? baseReducerVersion(document.header);
5005
6043
  if (isUndo(action) && protocolVersion < 2) return processUndoOperation(newDocument, action.scope, customReducer);
5006
6044
  const isNoopWithSkip = _action.type === "NOOP" && skipValue > 0;
5007
6045
  if ((isUndo(action) || isNoopWithSkip) && protocolVersion >= 2) {
@@ -5027,6 +6065,13 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5027
6065
  }
5028
6066
  newDocument = create(newDocument, (draft) => {
5029
6067
  try {
6068
+ if (_action.scope === "auth") {
6069
+ const authState = applyAuthAction(newDocument, _action).state;
6070
+ unsafe(() => {
6071
+ draft.state = castDraft(authState);
6072
+ });
6073
+ return;
6074
+ }
5030
6075
  const newState = customReducer(draft.state, _action, dispatch);
5031
6076
  if (newState) unsafe(() => {
5032
6077
  draft.state = castDraft(newState);
@@ -5820,10 +6865,12 @@ function applyInitialState(document, action) {
5820
6865
  const input = action.input;
5821
6866
  const newState = input.initialState || input.state;
5822
6867
  if (newState) {
5823
- document.state = {
6868
+ const merged = backfillAuthState({
5824
6869
  ...document.state,
5825
6870
  ...newState
5826
- };
6871
+ });
6872
+ merged.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, merged.auth);
6873
+ document.state = merged;
5827
6874
  document.initialState = document.state;
5828
6875
  }
5829
6876
  }
@@ -5883,7 +6930,6 @@ function computeUpgradeTransitions(manifest, fromVersion, toVersion) {
5883
6930
  }
5884
6931
  return transitions;
5885
6932
  }
5886
- const NON_DOMAIN_SCOPES$1 = new Set(["auth", "document"]);
5887
6933
  function highestReducerVersion(reducers) {
5888
6934
  const keys = Object.keys(reducers).map(Number);
5889
6935
  if (keys.length === 0) throw new Error("VersionedReplayConfig.reducers must not be empty");
@@ -5911,15 +6957,15 @@ function highestReducerVersion(reducers) {
5911
6957
  */
5912
6958
  function replayDocumentVersioned(initialState, operations, config, header, dispatch, options) {
5913
6959
  const { checkHashes = true, skipIndexValidation } = options || {};
5914
- const protocolVersion = header.protocolVersions?.["base-reducer"] ?? 1;
6960
+ const protocolVersion = baseReducerVersion(header);
5915
6961
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
5916
6962
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
5917
6963
  const legacyFallback = () => {
5918
- const domainOps = Object.fromEntries(Object.entries(operations).filter(([s]) => !NON_DOMAIN_SCOPES$1.has(s)));
6964
+ const replayOps = Object.fromEntries(Object.entries(operations).filter(([s]) => s !== "document"));
5919
6965
  const latestVersion = highestReducerVersion(config.reducers);
5920
6966
  const reducer = config.reducers[latestVersion];
5921
6967
  return {
5922
- ...replayDocument(initialState, domainOps, reducer, header, dispatch, {}, options),
6968
+ ...replayDocument(initialState, replayOps, reducer, header, dispatch, {}, options),
5923
6969
  operations
5924
6970
  };
5925
6971
  };
@@ -5943,14 +6989,14 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5943
6989
  const a = op.action;
5944
6990
  return a.input.fromVersion > 0 && a.input.fromVersion < a.input.toVersion;
5945
6991
  });
5946
- const domainScopes = Object.keys(operations).filter((s) => !NON_DOMAIN_SCOPES$1.has(s));
6992
+ const replayScopes = Object.keys(operations).filter((s) => s !== "document");
5947
6993
  const scopeOps = {};
5948
- for (const s of domainScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
6994
+ for (const s of replayScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
5949
6995
  const boundaries = validatedUpgrades.map((upgradeOp) => {
5950
6996
  const revisionSnapshot = upgradeOp.action.input.revision;
5951
6997
  const upgradeTimestamp = upgradeOp.timestampUtcMs;
5952
6998
  const boundary = {};
5953
- for (const s of domainScopes) {
6999
+ for (const s of replayScopes) {
5954
7000
  const ops = scopeOps[s] ?? [];
5955
7001
  if (revisionSnapshot !== void 0) {
5956
7002
  const rev = revisionSnapshot[s] ?? 0;
@@ -5968,7 +7014,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5968
7014
  }
5969
7015
  return boundary;
5970
7016
  });
5971
- for (let i = 1; i < boundaries.length; i++) for (const s of domainScopes) {
7017
+ for (let i = 1; i < boundaries.length; i++) for (const s of replayScopes) {
5972
7018
  const prev = boundaries[i - 1]?.[s] ?? 0;
5973
7019
  const curr = boundaries[i]?.[s] ?? 0;
5974
7020
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
@@ -5980,10 +7026,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5980
7026
  ]);
5981
7027
  const initialOperations = {};
5982
7028
  for (const s of allScopes) initialOperations[s] = [];
7029
+ const backfilledSeed = backfillAuthState(seedState);
5983
7030
  let document = {
5984
7031
  header,
5985
- state: seedState,
5986
- initialState: seedState,
7032
+ state: backfilledSeed,
7033
+ initialState: backfilledSeed,
5987
7034
  operations: initialOperations,
5988
7035
  clipboard: []
5989
7036
  };
@@ -5991,17 +7038,15 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5991
7038
  const segmentEndHashPerScope = /* @__PURE__ */ new Map();
5992
7039
  for (let k = 0; k <= validatedUpgrades.length; k++) {
5993
7040
  const reducer = config.reducers[currentVersion];
5994
- if (!reducer) {
5995
- const available = Object.keys(config.reducers).join(", ");
5996
- throw new Error(`No reducer registered for document version ${currentVersion}. Available versions: ${available}`);
5997
- }
5998
- for (const s of domainScopes) {
7041
+ if (!reducer) throw new UnsupportedDocumentModelVersionError(header.documentType, currentVersion, Object.keys(config.reducers).map(Number).sort((a, b) => a - b));
7042
+ for (const s of replayScopes) {
5999
7043
  const ops = scopeOps[s] ?? [];
6000
7044
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
6001
7045
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
6002
7046
  const segOps = ops.slice(segStart, segEnd);
6003
7047
  for (const op of segOps) {
6004
- document = reducer(document, op.action, dispatch, {
7048
+ if (isDenied(op)) document = updateHeaderRevision(appendWithoutApplying(document, op, s), s, op.timestampUtcMs);
7049
+ else document = reducer(document, op.action, dispatch, {
6005
7050
  ignoreSkipOperations: true,
6006
7051
  checkHashes,
6007
7052
  skipIndexValidation,
@@ -6018,6 +7063,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6018
7063
  if (!spineOp) continue;
6019
7064
  const spineActionType = spineOp.action.type;
6020
7065
  if (spineActionType === "CREATE_DOCUMENT" || spineActionType === "UPGRADE_DOCUMENT") continue;
7066
+ if (isDenied(spineOp)) continue;
6021
7067
  if (spineActionType === "DELETE_DOCUMENT") document = applyDeleteDocumentAction(document, spineOp.action);
6022
7068
  else document = reducer(document, spineOp.action, dispatch, {
6023
7069
  ignoreSkipOperations: true,
@@ -6048,7 +7094,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6048
7094
  }
6049
7095
  };
6050
7096
  if (!checkHashes) {
6051
- const allReplayedOps = domainScopes.flatMap((s) => scopeOps[s] ?? []);
7097
+ const allReplayedOps = replayScopes.flatMap((s) => scopeOps[s] ?? []);
6052
7098
  for (const scope of Object.keys(document.state)) {
6053
7099
  const capturedHash = segmentEndHashPerScope.get(scope);
6054
7100
  const scopeHash = capturedHash !== void 0 ? capturedHash : hashDocumentStateForScope(document, scope);
@@ -6090,7 +7136,6 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6090
7136
  }
6091
7137
  };
6092
7138
  }
6093
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
6094
7139
  function zipAsync(data) {
6095
7140
  return new Promise((resolve, reject) => {
6096
7141
  zip(data, (err, out) => err ? reject(err) : resolve(out));
@@ -6169,7 +7214,7 @@ async function parseZipData(data) {
6169
7214
  async function loadFromZipData(data, reducer, options) {
6170
7215
  const { initialState, header, clearedOperations } = await parseZipData(data);
6171
7216
  return {
6172
- ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope))), reducer, header, void 0, {}, options),
7217
+ ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => scope !== "document")), reducer, header, void 0, {}, options),
6173
7218
  operations: clearedOperations
6174
7219
  };
6175
7220
  }
@@ -6192,96 +7237,6 @@ const documentModelLoadFromInput = (input) => {
6192
7237
  const documentModelSaveToFileHandle = (document, input) => {
6193
7238
  return baseSaveToFileHandle(document, input);
6194
7239
  };
6195
- /**
6196
- * Creates a default PHAuthState
6197
- */
6198
- function defaultAuthState() {
6199
- return {};
6200
- }
6201
- /**
6202
- * Creates a default PHDocumentState
6203
- */
6204
- function defaultDocumentState() {
6205
- return {
6206
- version: 0,
6207
- hash: {
6208
- algorithm: HASH_ALGORITHM_SHA1,
6209
- encoding: HASH_ENCODING_BASE64
6210
- }
6211
- };
6212
- }
6213
- /**
6214
- * Creates a default PHBaseState with auth and document properties
6215
- */
6216
- function defaultBaseState() {
6217
- return {
6218
- auth: defaultAuthState(),
6219
- document: defaultDocumentState()
6220
- };
6221
- }
6222
- /**
6223
- * Creates a PHAuthState with the given properties
6224
- */
6225
- function createAuthState(auth) {
6226
- return {
6227
- ...defaultAuthState(),
6228
- ...auth
6229
- };
6230
- }
6231
- /**
6232
- * Creates a PHDocumentState with the given properties
6233
- */
6234
- function createDocumentState(document) {
6235
- return {
6236
- ...defaultDocumentState(),
6237
- ...document
6238
- };
6239
- }
6240
- /**
6241
- * Creates a PHBaseState with the given auth and document properties
6242
- */
6243
- function createBaseState(auth, document) {
6244
- return {
6245
- auth: createAuthState(auth),
6246
- document: createDocumentState(document)
6247
- };
6248
- }
6249
- function defaultGlobalState() {
6250
- return {
6251
- ...defaultBaseState(),
6252
- author: {
6253
- name: "",
6254
- website: ""
6255
- },
6256
- description: "",
6257
- extension: "",
6258
- id: "",
6259
- name: "",
6260
- specifications: []
6261
- };
6262
- }
6263
- function defaultLocalState() {
6264
- return {};
6265
- }
6266
- function createGlobalState(state) {
6267
- return {
6268
- ...defaultGlobalState(),
6269
- ...state || {}
6270
- };
6271
- }
6272
- function createLocalState(state) {
6273
- return {
6274
- ...defaultLocalState(),
6275
- ...state || {}
6276
- };
6277
- }
6278
- function createState(baseState, globalState, localState) {
6279
- return {
6280
- ...createBaseState(baseState?.auth, baseState?.document),
6281
- global: createGlobalState(globalState),
6282
- local: createLocalState(localState)
6283
- };
6284
- }
6285
7240
  //#endregion
6286
7241
  //#region ../document-model/dist/index.js
6287
7242
  const isStateOfType$1 = (state) => {
@@ -7360,6 +8315,6 @@ const driveDocumentModelModule = {
7360
8315
  }
7361
8316
  };
7362
8317
  //#endregion
7363
- export { redo as A, setName as B, createZip as C, deleteOperationError as D, deleteOperation as E, setModelDescription as F, setStateSchema as G, setOperationErrorName as H, setModelExtension as I, validateModules as J, undo as K, setModelId as L, setAuthorName as M, setAuthorWebsite as N, documentModelDocumentType as O, setInitialState as P, setModelName as R, createState as S, deleteModule as T, setOperationName as U, setOperationDescription as V, setOperationSchema as W, generateId as X, validateStateSchemaName as Y, baseLoadFromInputVersioned as _, handleTargetNameCollisions as a, createPresignedHeader as b, moveNode as c, logger as d, addModule as f, baseLoadFromInput as g, baseCreateDocument as h, generateNodesCopy as i, replayDocumentVersioned as j, isDocumentAction as k, updateNode as l, addOperationError as m, copyNode as n, isFileNode as o, addOperation as p, validateInitialState as q, driveDocumentModelModule as r, isFolderNode as s, addFolder as t, documentModelDocumentModelModule as u, baseSaveToFileHandle as v, defaultBaseState as w, createReducer as x, buildSignedAction as y, setModuleName as z };
8318
+ export { setOperationSchema as $, createZip as A, replayDocumentVersioned as B, baseSaveToFileHandle as C, createPresignedHeader as D, createBaseState as E, documentModelDocumentType as F, setModelExtension as G, setAuthorWebsite as H, hashDocumentStateForScope as I, setModuleName as J, setModelId as K, isDocumentAction as L, deleteModule as M, deleteOperation as N, createReducer as O, deleteOperationError as P, setOperationName as Q, redo as R, baseLoadFromInputVersioned as S, createAction as T, setInitialState as U, setAuthorName as V, setModelDescription as W, setOperationDescription as X, setName as Y, setOperationErrorName as Z, addOperationError as _, handleTargetNameCollisions as a, generateId as at, baseCreateDocument as b, isValidName as c, documentModelDocumentModelModule as d, setStateSchema as et, logger as f, addOperation as g, addModule as h, generateNodesCopy as i, validateStateSchemaName as it, defaultBaseState as j, createState as k, moveNode as l, BaseDocumentStateSchema as m, copyNode as n, validateInitialState as nt, isFileNode as o, BaseDocumentHeaderSchema as p, setModelName as q, driveDocumentModelModule as r, validateModules as rt, isFolderNode as s, addFolder as t, undo as tt, updateNode as u, assertAuthPreservedOnDuplicate as v, buildSignedAction as w, baseLoadFromInput as x, baseActions as y, releaseNewVersion as z };
7364
8319
 
7365
- //# sourceMappingURL=document-drive-sTKoi6L4.js.map
8320
+ //# sourceMappingURL=document-drive-CJz0STcj.js.map