@camstack/addon-export-google 0.1.124 → 0.1.125

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.
@@ -4636,6 +4636,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4636
4636
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4637
4637
  json.type = "boolean";
4638
4638
  };
4639
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4640
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4641
+ };
4642
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4643
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4644
+ };
4639
4645
  var nullProcessor = (_schema, ctx, json, _params) => {
4640
4646
  if (ctx.target === "openapi-3.0") {
4641
4647
  json.type = "string";
@@ -4643,12 +4649,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4643
4649
  json.enum = [null];
4644
4650
  } else json.type = "null";
4645
4651
  };
4652
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4653
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4654
+ };
4646
4655
  var voidProcessor = (_schema, ctx, _json, _params) => {
4647
4656
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4648
4657
  };
4649
4658
  var neverProcessor = (_schema, _ctx, json, _params) => {
4650
4659
  json.not = {};
4651
4660
  };
4661
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4662
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4652
4663
  var dateProcessor = (_schema, ctx, _json, _params) => {
4653
4664
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4654
4665
  };
@@ -4680,12 +4691,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4680
4691
  json.enum = vals;
4681
4692
  }
4682
4693
  };
4694
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4695
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4696
+ };
4697
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4698
+ const _json = json;
4699
+ const pattern = schema._zod.pattern;
4700
+ if (!pattern) throw new Error("Pattern not found in template literal");
4701
+ _json.type = "string";
4702
+ _json.pattern = pattern.source;
4703
+ };
4704
+ var fileProcessor = (schema, _ctx, json, _params) => {
4705
+ const _json = json;
4706
+ const file = {
4707
+ type: "string",
4708
+ format: "binary",
4709
+ contentEncoding: "binary"
4710
+ };
4711
+ const { minimum, maximum, mime } = schema._zod.bag;
4712
+ if (minimum !== void 0) file.minLength = minimum;
4713
+ if (maximum !== void 0) file.maxLength = maximum;
4714
+ if (mime) if (mime.length === 1) {
4715
+ file.contentMediaType = mime[0];
4716
+ Object.assign(_json, file);
4717
+ } else {
4718
+ Object.assign(_json, file);
4719
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4720
+ }
4721
+ else Object.assign(_json, file);
4722
+ };
4723
+ var successProcessor = (_schema, _ctx, json, _params) => {
4724
+ json.type = "boolean";
4725
+ };
4683
4726
  var customProcessor = (_schema, ctx, _json, _params) => {
4684
4727
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4685
4728
  };
4729
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4730
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4731
+ };
4686
4732
  var transformProcessor = (_schema, ctx, _json, _params) => {
4687
4733
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4688
4734
  };
4735
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4736
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4737
+ };
4738
+ var setProcessor = (_schema, ctx, _json, _params) => {
4739
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4740
+ };
4689
4741
  var arrayProcessor = (schema, ctx, _json, params) => {
4690
4742
  const json = _json;
4691
4743
  const def = schema._zod.def;
@@ -4890,6 +4942,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4890
4942
  seen.ref = def.innerType;
4891
4943
  json.readOnly = true;
4892
4944
  };
4945
+ var promiseProcessor = (schema, ctx, _json, params) => {
4946
+ const def = schema._zod.def;
4947
+ process(def.innerType, ctx, params);
4948
+ const seen = ctx.seen.get(schema);
4949
+ seen.ref = def.innerType;
4950
+ };
4893
4951
  var optionalProcessor = (schema, ctx, _json, params) => {
4894
4952
  const def = schema._zod.def;
4895
4953
  process(def.innerType, ctx, params);
@@ -4902,6 +4960,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4902
4960
  const seen = ctx.seen.get(schema);
4903
4961
  seen.ref = innerType;
4904
4962
  };
4963
+ var allProcessors = {
4964
+ string: stringProcessor,
4965
+ number: numberProcessor,
4966
+ boolean: booleanProcessor,
4967
+ bigint: bigintProcessor,
4968
+ symbol: symbolProcessor,
4969
+ null: nullProcessor,
4970
+ undefined: undefinedProcessor,
4971
+ void: voidProcessor,
4972
+ never: neverProcessor,
4973
+ any: anyProcessor,
4974
+ unknown: unknownProcessor,
4975
+ date: dateProcessor,
4976
+ enum: enumProcessor,
4977
+ literal: literalProcessor,
4978
+ nan: nanProcessor,
4979
+ template_literal: templateLiteralProcessor,
4980
+ file: fileProcessor,
4981
+ success: successProcessor,
4982
+ custom: customProcessor,
4983
+ function: functionProcessor,
4984
+ transform: transformProcessor,
4985
+ map: mapProcessor,
4986
+ set: setProcessor,
4987
+ array: arrayProcessor,
4988
+ object: objectProcessor,
4989
+ union: unionProcessor,
4990
+ intersection: intersectionProcessor,
4991
+ tuple: tupleProcessor,
4992
+ record: recordProcessor,
4993
+ nullable: nullableProcessor,
4994
+ nonoptional: nonoptionalProcessor,
4995
+ default: defaultProcessor,
4996
+ prefault: prefaultProcessor,
4997
+ catch: catchProcessor,
4998
+ pipe: pipeProcessor,
4999
+ readonly: readonlyProcessor,
5000
+ promise: promiseProcessor,
5001
+ optional: optionalProcessor,
5002
+ lazy: lazyProcessor
5003
+ };
5004
+ function toJSONSchema(input, params) {
5005
+ if ("_idmap" in input) {
5006
+ const registry = input;
5007
+ const ctx = initializeContext({
5008
+ ...params,
5009
+ processors: allProcessors
5010
+ });
5011
+ const defs = {};
5012
+ for (const entry of registry._idmap.entries()) {
5013
+ const [_, schema] = entry;
5014
+ process(schema, ctx);
5015
+ }
5016
+ const schemas = {};
5017
+ ctx.external = {
5018
+ registry,
5019
+ uri: params?.uri,
5020
+ defs
5021
+ };
5022
+ for (const entry of registry._idmap.entries()) {
5023
+ const [key, schema] = entry;
5024
+ extractDefs(ctx, schema);
5025
+ schemas[key] = finalize(ctx, schema);
5026
+ }
5027
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
5028
+ return { schemas };
5029
+ }
5030
+ const ctx = initializeContext({
5031
+ ...params,
5032
+ processors: allProcessors
5033
+ });
5034
+ process(input, ctx);
5035
+ extractDefs(ctx, input);
5036
+ return finalize(ctx, input);
5037
+ }
4905
5038
  //#endregion
4906
5039
  //#region ../../node_modules/zod/v4/classic/iso.js
4907
5040
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5926,7 +6059,7 @@ var ZodIssueCode = {
5926
6059
  var ZodFirstPartyTypeKind;
5927
6060
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5928
6061
  //#endregion
5929
- //#region ../types/dist/sleep-BkzQdpzF.mjs
6062
+ //#region ../types/dist/sleep-BaWhXZFm.mjs
5930
6063
  /**
5931
6064
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5932
6065
  * window to float samples (D455).
@@ -6889,7 +7022,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6889
7022
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6890
7023
  return out;
6891
7024
  }
6892
- function rowId(row, idKey) {
7025
+ function rowId$1(row, idKey) {
6893
7026
  const raw = row[idKey];
6894
7027
  if (typeof raw === "string" && raw.length > 0) return raw;
6895
7028
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6906,7 +7039,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6906
7039
  }
6907
7040
  const storedById = /* @__PURE__ */ new Map();
6908
7041
  for (const row of storedRows) {
6909
- const id = rowId(row, node.idKey);
7042
+ const id = rowId$1(row, node.idKey);
6910
7043
  if (id !== null) storedById.set(id, row);
6911
7044
  }
6912
7045
  const kept = /* @__PURE__ */ new Set();
@@ -6916,13 +7049,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6916
7049
  rows.push(row);
6917
7050
  continue;
6918
7051
  }
6919
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7052
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6920
7053
  kept.add(id);
6921
7054
  const withId = {
6922
7055
  ...row,
6923
7056
  [node.idKey]: row[node.idKey] ?? id
6924
7057
  };
6925
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7058
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6926
7059
  const storedRow = storedById.get(id) ?? {};
6927
7060
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6928
7061
  }
@@ -8657,6 +8790,38 @@ function normalizeAddonInitResult(result) {
8657
8790
  if (Array.isArray(result)) return { providers: result };
8658
8791
  return result;
8659
8792
  }
8793
+ var PREFIX$1 = "records/";
8794
+ /** The base of every records failure. `detail` is the human part of the message. */
8795
+ var RecordsError = class extends Error {
8796
+ code;
8797
+ detail;
8798
+ constructor(code, detail) {
8799
+ super(`${PREFIX$1}${code}: ${detail}`);
8800
+ this.name = "RecordsError";
8801
+ this.code = code;
8802
+ this.detail = detail;
8803
+ }
8804
+ };
8805
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8806
+ var RevConflictError = class extends RecordsError {
8807
+ constructor(detail) {
8808
+ super("rev-conflict", detail);
8809
+ this.name = "RevConflictError";
8810
+ }
8811
+ };
8812
+ var InvalidRecordError = class extends RecordsError {
8813
+ constructor(detail) {
8814
+ super("invalid-record", detail);
8815
+ this.name = "InvalidRecordError";
8816
+ }
8817
+ };
8818
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8819
+ var DeclarationRefusedError = class extends RecordsError {
8820
+ constructor(detail) {
8821
+ super("declaration-refused", detail);
8822
+ this.name = "DeclarationRefusedError";
8823
+ }
8824
+ };
8660
8825
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8661
8826
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8662
8827
  var RECORD_DATABASES = ["settings", "events"];
@@ -8672,6 +8837,50 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8672
8837
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8673
8838
  var RECORD_BATCH_MAX = 1e3;
8674
8839
  var RECORD_QUERY_MAX = 1e3;
8840
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8841
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8842
+ /**
8843
+ * Secret fields of a record, addressed the way a Zod schema declares them
8844
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8845
+ * (`auth.accessToken`, `headers[].value`).
8846
+ *
8847
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8848
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8849
+ * key releases exactly that key's secret.
8850
+ *
8851
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8852
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8853
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8854
+ * leaf names its element: `headers[X-Api].value`.
8855
+ *
8856
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8857
+ */
8858
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8859
+ function parseSecretPath(path) {
8860
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8861
+ return path.split(".").map((raw) => {
8862
+ const each = raw.endsWith("[]");
8863
+ const map = raw.endsWith("{}");
8864
+ const key = each || map ? raw.slice(0, -2) : raw;
8865
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8866
+ return {
8867
+ key,
8868
+ each,
8869
+ map
8870
+ };
8871
+ });
8872
+ }
8873
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8874
+ function secretArrayPrefixes(path) {
8875
+ const segments = parseSecretPath(path);
8876
+ const prefixes = [];
8877
+ const walked = [];
8878
+ for (const segment of segments) {
8879
+ walked.push(segment.key);
8880
+ if (segment.each) prefixes.push(walked.join("."));
8881
+ }
8882
+ return prefixes;
8883
+ }
8675
8884
  /**
8676
8885
  * The share-view scope kinds a share-link token can carry. The hub mints
8677
8886
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8696,6 +8905,75 @@ var PeerBytesTicketSchema = object({
8696
8905
  */
8697
8906
  declaredBytes: number().int().nonnegative().nullable()
8698
8907
  });
8908
+ function defOf(schema) {
8909
+ const zodBag = Reflect.get(schema, "_zod");
8910
+ if (typeof zodBag !== "object" || zodBag === null) return {};
8911
+ const def = Reflect.get(zodBag, "def");
8912
+ if (typeof def !== "object" || def === null) return {};
8913
+ return def;
8914
+ }
8915
+ function declaredHere(schema) {
8916
+ return globalRegistry.get(schema)?.secret === true;
8917
+ }
8918
+ /** Wrapper kinds whose `innerType` is the field itself. */
8919
+ var WRAPPERS = new Set([
8920
+ "optional",
8921
+ "nullable",
8922
+ "default",
8923
+ "prefault",
8924
+ "catch",
8925
+ "readonly",
8926
+ "nonoptional"
8927
+ ]);
8928
+ /**
8929
+ * The schema layers that make up ONE field: the schema itself and every
8930
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
8931
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
8932
+ * `.transform` on `in`).
8933
+ */
8934
+ function layersOf(schema) {
8935
+ const out = [];
8936
+ const queue = [schema];
8937
+ while (queue.length > 0) {
8938
+ const s = queue.shift();
8939
+ if (!s || out.includes(s)) continue;
8940
+ out.push(s);
8941
+ const def = defOf(s);
8942
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
8943
+ if (def.type === "pipe") {
8944
+ if (def.in) queue.push(def.in);
8945
+ if (def.out) queue.push(def.out);
8946
+ }
8947
+ }
8948
+ return out;
8949
+ }
8950
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
8951
+ function isZodSecret(schema) {
8952
+ return layersOf(schema).some(declaredHere);
8953
+ }
8954
+ /**
8955
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
8956
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
8957
+ * map" (`applianceSecrets{}`). A declared
8958
+ * object or array is reported as one path and not descended into — everything
8959
+ * under it is secret.
8960
+ */
8961
+ function collectZodSecretPaths(schema, prefix = "") {
8962
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
8963
+ const paths = [];
8964
+ for (const layer of layersOf(schema)) {
8965
+ const def = defOf(layer);
8966
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
8967
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
8968
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
8969
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
8970
+ else if (def.type === "intersection") {
8971
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
8972
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
8973
+ }
8974
+ }
8975
+ return [...new Set(paths)];
8976
+ }
8699
8977
  /**
8700
8978
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8701
8979
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8762,6 +9040,111 @@ var RecordKindDeclarationSchema = object({
8762
9040
  }).strict();
8763
9041
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8764
9042
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9043
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9044
+ function assertValidDeclaration(name, decl) {
9045
+ const refuse = (why) => {
9046
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9047
+ };
9048
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9049
+ const seen = /* @__PURE__ */ new Set();
9050
+ for (const index of decl.indexes) {
9051
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9052
+ seen.add(index.name);
9053
+ }
9054
+ const { retention } = decl;
9055
+ const hasSecrets = decl.secretPaths.length > 0;
9056
+ if ("ttlMs" in retention) {
9057
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9058
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9059
+ }
9060
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9061
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9062
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9063
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9064
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9065
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9066
+ }
9067
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9068
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9069
+ }
9070
+ function bodyFieldsOf(schema) {
9071
+ return { ...toJSONSchema(schema, {
9072
+ unrepresentable: "any",
9073
+ io: "input"
9074
+ }) };
9075
+ }
9076
+ function isRecordLike(value) {
9077
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9078
+ }
9079
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9080
+ function hasNameField(json, field) {
9081
+ const branches = json["oneOf"] ?? json["anyOf"];
9082
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9083
+ const properties = json["properties"];
9084
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9085
+ }
9086
+ /**
9087
+ * Declare the kinds of a package. The keys are the kind names. The result is
9088
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9089
+ * types its handle from.
9090
+ */
9091
+ function defineRecordKinds(specs) {
9092
+ const out = {};
9093
+ for (const [name, spec] of Object.entries(specs)) {
9094
+ const secretPaths = collectZodSecretPaths(spec.schema);
9095
+ const nameField = spec.entry?.nameField ?? "name";
9096
+ const fields = bodyFieldsOf(spec.schema);
9097
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9098
+ const parsed = RecordKindDeclarationSchema.parse({
9099
+ database: spec.database,
9100
+ class: spec.class,
9101
+ writeTrigger: spec.writeTrigger,
9102
+ device: spec.device,
9103
+ at: spec.at,
9104
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9105
+ retention: spec.retention,
9106
+ deviceRemoval: spec.deviceRemoval,
9107
+ maxDataBytes: spec.maxDataBytes,
9108
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9109
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9110
+ transactFamily: spec.transactFamily,
9111
+ entry: spec.entry === void 0 ? void 0 : {
9112
+ title: spec.entry.title,
9113
+ nameField,
9114
+ fields
9115
+ }
9116
+ });
9117
+ assertValidDeclaration(name, parsed);
9118
+ out[name] = {
9119
+ name,
9120
+ schema: spec.schema,
9121
+ declaration: parsed
9122
+ };
9123
+ }
9124
+ return out;
9125
+ }
9126
+ /**
9127
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9128
+ * engine, never aged, belonging to no device.
9129
+ */
9130
+ function defineEntryKind(name, spec) {
9131
+ const defined = defineRecordKinds({ [name]: {
9132
+ schema: spec.schema,
9133
+ class: "config",
9134
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9135
+ retention: { none: "an entry goes only when the operator deletes it" },
9136
+ ...spec.database === void 0 ? {} : { database: spec.database },
9137
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9138
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9139
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9140
+ entry: {
9141
+ title: spec.title,
9142
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9143
+ }
9144
+ } })[name];
9145
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9146
+ return defined;
9147
+ }
8765
9148
  object({
8766
9149
  field: string().min(1),
8767
9150
  on: literal("advance")
@@ -53599,6 +53982,21 @@ var IntegrationInstanceKindSchema = object({
53599
53982
  disconnectPath: string().min(1).optional()
53600
53983
  });
53601
53984
  var IntegrationInstanceDescriptionSchema = object({
53985
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
53986
+ role: _enum([
53987
+ "devices",
53988
+ "services",
53989
+ "both"
53990
+ ]),
53991
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
53992
+ discovery: object({
53993
+ mode: _enum([
53994
+ "none",
53995
+ "lan",
53996
+ "account"
53997
+ ]),
53998
+ scopedToInstance: boolean()
53999
+ }).optional(),
53602
54000
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
53603
54001
  instanceMode: IntegrationInstanceModeSchema,
53604
54002
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -53638,10 +54036,11 @@ var IntegrationInstanceSchema = object({
53638
54036
  /** The addon's own rule (an URL is present, a client id is present...). */
53639
54037
  configured: boolean(),
53640
54038
  /**
53641
- * The instance's own on/off switch (D996): always present, derived from the record body
53642
- * (`enabled !== false`, so a row written before the field existed is on).
54039
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54040
+ * so a row written before the field existed is on). Absent when the `integrations` registry
54041
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
53643
54042
  */
53644
- enabled: boolean(),
54043
+ enabled: boolean().optional(),
53645
54044
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
53646
54045
  kind: string().optional(),
53647
54046
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
@@ -90662,6 +91061,44 @@ var ActionSceneExports = class {
90662
91061
  }
90663
91062
  };
90664
91063
  //#endregion
91064
+ //#region src/export-records.ts
91065
+ /**
91066
+ * What the Google export exposes, as a record (planning#408 P4): ONE `google-exports` record per
91067
+ * instance id (`export-google` today) holds the devices Google syncs and the actions it sees as
91068
+ * scenes. The addon is its only writer; the in-memory copy it loads at boot is what every
91069
+ * fulfillment intent reads.
91070
+ */
91071
+ /** A single-instance addon keeps its records under its own addon id. */
91072
+ var GOOGLE_INSTANCE_ID = "export-google";
91073
+ var ExposedDeviceEntrySchema = object({
91074
+ deviceId: number(),
91075
+ exposedAt: number()
91076
+ });
91077
+ var ActionSceneEntrySchema = object({
91078
+ actionId: string(),
91079
+ displayName: string(),
91080
+ addedAt: number()
91081
+ });
91082
+ var GoogleExportsBodySchema = object({
91083
+ name: string().min(1),
91084
+ devices: array(ExposedDeviceEntrySchema),
91085
+ actions: array(ActionSceneEntrySchema)
91086
+ });
91087
+ var GOOGLE_EXPORTS_KIND_NAME = "google-exports";
91088
+ var GOOGLE_EXPORTS_NAME = "Google exposure";
91089
+ var googleExportsKind = defineEntryKind(GOOGLE_EXPORTS_KIND_NAME, {
91090
+ title: "Google exposure",
91091
+ nameField: "name",
91092
+ schema: GoogleExportsBodySchema
91093
+ });
91094
+ var EMPTY_GOOGLE_EXPORTS = {
91095
+ name: GOOGLE_EXPORTS_NAME,
91096
+ devices: [],
91097
+ actions: []
91098
+ };
91099
+ /** The settings keys that moved into the record; the migrations name them. */
91100
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
91101
+ //#endregion
90665
91102
  //#region src/google-home/trait-catalog.ts
90666
91103
  /**
90667
91104
  * The trait catalog — one ROW per camstack capability, and that row is the
@@ -91492,24 +91929,151 @@ async function planDropPublicHubUrl(ports) {
91492
91929
  }] };
91493
91930
  }
91494
91931
  //#endregion
91932
+ //#region src/migrations/exposure-to-record.ts
91933
+ /**
91934
+ * The Google exposure lists move into the `google-exports` record (planning#408 P4). Two
91935
+ * migrations, both `block-owner`: the addon must not serve a membership it cannot trust, and
91936
+ * after them nothing reads the old keys.
91937
+ *
91938
+ * 1. `moveExposureToRecord` (procedure): `exposed` and `exposedActions` become the record under
91939
+ * the instance id. An existing record is never overwritten. A record this pass just wrote is
91940
+ * read BACK and must equal what the settings carried, or the pass throws.
91941
+ * 2. `planDropMovedExposure` (plan): the two keys are deleted only while the record holds every
91942
+ * device and action the settings carried; a record that cannot be read leaves them in place.
91943
+ */
91944
+ function devicesOf(value) {
91945
+ if (!Array.isArray(value)) return [];
91946
+ return value.flatMap((entry) => {
91947
+ const parsed = ExposedDeviceEntrySchema.safeParse(entry);
91948
+ return parsed.success ? [parsed.data] : [];
91949
+ });
91950
+ }
91951
+ function actionsOf(value) {
91952
+ if (!Array.isArray(value)) return [];
91953
+ return value.flatMap((entry) => {
91954
+ const parsed = ActionSceneEntrySchema.safeParse(entry);
91955
+ return parsed.success ? [parsed.data] : [];
91956
+ });
91957
+ }
91958
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
91959
+ function canonical(value) {
91960
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
91961
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
91962
+ return JSON.stringify(value) ?? "null";
91963
+ }
91964
+ async function moveExposureToRecord(ports) {
91965
+ const stored = await ports.readStored();
91966
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
91967
+ outcome: "already-done",
91968
+ summary: { moved: false }
91969
+ };
91970
+ const devices = devicesOf(stored["exposed"]);
91971
+ const actions = actionsOf(stored["exposedActions"]);
91972
+ const dropped = (Array.isArray(stored["exposed"]) ? stored["exposed"].length : 0) - devices.length + ((Array.isArray(stored["exposedActions"]) ? stored["exposedActions"].length : 0) - actions.length);
91973
+ if (dropped > 0) ports.warn(`Google migration: ${dropped} exposure entr(ies) were not understood and are left out`);
91974
+ const body = {
91975
+ name: GOOGLE_EXPORTS_NAME,
91976
+ devices,
91977
+ actions
91978
+ };
91979
+ if (await ports.putExports(body) === "exists") return {
91980
+ outcome: "already-done",
91981
+ summary: { moved: false }
91982
+ };
91983
+ const held = await ports.readExports();
91984
+ if (held === null || canonical(held.devices) !== canonical(devices) || canonical(held.actions) !== canonical(actions)) throw new Error("the Google exposure record does not match the legacy settings; nothing was cleared");
91985
+ return {
91986
+ outcome: "done",
91987
+ summary: {
91988
+ moved: true,
91989
+ devices: devices.length,
91990
+ actions: actions.length
91991
+ }
91992
+ };
91993
+ }
91994
+ var rowId = (key) => `${GOOGLE_INSTANCE_ID}.${key}`;
91995
+ async function planDropMovedExposure(ports) {
91996
+ const stored = await ports.readStored();
91997
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
91998
+ if (present.length === 0) return { edits: [] };
91999
+ const refuse = (reason) => {
92000
+ ports.warn(`Google migration: the legacy exposure keys are kept: ${reason}`);
92001
+ throw new Error(`the legacy Google exposure keys are not deleted: ${reason}`);
92002
+ };
92003
+ const held = await ports.readExports();
92004
+ if (held === null) return refuse("no exposure record exists");
92005
+ const heldDevices = new Set(held.devices.map((d) => d.deviceId));
92006
+ for (const device of devicesOf(stored["exposed"])) if (!heldDevices.has(device.deviceId)) return refuse(`the record lacks the device ${device.deviceId}`);
92007
+ const heldActions = new Set(held.actions.map((a) => a.actionId));
92008
+ for (const action of actionsOf(stored["exposedActions"])) if (!heldActions.has(action.actionId)) return refuse(`the record lacks the action ${action.actionId}`);
92009
+ return { edits: [{
92010
+ op: "deleteKeys",
92011
+ scope: ADDON_SETTINGS_TABLE,
92012
+ keys: present.map(rowId),
92013
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
92014
+ addonId: GOOGLE_INSTANCE_ID,
92015
+ key,
92016
+ value: stored[key]
92017
+ }])))
92018
+ }] };
92019
+ }
92020
+ //#endregion
91495
92021
  //#region src/migrations/index.ts
92022
+ var DROP_PUBLIC_HUB_URL_ID = "export-google/2026-11-02-drop-public-hub-url";
92023
+ var EXPOSURE_TO_RECORD_ID = "export-google/2026-11-04-exposure-to-record";
92024
+ var DROP_MOVED_EXPOSURE_ID = "export-google/2026-11-04-drop-moved-exposure";
92025
+ var FIXTURE_MARK = "the linked account list the migration does not know";
91496
92026
  /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
91497
- var ADDON_MIGRATIONS = [{
91498
- meta: {
91499
- id: "export-google/2026-11-02-drop-public-hub-url",
91500
- owner: "export-google",
91501
- level: "addon-state",
91502
- seq: 1,
91503
- dependsOn: [],
91504
- store: "settings",
91505
- scope: "cluster",
91506
- onFailure: "tolerate",
91507
- bodyKind: "plan",
91508
- description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
91509
- fixtureMark: "the exposed device list the migration does not know"
91510
- },
91511
- plan: planDropPublicHubUrl
91512
- }];
92027
+ var ADDON_MIGRATIONS = [
92028
+ {
92029
+ meta: {
92030
+ id: DROP_PUBLIC_HUB_URL_ID,
92031
+ owner: "export-google",
92032
+ level: "addon-state",
92033
+ seq: 1,
92034
+ dependsOn: [],
92035
+ store: "settings",
92036
+ scope: "cluster",
92037
+ onFailure: "tolerate",
92038
+ bodyKind: "plan",
92039
+ description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
92040
+ fixtureMark: FIXTURE_MARK
92041
+ },
92042
+ plan: planDropPublicHubUrl
92043
+ },
92044
+ {
92045
+ meta: {
92046
+ id: EXPOSURE_TO_RECORD_ID,
92047
+ owner: "export-google",
92048
+ level: "addon-state",
92049
+ seq: 2,
92050
+ dependsOn: [],
92051
+ store: "settings",
92052
+ scope: "cluster",
92053
+ onFailure: "block-owner",
92054
+ bodyKind: "procedure",
92055
+ description: "Move the exposed devices and actions into the google-exports record; the record is read back before anything is deleted",
92056
+ fixtureMark: FIXTURE_MARK
92057
+ },
92058
+ procedure: moveExposureToRecord
92059
+ },
92060
+ {
92061
+ meta: {
92062
+ id: DROP_MOVED_EXPOSURE_ID,
92063
+ owner: "export-google",
92064
+ level: "addon-state",
92065
+ seq: 3,
92066
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
92067
+ store: "settings",
92068
+ scope: "cluster",
92069
+ onFailure: "block-owner",
92070
+ bodyKind: "plan",
92071
+ description: "Delete the exposed and exposedActions settings keys once the record holds what they carried",
92072
+ fixtureMark: FIXTURE_MARK
92073
+ },
92074
+ plan: planDropMovedExposure
92075
+ }
92076
+ ];
91513
92077
  //#endregion
91514
92078
  //#region src/public-endpoint.ts
91515
92079
  /** The typed refusal when the role resolves to nothing. */
@@ -91579,11 +92143,7 @@ var buildConsoleSetupFromRole = async (input) => {
91579
92143
  };
91580
92144
  //#endregion
91581
92145
  //#region src/types.ts
91582
- var DEFAULT_SETTINGS = {
91583
- exposed: [],
91584
- exposedActions: [],
91585
- linkedAccounts: []
91586
- };
92146
+ var DEFAULT_SETTINGS = { linkedAccounts: [] };
91587
92147
  //#endregion
91588
92148
  //#region src/export-google.addon.ts
91589
92149
  /**
@@ -91625,6 +92185,31 @@ var DEFAULT_SETTINGS = {
91625
92185
  var ADDON_ID = "export-google";
91626
92186
  var ExportGoogleAddon = class extends BaseAddon {
91627
92187
  gateway = null;
92188
+ /**
92189
+ * The `google-exports` record: what Google syncs. Loaded once at boot after the migrations;
92190
+ * this addon is its only writer, so the in-memory copy is the synchronous read the fulfillment
92191
+ * path needs. No settings key backs it.
92192
+ */
92193
+ exportsRow = EMPTY_GOOGLE_EXPORTS;
92194
+ exportsHandle = null;
92195
+ get exposedDevices() {
92196
+ return this.exportsRow.devices;
92197
+ }
92198
+ /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
92199
+ async writeExports(patch) {
92200
+ const handle = this.exportsHandle;
92201
+ if (handle === null) throw new Error("export-google: the exposure record is not open");
92202
+ const next = {
92203
+ name: this.exportsRow.name,
92204
+ devices: patch.devices ?? this.exportsRow.devices,
92205
+ actions: patch.actions ?? this.exportsRow.actions
92206
+ };
92207
+ await handle.put({
92208
+ id: GOOGLE_INSTANCE_ID,
92209
+ data: next
92210
+ });
92211
+ this.exportsRow = next;
92212
+ }
91628
92213
  constructor() {
91629
92214
  super({ ...DEFAULT_SETTINGS });
91630
92215
  }
@@ -91634,15 +92219,43 @@ var ExportGoogleAddon = class extends BaseAddon {
91634
92219
  logger: this.ctx.logger
91635
92220
  });
91636
92221
  this.gateway = gateway;
91637
- await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, { readStored: async () => this.resolveGlobalStore() }));
92222
+ const records = this.ctx.records;
92223
+ if (records === void 0) throw new Error("export-google needs ctx.records — check execution.placement (hub-only)");
92224
+ await records.declare({ "google-exports": googleExportsKind });
92225
+ const exportsHandle = records.kind(googleExportsKind);
92226
+ this.exportsHandle = exportsHandle;
92227
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
92228
+ readStored: async () => this.resolveGlobalStore(),
92229
+ warn: (message) => {
92230
+ this.ctx.logger.warn(message, { tags: {
92231
+ topic: "export-google",
92232
+ phase: "migration"
92233
+ } });
92234
+ },
92235
+ putExports: async (body) => {
92236
+ if (await exportsHandle.get("export-google") !== null) return "exists";
92237
+ try {
92238
+ await exportsHandle.put({
92239
+ id: GOOGLE_INSTANCE_ID,
92240
+ data: body
92241
+ }, { ifRev: 0 });
92242
+ } catch (err) {
92243
+ if (err instanceof RevConflictError) return "exists";
92244
+ throw err;
92245
+ }
92246
+ return "created";
92247
+ },
92248
+ readExports: async () => (await exportsHandle.get("export-google"))?.data ?? null
92249
+ }));
92250
+ this.exportsRow = (await exportsHandle.get("export-google"))?.data ?? EMPTY_GOOGLE_EXPORTS;
91638
92251
  const actionScenes = new ActionSceneExports({
91639
92252
  api: this.ctx.api,
91640
92253
  logger: this.ctx.logger,
91641
92254
  isAdminUser: async (userId) => {
91642
92255
  return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
91643
92256
  },
91644
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
91645
- }, this.config.exposedActions ?? []);
92257
+ persist: (entries) => this.writeExports({ actions: [...entries] })
92258
+ }, this.exportsRow.actions);
91646
92259
  actionScenes.reconcile().catch((err) => {
91647
92260
  this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: { error: errMsg$1(err) } });
91648
92261
  });
@@ -91652,7 +92265,7 @@ var ExportGoogleAddon = class extends BaseAddon {
91652
92265
  ownInstance(statusInstanceOf(input));
91653
92266
  return {
91654
92267
  linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
91655
- exposedDeviceCount: this.config.exposed.length,
92268
+ exposedDeviceCount: this.exposedDevices.length,
91656
92269
  setup: await this.buildSetupBlock()
91657
92270
  };
91658
92271
  },
@@ -91668,7 +92281,7 @@ var ExportGoogleAddon = class extends BaseAddon {
91668
92281
  },
91669
92282
  listExposedDevices: async ({ instanceId }) => {
91670
92283
  ownInstance(instanceId);
91671
- return this.config.exposed.map((entry) => ({ deviceId: String(entry.deviceId) }));
92284
+ return this.exposedDevices.map((entry) => ({ deviceId: String(entry.deviceId) }));
91672
92285
  },
91673
92286
  exposeDevice: async ({ instanceId, deviceId }) => {
91674
92287
  ownInstance(instanceId);
@@ -91682,7 +92295,7 @@ var ExportGoogleAddon = class extends BaseAddon {
91682
92295
  listExposedEntities: async ({ instanceId }) => {
91683
92296
  ownInstance(instanceId);
91684
92297
  await actionScenes.reconcile();
91685
- return [...this.config.exposed.map((entry) => ({ entity: {
92298
+ return [...this.exposedDevices.map((entry) => ({ entity: {
91686
92299
  kind: "device",
91687
92300
  deviceId: String(entry.deviceId)
91688
92301
  } })), ...actionScenes.list()];
@@ -91711,7 +92324,7 @@ var ExportGoogleAddon = class extends BaseAddon {
91711
92324
  sync: {
91712
92325
  gateway,
91713
92326
  logger: this.ctx.logger,
91714
- listExposed: () => this.config.exposed.map((entry) => entry.deviceId),
92327
+ listExposed: () => this.exposedDevices.map((entry) => entry.deviceId),
91715
92328
  actions: actionScenes
91716
92329
  },
91717
92330
  query: {
@@ -91732,7 +92345,7 @@ var ExportGoogleAddon = class extends BaseAddon {
91732
92345
  }));
91733
92346
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
91734
92347
  this.ctx.logger.info("export-google: initialized", { meta: {
91735
- exposedCount: this.config.exposed.length,
92348
+ exposedCount: this.exposedDevices.length,
91736
92349
  linkedAccounts: this.config.linkedAccounts.length,
91737
92350
  willReportState: false
91738
92351
  } });
@@ -91755,7 +92368,7 @@ var ExportGoogleAddon = class extends BaseAddon {
91755
92368
  this.gateway = null;
91756
92369
  }
91757
92370
  isExposed(deviceId) {
91758
- return this.config.exposed.some((entry) => entry.deviceId === deviceId);
92371
+ return this.exposedDevices.some((entry) => entry.deviceId === deviceId);
91759
92372
  }
91760
92373
  async exposeDevice(deviceIdRaw) {
91761
92374
  const deviceId = Number.parseInt(deviceIdRaw, 10);
@@ -91774,20 +92387,20 @@ var ExportGoogleAddon = class extends BaseAddon {
91774
92387
  });
91775
92388
  throw new Error(`export-google: device ${deviceId} has no capability this addon exports (bound: ${facts.capNames.join(", ") || "none"})`);
91776
92389
  }
91777
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
92390
+ const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
91778
92391
  next.push({
91779
92392
  deviceId,
91780
92393
  exposedAt: Date.now()
91781
92394
  });
91782
- await this.updateGlobalSettings({ exposed: next });
92395
+ await this.writeExports({ devices: next });
91783
92396
  this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", { tags: { deviceId } });
91784
92397
  }
91785
92398
  async unexposeDevice(deviceIdRaw) {
91786
92399
  const deviceId = Number.parseInt(deviceIdRaw, 10);
91787
92400
  if (!Number.isFinite(deviceId)) return;
91788
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
91789
- if (next.length === this.config.exposed.length) return;
91790
- await this.updateGlobalSettings({ exposed: next });
92401
+ const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
92402
+ if (next.length === this.exposedDevices.length) return;
92403
+ await this.writeExports({ devices: next });
91791
92404
  this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", { tags: { deviceId } });
91792
92405
  }
91793
92406
  requireGateway() {