appwrite-utils-cli 1.2.6 → 1.2.8

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.
@@ -492,6 +492,12 @@ export declare const convertYamlToAppwriteConfig: (yamlConfig: YamlConfig) => Ap
492
492
  export declare const loadYamlConfig: (configPath: string) => Promise<AppwriteConfig | null>;
493
493
  export declare const findYamlConfig: (startDir: string) => string | null;
494
494
  export declare const generateYamlConfigTemplate: (outputPath: string) => void;
495
+ /**
496
+ * Converts AppwriteConfig back to YAML format and writes to file
497
+ * @param configPath Path to the YAML config file
498
+ * @param config The AppwriteConfig to convert and save
499
+ */
500
+ export declare const writeYamlConfig: (configPath: string, config: AppwriteConfig) => Promise<void>;
495
501
  /**
496
502
  * Adds a new function to the YAML config file
497
503
  * @param configPath Path to the YAML config file
@@ -206,7 +206,7 @@ export const convertYamlToAppwriteConfig = (yamlConfig) => {
206
206
  templateBranch: func.templateBranch || "",
207
207
  specification: func.specification || "s-0.5vcpu-512mb",
208
208
  })),
209
- collections: [],
209
+ collections: [], // Note: Collections are managed separately in YAML configs via individual collection files
210
210
  };
211
211
  return appwriteConfig;
212
212
  };
@@ -397,6 +397,132 @@ export const generateYamlConfigTemplate = (outputPath) => {
397
397
  const finalContent = schemaReference + "# Appwrite Project Configuration\n" + yamlContent;
398
398
  fs.writeFileSync(outputPath, finalContent, "utf8");
399
399
  };
400
+ /**
401
+ * Converts AppwriteConfig back to YAML format and writes to file
402
+ * @param configPath Path to the YAML config file
403
+ * @param config The AppwriteConfig to convert and save
404
+ */
405
+ export const writeYamlConfig = async (configPath, config) => {
406
+ try {
407
+ // Convert AppwriteConfig back to YAML format
408
+ const yamlConfig = {
409
+ appwrite: {
410
+ endpoint: config.appwriteEndpoint,
411
+ project: config.appwriteProject,
412
+ key: config.appwriteKey,
413
+ },
414
+ logging: {
415
+ enabled: config.logging?.enabled || false,
416
+ level: config.logging?.level || "info",
417
+ directory: config.logging?.logDirectory,
418
+ console: config.logging?.console || false,
419
+ },
420
+ backups: {
421
+ enabled: config.enableBackups !== false,
422
+ interval: config.backupInterval || 3600,
423
+ retention: config.backupRetention || 30,
424
+ cleanup: config.enableBackupCleanup !== false,
425
+ },
426
+ data: {
427
+ enableMockData: config.enableMockData || false,
428
+ documentBucketId: config.documentBucketId || "documents",
429
+ usersCollectionName: config.usersCollectionName || "Members",
430
+ importDirectory: config.schemaConfig?.importDirectory || "importData",
431
+ },
432
+ schemas: {
433
+ outputDirectory: config.schemaConfig?.outputDirectory || "schemas",
434
+ yamlSchemaDirectory: config.schemaConfig?.yamlSchemaDirectory || ".yaml_schemas",
435
+ },
436
+ migrations: {
437
+ enabled: config.useMigrations !== false,
438
+ },
439
+ databases: config.databases?.map(db => ({
440
+ id: db.$id,
441
+ name: db.name,
442
+ bucket: db.bucket ? {
443
+ id: db.bucket.$id,
444
+ name: db.bucket.name,
445
+ permissions: db.bucket.permissions || [],
446
+ fileSecurity: db.bucket.fileSecurity,
447
+ enabled: db.bucket.enabled,
448
+ maximumFileSize: db.bucket.maximumFileSize,
449
+ allowedFileExtensions: db.bucket.allowedFileExtensions,
450
+ compression: db.bucket.compression,
451
+ encryption: db.bucket.encryption,
452
+ antivirus: db.bucket.antivirus,
453
+ } : undefined,
454
+ })) || [],
455
+ buckets: config.buckets?.map(bucket => ({
456
+ id: bucket.$id,
457
+ name: bucket.name,
458
+ permissions: bucket.permissions || [],
459
+ fileSecurity: bucket.fileSecurity,
460
+ enabled: bucket.enabled,
461
+ maximumFileSize: bucket.maximumFileSize,
462
+ allowedFileExtensions: bucket.allowedFileExtensions,
463
+ compression: bucket.compression,
464
+ encryption: bucket.encryption,
465
+ antivirus: bucket.antivirus,
466
+ })) || [],
467
+ functions: config.functions?.map(func => ({
468
+ id: func.$id,
469
+ name: func.name,
470
+ runtime: func.runtime,
471
+ execute: func.execute,
472
+ events: func.events,
473
+ schedule: func.schedule,
474
+ timeout: func.timeout,
475
+ enabled: func.enabled,
476
+ logging: func.logging,
477
+ entrypoint: func.entrypoint,
478
+ commands: func.commands,
479
+ scopes: func.scopes,
480
+ installationId: func.installationId,
481
+ providerRepositoryId: func.providerRepositoryId,
482
+ providerBranch: func.providerBranch,
483
+ providerSilentMode: func.providerSilentMode,
484
+ providerRootDirectory: func.providerRootDirectory,
485
+ templateRepository: func.templateRepository,
486
+ templateOwner: func.templateOwner,
487
+ templateRootDirectory: func.templateRootDirectory,
488
+ // templateBranch: func.templateBranch, // Not available in AppwriteFunction type
489
+ specification: func.specification,
490
+ })) || [],
491
+ };
492
+ // Write YAML config
493
+ const yamlContent = yaml.dump(yamlConfig, {
494
+ indent: 2,
495
+ lineWidth: 120,
496
+ sortKeys: false,
497
+ });
498
+ // Preserve schema reference if it exists
499
+ let finalContent = yamlContent;
500
+ if (fs.existsSync(configPath)) {
501
+ const existingContent = fs.readFileSync(configPath, "utf8");
502
+ const lines = existingContent.split('\n');
503
+ const schemaLine = lines.find(line => line.startsWith('# yaml-language-server:'));
504
+ const commentLine = lines.find(line => line.startsWith('# Appwrite Project Configuration'));
505
+ if (schemaLine) {
506
+ finalContent = schemaLine + '\n';
507
+ if (commentLine) {
508
+ finalContent += commentLine + '\n';
509
+ }
510
+ finalContent += yamlContent;
511
+ }
512
+ }
513
+ else {
514
+ // Add schema reference for new files
515
+ const schemaReference = "# yaml-language-server: $schema=./.yaml_schemas/appwrite-config.schema.json\n";
516
+ finalContent = schemaReference + "# Appwrite Project Configuration\n" + yamlContent;
517
+ }
518
+ fs.writeFileSync(configPath, finalContent, "utf8");
519
+ console.log(`✅ Updated YAML configuration at ${configPath}`);
520
+ }
521
+ catch (error) {
522
+ console.error("❌ Error writing YAML config:", error instanceof Error ? error.message : error);
523
+ throw error;
524
+ }
525
+ };
400
526
  /**
401
527
  * Adds a new function to the YAML config file
402
528
  * @param configPath Path to the YAML config file
@@ -102,9 +102,33 @@ export declare class ComprehensiveTransfer {
102
102
  */
103
103
  private createCollectionIndexesWithStatusCheck;
104
104
  /**
105
- * Helper method to transfer documents between databases
105
+ * Helper method to transfer documents between databases using bulk operations with content and permission-based filtering
106
106
  */
107
107
  private transferDocumentsBetweenDatabases;
108
+ /**
109
+ * Fetch target documents by IDs in batches to check existence and permissions
110
+ */
111
+ private fetchTargetDocumentsBatch;
112
+ /**
113
+ * Transfer documents using bulk operations with proper batch size handling
114
+ */
115
+ private transferDocumentsBulk;
116
+ /**
117
+ * Direct HTTP implementation of bulk upsert API
118
+ */
119
+ private bulkUpsertDocuments;
120
+ /**
121
+ * Transfer documents individually with rate limiting
122
+ */
123
+ private transferDocumentsIndividual;
124
+ /**
125
+ * Update documents individually with content and/or permission changes
126
+ */
127
+ private updateDocumentsIndividual;
128
+ /**
129
+ * Utility method to chunk arrays
130
+ */
131
+ private chunkArray;
108
132
  /**
109
133
  * Helper method to fetch all teams with pagination
110
134
  */
@@ -1,4 +1,4 @@
1
- import { converterFunctions, tryAwaitWithRetry, parseAttribute } from "appwrite-utils";
1
+ import { converterFunctions, tryAwaitWithRetry, parseAttribute, objectNeedsUpdate } from "appwrite-utils";
2
2
  import { Client, Databases, Storage, Users, Functions, Teams, Query, } from "node-appwrite";
3
3
  import { InputFile } from "node-appwrite/file";
4
4
  import { MessageFormatter } from "../shared/messageFormatter.js";
@@ -361,6 +361,27 @@ export class ComprehensiveTransfer {
361
361
  await this.createBucketWithFallback(bucket);
362
362
  MessageFormatter.success(`Created bucket: ${bucket.name}`, { prefix: "Transfer" });
363
363
  }
364
+ else {
365
+ // Compare bucket permissions and update if needed
366
+ const sourcePermissions = JSON.stringify(bucket.$permissions?.sort() || []);
367
+ const targetPermissions = JSON.stringify(existingBucket.$permissions?.sort() || []);
368
+ if (sourcePermissions !== targetPermissions ||
369
+ existingBucket.name !== bucket.name ||
370
+ existingBucket.fileSecurity !== bucket.fileSecurity ||
371
+ existingBucket.enabled !== bucket.enabled) {
372
+ MessageFormatter.warning(`Bucket ${bucket.name} exists but has different settings. Updating to match source.`, { prefix: "Transfer" });
373
+ try {
374
+ await this.targetStorage.updateBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, bucket.maximumFileSize, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
375
+ MessageFormatter.success(`Updated bucket ${bucket.name} to match source`, { prefix: "Transfer" });
376
+ }
377
+ catch (updateError) {
378
+ MessageFormatter.error(`Failed to update bucket ${bucket.name}`, updateError instanceof Error ? updateError : new Error(String(updateError)), { prefix: "Transfer" });
379
+ }
380
+ }
381
+ else {
382
+ MessageFormatter.info(`Bucket ${bucket.name} already exists with matching settings`, { prefix: "Transfer" });
383
+ }
384
+ }
364
385
  // Transfer bucket files with enhanced validation
365
386
  await this.transferBucketFiles(bucket.$id, bucket.$id);
366
387
  this.results.buckets.transferred++;
@@ -481,10 +502,27 @@ export class ComprehensiveTransfer {
481
502
  // Process files with rate limiting
482
503
  const fileTasks = files.files.map(file => this.fileLimit(async () => {
483
504
  try {
484
- // Check if file already exists
505
+ // Check if file already exists and compare permissions
506
+ let existingFile = null;
485
507
  try {
486
- await this.targetStorage.getFile(targetBucketId, file.$id);
487
- MessageFormatter.info(`File ${file.name} already exists, skipping`, { prefix: "Transfer" });
508
+ existingFile = await this.targetStorage.getFile(targetBucketId, file.$id);
509
+ // Compare permissions between source and target file
510
+ const sourcePermissions = JSON.stringify(file.$permissions?.sort() || []);
511
+ const targetPermissions = JSON.stringify(existingFile.$permissions?.sort() || []);
512
+ if (sourcePermissions !== targetPermissions) {
513
+ MessageFormatter.warning(`File ${file.name} (${file.$id}) exists but has different permissions. Source: ${sourcePermissions}, Target: ${targetPermissions}`, { prefix: "Transfer" });
514
+ // Update file permissions to match source
515
+ try {
516
+ await this.targetStorage.updateFile(targetBucketId, file.$id, file.name, file.$permissions);
517
+ MessageFormatter.success(`Updated file ${file.name} permissions to match source`, { prefix: "Transfer" });
518
+ }
519
+ catch (updateError) {
520
+ MessageFormatter.error(`Failed to update permissions for file ${file.name}`, updateError instanceof Error ? updateError : new Error(String(updateError)), { prefix: "Transfer" });
521
+ }
522
+ }
523
+ else {
524
+ MessageFormatter.info(`File ${file.name} already exists with matching permissions, skipping`, { prefix: "Transfer" });
525
+ }
488
526
  return;
489
527
  }
490
528
  catch (error) {
@@ -702,50 +740,259 @@ export class ComprehensiveTransfer {
702
740
  return await createOrUpdateIndexesWithStatusCheck(dbId, databases, collectionId, collection, indexes);
703
741
  }
704
742
  /**
705
- * Helper method to transfer documents between databases
743
+ * Helper method to transfer documents between databases using bulk operations with content and permission-based filtering
706
744
  */
707
745
  async transferDocumentsBetweenDatabases(sourceDb, targetDb, sourceDbId, targetDbId, sourceCollectionId, targetCollectionId) {
708
- MessageFormatter.info(`Transferring documents from ${sourceCollectionId} to ${targetCollectionId}`, { prefix: "Transfer" });
746
+ MessageFormatter.info(`Transferring documents from ${sourceCollectionId} to ${targetCollectionId} with bulk operations, content comparison, and permission filtering`, { prefix: "Transfer" });
709
747
  let lastId;
710
748
  let totalTransferred = 0;
749
+ let totalSkipped = 0;
750
+ let totalUpdated = 0;
751
+ // Check if bulk operations are supported
752
+ const supportsBulk = this.options.sourceEndpoint.includes('cloud.appwrite.io') ||
753
+ this.options.targetEndpoint.includes('cloud.appwrite.io');
754
+ if (supportsBulk) {
755
+ MessageFormatter.info(`Using bulk operations for enhanced performance`, { prefix: "Transfer" });
756
+ }
711
757
  while (true) {
712
- const queries = [Query.limit(50)]; // Smaller batch size for better performance
758
+ // Fetch source documents in larger batches (1000 instead of 50)
759
+ const queries = [Query.limit(1000)];
713
760
  if (lastId) {
714
761
  queries.push(Query.cursorAfter(lastId));
715
762
  }
716
- const documents = await tryAwaitWithRetry(async () => sourceDb.listDocuments(sourceDbId, sourceCollectionId, queries));
717
- if (documents.documents.length === 0) {
763
+ const sourceDocuments = await tryAwaitWithRetry(async () => sourceDb.listDocuments(sourceDbId, sourceCollectionId, queries));
764
+ if (sourceDocuments.documents.length === 0) {
718
765
  break;
719
766
  }
720
- // Transfer documents with rate limiting
721
- const transferTasks = documents.documents.map(doc => this.limit(async () => {
722
- try {
723
- // Check if document already exists
724
- try {
725
- await targetDb.getDocument(targetDbId, targetCollectionId, doc.$id);
726
- MessageFormatter.info(`Document ${doc.$id} already exists, skipping`, { prefix: "Transfer" });
727
- return;
767
+ MessageFormatter.info(`Processing batch of ${sourceDocuments.documents.length} source documents`, { prefix: "Transfer" });
768
+ // Extract document IDs from the current batch
769
+ const sourceDocIds = sourceDocuments.documents.map(doc => doc.$id);
770
+ // Fetch existing documents from target in a single query
771
+ const existingTargetDocs = await this.fetchTargetDocumentsBatch(targetDb, targetDbId, targetCollectionId, sourceDocIds);
772
+ // Create a map for quick lookup of existing documents
773
+ const existingDocsMap = new Map();
774
+ existingTargetDocs.forEach(doc => {
775
+ existingDocsMap.set(doc.$id, doc);
776
+ });
777
+ // Filter documents based on existence, content comparison, and permission comparison
778
+ const documentsToTransfer = [];
779
+ const documentsToUpdate = [];
780
+ for (const sourceDoc of sourceDocuments.documents) {
781
+ const existingTargetDoc = existingDocsMap.get(sourceDoc.$id);
782
+ if (!existingTargetDoc) {
783
+ // Document doesn't exist in target, needs to be transferred
784
+ documentsToTransfer.push(sourceDoc);
785
+ }
786
+ else {
787
+ // Document exists, compare both content and permissions
788
+ const sourcePermissions = JSON.stringify((sourceDoc.$permissions || []).sort());
789
+ const targetPermissions = JSON.stringify((existingTargetDoc.$permissions || []).sort());
790
+ const permissionsDiffer = sourcePermissions !== targetPermissions;
791
+ // Use objectNeedsUpdate to compare document content (excluding system fields)
792
+ const contentDiffers = objectNeedsUpdate(existingTargetDoc, sourceDoc);
793
+ if (contentDiffers && permissionsDiffer) {
794
+ // Both content and permissions differ
795
+ documentsToUpdate.push({
796
+ doc: sourceDoc,
797
+ targetDoc: existingTargetDoc,
798
+ reason: "content and permissions differ"
799
+ });
800
+ MessageFormatter.info(`Document ${sourceDoc.$id} exists but content and permissions differ - will update`, { prefix: "Transfer" });
728
801
  }
729
- catch (error) {
730
- // Document doesn't exist, proceed with creation
802
+ else if (contentDiffers) {
803
+ // Only content differs
804
+ documentsToUpdate.push({
805
+ doc: sourceDoc,
806
+ targetDoc: existingTargetDoc,
807
+ reason: "content differs"
808
+ });
809
+ MessageFormatter.info(`Document ${sourceDoc.$id} exists but content differs - will update`, { prefix: "Transfer" });
810
+ }
811
+ else if (permissionsDiffer) {
812
+ // Only permissions differ
813
+ documentsToUpdate.push({
814
+ doc: sourceDoc,
815
+ targetDoc: existingTargetDoc,
816
+ reason: "permissions differ"
817
+ });
818
+ MessageFormatter.info(`Document ${sourceDoc.$id} exists but permissions differ - will update`, { prefix: "Transfer" });
819
+ }
820
+ else {
821
+ // Document exists with identical content AND permissions, skip
822
+ totalSkipped++;
823
+ MessageFormatter.info(`Document ${sourceDoc.$id} exists with matching content and permissions - skipping`, { prefix: "Transfer" });
731
824
  }
732
- // Create document in target
733
- const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, ...docData } = doc;
734
- await tryAwaitWithRetry(async () => targetDb.createDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
735
- totalTransferred++;
736
- MessageFormatter.success(`Transferred document ${doc.$id}`, { prefix: "Transfer" });
737
825
  }
738
- catch (error) {
739
- MessageFormatter.error(`Failed to transfer document ${doc.$id}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
826
+ }
827
+ MessageFormatter.info(`Batch analysis: ${documentsToTransfer.length} to create, ${documentsToUpdate.length} to update, ${totalSkipped} skipped so far`, { prefix: "Transfer" });
828
+ // Process new documents with bulk operations if supported and available
829
+ if (documentsToTransfer.length > 0) {
830
+ if (supportsBulk && documentsToTransfer.length >= 10) {
831
+ // Use bulk operations for large batches
832
+ await this.transferDocumentsBulk(targetDb, targetDbId, targetCollectionId, documentsToTransfer);
833
+ totalTransferred += documentsToTransfer.length;
834
+ MessageFormatter.success(`Bulk transferred ${documentsToTransfer.length} new documents`, { prefix: "Transfer" });
740
835
  }
741
- }));
742
- await Promise.all(transferTasks);
743
- if (documents.documents.length < 50) {
836
+ else {
837
+ // Use individual transfers for smaller batches or non-bulk endpoints
838
+ const transferCount = await this.transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentsToTransfer);
839
+ totalTransferred += transferCount;
840
+ }
841
+ }
842
+ // Process document updates (always individual since bulk update with permissions needs special handling)
843
+ if (documentsToUpdate.length > 0) {
844
+ const updateCount = await this.updateDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentsToUpdate);
845
+ totalUpdated += updateCount;
846
+ }
847
+ if (sourceDocuments.documents.length < 1000) {
744
848
  break;
745
849
  }
746
- lastId = documents.documents[documents.documents.length - 1].$id;
850
+ lastId = sourceDocuments.documents[sourceDocuments.documents.length - 1].$id;
851
+ }
852
+ MessageFormatter.info(`Transfer complete: ${totalTransferred} new, ${totalUpdated} updated, ${totalSkipped} skipped from ${sourceCollectionId} to ${targetCollectionId}`, { prefix: "Transfer" });
853
+ }
854
+ /**
855
+ * Fetch target documents by IDs in batches to check existence and permissions
856
+ */
857
+ async fetchTargetDocumentsBatch(targetDb, targetDbId, targetCollectionId, docIds) {
858
+ const documents = [];
859
+ // Split IDs into chunks of 100 for Query.equal limitations
860
+ const idChunks = this.chunkArray(docIds, 100);
861
+ for (const chunk of idChunks) {
862
+ try {
863
+ const result = await tryAwaitWithRetry(async () => targetDb.listDocuments(targetDbId, targetCollectionId, [
864
+ Query.equal('$id', chunk),
865
+ Query.limit(100)
866
+ ]));
867
+ documents.push(...result.documents);
868
+ }
869
+ catch (error) {
870
+ // If query fails, fall back to individual gets (less efficient but more reliable)
871
+ MessageFormatter.warning(`Batch query failed for ${chunk.length} documents, falling back to individual checks`, { prefix: "Transfer" });
872
+ for (const docId of chunk) {
873
+ try {
874
+ const doc = await targetDb.getDocument(targetDbId, targetCollectionId, docId);
875
+ documents.push(doc);
876
+ }
877
+ catch (getError) {
878
+ // Document doesn't exist, which is fine
879
+ }
880
+ }
881
+ }
882
+ }
883
+ return documents;
884
+ }
885
+ /**
886
+ * Transfer documents using bulk operations with proper batch size handling
887
+ */
888
+ async transferDocumentsBulk(targetDb, targetDbId, targetCollectionId, documents) {
889
+ // Prepare documents for bulk upsert
890
+ const preparedDocs = documents.map(doc => {
891
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, ...docData } = doc;
892
+ return {
893
+ $id,
894
+ $permissions,
895
+ ...docData
896
+ };
897
+ });
898
+ // Process in smaller chunks for bulk operations (1000 for Pro, 100 for Free tier)
899
+ const batchSizes = [1000, 100]; // Start with Pro plan, fallback to Free
900
+ let processed = false;
901
+ for (const maxBatchSize of batchSizes) {
902
+ const documentBatches = this.chunkArray(preparedDocs, maxBatchSize);
903
+ try {
904
+ for (const batch of documentBatches) {
905
+ MessageFormatter.info(`Bulk upserting ${batch.length} documents...`, { prefix: "Transfer" });
906
+ await this.bulkUpsertDocuments(this.targetClient, targetDbId, targetCollectionId, batch);
907
+ MessageFormatter.success(`✅ Bulk upserted ${batch.length} documents`, { prefix: "Transfer" });
908
+ // Add delay between batches to respect rate limits
909
+ if (documentBatches.indexOf(batch) < documentBatches.length - 1) {
910
+ await new Promise(resolve => setTimeout(resolve, 200));
911
+ }
912
+ }
913
+ processed = true;
914
+ break; // Success, exit batch size loop
915
+ }
916
+ catch (error) {
917
+ MessageFormatter.warning(`Bulk upsert with batch size ${maxBatchSize} failed, trying smaller size...`, { prefix: "Transfer" });
918
+ continue; // Try next smaller batch size
919
+ }
920
+ }
921
+ if (!processed) {
922
+ MessageFormatter.warning(`All bulk operations failed, falling back to individual transfers`, { prefix: "Transfer" });
923
+ // Fall back to individual transfers
924
+ await this.transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documents);
925
+ }
926
+ }
927
+ /**
928
+ * Direct HTTP implementation of bulk upsert API
929
+ */
930
+ async bulkUpsertDocuments(client, dbId, collectionId, documents) {
931
+ const apiPath = `/databases/${dbId}/collections/${collectionId}/documents`;
932
+ const url = new URL(client.config.endpoint + apiPath);
933
+ const headers = {
934
+ 'Content-Type': 'application/json',
935
+ 'X-Appwrite-Project': client.config.project,
936
+ 'X-Appwrite-Key': client.config.key
937
+ };
938
+ const response = await fetch(url.toString(), {
939
+ method: 'PUT',
940
+ headers,
941
+ body: JSON.stringify({ documents })
942
+ });
943
+ if (!response.ok) {
944
+ const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
945
+ throw new Error(`Bulk upsert failed: ${response.status} - ${errorData.message || 'Unknown error'}`);
946
+ }
947
+ return await response.json();
948
+ }
949
+ /**
950
+ * Transfer documents individually with rate limiting
951
+ */
952
+ async transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documents) {
953
+ let successCount = 0;
954
+ const transferTasks = documents.map(doc => this.limit(async () => {
955
+ try {
956
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, ...docData } = doc;
957
+ await tryAwaitWithRetry(async () => targetDb.createDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
958
+ successCount++;
959
+ MessageFormatter.success(`Transferred document ${doc.$id}`, { prefix: "Transfer" });
960
+ }
961
+ catch (error) {
962
+ MessageFormatter.error(`Failed to transfer document ${doc.$id}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
963
+ }
964
+ }));
965
+ await Promise.all(transferTasks);
966
+ return successCount;
967
+ }
968
+ /**
969
+ * Update documents individually with content and/or permission changes
970
+ */
971
+ async updateDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentPairs) {
972
+ let successCount = 0;
973
+ const updateTasks = documentPairs.map(({ doc, targetDoc, reason }) => this.limit(async () => {
974
+ try {
975
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, ...docData } = doc;
976
+ await tryAwaitWithRetry(async () => targetDb.updateDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
977
+ successCount++;
978
+ MessageFormatter.success(`Updated document ${doc.$id} (${reason}) - permissions: [${targetDoc.$permissions?.join(', ')}] → [${doc.$permissions?.join(', ')}]`, { prefix: "Transfer" });
979
+ }
980
+ catch (error) {
981
+ MessageFormatter.error(`Failed to update document ${doc.$id} (${reason})`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
982
+ }
983
+ }));
984
+ await Promise.all(updateTasks);
985
+ return successCount;
986
+ }
987
+ /**
988
+ * Utility method to chunk arrays
989
+ */
990
+ chunkArray(array, size) {
991
+ const chunks = [];
992
+ for (let i = 0; i < array.length; i += size) {
993
+ chunks.push(array.slice(i, i + size));
747
994
  }
748
- MessageFormatter.info(`Transferred ${totalTransferred} documents from ${sourceCollectionId} to ${targetCollectionId}`, { prefix: "Transfer" });
995
+ return chunks;
749
996
  }
750
997
  /**
751
998
  * Helper method to fetch all teams with pagination
@@ -810,10 +1057,27 @@ export class ComprehensiveTransfer {
810
1057
  // Transfer memberships with rate limiting
811
1058
  const transferTasks = memberships.map(membership => this.userLimit(async () => {
812
1059
  try {
813
- // Check if membership already exists
1060
+ // Check if membership already exists and compare roles
1061
+ let existingMembership = null;
814
1062
  try {
815
- await this.targetTeams.getMembership(teamId, membership.$id);
816
- MessageFormatter.info(`Membership ${membership.$id} already exists, skipping`, { prefix: "Transfer" });
1063
+ existingMembership = await this.targetTeams.getMembership(teamId, membership.$id);
1064
+ // Compare roles between source and target membership
1065
+ const sourceRoles = JSON.stringify(membership.roles?.sort() || []);
1066
+ const targetRoles = JSON.stringify(existingMembership.roles?.sort() || []);
1067
+ if (sourceRoles !== targetRoles) {
1068
+ MessageFormatter.warning(`Membership ${membership.$id} exists but has different roles. Source: ${sourceRoles}, Target: ${targetRoles}`, { prefix: "Transfer" });
1069
+ // Update membership roles to match source
1070
+ try {
1071
+ await this.targetTeams.updateMembership(teamId, membership.$id, membership.roles);
1072
+ MessageFormatter.success(`Updated membership ${membership.$id} roles to match source`, { prefix: "Transfer" });
1073
+ }
1074
+ catch (updateError) {
1075
+ MessageFormatter.error(`Failed to update roles for membership ${membership.$id}`, updateError instanceof Error ? updateError : new Error(String(updateError)), { prefix: "Transfer" });
1076
+ }
1077
+ }
1078
+ else {
1079
+ MessageFormatter.info(`Membership ${membership.$id} already exists with matching roles, skipping`, { prefix: "Transfer" });
1080
+ }
817
1081
  return;
818
1082
  }
819
1083
  catch (error) {
@@ -7,6 +7,8 @@ export declare class SchemaGenerator {
7
7
  updateYamlCollections(): void;
8
8
  updateTsSchemas(): void;
9
9
  updateConfig(config: AppwriteConfig): void;
10
+ private updateYamlConfig;
11
+ private updateTypeScriptConfig;
10
12
  private extractRelationships;
11
13
  private addRelationship;
12
14
  generateSchemas(options?: {
@@ -155,6 +155,33 @@ export class SchemaGenerator {
155
155
  });
156
156
  }
157
157
  updateConfig(config) {
158
+ // Check if user is using YAML config
159
+ const { findYamlConfig, writeYamlConfig } = require("../config/yamlConfig.js");
160
+ const yamlConfigPath = findYamlConfig(this.appwriteFolderPath);
161
+ if (yamlConfigPath) {
162
+ // User has YAML config - update it and generate individual collection files
163
+ this.updateYamlConfig(config, yamlConfigPath);
164
+ }
165
+ else {
166
+ // User has TypeScript config - update the TS file
167
+ this.updateTypeScriptConfig(config);
168
+ }
169
+ }
170
+ async updateYamlConfig(config, yamlConfigPath) {
171
+ try {
172
+ const { writeYamlConfig } = await import("../config/yamlConfig.js");
173
+ // Write the main YAML config (without collections)
174
+ await writeYamlConfig(yamlConfigPath, config);
175
+ // Generate individual collection YAML files
176
+ this.updateYamlCollections();
177
+ console.log("✅ Updated YAML configuration and collection files");
178
+ }
179
+ catch (error) {
180
+ console.error("❌ Error updating YAML config:", error instanceof Error ? error.message : error);
181
+ throw error;
182
+ }
183
+ }
184
+ updateTypeScriptConfig(config) {
158
185
  const configPath = path.join(this.appwriteFolderPath, "appwriteConfig.ts");
159
186
  const configContent = `import { type AppwriteConfig } from "appwrite-utils";
160
187
 
@@ -175,7 +202,7 @@ const appwriteConfig: AppwriteConfig = {
175
202
  $id: func.$id || ulid(),
176
203
  name: func.name,
177
204
  runtime: func.runtime,
178
- dirPath: func.dirPath || `functions/${func.name}`,
205
+ dirPath: func.dirPath || "functions/" + func.name,
179
206
  entrypoint: func.entrypoint || "src/index.ts",
180
207
  execute: func.execute || [],
181
208
  events: func.events || [],
@@ -191,12 +218,14 @@ const appwriteConfig: AppwriteConfig = {
191
218
  providerSilentMode: func.providerSilentMode,
192
219
  providerRootDirectory: func.providerRootDirectory,
193
220
  specification: func.specification,
194
- })), null, 4)}
221
+ })), null, 4)},
222
+ collections: ${JSON.stringify(config.collections, null, 4)}
195
223
  };
196
224
 
197
225
  export default appwriteConfig;
198
226
  `;
199
227
  fs.writeFileSync(configPath, configContent, { encoding: "utf-8" });
228
+ console.log("✅ Updated TypeScript configuration file");
200
229
  }
201
230
  extractRelationships() {
202
231
  if (!this.config.collections) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "appwrite-utils-cli",
3
3
  "description": "Appwrite Utility Functions to help with database management, data conversion, data import, migrations, and much more. Meant to be used as a CLI tool, I do not recommend installing this in frontend environments.",
4
- "version": "1.2.6",
4
+ "version": "1.2.8",
5
5
  "main": "src/main.ts",
6
6
  "type": "module",
7
7
  "repository": {