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.js CHANGED
@@ -1939,9 +1939,9 @@ var require_source = __commonJS({
1939
1939
  }
1940
1940
  });
1941
1941
 
1942
- // node_modules/escape-string-regexp/index.js
1942
+ // node_modules/figures/node_modules/escape-string-regexp/index.js
1943
1943
  var require_escape_string_regexp = __commonJS({
1944
- "node_modules/escape-string-regexp/index.js"(exports, module) {
1944
+ "node_modules/figures/node_modules/escape-string-regexp/index.js"(exports, module) {
1945
1945
  "use strict";
1946
1946
  var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
1947
1947
  module.exports = function(str) {
@@ -19586,9 +19586,9 @@ var require_stream_duplex = __commonJS({
19586
19586
  }
19587
19587
  });
19588
19588
 
19589
- // node_modules/string_decoder/node_modules/safe-buffer/index.js
19589
+ // node_modules/safe-buffer/index.js
19590
19590
  var require_safe_buffer = __commonJS({
19591
- "node_modules/string_decoder/node_modules/safe-buffer/index.js"(exports, module) {
19591
+ "node_modules/safe-buffer/index.js"(exports, module) {
19592
19592
  var buffer = __require("buffer");
19593
19593
  var Buffer2 = buffer.Buffer;
19594
19594
  function copyProps(src, dst) {
@@ -69357,7 +69357,7 @@ var id_default = ID;
69357
69357
  // lib/constants.ts
69358
69358
  var SDK_TITLE = "Appwrite";
69359
69359
  var SDK_TITLE_LOWER = "appwrite";
69360
- var SDK_VERSION = "13.6.0";
69360
+ var SDK_VERSION = "13.6.1";
69361
69361
  var SDK_LOGO = "\n _ _ _ ___ __ _____\n /_\\ _ __ _ ____ ___ __(_) |_ ___ / __\\ / / \\_ \\\n //_\\\\| '_ \\| '_ \\ \\ /\\ / / '__| | __/ _ \\ / / / / / /\\/\n / _ \\ |_) | |_) \\ V V /| | | | || __/ / /___/ /___/\\/ /_\n \\_/ \\_/ .__/| .__/ \\_/\\_/ |_| |_|\\__\\___| \\____/\\____/\\____/\n |_| |_|\n\n";
69362
69362
  var EXECUTABLE_NAME = "appwrite";
69363
69363
  var NPM_PACKAGE_NAME = "appwrite-cli";
@@ -83265,7 +83265,7 @@ var int64Schema = external_exports.preprocess(
83265
83265
  const valueOfResult = val.valueOf();
83266
83266
  const bigIntVal = BigInt(valueOfResult);
83267
83267
  return bigIntVal;
83268
- } catch (e) {
83268
+ } catch (_e) {
83269
83269
  return void 0;
83270
83270
  }
83271
83271
  }
@@ -83275,7 +83275,7 @@ var int64Schema = external_exports.preprocess(
83275
83275
  if (typeof val === "string") {
83276
83276
  try {
83277
83277
  return BigInt(val);
83278
- } catch (e) {
83278
+ } catch (_e) {
83279
83279
  return void 0;
83280
83280
  }
83281
83281
  }
@@ -83589,7 +83589,7 @@ var createSettingsObject = (project) => {
83589
83589
  };
83590
83590
  };
83591
83591
  var checkDeployConditions = (localConfig2) => {
83592
- if (Object.keys(localConfig2.data).length === 0) {
83592
+ if (localConfig2.keys().length === 0) {
83593
83593
  throw new Error(
83594
83594
  "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."
83595
83595
  );
@@ -83737,7 +83737,7 @@ var Config = class {
83737
83737
  try {
83738
83738
  const file2 = fs.readFileSync(this.path).toString();
83739
83739
  this.data = JSONBig.parse(file2);
83740
- } catch (e) {
83740
+ } catch (_e) {
83741
83741
  this.data = {};
83742
83742
  }
83743
83743
  }
@@ -84648,7 +84648,7 @@ var Spinner = class _Spinner {
84648
84648
  static stop() {
84649
84649
  _Spinner.updatesBar.stop();
84650
84650
  }
84651
- static formatter(options, params, payload) {
84651
+ static formatter(_options, _params, payload) {
84652
84652
  const status = payload.status.padEnd(12);
84653
84653
  const middle = `${payload.resource} (${payload.id})`.padEnd(40);
84654
84654
  let prefix = import_chalk.default.cyan(payload.prefix ?? "\u29D7");
@@ -84719,19 +84719,22 @@ async function paginate(action, args = {}, limit = 100, wrapper = "", queries =
84719
84719
  ]
84720
84720
  });
84721
84721
  if (wrapper === "") {
84722
- if (response.length === 0) {
84722
+ const listResponse = response;
84723
+ if (listResponse.length === 0) {
84723
84724
  break;
84724
84725
  }
84725
- results = results.concat(response);
84726
+ results = results.concat(listResponse);
84726
84727
  } else {
84727
- if (response[wrapper].length === 0) {
84728
+ const wrappedResponse = response;
84729
+ const wrappedResults = wrappedResponse[wrapper] ?? [];
84730
+ if (wrappedResults.length === 0) {
84731
+ break;
84732
+ }
84733
+ results = results.concat(wrappedResults);
84734
+ total = wrappedResponse.total;
84735
+ if (results.length >= total) {
84728
84736
  break;
84729
84737
  }
84730
- results = results.concat(response[wrapper]);
84731
- }
84732
- total = response.total;
84733
- if (results.length >= total) {
84734
- break;
84735
84738
  }
84736
84739
  pageNumber++;
84737
84740
  }
@@ -103976,7 +103979,7 @@ var package_default = {
103976
103979
  type: "module",
103977
103980
  homepage: "https://appwrite.io/support",
103978
103981
  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",
103979
- version: "13.6.0",
103982
+ version: "13.6.1",
103980
103983
  license: "BSD-3-Clause",
103981
103984
  main: "dist/index.cjs",
103982
103985
  module: "dist/index.js",
@@ -104007,6 +104010,7 @@ var package_default = {
104007
104010
  "build:lib:esm": "esbuild index.ts --bundle --platform=node --target=node18 --format=esm --loader:.hbs=text --outfile=dist/index.js",
104008
104011
  "build:lib:cjs": "esbuild index.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --outfile=dist/index.cjs",
104009
104012
  "build:cli": "esbuild cli.ts --bundle --platform=node --target=node18 --format=cjs --loader:.hbs=text --external:fsevents --outfile=dist/cli.cjs",
104013
+ lint: "eslint .",
104010
104014
  format: 'prettier --write "**/*.{js,ts,json,md}"',
104011
104015
  generate: "tsx scripts/generate-commands.ts",
104012
104016
  prepublishOnly: "npm run build",
@@ -104038,7 +104042,12 @@ var package_default = {
104038
104042
  zod: "^4.3.5"
104039
104043
  },
104040
104044
  devDependencies: {
104045
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
104046
+ "@typescript-eslint/parser": "^8.0.0",
104041
104047
  "@types/bun": "^1.3.5",
104048
+ eslint: "^9.0.0",
104049
+ "eslint-plugin-unused-imports": "^4.0.0",
104050
+ "typescript-eslint": "^8.0.0",
104042
104051
  "@types/cli-progress": "^3.11.5",
104043
104052
  "@types/inquirer": "^8.2.10",
104044
104053
  "@types/json-bigint": "^1.0.4",
@@ -104070,14 +104079,28 @@ var cliConfig = {
104070
104079
  report: false,
104071
104080
  reportData: {}
104072
104081
  };
104082
+ var toJsonObject = (value) => {
104083
+ if (value && typeof value === "object" && !Array.isArray(value)) {
104084
+ return value;
104085
+ }
104086
+ return null;
104087
+ };
104088
+ var extractReportCommandArgs = (value) => {
104089
+ if (!value || typeof value !== "object") {
104090
+ return [];
104091
+ }
104092
+ const reportData = value;
104093
+ if (!Array.isArray(reportData.data?.args)) {
104094
+ return [];
104095
+ }
104096
+ return reportData.data.args;
104097
+ };
104073
104098
  var drawTable = (data) => {
104074
104099
  if (data.length == 0) {
104075
104100
  console.log("[]");
104076
104101
  return;
104077
104102
  }
104078
- const rows = data.map(
104079
- (item) => item && typeof item === "object" && !Array.isArray(item) ? item : {}
104080
- );
104103
+ const rows = data.map((item) => toJsonObject(item) ?? {});
104081
104104
  const obj = rows.reduce((res, item) => ({ ...res, ...item }), {});
104082
104105
  const keys = Object.keys(obj);
104083
104106
  if (keys.length === 0) {
@@ -104120,7 +104143,7 @@ var drawTable = (data) => {
104120
104143
  } else if (typeof row[key] === "object") {
104121
104144
  rowValues.push(JSON.stringify(row[key]));
104122
104145
  } else {
104123
- rowValues.push(row[key]);
104146
+ rowValues.push(String(row[key]));
104124
104147
  }
104125
104148
  }
104126
104149
  table.push(rowValues);
@@ -104132,7 +104155,7 @@ var drawJSON = (data) => {
104132
104155
  };
104133
104156
  var parseError = (err) => {
104134
104157
  if (cliConfig.report) {
104135
- (async () => {
104158
+ void (async () => {
104136
104159
  let appwriteVersion = "unknown";
104137
104160
  const endpoint = globalConfig2.getEndpoint();
104138
104161
  try {
@@ -104145,7 +104168,8 @@ var parseError = (err) => {
104145
104168
  } catch {
104146
104169
  }
104147
104170
  const version2 = SDK_VERSION;
104148
- const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${cliConfig.reportData.data.args.join(" ")}\``;
104171
+ const commandArgs = extractReportCommandArgs(cliConfig.reportData);
104172
+ const stepsToReproduce = `Running \`${EXECUTABLE_NAME} ${commandArgs.join(" ")}\``;
104149
104173
  const yourEnvironment = `CLI version: ${version2}
104150
104174
  Operation System: ${os2.type()}
104151
104175
  Appwrite version: ${appwriteVersion}
@@ -104197,7 +104221,7 @@ var actionRunner = (fn) => {
104197
104221
  error48(`The '--all' and '--id' flags cannot be used together.`);
104198
104222
  process.exit(1);
104199
104223
  }
104200
- return fn(...args).catch(parseError);
104224
+ return fn(...args).then(() => void 0).catch(parseError);
104201
104225
  };
104202
104226
  };
104203
104227
  var log = (message) => {
@@ -104310,6 +104334,9 @@ async function downloadDeploymentCode(params) {
104310
104334
  {},
104311
104335
  "arrayBuffer"
104312
104336
  );
104337
+ if (!(downloadBuffer instanceof ArrayBuffer)) {
104338
+ throw new Error("Failed to download deployment archive as ArrayBuffer.");
104339
+ }
104313
104340
  try {
104314
104341
  fs2.writeFileSync(compressedFileName, Buffer.from(downloadBuffer));
104315
104342
  } catch (err) {
@@ -104521,7 +104548,7 @@ var questionsInitProject = [
104521
104548
  name: "organization",
104522
104549
  message: "Choose your organization",
104523
104550
  choices: async () => {
104524
- let client = await sdkForConsole(true);
104551
+ const client = await sdkForConsole(true);
104525
104552
  const { teams } = isCloud() ? await paginate(
104526
104553
  async (opts = {}) => (await getOrganizationsService(opts.sdk)).list(),
104527
104554
  { sdk: client },
@@ -104533,7 +104560,7 @@ var questionsInitProject = [
104533
104560
  100,
104534
104561
  "teams"
104535
104562
  );
104536
- let choices = teams.map((team, idx) => {
104563
+ const choices = teams.map((team, _idx) => {
104537
104564
  return {
104538
104565
  name: `${team.name} (${team["$id"]})`,
104539
104566
  value: team["$id"]
@@ -104582,7 +104609,7 @@ var questionsInitProject = [
104582
104609
  "projects",
104583
104610
  queries
104584
104611
  );
104585
- let choices = projects.map((project) => {
104612
+ const choices = projects.map((project) => {
104586
104613
  return {
104587
104614
  name: `${project.name} (${project["$id"]})`,
104588
104615
  value: {
@@ -104603,13 +104630,13 @@ var questionsInitProject = [
104603
104630
  name: "region",
104604
104631
  message: `Select your ${SDK_TITLE} Cloud region`,
104605
104632
  choices: async () => {
104606
- let client = await sdkForConsole(true);
104633
+ const client = await sdkForConsole(true);
104607
104634
  const endpoint = globalConfig2.getEndpoint() || DEFAULT_ENDPOINT;
104608
- let response = await client.call(
104635
+ const response = await client.call(
104609
104636
  "GET",
104610
104637
  new URL(endpoint + "/console/regions")
104611
104638
  );
104612
- let regions = response.regions || [];
104639
+ const regions = response.regions || [];
104613
104640
  if (!regions.length) {
104614
104641
  throw new Error(
104615
104642
  "No regions found. Please check your network or Appwrite Cloud availability."
@@ -104736,9 +104763,9 @@ var questionGetEndpoint = [
104736
104763
  if (!value) {
104737
104764
  return "Please enter a valid endpoint.";
104738
104765
  }
104739
- let client = new Client().setEndpoint(value);
104766
+ const client = new Client().setEndpoint(value);
104740
104767
  try {
104741
- let response = await client.call(
104768
+ const response = await client.call(
104742
104769
  "get",
104743
104770
  new URL(value + "/health/version")
104744
104771
  );
@@ -104747,7 +104774,7 @@ var questionGetEndpoint = [
104747
104774
  } else {
104748
104775
  throw new Error();
104749
104776
  }
104750
- } catch (error49) {
104777
+ } catch (_error) {
104751
104778
  return "Invalid endpoint or your Appwrite server is not running as expected.";
104752
104779
  }
104753
104780
  }
@@ -104783,9 +104810,9 @@ var questionsPushSites = [
104783
104810
  validate: (value) => validateRequired("site", value),
104784
104811
  when: () => localConfig.getSites().length > 0,
104785
104812
  choices: () => {
104786
- let sites = localConfig.getSites();
104813
+ const sites = localConfig.getSites();
104787
104814
  checkDeployConditions(localConfig);
104788
- let choices = sites.map((site, idx) => {
104815
+ const choices = sites.map((site, _idx) => {
104789
104816
  return {
104790
104817
  name: `${site.name} (${site.$id})`,
104791
104818
  value: site.$id
@@ -104803,9 +104830,9 @@ var questionsPushFunctions = [
104803
104830
  validate: (value) => validateRequired("function", value),
104804
104831
  when: () => localConfig.getFunctions().length > 0,
104805
104832
  choices: () => {
104806
- let functions = localConfig.getFunctions();
104833
+ const functions = localConfig.getFunctions();
104807
104834
  checkDeployConditions(localConfig);
104808
- let choices = functions.map((func, idx) => {
104835
+ const choices = functions.map((func, _idx) => {
104809
104836
  return {
104810
104837
  name: `${func.name} (${func.$id})`,
104811
104838
  value: func.$id
@@ -104823,7 +104850,7 @@ var questionsPushCollections = [
104823
104850
  validate: (value) => validateRequired("collection", value),
104824
104851
  when: () => localConfig.getCollections().length > 0,
104825
104852
  choices: () => {
104826
- let collections = localConfig.getCollections();
104853
+ const collections = localConfig.getCollections();
104827
104854
  checkDeployConditions(localConfig);
104828
104855
  return collections.map((collection) => {
104829
104856
  return {
@@ -104842,7 +104869,7 @@ var questionsPushTables = [
104842
104869
  validate: (value) => validateRequired("table", value),
104843
104870
  when: () => localConfig.getTables().length > 0,
104844
104871
  choices: () => {
104845
- let tables = localConfig.getTables();
104872
+ const tables = localConfig.getTables();
104846
104873
  checkDeployConditions(localConfig);
104847
104874
  return tables.map((table) => {
104848
104875
  return {
@@ -104875,7 +104902,7 @@ var questionsPushBuckets = [
104875
104902
  validate: (value) => validateRequired("bucket", value),
104876
104903
  when: () => localConfig.getBuckets().length > 0,
104877
104904
  choices: () => {
104878
- let buckets = localConfig.getBuckets();
104905
+ const buckets = localConfig.getBuckets();
104879
104906
  checkDeployConditions(localConfig);
104880
104907
  return buckets.map((bucket) => {
104881
104908
  return {
@@ -104894,7 +104921,7 @@ var questionsPushMessagingTopics = [
104894
104921
  validate: (value) => validateRequired("topics", value),
104895
104922
  when: () => localConfig.getMessagingTopics().length > 0,
104896
104923
  choices: () => {
104897
- let topics = localConfig.getMessagingTopics();
104924
+ const topics = localConfig.getMessagingTopics();
104898
104925
  return topics.map((topic) => {
104899
104926
  return {
104900
104927
  name: `${topic.name} (${topic["$id"]})`,
@@ -104925,7 +104952,7 @@ var questionsPushTeams = [
104925
104952
  validate: (value) => validateRequired("team", value),
104926
104953
  when: () => localConfig.getTeams().length > 0,
104927
104954
  choices: () => {
104928
- let teams = localConfig.getTeams();
104955
+ const teams = localConfig.getTeams();
104929
104956
  checkDeployConditions(localConfig);
104930
104957
  return teams.map((team) => {
104931
104958
  return {
@@ -104967,7 +104994,7 @@ var Pools = class {
104967
104994
  return true;
104968
104995
  }
104969
104996
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
104970
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
104997
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
104971
104998
  if (steps > 1 && iteration === 1) {
104972
104999
  this.pollMaxDebounces *= steps;
104973
105000
  log(
@@ -104993,7 +105020,7 @@ var Pools = class {
104993
105020
  return true;
104994
105021
  }
104995
105022
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
104996
- let steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
105023
+ const steps = Math.max(1, Math.ceil(Number(total) / this.STEP_SIZE));
104997
105024
  if (steps > 1 && iteration === 1) {
104998
105025
  this.pollMaxDebounces *= steps;
104999
105026
  log(
@@ -105009,7 +105036,10 @@ var Pools = class {
105009
105036
  return false;
105010
105037
  }
105011
105038
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105012
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
105039
+ const steps = Math.max(
105040
+ 1,
105041
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
105042
+ );
105013
105043
  if (steps > 1 && iteration === 1) {
105014
105044
  this.pollMaxDebounces *= steps;
105015
105045
  log(
@@ -105052,7 +105082,10 @@ var Pools = class {
105052
105082
  return false;
105053
105083
  }
105054
105084
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105055
- let steps = Math.max(1, Math.ceil(attributeKeys.length / this.STEP_SIZE));
105085
+ const steps = Math.max(
105086
+ 1,
105087
+ Math.ceil(attributeKeys.length / this.STEP_SIZE)
105088
+ );
105056
105089
  if (steps > 1 && iteration === 1) {
105057
105090
  this.pollMaxDebounces *= steps;
105058
105091
  log(
@@ -105101,7 +105134,7 @@ var Pools = class {
105101
105134
  return false;
105102
105135
  }
105103
105136
  if (this.pollMaxDebounces === this.POLL_DEFAULT_VALUE) {
105104
- let steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
105137
+ const steps = Math.max(1, Math.ceil(indexKeys.length / this.STEP_SIZE));
105105
105138
  if (steps > 1 && iteration === 1) {
105106
105139
  this.pollMaxDebounces *= steps;
105107
105140
  log(
@@ -105194,7 +105227,7 @@ var Attributes = class {
105194
105227
  }
105195
105228
  return answers2.changes;
105196
105229
  }
105197
- let answers = await import_inquirer.default.prompt(questionPushChanges2);
105230
+ const answers = await import_inquirer.default.prompt(questionPushChanges2);
105198
105231
  if (answers.changes !== "YES" && answers.changes !== "NO") {
105199
105232
  answers.changes = await fixConfirmation();
105200
105233
  }
@@ -105237,8 +105270,8 @@ var Attributes = class {
105237
105270
  const keyName = `${import_chalk4.default.yellow(local.key)} in ${collection.name} (${collection["$id"]})`;
105238
105271
  const action = import_chalk4.default.cyan(recreating ? "recreating" : "changing");
105239
105272
  let reason = "";
105240
- let attribute = recreating ? remote : local;
105241
- for (let key of Object.keys(remote)) {
105273
+ const attribute = recreating ? remote : local;
105274
+ for (const key of Object.keys(remote)) {
105242
105275
  if (!KeysAttributes.has(key)) {
105243
105276
  continue;
105244
105277
  }
@@ -105748,7 +105781,7 @@ var Attributes = class {
105748
105781
  createIndexes = async (indexes, collection) => {
105749
105782
  log(`Creating indexes ...`);
105750
105783
  const databasesService = await getDatabasesService(this.client);
105751
- for (let index of indexes) {
105784
+ for (const index of indexes) {
105752
105785
  await databasesService.createIndex({
105753
105786
  databaseId: collection["databaseId"],
105754
105787
  collectionId: collection["$id"],
@@ -105772,7 +105805,7 @@ var Attributes = class {
105772
105805
  };
105773
105806
  createAttributes = async (attributes, collection) => {
105774
105807
  log(`Creating attributes ...`);
105775
- for (let attribute of attributes) {
105808
+ for (const attribute of attributes) {
105776
105809
  if (attribute.side !== "child") {
105777
105810
  await this.createAttribute(
105778
105811
  collection["databaseId"],
@@ -105796,7 +105829,7 @@ var Attributes = class {
105796
105829
  };
105797
105830
  createColumns = async (columns, table) => {
105798
105831
  log(`Creating columns ...`);
105799
- for (let column of columns) {
105832
+ for (const column of columns) {
105800
105833
  if (column.side !== "child") {
105801
105834
  await this.createAttribute(table["databaseId"], table["$id"], column);
105802
105835
  }
@@ -105831,7 +105864,7 @@ var getConfirmation = async () => {
105831
105864
  }
105832
105865
  return answers2.changes;
105833
105866
  }
105834
- let answers = await import_inquirer2.default.prompt(questionPushChanges);
105867
+ const answers = await import_inquirer2.default.prompt(questionPushChanges);
105835
105868
  if (answers.changes !== "YES" && answers.changes !== "NO") {
105836
105869
  answers.changes = await fixConfirmation();
105837
105870
  }
@@ -105881,7 +105914,7 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105881
105914
  options[secondResourceName] = localResource[secondId];
105882
105915
  }
105883
105916
  const remoteResource = await resourceGetFunction(options);
105884
- for (let [key, value] of Object.entries(
105917
+ for (const [key, value] of Object.entries(
105885
105918
  whitelistKeys(remoteResource, keys)
105886
105919
  )) {
105887
105920
  if (skipKeys.includes(key)) {
@@ -105890,28 +105923,30 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105890
105923
  if (isEmpty(value) && isEmpty(localResource[key])) {
105891
105924
  continue;
105892
105925
  }
105893
- if (Array.isArray(value) && Array.isArray(localResource[key])) {
105894
- if (JSON.stringify(value) !== JSON.stringify(localResource[key])) {
105926
+ const localValue = localResource[key];
105927
+ if (Array.isArray(value) && Array.isArray(localValue)) {
105928
+ if (JSON.stringify(value) !== JSON.stringify(localValue)) {
105895
105929
  changes.push({
105896
105930
  id: localResource["$id"],
105897
105931
  key,
105898
105932
  remote: import_chalk5.default.red(value.join("\n")),
105899
- local: import_chalk5.default.green(localResource[key].join("\n"))
105933
+ local: import_chalk5.default.green(
105934
+ localValue.map((entry) => String(entry)).join("\n")
105935
+ )
105900
105936
  });
105901
105937
  }
105902
- } else if (value !== localResource[key]) {
105938
+ } else if (value !== localValue) {
105903
105939
  changes.push({
105904
105940
  id: localResource["$id"],
105905
105941
  key,
105906
- remote: import_chalk5.default.red(value),
105907
- local: import_chalk5.default.green(localResource[key])
105942
+ remote: import_chalk5.default.red(String(value ?? "")),
105943
+ local: import_chalk5.default.green(String(localValue ?? ""))
105908
105944
  });
105909
105945
  }
105910
105946
  }
105911
105947
  } catch (e) {
105912
- if (Number(e.code) !== 404) {
105913
- throw e;
105914
- }
105948
+ const isNotFound = e instanceof AppwriteException && Number(e.code) === 404;
105949
+ if (!isNotFound) throw e;
105915
105950
  }
105916
105951
  })
105917
105952
  );
@@ -105928,18 +105963,37 @@ var approveChanges = async (resource, resourceGetFunction, keys, resourceName, r
105928
105963
 
105929
105964
  // lib/commands/utils/database-sync.ts
105930
105965
  var import_chalk6 = __toESM(require_source(), 1);
105966
+ var isTablesDBResource = (value) => {
105967
+ if (!value || typeof value !== "object") {
105968
+ return false;
105969
+ }
105970
+ return "$id" in value && typeof value.$id === "string" && "name" in value && typeof value.name === "string" && "enabled" in value && typeof value.enabled === "boolean";
105971
+ };
105972
+ var getSyncErrorMessage = (err) => {
105973
+ if (err instanceof AppwriteException) {
105974
+ return err.message;
105975
+ }
105976
+ if (err instanceof Error) {
105977
+ return err.message;
105978
+ }
105979
+ return String(err);
105980
+ };
105931
105981
  var checkAndApplyTablesDBChanges = async () => {
105932
105982
  log("Checking for tablesDB changes ...");
105933
105983
  const localTablesDBs = localConfig.getTablesDBs();
105934
- const { databases: remoteTablesDBs } = await paginate(
105984
+ const paginatedResult = await paginate(
105935
105985
  async (args) => {
105936
105986
  const tablesDBService = await getTablesDBService();
105937
- return await tablesDBService.list(args.queries || []);
105987
+ const queries = Array.isArray(args.queries) ? args.queries.filter(
105988
+ (query) => typeof query === "string"
105989
+ ) : [];
105990
+ return await tablesDBService.list(queries);
105938
105991
  },
105939
105992
  {},
105940
105993
  100,
105941
105994
  "databases"
105942
105995
  );
105996
+ const remoteTablesDBs = Array.isArray(paginatedResult.databases) ? paginatedResult.databases.filter(isTablesDBResource) : [];
105943
105997
  if (localTablesDBs.length === 0 && remoteTablesDBs.length === 0) {
105944
105998
  return { applied: false, resyncNeeded: false };
105945
105999
  }
@@ -105961,9 +106015,7 @@ var checkAndApplyTablesDBChanges = async () => {
105961
106015
  }
105962
106016
  }
105963
106017
  for (const localDB of localTablesDBs) {
105964
- const remoteDB = remoteTablesDBs.find(
105965
- (db) => db.$id === localDB.$id
105966
- );
106018
+ const remoteDB = remoteTablesDBs.find((db) => db.$id === localDB.$id);
105967
106019
  if (!remoteDB) {
105968
106020
  toCreate.push(localDB);
105969
106021
  changes.push({
@@ -106030,7 +106082,7 @@ var checkAndApplyTablesDBChanges = async () => {
106030
106082
  needsResync = true;
106031
106083
  } catch (e) {
106032
106084
  error48(
106033
- `Failed to delete database ${db.name} ( ${db.$id} ): ${e.message}`
106085
+ `Failed to delete database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106034
106086
  );
106035
106087
  throw new Error(
106036
106088
  `Database sync failed during deletion of ${db.$id}. Some changes may have been applied.`
@@ -106045,7 +106097,7 @@ var checkAndApplyTablesDBChanges = async () => {
106045
106097
  success2(`Created ${db.name} ( ${db.$id} )`);
106046
106098
  } catch (e) {
106047
106099
  error48(
106048
- `Failed to create database ${db.name} ( ${db.$id} ): ${e.message}`
106100
+ `Failed to create database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106049
106101
  );
106050
106102
  throw new Error(
106051
106103
  `Database sync failed during creation of ${db.$id}. Some changes may have been applied.`
@@ -106060,7 +106112,7 @@ var checkAndApplyTablesDBChanges = async () => {
106060
106112
  success2(`Updated ${db.name} ( ${db.$id} )`);
106061
106113
  } catch (e) {
106062
106114
  error48(
106063
- `Failed to update database ${db.name} ( ${db.$id} ): ${e.message}`
106115
+ `Failed to update database ${db.name} ( ${db.$id} ): ${getSyncErrorMessage(e)}`
106064
106116
  );
106065
106117
  throw new Error(
106066
106118
  `Database sync failed during update of ${db.$id}. Some changes may have been applied.`
@@ -106294,7 +106346,7 @@ var Push = class {
106294
106346
  }
106295
106347
  if (settings.services) {
106296
106348
  this.log("Applying service statuses ...");
106297
- for (let [service, status] of Object.entries(settings.services)) {
106349
+ for (const [service, status] of Object.entries(settings.services)) {
106298
106350
  await projectsService.updateServiceStatus({
106299
106351
  projectId,
106300
106352
  service,
@@ -106340,7 +106392,7 @@ var Push = class {
106340
106392
  }
106341
106393
  if (settings.auth.methods) {
106342
106394
  this.log("Applying auth methods statuses ...");
106343
- for (let [method, status] of Object.entries(settings.auth.methods)) {
106395
+ for (const [method, status] of Object.entries(settings.auth.methods)) {
106344
106396
  await projectsService.updateAuthStatus({
106345
106397
  projectId,
106346
106398
  method,
@@ -106644,7 +106696,7 @@ var Push = class {
106644
106696
  ([key, value]) => ({ key, value })
106645
106697
  );
106646
106698
  }
106647
- } catch (error49) {
106699
+ } catch (_error) {
106648
106700
  envVariables = [];
106649
106701
  }
106650
106702
  await Promise.all(
@@ -106941,7 +106993,7 @@ var Push = class {
106941
106993
  ([key, value]) => ({ key, value })
106942
106994
  );
106943
106995
  }
106944
- } catch (error49) {
106996
+ } catch (_error) {
106945
106997
  envVariables = [];
106946
106998
  }
106947
106999
  await Promise.all(
@@ -107108,7 +107160,7 @@ var Push = class {
107108
107160
  skipConfirmation,
107109
107161
  this.projectClient
107110
107162
  );
107111
- let tablesChanged = /* @__PURE__ */ new Set();
107163
+ const tablesChanged = /* @__PURE__ */ new Set();
107112
107164
  const errors = [];
107113
107165
  await Promise.all(
107114
107166
  tables.map(async (table) => {
@@ -107162,7 +107214,7 @@ var Push = class {
107162
107214
  }
107163
107215
  })
107164
107216
  );
107165
- for (let table of tables) {
107217
+ for (const table of tables) {
107166
107218
  let columns = table.columns;
107167
107219
  let indexes = table.indexes;
107168
107220
  let hadChanges = false;
@@ -107441,7 +107493,7 @@ var pushSettings = async () => {
107441
107493
  checkDeployConditions(localConfig);
107442
107494
  try {
107443
107495
  const projectsService = await getProjectsService();
107444
- let response = await projectsService.get(
107496
+ const response = await projectsService.get(
107445
107497
  localConfig.getProject().projectId
107446
107498
  );
107447
107499
  const remoteSettings = createSettingsObject(response);
@@ -107474,7 +107526,7 @@ var pushSettings = async () => {
107474
107526
  return;
107475
107527
  }
107476
107528
  }
107477
- } catch (e) {
107529
+ } catch (_e) {
107478
107530
  }
107479
107531
  try {
107480
107532
  log("Pushing project settings ...");
@@ -107524,7 +107576,7 @@ var pushSite = async ({
107524
107576
  );
107525
107577
  return;
107526
107578
  }
107527
- let sites = siteIds.map((id) => {
107579
+ const sites = siteIds.map((id) => {
107528
107580
  const sites2 = localConfig.getSites();
107529
107581
  const site = sites2.find((s) => s.$id === id);
107530
107582
  if (!site) {
@@ -107533,7 +107585,7 @@ var pushSite = async ({
107533
107585
  return site;
107534
107586
  });
107535
107587
  log("Validating sites ...");
107536
- for (let site of sites) {
107588
+ for (const site of sites) {
107537
107589
  if (!site.buildCommand) {
107538
107590
  log(`Site ${site.name} is missing build command.`);
107539
107591
  const answers = await import_inquirer3.default.prompt(questionsGetEntrypoint);
@@ -107644,7 +107696,7 @@ var pushFunction = async ({
107644
107696
  );
107645
107697
  return;
107646
107698
  }
107647
- let functions = functionIds.map((id) => {
107699
+ const functions = functionIds.map((id) => {
107648
107700
  const functions2 = localConfig.getFunctions();
107649
107701
  const func = functions2.find((f) => f.$id === id);
107650
107702
  if (!func) {
@@ -107653,7 +107705,7 @@ var pushFunction = async ({
107653
107705
  return func;
107654
107706
  });
107655
107707
  log("Validating functions ...");
107656
- for (let func of functions) {
107708
+ for (const func of functions) {
107657
107709
  if (!func.entrypoint) {
107658
107710
  log(`Function ${func.name} is missing an entrypoint.`);
107659
107711
  const answers = await import_inquirer3.default.prompt(questionsGetEntrypoint);
@@ -107794,7 +107846,7 @@ var pushTable = async ({
107794
107846
  });
107795
107847
  }
107796
107848
  }
107797
- } catch (e) {
107849
+ } catch (_e) {
107798
107850
  }
107799
107851
  }
107800
107852
  if (tablesToDelete.length > 0) {
@@ -107941,7 +107993,7 @@ var pushCollection = async () => {
107941
107993
  }
107942
107994
  };
107943
107995
  var pushBucket = async () => {
107944
- let bucketIds = [];
107996
+ const bucketIds = [];
107945
107997
  const configBuckets = localConfig.getBuckets();
107946
107998
  if (cliConfig.all) {
107947
107999
  checkDeployConditions(localConfig);
@@ -107960,7 +108012,7 @@ var pushBucket = async () => {
107960
108012
  );
107961
108013
  return;
107962
108014
  }
107963
- let buckets = [];
108015
+ const buckets = [];
107964
108016
  for (const bucketId of bucketIds) {
107965
108017
  const idBuckets = configBuckets.filter((b) => b.$id === bucketId);
107966
108018
  buckets.push(...idBuckets);
@@ -107991,7 +108043,7 @@ var pushBucket = async () => {
107991
108043
  }
107992
108044
  };
107993
108045
  var pushTeam = async () => {
107994
- let teamIds = [];
108046
+ const teamIds = [];
107995
108047
  const configTeams = localConfig.getTeams();
107996
108048
  if (cliConfig.all) {
107997
108049
  checkDeployConditions(localConfig);
@@ -108010,7 +108062,7 @@ var pushTeam = async () => {
108010
108062
  );
108011
108063
  return;
108012
108064
  }
108013
- let teams = [];
108065
+ const teams = [];
108014
108066
  for (const teamId of teamIds) {
108015
108067
  const idTeams = configTeams.filter((t) => t.$id === teamId);
108016
108068
  teams.push(...idTeams);
@@ -108041,7 +108093,7 @@ var pushTeam = async () => {
108041
108093
  }
108042
108094
  };
108043
108095
  var pushMessagingTopic = async () => {
108044
- let topicsIds = [];
108096
+ const topicsIds = [];
108045
108097
  const configTopics = localConfig.getMessagingTopics();
108046
108098
  if (cliConfig.all) {
108047
108099
  checkDeployConditions(localConfig);
@@ -108060,7 +108112,7 @@ var pushMessagingTopic = async () => {
108060
108112
  );
108061
108113
  return;
108062
108114
  }
108063
- let topics = [];
108115
+ const topics = [];
108064
108116
  for (const topicId of topicsIds) {
108065
108117
  const idTopic = configTopics.filter((b) => b.$id === topicId);
108066
108118
  topics.push(...idTopic);
@@ -108644,7 +108696,7 @@ var pullResources = async ({
108644
108696
  delete actions.collections;
108645
108697
  }
108646
108698
  if (cliConfig.all) {
108647
- for (let action of Object.values(actions)) {
108699
+ for (const action of Object.values(actions)) {
108648
108700
  cliConfig.all = true;
108649
108701
  await action({ returnOnZero: true });
108650
108702
  }
@@ -109162,7 +109214,7 @@ var BaseDatabasesGenerator = class {
109162
109214
  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";
109163
109215
 
109164
109216
  // lib/commands/generators/typescript/templates/databases.ts.hbs
109165
- 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';
109217
+ 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';
109166
109218
 
109167
109219
  // lib/commands/generators/typescript/templates/index.ts.hbs
109168
109220
  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';
@@ -109329,7 +109381,7 @@ ${dbReturnTypes}
109329
109381
 
109330
109382
  export type DatabaseHandle<D extends DatabaseId> = {
109331
109383
  use: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => DatabaseTableMap[D][T];
109332
- ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: any[]; indexes?: any[] }) => Promise<Models.Table>;
109384
+ ${supportsServerSide ? ` create: (tableId: string, name: string, options?: { permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean; columns?: object[]; indexes?: object[] }) => Promise<Models.Table>;
109333
109385
  update: <T extends keyof DatabaseTableMap[D] & string>(tableId: T, options?: { name?: string; permissions?: ${PERMISSION_CALLBACK_INLINE}; rowSecurity?: boolean; enabled?: boolean }) => Promise<Models.Table>;
109334
109386
  delete: <T extends keyof DatabaseTableMap[D] & string>(tableId: T) => Promise<void>;` : ""}
109335
109387
  };
@@ -109396,26 +109448,26 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109396
109448
  generateBulkMethods(supportsBulk) {
109397
109449
  if (!supportsBulk) return "";
109398
109450
  return `
109399
- createMany: (rows: any[], options?: { transactionId?: string }) =>
109451
+ createMany: (rows: object[], options?: { transactionId?: string }) =>
109400
109452
  tablesDB.createRows({
109401
109453
  databaseId,
109402
109454
  tableId,
109403
109455
  rows,
109404
109456
  transactionId: options?.transactionId,
109405
109457
  }),
109406
- updateMany: (data: any, options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
109458
+ updateMany: (data: object, options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
109407
109459
  tablesDB.updateRows({
109408
109460
  databaseId,
109409
109461
  tableId,
109410
109462
  data,
109411
- queries: options?.queries?.(createQueryBuilder()),
109463
+ queries: options?.queries?.(createQueryBuilder<T>()),
109412
109464
  transactionId: options?.transactionId,
109413
109465
  }),
109414
- deleteMany: (options?: { queries?: (q: any) => string[]; transactionId?: string }) =>
109466
+ deleteMany: (options?: { queries?: (q: QueryBuilder<T>) => string[]; transactionId?: string }) =>
109415
109467
  tablesDB.deleteRows({
109416
109468
  databaseId,
109417
109469
  tableId,
109418
- queries: options?.queries?.(createQueryBuilder()),
109470
+ queries: options?.queries?.(createQueryBuilder<T>()),
109419
109471
  transactionId: options?.transactionId,
109420
109472
  }),`;
109421
109473
  }
@@ -109429,9 +109481,9 @@ ${supportsServerSide ? ` create: (databaseId: string, name: string, options?: {
109429
109481
  return `
109430
109482
  // Remove bulk methods for tables with relationships
109431
109483
  if (!hasBulkMethods(databaseId, tableId)) {
109432
- delete (api as any).createMany;
109433
- delete (api as any).updateMany;
109434
- delete (api as any).deleteMany;
109484
+ delete (api as Record<string, unknown>).createMany;
109485
+ delete (api as Record<string, unknown>).updateMany;
109486
+ delete (api as Record<string, unknown>).deleteMany;
109435
109487
  }`;
109436
109488
  }
109437
109489
  generateDatabasesFile(config2, importExt) {