appwrite-cli 13.6.0 → 13.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +2 -2
  3. package/cli.ts +3 -3
  4. package/dist/bundle-win-arm64.mjs +336 -212
  5. package/dist/cli.cjs +336 -212
  6. package/dist/index.cjs +156 -104
  7. package/dist/index.js +156 -104
  8. package/dist/lib/commands/config-validations.d.ts +1 -1
  9. package/dist/lib/commands/config-validations.d.ts.map +1 -1
  10. package/dist/lib/commands/errors.d.ts +4 -4
  11. package/dist/lib/commands/errors.d.ts.map +1 -1
  12. package/dist/lib/commands/generate.d.ts.map +1 -1
  13. package/dist/lib/commands/generators/base.d.ts +5 -0
  14. package/dist/lib/commands/generators/base.d.ts.map +1 -1
  15. package/dist/lib/commands/generic.d.ts.map +1 -1
  16. package/dist/lib/commands/init.d.ts.map +1 -1
  17. package/dist/lib/commands/run.d.ts.map +1 -1
  18. package/dist/lib/commands/types.d.ts.map +1 -1
  19. package/dist/lib/commands/update.d.ts.map +1 -1
  20. package/dist/lib/commands/utils/change-approval.d.ts +3 -3
  21. package/dist/lib/commands/utils/change-approval.d.ts.map +1 -1
  22. package/dist/lib/commands/utils/database-sync.d.ts.map +1 -1
  23. package/dist/lib/commands/utils/deployment.d.ts +16 -4
  24. package/dist/lib/commands/utils/deployment.d.ts.map +1 -1
  25. package/dist/lib/commands/utils/pools.d.ts.map +1 -1
  26. package/dist/lib/constants.d.ts +1 -1
  27. package/dist/lib/emulation/docker.d.ts.map +1 -1
  28. package/dist/lib/json.d.ts +1 -1
  29. package/dist/lib/json.d.ts.map +1 -1
  30. package/dist/lib/paginate.d.ts +5 -6
  31. package/dist/lib/paginate.d.ts.map +1 -1
  32. package/dist/lib/parser.d.ts +5 -4
  33. package/dist/lib/parser.d.ts.map +1 -1
  34. package/dist/lib/spinner.d.ts +1 -1
  35. package/dist/lib/spinner.d.ts.map +1 -1
  36. package/dist/lib/utils.d.ts +6 -1
  37. package/dist/lib/utils.d.ts.map +1 -1
  38. package/dist/lib/validations.d.ts +1 -1
  39. package/dist/lib/validations.d.ts.map +1 -1
  40. package/eslint.config.js +45 -0
  41. package/install.ps1 +2 -2
  42. package/install.sh +1 -1
  43. package/lib/client.ts +3 -3
  44. package/lib/commands/config-validations.ts +1 -1
  45. package/lib/commands/config.ts +2 -2
  46. package/lib/commands/errors.ts +2 -2
  47. package/lib/commands/generate.ts +8 -6
  48. package/lib/commands/generators/base.ts +6 -0
  49. package/lib/commands/generators/typescript/databases.ts +9 -9
  50. package/lib/commands/generators/typescript/templates/databases.ts.hbs +16 -16
  51. package/lib/commands/generic.ts +21 -16
  52. package/lib/commands/init.ts +147 -61
  53. package/lib/commands/pull.ts +1 -1
  54. package/lib/commands/push.ts +19 -19
  55. package/lib/commands/run.ts +15 -9
  56. package/lib/commands/types.ts +18 -8
  57. package/lib/commands/update.ts +24 -16
  58. package/lib/commands/utils/attributes.ts +6 -6
  59. package/lib/commands/utils/change-approval.ts +26 -19
  60. package/lib/commands/utils/database-sync.ts +58 -18
  61. package/lib/commands/utils/deployment.ts +22 -5
  62. package/lib/commands/utils/pools.ts +11 -5
  63. package/lib/config.ts +1 -1
  64. package/lib/constants.ts +1 -1
  65. package/lib/emulation/docker.ts +5 -6
  66. package/lib/emulation/utils.ts +2 -2
  67. package/lib/json.ts +15 -7
  68. package/lib/paginate.ts +30 -20
  69. package/lib/parser.ts +46 -15
  70. package/lib/questions.ts +38 -38
  71. package/lib/spinner.ts +5 -1
  72. package/lib/utils.ts +15 -3
  73. package/lib/validations.ts +1 -1
  74. package/package.json +7 -1
  75. package/scoop/appwrite.config.json +3 -3
package/dist/index.cjs CHANGED
@@ -1934,9 +1934,9 @@ var require_source = __commonJS({
1934
1934
  }
1935
1935
  });
1936
1936
 
1937
- // node_modules/escape-string-regexp/index.js
1937
+ // node_modules/figures/node_modules/escape-string-regexp/index.js
1938
1938
  var require_escape_string_regexp = __commonJS({
1939
- "node_modules/escape-string-regexp/index.js"(exports2, module2) {
1939
+ "node_modules/figures/node_modules/escape-string-regexp/index.js"(exports2, module2) {
1940
1940
  "use strict";
1941
1941
  var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
1942
1942
  module2.exports = function(str) {
@@ -19581,9 +19581,9 @@ var require_stream_duplex = __commonJS({
19581
19581
  }
19582
19582
  });
19583
19583
 
19584
- // node_modules/string_decoder/node_modules/safe-buffer/index.js
19584
+ // node_modules/safe-buffer/index.js
19585
19585
  var require_safe_buffer = __commonJS({
19586
- "node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports2, module2) {
19586
+ "node_modules/safe-buffer/index.js"(exports2, module2) {
19587
19587
  var buffer = require("buffer");
19588
19588
  var Buffer2 = buffer.Buffer;
19589
19589
  function copyProps(src, dst) {
@@ -69377,7 +69377,7 @@ var id_default = ID;
69377
69377
  // lib/constants.ts
69378
69378
  var SDK_TITLE = "Appwrite";
69379
69379
  var SDK_TITLE_LOWER = "appwrite";
69380
- var SDK_VERSION = "13.6.0";
69380
+ var SDK_VERSION = "13.6.1";
69381
69381
  var SDK_LOGO = "\n _ _ _ ___ __ _____\n /_\\ _ __ _ ____ ___ __(_) |_ ___ / __\\ / / \\_ \\\n //_\\\\| '_ \\| '_ \\ \\ /\\ / / '__| | __/ _ \\ / / / / / /\\/\n / _ \\ |_) | |_) \\ V V /| | | | || __/ / /___/ /___/\\/ /_\n \\_/ \\_/ .__/| .__/ \\_/\\_/ |_| |_|\\__\\___| \\____/\\____/\\____/\n |_| |_|\n\n";
69382
69382
  var EXECUTABLE_NAME = "appwrite";
69383
69383
  var NPM_PACKAGE_NAME = "appwrite-cli";
@@ -83285,7 +83285,7 @@ var int64Schema = external_exports.preprocess(
83285
83285
  const valueOfResult = val.valueOf();
83286
83286
  const bigIntVal = BigInt(valueOfResult);
83287
83287
  return bigIntVal;
83288
- } catch (e) {
83288
+ } catch (_e) {
83289
83289
  return void 0;
83290
83290
  }
83291
83291
  }
@@ -83295,7 +83295,7 @@ var int64Schema = external_exports.preprocess(
83295
83295
  if (typeof val === "string") {
83296
83296
  try {
83297
83297
  return BigInt(val);
83298
- } catch (e) {
83298
+ } catch (_e) {
83299
83299
  return void 0;
83300
83300
  }
83301
83301
  }
@@ -83609,7 +83609,7 @@ var createSettingsObject = (project) => {
83609
83609
  };
83610
83610
  };
83611
83611
  var checkDeployConditions = (localConfig2) => {
83612
- if (Object.keys(localConfig2.data).length === 0) {
83612
+ if (localConfig2.keys().length === 0) {
83613
83613
  throw new Error(
83614
83614
  "No appwrite.config.json file found in the current directory. Please run this command again in the folder containing your appwrite.config.json file, or run 'appwrite init project' to link current directory to an Appwrite project."
83615
83615
  );
@@ -83757,7 +83757,7 @@ var Config = class {
83757
83757
  try {
83758
83758
  const file2 = import_fs.default.readFileSync(this.path).toString();
83759
83759
  this.data = JSONBig.parse(file2);
83760
- } catch (e) {
83760
+ } catch (_e) {
83761
83761
  this.data = {};
83762
83762
  }
83763
83763
  }
@@ -84668,7 +84668,7 @@ var Spinner = class _Spinner {
84668
84668
  static stop() {
84669
84669
  _Spinner.updatesBar.stop();
84670
84670
  }
84671
- static formatter(options, params, payload) {
84671
+ static formatter(_options, _params, payload) {
84672
84672
  const status = payload.status.padEnd(12);
84673
84673
  const middle = `${payload.resource} (${payload.id})`.padEnd(40);
84674
84674
  let prefix = import_chalk.default.cyan(payload.prefix ?? "\u29D7");
@@ -84739,19 +84739,22 @@ async function paginate(action, args = {}, limit = 100, wrapper = "", queries =
84739
84739
  ]
84740
84740
  });
84741
84741
  if (wrapper === "") {
84742
- if (response.length === 0) {
84742
+ const listResponse = response;
84743
+ if (listResponse.length === 0) {
84743
84744
  break;
84744
84745
  }
84745
- results = results.concat(response);
84746
+ results = results.concat(listResponse);
84746
84747
  } else {
84747
- if (response[wrapper].length === 0) {
84748
+ const wrappedResponse = response;
84749
+ const wrappedResults = wrappedResponse[wrapper] ?? [];
84750
+ if (wrappedResults.length === 0) {
84751
+ break;
84752
+ }
84753
+ results = results.concat(wrappedResults);
84754
+ total = wrappedResponse.total;
84755
+ if (results.length >= total) {
84748
84756
  break;
84749
84757
  }
84750
- results = results.concat(response[wrapper]);
84751
- }
84752
- total = response.total;
84753
- if (results.length >= total) {
84754
- break;
84755
84758
  }
84756
84759
  pageNumber++;
84757
84760
  }
@@ -103996,7 +103999,7 @@ var package_default = {
103996
103999
  type: "module",
103997
104000
  homepage: "https://appwrite.io/support",
103998
104001
  description: "Appwrite is an open-source self-hosted backend server that abstracts and simplifies complex and repetitive development tasks behind a very simple REST API",
103999
- version: "13.6.0",
104002
+ version: "13.6.1",
104000
104003
  license: "BSD-3-Clause",
104001
104004
  main: "dist/index.cjs",
104002
104005
  module: "dist/index.js",
@@ -104027,6 +104030,7 @@ var package_default = {
104027
104030
  "build:lib:esm": "esbuild index.ts --bundle --platform=node --target=node18 --format=esm --loader:.hbs=text --outfile=dist/index.js",
104028
104031
  "build:lib:cjs": "esbuild index.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --outfile=dist/index.cjs",
104029
104032
  "build:cli": "esbuild cli.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --external:fsevents --outfile=dist/cli.cjs",
104033
+ lint: "eslint .",
104030
104034
  format: 'prettier --write "**/*.{js,ts,json,md}"',
104031
104035
  generate: "tsx scripts/generate-commands.ts",
104032
104036
  prepublishOnly: "npm run build",
@@ -104058,7 +104062,12 @@ var package_default = {
104058
104062
  zod: "^4.3.5"
104059
104063
  },
104060
104064
  devDependencies: {
104065
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
104066
+ "@typescript-eslint/parser": "^8.0.0",
104061
104067
  "@types/bun": "^1.3.5",
104068
+ eslint: "^9.0.0",
104069
+ "eslint-plugin-unused-imports": "^4.0.0",
104070
+ "typescript-eslint": "^8.0.0",
104062
104071
  "@types/cli-progress": "^3.11.5",
104063
104072
  "@types/inquirer": "^8.2.10",
104064
104073
  "@types/json-bigint": "^1.0.4",
@@ -104090,14 +104099,28 @@ var cliConfig = {
104090
104099
  report: false,
104091
104100
  reportData: {}
104092
104101
  };
104102
+ var toJsonObject = (value) => {
104103
+ if (value && typeof value === "object" && !Array.isArray(value)) {
104104
+ return value;
104105
+ }
104106
+ return null;
104107
+ };
104108
+ var extractReportCommandArgs = (value) => {
104109
+ if (!value || typeof value !== "object") {
104110
+ return [];
104111
+ }
104112
+ const reportData = value;
104113
+ if (!Array.isArray(reportData.data?.args)) {
104114
+ return [];
104115
+ }
104116
+ return reportData.data.args;
104117
+ };
104093
104118
  var drawTable = (data) => {
104094
104119
  if (data.length == 0) {
104095
104120
  console.log("[]");
104096
104121
  return;
104097
104122
  }
104098
- const rows = data.map(
104099
- (item) => item && typeof item === "object" && !Array.isArray(item) ? item : {}
104100
- );
104123
+ const rows = data.map((item) => toJsonObject(item) ?? {});
104101
104124
  const obj = rows.reduce((res, item) => ({ ...res, ...item }), {});
104102
104125
  const keys = Object.keys(obj);
104103
104126
  if (keys.length === 0) {
@@ -104140,7 +104163,7 @@ var drawTable = (data) => {
104140
104163
  } else if (typeof row[key] === "object") {
104141
104164
  rowValues.push(JSON.stringify(row[key]));
104142
104165
  } else {
104143
- rowValues.push(row[key]);
104166
+ rowValues.push(String(row[key]));
104144
104167
  }
104145
104168
  }
104146
104169
  table.push(rowValues);
@@ -104152,7 +104175,7 @@ var drawJSON = (data) => {
104152
104175
  };
104153
104176
  var parseError = (err) => {
104154
104177
  if (cliConfig.report) {
104155
- (async () => {
104178
+ void (async () => {
104156
104179
  let appwriteVersion = "unknown";
104157
104180
  const endpoint = globalConfig2.getEndpoint();
104158
104181
  try {
@@ -104165,7 +104188,8 @@ var parseError = (err) => {
104165
104188
  } catch {
104166
104189
  }
104167
104190
  const version2 = SDK_VERSION;
104168
- const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${cliConfig.reportData.data.args.join(" ")}\``;
104191
+ const commandArgs = extractReportCommandArgs(cliConfig.reportData);
104192
+ const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${commandArgs.join(" ")}\``;
104169
104193
  const yourEnvironment = `CLI version: ${version2}
104170
104194
  Operation System: ${import_os2.default.type()}
104171
104195
  Appwrite version: ${appwriteVersion}
@@ -104217,7 +104241,7 @@ var actionRunner = (fn) => {
104217
104241
  error48(`The '--all' and '--id' flags cannot be used together.`);
104218
104242
  process.exit(1);
104219
104243
  }
104220
- return fn(...args).catch(parseError);
104244
+ return fn(...args).then(() => void 0).catch(parseError);
104221
104245
  };
104222
104246
  };
104223
104247
  var log = (message) => {
@@ -104330,6 +104354,9 @@ async function downloadDeploymentCode(params) {
104330
104354
  {},
104331
104355
  "arrayBuffer"
104332
104356
  );
104357
+ if (!(downloadBuffer instanceof ArrayBuffer)) {
104358
+ throw new Error("Failed to download deployment archive as ArrayBuffer.");
104359
+ }
104333
104360
  try {
104334
104361
  import_fs2.default.writeFileSync(compressedFileName, Buffer.from(downloadBuffer));
104335
104362
  } catch (err) {
@@ -104541,7 +104568,7 @@ var questionsInitProject = [
104541
104568
  name: "organization",
104542
104569
  message: "Choose your organization",
104543
104570
  choices: async () => {
104544
- let client = await sdkForConsole(true);
104571
+ const client = await sdkForConsole(true);
104545
104572
  const { teams } = isCloud() ? await paginate(
104546
104573
  async (opts = {}) => (await getOrganizationsService(opts.sdk)).list(),
104547
104574
  { sdk: client },
@@ -104553,7 +104580,7 @@ var questionsInitProject = [
104553
104580
  100,
104554
104581
  "teams"
104555
104582
  );
104556
- let choices = teams.map((team, idx) => {
104583
+ const choices = teams.map((team, _idx) => {
104557
104584
  return {
104558
104585
  name: `${team.name} (${team["$id"]})`,
104559
104586
  value: team["$id"]
@@ -104602,7 +104629,7 @@ var questionsInitProject = [
104602
104629
  "projects",
104603
104630
  queries
104604
104631
  );
104605
- let choices = projects.map((project) => {
104632
+ const choices = projects.map((project) => {
104606
104633
  return {
104607
104634
  name: `${project.name} (${project["$id"]})`,
104608
104635
  value: {
@@ -104623,13 +104650,13 @@ var questionsInitProject = [
104623
104650
  name: "region",
104624
104651
  message: `Select your ${SDK_TITLE} Cloud region`,
104625
104652
  choices: async () => {
104626
- let client = await sdkForConsole(true);
104653
+ const client = await sdkForConsole(true);
104627
104654
  const endpoint = globalConfig2.getEndpoint() || DEFAULT_ENDPOINT;
104628
- let response = await client.call(
104655
+ const response = await client.call(
104629
104656
  "GET",
104630
104657
  new URL(endpoint + "/console/regions")
104631
104658
  );
104632
- let regions = response.regions || [];
104659
+ const regions = response.regions || [];
104633
104660
  if (!regions.length) {
104634
104661
  throw new Error(
104635
104662
  "No regions found. Please check your network or Appwrite Cloud availability."
@@ -104756,9 +104783,9 @@ var questionGetEndpoint = [
104756
104783
  if (!value) {
104757
104784
  return "Please enter a valid endpoint.";
104758
104785
  }
104759
- let client = new Client().setEndpoint(value);
104786
+ const client = new Client().setEndpoint(value);
104760
104787
  try {
104761
- let response = await client.call(
104788
+ const response = await client.call(
104762
104789
  "get",
104763
104790
  new URL(value + "/health/version")
104764
104791
  );
@@ -104767,7 +104794,7 @@ var questionGetEndpoint = [
104767
104794
  } else {
104768
104795
  throw new Error();
104769
104796
  }
104770
- } catch (error49) {
104797
+ } catch (_error) {
104771
104798
  return "Invalid endpoint or your Appwrite server is not running as expected.";
104772
104799
  }
104773
104800
  }
@@ -104803,9 +104830,9 @@ var questionsPushSites = [
104803
104830
  validate: (value) => validateRequired("site", value),
104804
104831
  when: () => localConfig.getSites().length > 0,
104805
104832
  choices: () => {
104806
- let sites = localConfig.getSites();
104833
+ const sites = localConfig.getSites();
104807
104834
  checkDeployConditions(localConfig);
104808
- let choices = sites.map((site, idx) => {
104835
+ const choices = sites.map((site, _idx) => {
104809
104836
  return {
104810
104837
  name: `${site.name} (${site.$id})`,
104811
104838
  value: site.$id
@@ -104823,9 +104850,9 @@ var questionsPushFunctions = [
104823
104850
  validate: (value) => validateRequired("function", value),
104824
104851
  when: () => localConfig.getFunctions().length > 0,
104825
104852
  choices: () => {
104826
- let functions = localConfig.getFunctions();
104853
+ const functions = localConfig.getFunctions();
104827
104854
  checkDeployConditions(localConfig);
104828
- let choices = functions.map((func, idx) => {
104855
+ const choices = functions.map((func, _idx) => {
104829
104856
  return {
104830
104857
  name: `${func.name} (${func.$id})`,
104831
104858
  value: func.$id
@@ -104843,7 +104870,7 @@ var questionsPushCollections = [
104843
104870
  validate: (value) => validateRequired("collection", value),
104844
104871
  when: () => localConfig.getCollections().length > 0,
104845
104872
  choices: () => {
104846
- let collections = localConfig.getCollections();
104873
+ const collections = localConfig.getCollections();
104847
104874
  checkDeployConditions(localConfig);
104848
104875
  return collections.map((collection) => {
104849
104876
  return {
@@ -104862,7 +104889,7 @@ var questionsPushTables = [
104862
104889
  validate: (value) => validateRequired("table", value),
104863
104890
  when: () => localConfig.getTables().length > 0,
104864
104891
  choices: () => {
104865
- let tables = localConfig.getTables();
104892
+ const tables = localConfig.getTables();
104866
104893
  checkDeployConditions(localConfig);
104867
104894
  return tables.map((table) => {
104868
104895
  return {
@@ -104895,7 +104922,7 @@ var questionsPushBuckets = [
104895
104922
  validate: (value) => validateRequired("bucket", value),
104896
104923
  when: () => localConfig.getBuckets().length > 0,
104897
104924
  choices: () => {
104898
- let buckets = localConfig.getBuckets();
104925
+ const buckets = localConfig.getBuckets();
104899
104926
  checkDeployConditions(localConfig);
104900
104927
  return buckets.map((bucket) => {
104901
104928
  return {
@@ -104914,7 +104941,7 @@ var questionsPushMessagingTopics = [
104914
104941
  validate: (value) => validateRequired("topics", value),
104915
104942
  when: () => localConfig.getMessagingTopics().length > 0,
104916
104943
  choices: () => {
104917
- let topics = localConfig.getMessagingTopics();
104944
+ const topics = localConfig.getMessagingTopics();
104918
104945
  return topics.map((topic) => {
104919
104946
  return {
104920
104947
  name: `${topic.name} (${topic["$id"]})`,
@@ -104945,7 +104972,7 @@ var questionsPushTeams = [
104945
104972
  validate: (value) => validateRequired("team", value),
104946
104973
  when: () => localConfig.getTeams().length > 0,
104947
104974
  choices: () => {
104948
- let teams = localConfig.getTeams();
104975
+ const teams = localConfig.getTeams();
104949
104976
  checkDeployConditions(localConfig);
104950
104977
  return teams.map((team) => {
104951
104978
  return {
@@ -104987,7 +105014,7 @@ var Pools = class {
104987
105014
  return true;
104988
105015
  }
104989
105016
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
104990
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105017
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
104991
105018
  if (steps > 1 && iteration === 1) {
104992
105019
  this.pollMaxDebounces *= steps;
104993
105020
  log(
@@ -105013,7 +105040,7 @@ var Pools = class {
105013
105040
  return true;
105014
105041
  }
105015
105042
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105016
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105043
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105017
105044
  if (steps > 1 && iteration === 1) {
105018
105045
  this.pollMaxDebounces *= steps;
105019
105046
  log(
@@ -105029,7 +105056,10 @@ var Pools = class {
105029
105056
  return false;
105030
105057
  }
105031
105058
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105032
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
105059
+ const steps = Math.max(
105060
+ 1,
105061
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
105062
+ );
105033
105063
  if (steps > 1 && iteration === 1) {
105034
105064
  this.pollMaxDebounces *= steps;
105035
105065
  log(
@@ -105072,7 +105102,10 @@ var Pools = class {
105072
105102
  return false;
105073
105103
  }
105074
105104
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105075
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
105105
+ const steps = Math.max(
105106
+ 1,
105107
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
105108
+ );
105076
105109
  if (steps > 1 && iteration === 1) {
105077
105110
  this.pollMaxDebounces *= steps;
105078
105111
  log(
@@ -105121,7 +105154,7 @@ var Pools = class {
105121
105154
  return false;
105122
105155
  }
105123
105156
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105124
- let steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
105157
+ const steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
105125
105158
  if (steps > 1 && iteration === 1) {
105126
105159
  this.pollMaxDebounces *= steps;
105127
105160
  log(
@@ -105214,7 +105247,7 @@ var Attributes = class {
105214
105247
  }
105215
105248
  return answers2.changes;
105216
105249
  }
105217
- let answers = await import_inquirer.default.prompt(questionPushChanges2);
105250
+ const answers = await import_inquirer.default.prompt(questionPushChanges2);
105218
105251
  if (answers.changes !== "YES" && answers.changes !== "NO") {
105219
105252
  answers.changes = await fixConfirmation();
105220
105253
  }
@@ -105257,8 +105290,8 @@ var Attributes = class {
105257
105290
  const keyName = `${import_chalk4.default.yellow(local.key)} in ${collection.name} (${collection["$id"]})`;
105258
105291
  const action = import_chalk4.default.cyan(recreating ? "recreating" : "changing");
105259
105292
  let reason = "";
105260
- let attribute = recreating ? remote : local;
105261
- for (let key of Object.keys(remote)) {
105293
+ const attribute = recreating ? remote : local;
105294
+ for (const key of Object.keys(remote)) {
105262
105295
  if (!KeysAttributes.has(key)) {
105263
105296
  continue;
105264
105297
  }
@@ -105768,7 +105801,7 @@ var Attributes = class {
105768
105801
  createIndexes = async (indexes, collection) => {
105769
105802
  log(`Creating indexes ...`);
105770
105803
  const databasesService = await getDatabasesService(this.client);
105771
- for (let index of indexes) {
105804
+ for (const index of indexes) {
105772
105805
  await databasesService.createIndex({
105773
105806
  databaseId: collection["databaseId"],
105774
105807
  collectionId: collection["$id"],
@@ -105792,7 +105825,7 @@ var Attributes = class {
105792
105825
  };
105793
105826
  createAttributes = async (attributes, collection) => {
105794
105827
  log(`Creating attributes ...`);
105795
- for (let attribute of attributes) {
105828
+ for (const attribute of attributes) {
105796
105829
  if (attribute.side !== "child") {
105797
105830
  await this.createAttribute(
105798
105831
  collection["databaseId"],
@@ -105816,7 +105849,7 @@ var Attributes = class {
105816
105849
  };
105817
105850
  createColumns = async (columns, table) => {
105818
105851
  log(`Creating columns ...`);
105819
- for (let column of columns) {
105852
+ for (const column of columns) {
105820
105853
  if (column.side !== "child") {
105821
105854
  await this.createAttribute(table["databaseId"], table["$id"], column);
105822
105855
  }
@@ -105851,7 +105884,7 @@ var getConfirmation = async () => {
105851
105884
  }
105852
105885
  return answers2.changes;
105853
105886
  }
105854
- let answers = await import_inquirer2.default.prompt(questionPushChanges);
105887
+ const answers = await import_inquirer2.default.prompt(questionPushChanges);
105855
105888
  if (answers.changes !== "YES" && answers.changes !== "NO") {
105856
105889
  answers.changes = await fixConfirmation();
105857
105890
  }
@@ -105901,7 +105934,7 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105901
105934
  options[secondResourceName] = localResource[secondId];
105902
105935
  }
105903
105936
  const remoteResource = await resourceGetFunction(options);
105904
- for (let [key, value] of Object.entries(
105937
+ for (const [key, value] of Object.entries(
105905
105938
  whitelistKeys(remoteResource, keys)
105906
105939
  )) {
105907
105940
  if (skipKeys.includes(key)) {
@@ -105910,28 +105943,30 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105910
105943
  if (isEmpty(value) && isEmpty(localResource[key])) {
105911
105944
  continue;
105912
105945
  }
105913
- if (Array.isArray(value) && Array.isArray(localResource[key])) {
105914
- if (JSON.stringify(value) !== JSON.stringify(localResource[key])) {
105946
+ const localValue = localResource[key];
105947
+ if (Array.isArray(value) && Array.isArray(localValue)) {
105948
+ if (JSON.stringify(value) !== JSON.stringify(localValue)) {
105915
105949
  changes.push({
105916
105950
  id: localResource["$id"],
105917
105951
  key,
105918
105952
  remote: import_chalk5.default.red(value.join("\n")),
105919
- local: import_chalk5.default.green(localResource[key].join("\n"))
105953
+ local: import_chalk5.default.green(
105954
+ localValue.map((entry) => String(entry)).join("\n")
105955
+ )
105920
105956
  });
105921
105957
  }
105922
- } else if (value !== localResource[key]) {
105958
+ } else if (value !== localValue) {
105923
105959
  changes.push({
105924
105960
  id: localResource["$id"],
105925
105961
  key,
105926
- remote: import_chalk5.default.red(value),
105927
- local: import_chalk5.default.green(localResource[key])
105962
+ remote: import_chalk5.default.red(String(value ?? "")),
105963
+ local: import_chalk5.default.green(String(localValue ?? ""))
105928
105964
  });
105929
105965
  }
105930
105966
  }
105931
105967
  } catch (e) {
105932
- if (Number(e.code) !== 404) {
105933
- throw e;
105934
- }
105968
+ const isNotFound = e instanceof AppwriteException && Number(e.code) === 404;
105969
+ if (!isNotFound) throw e;
105935
105970
  }
105936
105971
  })
105937
105972
  );
@@ -105948,18 +105983,37 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105948
105983
 
105949
105984
  // lib/commands/utils/database-sync.ts
105950
105985
  var import_chalk6 = __toESM(require_source(), 1);
105986
+ var isTablesDBResource = (value) => {
105987
+ if (!value || typeof value !== "object") {
105988
+ return false;
105989
+ }
105990
+ return "$id" in value && typeof value.$id === "string" && "name" in value && typeof value.name === "string" && "enabled" in value && typeof value.enabled === "boolean";
105991
+ };
105992
+ var getSyncErrorMessage = (err) => {
105993
+ if (err instanceof AppwriteException) {
105994
+ return err.message;
105995
+ }
105996
+ if (err instanceof Error) {
105997
+ return err.message;
105998
+ }
105999
+ return String(err);
106000
+ };
105951
106001
  var checkAndApplyTablesDBChanges = async () => {
105952
106002
  log("Checking for tablesDB changes ...");
105953
106003
  const localTablesDBs = localConfig.getTablesDBs();
105954
- const { databases: remoteTablesDBs } = await paginate(
106004
+ const paginatedResult = await paginate(
105955
106005
  async (args) => {
105956
106006
  const tablesDBService = await getTablesDBService();
105957
- return await tablesDBService.list(args.queries || []);
106007
+ const queries = Array.isArray(args.queries) ? args.queries.filter(
106008
+ (query) => typeof query === "string"
106009
+ ) : [];
106010
+ return await tablesDBService.list(queries);
105958
106011
  },
105959
106012
  {},
105960
106013
  100,
105961
106014
  "databases"
105962
106015
  );
106016
+ const remoteTablesDBs = Array.isArray(paginatedResult.databases) ? paginatedResult.databases.filter(isTablesDBResource) : [];
105963
106017
  if (localTablesDBs.length === 0 && remoteTablesDBs.length === 0) {
105964
106018
  return { applied: false, resyncNeeded: false };
105965
106019
  }
@@ -105981,9 +106035,7 @@ var checkAndApplyTablesDBChanges = async () => {
105981
106035
  }
105982
106036
  }
105983
106037
  for (const localDB of localTablesDBs) {
105984
- const remoteDB = remoteTablesDBs.find(
105985
- (db) => db.$id === localDB.$id
105986
- );
106038
+ const remoteDB = remoteTablesDBs.find((db) => db.$id === localDB.$id);
105987
106039
  if (!remoteDB) {
105988
106040
  toCreate.push(localDB);
105989
106041
  changes.push({
@@ -106050,7 +106102,7 @@ var checkAndApplyTablesDBChanges = async () => {
106050
106102
  needsResync = true;
106051
106103
  } catch (e) {
106052
106104
  error48(
106053
- `Failed to delete database ${db.name} ( ${db.$id} ): ${e.message}`
106105
+ `Failed to delete database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106054
106106
  );
106055
106107
  throw new Error(
106056
106108
  `Database sync failed during deletion of ${db.$id}. Some changes may have been applied.`
@@ -106065,7 +106117,7 @@ var checkAndApplyTablesDBChanges = async () => {
106065
106117
  success2(`Created ${db.name} ( ${db.$id} )`);
106066
106118
  } catch (e) {
106067
106119
  error48(
106068
- `Failed to create database ${db.name} ( ${db.$id} ): ${e.message}`
106120
+ `Failed to create database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106069
106121
  );
106070
106122
  throw new Error(
106071
106123
  `Database sync failed during creation of ${db.$id}. Some changes may have been applied.`
@@ -106080,7 +106132,7 @@ var checkAndApplyTablesDBChanges = async () => {
106080
106132
  success2(`Updated ${db.name} ( ${db.$id} )`);
106081
106133
  } catch (e) {
106082
106134
  error48(
106083
- `Failed to update database ${db.name} ( ${db.$id} ): ${e.message}`
106135
+ `Failed to update database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106084
106136
  );
106085
106137
  throw new Error(
106086
106138
  `Database sync failed during update of ${db.$id}. Some changes may have been applied.`
@@ -106314,7 +106366,7 @@ var Push = class {
106314
106366
  }
106315
106367
  if (settings.services) {
106316
106368
  this.log("Applying service statuses ...");
106317
- for (let [service, status] of Object.entries(settings.services)) {
106369
+ for (const [service, status] of Object.entries(settings.services)) {
106318
106370
  await projectsService.updateServiceStatus({
106319
106371
  projectId,
106320
106372
  service,
@@ -106360,7 +106412,7 @@ var Push = class {
106360
106412
  }
106361
106413
  if (settings.auth.methods) {
106362
106414
  this.log("Applying auth methods statuses ...");
106363
- for (let [method, status] of Object.entries(settings.auth.methods)) {
106415
+ for (const [method, status] of Object.entries(settings.auth.methods)) {
106364
106416
  await projectsService.updateAuthStatus({
106365
106417
  projectId,
106366
106418
  method,
@@ -106664,7 +106716,7 @@ var Push = class {
106664
106716
  ([key, value]) => ({ key, value })
106665
106717
  );
106666
106718
  }
106667
- } catch (error49) {
106719
+ } catch (_error) {
106668
106720
  envVariables = [];
106669
106721
  }
106670
106722
  await Promise.all(
@@ -106961,7 +107013,7 @@ var Push = class {
106961
107013
  ([key, value]) => ({ key, value })
106962
107014
  );
106963
107015
  }
106964
- } catch (error49) {
107016
+ } catch (_error) {
106965
107017
  envVariables = [];
106966
107018
  }
106967
107019
  await Promise.all(
@@ -107128,7 +107180,7 @@ var Push = class {
107128
107180
  skipConfirmation,
107129
107181
  this.projectClient
107130
107182
  );
107131
- let tablesChanged = /* @__PURE__ */ new Set();
107183
+ const tablesChanged = /* @__PURE__ */ new Set();
107132
107184
  const errors = [];
107133
107185
  await Promise.all(
107134
107186
  tables.map(async (table) => {
@@ -107182,7 +107234,7 @@ var Push = class {
107182
107234
  }
107183
107235
  })
107184
107236
  );
107185
- for (let table of tables) {
107237
+ for (const table of tables) {
107186
107238
  let columns = table.columns;
107187
107239
  let indexes = table.indexes;
107188
107240
  let hadChanges = false;
@@ -107461,7 +107513,7 @@ var pushSettings = async () => {
107461
107513
  checkDeployConditions(localConfig);
107462
107514
  try {
107463
107515
  const projectsService = await getProjectsService();
107464
- let response = await projectsService.get(
107516
+ const response = await projectsService.get(
107465
107517
  localConfig.getProject().projectId
107466
107518
  );
107467
107519
  const remoteSettings = createSettingsObject(response);
@@ -107494,7 +107546,7 @@ var pushSettings = async () => {
107494
107546
  return;
107495
107547
  }
107496
107548
  }
107497
- } catch (e) {
107549
+ } catch (_e) {
107498
107550
  }
107499
107551
  try {
107500
107552
  log("Pushing project settings ...");
@@ -107544,7 +107596,7 @@ var pushSite = async ({
107544
107596
  );
107545
107597
  return;
107546
107598
  }
107547
- let sites = siteIds.map((id) => {
107599
+ const sites = siteIds.map((id) => {
107548
107600
  const sites2 = localConfig.getSites();
107549
107601
  const site = sites2.find((s) => s.$id === id);
107550
107602
  if (!site) {
@@ -107553,7 +107605,7 @@ var pushSite = async ({
107553
107605
  return site;
107554
107606
  });
107555
107607
  log("Validating sites ...");
107556
- for (let site of sites) {
107608
+ for (const site of sites) {
107557
107609
  if (!site.buildCommand) {
107558
107610
  log(`Site ${site.name} is missing build command.`);
107559
107611
  const answers = await import_inquirer3.default.prompt(questionsGetEntrypoint);
@@ -107664,7 +107716,7 @@ var pushFunction = async ({
107664
107716
  );
107665
107717
  return;
107666
107718
  }
107667
- let functions = functionIds.map((id) => {
107719
+ const functions = functionIds.map((id) => {
107668
107720
  const functions2 = localConfig.getFunctions();
107669
107721
  const func = functions2.find((f) => f.$id === id);
107670
107722
  if (!func) {
@@ -107673,7 +107725,7 @@ var pushFunction = async ({
107673
107725
  return func;
107674
107726
  });
107675
107727
  log("Validating functions ...");
107676
- for (let func of functions) {
107728
+ for (const func of functions) {
107677
107729
  if (!func.entrypoint) {
107678
107730
  log(`Function ${func.name} is missing an entrypoint.`);
107679
107731
  const answers = await import_inquirer3.default.prompt(questionsGetEntrypoint);
@@ -107814,7 +107866,7 @@ var pushTable = async ({
107814
107866
  });
107815
107867
  }
107816
107868
  }
107817
- } catch (e) {
107869
+ } catch (_e) {
107818
107870
  }
107819
107871
  }
107820
107872
  if (tablesToDelete.length > 0) {
@@ -107961,7 +108013,7 @@ var pushCollection = async () => {
107961
108013
  }
107962
108014
  };
107963
108015
  var pushBucket = async () => {
107964
- let bucketIds = [];
108016
+ const bucketIds = [];
107965
108017
  const configBuckets = localConfig.getBuckets();
107966
108018
  if (cliConfig.all) {
107967
108019
  checkDeployConditions(localConfig);
@@ -107980,7 +108032,7 @@ var pushBucket = async () => {
107980
108032
  );
107981
108033
  return;
107982
108034
  }
107983
- let buckets = [];
108035
+ const buckets = [];
107984
108036
  for (const bucketId of bucketIds) {
107985
108037
  const idBuckets = configBuckets.filter((b) => b.$id === bucketId);
107986
108038
  buckets.push(...idBuckets);
@@ -108011,7 +108063,7 @@ var pushBucket = async () => {
108011
108063
  }
108012
108064
  };
108013
108065
  var pushTeam = async () => {
108014
- let teamIds = [];
108066
+ const teamIds = [];
108015
108067
  const configTeams = localConfig.getTeams();
108016
108068
  if (cliConfig.all) {
108017
108069
  checkDeployConditions(localConfig);
@@ -108030,7 +108082,7 @@ var pushTeam = async () => {
108030
108082
  );
108031
108083
  return;
108032
108084
  }
108033
- let teams = [];
108085
+ const teams = [];
108034
108086
  for (const teamId of teamIds) {
108035
108087
  const idTeams = configTeams.filter((t) => t.$id === teamId);
108036
108088
  teams.push(...idTeams);
@@ -108061,7 +108113,7 @@ var pushTeam = async () => {
108061
108113
  }
108062
108114
  };
108063
108115
  var pushMessagingTopic = async () => {
108064
- let topicsIds = [];
108116
+ const topicsIds = [];
108065
108117
  const configTopics = localConfig.getMessagingTopics();
108066
108118
  if (cliConfig.all) {
108067
108119
  checkDeployConditions(localConfig);
@@ -108080,7 +108132,7 @@ var pushMessagingTopic = async () => {
108080
108132
  );
108081
108133
  return;
108082
108134
  }
108083
- let topics = [];
108135
+ const topics = [];
108084
108136
  for (const topicId of topicsIds) {
108085
108137
  const idTopic = configTopics.filter((b) => b.$id === topicId);
108086
108138
  topics.push(...idTopic);
@@ -108664,7 +108716,7 @@ var pullResources = async ({
108664
108716
  delete actions.collections;
108665
108717
  }
108666
108718
  if (cliConfig.all) {
108667
- for (let action of Object.values(actions)) {
108719
+ for (const action of Object.values(actions)) {
108668
108720
  cliConfig.all = true;
108669
108721
  await action({ returnOnZero: true });
108670
108722
  }
@@ -109182,7 +109234,7 @@ var BaseDatabasesGenerator = class {
109182
109234
  var types_ts_default = "import { type Models } from '{{appwriteDep}}';\n\n{{{ENUMS}}}{{{TYPES}}}\ndeclare const __roleStringBrand: unique symbol;\nexport type RoleString = string & { readonly [__roleStringBrand]: never };\n\nexport type RoleBuilder = {\n any: () => RoleString;\n user: (userId: string, status?: string) => RoleString;\n users: (status?: string) => RoleString;\n guests: () => RoleString;\n team: (teamId: string, role?: string) => RoleString;\n member: (memberId: string) => RoleString;\n label: (label: string) => RoleString;\n}\n\nexport type PermissionBuilder = {\n read: (role: RoleString) => string;\n write: (role: RoleString) => string;\n create: (role: RoleString) => string;\n update: (role: RoleString) => string;\n delete: (role: RoleString) => string;\n}\n\nexport type PermissionCallback = (permission: PermissionBuilder, role: RoleBuilder) => string[];\n\nexport type QueryValue = string | number | boolean;\n\nexport type ExtractQueryValue<T> = T extends (infer U)[]\n ? U extends QueryValue ? U : never\n : T extends QueryValue | null ? NonNullable<T> : never;\n\nexport type QueryableKeys<T> = {\n [K in keyof T]: ExtractQueryValue<T[K]> extends never ? never : K;\n}[keyof T];\n\nexport type QueryBuilder<T> = {\n equal: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n notEqual: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n lessThan: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n lessThanEqual: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n greaterThan: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n greaterThanEqual: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n contains: <K extends QueryableKeys<T>>(field: K, value: ExtractQueryValue<T[K]>) => string;\n search: <K extends QueryableKeys<T>>(field: K, value: string) => string;\n isNull: <K extends QueryableKeys<T>>(field: K) => string;\n isNotNull: <K extends QueryableKeys<T>>(field: K) => string;\n startsWith: <K extends QueryableKeys<T>>(field: K, value: string) => string;\n endsWith: <K extends QueryableKeys<T>>(field: K, value: string) => string;\n between: <K extends QueryableKeys<T>>(field: K, start: ExtractQueryValue<T[K]>, end: ExtractQueryValue<T[K]>) => string;\n select: <K extends keyof T>(fields: K[]) => string;\n orderAsc: <K extends keyof T>(field: K) => string;\n orderDesc: <K extends keyof T>(field: K) => string;\n limit: (value: number) => string;\n offset: (value: number) => string;\n cursorAfter: (documentId: string) => string;\n cursorBefore: (documentId: string) => string;\n or: (...queries: string[]) => string;\n and: (...queries: string[]) => string;\n}\n\nexport type DatabaseId = {{{databaseIdType}}};\n\n{{{DATABASE_TABLES_TYPE}}}\n";
109183
109235
 
109184
109236
  // lib/commands/generators/typescript/templates/databases.ts.hbs
109185
- var databases_ts_default = 'import { Client, TablesDB, ID, Query, type Models, Permission, Role } from \'{{appwriteDep}}\';\nimport type { DatabaseHandle, DatabaseId, DatabaseTableMap, DatabaseTables, QueryBuilder, PermissionBuilder, RoleBuilder, RoleString } from \'./types{{importExt}}\';\n{{#if supportsServerSide}}\nimport { PROJECT_ID, ENDPOINT, API_KEY } from \'./constants{{importExt}}\';\n{{else}}\nimport { PROJECT_ID, ENDPOINT } from \'./constants{{importExt}}\';\n{{/if}}\n\nconst createQueryBuilder = <T>(): QueryBuilder<T> => ({\n equal: (field, value) => Query.equal(String(field), value as any),\n notEqual: (field, value) => Query.notEqual(String(field), value as any),\n lessThan: (field, value) => Query.lessThan(String(field), value as any),\n lessThanEqual: (field, value) => Query.lessThanEqual(String(field), value as any),\n greaterThan: (field, value) => Query.greaterThan(String(field), value as any),\n greaterThanEqual: (field, value) => Query.greaterThanEqual(String(field), value as any),\n contains: (field, value) => Query.contains(String(field), value as any),\n search: (field, value) => Query.search(String(field), value),\n isNull: (field) => Query.isNull(String(field)),\n isNotNull: (field) => Query.isNotNull(String(field)),\n startsWith: (field, value) => Query.startsWith(String(field), value),\n endsWith: (field, value) => Query.endsWith(String(field), value),\n between: (field, start, end) => Query.between(String(field), start as any, end as any),\n select: (fields) => Query.select(fields.map(String)),\n orderAsc: (field) => Query.orderAsc(String(field)),\n orderDesc: (field) => Query.orderDesc(String(field)),\n limit: (value) => Query.limit(value),\n offset: (value) => Query.offset(value),\n cursorAfter: (documentId) => Query.cursorAfter(documentId),\n cursorBefore: (documentId) => Query.cursorBefore(documentId),\n or: (...queries) => Query.or(queries),\n and: (...queries) => Query.and(queries),\n});\n\n{{{TABLE_ID_MAP}}}\n\n{{{TABLES_WITH_RELATIONSHIPS}}}\n\nconst roleBuilder: RoleBuilder = {\n any: () => Role.any() as RoleString,\n user: (userId, status?) => Role.user(userId, status) as RoleString,\n users: (status?) => Role.users(status) as RoleString,\n guests: () => Role.guests() as RoleString,\n team: (teamId, role?) => Role.team(teamId, role) as RoleString,\n member: (memberId) => Role.member(memberId) as RoleString,\n label: (label) => Role.label(label) as RoleString,\n};\n\nconst permissionBuilder: PermissionBuilder = {\n read: (role) => Permission.read(role),\n write: (role) => Permission.write(role),\n create: (role) => Permission.create(role),\n update: (role) => Permission.update(role),\n delete: (role) => Permission.delete(role),\n};\n\nconst resolvePermissions = (callback?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]): string[] | undefined =>\n callback?.(permissionBuilder, roleBuilder);\n\nfunction createTableApi<T extends Models.Row>(\n tablesDB: TablesDB,\n databaseId: string,\n tableId: string,\n) {\n return {\n create: (data: any, options?: { rowId?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.createRow<T>({\n databaseId,\n tableId,\n rowId: options?.rowId ?? ID.unique(),\n data,\n permissions: resolvePermissions(options?.permissions),\n transactionId: options?.transactionId,\n }),\n get: (id: string) =>\n tablesDB.getRow<T>({\n databaseId,\n tableId,\n rowId: id,\n }),\n update: (id: string, data: any, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.updateRow<T>({\n databaseId,\n tableId,\n rowId: id,\n data,\n ...(options?.permissions ? { permissions: resolvePermissions(options.permissions) } : {}),\n transactionId: options?.transactionId,\n }),\n delete: async (id: string, options?: { transactionId?: string }) => {\n await tablesDB.deleteRow({\n databaseId,\n tableId,\n rowId: id,\n transactionId: options?.transactionId,\n });\n },\n list: (options?: { queries?: (q: any) => string[] }) =>\n tablesDB.listRows<T>({\n databaseId,\n tableId,\n queries: options?.queries?.(createQueryBuilder<T>()),\n }),{{{BULK_METHODS}}}\n };\n}\n\n{{{BULK_CHECK}}}\nconst hasOwn = (obj: unknown, key: string): boolean =>\n obj != null && Object.prototype.hasOwnProperty.call(obj, key);\n\nfunction createDatabaseHandle<D extends DatabaseId>(\n tablesDB: TablesDB,\n databaseId: D,\n): DatabaseHandle<D> {\n const tableApiCache = new Map<string, unknown>();\n const dbMap = tableIdMap[databaseId];\n\n return {\n use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T): DatabaseTableMap[D][T] => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n\n if (!tableApiCache.has(tableId)) {\n const resolvedTableId = dbMap[tableId];\n const api = createTableApi(tablesDB, databaseId, resolvedTableId);\n {{{BULK_REMOVAL}}}\n tableApiCache.set(tableId, api);\n }\n return tableApiCache.get(tableId) as DatabaseTableMap[D][T];\n },\n{{#if supportsServerSide}}\n create: (tableId: string, name: string, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean; columns?: any[]; indexes?: any[] }) =>\n tablesDB.createTable({\n databaseId,\n tableId,\n name,\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n columns: options?.columns,\n indexes: options?.indexes,\n }),\n update: (tableId: string, options?: { name?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean }) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n return tablesDB.updateTable({\n databaseId,\n tableId: resolvedTableId,\n name: options?.name ?? tableId, // TODO: remove this fallback once fixed in other SDKs\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n });\n },\n delete: async (tableId: string) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n await tablesDB.deleteTable({\n databaseId,\n tableId: resolvedTableId,\n });\n },\n{{/if}}\n };\n}\n\nfunction createDatabasesApi(tablesDB: TablesDB): DatabaseTables {\n const dbCache = new Map<DatabaseId, ReturnType<typeof createDatabaseHandle>>();\n\n return {\n use: (databaseId: DatabaseId) => {\n if (!hasOwn(tableIdMap, databaseId)) {\n throw new Error(`Unknown database "${databaseId}"`);\n }\n\n if (!dbCache.has(databaseId)) {\n dbCache.set(databaseId, createDatabaseHandle(tablesDB, databaseId));\n }\n return dbCache.get(databaseId);\n },\n{{#if supportsServerSide}}\n create: (databaseId: string, name: string, options?: { enabled?: boolean }) =>\n tablesDB.create({\n databaseId,\n name,\n enabled: options?.enabled,\n }),\n update: (databaseId: DatabaseId, options?: { name?: string; enabled?: boolean }) => {\n return tablesDB.update({\n databaseId,\n name: options?.name ?? databaseId,\n enabled: options?.enabled,\n });\n },\n delete: async (databaseId: DatabaseId) => {\n await tablesDB.delete({\n databaseId,\n });\n },\n{{/if}}\n } as DatabaseTables;\n}\n\n// Initialize client\nconst client = new Client()\n .setEndpoint(ENDPOINT)\n .setProject(PROJECT_ID){{#if supportsServerSide}}\n .setKey(API_KEY){{/if}};\n\nconst tablesDB = new TablesDB(client);\n\nexport const databases: DatabaseTables = createDatabasesApi(tablesDB);\n';
109237
+ var databases_ts_default = 'import { Client, TablesDB, ID, Query, type Models, Permission, Role } from \'{{appwriteDep}}\';\nimport type { DatabaseHandle, DatabaseId, DatabaseTableMap, DatabaseTables, QueryBuilder, QueryValue, PermissionBuilder, RoleBuilder, RoleString } from \'./types{{importExt}}\';\n{{#if supportsServerSide}}\nimport { PROJECT_ID, ENDPOINT, API_KEY } from \'./constants{{importExt}}\';\n{{else}}\nimport { PROJECT_ID, ENDPOINT } from \'./constants{{importExt}}\';\n{{/if}}\n\nconst createQueryBuilder = <T>(): QueryBuilder<T> => ({\n equal: (field, value) => Query.equal(String(field), value as QueryValue),\n notEqual: (field, value) => Query.notEqual(String(field), value as QueryValue),\n lessThan: (field, value) => Query.lessThan(String(field), value as QueryValue),\n lessThanEqual: (field, value) => Query.lessThanEqual(String(field), value as QueryValue),\n greaterThan: (field, value) => Query.greaterThan(String(field), value as QueryValue),\n greaterThanEqual: (field, value) => Query.greaterThanEqual(String(field), value as QueryValue),\n contains: (field, value) => Query.contains(String(field), value as string | QueryValue[]),\n search: (field, value) => Query.search(String(field), value),\n isNull: (field) => Query.isNull(String(field)),\n isNotNull: (field) => Query.isNotNull(String(field)),\n startsWith: (field, value) => Query.startsWith(String(field), value),\n endsWith: (field, value) => Query.endsWith(String(field), value),\n between: (field, start, end) => Query.between(String(field), start as string | number, end as string | number),\n select: (fields) => Query.select(fields.map(String)),\n orderAsc: (field) => Query.orderAsc(String(field)),\n orderDesc: (field) => Query.orderDesc(String(field)),\n limit: (value) => Query.limit(value),\n offset: (value) => Query.offset(value),\n cursorAfter: (documentId) => Query.cursorAfter(documentId),\n cursorBefore: (documentId) => Query.cursorBefore(documentId),\n or: (...queries) => Query.or(queries),\n and: (...queries) => Query.and(queries),\n});\n\n{{{TABLE_ID_MAP}}}\n\n{{{TABLES_WITH_RELATIONSHIPS}}}\n\nconst roleBuilder: RoleBuilder = {\n any: () => Role.any() as RoleString,\n user: (userId, status?) => Role.user(userId, status) as RoleString,\n users: (status?) => Role.users(status) as RoleString,\n guests: () => Role.guests() as RoleString,\n team: (teamId, role?) => Role.team(teamId, role) as RoleString,\n member: (memberId) => Role.member(memberId) as RoleString,\n label: (label) => Role.label(label) as RoleString,\n};\n\nconst permissionBuilder: PermissionBuilder = {\n read: (role) => Permission.read(role),\n write: (role) => Permission.write(role),\n create: (role) => Permission.create(role),\n update: (role) => Permission.update(role),\n delete: (role) => Permission.delete(role),\n};\n\nconst resolvePermissions = (callback?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]): string[] | undefined =>\n callback?.(permissionBuilder, roleBuilder);\n\nfunction createTableApi<T extends Models.Row>(\n tablesDB: TablesDB,\n databaseId: string,\n tableId: string,\n) {\n return {\n create: (data: Omit<T, keyof Models.Row>, options?: { rowId?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.createRow<T>({\n databaseId,\n tableId,\n rowId: options?.rowId ?? ID.unique(),\n data: data as T extends Models.DefaultRow ? Partial<Models.Row> & Record<string, unknown> : Partial<Models.Row> & Omit<T, keyof Models.Row>,\n permissions: resolvePermissions(options?.permissions),\n transactionId: options?.transactionId,\n }),\n get: (id: string) =>\n tablesDB.getRow<T>({\n databaseId,\n tableId,\n rowId: id,\n }),\n update: (id: string, data: Partial<Omit<T, keyof Models.Row>>, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; transactionId?: string }) =>\n tablesDB.updateRow<T>({\n databaseId,\n tableId,\n rowId: id,\n data: data as T extends Models.DefaultRow ? Partial<Models.Row> & Record<string, unknown> : Partial<Models.Row> & Partial<Omit<T, keyof Models.Row>>,\n ...(options?.permissions ? { permissions: resolvePermissions(options.permissions) } : {}),\n transactionId: options?.transactionId,\n }),\n delete: async (id: string, options?: { transactionId?: string }) => {\n await tablesDB.deleteRow({\n databaseId,\n tableId,\n rowId: id,\n transactionId: options?.transactionId,\n });\n },\n list: (options?: { queries?: (q: QueryBuilder<T>) => string[] }) =>\n tablesDB.listRows<T>({\n databaseId,\n tableId,\n queries: options?.queries?.(createQueryBuilder<T>()),\n }),{{{BULK_METHODS}}}\n };\n}\n\n{{{BULK_CHECK}}}\nconst hasOwn = (obj: unknown, key: string): boolean =>\n obj != null && Object.prototype.hasOwnProperty.call(obj, key);\n\nfunction createDatabaseHandle<D extends DatabaseId>(\n tablesDB: TablesDB,\n databaseId: D,\n): DatabaseHandle<D> {\n const tableApiCache = new Map<string, unknown>();\n const dbMap = tableIdMap[databaseId];\n\n return {\n use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T): DatabaseTableMap[D][T] => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n\n if (!tableApiCache.has(tableId)) {\n const resolvedTableId = dbMap[tableId];\n const api = createTableApi(tablesDB, databaseId, resolvedTableId);\n {{{BULK_REMOVAL}}}\n tableApiCache.set(tableId, api);\n }\n return tableApiCache.get(tableId) as DatabaseTableMap[D][T];\n },\n{{#if supportsServerSide}}\n create: (tableId: string, name: string, options?: { permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean; columns?: object[]; indexes?: object[] }) =>\n tablesDB.createTable({\n databaseId,\n tableId,\n name,\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n columns: options?.columns,\n indexes: options?.indexes,\n }),\n update: (tableId: string, options?: { name?: string; permissions?: (permission: { read: (role: RoleString) => string; write: (role: RoleString) => string; create: (role: RoleString) => string; update: (role: RoleString) => string; delete: (role: RoleString) => string }, role: { any: () => RoleString; user: (userId: string, status?: string) => RoleString; users: (status?: string) => RoleString; guests: () => RoleString; team: (teamId: string, role?: string) => RoleString; member: (memberId: string) => RoleString; label: (label: string) => RoleString }) => string[]; rowSecurity?: boolean; enabled?: boolean }) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n return tablesDB.updateTable({\n databaseId,\n tableId: resolvedTableId,\n name: options?.name,\n permissions: resolvePermissions(options?.permissions),\n rowSecurity: options?.rowSecurity,\n enabled: options?.enabled,\n });\n },\n delete: async (tableId: string) => {\n if (!hasOwn(dbMap, tableId)) {\n throw new Error(`Unknown table "${tableId}" in database "${databaseId}"`);\n }\n const resolvedTableId = dbMap[tableId];\n await tablesDB.deleteTable({\n databaseId,\n tableId: resolvedTableId,\n });\n },\n{{/if}}\n };\n}\n\nfunction createDatabasesApi(tablesDB: TablesDB): DatabaseTables {\n const dbCache = new Map<DatabaseId, ReturnType<typeof createDatabaseHandle>>();\n\n return {\n use: (databaseId: DatabaseId) => {\n if (!hasOwn(tableIdMap, databaseId)) {\n throw new Error(`Unknown database "${databaseId}"`);\n }\n\n if (!dbCache.has(databaseId)) {\n dbCache.set(databaseId, createDatabaseHandle(tablesDB, databaseId));\n }\n return dbCache.get(databaseId);\n },\n{{#if supportsServerSide}}\n create: (databaseId: string, name: string, options?: { enabled?: boolean }) =>\n tablesDB.create({\n databaseId,\n name,\n enabled: options?.enabled,\n }),\n update: (databaseId: DatabaseId, options?: { name?: string; enabled?: boolean }) => {\n return tablesDB.update({\n databaseId,\n name: options?.name ?? databaseId,\n enabled: options?.enabled,\n });\n },\n delete: async (databaseId: DatabaseId) => {\n await tablesDB.delete({\n databaseId,\n });\n },\n{{/if}}\n } as DatabaseTables;\n}\n\n// Initialize client\nconst client = new Client()\n .setEndpoint(ENDPOINT)\n .setProject(PROJECT_ID){{#if supportsServerSide}}\n .setKey(API_KEY){{/if}};\n\nconst tablesDB = new TablesDB(client);\n\nexport const databases: DatabaseTables = createDatabasesApi(tablesDB);\n';
109186
109238
 
109187
109239
  // lib/commands/generators/typescript/templates/index.ts.hbs
109188
109240
  var index_ts_default = '/**\n * {{sdkTitle}} Generated SDK\n *\n * This file is auto-generated. Do not edit manually.\n * Re-run `{{executableName}} generate` to regenerate.\n */\n\nexport { databases } from "./databases{{importExt}}";\nexport * from "./types{{importExt}}";\n';
@@ -109349,7 +109401,7 @@ ${dbReturnTypes}
109349
109401
 
109350
109402
  export type DatabaseHandle<D extends DatabaseId> = {
109351
109403
  use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => DatabaseTableMap[D][T];
109352
- ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: any[]; indexes?: any[] }) => Promise<Models.Table>;
109404
+ ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: object[]; indexes?: object[] }) => Promise<Models.Table>;
109353
109405
  update: <T extends keyof DatabaseTableMap[D] & string>(tableId: T, options?: { name?: string; permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean }) => Promise<Models.Table>;
109354
109406
  delete: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => Promise<void>;` : ""}
109355
109407
  };
@@ -109416,26 +109468,26 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109416
109468
  generateBulkMethods(supportsBulk) {
109417
109469
  if (!supportsBulk) return "";
109418
109470
  return `
109419
- createMany: (rows: any[], options?: { transactionId?: string }) =>
109471
+ createMany: (rows: object[], options?: { transactionId?: string }) =>
109420
109472
  tablesDB.createRows({
109421
109473
  databaseId,
109422
109474
  tableId,
109423
109475
  rows,
109424
109476
  transactionId: options?.transactionId,
109425
109477
  }),
109426
- updateMany: (data: any, options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
109478
+ updateMany: (data: object, options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
109427
109479
  tablesDB.updateRows({
109428
109480
  databaseId,
109429
109481
  tableId,
109430
109482
  data,
109431
- queries: options?.queries?.(createQueryBuilder()),
109483
+ queries: options?.queries?.(createQueryBuilder<T>()),
109432
109484
  transactionId: options?.transactionId,
109433
109485
  }),
109434
- deleteMany: (options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
109486
+ deleteMany: (options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
109435
109487
  tablesDB.deleteRows({
109436
109488
  databaseId,
109437
109489
  tableId,
109438
- queries: options?.queries?.(createQueryBuilder()),
109490
+ queries: options?.queries?.(createQueryBuilder<T>()),
109439
109491
  transactionId: options?.transactionId,
109440
109492
  }),`;
109441
109493
  }
@@ -109449,9 +109501,9 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109449
109501
  return `
109450
109502
  // Remove bulk methods for tables with relationships
109451
109503
  if (!hasBulkMethods(databaseId, tableId)) {
109452
- delete (api as any).createMany;
109453
- delete (api as any).updateMany;
109454
- delete (api as any).deleteMany;
109504
+ delete (api as Record<string, unknown>).createMany;
109505
+ delete (api as Record<string, unknown>).updateMany;
109506
+ delete (api as Record<string, unknown>).deleteMany;
109455
109507
  }`;
109456
109508
  }
109457
109509
  generateDatabasesFile(config2, importExt) {