@aws-amplify/datastore 5.0.32 → 5.0.33-s-auth.30d0cd2.0

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 (149) hide show
  1. package/dist/cjs/authModeStrategies/multiAuthStrategy.js +1 -1
  2. package/dist/cjs/authModeStrategies/multiAuthStrategy.js.map +1 -1
  3. package/dist/cjs/datastore/datastore.js +46 -41
  4. package/dist/cjs/datastore/datastore.js.map +1 -1
  5. package/dist/cjs/index.js +3 -1
  6. package/dist/cjs/index.js.map +1 -1
  7. package/dist/cjs/predicates/index.js +1 -0
  8. package/dist/cjs/predicates/index.js.map +1 -1
  9. package/dist/cjs/predicates/next.js +13 -12
  10. package/dist/cjs/predicates/next.js.map +1 -1
  11. package/dist/cjs/predicates/sort.js +2 -2
  12. package/dist/cjs/predicates/sort.js.map +1 -1
  13. package/dist/cjs/storage/adapter/AsyncStorageAdapter.js +21 -18
  14. package/dist/cjs/storage/adapter/AsyncStorageAdapter.js.map +1 -1
  15. package/dist/cjs/storage/adapter/AsyncStorageDatabase.js +10 -9
  16. package/dist/cjs/storage/adapter/AsyncStorageDatabase.js.map +1 -1
  17. package/dist/cjs/storage/adapter/InMemoryStore.js +4 -1
  18. package/dist/cjs/storage/adapter/InMemoryStore.js.map +1 -1
  19. package/dist/cjs/storage/adapter/IndexedDBAdapter.js +21 -23
  20. package/dist/cjs/storage/adapter/IndexedDBAdapter.js.map +1 -1
  21. package/dist/cjs/storage/adapter/StorageAdapterBase.js +7 -7
  22. package/dist/cjs/storage/adapter/StorageAdapterBase.js.map +1 -1
  23. package/dist/cjs/storage/adapter/getDefaultAdapter/index.js +4 -1
  24. package/dist/cjs/storage/adapter/getDefaultAdapter/index.js.map +1 -1
  25. package/dist/cjs/storage/adapter/getDefaultAdapter/index.native.js +1 -0
  26. package/dist/cjs/storage/adapter/getDefaultAdapter/index.native.js.map +1 -1
  27. package/dist/cjs/storage/relationship.js +1 -0
  28. package/dist/cjs/storage/relationship.js.map +1 -1
  29. package/dist/cjs/storage/storage.js +14 -14
  30. package/dist/cjs/storage/storage.js.map +1 -1
  31. package/dist/cjs/sync/datastoreConnectivity.js +0 -3
  32. package/dist/cjs/sync/datastoreConnectivity.js.map +1 -1
  33. package/dist/cjs/sync/index.js +47 -43
  34. package/dist/cjs/sync/index.js.map +1 -1
  35. package/dist/cjs/sync/merger.js +1 -1
  36. package/dist/cjs/sync/merger.js.map +1 -1
  37. package/dist/cjs/sync/outbox.js +19 -17
  38. package/dist/cjs/sync/outbox.js.map +1 -1
  39. package/dist/cjs/sync/processors/errorMaps.js.map +1 -1
  40. package/dist/cjs/sync/processors/mutation.js +31 -28
  41. package/dist/cjs/sync/processors/mutation.js.map +1 -1
  42. package/dist/cjs/sync/processors/subscription.js +21 -12
  43. package/dist/cjs/sync/processors/subscription.js.map +1 -1
  44. package/dist/cjs/sync/processors/sync.js +25 -21
  45. package/dist/cjs/sync/processors/sync.js.map +1 -1
  46. package/dist/cjs/sync/utils.js +20 -21
  47. package/dist/cjs/sync/utils.js.map +1 -1
  48. package/dist/cjs/types.js +1 -0
  49. package/dist/cjs/types.js.map +1 -1
  50. package/dist/cjs/util.js +46 -25
  51. package/dist/cjs/util.js.map +1 -1
  52. package/dist/esm/authModeStrategies/multiAuthStrategy.d.ts +1 -1
  53. package/dist/esm/authModeStrategies/multiAuthStrategy.mjs +1 -1
  54. package/dist/esm/authModeStrategies/multiAuthStrategy.mjs.map +1 -1
  55. package/dist/esm/datastore/datastore.d.ts +4 -6
  56. package/dist/esm/datastore/datastore.mjs +42 -34
  57. package/dist/esm/datastore/datastore.mjs.map +1 -1
  58. package/dist/esm/index.d.ts +1 -1
  59. package/dist/esm/index.mjs +2 -2
  60. package/dist/esm/index.mjs.map +1 -1
  61. package/dist/esm/predicates/index.mjs +1 -0
  62. package/dist/esm/predicates/index.mjs.map +1 -1
  63. package/dist/esm/predicates/next.d.ts +7 -7
  64. package/dist/esm/predicates/next.mjs +13 -12
  65. package/dist/esm/predicates/next.mjs.map +1 -1
  66. package/dist/esm/predicates/sort.d.ts +1 -1
  67. package/dist/esm/predicates/sort.mjs +2 -2
  68. package/dist/esm/predicates/sort.mjs.map +1 -1
  69. package/dist/esm/storage/adapter/AsyncStorageAdapter.d.ts +1 -1
  70. package/dist/esm/storage/adapter/AsyncStorageAdapter.mjs +21 -18
  71. package/dist/esm/storage/adapter/AsyncStorageAdapter.mjs.map +1 -1
  72. package/dist/esm/storage/adapter/AsyncStorageDatabase.mjs +10 -9
  73. package/dist/esm/storage/adapter/AsyncStorageDatabase.mjs.map +1 -1
  74. package/dist/esm/storage/adapter/InMemoryStore.mjs +4 -1
  75. package/dist/esm/storage/adapter/InMemoryStore.mjs.map +1 -1
  76. package/dist/esm/storage/adapter/IndexedDBAdapter.mjs +21 -23
  77. package/dist/esm/storage/adapter/IndexedDBAdapter.mjs.map +1 -1
  78. package/dist/esm/storage/adapter/StorageAdapterBase.d.ts +2 -2
  79. package/dist/esm/storage/adapter/StorageAdapterBase.mjs +7 -7
  80. package/dist/esm/storage/adapter/StorageAdapterBase.mjs.map +1 -1
  81. package/dist/esm/storage/adapter/getDefaultAdapter/index.mjs +3 -1
  82. package/dist/esm/storage/adapter/getDefaultAdapter/index.mjs.map +1 -1
  83. package/dist/esm/storage/adapter/getDefaultAdapter/index.native.mjs +1 -0
  84. package/dist/esm/storage/adapter/getDefaultAdapter/index.native.mjs.map +1 -1
  85. package/dist/esm/storage/adapter/index.d.ts +1 -1
  86. package/dist/esm/storage/relationship.mjs +1 -0
  87. package/dist/esm/storage/relationship.mjs.map +1 -1
  88. package/dist/esm/storage/storage.d.ts +11 -11
  89. package/dist/esm/storage/storage.mjs +10 -10
  90. package/dist/esm/storage/storage.mjs.map +1 -1
  91. package/dist/esm/sync/datastoreConnectivity.d.ts +2 -2
  92. package/dist/esm/sync/datastoreConnectivity.mjs +0 -3
  93. package/dist/esm/sync/datastoreConnectivity.mjs.map +1 -1
  94. package/dist/esm/sync/index.d.ts +3 -3
  95. package/dist/esm/sync/index.mjs +47 -43
  96. package/dist/esm/sync/index.mjs.map +1 -1
  97. package/dist/esm/sync/merger.d.ts +1 -1
  98. package/dist/esm/sync/merger.mjs +1 -1
  99. package/dist/esm/sync/merger.mjs.map +1 -1
  100. package/dist/esm/sync/outbox.d.ts +4 -4
  101. package/dist/esm/sync/outbox.mjs +19 -17
  102. package/dist/esm/sync/outbox.mjs.map +1 -1
  103. package/dist/esm/sync/processors/errorMaps.mjs.map +1 -1
  104. package/dist/esm/sync/processors/mutation.d.ts +5 -5
  105. package/dist/esm/sync/processors/mutation.mjs +31 -28
  106. package/dist/esm/sync/processors/mutation.mjs.map +1 -1
  107. package/dist/esm/sync/processors/subscription.d.ts +1 -1
  108. package/dist/esm/sync/processors/subscription.mjs +21 -12
  109. package/dist/esm/sync/processors/subscription.mjs.map +1 -1
  110. package/dist/esm/sync/processors/sync.d.ts +3 -3
  111. package/dist/esm/sync/processors/sync.mjs +13 -9
  112. package/dist/esm/sync/processors/sync.mjs.map +1 -1
  113. package/dist/esm/sync/utils.d.ts +11 -13
  114. package/dist/esm/sync/utils.mjs +20 -21
  115. package/dist/esm/sync/utils.mjs.map +1 -1
  116. package/dist/esm/types.d.ts +121 -131
  117. package/dist/esm/types.mjs +3 -2
  118. package/dist/esm/types.mjs.map +1 -1
  119. package/dist/esm/util.d.ts +5 -5
  120. package/dist/esm/util.mjs +46 -25
  121. package/dist/esm/util.mjs.map +1 -1
  122. package/package.json +74 -73
  123. package/src/authModeStrategies/multiAuthStrategy.ts +8 -4
  124. package/src/datastore/datastore.ts +145 -123
  125. package/src/index.ts +10 -8
  126. package/src/predicates/index.ts +10 -2
  127. package/src/predicates/next.ts +39 -28
  128. package/src/predicates/sort.ts +23 -26
  129. package/src/storage/adapter/AsyncStorageAdapter.ts +43 -25
  130. package/src/storage/adapter/AsyncStorageDatabase.ts +18 -10
  131. package/src/storage/adapter/InMemoryStore.ts +5 -1
  132. package/src/storage/adapter/IndexedDBAdapter.ts +50 -37
  133. package/src/storage/adapter/StorageAdapterBase.ts +24 -18
  134. package/src/storage/adapter/getDefaultAdapter/index.native.ts +1 -0
  135. package/src/storage/adapter/getDefaultAdapter/index.ts +4 -1
  136. package/src/storage/adapter/index.ts +2 -2
  137. package/src/storage/relationship.ts +5 -1
  138. package/src/storage/storage.ts +38 -30
  139. package/src/sync/datastoreConnectivity.ts +4 -6
  140. package/src/sync/index.ts +228 -230
  141. package/src/sync/merger.ts +4 -3
  142. package/src/sync/outbox.ts +26 -24
  143. package/src/sync/processors/errorMaps.ts +5 -0
  144. package/src/sync/processors/mutation.ts +80 -72
  145. package/src/sync/processors/subscription.ts +69 -53
  146. package/src/sync/processors/sync.ts +49 -37
  147. package/src/sync/utils.ts +60 -41
  148. package/src/types.ts +165 -165
  149. package/src/util.ts +89 -53
@@ -1 +1 @@
1
- {"version":3,"file":"subscription.mjs","sources":["../../../../src/sync/processors/subscription.ts"],"sourcesContent":["import { InternalAPI } from '@aws-amplify/api/internals';\nimport { Hub, fetchAuthSession, ConsoleLogger, } from '@aws-amplify/core';\nimport { Category, DataStoreAction, BackgroundProcessManager, } from '@aws-amplify/core/internals/utils';\nimport { Observable } from 'rxjs';\nimport { ProcessName, } from '../../types';\nimport { buildSubscriptionGraphQLOperation, getAuthorizationRules, getModelAuthModes, getUserGroupsFromToken, TransformerMutationType, getTokenForCustomAuth, predicateToGraphQLFilter, RTFError, generateRTFRemediation, } from '../utils';\nimport { ModelPredicateCreator } from '../../predicates';\nimport { validatePredicate } from '../../util';\nimport { getSubscriptionErrorType } from './errorMaps';\nimport { CONTROL_MSG as PUBSUB_CONTROL_MSG } from '@aws-amplify/api-graphql';\nconst logger = new ConsoleLogger('DataStore');\nexport var CONTROL_MSG;\n(function (CONTROL_MSG) {\n CONTROL_MSG[\"CONNECTED\"] = \"CONNECTED\";\n})(CONTROL_MSG || (CONTROL_MSG = {}));\nexport var USER_CREDENTIALS;\n(function (USER_CREDENTIALS) {\n USER_CREDENTIALS[USER_CREDENTIALS[\"none\"] = 0] = \"none\";\n USER_CREDENTIALS[USER_CREDENTIALS[\"unauth\"] = 1] = \"unauth\";\n USER_CREDENTIALS[USER_CREDENTIALS[\"auth\"] = 2] = \"auth\";\n})(USER_CREDENTIALS || (USER_CREDENTIALS = {}));\nclass SubscriptionProcessor {\n constructor(schema, syncPredicates, amplifyConfig = {}, authModeStrategy, errorHandler, amplifyContext = {\n InternalAPI,\n }) {\n this.schema = schema;\n this.syncPredicates = syncPredicates;\n this.amplifyConfig = amplifyConfig;\n this.authModeStrategy = authModeStrategy;\n this.errorHandler = errorHandler;\n this.amplifyContext = amplifyContext;\n this.typeQuery = new WeakMap();\n this.buffer = [];\n this.runningProcesses = new BackgroundProcessManager();\n }\n buildSubscription(namespace, model, transformerMutationType, userCredentials, oidcTokenPayload, authMode, filterArg = false) {\n const { aws_appsync_authenticationType } = this.amplifyConfig;\n const { isOwner, ownerField, ownerValue } = this.getAuthorizationInfo(model, userCredentials, aws_appsync_authenticationType, oidcTokenPayload, authMode) || {};\n const [opType, opName, query] = buildSubscriptionGraphQLOperation(namespace, model, transformerMutationType, isOwner, ownerField, filterArg);\n return { authMode, opType, opName, query, isOwner, ownerField, ownerValue };\n }\n getAuthorizationInfo(model, userCredentials, defaultAuthType, oidcTokenPayload, authMode) {\n const rules = getAuthorizationRules(model);\n // Return null if user doesn't have proper credentials for private API with IAM auth\n const iamPrivateAuth = authMode === 'iam' &&\n rules.find(rule => rule.authStrategy === 'private' && rule.provider === 'iam');\n if (iamPrivateAuth && userCredentials === USER_CREDENTIALS.unauth) {\n return null;\n }\n // Group auth should take precedence over owner auth, so we are checking\n // if rule(s) have group authorization as well as if either the Cognito or\n // OIDC token has a groupClaim. If so, we are returning auth info before\n // any further owner-based auth checks.\n const groupAuthRules = rules.filter(rule => rule.authStrategy === 'groups' &&\n ['userPools', 'oidc'].includes(rule.provider));\n const validGroup = (authMode === 'oidc' || authMode === 'userPool') &&\n groupAuthRules.find(groupAuthRule => {\n // validate token against groupClaim\n if (oidcTokenPayload) {\n const oidcUserGroups = getUserGroupsFromToken(oidcTokenPayload, groupAuthRule);\n return [...oidcUserGroups].find(userGroup => {\n return groupAuthRule.groups.find(group => group === userGroup);\n });\n }\n });\n if (validGroup) {\n return {\n authMode,\n isOwner: false,\n };\n }\n let ownerAuthInfo;\n if (ownerAuthInfo) {\n return ownerAuthInfo;\n }\n // Owner auth needs additional values to be returned in order to create the subscription with\n // the correct parameters so we are getting the owner value from the OIDC token via the\n // identityClaim from the auth rule.\n const oidcOwnerAuthRules = authMode === 'oidc' || authMode === 'userPool'\n ? rules.filter(rule => rule.authStrategy === 'owner' &&\n (rule.provider === 'oidc' || rule.provider === 'userPools'))\n : [];\n oidcOwnerAuthRules.forEach(ownerAuthRule => {\n const ownerValue = oidcTokenPayload[ownerAuthRule.identityClaim];\n const singleOwner = model.fields[ownerAuthRule.ownerField]?.isArray !== true;\n const isOwnerArgRequired = singleOwner && !ownerAuthRule.areSubscriptionsPublic;\n if (ownerValue) {\n ownerAuthInfo = {\n authMode,\n isOwner: isOwnerArgRequired,\n ownerField: ownerAuthRule.ownerField,\n ownerValue: String(ownerValue),\n };\n }\n });\n if (ownerAuthInfo) {\n return ownerAuthInfo;\n }\n // Fallback: return authMode or default auth type\n return {\n authMode: authMode || defaultAuthType,\n isOwner: false,\n };\n }\n hubQueryCompletionListener(completed, capsule) {\n const { payload: { event }, } = capsule;\n if (event === PUBSUB_CONTROL_MSG.SUBSCRIPTION_ACK) {\n completed();\n }\n }\n start() {\n this.runningProcesses =\n this.runningProcesses || new BackgroundProcessManager();\n const ctlObservable = new Observable(observer => {\n const promises = [];\n // Creating subs for each model/operation combo so they can be unsubscribed\n // independently, since the auth retry behavior is asynchronous.\n let subscriptions = {};\n let oidcTokenPayload;\n let userCredentials = USER_CREDENTIALS.none;\n this.runningProcesses.add(async () => {\n try {\n // retrieving current AWS Credentials\n const credentials = (await fetchAuthSession()).tokens?.accessToken;\n userCredentials = credentials\n ? USER_CREDENTIALS.auth\n : USER_CREDENTIALS.unauth;\n }\n catch (err) {\n // best effort to get AWS credentials\n }\n try {\n // retrieving current token info from Cognito UserPools\n const session = await fetchAuthSession();\n oidcTokenPayload = session.tokens?.idToken?.payload;\n }\n catch (err) {\n // best effort to get jwt from Cognito\n }\n Object.values(this.schema.namespaces).forEach(namespace => {\n Object.values(namespace.models)\n .filter(({ syncable }) => syncable)\n .forEach(modelDefinition => this.runningProcesses.isOpen &&\n this.runningProcesses.add(async () => {\n const modelAuthModes = await getModelAuthModes({\n authModeStrategy: this.authModeStrategy,\n defaultAuthMode: this.amplifyConfig.aws_appsync_authenticationType,\n modelName: modelDefinition.name,\n schema: this.schema,\n });\n // subscriptions are created only based on the READ auth mode(s)\n const readAuthModes = modelAuthModes.READ;\n subscriptions = {\n ...subscriptions,\n [modelDefinition.name]: {\n [TransformerMutationType.CREATE]: [],\n [TransformerMutationType.UPDATE]: [],\n [TransformerMutationType.DELETE]: [],\n },\n };\n const operations = [\n TransformerMutationType.CREATE,\n TransformerMutationType.UPDATE,\n TransformerMutationType.DELETE,\n ];\n const operationAuthModeAttempts = {\n [TransformerMutationType.CREATE]: 0,\n [TransformerMutationType.UPDATE]: 0,\n [TransformerMutationType.DELETE]: 0,\n };\n const predicatesGroup = ModelPredicateCreator.getPredicates(this.syncPredicates.get(modelDefinition), false);\n const addFilterArg = predicatesGroup !== undefined;\n // Retry subscriptions that failed for one of the following reasons:\n // 1. unauthorized - retry with next auth mode (if available)\n // 2. RTF error - retry without sending filter arg. (filtering will fall back to clientside)\n const subscriptionRetry = async (operation, addFilter = addFilterArg) => {\n const { opType: transformerMutationType, opName, query, isOwner, ownerField, ownerValue, authMode, } = this.buildSubscription(namespace, modelDefinition, operation, userCredentials, oidcTokenPayload, readAuthModes[operationAuthModeAttempts[operation]], addFilter);\n const authToken = await getTokenForCustomAuth(authMode, this.amplifyConfig);\n const variables = {};\n const customUserAgentDetails = {\n category: Category.DataStore,\n action: DataStoreAction.Subscribe,\n };\n if (addFilter && predicatesGroup) {\n variables['filter'] =\n predicateToGraphQLFilter(predicatesGroup);\n }\n if (isOwner) {\n if (!ownerValue) {\n observer.error('Owner field required, sign in is needed in order to perform this operation');\n return;\n }\n variables[ownerField] = ownerValue;\n }\n logger.debug(`Attempting ${operation} subscription with authMode: ${readAuthModes[operationAuthModeAttempts[operation]]}`);\n const queryObservable = this.amplifyContext.InternalAPI.graphql({\n query,\n variables,\n ...{ authMode },\n authToken,\n }, undefined, customUserAgentDetails);\n let subscriptionReadyCallback;\n // TODO: consider onTerminate.then(() => API.cancel(...))\n subscriptions[modelDefinition.name][transformerMutationType].push(queryObservable.subscribe({\n next: result => {\n const { data, errors } = result;\n if (Array.isArray(errors) && errors.length > 0) {\n const messages = errors.map(({ message }) => message);\n logger.warn(`Skipping incoming subscription. Messages: ${messages.join('\\n')}`);\n this.drainBuffer();\n return;\n }\n const predicatesGroup = ModelPredicateCreator.getPredicates(this.syncPredicates.get(modelDefinition), false);\n // @ts-ignore\n const { [opName]: record } = data;\n // checking incoming subscription against syncPredicate.\n // once AppSync implements filters on subscriptions, we'll be\n // able to set these when establishing the subscription instead.\n // Until then, we'll need to filter inbound\n if (this.passesPredicateValidation(record, predicatesGroup)) {\n this.pushToBuffer(transformerMutationType, modelDefinition, record);\n }\n this.drainBuffer();\n },\n error: async (subscriptionError) => {\n const { errors: [{ message = '' } = {}], } = ({\n errors: [],\n } = subscriptionError);\n const isRTFError = \n // only attempt catch if a filter variable was added to the subscription query\n addFilter &&\n this.catchRTFError(message, modelDefinition, predicatesGroup);\n // Catch RTF errors\n if (isRTFError) {\n // Unsubscribe and clear subscription array for model/operation\n subscriptions[modelDefinition.name][transformerMutationType].forEach(subscription => subscription.unsubscribe());\n subscriptions[modelDefinition.name][transformerMutationType] = [];\n // retry subscription connection without filter\n subscriptionRetry(operation, false);\n return;\n }\n if (message.includes(PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR) ||\n message.includes(PUBSUB_CONTROL_MSG.CONNECTION_FAILED)) {\n // Unsubscribe and clear subscription array for model/operation\n subscriptions[modelDefinition.name][transformerMutationType].forEach(subscription => subscription.unsubscribe());\n subscriptions[modelDefinition.name][transformerMutationType] = [];\n operationAuthModeAttempts[operation]++;\n if (operationAuthModeAttempts[operation] >=\n readAuthModes.length) {\n // last auth mode retry. Continue with error\n logger.debug(`${operation} subscription failed with authMode: ${readAuthModes[operationAuthModeAttempts[operation] - 1]}`);\n }\n else {\n // retry with different auth mode. Do not trigger\n // observer error or error handler\n logger.debug(`${operation} subscription failed with authMode: ${readAuthModes[operationAuthModeAttempts[operation] - 1]}. Retrying with authMode: ${readAuthModes[operationAuthModeAttempts[operation]]}`);\n subscriptionRetry(operation);\n return;\n }\n }\n logger.warn('subscriptionError', message);\n try {\n await this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message,\n model: modelDefinition.name,\n operation,\n errorType: getSubscriptionErrorType(subscriptionError),\n process: ProcessName.subscribe,\n remoteModel: null,\n cause: subscriptionError,\n });\n }\n catch (e) {\n logger.error('Subscription error handler failed with:', e);\n }\n if (typeof subscriptionReadyCallback === 'function') {\n subscriptionReadyCallback();\n }\n if (message.includes('\"errorType\":\"Unauthorized\"') ||\n message.includes('\"errorType\":\"OperationDisabled\"')) {\n return;\n }\n observer.error(message);\n },\n }));\n promises.push((async () => {\n let boundFunction;\n let removeBoundFunctionListener;\n await new Promise(res => {\n subscriptionReadyCallback = res;\n boundFunction = this.hubQueryCompletionListener.bind(this, res);\n removeBoundFunctionListener = Hub.listen('api', boundFunction);\n });\n removeBoundFunctionListener();\n })());\n };\n operations.forEach(op => subscriptionRetry(op));\n }));\n });\n this.runningProcesses.isOpen &&\n this.runningProcesses.add(() => Promise.all(promises).then(() => {\n observer.next(CONTROL_MSG.CONNECTED);\n }));\n }, 'subscription processor new subscriber');\n return this.runningProcesses.addCleaner(async () => {\n Object.keys(subscriptions).forEach(modelName => {\n subscriptions[modelName][TransformerMutationType.CREATE].forEach(subscription => subscription.unsubscribe());\n subscriptions[modelName][TransformerMutationType.UPDATE].forEach(subscription => subscription.unsubscribe());\n subscriptions[modelName][TransformerMutationType.DELETE].forEach(subscription => subscription.unsubscribe());\n });\n });\n });\n const dataObservable = new Observable(observer => {\n this.dataObserver = observer;\n this.drainBuffer();\n return this.runningProcesses.addCleaner(async () => {\n this.dataObserver = null;\n });\n });\n return [ctlObservable, dataObservable];\n }\n async stop() {\n await this.runningProcesses.close();\n await this.runningProcesses.open();\n }\n passesPredicateValidation(record, predicatesGroup) {\n if (!predicatesGroup) {\n return true;\n }\n const { predicates, type } = predicatesGroup;\n return validatePredicate(record, type, predicates);\n }\n pushToBuffer(transformerMutationType, modelDefinition, data) {\n this.buffer.push([transformerMutationType, modelDefinition, data]);\n }\n drainBuffer() {\n if (this.dataObserver) {\n this.buffer.forEach(data => this.dataObserver.next(data));\n this.buffer = [];\n }\n }\n /**\n * @returns true if the service returned an RTF subscription error\n * @remarks logs a warning with remediation instructions\n *\n */\n catchRTFError(message, modelDefinition, predicatesGroup) {\n const header = 'Backend subscriptions filtering error.\\n' +\n 'Subscriptions filtering will be applied clientside.\\n';\n const messageErrorTypeMap = {\n 'UnknownArgument: Unknown field argument filter': RTFError.UnknownField,\n 'Filters exceed maximum attributes limit': RTFError.MaxAttributes,\n 'Filters combination exceed maximum limit': RTFError.MaxCombinations,\n 'filter uses same fieldName multiple time': RTFError.RepeatedFieldname,\n \"The variables input contains a field name 'not'\": RTFError.NotGroup,\n 'The variables input contains a field that is not defined for input object type': RTFError.FieldNotInType,\n };\n const [_errorMsg, errorType] = Object.entries(messageErrorTypeMap).find(([errorMsg]) => message.includes(errorMsg)) || [];\n if (errorType !== undefined) {\n const remediationMessage = generateRTFRemediation(errorType, modelDefinition, predicatesGroup);\n logger.warn(`${header}\\n${message}\\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C,OAAO,CAAC,mBAAmB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;AAClI,QAAQ,IAAI,SAAS,KAAK,SAAS,EAAE;AACrC,YAAY,MAAM,kBAAkB,GAAG,sBAAsB,CAAC,SAAS,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;AAC3G,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC;AACxE,YAAY,OAAO,IAAI,CAAC;AACxB,SAAS;AACT,QAAQ,OAAO,KAAK,CAAC;AACrB,KAAK;AACL;;;;"}
1
+ {"version":3,"file":"subscription.mjs","sources":["../../../../src/sync/processors/subscription.ts"],"sourcesContent":["import { InternalAPI } from '@aws-amplify/api/internals';\nimport { ConsoleLogger, Hub, fetchAuthSession, } from '@aws-amplify/core';\nimport { BackgroundProcessManager, Category, DataStoreAction, } from '@aws-amplify/core/internals/utils';\nimport { Observable } from 'rxjs';\nimport { CONTROL_MSG as PUBSUB_CONTROL_MSG } from '@aws-amplify/api-graphql';\nimport { ProcessName, } from '../../types';\nimport { RTFError, TransformerMutationType, buildSubscriptionGraphQLOperation, generateRTFRemediation, getAuthorizationRules, getModelAuthModes, getTokenForCustomAuth, getUserGroupsFromToken, predicateToGraphQLFilter, } from '../utils';\nimport { ModelPredicateCreator } from '../../predicates';\nimport { validatePredicate } from '../../util';\nimport { getSubscriptionErrorType } from './errorMaps';\nconst logger = new ConsoleLogger('DataStore');\nexport var CONTROL_MSG;\n(function (CONTROL_MSG) {\n CONTROL_MSG[\"CONNECTED\"] = \"CONNECTED\";\n})(CONTROL_MSG || (CONTROL_MSG = {}));\nexport var USER_CREDENTIALS;\n(function (USER_CREDENTIALS) {\n USER_CREDENTIALS[USER_CREDENTIALS[\"none\"] = 0] = \"none\";\n USER_CREDENTIALS[USER_CREDENTIALS[\"unauth\"] = 1] = \"unauth\";\n USER_CREDENTIALS[USER_CREDENTIALS[\"auth\"] = 2] = \"auth\";\n})(USER_CREDENTIALS || (USER_CREDENTIALS = {}));\nclass SubscriptionProcessor {\n constructor(schema, syncPredicates, amplifyConfig = {}, authModeStrategy, errorHandler, amplifyContext = {\n InternalAPI,\n }) {\n this.schema = schema;\n this.syncPredicates = syncPredicates;\n this.amplifyConfig = amplifyConfig;\n this.authModeStrategy = authModeStrategy;\n this.errorHandler = errorHandler;\n this.amplifyContext = amplifyContext;\n this.typeQuery = new WeakMap();\n this.buffer = [];\n this.runningProcesses = new BackgroundProcessManager();\n }\n buildSubscription(namespace, model, transformerMutationType, userCredentials, oidcTokenPayload, authMode, filterArg = false) {\n const { aws_appsync_authenticationType } = this.amplifyConfig;\n const { isOwner, ownerField, ownerValue } = this.getAuthorizationInfo(model, userCredentials, aws_appsync_authenticationType, oidcTokenPayload, authMode) || {};\n const [opType, opName, query] = buildSubscriptionGraphQLOperation(namespace, model, transformerMutationType, isOwner, ownerField, filterArg);\n return { authMode, opType, opName, query, isOwner, ownerField, ownerValue };\n }\n getAuthorizationInfo(model, userCredentials, defaultAuthType, oidcTokenPayload, authMode) {\n const rules = getAuthorizationRules(model);\n // Return null if user doesn't have proper credentials for private API with IAM auth\n const iamPrivateAuth = authMode === 'iam' &&\n rules.find(rule => rule.authStrategy === 'private' && rule.provider === 'iam');\n if (iamPrivateAuth && userCredentials === USER_CREDENTIALS.unauth) {\n return null;\n }\n // Group auth should take precedence over owner auth, so we are checking\n // if rule(s) have group authorization as well as if either the Cognito or\n // OIDC token has a groupClaim. If so, we are returning auth info before\n // any further owner-based auth checks.\n const groupAuthRules = rules.filter(rule => rule.authStrategy === 'groups' &&\n ['userPools', 'oidc'].includes(rule.provider));\n const validGroup = (authMode === 'oidc' || authMode === 'userPool') &&\n // eslint-disable-next-line array-callback-return\n groupAuthRules.find(groupAuthRule => {\n // validate token against groupClaim\n if (oidcTokenPayload) {\n const oidcUserGroups = getUserGroupsFromToken(oidcTokenPayload, groupAuthRule);\n return [...oidcUserGroups].find(userGroup => {\n return groupAuthRule.groups.find(group => group === userGroup);\n });\n }\n });\n if (validGroup) {\n return {\n authMode,\n isOwner: false,\n };\n }\n let ownerAuthInfo;\n if (ownerAuthInfo) {\n return ownerAuthInfo;\n }\n // Owner auth needs additional values to be returned in order to create the subscription with\n // the correct parameters so we are getting the owner value from the OIDC token via the\n // identityClaim from the auth rule.\n const oidcOwnerAuthRules = authMode === 'oidc' || authMode === 'userPool'\n ? rules.filter(rule => rule.authStrategy === 'owner' &&\n (rule.provider === 'oidc' || rule.provider === 'userPools'))\n : [];\n oidcOwnerAuthRules.forEach(ownerAuthRule => {\n const ownerValue = oidcTokenPayload[ownerAuthRule.identityClaim];\n const singleOwner = model.fields[ownerAuthRule.ownerField]?.isArray !== true;\n const isOwnerArgRequired = singleOwner && !ownerAuthRule.areSubscriptionsPublic;\n if (ownerValue) {\n ownerAuthInfo = {\n authMode,\n isOwner: isOwnerArgRequired,\n ownerField: ownerAuthRule.ownerField,\n ownerValue: String(ownerValue),\n };\n }\n });\n if (ownerAuthInfo) {\n return ownerAuthInfo;\n }\n // Fallback: return authMode or default auth type\n return {\n authMode: authMode || defaultAuthType,\n isOwner: false,\n };\n }\n hubQueryCompletionListener(completed, capsule) {\n const { payload: { event }, } = capsule;\n if (event === PUBSUB_CONTROL_MSG.SUBSCRIPTION_ACK) {\n completed();\n }\n }\n start() {\n this.runningProcesses =\n this.runningProcesses || new BackgroundProcessManager();\n const ctlObservable = new Observable(observer => {\n const promises = [];\n // Creating subs for each model/operation combo so they can be unsubscribed\n // independently, since the auth retry behavior is asynchronous.\n let subscriptions = {};\n let oidcTokenPayload;\n let userCredentials = USER_CREDENTIALS.none;\n this.runningProcesses.add(async () => {\n try {\n // retrieving current AWS Credentials\n const credentials = (await fetchAuthSession()).tokens?.accessToken;\n userCredentials = credentials\n ? USER_CREDENTIALS.auth\n : USER_CREDENTIALS.unauth;\n }\n catch (err) {\n // best effort to get AWS credentials\n }\n try {\n // retrieving current token info from Cognito UserPools\n const session = await fetchAuthSession();\n oidcTokenPayload = session.tokens?.idToken?.payload;\n }\n catch (err) {\n // best effort to get jwt from Cognito\n }\n Object.values(this.schema.namespaces).forEach(namespace => {\n Object.values(namespace.models)\n .filter(({ syncable }) => syncable)\n .forEach(modelDefinition => this.runningProcesses.isOpen &&\n this.runningProcesses.add(async () => {\n const modelAuthModes = await getModelAuthModes({\n authModeStrategy: this.authModeStrategy,\n defaultAuthMode: this.amplifyConfig.aws_appsync_authenticationType,\n modelName: modelDefinition.name,\n schema: this.schema,\n });\n // subscriptions are created only based on the READ auth mode(s)\n const readAuthModes = modelAuthModes.READ;\n subscriptions = {\n ...subscriptions,\n [modelDefinition.name]: {\n [TransformerMutationType.CREATE]: [],\n [TransformerMutationType.UPDATE]: [],\n [TransformerMutationType.DELETE]: [],\n },\n };\n const operations = [\n TransformerMutationType.CREATE,\n TransformerMutationType.UPDATE,\n TransformerMutationType.DELETE,\n ];\n const operationAuthModeAttempts = {\n [TransformerMutationType.CREATE]: 0,\n [TransformerMutationType.UPDATE]: 0,\n [TransformerMutationType.DELETE]: 0,\n };\n const predicatesGroup = ModelPredicateCreator.getPredicates(this.syncPredicates.get(modelDefinition), false);\n const addFilterArg = predicatesGroup !== undefined;\n // Retry subscriptions that failed for one of the following reasons:\n // 1. unauthorized - retry with next auth mode (if available)\n // 2. RTF error - retry without sending filter arg. (filtering will fall back to clientside)\n const subscriptionRetry = async (operation, addFilter = addFilterArg) => {\n const { opType: transformerMutationType, opName, query, isOwner, ownerField, ownerValue, authMode, } = this.buildSubscription(namespace, modelDefinition, operation, userCredentials, oidcTokenPayload, readAuthModes[operationAuthModeAttempts[operation]], addFilter);\n const authToken = await getTokenForCustomAuth(authMode, this.amplifyConfig);\n const variables = {};\n const customUserAgentDetails = {\n category: Category.DataStore,\n action: DataStoreAction.Subscribe,\n };\n if (addFilter && predicatesGroup) {\n variables.filter =\n predicateToGraphQLFilter(predicatesGroup);\n }\n if (isOwner) {\n if (!ownerValue) {\n observer.error('Owner field required, sign in is needed in order to perform this operation');\n return;\n }\n variables[ownerField] = ownerValue;\n }\n logger.debug(`Attempting ${operation} subscription with authMode: ${readAuthModes[operationAuthModeAttempts[operation]]}`);\n const queryObservable = this.amplifyContext.InternalAPI.graphql({\n query,\n variables,\n ...{ authMode },\n authToken,\n }, undefined, customUserAgentDetails);\n let subscriptionReadyCallback;\n // TODO: consider onTerminate.then(() => API.cancel(...))\n subscriptions[modelDefinition.name][transformerMutationType].push(queryObservable.subscribe({\n next: result => {\n const { data, errors } = result;\n if (Array.isArray(errors) && errors.length > 0) {\n const messages = errors.map(({ message }) => message);\n logger.warn(`Skipping incoming subscription. Messages: ${messages.join('\\n')}`);\n this.drainBuffer();\n return;\n }\n const resolvedPredicatesGroup = ModelPredicateCreator.getPredicates(this.syncPredicates.get(modelDefinition), false);\n const { [opName]: record } = data;\n // checking incoming subscription against syncPredicate.\n // once AppSync implements filters on subscriptions, we'll be\n // able to set these when establishing the subscription instead.\n // Until then, we'll need to filter inbound\n if (this.passesPredicateValidation(record, resolvedPredicatesGroup)) {\n this.pushToBuffer(transformerMutationType, modelDefinition, record);\n }\n this.drainBuffer();\n },\n error: async (subscriptionError) => {\n const { errors: [{ message = '' } = {}], } = ({\n // eslint-disable-next-line no-empty-pattern\n errors: [],\n } = subscriptionError);\n const isRTFError = \n // only attempt catch if a filter variable was added to the subscription query\n addFilter &&\n this.catchRTFError(message, modelDefinition, predicatesGroup);\n // Catch RTF errors\n if (isRTFError) {\n // Unsubscribe and clear subscription array for model/operation\n subscriptions[modelDefinition.name][transformerMutationType].forEach(subscription => subscription.unsubscribe());\n subscriptions[modelDefinition.name][transformerMutationType] = [];\n // retry subscription connection without filter\n subscriptionRetry(operation, false);\n return;\n }\n if (message.includes(PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR) ||\n message.includes(PUBSUB_CONTROL_MSG.CONNECTION_FAILED)) {\n // Unsubscribe and clear subscription array for model/operation\n subscriptions[modelDefinition.name][transformerMutationType].forEach(subscription => subscription.unsubscribe());\n subscriptions[modelDefinition.name][transformerMutationType] = [];\n operationAuthModeAttempts[operation]++;\n if (operationAuthModeAttempts[operation] >=\n readAuthModes.length) {\n // last auth mode retry. Continue with error\n logger.debug(`${operation} subscription failed with authMode: ${readAuthModes[operationAuthModeAttempts[operation] - 1]}`);\n }\n else {\n // retry with different auth mode. Do not trigger\n // observer error or error handler\n logger.debug(`${operation} subscription failed with authMode: ${readAuthModes[operationAuthModeAttempts[operation] - 1]}. Retrying with authMode: ${readAuthModes[operationAuthModeAttempts[operation]]}`);\n subscriptionRetry(operation);\n return;\n }\n }\n logger.warn('subscriptionError', message);\n try {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n await this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message,\n model: modelDefinition.name,\n operation,\n errorType: getSubscriptionErrorType(subscriptionError),\n process: ProcessName.subscribe,\n remoteModel: null,\n cause: subscriptionError,\n });\n }\n catch (e) {\n logger.error('Subscription error handler failed with:', e);\n }\n if (typeof subscriptionReadyCallback === 'function') {\n subscriptionReadyCallback();\n }\n if (message.includes('\"errorType\":\"Unauthorized\"') ||\n message.includes('\"errorType\":\"OperationDisabled\"')) {\n return;\n }\n observer.error(message);\n },\n }));\n promises.push((async () => {\n let boundFunction;\n let removeBoundFunctionListener;\n await new Promise(resolve => {\n subscriptionReadyCallback = resolve;\n boundFunction = this.hubQueryCompletionListener.bind(this, resolve);\n removeBoundFunctionListener = Hub.listen('api', boundFunction);\n });\n removeBoundFunctionListener();\n })());\n };\n operations.forEach(op => subscriptionRetry(op));\n }));\n });\n this.runningProcesses.isOpen &&\n this.runningProcesses.add(() => Promise.all(promises).then(() => {\n observer.next(CONTROL_MSG.CONNECTED);\n }));\n }, 'subscription processor new subscriber');\n return this.runningProcesses.addCleaner(async () => {\n Object.keys(subscriptions).forEach(modelName => {\n subscriptions[modelName][TransformerMutationType.CREATE].forEach(subscription => {\n subscription.unsubscribe();\n });\n subscriptions[modelName][TransformerMutationType.UPDATE].forEach(subscription => {\n subscription.unsubscribe();\n });\n subscriptions[modelName][TransformerMutationType.DELETE].forEach(subscription => {\n subscription.unsubscribe();\n });\n });\n });\n });\n const dataObservable = new Observable(observer => {\n this.dataObserver = observer;\n this.drainBuffer();\n return this.runningProcesses.addCleaner(async () => {\n this.dataObserver = null;\n });\n });\n return [ctlObservable, dataObservable];\n }\n async stop() {\n await this.runningProcesses.close();\n await this.runningProcesses.open();\n }\n passesPredicateValidation(record, predicatesGroup) {\n if (!predicatesGroup) {\n return true;\n }\n const { predicates, type } = predicatesGroup;\n return validatePredicate(record, type, predicates);\n }\n pushToBuffer(transformerMutationType, modelDefinition, data) {\n this.buffer.push([transformerMutationType, modelDefinition, data]);\n }\n drainBuffer() {\n if (this.dataObserver) {\n this.buffer.forEach(data => {\n this.dataObserver.next(data);\n });\n this.buffer = [];\n }\n }\n /**\n * @returns true if the service returned an RTF subscription error\n * @remarks logs a warning with remediation instructions\n *\n */\n catchRTFError(message, modelDefinition, predicatesGroup) {\n const header = 'Backend subscriptions filtering error.\\n' +\n 'Subscriptions filtering will be applied clientside.\\n';\n const messageErrorTypeMap = {\n 'UnknownArgument: Unknown field argument filter': RTFError.UnknownField,\n 'Filters exceed maximum attributes limit': RTFError.MaxAttributes,\n 'Filters combination exceed maximum limit': RTFError.MaxCombinations,\n 'filter uses same fieldName multiple time': RTFError.RepeatedFieldname,\n \"The variables input contains a field name 'not'\": RTFError.NotGroup,\n 'The variables input contains a field that is not defined for input object type': RTFError.FieldNotInType,\n };\n const [_errorMsg, errorType] = Object.entries(messageErrorTypeMap).find(([errorMsg]) => message.includes(errorMsg)) || [];\n if (errorType !== undefined) {\n const remediationMessage = generateRTFRemediation(errorType, modelDefinition, predicatesGroup);\n logger.warn(`${header}\\n${message}\\n${remediationMessage}`);\n return true;\n }\n return false;\n }\n}\nexport { SubscriptionProcessor };\n"],"names":["PUBSUB_CONTROL_MSG"],"mappings":";;;;;;;;;;;AAUA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,WAAW,CAAC,CAAC;AACpC,IAAC,YAAY;AACvB,CAAC,UAAU,WAAW,EAAE;AACxB,IAAI,WAAW,CAAC,WAAW,CAAC,GAAG,WAAW,CAAC;AAC3C,CAAC,EAAE,WAAW,KAAK,WAAW,GAAG,EAAE,CAAC,CAAC,CAAC;AAC5B,IAAC,iBAAiB;AAC5B,CAAC,UAAU,gBAAgB,EAAE;AAC7B,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC;AAC5D,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,QAAQ,CAAC;AAChE,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC;AAC5D,CAAC,EAAE,gBAAgB,KAAK,gBAAgB,GAAG,EAAE,CAAC,CAAC,CAAC;AAChD,MAAM,qBAAqB,CAAC;AAC5B,IAAI,WAAW,CAAC,MAAM,EAAE,cAAc,EAAE,aAAa,GAAG,EAAE,EAAE,gBAAgB,EAAE,YAAY,EAAE,cAAc,GAAG;AAC7G,QAAQ,WAAW;AACnB,KAAK,EAAE;AACP,QAAQ,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;AAC7B,QAAQ,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;AAC7C,QAAQ,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;AAC3C,QAAQ,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;AACjD,QAAQ,IAAI,CAAC,YAA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eAAe;AAChF,YAAY,0CAA0C,EAAE,QAAQ,CAAC,iBAAiB;AAClF,YAAY,iDAAiD,EAAE,QAAQ,CAAC,QAAQ;AAChF,YAAY,gFAAgF,EAAE,QAAQ,CAAC,cAAc;AACrH,SAAS,CAAC;AACV,QAAQ,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;AAClI,QAAQ,IAAI,SAAS,KAAK,SAAS,EAAE;AACrC,YAAY,MAAM,kBAAkB,GAAG,sBAAsB,CAAC,SAAS,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;AAC3G,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,kBAAkB,CAAC,CAAC,CAAC,CAAC;AACxE,YAAY,OAAO,IAAI,CAAC;AACxB,SAAS;AACT,QAAQ,OAAO,KAAK,CAAC;AACrB,KAAK;AACL;;;;"}
@@ -1,5 +1,5 @@
1
1
  import { Observable } from 'rxjs';
2
- import { InternalSchema, ModelInstanceMetadata, SchemaModel, ModelPredicate, AuthModeStrategy, ErrorHandler, AmplifyContext } from '../../types';
2
+ import { AmplifyContext, AuthModeStrategy, ErrorHandler, InternalSchema, ModelInstanceMetadata, ModelPredicate, SchemaModel } from '../../types';
3
3
  declare class SyncProcessor {
4
4
  private readonly schema;
5
5
  private readonly syncPredicates;
@@ -17,12 +17,12 @@ declare class SyncProcessor {
17
17
  start(typesLastSync: Map<SchemaModel, [string, number]>): Observable<SyncModelPage>;
18
18
  stop(): Promise<void>;
19
19
  }
20
- export type SyncModelPage = {
20
+ export interface SyncModelPage {
21
21
  namespace: string;
22
22
  modelDefinition: SchemaModel;
23
23
  items: ModelInstanceMetadata[];
24
24
  startedAt: number;
25
25
  done: boolean;
26
26
  isFullSync: boolean;
27
- };
27
+ }
28
28
  export { SyncProcessor };
@@ -1,9 +1,9 @@
1
1
  import { InternalAPI } from '@aws-amplify/api/internals';
2
2
  import { Observable } from 'rxjs';
3
- import { ProcessName } from '../../types.mjs';
4
- import { buildGraphQLOperation, predicateToGraphQLFilter, getModelAuthModes, getTokenForCustomAuth, getClientSideAuthError, getForbiddenError } from '../utils.mjs';
5
3
  import { BackgroundProcessManager, jitteredExponentialRetry, Category, DataStoreAction, NonRetryableError } from '@aws-amplify/core/internals/utils';
6
4
  import { ConsoleLogger, Hub } from '@aws-amplify/core';
5
+ import { ProcessName } from '../../types.mjs';
6
+ import { buildGraphQLOperation, predicateToGraphQLFilter, getModelAuthModes, getTokenForCustomAuth, getClientSideAuthError, getForbiddenError } from '../utils.mjs';
7
7
  import { ModelPredicateCreator } from '../../predicates/index.mjs';
8
8
  import { getSyncErrorType } from './errorMaps.mjs';
9
9
 
@@ -97,7 +97,7 @@ class SyncProcessor {
97
97
  throw error;
98
98
  }
99
99
  logger.debug(`Sync failed with authMode: ${readAuthModes[authModeAttempts - 1]}. Retrying with authMode: ${readAuthModes[authModeAttempts]}`);
100
- return await authModeRetry();
100
+ return authModeRetry();
101
101
  }
102
102
  };
103
103
  const { data } = await authModeRetry();
@@ -110,7 +110,7 @@ class SyncProcessor {
110
110
  };
111
111
  }
112
112
  async jitteredRetry({ query, variables, opName, modelDefinition, authMode, onTerminate, }) {
113
- return await jitteredExponentialRetry(async (query, variables) => {
113
+ return jitteredExponentialRetry(async (retriedQuery, retriedVariables) => {
114
114
  try {
115
115
  const authToken = await getTokenForCustomAuth(authMode, this.amplifyConfig);
116
116
  const customUserAgentDetails = {
@@ -118,8 +118,8 @@ class SyncProcessor {
118
118
  action: DataStoreAction.GraphQl,
119
119
  };
120
120
  return await this.amplifyContext.InternalAPI.graphql({
121
- query,
122
- variables,
121
+ query: retriedQuery,
122
+ variables: retriedVariables,
123
123
  authMode,
124
124
  authToken,
125
125
  }, undefined, customUserAgentDetails);
@@ -144,6 +144,7 @@ class SyncProcessor {
144
144
  if (hasItems && otherErrors?.length) {
145
145
  await Promise.all(otherErrors.map(async (err) => {
146
146
  try {
147
+ // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
147
148
  await this.errorHandler({
148
149
  recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',
149
150
  localModel: null,
@@ -236,7 +237,8 @@ class SyncProcessor {
236
237
  const filter = this.graphqlFilterFromPredicate(modelDefinition);
237
238
  const parents = this.schema.namespaces[namespace].modelTopologicalOrdering.get(modelDefinition.name);
238
239
  const promises = parents.map(parent => parentPromises.get(`${namespace}_${parent}`));
239
- const promise = new Promise(async (res) => {
240
+ // eslint-disable-next-line no-async-promise-executor
241
+ const promise = new Promise(async (resolve) => {
240
242
  await Promise.all(promises);
241
243
  do {
242
244
  /**
@@ -246,7 +248,8 @@ class SyncProcessor {
246
248
  */
247
249
  if (!this.runningProcesses.isOpen) {
248
250
  logger.debug(`Sync processor has been stopped, terminating sync for ${modelDefinition.name}`);
249
- return res();
251
+ resolve();
252
+ return;
250
253
  }
251
254
  const limit = Math.min(maxRecordsToSync - recordsReceived, syncPageSize);
252
255
  /**
@@ -259,6 +262,7 @@ class SyncProcessor {
259
262
  }
260
263
  catch (error) {
261
264
  try {
265
+ // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
262
266
  await this.errorHandler({
263
267
  recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',
264
268
  localModel: null,
@@ -296,7 +300,7 @@ class SyncProcessor {
296
300
  isFullSync: !lastSync,
297
301
  });
298
302
  } while (!done);
299
- res();
303
+ resolve();
300
304
  });
301
305
  parentPromises.set(`${namespace}_${modelDefinition.name}`, promise);
302
306
  await promise;
@@ -1 +1 @@
1
- {"version":3,"file":"sync.mjs","sources":["../../../../src/sync/processors/sync.ts"],"sourcesContent":["import { InternalAPI } from '@aws-amplify/api/internals';\nimport { Observable } from 'rxjs';\nimport { ProcessName, } from '../../types';\nimport { buildGraphQLOperation, getModelAuthModes, getClientSideAuthError, getForbiddenError, predicateToGraphQLFilter, getTokenForCustomAuth, } from '../utils';\nimport { jitteredExponentialRetry, Category, DataStoreAction, NonRetryableError, BackgroundProcessManager, } from '@aws-amplify/core/internals/utils';\nimport { ConsoleLogger, Hub } from '@aws-amplify/core';\nimport { ModelPredicateCreator } from '../../predicates';\nimport { getSyncErrorType } from './errorMaps';\nconst opResultDefaults = {\n items: [],\n nextToken: null,\n startedAt: null,\n};\nconst logger = new ConsoleLogger('DataStore');\nclass SyncProcessor {\n constructor(schema, syncPredicates, amplifyConfig = {}, authModeStrategy, errorHandler, amplifyContext) {\n this.schema = schema;\n this.syncPredicates = syncPredicates;\n this.amplifyConfig = amplifyConfig;\n this.authModeStrategy = authModeStrategy;\n this.errorHandler = errorHandler;\n this.amplifyContext = amplifyContext;\n this.typeQuery = new WeakMap();\n this.runningProcesses = new BackgroundProcessManager();\n amplifyContext.InternalAPI = amplifyContext.InternalAPI || InternalAPI;\n this.generateQueries();\n }\n generateQueries() {\n Object.values(this.schema.namespaces).forEach(namespace => {\n Object.values(namespace.models)\n .filter(({ syncable }) => syncable)\n .forEach(model => {\n const [[, ...opNameQuery]] = buildGraphQLOperation(namespace, model, 'LIST');\n this.typeQuery.set(model, opNameQuery);\n });\n });\n }\n graphqlFilterFromPredicate(model) {\n if (!this.syncPredicates) {\n return null;\n }\n const predicatesGroup = ModelPredicateCreator.getPredicates(this.syncPredicates.get(model), false);\n if (!predicatesGroup) {\n return null;\n }\n return predicateToGraphQLFilter(predicatesGroup);\n }\n async retrievePage(modelDefinition, lastSync, nextToken, limit = null, filter, onTerminate) {\n const [opName, query] = this.typeQuery.get(modelDefinition);\n const variables = {\n limit,\n nextToken,\n lastSync,\n filter,\n };\n const modelAuthModes = await getModelAuthModes({\n authModeStrategy: this.authModeStrategy,\n defaultAuthMode: this.amplifyConfig.aws_appsync_authenticationType,\n modelName: modelDefinition.name,\n schema: this.schema,\n });\n // sync only needs the READ auth mode(s)\n const readAuthModes = modelAuthModes.READ;\n let authModeAttempts = 0;\n const authModeRetry = async () => {\n if (!this.runningProcesses.isOpen) {\n throw new Error('sync.retreievePage termination was requested. Exiting.');\n }\n try {\n logger.debug(`Attempting sync with authMode: ${readAuthModes[authModeAttempts]}`);\n const response = await this.jitteredRetry({\n query,\n variables,\n opName,\n modelDefinition,\n authMode: readAuthModes[authModeAttempts],\n onTerminate,\n });\n logger.debug(`Sync successful with authMode: ${readAuthModes[authModeAttempts]}`);\n return response;\n }\n catch (error) {\n authModeAttempts++;\n if (authModeAttempts >= readAuthModes.length) {\n const authMode = readAuthModes[authModeAttempts - 1];\n logger.debug(`Sync failed with authMode: ${authMode}`, error);\n if (getClientSideAuthError(error) || getForbiddenError(error)) {\n // return empty list of data so DataStore will continue to sync other models\n logger.warn(`User is unauthorized to query ${opName} with auth mode ${authMode}. No data could be returned.`);\n return {\n data: {\n [opName]: opResultDefaults,\n },\n };\n }\n throw error;\n }\n logger.debug(`Sync failed with authMode: ${readAuthModes[authModeAttempts - 1]}. Retrying with authMode: ${readAuthModes[authModeAttempts]}`);\n return await authModeRetry();\n }\n };\n const { data } = await authModeRetry();\n const { [opName]: opResult } = data;\n const { items, nextToken: newNextToken, startedAt } = opResult;\n return {\n nextToken: newNextToken,\n startedAt,\n items,\n };\n }\n async jitteredRetry({ query, variables, opName, modelDefinition, authMode, onTerminate, }) {\n return await jitteredExponentialRetry(async (query, variables) => {\n try {\n const authToken = await getTokenForCustomAuth(authMode, this.amplifyConfig);\n const customUserAgentDetails = {\n category: Category.DataStore,\n action: DataStoreAction.GraphQl,\n };\n return await this.amplifyContext.InternalAPI.graphql({\n query,\n variables,\n authMode,\n authToken,\n }, undefined, customUserAgentDetails);\n // TODO: onTerminate.then(() => API.cancel(...))\n }\n catch (error) {\n // Catch client-side (GraphQLAuthError) & 401/403 errors here so that we don't continue to retry\n const clientOrForbiddenErrorMessage = getClientSideAuthError(error) || getForbiddenError(error);\n if (clientOrForbiddenErrorMessage) {\n logger.error('Sync processor retry error:', error);\n throw new NonRetryableError(clientOrForbiddenErrorMessage);\n }\n const hasItems = Boolean(error?.data?.[opName]?.items);\n const unauthorized = error?.errors &&\n error.errors.some(err => err.errorType === 'Unauthorized');\n const otherErrors = error?.errors &&\n error.errors.filter(err => err.errorType !== 'Unauthorized');\n const result = error;\n if (hasItems) {\n result.data[opName].items = result.data[opName].items.filter(item => item !== null);\n }\n if (hasItems && otherErrors?.length) {\n await Promise.all(otherErrors.map(async (err) => {\n try {\n await this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message: err.message,\n model: modelDefinition.name,\n operation: opName,\n errorType: getSyncErrorType(err),\n process: ProcessName.sync,\n remoteModel: null,\n cause: err,\n });\n }\n catch (e) {\n logger.error('Sync error handler failed with:', e);\n }\n }));\n Hub.dispatch('datastore', {\n event: 'nonApplicableDataReceived',\n data: {\n errors: otherErrors,\n modelName: modelDefinition.name,\n },\n });\n }\n /**\n * Handle $util.unauthorized() in resolver request mapper, which responses with something\n * like this:\n *\n * ```\n * {\n * \tdata: { syncYourModel: null },\n * \terrors: [\n * \t\t{\n * \t\t\tpath: ['syncLegacyJSONComments'],\n * \t\t\tdata: null,\n * \t\t\terrorType: 'Unauthorized',\n * \t\t\terrorInfo: null,\n * \t\t\tlocations: [{ line: 2, column: 3, sourceName: null }],\n * \t\t\tmessage:\n * \t\t\t\t'Not Authorized to access syncYourModel on type Query',\n * \t\t\t},\n * \t\t],\n * \t}\n * ```\n *\n * The correct handling for this is to signal that we've encountered a non-retryable error,\n * since the server has responded with an auth error and *NO DATA* at this point.\n */\n if (unauthorized) {\n this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message: error.message,\n model: modelDefinition.name,\n operation: opName,\n errorType: getSyncErrorType(error.errors[0]),\n process: ProcessName.sync,\n remoteModel: null,\n cause: error,\n });\n throw new NonRetryableError(error);\n }\n if (result.data?.[opName]?.items?.length) {\n return result;\n }\n throw error;\n }\n }, [query, variables], undefined, onTerminate);\n }\n start(typesLastSync) {\n const { maxRecordsToSync, syncPageSize } = this.amplifyConfig;\n const parentPromises = new Map();\n const observable = new Observable(observer => {\n const sortedTypesLastSyncs = Object.values(this.schema.namespaces).reduce((map, namespace) => {\n for (const modelName of Array.from(namespace.modelTopologicalOrdering.keys())) {\n const typeLastSync = typesLastSync.get(namespace.models[modelName]);\n map.set(namespace.models[modelName], typeLastSync);\n }\n return map;\n }, new Map());\n const allModelsReady = Array.from(sortedTypesLastSyncs.entries())\n .filter(([{ syncable }]) => syncable)\n .map(([modelDefinition, [namespace, lastSync]]) => this.runningProcesses.isOpen &&\n this.runningProcesses.add(async (onTerminate) => {\n let done = false;\n let nextToken = null;\n let startedAt = null;\n let items = null;\n let recordsReceived = 0;\n const filter = this.graphqlFilterFromPredicate(modelDefinition);\n const parents = this.schema.namespaces[namespace].modelTopologicalOrdering.get(modelDefinition.name);\n const promises = parents.map(parent => parentPromises.get(`${namespace}_${parent}`));\n const promise = new Promise(async (res) => {\n await Promise.all(promises);\n do {\n /**\n * If `runningProcesses` is not open, it means that the sync processor has been\n * stopped (for example by calling `DataStore.clear()` upstream) and has not yet\n * finished terminating and/or waiting for its background processes to complete.\n */\n if (!this.runningProcesses.isOpen) {\n logger.debug(`Sync processor has been stopped, terminating sync for ${modelDefinition.name}`);\n return res();\n }\n const limit = Math.min(maxRecordsToSync - recordsReceived, syncPageSize);\n /**\n * It's possible that `retrievePage` will fail.\n * If it does fail, continue merging the rest of the data,\n * and invoke the error handler for non-applicable data.\n */\n try {\n ({ items, nextToken, startedAt } = await this.retrievePage(modelDefinition, lastSync, nextToken, limit, filter, onTerminate));\n }\n catch (error) {\n try {\n await this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message: error.message,\n model: modelDefinition.name,\n operation: null,\n errorType: getSyncErrorType(error),\n process: ProcessName.sync,\n remoteModel: null,\n cause: error,\n });\n }\n catch (e) {\n logger.error('Sync error handler failed with:', e);\n }\n /**\n * If there's an error, this model fails, but the rest of the sync should\n * continue. To facilitate this, we explicitly mark this model as `done`\n * with no items and allow the loop to continue organically. This ensures\n * all callbacks (subscription messages) happen as normal, so anything\n * waiting on them knows the model is as done as it can be.\n */\n done = true;\n items = [];\n }\n recordsReceived += items.length;\n done =\n nextToken === null || recordsReceived >= maxRecordsToSync;\n observer.next({\n namespace,\n modelDefinition,\n items,\n done,\n startedAt,\n isFullSync: !lastSync,\n });\n } while (!done);\n res();\n });\n parentPromises.set(`${namespace}_${modelDefinition.name}`, promise);\n await promise;\n }, `adding model ${modelDefinition.name}`));\n Promise.all(allModelsReady).then(() => {\n observer.complete();\n });\n });\n return observable;\n }\n async stop() {\n logger.debug('stopping sync processor');\n await this.runningProcesses.close();\n await this.runningProcesses.open();\n logger.debug('sync processor stopped');\n }\n}\nexport { SyncProcessor };\n"],"names":[],"mappings":";;;;;;;;;AAQA,MAAM,gBAAgB,GAAG;AACzB,IAAI,KAAK,EAAE,EAAE;AACb,IAAI,SAAS,EAAE,IAAI;AACnB,IAAI,SAAS,EAAE,IAAI;AACnB,CAAC,CAAC;AACF,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,WAAW,CAAC,CAAC;AAC9C,MAAM,aAAa,CAAC;AACpB,IAAI,WAAW,CAAC,MAAM,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M,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;AAC3C,QAAQ,MAAM,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAC/C,KAAK;AACL;;;;"}
1
+ {"version":3,"file":"sync.mjs","sources":["../../../../src/sync/processors/sync.ts"],"sourcesContent":["import { InternalAPI } from '@aws-amplify/api/internals';\nimport { Observable } from 'rxjs';\nimport { BackgroundProcessManager, Category, DataStoreAction, NonRetryableError, jitteredExponentialRetry, } from '@aws-amplify/core/internals/utils';\nimport { ConsoleLogger, Hub } from '@aws-amplify/core';\nimport { ProcessName, } from '../../types';\nimport { buildGraphQLOperation, getClientSideAuthError, getForbiddenError, getModelAuthModes, getTokenForCustomAuth, predicateToGraphQLFilter, } from '../utils';\nimport { ModelPredicateCreator } from '../../predicates';\nimport { getSyncErrorType } from './errorMaps';\nconst opResultDefaults = {\n items: [],\n nextToken: null,\n startedAt: null,\n};\nconst logger = new ConsoleLogger('DataStore');\nclass SyncProcessor {\n constructor(schema, syncPredicates, amplifyConfig = {}, authModeStrategy, errorHandler, amplifyContext) {\n this.schema = schema;\n this.syncPredicates = syncPredicates;\n this.amplifyConfig = amplifyConfig;\n this.authModeStrategy = authModeStrategy;\n this.errorHandler = errorHandler;\n this.amplifyContext = amplifyContext;\n this.typeQuery = new WeakMap();\n this.runningProcesses = new BackgroundProcessManager();\n amplifyContext.InternalAPI = amplifyContext.InternalAPI || InternalAPI;\n this.generateQueries();\n }\n generateQueries() {\n Object.values(this.schema.namespaces).forEach(namespace => {\n Object.values(namespace.models)\n .filter(({ syncable }) => syncable)\n .forEach(model => {\n const [[, ...opNameQuery]] = buildGraphQLOperation(namespace, model, 'LIST');\n this.typeQuery.set(model, opNameQuery);\n });\n });\n }\n graphqlFilterFromPredicate(model) {\n if (!this.syncPredicates) {\n return null;\n }\n const predicatesGroup = ModelPredicateCreator.getPredicates(this.syncPredicates.get(model), false);\n if (!predicatesGroup) {\n return null;\n }\n return predicateToGraphQLFilter(predicatesGroup);\n }\n async retrievePage(modelDefinition, lastSync, nextToken, limit = null, filter, onTerminate) {\n const [opName, query] = this.typeQuery.get(modelDefinition);\n const variables = {\n limit,\n nextToken,\n lastSync,\n filter,\n };\n const modelAuthModes = await getModelAuthModes({\n authModeStrategy: this.authModeStrategy,\n defaultAuthMode: this.amplifyConfig.aws_appsync_authenticationType,\n modelName: modelDefinition.name,\n schema: this.schema,\n });\n // sync only needs the READ auth mode(s)\n const readAuthModes = modelAuthModes.READ;\n let authModeAttempts = 0;\n const authModeRetry = async () => {\n if (!this.runningProcesses.isOpen) {\n throw new Error('sync.retreievePage termination was requested. Exiting.');\n }\n try {\n logger.debug(`Attempting sync with authMode: ${readAuthModes[authModeAttempts]}`);\n const response = await this.jitteredRetry({\n query,\n variables,\n opName,\n modelDefinition,\n authMode: readAuthModes[authModeAttempts],\n onTerminate,\n });\n logger.debug(`Sync successful with authMode: ${readAuthModes[authModeAttempts]}`);\n return response;\n }\n catch (error) {\n authModeAttempts++;\n if (authModeAttempts >= readAuthModes.length) {\n const authMode = readAuthModes[authModeAttempts - 1];\n logger.debug(`Sync failed with authMode: ${authMode}`, error);\n if (getClientSideAuthError(error) || getForbiddenError(error)) {\n // return empty list of data so DataStore will continue to sync other models\n logger.warn(`User is unauthorized to query ${opName} with auth mode ${authMode}. No data could be returned.`);\n return {\n data: {\n [opName]: opResultDefaults,\n },\n };\n }\n throw error;\n }\n logger.debug(`Sync failed with authMode: ${readAuthModes[authModeAttempts - 1]}. Retrying with authMode: ${readAuthModes[authModeAttempts]}`);\n return authModeRetry();\n }\n };\n const { data } = await authModeRetry();\n const { [opName]: opResult } = data;\n const { items, nextToken: newNextToken, startedAt } = opResult;\n return {\n nextToken: newNextToken,\n startedAt,\n items,\n };\n }\n async jitteredRetry({ query, variables, opName, modelDefinition, authMode, onTerminate, }) {\n return jitteredExponentialRetry(async (retriedQuery, retriedVariables) => {\n try {\n const authToken = await getTokenForCustomAuth(authMode, this.amplifyConfig);\n const customUserAgentDetails = {\n category: Category.DataStore,\n action: DataStoreAction.GraphQl,\n };\n return await this.amplifyContext.InternalAPI.graphql({\n query: retriedQuery,\n variables: retriedVariables,\n authMode,\n authToken,\n }, undefined, customUserAgentDetails);\n // TODO: onTerminate.then(() => API.cancel(...))\n }\n catch (error) {\n // Catch client-side (GraphQLAuthError) & 401/403 errors here so that we don't continue to retry\n const clientOrForbiddenErrorMessage = getClientSideAuthError(error) || getForbiddenError(error);\n if (clientOrForbiddenErrorMessage) {\n logger.error('Sync processor retry error:', error);\n throw new NonRetryableError(clientOrForbiddenErrorMessage);\n }\n const hasItems = Boolean(error?.data?.[opName]?.items);\n const unauthorized = error?.errors &&\n error.errors.some(err => err.errorType === 'Unauthorized');\n const otherErrors = error?.errors &&\n error.errors.filter(err => err.errorType !== 'Unauthorized');\n const result = error;\n if (hasItems) {\n result.data[opName].items = result.data[opName].items.filter(item => item !== null);\n }\n if (hasItems && otherErrors?.length) {\n await Promise.all(otherErrors.map(async (err) => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n await this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message: err.message,\n model: modelDefinition.name,\n operation: opName,\n errorType: getSyncErrorType(err),\n process: ProcessName.sync,\n remoteModel: null,\n cause: err,\n });\n }\n catch (e) {\n logger.error('Sync error handler failed with:', e);\n }\n }));\n Hub.dispatch('datastore', {\n event: 'nonApplicableDataReceived',\n data: {\n errors: otherErrors,\n modelName: modelDefinition.name,\n },\n });\n }\n /**\n * Handle $util.unauthorized() in resolver request mapper, which responses with something\n * like this:\n *\n * ```\n * {\n * \tdata: { syncYourModel: null },\n * \terrors: [\n * \t\t{\n * \t\t\tpath: ['syncLegacyJSONComments'],\n * \t\t\tdata: null,\n * \t\t\terrorType: 'Unauthorized',\n * \t\t\terrorInfo: null,\n * \t\t\tlocations: [{ line: 2, column: 3, sourceName: null }],\n * \t\t\tmessage:\n * \t\t\t\t'Not Authorized to access syncYourModel on type Query',\n * \t\t\t},\n * \t\t],\n * \t}\n * ```\n *\n * The correct handling for this is to signal that we've encountered a non-retryable error,\n * since the server has responded with an auth error and *NO DATA* at this point.\n */\n if (unauthorized) {\n this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message: error.message,\n model: modelDefinition.name,\n operation: opName,\n errorType: getSyncErrorType(error.errors[0]),\n process: ProcessName.sync,\n remoteModel: null,\n cause: error,\n });\n throw new NonRetryableError(error);\n }\n if (result.data?.[opName]?.items?.length) {\n return result;\n }\n throw error;\n }\n }, [query, variables], undefined, onTerminate);\n }\n start(typesLastSync) {\n const { maxRecordsToSync, syncPageSize } = this.amplifyConfig;\n const parentPromises = new Map();\n const observable = new Observable(observer => {\n const sortedTypesLastSyncs = Object.values(this.schema.namespaces).reduce((map, namespace) => {\n for (const modelName of Array.from(namespace.modelTopologicalOrdering.keys())) {\n const typeLastSync = typesLastSync.get(namespace.models[modelName]);\n map.set(namespace.models[modelName], typeLastSync);\n }\n return map;\n }, new Map());\n const allModelsReady = Array.from(sortedTypesLastSyncs.entries())\n .filter(([{ syncable }]) => syncable)\n .map(([modelDefinition, [namespace, lastSync]]) => this.runningProcesses.isOpen &&\n this.runningProcesses.add(async (onTerminate) => {\n let done = false;\n let nextToken = null;\n let startedAt = null;\n let items = null;\n let recordsReceived = 0;\n const filter = this.graphqlFilterFromPredicate(modelDefinition);\n const parents = this.schema.namespaces[namespace].modelTopologicalOrdering.get(modelDefinition.name);\n const promises = parents.map(parent => parentPromises.get(`${namespace}_${parent}`));\n // eslint-disable-next-line no-async-promise-executor\n const promise = new Promise(async (resolve) => {\n await Promise.all(promises);\n do {\n /**\n * If `runningProcesses` is not open, it means that the sync processor has been\n * stopped (for example by calling `DataStore.clear()` upstream) and has not yet\n * finished terminating and/or waiting for its background processes to complete.\n */\n if (!this.runningProcesses.isOpen) {\n logger.debug(`Sync processor has been stopped, terminating sync for ${modelDefinition.name}`);\n resolve();\n return;\n }\n const limit = Math.min(maxRecordsToSync - recordsReceived, syncPageSize);\n /**\n * It's possible that `retrievePage` will fail.\n * If it does fail, continue merging the rest of the data,\n * and invoke the error handler for non-applicable data.\n */\n try {\n ({ items, nextToken, startedAt } = await this.retrievePage(modelDefinition, lastSync, nextToken, limit, filter, onTerminate));\n }\n catch (error) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n await this.errorHandler({\n recoverySuggestion: 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',\n localModel: null,\n message: error.message,\n model: modelDefinition.name,\n operation: null,\n errorType: getSyncErrorType(error),\n process: ProcessName.sync,\n remoteModel: null,\n cause: error,\n });\n }\n catch (e) {\n logger.error('Sync error handler failed with:', e);\n }\n /**\n * If there's an error, this model fails, but the rest of the sync should\n * continue. To facilitate this, we explicitly mark this model as `done`\n * with no items and allow the loop to continue organically. This ensures\n * all callbacks (subscription messages) happen as normal, so anything\n * waiting on them knows the model is as done as it can be.\n */\n done = true;\n items = [];\n }\n recordsReceived += items.length;\n done =\n nextToken === null || recordsReceived >= maxRecordsToSync;\n observer.next({\n namespace,\n modelDefinition,\n items,\n done,\n startedAt,\n isFullSync: !lastSync,\n });\n } while (!done);\n resolve();\n });\n parentPromises.set(`${namespace}_${modelDefinition.name}`, promise);\n await promise;\n }, `adding model ${modelDefinition.name}`));\n Promise.all(allModelsReady).then(() => {\n observer.complete();\n });\n });\n return observable;\n }\n async stop() {\n logger.debug('stopping sync processor');\n await this.runningProcesses.close();\n await this.runningProcesses.open();\n logger.debug('sync processor stopped');\n }\n}\nexport { SyncProcessor };\n"],"names":[],"mappings":";;;;;;;;;AAQ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,CAAC,QAAQ,EAAE,CAAC;AACpC,aAAa,CAAC,CAAC;AACf,SAAS,CAAC,CAAC;AACX,QAAQ,OAAO,UAAU,CAAC;AAC1B,KAAK;AACL,IAAI,MAAM,IAAI,GAAG;AACjB,QAAQ,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;AAChD,QAAQ,MAAM,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;AAC5C,QAAQ,MAAM,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;AAC3C,QAAQ,MAAM,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAC/C,KAAK;AACL;;;;"}
@@ -1,22 +1,22 @@
1
1
  import { GraphQLAuthError } from '@aws-amplify/api';
2
2
  import { GraphQLAuthMode } from '@aws-amplify/core/internals/utils';
3
3
  import { ModelInstanceCreator } from '../datastore/datastore';
4
- import { AuthorizationRule, GraphQLCondition, GraphQLFilter, ModelInstanceMetadata, OpType, PersistentModel, PersistentModelConstructor, PredicatesGroup, RelationshipType, SchemaModel, SchemaNamespace, SchemaNonModel, ModelOperation, InternalSchema, AuthModeStrategy } from '../types';
4
+ import { AuthModeStrategy, AuthorizationRule, GraphQLCondition, GraphQLFilter, InternalSchema, ModelInstanceMetadata, ModelOperation, OpType, PersistentModel, PersistentModelConstructor, PredicatesGroup, RelationshipType, SchemaModel, SchemaNamespace, SchemaNonModel } from '../types';
5
5
  import { MutationEvent } from './';
6
- declare enum GraphQLOperationType {
7
- LIST = "query",
8
- CREATE = "mutation",
9
- UPDATE = "mutation",
10
- DELETE = "mutation",
11
- GET = "query"
12
- }
6
+ declare const GraphQLOperationType: {
7
+ LIST: string;
8
+ CREATE: string;
9
+ UPDATE: string;
10
+ DELETE: string;
11
+ GET: string;
12
+ };
13
13
  export declare enum TransformerMutationType {
14
14
  CREATE = "Create",
15
15
  UPDATE = "Update",
16
16
  DELETE = "Delete",
17
17
  GET = "Get"
18
18
  }
19
- export declare function getMetadataFields(): ReadonlyArray<string>;
19
+ export declare function getMetadataFields(): readonly string[];
20
20
  export declare function generateSelectionSet(namespace: SchemaNamespace, modelDefinition: SchemaModel | SchemaNonModel): string;
21
21
  export declare function getAuthorizationRules(modelDefinition: SchemaModel): AuthorizationRule[];
22
22
  export declare function buildSubscriptionGraphQLOperation(namespace: SchemaNamespace, modelDefinition: SchemaModel, transformerMutationType: TransformerMutationType, isOwnerAuthorization: boolean, ownerField: string, filterArg?: boolean): [TransformerMutationType, string, string];
@@ -26,7 +26,7 @@ export declare function predicateToGraphQLCondition(predicate: PredicatesGroup<a
26
26
  /**
27
27
  * @param predicatesGroup - Predicate Group
28
28
  @returns GQL Filter Expression from Predicate Group
29
-
29
+
30
30
  @remarks Flattens redundant list predicates
31
31
  @example
32
32
 
@@ -88,9 +88,7 @@ export declare enum RTFError {
88
88
  FieldNotInType = 5
89
89
  }
90
90
  export declare function generateRTFRemediation(errorType: RTFError, modelDefinition: SchemaModel, predicatesGroup: PredicatesGroup<any> | undefined): string;
91
- export declare function getUserGroupsFromToken(token: {
92
- [field: string]: any;
93
- }, rule: AuthorizationRule): string[];
91
+ export declare function getUserGroupsFromToken(token: Record<string, any>, rule: AuthorizationRule): string[];
94
92
  export declare function getModelAuthModes({ authModeStrategy, defaultAuthMode, modelName, schema, }: {
95
93
  authModeStrategy: AuthModeStrategy;
96
94
  defaultAuthMode: GraphQLAuthMode;
@@ -1,19 +1,18 @@
1
1
  import { GraphQLAuthError } from '@aws-amplify/api';
2
+ import { ConsoleLogger } from '@aws-amplify/core';
2
3
  import { isSchemaModel, isSchemaModelWithAttributes, isGraphQLScalarType, isEnumFieldType, isTargetNameAssociation, isNonModelFieldType, OpType, isPredicateObj, isPredicateGroup, ModelOperation } from '../types.mjs';
3
4
  import { establishRelationAndKeys, extractPrimaryKeyFieldNames, IDENTIFIER_KEY_SEPARATOR } from '../util.mjs';
4
- import { ConsoleLogger } from '@aws-amplify/core';
5
5
 
6
6
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
7
7
  // SPDX-License-Identifier: Apache-2.0
8
8
  const logger = new ConsoleLogger('DataStore');
9
- var GraphQLOperationType;
10
- (function (GraphQLOperationType) {
11
- GraphQLOperationType["LIST"] = "query";
12
- GraphQLOperationType["CREATE"] = "mutation";
13
- GraphQLOperationType["UPDATE"] = "mutation";
14
- GraphQLOperationType["DELETE"] = "mutation";
15
- GraphQLOperationType["GET"] = "query";
16
- })(GraphQLOperationType || (GraphQLOperationType = {}));
9
+ const GraphQLOperationType = {
10
+ LIST: 'query',
11
+ CREATE: 'mutation',
12
+ UPDATE: 'mutation',
13
+ DELETE: 'mutation',
14
+ GET: 'query',
15
+ };
17
16
  var TransformerMutationType;
18
17
  (function (TransformerMutationType) {
19
18
  TransformerMutationType["CREATE"] = "Create";
@@ -26,7 +25,7 @@ const dummyMetadata = {
26
25
  _lastChangedAt: undefined,
27
26
  _deleted: undefined,
28
27
  };
29
- const metadataFields = (Object.keys(dummyMetadata));
28
+ const metadataFields = Object.keys(dummyMetadata);
30
29
  function getMetadataFields() {
31
30
  return metadataFields;
32
31
  }
@@ -58,7 +57,7 @@ function getOwnerFields(modelDefinition) {
58
57
  if (isSchemaModelWithAttributes(modelDefinition)) {
59
58
  modelDefinition.attributes.forEach(attr => {
60
59
  if (attr.properties && attr.properties.rules) {
61
- const rule = attr.properties.rules.find(rule => rule.allow === 'owner');
60
+ const rule = attr.properties.rules.find(currentRule => currentRule.allow === 'owner');
62
61
  if (rule && rule.ownerField) {
63
62
  ownerFields.push(rule.ownerField);
64
63
  }
@@ -100,8 +99,8 @@ function getConnectionFields(modelDefinition, namespace) {
100
99
  if (association.targetNames && association.targetNames.length > 0) {
101
100
  // Need to retrieve relations in order to get connected model keys
102
101
  const [relations] = establishRelationAndKeys(namespace);
103
- const connectedModelName = modelDefinition.fields[name].type['model'];
104
- const byPkIndex = relations[connectedModelName].indexes.find(([name]) => name === 'byPk');
102
+ const connectedModelName = modelDefinition.fields[name].type.model;
103
+ const byPkIndex = relations[connectedModelName].indexes.find(([currentName]) => currentName === 'byPk');
105
104
  const keyFields = byPkIndex && byPkIndex[1];
106
105
  const keyFieldSelectionSet = keyFields?.join(' ');
107
106
  // We rely on `_deleted` when we process the sync query (e.g. in batchSave in the adapters)
@@ -124,13 +123,13 @@ function getNonModelFields(namespace, modelDefinition) {
124
123
  Object.values(modelDefinition.fields).forEach(({ name, type }) => {
125
124
  if (isNonModelFieldType(type)) {
126
125
  const typeDefinition = namespace.nonModels[type.nonModel];
127
- const scalarFields = Object.values(getScalarFields(typeDefinition)).map(({ name }) => name);
126
+ const scalarFields = Object.values(getScalarFields(typeDefinition)).map(({ name: currentName }) => currentName);
128
127
  const nested = [];
129
128
  Object.values(typeDefinition.fields).forEach(field => {
130
- const { type, name } = field;
131
- if (isNonModelFieldType(type)) {
132
- const typeDefinition = namespace.nonModels[type.nonModel];
133
- nested.push(`${name} { ${generateSelectionSet(namespace, typeDefinition)} }`);
129
+ const { type: fieldType, name: fieldName } = field;
130
+ if (isNonModelFieldType(fieldType)) {
131
+ const nonModelTypeDefinition = namespace.nonModels[fieldType.nonModel];
132
+ nested.push(`${fieldName} { ${generateSelectionSet(namespace, nonModelTypeDefinition)} }`);
134
133
  }
135
134
  });
136
135
  result.push(`${name} { ${scalarFields.join(' ')} ${nested.join(' ')} }`);
@@ -329,7 +328,7 @@ function predicateToGraphQLCondition(predicate, modelDefinition) {
329
328
  /**
330
329
  * @param predicatesGroup - Predicate Group
331
330
  @returns GQL Filter Expression from Predicate Group
332
-
331
+
333
332
  @remarks Flattens redundant list predicates
334
333
  @example
335
334
 
@@ -634,8 +633,8 @@ function getForbiddenError(error) {
634
633
  return null;
635
634
  }
636
635
  function resolveServiceErrorStatusCode(error) {
637
- if (error?.['$metadata']?.['httpStatusCode']) {
638
- return Number(error?.['$metadata']?.['httpStatusCode']);
636
+ if (error?.$metadata?.httpStatusCode) {
637
+ return Number(error?.$metadata?.httpStatusCode);
639
638
  }
640
639
  else if (error?.originalError) {
641
640
  return resolveServiceErrorStatusCode(error?.originalError);