@powerhousedao/powerhouse-vetra-packages 6.2.2-dev.7 → 6.2.2-dev.71

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-D9kxNMhQ.js} +3 -2
  2. package/dist/browser/assets/{projection-entry-DVec8YRh.js → projection-entry-CuhmOECW.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-KEU-HR3o.js → connect-BQ3NfcJz.js} +916 -200
  6. package/dist/browser/connect-BQ3NfcJz.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-D5ra2aRj.js → dist-Ha_NNo7z.js} +1987 -1451
  12. package/dist/browser/dist-Ha_NNo7z.js.map +1 -0
  13. package/dist/browser/{document-drive-IdFV1QXL.js → document-drive-BgXuuZ9v.js} +1184 -122
  14. package/dist/browser/document-drive-BgXuuZ9v.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-DHPXrcLc.js +25 -0
  19. package/dist/browser/editor-DHPXrcLc.js.map +1 -0
  20. package/dist/browser/{editor-DiZF3ao3.js → editor-XuCmPGuB.js} +671 -236
  21. package/dist/browser/editor-XuCmPGuB.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-Cy-QxsDg.mjs → browser/folder-view-CuDz6ylG.js} +73 -46
  26. package/dist/browser/folder-view-CuDz6ylG.js.map +1 -0
  27. package/dist/browser/{graphql-editor-ZLRO_8Ce.js → graphql-editor-DSVq4B4o.js} +8 -7
  28. package/dist/browser/{graphql-editor-ZLRO_8Ce.js.map → graphql-editor-DSVq4B4o.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-DBuZ6gN7.js → json-editor-CKhR3Fvh.js} +4 -4
  34. package/dist/browser/{json-editor-DBuZ6gN7.js.map → json-editor-CKhR3Fvh.js.map} +1 -1
  35. package/dist/browser/{lib-C-f3izXz.js → lib-DMgQj1v2.js} +13 -4
  36. package/dist/browser/lib-DMgQj1v2.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-BjQKM498.js → state-schemas-D0_9u4nu.js} +8 -18
  42. package/dist/browser/state-schemas-D0_9u4nu.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-KcYZcy_Z.mjs → connect-DOD5zQrl.mjs} +916 -200
  46. package/dist/node/connect-DOD5zQrl.mjs.map +1 -0
  47. package/dist/node/{dist-DJEK2WVi.mjs → dist-CNlIJlyu.mjs} +1992 -1451
  48. package/dist/node/dist-CNlIJlyu.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-C8hbqQ3C.mjs → document-drive-BV8zVgUr.mjs} +1184 -122
  54. package/dist/node/document-drive-BV8zVgUr.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-BIIW42CR.mjs +25 -0
  59. package/dist/node/editor-BIIW42CR.mjs.map +1 -0
  60. package/dist/node/{editor-B1KhoF1f.mjs → editor-BznTtugG.mjs} +672 -237
  61. package/dist/node/editor-BznTtugG.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-DMFqcJhc.js → node/folder-view-WvkfzzHI.mjs} +73 -46
  66. package/dist/node/folder-view-WvkfzzHI.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-C5VLRqEf.mjs → graphql-editor-aDsDHPSg.mjs} +7 -7
  70. package/dist/node/{graphql-editor-C5VLRqEf.mjs.map → graphql-editor-aDsDHPSg.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-iI2s9a_4.mjs → json-editor-hK4xilEL.mjs} +4 -4
  76. package/dist/node/{json-editor-iI2s9a_4.mjs.map → json-editor-hK4xilEL.mjs.map} +1 -1
  77. package/dist/node/{main-D82dkD7g.mjs → main-DutzjcaZ.mjs} +15 -6
  78. package/dist/node/main-DutzjcaZ.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-Bl7nA8bB.mjs → state-schemas-CQ4bprzx.mjs} +10 -20
  82. package/dist/{browser/state-schemas-BjQKM498.js.map → node/state-schemas-CQ4bprzx.mjs.map} +1 -1
  83. package/package.json +8 -7
  84. package/dist/browser/connect-KEU-HR3o.js.map +0 -1
  85. package/dist/browser/dist-D5ra2aRj.js.map +0 -1
  86. package/dist/browser/document-drive-IdFV1QXL.js.map +0 -1
  87. package/dist/browser/documents-D4ek7Ubv.js.map +0 -1
  88. package/dist/browser/editor-DiZF3ao3.js.map +0 -1
  89. package/dist/browser/editor-SqNULDP-.js +0 -29
  90. package/dist/browser/editor-SqNULDP-.js.map +0 -1
  91. package/dist/browser/folder-view-DMFqcJhc.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-KcYZcy_Z.mjs.map +0 -1
  95. package/dist/node/dist-DJEK2WVi.mjs.map +0 -1
  96. package/dist/node/document-drive-C8hbqQ3C.mjs.map +0 -1
  97. package/dist/node/editor-B1KhoF1f.mjs.map +0 -1
  98. package/dist/node/editor-yBGEvMGD.mjs +0 -29
  99. package/dist/node/editor-yBGEvMGD.mjs.map +0 -1
  100. package/dist/node/folder-view-Cy-QxsDg.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-Bl7nA8bB.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-aaTmfxFW.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();
@@ -2946,6 +2980,103 @@ function castDraft(value) {
2946
2980
  }
2947
2981
  //#endregion
2948
2982
  //#region ../shared/dist/document-model/index.js
2983
+ /**
2984
+ * What separates a signature's params when it travels as one string.
2985
+ *
2986
+ * GraphQL declares `signatures` as a list of strings, not a list of lists, so a
2987
+ * tuple is joined for transport and split on arrival. The separator is here so
2988
+ * the two halves cannot disagree about it - they live in different packages, and
2989
+ * a mismatch would corrupt every signature that crossed the wire rather than
2990
+ * failing outright.
2991
+ */
2992
+ const SIGNATURE_PARAM_SEPARATOR = ", ";
2993
+ /** The number of params a signature carries. */
2994
+ const SIGNATURE_PARAM_COUNT = 5;
2995
+ /** Joins a signature's params for transport. Already-joined input passes through. */
2996
+ function serializeSignature(signature) {
2997
+ return Array.isArray(signature) ? signature.join(SIGNATURE_PARAM_SEPARATOR) : signature;
2998
+ }
2999
+ /**
3000
+ * Splits a transported signature back into its params. A tuple passes through.
3001
+ *
3002
+ * Short input is padded rather than refused: verification reads the params by
3003
+ * position and fails on a wrong one, which says more than a length complaint
3004
+ * raised here would.
3005
+ */
3006
+ function deserializeSignature(signature) {
3007
+ if (Array.isArray(signature)) return signature;
3008
+ const parts = signature.split(SIGNATURE_PARAM_SEPARATOR);
3009
+ return Array.from({ length: SIGNATURE_PARAM_COUNT }, (_unused, index) => parts[index] ?? "");
3010
+ }
3011
+ /**
3012
+ * Projects an action onto the fields the GraphQL `ActionInput` declares.
3013
+ *
3014
+ * A projection rather than a spread, because an input object rejects a field it
3015
+ * does not declare, and that refusal takes the whole request with it. An action
3016
+ * read back out of storage can carry fields the type no longer has - a legacy
3017
+ * `attachments` array, or the operation fields left behind by a signing helper
3018
+ * that returns an operation - and any one of them would sink an otherwise valid
3019
+ * submission.
3020
+ *
3021
+ * Only fields the action actually carries are emitted, so an unsigned action
3022
+ * sends no context at all rather than a context full of nulls.
3023
+ */
3024
+ function toTransportAction(action) {
3025
+ if (action.input === void 0 || action.input === null) throw new Error(`Action ${action.id} (${action.type}) has no input, which the wire requires`);
3026
+ const projected = {
3027
+ id: action.id,
3028
+ type: action.type,
3029
+ timestampUtcMs: action.timestampUtcMs,
3030
+ input: action.input,
3031
+ scope: action.scope
3032
+ };
3033
+ const context = toTransportContext(action.context);
3034
+ return context ? {
3035
+ ...projected,
3036
+ context
3037
+ } : projected;
3038
+ }
3039
+ function toTransportContext(context) {
3040
+ if (!context) return;
3041
+ const projected = {};
3042
+ if (context.prevOpIndex !== void 0) projected.prevOpIndex = context.prevOpIndex;
3043
+ if (context.prevOpHash !== void 0) projected.prevOpHash = context.prevOpHash;
3044
+ if (context.nonce !== void 0) projected.nonce = context.nonce;
3045
+ const signer = context.signer;
3046
+ if (signer) projected.signer = {
3047
+ ...signer.user ? { user: toTransportSignerUser(signer.user) } : {},
3048
+ ...signer.app ? { app: toTransportSignerApp(signer.app) } : {},
3049
+ signatures: (signer.signatures ?? []).map(serializeSignature)
3050
+ };
3051
+ return Object.keys(projected).length > 0 ? projected : void 0;
3052
+ }
3053
+ /**
3054
+ * The identity, projected for the same reason the context around it is.
3055
+ *
3056
+ * A signer is handed in by the app, so what reaches here is only as narrow as
3057
+ * whoever built it: an identity carrying a session's DID, credential or profile
3058
+ * alongside the address is refused by `ReactorSignerUserInput`, and that
3059
+ * refusal takes the whole submission with it.
3060
+ *
3061
+ * The compiler cannot stand in for this. `UserActionSigner` already declares
3062
+ * exactly these three fields, but excess-property checks apply to fresh object
3063
+ * literals and never to a variable of a wider type, so a wide identity assigned
3064
+ * to the narrow type passes untouched.
3065
+ */
3066
+ function toTransportSignerUser(user) {
3067
+ return {
3068
+ address: user.address,
3069
+ networkId: user.networkId,
3070
+ chainId: user.chainId
3071
+ };
3072
+ }
3073
+ /** The signing app, projected on the same rule as the identity above. */
3074
+ function toTransportSignerApp(app) {
3075
+ return {
3076
+ name: app.name,
3077
+ key: app.key
3078
+ };
3079
+ }
2949
3080
  var InvalidActionInputError = class extends Error {
2950
3081
  data;
2951
3082
  constructor(data) {
@@ -2978,6 +3109,75 @@ var DowngradeNotSupportedError = class extends Error {
2978
3109
  this.toVersion = toVersion;
2979
3110
  }
2980
3111
  };
3112
+ /**
3113
+ * Thrown when INITIALIZE_AUTH is applied to an already-initialized auth scope.
3114
+ * The genesis action is valid only at auth revision zero.
3115
+ */
3116
+ var AuthAlreadyInitializedError = class extends Error {
3117
+ documentId;
3118
+ constructor(documentId) {
3119
+ super(`Auth scope already initialized for document ${documentId}: INITIALIZE_AUTH is valid only at auth revision zero`);
3120
+ this.name = "AuthAlreadyInitializedError";
3121
+ this.documentId = documentId;
3122
+ }
3123
+ };
3124
+ /**
3125
+ * Thrown when INITIALIZE_AUTH is not signed by the document creator (its signer
3126
+ * does not match `header.sig.publicKey`), so it cannot set the auth policy.
3127
+ */
3128
+ var AuthInitializerNotCreatorError = class extends Error {
3129
+ documentId;
3130
+ constructor(documentId) {
3131
+ super(`INITIALIZE_AUTH for document ${documentId} must be signed by the document creator`);
3132
+ this.name = "AuthInitializerNotCreatorError";
3133
+ this.documentId = documentId;
3134
+ }
3135
+ };
3136
+ /**
3137
+ * Thrown when INITIALIZE_AUTH carries a version below 1. Version 0 is reserved
3138
+ * for the uninitialized auth scope.
3139
+ */
3140
+ var InvalidAuthVersionError = class extends Error {
3141
+ documentId;
3142
+ version;
3143
+ constructor(documentId, version) {
3144
+ super(`Invalid auth policy version ${version} for document ${documentId}: INITIALIZE_AUTH requires an integer version >= 1`);
3145
+ this.name = "InvalidAuthVersionError";
3146
+ this.documentId = documentId;
3147
+ this.version = version;
3148
+ }
3149
+ };
3150
+ /** Thrown when a duplicate would lose the source policy's version or creator binding. */
3151
+ var AuthPolicyNotPreservedError = class extends Error {
3152
+ documentId;
3153
+ constructor(documentId) {
3154
+ super(`Duplicating document ${documentId} would not preserve its auth policy: the copy loses the policy version or its creator binding`);
3155
+ this.name = "AuthPolicyNotPreservedError";
3156
+ this.documentId = documentId;
3157
+ }
3158
+ };
3159
+ /**
3160
+ * Thrown when a grant referenced by REMOVE_GRANT or MOVE_GRANT does not exist.
3161
+ */
3162
+ var GrantNotFoundError = class extends Error {
3163
+ grantId;
3164
+ constructor(grantId) {
3165
+ super(`Grant not found in auth scope: ${grantId}`);
3166
+ this.name = "GrantNotFoundError";
3167
+ this.grantId = grantId;
3168
+ }
3169
+ };
3170
+ /**
3171
+ * Thrown when a disallowed action (UNDO, REDO, PRUNE) targets the auth scope.
3172
+ */
3173
+ var AuthActionNotAllowedError = class extends Error {
3174
+ actionType;
3175
+ constructor(actionType) {
3176
+ super(`${actionType} is not permitted on the auth scope`);
3177
+ this.name = "AuthActionNotAllowedError";
3178
+ this.actionType = actionType;
3179
+ }
3180
+ };
2981
3181
  var HashMismatchError = class extends Error {
2982
3182
  _scope;
2983
3183
  _document;
@@ -3004,6 +3204,25 @@ var HashMismatchError = class extends Error {
3004
3204
  return this._operation;
3005
3205
  }
3006
3206
  };
3207
+ /**
3208
+ * Thrown when replay or import requires a document model version that is not
3209
+ * registered. Carries the data the UI needs to explain the mismatch.
3210
+ */
3211
+ var UnsupportedDocumentModelVersionError = class extends Error {
3212
+ documentType;
3213
+ requiredVersion;
3214
+ availableVersions;
3215
+ constructor(documentType, requiredVersion, availableVersions) {
3216
+ super(`No reducer registered for document version ${requiredVersion}. Available versions: ${availableVersions.join(", ")}`);
3217
+ this.name = "UnsupportedDocumentModelVersionError";
3218
+ this.documentType = documentType;
3219
+ this.requiredVersion = requiredVersion;
3220
+ this.availableVersions = availableVersions;
3221
+ }
3222
+ static isError(error) {
3223
+ return Error.isError(error) && error.name === "UnsupportedDocumentModelVersionError";
3224
+ }
3225
+ };
3007
3226
  const isDefinedNonNullAny$1 = (v) => v !== void 0 && v !== null;
3008
3227
  any().refine((v) => isDefinedNonNullAny$1(v));
3009
3228
  const Load_StateSchema = _enum(["LOAD_STATE"]);
@@ -3444,6 +3663,88 @@ const ConfigEntrySchema = object({
3444
3663
  required: boolean().optional(),
3445
3664
  default: boolean().optional()
3446
3665
  });
3666
+ const PwaUrlPatternSchema = union([string(), strictObject({
3667
+ source: string(),
3668
+ flags: string().optional()
3669
+ }).refine((p) => {
3670
+ try {
3671
+ new RegExp(p.source, p.flags);
3672
+ return true;
3673
+ } catch {
3674
+ return false;
3675
+ }
3676
+ }, { message: "source/flags do not compile to a valid RegExp" })]);
3677
+ const PwaRuntimeCachingSchema = strictObject({
3678
+ urlPattern: PwaUrlPatternSchema,
3679
+ handler: _enum([
3680
+ "CacheFirst",
3681
+ "CacheOnly",
3682
+ "NetworkFirst",
3683
+ "NetworkOnly",
3684
+ "StaleWhileRevalidate"
3685
+ ]),
3686
+ method: _enum([
3687
+ "GET",
3688
+ "POST",
3689
+ "PUT",
3690
+ "DELETE",
3691
+ "HEAD",
3692
+ "PATCH"
3693
+ ]).optional(),
3694
+ options: strictObject({
3695
+ cacheName: string().optional(),
3696
+ networkTimeoutSeconds: number().optional(),
3697
+ expiration: strictObject({
3698
+ maxEntries: number().optional(),
3699
+ maxAgeSeconds: number().optional()
3700
+ }).optional(),
3701
+ cacheableResponse: strictObject({
3702
+ statuses: array(number()).optional(),
3703
+ headers: record(string(), string()).optional()
3704
+ }).optional()
3705
+ }).optional()
3706
+ });
3707
+ const PwaIconSchema = strictObject({
3708
+ src: string(),
3709
+ sizes: string().optional(),
3710
+ type: string().optional(),
3711
+ purpose: string().optional()
3712
+ });
3713
+ const PwaFileHandlerSchema = strictObject({
3714
+ accept: record(string(), array(string().regex(/^\./, "file extensions must start with '.'"))),
3715
+ icons: array(PwaIconSchema).optional(),
3716
+ launch_type: _enum(["single-client", "multiple-clients"]).optional()
3717
+ });
3718
+ const PwaConfigSchema = strictObject({
3719
+ manifest: strictObject({
3720
+ name: string().optional(),
3721
+ short_name: string().optional(),
3722
+ description: string().optional(),
3723
+ theme_color: string().optional(),
3724
+ background_color: string().optional(),
3725
+ display: _enum([
3726
+ "fullscreen",
3727
+ "standalone",
3728
+ "minimal-ui",
3729
+ "browser"
3730
+ ]).optional(),
3731
+ start_url: string().optional(),
3732
+ scope: string().optional(),
3733
+ icons: array(PwaIconSchema).optional(),
3734
+ file_handlers: array(PwaFileHandlerSchema).optional(),
3735
+ launch_handler: strictObject({ client_mode: _enum([
3736
+ "auto",
3737
+ "focus-existing",
3738
+ "navigate-existing",
3739
+ "navigate-new"
3740
+ ]) }).optional()
3741
+ }).optional(),
3742
+ globPatterns: array(string()).optional(),
3743
+ globIgnores: array(string()).optional(),
3744
+ maximumFileSizeToCacheInBytes: number().optional(),
3745
+ runtimeCaching: array(PwaRuntimeCachingSchema).optional(),
3746
+ navigateFallbackDenylist: array(PwaUrlPatternSchema).optional()
3747
+ });
3447
3748
  object({
3448
3749
  name: string(),
3449
3750
  description: string().optional(),
@@ -3455,7 +3756,8 @@ object({
3455
3756
  editors: PowerhouseModulesSchema,
3456
3757
  processors: PowerhouseModulesSchema,
3457
3758
  subgraphs: PowerhouseModulesSchema,
3458
- config: array(ConfigEntrySchema).optional()
3759
+ config: array(ConfigEntrySchema).optional(),
3760
+ pwa: PwaConfigSchema.optional()
3459
3761
  });
3460
3762
  /**
3461
3763
  * Cancels the last `count` operations.
@@ -3726,6 +4028,505 @@ const actions = {
3726
4028
  ...baseActions,
3727
4029
  ...documentModelActions
3728
4030
  };
4031
+ const documentModelDocumentType = "powerhouse/document-model";
4032
+ /**
4033
+ * Thrown when a grant violates the v1 validation rules. The message is stored
4034
+ * on error operations, so it must be a pure function of the input.
4035
+ */
4036
+ var InvalidGrantError = class extends Error {
4037
+ grantId;
4038
+ constructor(grantId, problem) {
4039
+ super(`Invalid grant "${grantId}": ${problem}`);
4040
+ this.name = "InvalidGrantError";
4041
+ this.grantId = grantId;
4042
+ }
4043
+ };
4044
+ /** Thrown for a `{ group }` principal on a group document: references never chain. */
4045
+ var GroupPrincipalNotAllowedError = class extends Error {
4046
+ grantId;
4047
+ constructor(grantId) {
4048
+ super(`Grant "${grantId}" uses a group principal on a group document: a group's auth scope cannot reference other groups`);
4049
+ this.name = "GroupPrincipalNotAllowedError";
4050
+ this.grantId = grantId;
4051
+ }
4052
+ };
4053
+ /**
4054
+ * Thrown when a change would leave a creator-less policy with no grant
4055
+ * permitting execute on the auth scope. Without the creator carve-out no
4056
+ * subject could ever administer such a policy again.
4057
+ */
4058
+ var AuthAdministrationLockoutError = class extends Error {
4059
+ grantId;
4060
+ constructor(grantId) {
4061
+ 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`);
4062
+ this.name = "AuthAdministrationLockoutError";
4063
+ this.grantId = grantId;
4064
+ }
4065
+ };
4066
+ /**
4067
+ * Thrown when INITIALIZE_AUTH would create a creator-less policy with no grant
4068
+ * permitting execute on the auth scope. Such a policy would be born with no
4069
+ * subject able to administer it.
4070
+ */
4071
+ var AuthAdministrationMissingError = class extends Error {
4072
+ constructor() {
4073
+ super("Initial grants include no reachable grant permitting execute on the auth scope: a policy with no creator must always include one");
4074
+ this.name = "AuthAdministrationMissingError";
4075
+ }
4076
+ };
4077
+ const GRANT_KEYS = new Set([
4078
+ "id",
4079
+ "description",
4080
+ "effect",
4081
+ "principal",
4082
+ "capability",
4083
+ "where"
4084
+ ]);
4085
+ const PRINCIPAL_KINDS = new Set([
4086
+ "anyone",
4087
+ "address",
4088
+ "group",
4089
+ "match"
4090
+ ]);
4091
+ const COMPARISON_CONDITION_KINDS = new Set([
4092
+ "eq",
4093
+ "ne",
4094
+ "lt",
4095
+ "lte",
4096
+ "gt",
4097
+ "gte"
4098
+ ]);
4099
+ function isPlainValue(value) {
4100
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4101
+ }
4102
+ function operandProblem(value, capabilityScope, budget) {
4103
+ budget.nodes -= 1;
4104
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
4105
+ if (!isPlainValue(value)) return "operand must be an object";
4106
+ const keys = Object.keys(value);
4107
+ if (keys.length !== 1) return "operand must have exactly one of attr or lit";
4108
+ if (keys[0] === "attr") {
4109
+ const attr = value.attr;
4110
+ if (typeof attr !== "string" || attr.length === 0) return "attr must be a non-empty string";
4111
+ if (capabilityScope !== void 0 && capabilityScope !== "*" && attr.startsWith("doc.")) {
4112
+ const pathScope = attr.split(".")[1] ?? "";
4113
+ if (pathScope !== capabilityScope) return `condition path "${attr}" reads scope "${pathScope}" but the capability covers only scope "${capabilityScope}"`;
4114
+ }
4115
+ return null;
4116
+ }
4117
+ if (keys[0] === "lit") {
4118
+ const lit = value.lit;
4119
+ if (lit !== null && typeof lit !== "string" && typeof lit !== "number" && typeof lit !== "boolean") return "lit must be a string, number, boolean, or null";
4120
+ if (typeof lit === "number" && !Number.isFinite(lit)) return "lit must be a finite number";
4121
+ if (typeof lit === "number" && Object.is(lit, -0)) return "lit must not be negative zero";
4122
+ return null;
4123
+ }
4124
+ return `unknown operand kind "${keys[0]}"`;
4125
+ }
4126
+ function conditionProblem(value, capabilityScope, depth, budget) {
4127
+ if (depth > 10) return `condition exceeds depth 10`;
4128
+ budget.nodes -= 1;
4129
+ if (budget.nodes < 0) return `condition exceeds 100 nodes`;
4130
+ if (!isPlainValue(value)) return "condition must be an object";
4131
+ const keys = Object.keys(value);
4132
+ if (keys.length !== 1) return "condition must have exactly one operator";
4133
+ const kind = keys[0];
4134
+ const body = value[kind];
4135
+ if (COMPARISON_CONDITION_KINDS.has(kind)) {
4136
+ if (!Array.isArray(body) || body.length !== 2) return `${kind} requires a pair of operands`;
4137
+ for (const operand of body) {
4138
+ const problem = operandProblem(operand, capabilityScope, budget);
4139
+ if (problem !== null) return problem;
4140
+ }
4141
+ return null;
4142
+ }
4143
+ if (kind === "in" || kind === "notIn") {
4144
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return `${kind} requires an operand and an operand list`;
4145
+ const first = operandProblem(body[0], capabilityScope, budget);
4146
+ if (first !== null) return first;
4147
+ for (const operand of body[1]) {
4148
+ const problem = operandProblem(operand, capabilityScope, budget);
4149
+ if (problem !== null) return problem;
4150
+ }
4151
+ return null;
4152
+ }
4153
+ if (kind === "exists") return operandProblem(body, capabilityScope, budget);
4154
+ if (kind === "and" || kind === "or") {
4155
+ if (!Array.isArray(body)) return `${kind} requires a condition list`;
4156
+ for (const child of body) {
4157
+ const problem = conditionProblem(child, capabilityScope, depth + 1, budget);
4158
+ if (problem !== null) return problem;
4159
+ }
4160
+ return null;
4161
+ }
4162
+ if (kind === "not") return conditionProblem(body, capabilityScope, depth + 1, budget);
4163
+ return `unknown condition operator "${kind}"`;
4164
+ }
4165
+ function principalProblem(value, capabilityScope) {
4166
+ if (!isPlainValue(value)) return "principal must be an object";
4167
+ const keys = Object.keys(value);
4168
+ if (keys.length !== 1 || !PRINCIPAL_KINDS.has(keys[0])) return "principal must have exactly one of anyone, address, group, or match";
4169
+ const kind = keys[0];
4170
+ if (kind === "anyone" && value.anyone !== true) return "anyone must be true";
4171
+ if (kind === "address") {
4172
+ const address = value.address;
4173
+ if (typeof address !== "string" || address.length === 0) return "address must be a non-empty string";
4174
+ }
4175
+ if (kind === "group") {
4176
+ const group = value.group;
4177
+ if (typeof group !== "string" || group.length === 0) return "group must be a non-empty string";
4178
+ }
4179
+ if (kind === "match") return conditionProblem(value.match, capabilityScope, 1, { nodes: 100 });
4180
+ return null;
4181
+ }
4182
+ function capabilityProblem(value) {
4183
+ if (!isPlainValue(value)) return "capability must be an object";
4184
+ const can = value.can;
4185
+ if (can !== "read" && can !== "execute") return "capability.can must be read or execute";
4186
+ const allowedKeys = can === "execute" ? [
4187
+ "can",
4188
+ "scope",
4189
+ "operation"
4190
+ ] : ["can", "scope"];
4191
+ const unknownKeys = Object.keys(value).filter((key) => !allowedKeys.includes(key)).sort();
4192
+ if (unknownKeys.length > 0) return `unknown capability key "${unknownKeys[0]}"`;
4193
+ if (value.scope !== void 0) {
4194
+ if (typeof value.scope !== "string" || value.scope.length === 0) return "capability.scope must be a non-empty string";
4195
+ }
4196
+ if (can === "execute" && value.operation !== void 0) {
4197
+ const operation = value.operation;
4198
+ if (!Array.isArray(operation)) return "capability.operation must be an array";
4199
+ if (operation.length > 100) return `capability.operation exceeds 100 entries`;
4200
+ for (const entry of operation) if (typeof entry !== "string" || entry.length === 0) return "capability.operation entries must be non-empty strings";
4201
+ }
4202
+ return null;
4203
+ }
4204
+ /** Returns the first v1-rule violation, or null. Pure, total, deterministic. */
4205
+ function grantProblem(value) {
4206
+ if (!isPlainValue(value)) return "grant must be an object";
4207
+ const unknownKeys = Object.keys(value).filter((key) => !GRANT_KEYS.has(key)).sort();
4208
+ if (unknownKeys.length > 0) return `unknown grant key "${unknownKeys[0]}"`;
4209
+ if (typeof value.id !== "string" || value.id.length === 0) return "id must be a non-empty string";
4210
+ if (typeof value.description !== "string") return "description must be a string";
4211
+ if (value.effect !== "allow" && value.effect !== "deny") return "effect must be allow or deny";
4212
+ const capabilityValue = value.capability;
4213
+ const capability = capabilityProblem(capabilityValue);
4214
+ if (capability !== null) return capability;
4215
+ const capabilityScope = capabilityValue.scope;
4216
+ const principal = principalProblem(value.principal, capabilityScope);
4217
+ if (principal !== null) return principal;
4218
+ if (value.where !== void 0) return conditionProblem(value.where, capabilityScope, 1, { nodes: 100 });
4219
+ return null;
4220
+ }
4221
+ /** V1 shape rules plus the group-document group-principal ban. */
4222
+ function assertValidGrant(grant, documentType) {
4223
+ const grantId = isPlainValue(grant) && typeof grant.id === "string" ? grant.id : "";
4224
+ const problem = grantProblem(grant);
4225
+ if (problem !== null) throw new InvalidGrantError(grantId, problem);
4226
+ if (documentType === "powerhouse/reactor-group" && "group" in grant.principal) throw new GroupPrincipalNotAllowedError(grantId);
4227
+ }
4228
+ /**
4229
+ * Validates an initial grant list: the count cap, every grant, and — on a
4230
+ * creator-less policy — that some grant keeps the auth scope administrable.
4231
+ */
4232
+ function assertValidInitialGrants(grants, documentType, creator) {
4233
+ if (grants.length > 100) throw new InvalidGrantError("", `policy exceeds 100 grants`);
4234
+ for (const grant of grants) assertValidGrant(grant, documentType);
4235
+ if (creator === void 0 && !administrationReachable(grants)) throw new AuthAdministrationMissingError();
4236
+ }
4237
+ /**
4238
+ * Validates a grant upsert: the grant itself, the count cap on append, and
4239
+ * administration retention. Retention is checked on an append as well as an
4240
+ * in-place replace, because a grant appended after the administration grant can
4241
+ * shadow it (evaluation is last-applicable-grant-wins) and so take
4242
+ * administration away without removing anything.
4243
+ */
4244
+ function assertValidGrantUpsert(grant, existing, documentType, creator) {
4245
+ assertValidGrant(grant, documentType);
4246
+ const exists = existing.some((g) => g.id === grant.id);
4247
+ if (!exists && existing.length >= 100) throw new InvalidGrantError(grant.id, `policy exceeds 100 grants`);
4248
+ assertAuthAdministrationRetained(creator, existing, exists ? existing.map((g) => g.id === grant.id ? grant : g) : [...existing, grant], grant.id);
4249
+ }
4250
+ /**
4251
+ * The request whose coverage keeps a policy administrable: a subject who may
4252
+ * SET_GRANT can upsert any grant, so every other repair stays reachable.
4253
+ */
4254
+ const AUTH_ADMINISTRATION_REQUEST = {
4255
+ verb: "execute",
4256
+ scope: "auth",
4257
+ operation: "SET_GRANT"
4258
+ };
4259
+ /**
4260
+ * Whether some subject can still administer the auth scope under this grant list.
4261
+ *
4262
+ * Asks the evaluator rather than pattern-matching a single grant: evaluation is
4263
+ * last-applicable-grant-wins, so an allow that some later deny shadows keeps
4264
+ * nothing reachable even though it is still present in the list. Only anyone and
4265
+ * address principals are candidates, because those are the ones v1 can match at
4266
+ * all; a `where` condition or a group or match principal never applies.
4267
+ */
4268
+ function administrationReachable(grants) {
4269
+ return grants.some((grant) => {
4270
+ const subject = administrationCandidate(grant);
4271
+ if (subject === void 0) return false;
4272
+ return evaluateGrantStack(grants, subject, AUTH_ADMINISTRATION_REQUEST).decision === "allow";
4273
+ });
4274
+ }
4275
+ /**
4276
+ * The subject to test this grant with, or undefined when the grant could never
4277
+ * carry administration for anyone.
4278
+ */
4279
+ function administrationCandidate(grant) {
4280
+ if (grant.effect !== "allow" || grant.where !== void 0 || !capabilityCovers(grant.capability, AUTH_ADMINISTRATION_REQUEST)) return;
4281
+ if ("address" in grant.principal) return {
4282
+ address: grant.principal.address,
4283
+ key: void 0
4284
+ };
4285
+ if ("anyone" in grant.principal) return {
4286
+ address: void 0,
4287
+ key: void 0
4288
+ };
4289
+ }
4290
+ /**
4291
+ * A creator-less policy must always retain a grant permitting execute on the
4292
+ * auth scope; on a signed document the creator carve-out keeps administration
4293
+ * reachable instead. Rejects a change that takes the last such grant away. A
4294
+ * policy already without one is left alone: the change is not what locks it.
4295
+ */
4296
+ function assertAuthAdministrationRetained(creator, previous, next, grantId) {
4297
+ if (creator !== void 0) return;
4298
+ if (administrationReachable(previous) && !administrationReachable(next)) throw new AuthAdministrationLockoutError(grantId);
4299
+ }
4300
+ /**
4301
+ * An operand whose shape validation would have rejected. Distinguished from
4302
+ * an unresolved path so a structurally malformed operand poisons its whole
4303
+ * condition to false rather than reading as "absent", which `not` would
4304
+ * otherwise widen to true.
4305
+ */
4306
+ const INVALID_OPERAND = Symbol("invalid-operand");
4307
+ /**
4308
+ * Narrows to the values conditions compare. An object, array, or non-finite
4309
+ * number resolves to undefined, and every comparison involving undefined is
4310
+ * false.
4311
+ */
4312
+ function asConditionValue(value) {
4313
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4314
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4315
+ }
4316
+ /**
4317
+ * Resolves one operand. Attr roots: `subject.*`, `doc.<scope>.*` where the
4318
+ * scope must be the executing scope (validation already rejects any other,
4319
+ * but resolution stays total), and `action.input.*`. Path steps read own
4320
+ * properties only, so prototype members can never influence a verdict.
4321
+ */
4322
+ function resolveOperand(operand, subject, request, conditions) {
4323
+ if (!isPlainValue(operand)) return INVALID_OPERAND;
4324
+ const keys = Object.keys(operand);
4325
+ if (keys.length !== 1) return INVALID_OPERAND;
4326
+ if (keys[0] === "lit") {
4327
+ const value = asConditionValue(operand.lit);
4328
+ return value === void 0 ? INVALID_OPERAND : value;
4329
+ }
4330
+ if (keys[0] !== "attr") return INVALID_OPERAND;
4331
+ const attr = operand.attr;
4332
+ if (typeof attr !== "string" || attr.length === 0) return INVALID_OPERAND;
4333
+ const path = attr.split(".");
4334
+ let value;
4335
+ let rest;
4336
+ if (path[0] === "subject") {
4337
+ value = subject;
4338
+ rest = path.slice(1);
4339
+ } else if (path[0] === "doc") {
4340
+ if (path[1] !== request.scope) return;
4341
+ value = conditions.scopeState;
4342
+ rest = path.slice(2);
4343
+ } else if (path[0] === "action" && path[1] === "input") {
4344
+ value = conditions.actionInput;
4345
+ rest = path.slice(2);
4346
+ } else return;
4347
+ for (const segment of rest) {
4348
+ if (!isPlainValue(value) || !Object.hasOwn(value, segment)) return;
4349
+ value = value[segment];
4350
+ }
4351
+ return asConditionValue(value);
4352
+ }
4353
+ /**
4354
+ * Total order within one type: numbers numerically, strings by code point.
4355
+ * Everything else, including mixed types, does not order.
4356
+ */
4357
+ function compareValues(left, right) {
4358
+ if (typeof left === "number" && typeof right === "number") return left < right ? -1 : left > right ? 1 : 0;
4359
+ if (typeof left === "string" && typeof right === "string") {
4360
+ const leftPoints = Array.from(left);
4361
+ const rightPoints = Array.from(right);
4362
+ const shared = Math.min(leftPoints.length, rightPoints.length);
4363
+ for (let i = 0; i < shared; i++) {
4364
+ const a = leftPoints[i].codePointAt(0) ?? 0;
4365
+ const b = rightPoints[i].codePointAt(0) ?? 0;
4366
+ if (a !== b) return a < b ? -1 : 1;
4367
+ }
4368
+ return leftPoints.length === rightPoints.length ? 0 : leftPoints.length < rightPoints.length ? -1 : 1;
4369
+ }
4370
+ }
4371
+ /**
4372
+ * Tri-state evaluation: undefined marks a structurally invalid node, which
4373
+ * poisons the whole tree to false at the top — and a structurally malformed
4374
+ * operand poisons its condition the same way. Both are distinct from an
4375
+ * operand whose path fails to resolve, which is a valid comparison that is
4376
+ * false. The distinction keeps `not` from widening over malformed input.
4377
+ */
4378
+ function evaluateNode(node, subject, request, conditions) {
4379
+ if (!isPlainValue(node)) return;
4380
+ const keys = Object.keys(node);
4381
+ if (keys.length !== 1) return;
4382
+ const kind = keys[0];
4383
+ const body = node[kind];
4384
+ switch (kind) {
4385
+ case "eq":
4386
+ case "ne":
4387
+ case "lt":
4388
+ case "lte":
4389
+ case "gt":
4390
+ case "gte": {
4391
+ if (!Array.isArray(body) || body.length !== 2) return;
4392
+ const left = resolveOperand(body[0], subject, request, conditions);
4393
+ const right = resolveOperand(body[1], subject, request, conditions);
4394
+ if (left === INVALID_OPERAND || right === INVALID_OPERAND) return;
4395
+ if (left === void 0 || right === void 0) return false;
4396
+ if (kind === "eq") return left === right;
4397
+ if (kind === "ne") return left !== right;
4398
+ const order = compareValues(left, right);
4399
+ if (order === void 0) return false;
4400
+ switch (kind) {
4401
+ case "lt": return order < 0;
4402
+ case "lte": return order <= 0;
4403
+ case "gt": return order > 0;
4404
+ case "gte": return order >= 0;
4405
+ }
4406
+ return;
4407
+ }
4408
+ case "in":
4409
+ case "notIn": {
4410
+ if (!Array.isArray(body) || body.length !== 2 || !Array.isArray(body[1])) return;
4411
+ const left = resolveOperand(body[0], subject, request, conditions);
4412
+ if (left === INVALID_OPERAND) return;
4413
+ const elements = body[1].map((element) => resolveOperand(element, subject, request, conditions));
4414
+ if (elements.some((value) => value === INVALID_OPERAND)) return;
4415
+ if (left === void 0) return false;
4416
+ const found = elements.some((value) => value !== void 0 && value === left);
4417
+ return kind === "in" ? found : !found;
4418
+ }
4419
+ case "exists": {
4420
+ const value = resolveOperand(body, subject, request, conditions);
4421
+ if (value === INVALID_OPERAND) return;
4422
+ return value !== void 0;
4423
+ }
4424
+ case "and":
4425
+ case "or": {
4426
+ if (!Array.isArray(body)) return;
4427
+ let result = kind === "and";
4428
+ for (const child of body) {
4429
+ const value = evaluateNode(child, subject, request, conditions);
4430
+ if (value === void 0) return;
4431
+ if (kind === "and") result = result && value;
4432
+ else result = result || value;
4433
+ }
4434
+ return result;
4435
+ }
4436
+ case "not": {
4437
+ const value = evaluateNode(body, subject, request, conditions);
4438
+ return value === void 0 ? void 0 : !value;
4439
+ }
4440
+ default: return;
4441
+ }
4442
+ }
4443
+ /**
4444
+ * Evaluates a version-1 condition. Deterministic, total, and pure: any input
4445
+ * shape yields a boolean and never throws, and a malformed condition is
4446
+ * false. These are consensus semantics, versioned by `PHAuthState.version`;
4447
+ * changing them requires a new version.
4448
+ */
4449
+ function evaluateCondition(condition, subject, request, conditions) {
4450
+ return evaluateNode(condition, subject, request, conditions) === true;
4451
+ }
4452
+ /** Whether a capability's scope reaches the requested one. */
4453
+ function scopeCovers(scope, requested) {
4454
+ return scope === void 0 || scope === "*" || scope === requested;
4455
+ }
4456
+ /**
4457
+ * Whether one grant answers this request.
4458
+ *
4459
+ * A grant allowing execute on a scope also allows reading it: executing an
4460
+ * operation means reading the state it applies to, so permitting the write while
4461
+ * withholding the read would describe an access nobody could use. The converse
4462
+ * does not hold -- a read grant confers no write.
4463
+ *
4464
+ * Only an allow carries across. A deny on execute withholds the write and says
4465
+ * nothing about the read, so a policy locking writes down does not silently
4466
+ * revoke a read grant sitting before it. The operation list is not consulted
4467
+ * either: it restricts which operations may be executed, not whether the scope
4468
+ * is visible, and a read carries no operation to match against.
4469
+ *
4470
+ * Reads are not consensus -- no replica records a read, and the two read call
4471
+ * sites are both inside the read gate -- so this rule is not part of what makes
4472
+ * an operation valid, and does not need a policy version of its own.
4473
+ */
4474
+ function grantAnswers(grant, request) {
4475
+ if (capabilityCovers(grant.capability, request)) return true;
4476
+ return request.verb === "read" && grant.effect === "allow" && grant.capability.can === "execute" && scopeCovers(grant.capability.scope, request.scope);
4477
+ }
4478
+ function capabilityCovers(capability, request) {
4479
+ if (capability.can !== request.verb) return false;
4480
+ if (!scopeCovers(capability.scope, request.scope)) return false;
4481
+ if (capability.can === "execute") {
4482
+ if (capability.operation === void 0) return true;
4483
+ return request.operation !== void 0 && capability.operation.includes(request.operation);
4484
+ }
4485
+ return true;
4486
+ }
4487
+ function principalMatches(principal, subject, request, groups, conditions) {
4488
+ if ("anyone" in principal) return true;
4489
+ if ("address" in principal) return subject.address !== void 0 && subject.address.toLowerCase() === principal.address.toLowerCase();
4490
+ if ("group" in principal) {
4491
+ if (groups === void 0 || subject.address === void 0) return false;
4492
+ const group = groups[principal.group];
4493
+ if (group === void 0 || !Array.isArray(group.members)) return false;
4494
+ const address = subject.address.toLowerCase();
4495
+ return group.members.some((member) => member.toLowerCase() === address);
4496
+ }
4497
+ if ("match" in principal) {
4498
+ if (conditions === void 0) return false;
4499
+ return evaluateCondition(principal.match, subject, request, conditions);
4500
+ }
4501
+ return false;
4502
+ }
4503
+ /**
4504
+ * Evaluates a v1 grant stack: default deny, last applicable grant wins, and
4505
+ * reports which grant decided it. Group principals match only against a
4506
+ * supplied groups map, and `where` clauses and { match } principals evaluate
4507
+ * only against a supplied condition context; a grant that uses an unsupplied
4508
+ * feature never applies.
4509
+ */
4510
+ function evaluateGrantStack(grants, subject, request, groups, conditions) {
4511
+ let applicable;
4512
+ for (const grant of grants) {
4513
+ if (grant.where !== void 0) {
4514
+ if (conditions === void 0) continue;
4515
+ if (!evaluateCondition(grant.where, subject, request, conditions)) continue;
4516
+ }
4517
+ if (grantAnswers(grant, request) && principalMatches(grant.principal, subject, request, groups, conditions)) applicable = grant;
4518
+ }
4519
+ if (applicable === void 0) return {
4520
+ decision: "deny",
4521
+ refusal: "no-applicable-grant"
4522
+ };
4523
+ if (applicable.effect === "deny") return {
4524
+ decision: "deny",
4525
+ refusal: "denied-by-grant",
4526
+ grantId: applicable.id
4527
+ };
4528
+ return { decision: "allow" };
4529
+ }
3729
4530
  const documentModelFileExtension = "phdm";
3730
4531
  const documentModelInitialLocalState = {};
3731
4532
  const documentModelInitialGlobalState = {
@@ -4307,7 +5108,306 @@ const documentModelGlobalState = {
4307
5108
  };
4308
5109
  const HASH_ALGORITHM_SHA1 = "sha1";
4309
5110
  const HASH_ENCODING_BASE64 = "base64";
4310
- const documentModelDocumentType = "powerhouse/document-model";
5111
+ /**
5112
+ * Creates a default PHAuthState
5113
+ */
5114
+ function defaultAuthState() {
5115
+ return {
5116
+ version: 0,
5117
+ grants: []
5118
+ };
5119
+ }
5120
+ /**
5121
+ * Creates a default PHDocumentState
5122
+ */
5123
+ function defaultDocumentState() {
5124
+ return {
5125
+ version: 0,
5126
+ hash: {
5127
+ algorithm: HASH_ALGORITHM_SHA1,
5128
+ encoding: HASH_ENCODING_BASE64
5129
+ }
5130
+ };
5131
+ }
5132
+ /**
5133
+ * Creates a default PHBaseState with auth and document properties
5134
+ */
5135
+ function defaultBaseState() {
5136
+ return {
5137
+ auth: defaultAuthState(),
5138
+ document: defaultDocumentState()
5139
+ };
5140
+ }
5141
+ /**
5142
+ * Creates a PHAuthState with the given properties
5143
+ */
5144
+ function createAuthState(auth) {
5145
+ return {
5146
+ ...defaultAuthState(),
5147
+ ...auth
5148
+ };
5149
+ }
5150
+ /**
5151
+ * Creates a PHDocumentState with the given properties
5152
+ */
5153
+ function createDocumentState(document) {
5154
+ return {
5155
+ ...defaultDocumentState(),
5156
+ ...document
5157
+ };
5158
+ }
5159
+ /**
5160
+ * Creates a PHBaseState with the given auth and document properties
5161
+ */
5162
+ function createBaseState(auth, document) {
5163
+ return {
5164
+ auth: createAuthState(auth),
5165
+ document: createDocumentState(document)
5166
+ };
5167
+ }
5168
+ /**
5169
+ * Backfills the auth scope to the default for legacy documents serialized with
5170
+ * an empty `auth`. Replaces only `state.auth`. Idempotent.
5171
+ */
5172
+ function backfillAuthState(state) {
5173
+ return {
5174
+ ...state,
5175
+ auth: createAuthState(state.auth)
5176
+ };
5177
+ }
5178
+ function defaultGlobalState() {
5179
+ return {
5180
+ ...defaultBaseState(),
5181
+ author: {
5182
+ name: "",
5183
+ website: ""
5184
+ },
5185
+ description: "",
5186
+ extension: "",
5187
+ id: "",
5188
+ name: "",
5189
+ specifications: []
5190
+ };
5191
+ }
5192
+ function defaultLocalState() {
5193
+ return {};
5194
+ }
5195
+ function createGlobalState(state) {
5196
+ return {
5197
+ ...defaultGlobalState(),
5198
+ ...state || {}
5199
+ };
5200
+ }
5201
+ function createLocalState(state) {
5202
+ return {
5203
+ ...defaultLocalState(),
5204
+ ...state || {}
5205
+ };
5206
+ }
5207
+ function createState(baseState, globalState, localState) {
5208
+ return {
5209
+ ...createBaseState(baseState?.auth, baseState?.document),
5210
+ global: createGlobalState(globalState),
5211
+ local: createLocalState(localState)
5212
+ };
5213
+ }
5214
+ /**
5215
+ * Destructuring a null input (reachable via raw synced operations) would
5216
+ * store an engine-specific TypeError message on the error operation.
5217
+ */
5218
+ function assertActionInputShape(input) {
5219
+ if (!isPlainValue(input)) throw new InvalidActionInputError({ input: "must be an object" });
5220
+ }
5221
+ function withGrants(document, grants) {
5222
+ return {
5223
+ ...document,
5224
+ state: {
5225
+ ...document.state,
5226
+ auth: {
5227
+ ...document.state.auth,
5228
+ grants
5229
+ }
5230
+ }
5231
+ };
5232
+ }
5233
+ const P256_PUBKEY_MULTICODEC = [128, 36];
5234
+ const DID_KEY_PREFIX = "did:key:z";
5235
+ function bytesEqual(a, b) {
5236
+ if (a.length !== b.length) return false;
5237
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
5238
+ return true;
5239
+ }
5240
+ /**
5241
+ * True when `signerKey` (an ActionSigner app key, a did:key) identifies the same
5242
+ * key recorded as the document creator. Returns false
5243
+ * when there is no creator (empty JWK) or no signer key.
5244
+ */
5245
+ function isDocumentCreator(creatorKey, signerKey) {
5246
+ if (!creatorKey?.x || !creatorKey.y) return false;
5247
+ if (!signerKey || !signerKey.startsWith(DID_KEY_PREFIX)) return false;
5248
+ const decoded = base58Decode(signerKey.slice(9));
5249
+ if (!decoded || decoded.length !== 35) return false;
5250
+ if (decoded[0] !== P256_PUBKEY_MULTICODEC[0] || decoded[1] !== P256_PUBKEY_MULTICODEC[1]) return false;
5251
+ const parityPrefix = decoded[2];
5252
+ if (parityPrefix !== 2 && parityPrefix !== 3) return false;
5253
+ const didX = decoded.subarray(3, 35);
5254
+ const jwkX = base64UrlToBytes(creatorKey.x);
5255
+ const jwkY = base64UrlToBytes(creatorKey.y);
5256
+ if (jwkX.length !== 32 || jwkY.length !== 32) return false;
5257
+ if (!bytesEqual(didX, jwkX)) return false;
5258
+ return (jwkY[31] & 1) === 1 === (parityPrefix === 3);
5259
+ }
5260
+ /**
5261
+ * Sets the initial policy. Valid only while the auth scope is uninitialized
5262
+ * (version 0). The input version is the policy language version and must be an
5263
+ * integer >= 1; 0 is reserved for the uninitialized state. On a signed-header
5264
+ * document it must be signed by the document creator (`header.sig.publicKey`).
5265
+ * A creator-less policy must include a grant permitting execute on the auth
5266
+ * scope, or it would be born locked out.
5267
+ */
5268
+ function applyInitializeAuthAction(document, action) {
5269
+ assertActionInputShape(action.input);
5270
+ const { version, grants } = action.input;
5271
+ if (!Number.isInteger(version) || version < 1) throw new InvalidAuthVersionError(document.header.id, version);
5272
+ if (document.state.auth.version !== 0) throw new AuthAlreadyInitializedError(document.header.id);
5273
+ if (!Array.isArray(grants)) throw new InvalidActionInputError({ grants: "must be an array" });
5274
+ const creatorKey = document.header.sig.publicKey;
5275
+ const signerKey = action.context?.signer?.app.key;
5276
+ const hasCreator = Boolean(creatorKey.kty || creatorKey.x || creatorKey.y);
5277
+ if (hasCreator && !isDocumentCreator(creatorKey, signerKey)) throw new AuthInitializerNotCreatorError(document.header.id);
5278
+ const creator = hasCreator ? signerKey : void 0;
5279
+ assertValidInitialGrants(grants, document.header.documentType, creator);
5280
+ return {
5281
+ ...document,
5282
+ state: {
5283
+ ...document.state,
5284
+ auth: createAuthState(creator ? {
5285
+ version,
5286
+ grants,
5287
+ creator
5288
+ } : {
5289
+ version,
5290
+ grants
5291
+ })
5292
+ }
5293
+ };
5294
+ }
5295
+ /** Upserts a grant by id: replaces in place if present, otherwise appends. */
5296
+ function applySetGrantAction(document, action) {
5297
+ assertActionInputShape(action.input);
5298
+ const { grant } = action.input;
5299
+ const grants = document.state.auth.grants;
5300
+ assertValidGrantUpsert(grant, grants, document.header.documentType, document.state.auth.creator);
5301
+ return withGrants(document, grants.some((g) => g.id === grant.id) ? grants.map((g) => g.id === grant.id ? grant : g) : [...grants, grant]);
5302
+ }
5303
+ /**
5304
+ * Removes a grant by id; throws if the id is not present or if the removal
5305
+ * would leave a creator-less policy with no auth-administration grant.
5306
+ */
5307
+ function applyRemoveGrantAction(document, action) {
5308
+ assertActionInputShape(action.input);
5309
+ const { id } = action.input;
5310
+ const { grants, creator } = document.state.auth;
5311
+ if (!grants.some((g) => g.id === id)) throw new GrantNotFoundError(id);
5312
+ const next = grants.filter((g) => g.id !== id);
5313
+ assertAuthAdministrationRetained(creator, grants, next, id);
5314
+ return withGrants(document, next);
5315
+ }
5316
+ /**
5317
+ * Moves a grant by id to a new index. Order is load-bearing (the last
5318
+ * applicable grant wins), so the relative order of the other grants is kept.
5319
+ * The target index is clamped to the valid range; an unknown id throws.
5320
+ *
5321
+ * Order alone decides which grant wins, so a move can take administration away
5322
+ * without changing the list's contents. It carries the same retention rule as
5323
+ * the two mutation paths.
5324
+ */
5325
+ function applyMoveGrantAction(document, action) {
5326
+ assertActionInputShape(action.input);
5327
+ const { id, index } = action.input;
5328
+ const { grants, creator } = document.state.auth;
5329
+ const from = grants.findIndex((g) => g.id === id);
5330
+ if (from === -1) throw new GrantNotFoundError(id);
5331
+ const next = [...grants];
5332
+ const [moved] = next.splice(from, 1);
5333
+ const to = Math.max(0, Math.min(index, next.length));
5334
+ next.splice(to, 0, moved);
5335
+ assertAuthAdministrationRetained(creator, grants, next, id);
5336
+ return withGrants(document, next);
5337
+ }
5338
+ /**
5339
+ * Dispatches an auth-scope action to its handler. This is the auth scope's
5340
+ * dedicated reducer: it is applied by the base reducer instead of the model
5341
+ * reducer, mirroring the document-scope platform handlers. Unknown types are a
5342
+ * no-op, matching the model-reducer default.
5343
+ */
5344
+ function applyAuthAction(document, action) {
5345
+ switch (action.type) {
5346
+ case "INITIALIZE_AUTH": return applyInitializeAuthAction(document, action);
5347
+ case "SET_GRANT": return applySetGrantAction(document, action);
5348
+ case "REMOVE_GRANT": return applyRemoveGrantAction(document, action);
5349
+ case "MOVE_GRANT": return applyMoveGrantAction(document, action);
5350
+ default: return document;
5351
+ }
5352
+ }
5353
+ /**
5354
+ * Because only creators can initialize auth scopes, we must verify that either
5355
+ * the document has no auth or the version and creator match.
5356
+ */
5357
+ function assertAuthPreservedOnDuplicate(documentId, source, duplicated) {
5358
+ if (!source || source.version === 0) return;
5359
+ if (duplicated === void 0 || duplicated.version !== source.version || duplicated.creator !== source.creator) throw new AuthPolicyNotPreservedError(documentId);
5360
+ }
5361
+ /**
5362
+ * The auth scope a state snapshot may install, given the policy already there.
5363
+ *
5364
+ * `applyAuthAction` is the validated door onto `state.auth`, but a whole-state
5365
+ * snapshot (UPGRADE_DOCUMENT's `initialState`, LOAD_STATE's `data`) replaces the
5366
+ * scope wholesale and is authorized as a `document`-scope write. Without this,
5367
+ * a subject holding `execute` on `document` and no auth grant at all can install
5368
+ * a policy of its choosing, name itself `creator` (which exempts the policy from
5369
+ * the retention rule for good), or wipe an existing policy by carrying the
5370
+ * default uninitialized one.
5371
+ *
5372
+ * Three cases:
5373
+ *
5374
+ * - the snapshot carries no policy, or an uninitialized one: the document
5375
+ * keeps the policy it has, so a default-state upgrade cannot reset it;
5376
+ * - the document is uninitialized and the snapshot carries a policy: the
5377
+ * policy is installed after the same validation genesis applies, so it
5378
+ * cannot be born locked out;
5379
+ * - both carry a policy: they must agree. A duplicate preserves its source's
5380
+ * policy (see {@link assertAuthPreservedOnDuplicate}), and anything else is
5381
+ * an attempt to replace one policy with another.
5382
+ */
5383
+ function resolveSnapshotAuth(documentId, documentType, current, incoming) {
5384
+ const currentAuth = current ?? createAuthState({
5385
+ version: 0,
5386
+ grants: []
5387
+ });
5388
+ if (!incoming || !incoming.version) return currentAuth;
5389
+ if (currentAuth.version !== 0) {
5390
+ if (stringify$1(incoming) !== stringify$1(currentAuth)) throw new AuthPolicyNotPreservedError(documentId);
5391
+ return incoming;
5392
+ }
5393
+ if (!Array.isArray(incoming.grants)) throw new InvalidActionInputError({ grants: "must be an array" });
5394
+ assertValidInitialGrants(incoming.grants, documentType, incoming.creator);
5395
+ return incoming;
5396
+ }
5397
+ /** UNDO, REDO and PRUNE are rejected on the auth scope. */
5398
+ function assertAuthScopeActionAllowed(action) {
5399
+ if (action.scope === "auth" && [
5400
+ "UNDO",
5401
+ "REDO",
5402
+ "PRUNE"
5403
+ ].includes(action.type)) throw new AuthActionNotAllowedError(action.type);
5404
+ }
5405
+ /**
5406
+ * True iff authorization rejected the action.
5407
+ */
5408
+ function isDenied(operation) {
5409
+ return operation.deniedReason !== void 0;
5410
+ }
4311
5411
  const BaseDocumentHeaderSchema = object({
4312
5412
  id: string(),
4313
5413
  name: string(),
@@ -4438,6 +5538,7 @@ function createDocumentScopeOperations(header, state) {
4438
5538
  function baseCreateDocument(createState, initialState, documentType = "") {
4439
5539
  const state = createState(initialState);
4440
5540
  const header = createPresignedHeader(generateId(), documentType);
5541
+ header.protocolVersions = { "base-reducer": 2 };
4441
5542
  return {
4442
5543
  header,
4443
5544
  state,
@@ -4461,6 +5562,18 @@ function hashDocumentStateForScope(document, scope = "global") {
4461
5562
  * Uses the V2 model where consecutive NOOPs form chains.
4462
5563
  * Unlike V1 garbageCollect, this preserves ALL operations but marks which to apply.
4463
5564
  */
5565
+ /**
5566
+ * The base-reducer protocol version a document is written against. Every
5567
+ * document carries one, set from the CREATE_DOCUMENT input. A header without
5568
+ * one was built outside that path, and choosing a version on its behalf would
5569
+ * replay the document through a reducer it was not written for, so it is an
5570
+ * error rather than a default.
5571
+ */
5572
+ function baseReducerVersion(header) {
5573
+ const version = header.protocolVersions?.["base-reducer"];
5574
+ if (typeof version !== "number") throw new Error(`Document ${header.id} carries no base-reducer protocol version`);
5575
+ return version;
5576
+ }
4464
5577
  function garbageCollectV2(sortedOperations) {
4465
5578
  const result = [];
4466
5579
  let noopChainLength = 0;
@@ -4477,9 +5590,26 @@ function garbageCollectV2(sortedOperations) {
4477
5590
  const defaultCreateState = (state) => {
4478
5591
  return state;
4479
5592
  };
5593
+ /**
5594
+ * Records an operation in the history without applying it, which is what a
5595
+ * denied operation needs: it occupies its index and contributes no state.
5596
+ *
5597
+ * The scope defaults to the action's own, and is passed explicitly by a rebuild
5598
+ * that is walking one stream and does not want to trust the action's copy.
5599
+ */
5600
+ function appendWithoutApplying(document, operation, scope = operation.action.scope) {
5601
+ return {
5602
+ ...document,
5603
+ operations: {
5604
+ ...document.operations,
5605
+ [scope]: [...document.operations[scope] ?? [], operation]
5606
+ }
5607
+ };
5608
+ }
4480
5609
  function replayDocument(initialState, operations, reducer, header, dispatch, skipHeaderOperations = {}, options) {
4481
5610
  const { checkHashes = true, reuseOperationResultingState, operationResultingStateParser = parseResultingState, skipIndexValidation } = options || {};
4482
- let documentState = initialState;
5611
+ const backfilledInitialState = backfillAuthState(initialState);
5612
+ let documentState = backfilledInitialState;
4483
5613
  const operationsToReplay = [];
4484
5614
  const allScopes = new Set([
4485
5615
  ...Object.keys(operations),
@@ -4514,12 +5644,13 @@ function replayDocument(initialState, operations, reducer, header, dispatch, ski
4514
5644
  const document = {
4515
5645
  header,
4516
5646
  state: defaultCreateState(documentState),
4517
- initialState,
5647
+ initialState: backfilledInitialState,
4518
5648
  operations: initialOperations,
4519
5649
  clipboard: []
4520
5650
  };
4521
5651
  let result = document;
4522
5652
  if (operationsToReplay.length) result = operationsToReplay.reduce((document, operation) => {
5653
+ if (isDenied(operation)) return updateHeaderRevision(appendWithoutApplying(document, operation), operation.action.scope, operation.timestampUtcMs);
4523
5654
  return reducer(document, operation.action, dispatch, {
4524
5655
  ignoreSkipOperations: true,
4525
5656
  checkHashes,
@@ -4801,13 +5932,15 @@ function redoOperation(document, action, skip) {
4801
5932
  });
4802
5933
  }
4803
5934
  function loadStateOperation(document, action) {
5935
+ const loaded = backfillAuthState(action.state.data);
5936
+ loaded.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, loaded.auth);
4804
5937
  return {
4805
5938
  ...document,
4806
5939
  header: {
4807
5940
  ...document.header,
4808
5941
  name: action.state.name
4809
5942
  },
4810
- state: action.state.data
5943
+ state: loaded
4811
5944
  };
4812
5945
  }
4813
5946
  function replayOperations(initialState, clearedOperations, stateReducer, header, dispatch, documentReducer = baseReducer, skipHeaderOperations = {}, options) {
@@ -4981,12 +6114,13 @@ function processUndoOperation(document, scope, customReducer, reuseOperationResu
4981
6114
  function baseReducer(document, action, customReducer, dispatch, options = {}) {
4982
6115
  const { skip, ignoreSkipOperations = false, reuseOperationResultingState = false, operationResultingStateParser, pruneOnSkip = true, branch = "main" } = options;
4983
6116
  let _action = actionFromAction(action);
6117
+ assertAuthScopeActionAllowed(_action);
4984
6118
  let skipValue = skip ?? options.replayOptions?.operation.skip ?? 0;
4985
6119
  let newDocument = { ...document };
4986
6120
  let reuseLastOperationIndex = false;
4987
6121
  const shouldProcessSkipOperation = !ignoreSkipOperations && skipValue > 0;
4988
6122
  if (isUndoRedo(_action)) {
4989
- const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? 1);
6123
+ const { skip: calculatedSkip, action: transformedAction, document: processedDocument, reuseLastOperationIndex: reuseIndex } = processUndoRedo(document, _action, skipValue, options.protocolVersion ?? baseReducerVersion(document.header));
4990
6124
  _action = transformedAction;
4991
6125
  skipValue = calculatedSkip;
4992
6126
  newDocument = processedDocument;
@@ -5002,7 +6136,7 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5002
6136
  branch
5003
6137
  };
5004
6138
  newDocument = updateDocument(newDocument, _action, reuseLastOperationIndex, skipValue, operationContext, options.replayOptions?.operation, options.skipIndexValidation);
5005
- const protocolVersion = options.protocolVersion ?? 1;
6139
+ const protocolVersion = options.protocolVersion ?? baseReducerVersion(document.header);
5006
6140
  if (isUndo(action) && protocolVersion < 2) return processUndoOperation(newDocument, action.scope, customReducer);
5007
6141
  const isNoopWithSkip = _action.type === "NOOP" && skipValue > 0;
5008
6142
  if ((isUndo(action) || isNoopWithSkip) && protocolVersion >= 2) {
@@ -5028,6 +6162,13 @@ function baseReducer(document, action, customReducer, dispatch, options = {}) {
5028
6162
  }
5029
6163
  newDocument = create(newDocument, (draft) => {
5030
6164
  try {
6165
+ if (_action.scope === "auth") {
6166
+ const authState = applyAuthAction(newDocument, _action).state;
6167
+ unsafe(() => {
6168
+ draft.state = castDraft(authState);
6169
+ });
6170
+ return;
6171
+ }
5031
6172
  const newState = customReducer(draft.state, _action, dispatch);
5032
6173
  if (newState) unsafe(() => {
5033
6174
  draft.state = castDraft(newState);
@@ -5817,14 +6958,27 @@ const documentModelStateReducer = (state, action) => {
5817
6958
  }
5818
6959
  };
5819
6960
  const documentModelReducer = createReducer(documentModelStateReducer);
6961
+ /**
6962
+ * Canonical document-model version normalization: documents stamped with 0
6963
+ * or nothing at all predate versioning and are treated as version 1, the
6964
+ * same version the registry assigns unversioned modules. Every consumer
6965
+ * that resolves a module or compares versions must use this rule; resolving
6966
+ * 0 to "latest" instead re-pins a legacy document's history to whichever
6967
+ * module happens to be newest.
6968
+ */
6969
+ function normalizeDocumentModelVersion(version) {
6970
+ return version && version > 0 ? version : 1;
6971
+ }
5820
6972
  function applyInitialState(document, action) {
5821
6973
  const input = action.input;
5822
6974
  const newState = input.initialState || input.state;
5823
6975
  if (newState) {
5824
- document.state = {
6976
+ const merged = backfillAuthState({
5825
6977
  ...document.state,
5826
6978
  ...newState
5827
- };
6979
+ });
6980
+ merged.auth = resolveSnapshotAuth(document.header.id, document.header.documentType, backfillAuthState({ ...document.state }).auth, merged.auth);
6981
+ document.state = merged;
5828
6982
  document.initialState = document.state;
5829
6983
  }
5830
6984
  }
@@ -5884,7 +7038,6 @@ function computeUpgradeTransitions(manifest, fromVersion, toVersion) {
5884
7038
  }
5885
7039
  return transitions;
5886
7040
  }
5887
- const NON_DOMAIN_SCOPES$1 = new Set(["auth", "document"]);
5888
7041
  function highestReducerVersion(reducers) {
5889
7042
  const keys = Object.keys(reducers).map(Number);
5890
7043
  if (keys.length === 0) throw new Error("VersionedReplayConfig.reducers must not be empty");
@@ -5912,15 +7065,15 @@ function highestReducerVersion(reducers) {
5912
7065
  */
5913
7066
  function replayDocumentVersioned(initialState, operations, config, header, dispatch, options) {
5914
7067
  const { checkHashes = true, skipIndexValidation } = options || {};
5915
- const protocolVersion = header.protocolVersions?.["base-reducer"] ?? 1;
7068
+ const protocolVersion = baseReducerVersion(header);
5916
7069
  const spine = (operations["document"] ?? []).slice().sort((a, b) => a.index - b.index);
5917
7070
  const upgrades = spine.filter((op) => op.action.type === "UPGRADE_DOCUMENT");
5918
7071
  const legacyFallback = () => {
5919
- const domainOps = Object.fromEntries(Object.entries(operations).filter(([s]) => !NON_DOMAIN_SCOPES$1.has(s)));
7072
+ const replayOps = Object.fromEntries(Object.entries(operations).filter(([s]) => s !== "document"));
5920
7073
  const latestVersion = highestReducerVersion(config.reducers);
5921
7074
  const reducer = config.reducers[latestVersion];
5922
7075
  return {
5923
- ...replayDocument(initialState, domainOps, reducer, header, dispatch, {}, options),
7076
+ ...replayDocument(initialState, replayOps, reducer, header, dispatch, {}, options),
5924
7077
  operations
5925
7078
  };
5926
7079
  };
@@ -5944,14 +7097,14 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5944
7097
  const a = op.action;
5945
7098
  return a.input.fromVersion > 0 && a.input.fromVersion < a.input.toVersion;
5946
7099
  });
5947
- const domainScopes = Object.keys(operations).filter((s) => !NON_DOMAIN_SCOPES$1.has(s));
7100
+ const replayScopes = Object.keys(operations).filter((s) => s !== "document");
5948
7101
  const scopeOps = {};
5949
- for (const s of domainScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
7102
+ for (const s of replayScopes) scopeOps[s] = (operations[s] ?? []).slice().sort((a, b) => a.index - b.index);
5950
7103
  const boundaries = validatedUpgrades.map((upgradeOp) => {
5951
7104
  const revisionSnapshot = upgradeOp.action.input.revision;
5952
7105
  const upgradeTimestamp = upgradeOp.timestampUtcMs;
5953
7106
  const boundary = {};
5954
- for (const s of domainScopes) {
7107
+ for (const s of replayScopes) {
5955
7108
  const ops = scopeOps[s] ?? [];
5956
7109
  if (revisionSnapshot !== void 0) {
5957
7110
  const rev = revisionSnapshot[s] ?? 0;
@@ -5969,7 +7122,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5969
7122
  }
5970
7123
  return boundary;
5971
7124
  });
5972
- for (let i = 1; i < boundaries.length; i++) for (const s of domainScopes) {
7125
+ for (let i = 1; i < boundaries.length; i++) for (const s of replayScopes) {
5973
7126
  const prev = boundaries[i - 1]?.[s] ?? 0;
5974
7127
  const curr = boundaries[i]?.[s] ?? 0;
5975
7128
  if (boundaries[i]) boundaries[i][s] = Math.max(prev, curr);
@@ -5981,10 +7134,11 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5981
7134
  ]);
5982
7135
  const initialOperations = {};
5983
7136
  for (const s of allScopes) initialOperations[s] = [];
7137
+ const backfilledSeed = backfillAuthState(seedState);
5984
7138
  let document = {
5985
7139
  header,
5986
- state: seedState,
5987
- initialState: seedState,
7140
+ state: backfilledSeed,
7141
+ initialState: backfilledSeed,
5988
7142
  operations: initialOperations,
5989
7143
  clipboard: []
5990
7144
  };
@@ -5992,17 +7146,15 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
5992
7146
  const segmentEndHashPerScope = /* @__PURE__ */ new Map();
5993
7147
  for (let k = 0; k <= validatedUpgrades.length; k++) {
5994
7148
  const reducer = config.reducers[currentVersion];
5995
- if (!reducer) {
5996
- const available = Object.keys(config.reducers).join(", ");
5997
- throw new Error(`No reducer registered for document version ${currentVersion}. Available versions: ${available}`);
5998
- }
5999
- for (const s of domainScopes) {
7149
+ if (!reducer) throw new UnsupportedDocumentModelVersionError(header.documentType, currentVersion, Object.keys(config.reducers).map(Number).sort((a, b) => a - b));
7150
+ for (const s of replayScopes) {
6000
7151
  const ops = scopeOps[s] ?? [];
6001
7152
  const segStart = k === 0 ? 0 : boundaries[k - 1]?.[s] ?? 0;
6002
7153
  const segEnd = k < validatedUpgrades.length ? boundaries[k]?.[s] ?? ops.length : ops.length;
6003
7154
  const segOps = ops.slice(segStart, segEnd);
6004
7155
  for (const op of segOps) {
6005
- document = reducer(document, op.action, dispatch, {
7156
+ if (isDenied(op)) document = updateHeaderRevision(appendWithoutApplying(document, op, s), s, op.timestampUtcMs);
7157
+ else document = reducer(document, op.action, dispatch, {
6006
7158
  ignoreSkipOperations: true,
6007
7159
  checkHashes,
6008
7160
  skipIndexValidation,
@@ -6019,6 +7171,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6019
7171
  if (!spineOp) continue;
6020
7172
  const spineActionType = spineOp.action.type;
6021
7173
  if (spineActionType === "CREATE_DOCUMENT" || spineActionType === "UPGRADE_DOCUMENT") continue;
7174
+ if (isDenied(spineOp)) continue;
6022
7175
  if (spineActionType === "DELETE_DOCUMENT") document = applyDeleteDocumentAction(document, spineOp.action);
6023
7176
  else document = reducer(document, spineOp.action, dispatch, {
6024
7177
  ignoreSkipOperations: true,
@@ -6049,7 +7202,7 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6049
7202
  }
6050
7203
  };
6051
7204
  if (!checkHashes) {
6052
- const allReplayedOps = domainScopes.flatMap((s) => scopeOps[s] ?? []);
7205
+ const allReplayedOps = replayScopes.flatMap((s) => scopeOps[s] ?? []);
6053
7206
  for (const scope of Object.keys(document.state)) {
6054
7207
  const capturedHash = segmentEndHashPerScope.get(scope);
6055
7208
  const scopeHash = capturedHash !== void 0 ? capturedHash : hashDocumentStateForScope(document, scope);
@@ -6091,7 +7244,6 @@ function replayDocumentVersioned(initialState, operations, config, header, dispa
6091
7244
  }
6092
7245
  };
6093
7246
  }
6094
- const NON_DOMAIN_SCOPES = new Set(["auth", "document"]);
6095
7247
  function zipAsync(data) {
6096
7248
  return new Promise((resolve, reject) => {
6097
7249
  zip(data, (err, out) => err ? reject(err) : resolve(out));
@@ -6170,7 +7322,7 @@ async function parseZipData(data) {
6170
7322
  async function loadFromZipData(data, reducer, options) {
6171
7323
  const { initialState, header, clearedOperations } = await parseZipData(data);
6172
7324
  return {
6173
- ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope))), reducer, header, void 0, {}, options),
7325
+ ...replayDocument(initialState, Object.fromEntries(Object.entries(clearedOperations).filter(([scope]) => scope !== "document")), reducer, header, void 0, {}, options),
6174
7326
  operations: clearedOperations
6175
7327
  };
6176
7328
  }
@@ -6193,96 +7345,6 @@ const documentModelLoadFromInput = (input) => {
6193
7345
  const documentModelSaveToFileHandle = (document, input) => {
6194
7346
  return baseSaveToFileHandle(document, input);
6195
7347
  };
6196
- /**
6197
- * Creates a default PHAuthState
6198
- */
6199
- function defaultAuthState() {
6200
- return {};
6201
- }
6202
- /**
6203
- * Creates a default PHDocumentState
6204
- */
6205
- function defaultDocumentState() {
6206
- return {
6207
- version: 0,
6208
- hash: {
6209
- algorithm: HASH_ALGORITHM_SHA1,
6210
- encoding: HASH_ENCODING_BASE64
6211
- }
6212
- };
6213
- }
6214
- /**
6215
- * Creates a default PHBaseState with auth and document properties
6216
- */
6217
- function defaultBaseState() {
6218
- return {
6219
- auth: defaultAuthState(),
6220
- document: defaultDocumentState()
6221
- };
6222
- }
6223
- /**
6224
- * Creates a PHAuthState with the given properties
6225
- */
6226
- function createAuthState(auth) {
6227
- return {
6228
- ...defaultAuthState(),
6229
- ...auth
6230
- };
6231
- }
6232
- /**
6233
- * Creates a PHDocumentState with the given properties
6234
- */
6235
- function createDocumentState(document) {
6236
- return {
6237
- ...defaultDocumentState(),
6238
- ...document
6239
- };
6240
- }
6241
- /**
6242
- * Creates a PHBaseState with the given auth and document properties
6243
- */
6244
- function createBaseState(auth, document) {
6245
- return {
6246
- auth: createAuthState(auth),
6247
- document: createDocumentState(document)
6248
- };
6249
- }
6250
- function defaultGlobalState() {
6251
- return {
6252
- ...defaultBaseState(),
6253
- author: {
6254
- name: "",
6255
- website: ""
6256
- },
6257
- description: "",
6258
- extension: "",
6259
- id: "",
6260
- name: "",
6261
- specifications: []
6262
- };
6263
- }
6264
- function defaultLocalState() {
6265
- return {};
6266
- }
6267
- function createGlobalState(state) {
6268
- return {
6269
- ...defaultGlobalState(),
6270
- ...state || {}
6271
- };
6272
- }
6273
- function createLocalState(state) {
6274
- return {
6275
- ...defaultLocalState(),
6276
- ...state || {}
6277
- };
6278
- }
6279
- function createState(baseState, globalState, localState) {
6280
- return {
6281
- ...createBaseState(baseState?.auth, baseState?.document),
6282
- global: createGlobalState(globalState),
6283
- local: createLocalState(localState)
6284
- };
6285
- }
6286
7348
  //#endregion
6287
7349
  //#region ../document-model/dist/index.js
6288
7350
  const isStateOfType$1 = (state) => {
@@ -7361,6 +8423,6 @@ const driveDocumentModelModule = {
7361
8423
  }
7362
8424
  };
7363
8425
  //#endregion
7364
- 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 };
8426
+ export { setOperationDescription as $, createState as A, normalizeDocumentModelVersion as B, baseLoadFromInputVersioned as C, createBaseState as D, createAction as E, deleteOperationError as F, setAuthorWebsite as G, releaseNewVersion as H, deserializeSignature as I, setModelExtension as J, setInitialState as K, documentModelDocumentType as L, defaultBaseState as M, deleteModule as N, createPresignedHeader as O, deleteOperation as P, setName as Q, hashDocumentStateForScope as R, baseLoadFromInput as S, buildSignedAction as T, replayDocumentVersioned as U, redo as V, setAuthorName as W, setModelName as X, setModelId as Y, setModuleName as Z, addOperation as _, handleTargetNameCollisions as a, undo as at, baseActions as b, isValidName as c, validateStateSchemaName as ct, documentModelDocumentModelModule as d, setOperationErrorName as et, logger as f, addModule as g, UnsupportedDocumentModelVersionError as h, generateNodesCopy as i, toTransportAction as it, createZip as j, createReducer as k, moveNode as l, generateId as lt, BaseDocumentStateSchema as m, copyNode as n, setOperationSchema as nt, isFileNode as o, validateInitialState as ot, BaseDocumentHeaderSchema as p, setModelDescription as q, driveDocumentModelModule as r, setStateSchema as rt, isFolderNode as s, validateModules as st, addFolder as t, setOperationName as tt, updateNode as u, addOperationError as v, baseSaveToFileHandle as w, baseCreateDocument as x, assertAuthPreservedOnDuplicate as y, isDocumentAction as z };
7365
8427
 
7366
- //# sourceMappingURL=document-drive-IdFV1QXL.js.map
8428
+ //# sourceMappingURL=document-drive-BgXuuZ9v.js.map