@meshagent/meshagent-ts-auth 0.35.6 → 0.35.7

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.
@@ -14835,11 +14835,14 @@ ${err.toString()}`);
14835
14835
  }
14836
14836
  function toCredentials(values) {
14837
14837
  return values.map((entry) => ({
14838
- registry: entry.registry,
14838
+ registry: entry.registry ?? null,
14839
14839
  username: entry.username,
14840
14840
  password: entry.password
14841
14841
  }));
14842
14842
  }
14843
+ function toMountList(values) {
14844
+ return values.map((entry) => entry);
14845
+ }
14843
14846
  function readStringField(data, field, operation) {
14844
14847
  const value = data[field];
14845
14848
  if (typeof value !== "string") {
@@ -14847,28 +14850,124 @@ ${err.toString()}`);
14847
14850
  }
14848
14851
  return value;
14849
14852
  }
14850
- function decodeJsonStatus(data) {
14851
- const text = new TextDecoder().decode(data);
14853
+ function readIntegerField(data, field, operation) {
14854
+ const value = data[field];
14855
+ if (typeof value !== "number" || !Number.isInteger(value)) {
14856
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14857
+ }
14858
+ return value;
14859
+ }
14860
+ function readOptionalIntegerField(data, field, operation) {
14861
+ const value = data[field];
14862
+ if (value === void 0 || value === null) {
14863
+ return void 0;
14864
+ }
14865
+ if (typeof value !== "number" || !Number.isInteger(value)) {
14866
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14867
+ }
14868
+ return value;
14869
+ }
14870
+ function decodeUtf8(data, operation) {
14871
+ try {
14872
+ return new TextDecoder("utf-8", { fatal: true }).decode(data);
14873
+ } catch {
14874
+ throw new room_server_client_1.RoomServerException(`containers.${operation} returned invalid UTF-8 data`);
14875
+ }
14876
+ }
14877
+ function decodeJsonStatus(data, operation) {
14878
+ const text = decodeUtf8(data, operation);
14852
14879
  let parsed;
14853
14880
  try {
14854
14881
  parsed = JSON.parse(text);
14855
14882
  } catch {
14856
- throw new room_server_client_1.RoomServerException("containers.exec returned an invalid status payload");
14883
+ throw new room_server_client_1.RoomServerException(`containers.${operation} returned an invalid status payload`);
14857
14884
  }
14858
14885
  if (!isRecord(parsed)) {
14859
- throw new room_server_client_1.RoomServerException("containers.exec returned an invalid status payload");
14886
+ throw new room_server_client_1.RoomServerException(`containers.${operation} returned an invalid status payload`);
14860
14887
  }
14861
14888
  const status = parsed["status"];
14862
14889
  if (typeof status !== "number" || !Number.isInteger(status)) {
14863
- throw new room_server_client_1.RoomServerException("containers.exec returned an invalid status payload");
14890
+ throw new room_server_client_1.RoomServerException(`containers.${operation} returned an invalid status payload`);
14864
14891
  }
14865
14892
  return status;
14866
14893
  }
14894
+ function normalizeImageLabels(labelsRaw, operation) {
14895
+ if (Array.isArray(labelsRaw)) {
14896
+ const labels = {};
14897
+ for (const entry of labelsRaw) {
14898
+ if (!isRecord(entry)) {
14899
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14900
+ }
14901
+ const key = entry["key"];
14902
+ const value = entry["value"];
14903
+ if (typeof key !== "string" || typeof value !== "string") {
14904
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14905
+ }
14906
+ labels[key] = value;
14907
+ }
14908
+ return labels;
14909
+ }
14910
+ if (isRecord(labelsRaw)) {
14911
+ const labels = {};
14912
+ for (const [key, value] of Object.entries(labelsRaw)) {
14913
+ if (typeof value !== "string") {
14914
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14915
+ }
14916
+ labels[key] = value;
14917
+ }
14918
+ return labels;
14919
+ }
14920
+ if (labelsRaw === void 0 || labelsRaw === null) {
14921
+ return {};
14922
+ }
14923
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14924
+ }
14925
+ function parseImportedImage(data, operation) {
14926
+ const resolvedRef = data["resolved_ref"];
14927
+ const refsRaw = data["refs"];
14928
+ if (typeof resolvedRef !== "string" || !Array.isArray(refsRaw) || refsRaw.some((entry) => typeof entry !== "string")) {
14929
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14930
+ }
14931
+ return {
14932
+ resolvedRef,
14933
+ refs: refsRaw
14934
+ };
14935
+ }
14936
+ function parseBuildJob(data, operation) {
14937
+ const id = readStringField(data, "id", operation);
14938
+ const tag2 = readStringField(data, "tag", operation);
14939
+ const status = readStringField(data, "status", operation);
14940
+ if (!["queued", "running", "failed", "cancelled", "succeeded"].includes(status)) {
14941
+ throw new room_server_client_1.RoomServerException(`unexpected return type from containers.${operation}`);
14942
+ }
14943
+ return {
14944
+ id,
14945
+ tag: tag2,
14946
+ status,
14947
+ exitCode: readOptionalIntegerField(data, "exit_code", operation)
14948
+ };
14949
+ }
14950
+ function buildRequestPayload(params) {
14951
+ return {
14952
+ tag: params.tag,
14953
+ mounts: toMountList(params.mounts),
14954
+ context_path: params.contextPath,
14955
+ dockerfile_path: params.dockerfilePath ?? null,
14956
+ private: params.private ?? false,
14957
+ credentials: toCredentials(params.credentials ?? []),
14958
+ context_archive_path: params.contextArchivePath ?? null,
14959
+ context_archive_ref: params.contextArchiveRef ?? null,
14960
+ context_archive_mount_path: params.contextArchiveMountPath ?? null,
14961
+ context_archive_arch: params.contextArchiveArch ?? null
14962
+ };
14963
+ }
14867
14964
  var ExecSession = class {
14868
14965
  constructor(params) {
14869
14966
  this.previousOutput = [];
14967
+ this.previousError = [];
14870
14968
  this.resultCompleter = new completer_1.Completer();
14871
14969
  this.outputController = new stream_controller_1.StreamController();
14970
+ this.errorController = new stream_controller_1.StreamController();
14872
14971
  this.queuedInput = [];
14873
14972
  this.inputClosed = false;
14874
14973
  this.closed = false;
@@ -14879,6 +14978,7 @@ ${err.toString()}`);
14879
14978
  this.tty = params.tty;
14880
14979
  this.result = this.resultCompleter.fut;
14881
14980
  this.output = this.outputController.stream;
14981
+ this.stderr = this.errorController.stream;
14882
14982
  }
14883
14983
  async *inputStream() {
14884
14984
  yield new response_1.BinaryContent({
@@ -14933,6 +15033,7 @@ ${err.toString()}`);
14933
15033
  this.closed = true;
14934
15034
  this.closeInputStream();
14935
15035
  this.outputController.close();
15036
+ this.errorController.close();
14936
15037
  }
14937
15038
  closeError(error) {
14938
15039
  if (!this.resultCompleter.completed) {
@@ -14941,11 +15042,16 @@ ${err.toString()}`);
14941
15042
  this.closed = true;
14942
15043
  this.closeInputStream();
14943
15044
  this.outputController.close();
15045
+ this.errorController.close();
14944
15046
  }
14945
15047
  addOutput(data) {
14946
15048
  this.previousOutput.push(data);
14947
15049
  this.outputController.add(data);
14948
15050
  }
15051
+ addError(data) {
15052
+ this.previousError.push(data);
15053
+ this.errorController.add(data);
15054
+ }
14949
15055
  get isClosed() {
14950
15056
  return this.closed;
14951
15057
  }
@@ -14989,7 +15095,7 @@ ${err.toString()}`);
14989
15095
  }
14990
15096
  async listImages() {
14991
15097
  const output = await this.invoke("list_images", {});
14992
- if (!(output instanceof response_1.JsonContent)) {
15098
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
14993
15099
  throw this.unexpectedResponseError("list_images");
14994
15100
  }
14995
15101
  const imagesRaw = output.json["images"];
@@ -15013,17 +15119,65 @@ ${err.toString()}`);
15013
15119
  id,
15014
15120
  tags: normalizedTags,
15015
15121
  size: typeof size === "number" ? size : void 0,
15016
- labels: isRecord(labelsRaw) ? labelsRaw : {}
15122
+ labels: normalizeImageLabels(labelsRaw, "list_images")
15017
15123
  });
15018
15124
  }
15019
15125
  return images;
15020
15126
  }
15127
+ async deleteImage(params) {
15128
+ await this.invoke("delete_image", {
15129
+ image: params.image
15130
+ });
15131
+ }
15021
15132
  async pullImage(params) {
15022
15133
  await this.invoke("pull_image", {
15023
15134
  tag: params.tag,
15024
15135
  credentials: toCredentials(params.credentials ?? [])
15025
15136
  });
15026
15137
  }
15138
+ async pushImage(params) {
15139
+ const output = await this.invoke("push_image", {
15140
+ tag: params.tag,
15141
+ credentials: toCredentials(params.credentials ?? []),
15142
+ private: params.private ?? false
15143
+ });
15144
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15145
+ throw this.unexpectedResponseError("push_image");
15146
+ }
15147
+ return readStringField(output.json, "container_id", "push_image");
15148
+ }
15149
+ async load(params) {
15150
+ const output = await this.invoke("load", {
15151
+ archive_path: params.archivePath
15152
+ });
15153
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15154
+ throw this.unexpectedResponseError("load");
15155
+ }
15156
+ return parseImportedImage(output.json, "load");
15157
+ }
15158
+ async loadImage(params) {
15159
+ const output = await this.invoke("load_image", {
15160
+ mounts: toMountList(params.mounts),
15161
+ archive_path: params.archivePath,
15162
+ private: params.private ?? false
15163
+ });
15164
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15165
+ throw this.unexpectedResponseError("load_image");
15166
+ }
15167
+ return readStringField(output.json, "container_id", "load_image");
15168
+ }
15169
+ async saveImage(params) {
15170
+ const output = await this.invoke("save_image", {
15171
+ tag: params.tag,
15172
+ mounts: toMountList(params.mounts),
15173
+ archive_path: params.archivePath,
15174
+ private: params.private ?? false
15175
+ });
15176
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15177
+ throw this.unexpectedResponseError("save_image");
15178
+ }
15179
+ return readStringField(output.json, "container_id", "save_image");
15180
+ }
15027
15181
  async run(params) {
15028
15182
  const output = await this.invoke("run", {
15029
15183
  image: params.image,
@@ -15046,6 +15200,46 @@ ${err.toString()}`);
15046
15200
  }
15047
15201
  return readStringField(output.json, "container_id", "run");
15048
15202
  }
15203
+ async startBuild(params) {
15204
+ const output = await this.invoke("start_build", buildRequestPayload(params));
15205
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15206
+ throw this.unexpectedResponseError("start_build");
15207
+ }
15208
+ return readStringField(output.json, "build_id", "start_build");
15209
+ }
15210
+ async build(params) {
15211
+ const output = await this.invoke("build", buildRequestPayload(params));
15212
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15213
+ throw this.unexpectedResponseError("build");
15214
+ }
15215
+ return readStringField(output.json, "build_id", "build");
15216
+ }
15217
+ async listBuilds() {
15218
+ const output = await this.invoke("list_builds", {});
15219
+ if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15220
+ throw this.unexpectedResponseError("list_builds");
15221
+ }
15222
+ const buildsRaw = output.json["builds"];
15223
+ if (!Array.isArray(buildsRaw)) {
15224
+ throw this.unexpectedResponseError("list_builds");
15225
+ }
15226
+ return buildsRaw.map((entry) => {
15227
+ if (!isRecord(entry)) {
15228
+ throw this.unexpectedResponseError("list_builds");
15229
+ }
15230
+ return parseBuildJob(entry, "list_builds");
15231
+ });
15232
+ }
15233
+ async cancelBuild(params) {
15234
+ await this.invoke("cancel_build", {
15235
+ build_id: params.buildId
15236
+ });
15237
+ }
15238
+ async deleteBuild(params) {
15239
+ await this.invoke("delete_build", {
15240
+ build_id: params.buildId
15241
+ });
15242
+ }
15049
15243
  async runService(params) {
15050
15244
  const output = await this.invoke("run_service", {
15051
15245
  service_id: params.serviceId,
@@ -15073,6 +15267,12 @@ ${err.toString()}`);
15073
15267
  if (chunk instanceof response_1.ErrorContent) {
15074
15268
  throw new room_server_client_1.RoomServerException(chunk.text, chunk.code);
15075
15269
  }
15270
+ if (chunk instanceof response_1.ControlContent) {
15271
+ if (chunk.method === "close") {
15272
+ break;
15273
+ }
15274
+ throw this.unexpectedResponseError("exec");
15275
+ }
15076
15276
  if (!(chunk instanceof response_1.BinaryContent)) {
15077
15277
  throw this.unexpectedResponseError("exec");
15078
15278
  }
@@ -15084,8 +15284,12 @@ ${err.toString()}`);
15084
15284
  session.addOutput(chunk.data);
15085
15285
  continue;
15086
15286
  }
15287
+ if (channel === 2) {
15288
+ session.addError(chunk.data);
15289
+ continue;
15290
+ }
15087
15291
  if (channel === 3) {
15088
- session.close(decodeJsonStatus(chunk.data));
15292
+ session.close(decodeJsonStatus(chunk.data, "exec"));
15089
15293
  return;
15090
15294
  }
15091
15295
  }
@@ -15098,7 +15302,7 @@ ${err.toString()}`);
15098
15302
  async stop(params) {
15099
15303
  await this.invoke("stop_container", {
15100
15304
  container_id: params.containerId,
15101
- force: params.force ?? true
15305
+ force: params.force ?? false
15102
15306
  });
15103
15307
  }
15104
15308
  async waitForExit(params) {
@@ -15108,11 +15312,7 @@ ${err.toString()}`);
15108
15312
  if (!(output instanceof response_1.JsonContent) || !isRecord(output.json)) {
15109
15313
  throw this.unexpectedResponseError("wait_for_exit");
15110
15314
  }
15111
- const exitCode = output.json["exit_code"];
15112
- if (typeof exitCode !== "number" || !Number.isInteger(exitCode)) {
15113
- throw this.unexpectedResponseError("wait_for_exit");
15114
- }
15115
- return exitCode;
15315
+ return readIntegerField(output.json, "exit_code", "wait_for_exit");
15116
15316
  }
15117
15317
  async deleteContainer(params) {
15118
15318
  await this.invoke("delete_container", {
@@ -15151,13 +15351,20 @@ ${err.toString()}`);
15151
15351
  tool: "logs",
15152
15352
  input: inputStream()
15153
15353
  }).then(async (stream) => {
15154
- const decoder2 = new TextDecoder();
15155
15354
  for await (const chunk of stream) {
15156
15355
  if (chunk instanceof response_1.ErrorContent) {
15157
15356
  throw new room_server_client_1.RoomServerException(chunk.text, chunk.code);
15158
15357
  }
15159
15358
  if (chunk instanceof response_1.ControlContent) {
15160
- continue;
15359
+ if (chunk.method === "close") {
15360
+ closeInputStream();
15361
+ streamController.close();
15362
+ if (!result.completed) {
15363
+ result.complete();
15364
+ }
15365
+ return;
15366
+ }
15367
+ throw this.unexpectedResponseError("logs");
15161
15368
  }
15162
15369
  if (!(chunk instanceof response_1.BinaryContent)) {
15163
15370
  throw this.unexpectedResponseError("logs");
@@ -15169,11 +15376,122 @@ ${err.toString()}`);
15169
15376
  if (channel !== 1) {
15170
15377
  continue;
15171
15378
  }
15172
- streamController.add(decoder2.decode(chunk.data));
15379
+ streamController.add(decodeUtf8(chunk.data, "logs"));
15173
15380
  }
15174
15381
  closeInputStream();
15175
15382
  streamController.close();
15176
- result.complete();
15383
+ if (!result.completed) {
15384
+ result.complete();
15385
+ }
15386
+ }).catch((error) => {
15387
+ closeInputStream();
15388
+ streamController.close();
15389
+ if (!result.completed) {
15390
+ result.completeError(error);
15391
+ }
15392
+ });
15393
+ const outputStream = {
15394
+ [Symbol.asyncIterator]() {
15395
+ const it = streamController.stream[Symbol.asyncIterator]();
15396
+ return {
15397
+ async next() {
15398
+ return await it.next();
15399
+ },
15400
+ async return(value) {
15401
+ closeInputStream();
15402
+ return await it.return?.(value) ?? { done: true, value };
15403
+ },
15404
+ async throw(e) {
15405
+ closeInputStream();
15406
+ if (it.throw) {
15407
+ return await it.throw(e);
15408
+ }
15409
+ throw e;
15410
+ }
15411
+ };
15412
+ }
15413
+ };
15414
+ return {
15415
+ stream: outputStream,
15416
+ result: result.fut,
15417
+ cancel: async () => {
15418
+ closeInputStream();
15419
+ await result.fut.catch(() => void 0);
15420
+ }
15421
+ };
15422
+ }
15423
+ getBuildLogs(params) {
15424
+ const requestId = (0, uuid_1.v4)();
15425
+ const closeInput = new completer_1.Completer();
15426
+ const streamController = new stream_controller_1.StreamController();
15427
+ const result = new completer_1.Completer();
15428
+ let inputClosed = false;
15429
+ const closeInputStream = () => {
15430
+ if (inputClosed) {
15431
+ return;
15432
+ }
15433
+ inputClosed = true;
15434
+ if (!closeInput.completed) {
15435
+ closeInput.complete();
15436
+ }
15437
+ };
15438
+ const inputStream = async function* () {
15439
+ yield new response_1.BinaryContent({
15440
+ data: new Uint8Array(0),
15441
+ headers: {
15442
+ kind: "start",
15443
+ request_id: requestId,
15444
+ build_id: params.buildId,
15445
+ follow: params.follow ?? true
15446
+ }
15447
+ });
15448
+ await closeInput.fut;
15449
+ };
15450
+ this.room.invokeStream({
15451
+ toolkit: "containers",
15452
+ tool: "get_build_logs",
15453
+ input: inputStream()
15454
+ }).then(async (stream) => {
15455
+ for await (const chunk of stream) {
15456
+ if (chunk instanceof response_1.ErrorContent) {
15457
+ throw new room_server_client_1.RoomServerException(chunk.text, chunk.code);
15458
+ }
15459
+ if (chunk instanceof response_1.ControlContent) {
15460
+ if (chunk.method === "close") {
15461
+ closeInputStream();
15462
+ streamController.close();
15463
+ if (!result.completed) {
15464
+ result.complete(null);
15465
+ }
15466
+ return;
15467
+ }
15468
+ throw this.unexpectedResponseError("get_build_logs");
15469
+ }
15470
+ if (!(chunk instanceof response_1.BinaryContent)) {
15471
+ throw this.unexpectedResponseError("get_build_logs");
15472
+ }
15473
+ const channel = chunk.headers["channel"];
15474
+ if (typeof channel !== "number") {
15475
+ throw new room_server_client_1.RoomServerException("containers.get_build_logs returned a chunk without a valid channel");
15476
+ }
15477
+ if (channel === 1) {
15478
+ streamController.add(decodeUtf8(chunk.data, "get_build_logs"));
15479
+ continue;
15480
+ }
15481
+ if (channel === 3) {
15482
+ closeInputStream();
15483
+ streamController.close();
15484
+ if (!result.completed) {
15485
+ result.complete(decodeJsonStatus(chunk.data, "get_build_logs"));
15486
+ }
15487
+ return;
15488
+ }
15489
+ }
15490
+ closeInputStream();
15491
+ streamController.close();
15492
+ if (!result.completed) {
15493
+ result.complete(null);
15494
+ }
15177
15495
  }).catch((error) => {
15178
15496
  closeInputStream();
15179
15497
  streamController.close();
@@ -15510,6 +15828,52 @@ ${err.toString()}`);
15510
15828
  data_type: toolkitDataTypeJson(dataType)
15511
15829
  }));
15512
15830
  }
15831
+ function publicDataTypeJson(value) {
15832
+ if (!isRecord(value)) {
15833
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.inspect");
15834
+ }
15835
+ const type = value.type;
15836
+ if (typeof type !== "string") {
15837
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.inspect");
15838
+ }
15839
+ const metadataList = value.metadata;
15840
+ let metadata;
15841
+ if (metadataList != null) {
15842
+ if (!Array.isArray(metadataList)) {
15843
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.inspect");
15844
+ }
15845
+ metadata = {};
15846
+ for (const entry of metadataList) {
15847
+ if (!isRecord(entry) || typeof entry.key !== "string" || typeof entry.value !== "string") {
15848
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.inspect");
15849
+ }
15850
+ metadata[entry.key] = entry.value;
15851
+ }
15852
+ }
15853
+ const payload = {
15854
+ type,
15855
+ nullable: value.nullable,
15856
+ metadata
15857
+ };
15858
+ if (type === "vector") {
15859
+ payload.size = value.size;
15860
+ payload.element_type = publicDataTypeJson(value.element_type);
15861
+ } else if (type === "list") {
15862
+ payload.element_type = publicDataTypeJson(value.element_type);
15863
+ } else if (type === "struct") {
15864
+ const rawFields = value.fields;
15865
+ if (!Array.isArray(rawFields)) {
15866
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.inspect");
15867
+ }
15868
+ payload.fields = Object.fromEntries(rawFields.map((field) => {
15869
+ if (!isRecord(field) || typeof field.name !== "string") {
15870
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.inspect");
15871
+ }
15872
+ return [field.name, publicDataTypeJson(field.data_type)];
15873
+ }));
15874
+ }
15875
+ return payload;
15876
+ }
15513
15877
  function encodeLegacyValue(value) {
15514
15878
  if (value instanceof Uint8Array) {
15515
15879
  return {
@@ -15679,6 +16043,47 @@ ${err.toString()}`);
15679
16043
  }
15680
16044
  return null;
15681
16045
  }
16046
+ function normalizeTableRefs(tables) {
16047
+ return tables.map((table) => typeof table === "string" ? { name: table } : table);
16048
+ }
16049
+ function tableIndexFromJson(value) {
16050
+ if (!isRecord(value) || typeof value.name !== "string" || typeof value.type !== "string" || !Array.isArray(value.columns)) {
16051
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_indexes");
16052
+ }
16053
+ return {
16054
+ name: value.name,
16055
+ type: value.type,
16056
+ columns: value.columns.map((column) => {
16057
+ if (typeof column !== "string") {
16058
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_indexes");
16059
+ }
16060
+ return column;
16061
+ })
16062
+ };
16063
+ }
16064
+ function tableVersionFromJson(value) {
16065
+ if (!isRecord(value) || typeof value.metadata_json !== "string" || typeof value.timestamp !== "string" || typeof value.version !== "number") {
16066
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_versions");
16067
+ }
16068
+ const timestamp = new Date(value.timestamp);
16069
+ if (Number.isNaN(timestamp.getTime())) {
16070
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_versions");
16071
+ }
16072
+ let metadata;
16073
+ try {
16074
+ metadata = JSON.parse(value.metadata_json);
16075
+ } catch (_) {
16076
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_versions");
16077
+ }
16078
+ if (!isRecord(metadata)) {
16079
+ throw new room_server_client_1.RoomServerException("unexpected return type from database.list_versions");
16080
+ }
16081
+ return {
16082
+ version: value.version,
16083
+ timestamp,
16084
+ metadata
16085
+ };
16086
+ }
15682
16087
  var DatabaseWriteInputStream = class {
15683
16088
  constructor(start, chunks) {
15684
16089
  this.start = start;
@@ -15857,79 +16262,90 @@ ${err.toString()}`);
15857
16262
  input.close();
15858
16263
  }
15859
16264
  }
15860
- async listTables() {
15861
- const response = await this.invoke("list_tables", { namespace: null });
16265
+ async listTables({ namespace } = {}) {
16266
+ const response = await this.invoke("list_tables", { namespace: namespace ?? null });
15862
16267
  if (!(response instanceof response_1.JsonContent)) {
15863
16268
  throw this._unexpectedResponseError("list_tables");
15864
16269
  }
15865
16270
  return Array.isArray(response.json.tables) ? response.json.tables : [];
15866
16271
  }
15867
- async createTable({ name, data, schema, mode = "create" }) {
16272
+ async createTable({ name, data, schema, mode = "create", namespace, metadata }) {
15868
16273
  const input = new DatabaseWriteInputStream({
15869
16274
  kind: "start",
15870
16275
  name,
15871
16276
  fields: schemaEntries(schema),
15872
16277
  mode,
15873
- namespace: null,
15874
- metadata: null
16278
+ namespace: namespace ?? null,
16279
+ metadata: metadataEntries(metadata)
15875
16280
  }, data ?? []);
15876
16281
  await this.drainWriteStream("create_table", input);
15877
16282
  }
15878
- async createTableWithSchema({ name, schema, data, mode = "create" }) {
16283
+ async createTableWithSchema({ name, schema, data, mode = "create", namespace, metadata }) {
15879
16284
  return this.createTable({
15880
16285
  name,
15881
16286
  schema,
15882
16287
  data: data == null ? void 0 : rowChunkList(data),
15883
- mode
16288
+ mode,
16289
+ namespace,
16290
+ metadata
15884
16291
  });
15885
16292
  }
15886
- async createTableFromData({ name, data, mode = "create" }) {
16293
+ async createTableFromData({ name, data, mode = "create", namespace, metadata }) {
15887
16294
  return this.createTable({
15888
16295
  name,
15889
16296
  data: data == null ? void 0 : rowChunkList(data),
15890
- mode
16297
+ mode,
16298
+ namespace,
16299
+ metadata
15891
16300
  });
15892
16301
  }
15893
- async createTableFromDataStream({ name, chunks, schema, mode = "create" }) {
15894
- return this.createTable({ name, data: chunks, schema, mode });
16302
+ async createTableFromDataStream({ name, chunks, schema, mode = "create", namespace, metadata }) {
16303
+ return this.createTable({ name, data: chunks, schema, mode, namespace, metadata });
15895
16304
  }
15896
- async dropTable({ name, ignoreMissing = false }) {
16305
+ async dropTable({ name, ignoreMissing = false, namespace }) {
15897
16306
  await this.room.invoke({
15898
16307
  toolkit: "database",
15899
16308
  tool: "drop_table",
15900
- input: { name, ignore_missing: ignoreMissing, namespace: null }
16309
+ input: { name, ignore_missing: ignoreMissing, namespace: namespace ?? null }
15901
16310
  });
15902
16311
  }
15903
- async addColumns({ table, newColumns }) {
16312
+ async dropIndex({ table, name, namespace }) {
16313
+ await this.room.invoke({
16314
+ toolkit: "database",
16315
+ tool: "drop_index",
16316
+ input: { table, name, namespace: namespace ?? null }
16317
+ });
16318
+ }
16319
+ async addColumns({ table, newColumns, namespace }) {
15904
16320
  await this.room.invoke({
15905
16321
  toolkit: "database",
15906
16322
  tool: "add_columns",
15907
16323
  input: {
15908
16324
  table,
15909
- columns: Object.entries(newColumns).map(([name, valueSql]) => ({ name, value_sql: valueSql, data_type: null })),
15910
- namespace: null
16325
+ columns: Object.entries(newColumns).map(([name, value]) => value instanceof data_types_1.DataType ? { name, value_sql: null, data_type: toolkitDataTypeJson(value) } : { name, value_sql: value, data_type: null }),
16326
+ namespace: namespace ?? null
15911
16327
  }
15912
16328
  });
15913
16329
  }
15914
- async dropColumns({ table, columns }) {
16330
+ async dropColumns({ table, columns, namespace }) {
15915
16331
  await this.room.invoke({
15916
16332
  toolkit: "database",
15917
16333
  tool: "drop_columns",
15918
- input: { table, columns, namespace: null }
16334
+ input: { table, columns, namespace: namespace ?? null }
15919
16335
  });
15920
16336
  }
15921
- async insert({ table, records }) {
15922
- await this.insertStream({ table, chunks: rowChunkList(records) });
16337
+ async insert({ table, records, namespace }) {
16338
+ await this.insertStream({ table, chunks: rowChunkList(records), namespace });
15923
16339
  }
15924
- async insertStream({ table, chunks }) {
16340
+ async insertStream({ table, chunks, namespace }) {
15925
16341
  const input = new DatabaseWriteInputStream({
15926
16342
  kind: "start",
15927
16343
  table,
15928
- namespace: null
16344
+ namespace: namespace ?? null
15929
16345
  }, chunks);
15930
16346
  await this.drainWriteStream("insert", input);
15931
16347
  }
15932
- async update({ table, where, values, valuesSql }) {
16348
+ async update({ table, where, values, valuesSql, namespace }) {
15933
16349
  await this.room.invoke({
15934
16350
  toolkit: "database",
15935
16351
  tool: "update",
@@ -15938,26 +16354,26 @@ ${err.toString()}`);
15938
16354
  where,
15939
16355
  values: values == null ? null : Object.entries(values).map(([column, value]) => ({ column, value_json: JSON.stringify(encodeLegacyValue(value)) })),
15940
16356
  values_sql: valuesSql == null ? null : Object.entries(valuesSql).map(([column, expression]) => ({ column, expression })),
15941
- namespace: null
16357
+ namespace: namespace ?? null
15942
16358
  }
15943
16359
  });
15944
16360
  }
15945
- async delete({ table, where }) {
16361
+ async delete({ table, where, namespace }) {
15946
16362
  await this.room.invoke({
15947
16363
  toolkit: "database",
15948
16364
  tool: "delete",
15949
- input: { table, where, namespace: null }
16365
+ input: { table, where, namespace: namespace ?? null }
15950
16366
  });
15951
16367
  }
15952
- async merge({ table, on, records }) {
15953
- await this.mergeStream({ table, on, chunks: rowChunkList(records) });
16368
+ async merge({ table, on, records, namespace }) {
16369
+ await this.mergeStream({ table, on, chunks: rowChunkList(records), namespace });
15954
16370
  }
15955
- async mergeStream({ table, on, chunks }) {
16371
+ async mergeStream({ table, on, chunks, namespace }) {
15956
16372
  const input = new DatabaseWriteInputStream({
15957
16373
  kind: "start",
15958
16374
  table,
15959
16375
  on,
15960
- namespace: null
16376
+ namespace: namespace ?? null
15961
16377
  }, chunks);
15962
16378
  await this.drainWriteStream("merge", input);
15963
16379
  }
@@ -15972,18 +16388,18 @@ ${err.toString()}`);
15972
16388
  yield* this.streamRows("sql", {
15973
16389
  kind: "start",
15974
16390
  query,
15975
- tables,
16391
+ tables: normalizeTableRefs(tables),
15976
16392
  params_json: params == null ? null : JSON.stringify(encodeLegacyValue(params))
15977
16393
  });
15978
16394
  }
15979
- async search({ table, text, vector, where, limit, select }) {
16395
+ async search({ table, text, vector, where, offset, limit, select, namespace }) {
15980
16396
  const rows = [];
15981
- for await (const chunk of this.searchStream({ table, text, vector, where, limit, select })) {
16397
+ for await (const chunk of this.searchStream({ table, text, vector, where, offset, limit, select, namespace })) {
15982
16398
  rows.push(...chunk);
15983
16399
  }
15984
16400
  return rows;
15985
16401
  }
15986
- async *searchStream({ table, text, vector, where, limit, select }) {
16402
+ async *searchStream({ table, text, vector, where, offset, limit, select, namespace }) {
15987
16403
  yield* this.streamRows("search", {
15988
16404
  kind: "start",
15989
16405
  table,
@@ -15991,45 +16407,91 @@ ${err.toString()}`);
15991
16407
  vector: vector ?? null,
15992
16408
  text_columns: null,
15993
16409
  where: buildWhereClause(where),
15994
- offset: null,
16410
+ offset: offset ?? null,
15995
16411
  limit: limit ?? null,
15996
16412
  select: select ?? null,
15997
- namespace: null
16413
+ namespace: namespace ?? null
15998
16414
  });
15999
16415
  }
16000
- async optimize(table) {
16001
- await this.room.invoke({ toolkit: "database", tool: "optimize", input: { table, namespace: null } });
16416
+ async count({ table, text, vector, where, namespace }) {
16417
+ const response = await this.invoke("count", {
16418
+ table,
16419
+ text: text ?? null,
16420
+ vector: vector ?? null,
16421
+ text_columns: null,
16422
+ where: buildWhereClause(where),
16423
+ namespace: namespace ?? null
16424
+ });
16425
+ if (!(response instanceof response_1.JsonContent) || typeof response.json.count !== "number" || !Number.isInteger(response.json.count)) {
16426
+ throw this._unexpectedResponseError("count");
16427
+ }
16428
+ return response.json.count;
16429
+ }
16430
+ async inspect({ table, namespace }) {
16431
+ const response = await this.invoke("inspect", { table, namespace: namespace ?? null });
16432
+ if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.fields)) {
16433
+ throw this._unexpectedResponseError("inspect");
16434
+ }
16435
+ return Object.fromEntries(response.json.fields.map((field) => {
16436
+ if (!isRecord(field) || typeof field.name !== "string") {
16437
+ throw this._unexpectedResponseError("inspect");
16438
+ }
16439
+ return [field.name, data_types_1.DataType.fromJson(publicDataTypeJson(field.data_type))];
16440
+ }));
16002
16441
  }
16003
- async createVectorIndex({ table, column, replace = false }) {
16442
+ async optimize(tableOrParams) {
16443
+ const table = typeof tableOrParams === "string" ? tableOrParams : tableOrParams.table;
16444
+ const namespace = typeof tableOrParams === "string" ? void 0 : tableOrParams.namespace;
16445
+ await this.room.invoke({ toolkit: "database", tool: "optimize", input: { table, namespace: namespace ?? null } });
16446
+ }
16447
+ async restore({ table, version, namespace }) {
16448
+ await this.room.invoke({
16449
+ toolkit: "database",
16450
+ tool: "restore",
16451
+ input: { table, version, namespace: namespace ?? null }
16452
+ });
16453
+ }
16454
+ async checkout({ table, version, namespace }) {
16455
+ await this.room.invoke({
16456
+ toolkit: "database",
16457
+ tool: "checkout",
16458
+ input: { table, version, namespace: namespace ?? null }
16459
+ });
16460
+ }
16461
+ async listVersions({ table, namespace }) {
16462
+ const response = await this.invoke("list_versions", { table, namespace: namespace ?? null });
16463
+ if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.versions)) {
16464
+ throw this._unexpectedResponseError("list_versions");
16465
+ }
16466
+ return response.json.versions.map((version) => tableVersionFromJson(version));
16467
+ }
16468
+ async createVectorIndex({ table, column, replace = false, namespace }) {
16004
16469
  await this.room.invoke({
16005
16470
  toolkit: "database",
16006
16471
  tool: "create_vector_index",
16007
- input: { table, column, replace, namespace: null }
16472
+ input: { table, column, replace, namespace: namespace ?? null }
16008
16473
  });
16009
16474
  }
16010
- async createScalarIndex({ table, column, replace = false }) {
16475
+ async createScalarIndex({ table, column, replace = false, namespace }) {
16011
16476
  await this.room.invoke({
16012
16477
  toolkit: "database",
16013
16478
  tool: "create_scalar_index",
16014
- input: { table, column, replace, namespace: null }
16479
+ input: { table, column, replace, namespace: namespace ?? null }
16015
16480
  });
16016
16481
  }
16017
- async createFullTextSearchIndex({ table, column, replace = false }) {
16482
+ async createFullTextSearchIndex({ table, column, replace = false, namespace }) {
16018
16483
  await this.room.invoke({
16019
16484
  toolkit: "database",
16020
16485
  tool: "create_full_text_search_index",
16021
- input: { table, column, replace, namespace: null }
16486
+ input: { table, column, replace, namespace: namespace ?? null }
16022
16487
  });
16023
16488
  }
16024
- async listIndexes({ table }) {
16025
- const response = await this.invoke("list_indexes", { table, namespace: null });
16026
- if (!(response instanceof response_1.JsonContent)) {
16489
+ async listIndexes({ table, namespace }) {
16490
+ const response = await this.invoke("list_indexes", { table, namespace: namespace ?? null });
16491
+ if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json.indexes)) {
16027
16492
  throw this._unexpectedResponseError("list_indexes");
16028
16493
  }
16029
- if (!Array.isArray(response.json.indexes)) {
16030
- throw this._unexpectedResponseError("list_indexes");
16031
- }
16032
- return response.json.indexes;
16494
+ return response.json.indexes.map((index) => tableIndexFromJson(index));
16033
16495
  }
16034
16496
  };
16035
16497
  exports.DatabaseClient = DatabaseClient;
@@ -16082,9 +16544,10 @@ ${err.toString()}`);
16082
16544
  };
16083
16545
  exports.FileCreatedEvent = FileCreatedEvent;
16084
16546
  var FileDeletedEvent = class extends RoomEvent {
16085
- constructor({ path }) {
16547
+ constructor({ path, participantId }) {
16086
16548
  super();
16087
16549
  this.path = path;
16550
+ this.participantId = participantId;
16088
16551
  }
16089
16552
  get name() {
16090
16553
  return "file deleted";
@@ -16095,9 +16558,10 @@ ${err.toString()}`);
16095
16558
  };
16096
16559
  exports.FileDeletedEvent = FileDeletedEvent;
16097
16560
  var FileUpdatedEvent = class extends RoomEvent {
16098
- constructor({ path }) {
16561
+ constructor({ path, participantId }) {
16099
16562
  super();
16100
16563
  this.path = path;
16564
+ this.participantId = participantId;
16101
16565
  }
16102
16566
  get name() {
16103
16567
  return "file updated";
@@ -23487,6 +23951,14 @@ ${newlined}
23487
23951
  getAttribute(name) {
23488
23952
  return this._attributes[name];
23489
23953
  }
23954
+ _setAttribute(name, value) {
23955
+ this._attributes[name] = value;
23956
+ }
23957
+ _setAttributes(attributes) {
23958
+ for (const [name, value] of Object.entries(attributes)) {
23959
+ this._setAttribute(name, value);
23960
+ }
23961
+ }
23490
23962
  };
23491
23963
  exports.Participant = Participant;
23492
23964
  var RemoteParticipant = class extends Participant {
@@ -23505,7 +23977,7 @@ ${newlined}
23505
23977
  super(client, id);
23506
23978
  }
23507
23979
  async setAttribute(name, value) {
23508
- this._attributes[name] = value;
23980
+ this._setAttribute(name, value);
23509
23981
  try {
23510
23982
  const payload = (0, utils_1.packMessage)({ [name]: value });
23511
23983
  await this.client.protocol.send("set_attributes", payload);
@@ -23523,15 +23995,13 @@ ${newlined}
23523
23995
  "../meshagent-ts/dist/browser/messaging-client.js"(exports) {
23524
23996
  "use strict";
23525
23997
  Object.defineProperty(exports, "__esModule", { value: true });
23526
- exports.MessageStreamReader = exports.MessageStreamWriter = exports.MessagingClient = exports.MessageStreamChunk = void 0;
23527
- var uuid_1 = require_cjs_browser();
23998
+ exports.MessagingClient = void 0;
23528
23999
  var event_emitter_1 = require_event_emitter();
24000
+ var completer_1 = require_completer();
23529
24001
  var participant_1 = require_participant();
23530
24002
  var room_event_1 = require_room_event();
23531
24003
  var room_server_client_1 = require_room_server_client();
23532
- var utils_1 = require_utils();
23533
- var stream_controller_1 = require_stream_controller();
23534
- var completer_1 = require_completer();
24004
+ var utils_1 = require_utils();
23535
24005
  var globalScope = globalThis;
23536
24006
  function bytesToBase64(bytes) {
23537
24007
  if (globalScope.Buffer) {
@@ -23546,21 +24016,18 @@ ${newlined}
23546
24016
  }
23547
24017
  return globalScope.btoa(binary);
23548
24018
  }
23549
- var MessageStreamChunk = class {
23550
- constructor({ header, data }) {
23551
- this.header = header;
23552
- this.data = data;
23553
- }
23554
- };
23555
- exports.MessageStreamChunk = MessageStreamChunk;
23556
24019
  var MessagingClient = class extends event_emitter_1.EventEmitter {
23557
24020
  constructor({ room }) {
23558
24021
  super();
23559
- this._streamWriters = {};
23560
- this._streamReaders = {};
24022
+ this._messageHandler = this._handleMessageSend.bind(this);
23561
24023
  this._participants = {};
24024
+ this._messageQueue = [];
24025
+ this._messageQueued = null;
24026
+ this._sendTask = null;
24027
+ this._messageQueueClosed = false;
24028
+ this._enabled = false;
23562
24029
  this.client = room;
23563
- this.client.protocol.addHandler("messaging.send", this._handleMessageSend.bind(this));
24030
+ this.client.protocol.addHandler("messaging.send", this._messageHandler);
23564
24031
  }
23565
24032
  _messageInput(params) {
23566
24033
  const input = {
@@ -23575,6 +24042,16 @@ ${newlined}
23575
24042
  }
23576
24043
  return input;
23577
24044
  }
24045
+ _syntheticMessageEvent(params) {
24046
+ return new room_event_1.RoomMessageEvent({
24047
+ message: new room_event_1.RoomMessage({
24048
+ fromParticipantId: params.fromParticipantId,
24049
+ type: params.type,
24050
+ message: params.message,
24051
+ local: true
24052
+ })
24053
+ });
24054
+ }
23578
24055
  _removeParticipant(participantId) {
23579
24056
  const participant = this._participants[participantId];
23580
24057
  if (participant === void 0) {
@@ -23582,15 +24059,24 @@ ${newlined}
23582
24059
  }
23583
24060
  participant._setOnline(false);
23584
24061
  delete this._participants[participantId];
23585
- for (const [streamId, reader] of Object.entries(this._streamReaders)) {
23586
- if (reader._to.id !== participant.id) {
23587
- continue;
23588
- }
23589
- reader._controller.close();
23590
- delete this._streamReaders[streamId];
23591
- }
23592
24062
  return participant;
23593
24063
  }
24064
+ _markParticipantOffline(participant) {
24065
+ if (!(participant instanceof participant_1.RemoteParticipant)) {
24066
+ return;
24067
+ }
24068
+ participant._setOnline(false);
24069
+ const current = this._participants[participant.id];
24070
+ if (current === void 0) {
24071
+ return;
24072
+ }
24073
+ this._removeParticipant(participant.id);
24074
+ this.emit("participant_removed", this._syntheticMessageEvent({
24075
+ fromParticipantId: participant.id,
24076
+ type: "participant.disabled",
24077
+ message: { id: participant.id }
24078
+ }));
24079
+ }
23594
24080
  _resolveMessageRecipient(to) {
23595
24081
  if (!(to instanceof participant_1.RemoteParticipant)) {
23596
24082
  return to;
@@ -23600,46 +24086,129 @@ ${newlined}
23600
24086
  }
23601
24087
  return this._participants[to.id] ?? null;
23602
24088
  }
23603
- _participantNotFound(ignoreOffline) {
23604
- if (ignoreOffline) {
23605
- return null;
24089
+ _queueMessage(message2) {
24090
+ if (this._sendTask === null) {
24091
+ throw new room_server_client_1.RoomServerException("Cannot send messages because messaging has not been started");
24092
+ }
24093
+ this._messageQueue.push(message2);
24094
+ const waiter = this._messageQueued;
24095
+ if (waiter !== null) {
24096
+ this._messageQueued = null;
24097
+ waiter.complete();
24098
+ }
24099
+ }
24100
+ _rejectQueuedMessages(error) {
24101
+ while (this._messageQueue.length > 0) {
24102
+ const message2 = this._messageQueue.shift();
24103
+ message2?.completer?.completeError(error);
24104
+ }
24105
+ }
24106
+ _isParticipantNotFound(error) {
24107
+ return error instanceof room_server_client_1.RoomServerException && error.message === "the participant was not found";
24108
+ }
24109
+ async _nextQueuedMessage() {
24110
+ while (this._messageQueue.length === 0) {
24111
+ if (this._messageQueueClosed) {
24112
+ return null;
24113
+ }
24114
+ if (this._messageQueued === null) {
24115
+ this._messageQueued = new completer_1.Completer();
24116
+ }
24117
+ await this._messageQueued.fut;
24118
+ }
24119
+ return this._messageQueue.shift() ?? null;
24120
+ }
24121
+ async _sendMessages() {
24122
+ while (true) {
24123
+ const queued = await this._nextQueuedMessage();
24124
+ if (queued === null) {
24125
+ return;
24126
+ }
24127
+ const resolvedTo = this._resolveMessageRecipient(queued.to);
24128
+ if (resolvedTo === null) {
24129
+ const error = new room_server_client_1.RoomServerException("the participant was not found");
24130
+ if (queued.dropIfOffline) {
24131
+ queued.completer?.complete();
24132
+ } else {
24133
+ queued.completer?.completeError(error);
24134
+ }
24135
+ continue;
24136
+ }
24137
+ try {
24138
+ await this.client.invoke({
24139
+ toolkit: "messaging",
24140
+ tool: "send",
24141
+ input: this._messageInput({
24142
+ toParticipantId: resolvedTo.id,
24143
+ type: queued.type,
24144
+ message: queued.message,
24145
+ attachment: queued.attachment
24146
+ })
24147
+ });
24148
+ queued.completer?.complete();
24149
+ } catch (error) {
24150
+ if (this._isParticipantNotFound(error)) {
24151
+ this._markParticipantOffline(queued.to);
24152
+ if (queued.dropIfOffline) {
24153
+ queued.completer?.complete();
24154
+ continue;
24155
+ }
24156
+ }
24157
+ queued.completer?.completeError(error);
24158
+ }
24159
+ }
24160
+ }
24161
+ async start() {
24162
+ if (this._sendTask !== null) {
24163
+ return;
24164
+ }
24165
+ this._messageQueueClosed = false;
24166
+ this._sendTask = this._sendMessages();
24167
+ }
24168
+ async stop() {
24169
+ if (this._sendTask === null) {
24170
+ this._enabled = false;
24171
+ return;
24172
+ }
24173
+ this._messageQueueClosed = true;
24174
+ const waiter = this._messageQueued;
24175
+ if (waiter !== null) {
24176
+ this._messageQueued = null;
24177
+ waiter.complete();
23606
24178
  }
23607
- throw new room_server_client_1.RoomServerException("the participant was not found");
24179
+ const sendTask = this._sendTask;
24180
+ this._sendTask = null;
24181
+ await sendTask;
24182
+ this._enabled = false;
23608
24183
  }
23609
- async createStream({ to, header }) {
23610
- const streamId = (0, uuid_1.v4)();
24184
+ async sendMessage({ to, type, message: message2, attachment, ignoreOffline = false }) {
23611
24185
  const completer = new completer_1.Completer();
23612
- this._streamWriters[streamId] = completer;
23613
- await this.sendMessage({
24186
+ this._queueMessage({
23614
24187
  to,
23615
- type: "stream.open",
23616
- message: { stream_id: streamId, header }
24188
+ type,
24189
+ message: message2,
24190
+ attachment,
24191
+ dropIfOffline: ignoreOffline,
24192
+ completer
23617
24193
  });
23618
- return completer.fut;
24194
+ await completer.fut;
23619
24195
  }
23620
- async sendMessage({ to, type, message: message2, attachment, ignoreOffline = false }) {
23621
- const resolvedTo = this._resolveMessageRecipient(to) ?? this._participantNotFound(ignoreOffline);
23622
- if (resolvedTo === null) {
23623
- return;
23624
- }
23625
- await this.client.invoke({
23626
- toolkit: "messaging",
23627
- tool: "send",
23628
- input: this._messageInput({
23629
- toParticipantId: resolvedTo.id,
23630
- type,
23631
- message: message2,
23632
- attachment
23633
- })
24196
+ sendMessageNowait({ to, type, message: message2, attachment }) {
24197
+ this._queueMessage({
24198
+ to,
24199
+ type,
24200
+ message: message2,
24201
+ attachment,
24202
+ dropIfOffline: true
23634
24203
  });
23635
24204
  }
23636
- async enable(onStreamAccept) {
24205
+ async enable() {
23637
24206
  await this.client.invoke({
23638
24207
  toolkit: "messaging",
23639
24208
  tool: "enable",
23640
24209
  input: {}
23641
24210
  });
23642
- this._onStreamAcceptCallback = onStreamAccept;
24211
+ this._enabled = true;
23643
24212
  }
23644
24213
  async disable() {
23645
24214
  await this.client.invoke({
@@ -23647,6 +24216,7 @@ ${newlined}
23647
24216
  tool: "disable",
23648
24217
  input: {}
23649
24218
  });
24219
+ this._enabled = false;
23650
24220
  }
23651
24221
  async broadcastMessage({ type, message: message2, attachment }) {
23652
24222
  await this.client.invoke({
@@ -23658,6 +24228,23 @@ ${newlined}
23658
24228
  get remoteParticipants() {
23659
24229
  return Object.values(this._participants);
23660
24230
  }
24231
+ get isEnabled() {
24232
+ return this._enabled;
24233
+ }
24234
+ getParticipants() {
24235
+ return this.remoteParticipants;
24236
+ }
24237
+ getParticipant(id) {
24238
+ return this._participants[id] ?? null;
24239
+ }
24240
+ getParticipantByName(name) {
24241
+ for (const participant of this.remoteParticipants) {
24242
+ if (participant.getAttribute("name") === name) {
24243
+ return participant;
24244
+ }
24245
+ }
24246
+ return null;
24247
+ }
23661
24248
  async _handleMessageSend(protocol, messageId, type, bytes) {
23662
24249
  const headerStr = (0, utils_1.splitMessageHeader)(bytes || new Uint8Array());
23663
24250
  const payload = (0, utils_1.splitMessagePayload)(bytes || new Uint8Array());
@@ -23681,21 +24268,6 @@ ${newlined}
23681
24268
  case "participant.disabled":
23682
24269
  this._onParticipantDisabled(message2);
23683
24270
  break;
23684
- case "stream.open":
23685
- this._onStreamOpen(message2);
23686
- break;
23687
- case "stream.accept":
23688
- this._onStreamAccept(message2);
23689
- break;
23690
- case "stream.reject":
23691
- this._onStreamReject(message2);
23692
- break;
23693
- case "stream.chunk":
23694
- this._onStreamChunk(message2);
23695
- break;
23696
- case "stream.close":
23697
- this._onStreamClose(message2);
23698
- break;
23699
24271
  }
23700
24272
  const messageEvent = new room_event_1.RoomMessageEvent({ message: message2 });
23701
24273
  this.client.emit(messageEvent);
@@ -23704,20 +24276,17 @@ ${newlined}
23704
24276
  _onParticipantEnabled(message2) {
23705
24277
  const data = message2.message;
23706
24278
  const p = new participant_1.RemoteParticipant(this.client, data["id"], data["role"], true);
23707
- for (const [k, v] of Object.entries(data["attributes"] || {})) {
23708
- p._attributes[k] = v;
23709
- }
24279
+ p._setAttributes(data["attributes"] ?? {});
23710
24280
  this._participants[data["id"]] = p;
23711
24281
  this.emit("participant_added", { message: message2 });
23712
24282
  }
23713
24283
  _onParticipantAttributes(message2) {
23714
24284
  const part = this._participants[message2.fromParticipantId];
23715
- if (!part)
24285
+ if (!part) {
23716
24286
  return;
23717
- const attrObj = message2.message["attributes"];
23718
- for (const [k, v] of Object.entries(attrObj)) {
23719
- part._attributes[k] = v;
23720
24287
  }
24288
+ const attrObj = message2.message["attributes"];
24289
+ part._setAttributes(attrObj);
23721
24290
  this.emit("participant_attributes_updated", { message: message2 });
23722
24291
  }
23723
24292
  _onParticipantDisabled(message2) {
@@ -23730,128 +24299,27 @@ ${newlined}
23730
24299
  const participants = message2.message["participants"];
23731
24300
  for (const data of participants) {
23732
24301
  const rp = new participant_1.RemoteParticipant(this.client, data["id"], data["role"], true);
23733
- for (const [k, v] of Object.entries(data["attributes"] || {})) {
23734
- rp._attributes[k] = v;
23735
- }
24302
+ rp._setAttributes(data["attributes"] ?? {});
23736
24303
  this._participants[data["id"]] = rp;
23737
24304
  }
24305
+ this._enabled = true;
23738
24306
  this.emit("messaging_enabled", { message: message2 });
23739
24307
  }
23740
- _onStreamOpen(message2) {
23741
- const from = [...this.remoteParticipants].find((x) => x.id === message2.fromParticipantId);
23742
- if (!from)
23743
- return;
23744
- const streamId = message2.message["stream_id"];
23745
- const controller = new stream_controller_1.StreamController();
23746
- const reader = new MessageStreamReader({
23747
- streamId,
23748
- to: from,
23749
- client: this,
23750
- controller
23751
- });
23752
- try {
23753
- if (!this._onStreamAcceptCallback) {
23754
- throw new Error("streams are not allowed by this client");
23755
- }
23756
- this._onStreamAcceptCallback(reader);
23757
- void this.sendMessage({
23758
- to: from,
23759
- type: "stream.accept",
23760
- message: { stream_id: streamId },
23761
- ignoreOffline: true
23762
- }).catch((error) => {
23763
- console.warn("unable to send stream response", error);
23764
- });
23765
- } catch (e) {
23766
- void this.sendMessage({
23767
- to: from,
23768
- type: "stream.reject",
23769
- message: { stream_id: streamId, error: String(e) },
23770
- ignoreOffline: true
23771
- }).catch((error) => {
23772
- console.warn("unable to send stream response", error);
23773
- });
23774
- }
23775
- this._streamReaders[streamId] = reader;
23776
- this.emit("stream_opened", { message: message2 });
23777
- }
23778
- _onStreamAccept(message2) {
23779
- const streamId = message2.message["stream_id"];
23780
- const writerCompleter = this._streamWriters[streamId];
23781
- if (!writerCompleter)
23782
- return;
23783
- const from = [...this.remoteParticipants].find((x) => x.id === message2.fromParticipantId);
23784
- if (!from)
23785
- return;
23786
- writerCompleter.complete(new MessageStreamWriter({
23787
- streamId,
23788
- to: from,
23789
- client: this
23790
- }));
23791
- }
23792
- _onStreamReject(message2) {
23793
- const streamId = message2.message["stream_id"];
23794
- const writerCompleter = this._streamWriters[streamId];
23795
- if (!writerCompleter)
23796
- return;
23797
- writerCompleter.completeError(new Error("The stream was rejected by the remote client"));
23798
- }
23799
- _onStreamChunk(message2) {
23800
- const streamId = message2.message["stream_id"];
23801
- const reader = this._streamReaders[streamId];
23802
- if (!reader)
23803
- return;
23804
- reader._controller.add(new MessageStreamChunk({
23805
- header: message2.message,
23806
- data: message2.attachment
23807
- }));
23808
- }
23809
- _onStreamClose(message2) {
23810
- const streamId = message2.message["stream_id"];
23811
- const reader = this._streamReaders[streamId];
23812
- if (!reader)
23813
- return;
23814
- reader._controller.close();
23815
- delete this._streamReaders[streamId];
23816
- }
23817
24308
  dispose() {
24309
+ const error = new room_server_client_1.RoomServerException("messaging client disposed");
24310
+ this._messageQueueClosed = true;
24311
+ this._enabled = false;
24312
+ this._rejectQueuedMessages(error);
24313
+ const waiter = this._messageQueued;
24314
+ if (waiter !== null) {
24315
+ this._messageQueued = null;
24316
+ waiter.complete();
24317
+ }
23818
24318
  super.dispose();
23819
24319
  this.client.protocol.removeHandler("messaging.send");
23820
24320
  }
23821
24321
  };
23822
24322
  exports.MessagingClient = MessagingClient;
23823
- var MessageStreamWriter = class {
23824
- constructor({ streamId, to, client }) {
23825
- this._streamId = streamId;
23826
- this._to = to;
23827
- this._client = client;
23828
- }
23829
- async write(chunk) {
23830
- await this._client.sendMessage({
23831
- to: this._to,
23832
- type: "stream.chunk",
23833
- message: { stream_id: this._streamId, header: chunk.header },
23834
- attachment: chunk.data
23835
- });
23836
- }
23837
- async close() {
23838
- await this._client.sendMessage({
23839
- to: this._to,
23840
- type: "stream.close",
23841
- message: { stream_id: this._streamId }
23842
- });
23843
- }
23844
- };
23845
- exports.MessageStreamWriter = MessageStreamWriter;
23846
- var MessageStreamReader = class {
23847
- constructor({ streamId, to, client, controller }) {
23848
- this._streamId = streamId;
23849
- this._to = to;
23850
- this._client = client;
23851
- this._controller = controller;
23852
- }
23853
- };
23854
- exports.MessageStreamReader = MessageStreamReader;
23855
24323
  }
23856
24324
  });
23857
24325
 
@@ -24807,12 +25275,62 @@ ${newlined}
24807
25275
  "../meshagent-ts/dist/browser/storage-client.js"(exports) {
24808
25276
  "use strict";
24809
25277
  Object.defineProperty(exports, "__esModule", { value: true });
24810
- exports.StorageClient = exports.FileHandle = void 0;
25278
+ exports.StorageClient = exports.StorageEntry = exports.FileHandle = void 0;
24811
25279
  var room_event_1 = require_room_event();
24812
25280
  var response_1 = require_response();
24813
25281
  var utils_1 = require_utils();
24814
25282
  var event_emitter_1 = require_event_emitter();
24815
25283
  var room_server_client_1 = require_room_server_client();
25284
+ var _DEFAULT_UPLOAD_MIME_TYPE = "application/octet-stream";
25285
+ var _UPLOAD_MIME_TYPES_BY_SUFFIX = /* @__PURE__ */ new Map([
25286
+ [".tar.gz", "application/x-tar"],
25287
+ [".tgz", "application/x-tar"]
25288
+ ]);
25289
+ var _UPLOAD_MIME_TYPES_BY_EXTENSION = /* @__PURE__ */ new Map([
25290
+ [".bin", "application/octet-stream"],
25291
+ [".css", "text/css"],
25292
+ [".csv", "text/csv"],
25293
+ [".gif", "image/gif"],
25294
+ [".gz", "application/gzip"],
25295
+ [".htm", "text/html"],
25296
+ [".html", "text/html"],
25297
+ [".jpeg", "image/jpeg"],
25298
+ [".jpg", "image/jpeg"],
25299
+ [".js", "text/javascript"],
25300
+ [".json", "application/json"],
25301
+ [".md", "text/markdown"],
25302
+ [".mp3", "audio/mpeg"],
25303
+ [".mp4", "video/mp4"],
25304
+ [".pdf", "application/pdf"],
25305
+ [".png", "image/png"],
25306
+ [".svg", "image/svg+xml"],
25307
+ [".tar", "application/x-tar"],
25308
+ [".txt", "text/plain"],
25309
+ [".ts", "text/typescript"],
25310
+ [".tsx", "text/tsx"],
25311
+ [".wasm", "application/wasm"],
25312
+ [".webp", "image/webp"],
25313
+ [".xml", "application/xml"],
25314
+ [".yaml", "application/yaml"],
25315
+ [".yml", "application/yaml"],
25316
+ [".zip", "application/zip"]
25317
+ ]);
25318
+ function _unexpectedStorageResponseError(operation) {
25319
+ return new room_server_client_1.RoomServerException(`unexpected return type from storage.${operation}`);
25320
+ }
25321
+ function _parseStorageTimestamp(value, operation) {
25322
+ if (value == null) {
25323
+ return null;
25324
+ }
25325
+ if (typeof value !== "string") {
25326
+ throw _unexpectedStorageResponseError(operation);
25327
+ }
25328
+ const timestamp = new Date(value);
25329
+ if (Number.isNaN(timestamp.getTime())) {
25330
+ throw _unexpectedStorageResponseError(operation);
25331
+ }
25332
+ return timestamp;
25333
+ }
24816
25334
  var FileHandle = class {
24817
25335
  constructor({ id }) {
24818
25336
  this.id = id;
@@ -24820,16 +25338,19 @@ ${newlined}
24820
25338
  };
24821
25339
  exports.FileHandle = FileHandle;
24822
25340
  var StorageEntry = class {
24823
- constructor({ name, isFolder, size = null }) {
25341
+ constructor({ name, isFolder, size = null, createdAt = null, updatedAt = null }) {
24824
25342
  this.name = name;
24825
25343
  this.isFolder = isFolder;
24826
25344
  this.size = size;
25345
+ this.createdAt = createdAt;
25346
+ this.updatedAt = updatedAt;
24827
25347
  }
24828
25348
  nameWithoutExtension() {
24829
25349
  const segments = this.name.replace(/^\/+/, "").replace(/\/+$/, "").split(/\/+/);
24830
25350
  return (segments[segments.length - 1] || "").replace(/\.[^/.]+$/, "");
24831
25351
  }
24832
25352
  };
25353
+ exports.StorageEntry = StorageEntry;
24833
25354
  var StorageClient = class extends event_emitter_1.EventEmitter {
24834
25355
  constructor({ room }) {
24835
25356
  super();
@@ -24839,18 +25360,30 @@ ${newlined}
24839
25360
  }
24840
25361
  async _handleFileUpdated(protocol, messageId, type, bytes) {
24841
25362
  const [data, _] = (0, utils_1.unpackMessage)(bytes || new Uint8Array());
24842
- const event = new room_event_1.FileUpdatedEvent({ path: data["path"] });
25363
+ const event = new room_event_1.FileUpdatedEvent({ path: data["path"], participantId: data["participant_id"] });
24843
25364
  this.client.emit(event);
24844
25365
  this.emit("file.updated", event);
24845
25366
  }
24846
25367
  async _handleFileDeleted(protocol, messageId, type, bytes) {
24847
25368
  const [data, _] = (0, utils_1.unpackMessage)(bytes || new Uint8Array());
24848
- const event = new room_event_1.FileDeletedEvent({ path: data["path"] });
25369
+ const event = new room_event_1.FileDeletedEvent({ path: data["path"], participantId: data["participant_id"] });
24849
25370
  this.client.emit(event);
24850
25371
  this.emit("file.deleted", event);
24851
25372
  }
24852
25373
  _unexpectedResponseError(operation) {
24853
- return new room_server_client_1.RoomServerException(`unexpected return type from storage.${operation}`);
25374
+ return _unexpectedStorageResponseError(operation);
25375
+ }
25376
+ _storageEntry(operation, value) {
25377
+ if (typeof value["name"] !== "string" || typeof value["is_folder"] !== "boolean" || value["size"] != null && typeof value["size"] !== "number") {
25378
+ throw this._unexpectedResponseError(operation);
25379
+ }
25380
+ return new StorageEntry({
25381
+ name: value["name"],
25382
+ isFolder: value["is_folder"],
25383
+ size: typeof value["size"] === "number" ? value["size"] : null,
25384
+ createdAt: _parseStorageTimestamp(value["created_at"], operation),
25385
+ updatedAt: _parseStorageTimestamp(value["updated_at"], operation)
25386
+ });
24854
25387
  }
24855
25388
  async _invoke(operation, input, callerContext) {
24856
25389
  return await this.client.invoke({
@@ -24862,22 +25395,26 @@ ${newlined}
24862
25395
  }
24863
25396
  async list(path) {
24864
25397
  const response = await this._invoke("list", { path });
24865
- if (!(response instanceof response_1.JsonContent)) {
25398
+ if (!(response instanceof response_1.JsonContent) || !Array.isArray(response.json["files"])) {
24866
25399
  throw this._unexpectedResponseError("list");
24867
25400
  }
24868
25401
  const files = response.json["files"];
24869
- const entries = files.map((f) => {
24870
- return new StorageEntry({
24871
- name: f["name"],
24872
- isFolder: f["is_folder"],
24873
- size: typeof f["size"] === "number" ? f["size"] : null
24874
- });
24875
- });
25402
+ const entries = files.map((f) => this._storageEntry("list", f));
24876
25403
  entries.sort((a, b) => a.name.localeCompare(b.name));
24877
25404
  return entries;
24878
25405
  }
24879
- async delete(path) {
24880
- await this._invoke("delete", { path, recursive: null });
25406
+ async stat(path) {
25407
+ const response = await this._invoke("stat", { path });
25408
+ if (!(response instanceof response_1.JsonContent) || typeof response.json["exists"] !== "boolean") {
25409
+ throw this._unexpectedResponseError("stat");
25410
+ }
25411
+ if (!response.json["exists"]) {
25412
+ return null;
25413
+ }
25414
+ return this._storageEntry("stat", response.json);
25415
+ }
25416
+ async delete(path, { recursive = null } = {}) {
25417
+ await this._invoke("delete", { path, recursive });
24881
25418
  }
24882
25419
  async exists(path) {
24883
25420
  const result = await this._invoke("exists", { path });
@@ -24894,6 +25431,22 @@ ${newlined}
24894
25431
  const lastSegment = segments.length > 0 ? segments[segments.length - 1] : void 0;
24895
25432
  return lastSegment ?? path;
24896
25433
  }
25434
+ _defaultUploadMimeType(name, mimeType) {
25435
+ if (typeof mimeType === "string" && mimeType.length > 0) {
25436
+ return mimeType;
25437
+ }
25438
+ const lowerName = name.toLowerCase();
25439
+ for (const [suffix, contentType] of _UPLOAD_MIME_TYPES_BY_SUFFIX.entries()) {
25440
+ if (lowerName.endsWith(suffix)) {
25441
+ return contentType;
25442
+ }
25443
+ }
25444
+ const lastDot = lowerName.lastIndexOf(".");
25445
+ if (lastDot >= 0) {
25446
+ return _UPLOAD_MIME_TYPES_BY_EXTENSION.get(lowerName.slice(lastDot)) ?? _DEFAULT_UPLOAD_MIME_TYPE;
25447
+ }
25448
+ return _DEFAULT_UPLOAD_MIME_TYPE;
25449
+ }
24897
25450
  async upload(path, bytes, { overwrite = false, name, mimeType = null } = {}) {
24898
25451
  async function* singleChunk() {
24899
25452
  yield bytes;
@@ -24907,6 +25460,7 @@ ${newlined}
24907
25460
  }
24908
25461
  async uploadStream(path, chunks, { overwrite = false, chunkSize = 64 * 1024, size = null, name, mimeType = null } = {}) {
24909
25462
  const resolvedName = this._defaultUploadName(path, name);
25463
+ const resolvedMimeType = this._defaultUploadMimeType(resolvedName, mimeType);
24910
25464
  const input = new _StorageUploadInputStream({
24911
25465
  path,
24912
25466
  overwrite,
@@ -24914,7 +25468,7 @@ ${newlined}
24914
25468
  chunkSize,
24915
25469
  size,
24916
25470
  name: resolvedName,
24917
- mimeType
25471
+ mimeType: resolvedMimeType
24918
25472
  });
24919
25473
  const response = await this.client.invokeStream({
24920
25474
  toolkit: "storage",
@@ -25244,86 +25798,285 @@ ${newlined}
25244
25798
  Object.defineProperty(exports, "__esModule", { value: true });
25245
25799
  exports.SecretsClient = void 0;
25246
25800
  var response_1 = require_response();
25801
+ var room_server_client_1 = require_room_server_client();
25802
+ var utils_1 = require_utils();
25803
+ function isRecord(value) {
25804
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25805
+ }
25247
25806
  var SecretsClient = class {
25248
- constructor({ room }) {
25807
+ constructor({ room, oauthTokenRequestHandler, secretRequestHandler }) {
25808
+ this._oauthRequestHandler = this._handleClientOAuthTokenRequest.bind(this);
25809
+ this._secretRequestHandler = this._handleClientSecretRequest.bind(this);
25249
25810
  this.client = room;
25811
+ this.oauthTokenRequestHandler = oauthTokenRequestHandler;
25812
+ this.secretRequestHandler = secretRequestHandler;
25813
+ this.client.protocol.addHandler("secrets.request_oauth_token", this._oauthRequestHandler);
25814
+ this.client.protocol.addHandler("secrets.request_secret", this._secretRequestHandler);
25250
25815
  }
25251
25816
  unexpectedResponse(operation) {
25252
- return new Error(`unexpected return type from secrets.${operation}`);
25817
+ return new room_server_client_1.RoomServerException(`unexpected return type from secrets.${operation}`);
25253
25818
  }
25254
- async setSecret({ secretId, data, mimeType, name, delegatedTo, forIdentity }) {
25255
- const response = await this.client.invoke({
25819
+ async invoke(operation, input) {
25820
+ return await this.client.invoke({
25256
25821
  toolkit: "secrets",
25257
- tool: "set_secret",
25258
- input: new response_1.BinaryContent({
25259
- data,
25260
- headers: {
25261
- secret_id: secretId,
25262
- type: mimeType ?? null,
25263
- name: name ?? null,
25264
- delegated_to: delegatedTo ?? null,
25265
- for_identity: forIdentity ?? null,
25266
- has_data: true
25267
- }
25268
- })
25822
+ tool: operation,
25823
+ input
25269
25824
  });
25270
- if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25271
- return;
25825
+ }
25826
+ serializeConnectorRef(connector) {
25827
+ if (connector == null) {
25828
+ return null;
25272
25829
  }
25273
- throw this.unexpectedResponse("set_secret");
25830
+ return {
25831
+ openai_connector_id: connector.openaiConnectorId ?? null,
25832
+ server_url: connector.serverUrl ?? null,
25833
+ client_secret_id: connector.clientSecretId ?? null
25834
+ };
25274
25835
  }
25275
- async getSecret({ secretId, delegatedTo }) {
25276
- const req = {
25277
- secret_id: secretId,
25278
- type: null,
25279
- name: null,
25280
- delegated_to: delegatedTo ?? null
25836
+ serializeOAuthConfig(oauth) {
25837
+ if (oauth == null) {
25838
+ return null;
25839
+ }
25840
+ return {
25841
+ client_id: oauth.client_id,
25842
+ client_secret: oauth.client_secret ?? null,
25843
+ authorization_endpoint: oauth.authorization_endpoint,
25844
+ token_endpoint: oauth.token_endpoint,
25845
+ no_pkce: oauth.no_pkce ?? null,
25846
+ scopes: oauth.scopes ?? null
25281
25847
  };
25282
- const response = await this.client.invoke({ toolkit: "secrets", tool: "get_secret", input: req });
25283
- if (response instanceof response_1.EmptyContent) {
25848
+ }
25849
+ parseAccessToken(operation, response) {
25850
+ if (!(response instanceof response_1.JsonContent)) {
25851
+ throw this.unexpectedResponse(operation);
25852
+ }
25853
+ const token = response.json["access_token"];
25854
+ if (typeof token !== "string" || token.length === 0) {
25284
25855
  return null;
25285
25856
  }
25286
- if (response instanceof response_1.FileContent) {
25287
- return response;
25857
+ return token;
25858
+ }
25859
+ parseSecretInfo(value) {
25860
+ if (!isRecord(value) || typeof value["id"] !== "string" || typeof value["name"] !== "string" || typeof value["type"] !== "string") {
25861
+ throw this.unexpectedResponse("list_secrets");
25288
25862
  }
25289
- throw this.unexpectedResponse("get_secret");
25863
+ const delegatedTo = value["delegated_to"];
25864
+ if (delegatedTo !== void 0 && delegatedTo !== null && typeof delegatedTo !== "string") {
25865
+ throw this.unexpectedResponse("list_secrets");
25866
+ }
25867
+ return {
25868
+ id: value["id"],
25869
+ name: value["name"],
25870
+ type: value["type"],
25871
+ delegatedTo
25872
+ };
25873
+ }
25874
+ async _handleClientOAuthTokenRequest(protocol, messageId, type, bytes) {
25875
+ void protocol;
25876
+ void messageId;
25877
+ void type;
25878
+ if (bytes == null) {
25879
+ throw new room_server_client_1.RoomServerException("invalid secrets.request_oauth_token payload");
25880
+ }
25881
+ if (this.oauthTokenRequestHandler == null) {
25882
+ throw new room_server_client_1.RoomServerException("No oauth token handler registered");
25883
+ }
25884
+ const [request] = (0, utils_1.unpackMessage)(bytes);
25885
+ const requestId = request["request_id"];
25886
+ const challenge = request["challenge"];
25887
+ const requestPayload = request["request"];
25888
+ if (typeof requestId !== "string" || !isRecord(requestPayload)) {
25889
+ throw new room_server_client_1.RoomServerException("invalid secrets.request_oauth_token payload");
25890
+ }
25891
+ const oauth = requestPayload["oauth"];
25892
+ if (!isRecord(oauth) || typeof oauth["authorization_endpoint"] !== "string" || typeof oauth["token_endpoint"] !== "string") {
25893
+ throw new room_server_client_1.RoomServerException("invalid secrets.request_oauth_token payload");
25894
+ }
25895
+ const scopes = oauth["scopes"];
25896
+ if (scopes !== void 0 && scopes !== null && (!Array.isArray(scopes) || scopes.some((scope) => typeof scope !== "string"))) {
25897
+ throw new room_server_client_1.RoomServerException("invalid secrets.request_oauth_token payload");
25898
+ }
25899
+ Promise.resolve(this.oauthTokenRequestHandler({
25900
+ requestId,
25901
+ authorizationEndpoint: oauth["authorization_endpoint"],
25902
+ tokenEndpoint: oauth["token_endpoint"],
25903
+ challenge: typeof challenge === "string" ? challenge : null,
25904
+ scopes: scopes ?? null,
25905
+ clientId: typeof oauth["client_id"] === "string" ? oauth["client_id"] : null
25906
+ })).catch((error) => {
25907
+ console.warn("OAuth token request handler threw", error);
25908
+ });
25909
+ }
25910
+ async _handleClientSecretRequest(protocol, messageId, type, bytes) {
25911
+ void protocol;
25912
+ void messageId;
25913
+ void type;
25914
+ if (bytes == null) {
25915
+ throw new room_server_client_1.RoomServerException("invalid secrets.request_secret payload");
25916
+ }
25917
+ if (this.secretRequestHandler == null) {
25918
+ throw new room_server_client_1.RoomServerException("No secret handler registered");
25919
+ }
25920
+ const [request] = (0, utils_1.unpackMessage)(bytes);
25921
+ const requestId = request["request_id"];
25922
+ const requestPayload = request["request"];
25923
+ if (typeof requestId !== "string" || !isRecord(requestPayload) || typeof requestPayload["url"] !== "string" || typeof requestPayload["type"] !== "string") {
25924
+ throw new room_server_client_1.RoomServerException("invalid secrets.request_secret payload");
25925
+ }
25926
+ Promise.resolve(this.secretRequestHandler({
25927
+ requestId,
25928
+ url: requestPayload["url"],
25929
+ type: requestPayload["type"],
25930
+ delegateTo: typeof requestPayload["delegate_to"] === "string" ? requestPayload["delegate_to"] : null
25931
+ })).catch((error) => {
25932
+ console.warn("Secret request handler threw", error);
25933
+ });
25934
+ }
25935
+ async provideOAuthAuthorization({ requestId, code }) {
25936
+ const response = await this.invoke("provide_oauth_authorization", {
25937
+ request_id: requestId,
25938
+ code,
25939
+ error: null
25940
+ });
25941
+ if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25942
+ return;
25943
+ }
25944
+ throw this.unexpectedResponse("provide_oauth_authorization");
25945
+ }
25946
+ async rejectOAuthAuthorization({ requestId, error }) {
25947
+ const response = await this.invoke("provide_oauth_authorization", {
25948
+ request_id: requestId,
25949
+ code: null,
25950
+ error
25951
+ });
25952
+ if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25953
+ return;
25954
+ }
25955
+ throw this.unexpectedResponse("provide_oauth_authorization");
25956
+ }
25957
+ async provideSecret({ requestId, data }) {
25958
+ const response = await this.invoke("provide_secret", new response_1.BinaryContent({
25959
+ data,
25960
+ headers: {
25961
+ request_id: requestId,
25962
+ error: null
25963
+ }
25964
+ }));
25965
+ if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25966
+ return;
25967
+ }
25968
+ throw this.unexpectedResponse("provide_secret");
25969
+ }
25970
+ async rejectSecret({ requestId, error }) {
25971
+ const response = await this.invoke("provide_secret", new response_1.BinaryContent({
25972
+ data: new Uint8Array(0),
25973
+ headers: {
25974
+ request_id: requestId,
25975
+ error
25976
+ }
25977
+ }));
25978
+ if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25979
+ return;
25980
+ }
25981
+ throw this.unexpectedResponse("provide_secret");
25982
+ }
25983
+ async getOfflineOAuthToken({ connector, oauth, delegatedTo, delegatedBy }) {
25984
+ const response = await this.invoke("get_offline_oauth_token", {
25985
+ connector: this.serializeConnectorRef(connector),
25986
+ oauth: this.serializeOAuthConfig(oauth),
25987
+ delegated_to: delegatedTo ?? null,
25988
+ delegated_by: delegatedBy ?? null
25989
+ });
25990
+ return this.parseAccessToken("get_offline_oauth_token", response);
25991
+ }
25992
+ async requestOAuthToken({ connector, oauth, timeout = 60 * 5, fromParticipantId, redirectUri, delegateTo }) {
25993
+ const response = await this.invoke("request_oauth_token", {
25994
+ connector: this.serializeConnectorRef(connector),
25995
+ oauth: this.serializeOAuthConfig(oauth),
25996
+ redirect_uri: typeof redirectUri === "string" ? redirectUri : redirectUri.toString(),
25997
+ timeout,
25998
+ participant_id: fromParticipantId,
25999
+ delegate_to: delegateTo ?? null
26000
+ });
26001
+ return this.parseAccessToken("request_oauth_token", response);
25290
26002
  }
25291
26003
  async listSecrets() {
25292
- const response = await this.client.invoke({ toolkit: "secrets", tool: "list_secrets", input: {} });
26004
+ const response = await this.invoke("list_secrets", {});
25293
26005
  if (!(response instanceof response_1.JsonContent)) {
25294
26006
  throw this.unexpectedResponse("list_secrets");
25295
26007
  }
25296
- const secrets = Array.isArray(response.json?.secrets) ? response.json.secrets : [];
25297
- return secrets.map((item) => ({
25298
- id: item.id,
25299
- name: item.name,
25300
- type: item.type,
25301
- delegatedTo: item.delegated_to
25302
- }));
26008
+ const secrets = response.json["secrets"];
26009
+ if (!Array.isArray(secrets)) {
26010
+ throw this.unexpectedResponse("list_secrets");
26011
+ }
26012
+ return secrets.map((item) => this.parseSecretInfo(item));
25303
26013
  }
25304
26014
  async deleteSecret({ secretId, delegatedTo }) {
25305
- const req = {
26015
+ const response = await this.invoke("delete_secret", {
25306
26016
  id: secretId,
25307
26017
  delegated_to: delegatedTo ?? null
25308
- };
25309
- const response = await this.client.invoke({ toolkit: "secrets", tool: "delete_secret", input: req });
26018
+ });
25310
26019
  if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25311
26020
  return;
25312
26021
  }
25313
26022
  throw this.unexpectedResponse("delete_secret");
25314
26023
  }
25315
26024
  async deleteRequestedSecret({ url, type, delegatedTo }) {
25316
- const req = {
26025
+ const response = await this.invoke("delete_requested_secret", {
25317
26026
  url,
25318
26027
  type,
25319
26028
  delegated_to: delegatedTo ?? null
25320
- };
25321
- const response = await this.client.invoke({ toolkit: "secrets", tool: "delete_requested_secret", input: req });
26029
+ });
25322
26030
  if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
25323
26031
  return;
25324
26032
  }
25325
26033
  throw this.unexpectedResponse("delete_requested_secret");
25326
26034
  }
26035
+ async requestSecret({ fromParticipantId, url, type, timeout = 60 * 5, delegateTo }) {
26036
+ const response = await this.invoke("request_secret", {
26037
+ url,
26038
+ type,
26039
+ participant_id: fromParticipantId,
26040
+ timeout,
26041
+ delegate_to: delegateTo ?? null
26042
+ });
26043
+ if (response instanceof response_1.FileContent) {
26044
+ return response.data;
26045
+ }
26046
+ throw this.unexpectedResponse("request_secret");
26047
+ }
26048
+ async setSecret({ secretId, type, mimeType, name, delegatedTo, forIdentity, data }) {
26049
+ const response = await this.invoke("set_secret", new response_1.BinaryContent({
26050
+ data,
26051
+ headers: {
26052
+ secret_id: secretId ?? null,
26053
+ type: type ?? mimeType ?? null,
26054
+ name: name ?? null,
26055
+ delegated_to: delegatedTo ?? null,
26056
+ for_identity: forIdentity ?? null,
26057
+ has_data: true
26058
+ }
26059
+ }));
26060
+ if (response instanceof response_1.EmptyContent || response instanceof response_1.JsonContent) {
26061
+ return;
26062
+ }
26063
+ throw this.unexpectedResponse("set_secret");
26064
+ }
26065
+ async getSecret({ secretId, type, name, delegatedTo }) {
26066
+ const response = await this.invoke("get_secret", {
26067
+ secret_id: secretId ?? null,
26068
+ type: type ?? null,
26069
+ name: name ?? null,
26070
+ delegated_to: delegatedTo ?? null
26071
+ });
26072
+ if (response instanceof response_1.EmptyContent) {
26073
+ return null;
26074
+ }
26075
+ if (response instanceof response_1.FileContent) {
26076
+ return response;
26077
+ }
26078
+ throw this.unexpectedResponse("get_secret");
26079
+ }
25327
26080
  };
25328
26081
  exports.SecretsClient = SecretsClient;
25329
26082
  }
@@ -25482,6 +26235,7 @@ ${newlined}
25482
26235
  return this._ready.fut;
25483
26236
  }
25484
26237
  async start({ onDone, onError } = {}) {
26238
+ await this.messaging.start();
25485
26239
  this.sync.start({ onDone, onError });
25486
26240
  await this.ready;
25487
26241
  }
@@ -25491,6 +26245,7 @@ ${newlined}
25491
26245
  pr?.reject(new Error("Disposed"));
25492
26246
  this._pendingRequests.delete(prKey);
25493
26247
  }
26248
+ this.messaging.dispose();
25494
26249
  this.sync.dispose();
25495
26250
  for (const stream of this._toolCallStreams.values()) {
25496
26251
  stream.close();
@@ -26252,9 +27007,6 @@ ${newlined}
26252
27007
 
26253
27008
  // src/ensure-login.ts
26254
27009
  var DEFAULT_SERVER_URL = "https://api.meshagent.com";
26255
- var CALLBACK_URL_KEY = "ma:callback_url";
26256
- var CALLBACK_SOURCE_QUERY_PARAM = "ma_origin";
26257
- var CALLBACK_SOURCE_QUERY_VALUE = "meshagent_auth";
26258
27010
  function getCurrentUrl() {
26259
27011
  if (typeof window === "undefined") {
26260
27012
  throw new Error("ensureLogin requires a browser environment");
@@ -26263,23 +27015,17 @@ ${newlined}
26263
27015
  }
26264
27016
  function clearMeshagentAuthQueryParams(url) {
26265
27017
  url.searchParams.delete("code");
27018
+ url.searchParams.delete("scope");
26266
27019
  url.searchParams.delete("state");
26267
27020
  url.searchParams.delete("error");
26268
27021
  url.searchParams.delete("error_description");
26269
27022
  url.searchParams.delete("error_uri");
26270
- url.searchParams.delete(CALLBACK_SOURCE_QUERY_PARAM);
26271
- }
26272
- function hasMeshagentCallbackMarker(url) {
26273
- return url.searchParams.get(CALLBACK_SOURCE_QUERY_PARAM) === CALLBACK_SOURCE_QUERY_VALUE;
26274
27023
  }
26275
27024
  function isMeshagentCallbackUrl(callbackUrl) {
26276
27025
  const currentUrl = getCurrentUrl();
26277
27026
  if (!currentUrl.searchParams.has("code")) {
26278
27027
  return false;
26279
27028
  }
26280
- if (!callbackUrl) {
26281
- return hasMeshagentCallbackMarker(currentUrl);
26282
- }
26283
27029
  const expectedCallbackUrl = new URL(callbackUrl, currentUrl);
26284
27030
  clearMeshagentAuthQueryParams(currentUrl);
26285
27031
  clearMeshagentAuthQueryParams(expectedCallbackUrl);
@@ -26291,28 +27037,8 @@ ${newlined}
26291
27037
  }
26292
27038
  const currentUrl = getCurrentUrl();
26293
27039
  clearMeshagentAuthQueryParams(currentUrl);
26294
- currentUrl.searchParams.set(
26295
- CALLBACK_SOURCE_QUERY_PARAM,
26296
- CALLBACK_SOURCE_QUERY_VALUE
26297
- );
26298
27040
  return currentUrl.toString();
26299
27041
  }
26300
- function getExchangeCallbackUrl(callbackUrl, storage) {
26301
- if (callbackUrl) {
26302
- return callbackUrl;
26303
- }
26304
- const storedCallbackUrl = storage.getItem(CALLBACK_URL_KEY);
26305
- if (storedCallbackUrl) {
26306
- return storedCallbackUrl;
26307
- }
26308
- return getRedirectCallbackUrl(void 0);
26309
- }
26310
- function saveCallbackUrl(storage, callbackUrl) {
26311
- storage.setItem(CALLBACK_URL_KEY, callbackUrl);
26312
- }
26313
- function clearCallbackUrl(storage) {
26314
- storage.removeItem(CALLBACK_URL_KEY);
26315
- }
26316
27042
  function replaceCurrentUrlWithoutAuthParams() {
26317
27043
  if (typeof window === "undefined" || typeof window.history.replaceState !== "function") {
26318
27044
  return;
@@ -26330,9 +27056,9 @@ ${newlined}
26330
27056
  const serverBaseUrl = serverUrl ?? DEFAULT_SERVER_URL;
26331
27057
  const storage = getDefaultStorage();
26332
27058
  const cache2 = new LocalStoragePkceCache(storage);
26333
- const authorizationCode = isMeshagentCallbackUrl(callbackUrl) ? getAuthorizationCode() : null;
27059
+ const authorizationCode = isMeshagentCallbackUrl(callbackUrl ?? window.location.href) ? getAuthorizationCode() : null;
26334
27060
  if (authorizationCode) {
26335
- const exchangeCallbackUrl = getExchangeCallbackUrl(callbackUrl, storage);
27061
+ const exchangeCallbackUrl = getRedirectCallbackUrl(callbackUrl);
26336
27062
  await exchangeToken({
26337
27063
  oauthClientId,
26338
27064
  serverUrl: serverBaseUrl,
@@ -26342,18 +27068,22 @@ ${newlined}
26342
27068
  auth: MeshagentAuth.current
26343
27069
  });
26344
27070
  await cache2.clearVerifier();
26345
- clearCallbackUrl(storage);
26346
27071
  replaceCurrentUrlWithoutAuthParams();
26347
27072
  return;
26348
27073
  }
26349
27074
  if (MeshagentAuth.current.isLoggedIn()) {
27075
+ const auth = MeshagentAuth.current;
27076
+ const client = getMeshagentClient(auth, serverUrl ?? DEFAULT_SERVER_URL);
27077
+ const me = await client.getUserProfile("me");
27078
+ if (me) {
27079
+ auth.setUser(me);
27080
+ }
26350
27081
  return;
26351
27082
  }
26352
27083
  const redirectCallbackUrl = getRedirectCallbackUrl(callbackUrl);
26353
27084
  const generator = new PkceGenerator();
26354
27085
  const pkce = await generator.generate();
26355
27086
  await cache2.saveVerifier(pkce.codeVerifier);
26356
- saveCallbackUrl(storage, redirectCallbackUrl);
26357
27087
  const query = new URLSearchParams({
26358
27088
  scope: "email",
26359
27089
  client_id: oauthClientId,