@foxtware/mineral 0.1.27 → 0.1.29

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 (178) hide show
  1. package/.creds.yml.sample +29 -0
  2. package/AGENTS.md +24 -0
  3. package/_build_scripts/createNewFunction.js +26 -3
  4. package/api/dropbox/docs.md +7 -0
  5. package/api/dropbox/dropbox.constants.js +10 -0
  6. package/api/dropbox/dropbox.utils.js +67 -0
  7. package/api/dropbox/dropboxAccountGet.js +64 -0
  8. package/api/dropbox/dropboxFileCopy.js +67 -0
  9. package/api/dropbox/dropboxFileDelete.js +89 -0
  10. package/api/dropbox/dropboxFileDownload.js +139 -0
  11. package/api/dropbox/dropboxFileMetadataGet.js +100 -0
  12. package/api/dropbox/dropboxFileMove.js +67 -0
  13. package/api/dropbox/dropboxFileUpload.js +129 -0
  14. package/api/dropbox/dropboxFolderCreate.js +68 -0
  15. package/api/dropbox/dropboxFolderList.js +66 -0
  16. package/api/dropbox/dropboxGet.js +158 -0
  17. package/api/dropbox/dropboxSearch.js +161 -0
  18. package/api/dropbox/dropboxSharedLinkCreate.js +68 -0
  19. package/api/dropbox/dropboxSpaceUsageGet.js +55 -0
  20. package/api/dropbox/dropboxTemporaryLinkGet.js +75 -0
  21. package/api/fastsimon/.gitkeep +0 -0
  22. package/api/fastsimon/docs.md +14 -0
  23. package/api/fastsimon/fastsimon.constants.js +18 -0
  24. package/api/fastsimon/fastsimon.utils.js +246 -0
  25. package/api/fastsimon/fastsimonSearch.js +84 -0
  26. package/api/figma/docs.md +3 -3
  27. package/api/figma/figma.constants.js +1 -1
  28. package/api/figma/figma.utils.js +13 -2
  29. package/api/figma/figmaActivityLogsGet.js +44 -0
  30. package/api/figma/figmaAiUsageDailyGet.js +44 -0
  31. package/api/figma/figmaComponentGet.js +48 -0
  32. package/api/figma/figmaComponentSetGet.js +48 -0
  33. package/api/figma/figmaDevResourcesCreate.js +47 -0
  34. package/api/figma/figmaDevResourcesUpdate.js +47 -0
  35. package/api/figma/figmaDeveloperLogsCreate.js +47 -0
  36. package/api/figma/figmaDiscoveryGet.js +44 -0
  37. package/api/figma/figmaFileCommentCreate.js +50 -0
  38. package/api/figma/figmaFileCommentDelete.js +51 -0
  39. package/api/figma/figmaFileCommentReactionCreate.js +53 -0
  40. package/api/figma/figmaFileCommentReactionDelete.js +51 -0
  41. package/api/figma/figmaFileCommentReactionsGet.js +51 -0
  42. package/api/figma/figmaFileCommentsGet.js +48 -0
  43. package/api/figma/figmaFileComponentSetsGet.js +48 -0
  44. package/api/figma/figmaFileComponentsGet.js +48 -0
  45. package/api/figma/figmaFileDevResourceDelete.js +51 -0
  46. package/api/figma/figmaFileDevResourcesGet.js +48 -0
  47. package/api/figma/figmaFileGet.js +48 -0
  48. package/api/figma/figmaFileImageFillsGet.js +48 -0
  49. package/api/figma/figmaFileImagesGet.js +48 -0
  50. package/api/figma/figmaFileMetaGet.js +48 -0
  51. package/api/figma/figmaFileNodesGet.js +48 -0
  52. package/api/figma/figmaFileStylesGet.js +48 -0
  53. package/api/figma/figmaFileVersionsGet.js +48 -0
  54. package/api/figma/figmaFolderFilesGet.js +48 -0
  55. package/api/figma/figmaFolderFoldersGet.js +48 -0
  56. package/api/figma/figmaFolderMetaGet.js +48 -0
  57. package/api/figma/figmaGet.js +15 -63
  58. package/api/figma/figmaMeGet.js +53 -0
  59. package/api/figma/figmaOembedGet.js +44 -0
  60. package/api/figma/figmaPaymentsGet.js +44 -0
  61. package/api/figma/figmaProjectFilesGet.js +48 -0
  62. package/api/figma/figmaProjectMetaGet.js +48 -0
  63. package/api/figma/figmaStyleGet.js +48 -0
  64. package/api/figma/figmaTeamComponentSetsGet.js +48 -0
  65. package/api/figma/figmaTeamComponentsGet.js +48 -0
  66. package/api/figma/figmaTeamFoldersGet.js +48 -0
  67. package/api/figma/figmaTeamProjectsGet.js +48 -0
  68. package/api/figma/figmaTeamStylesGet.js +48 -0
  69. package/api/figma/figmaTeamWebhooksGet.js +47 -0
  70. package/api/figma/figmaVariablesLocalGet.js +48 -0
  71. package/api/figma/figmaVariablesPublishedGet.js +48 -0
  72. package/api/figma/figmaVariablesUpdate.js +50 -0
  73. package/api/figma/figmaWebhookCreate.js +47 -0
  74. package/api/figma/figmaWebhookDelete.js +48 -0
  75. package/api/figma/figmaWebhookGet.js +46 -0
  76. package/api/figma/figmaWebhookRequestsGet.js +47 -0
  77. package/api/figma/figmaWebhookUpdate.js +50 -0
  78. package/api/figma/figmaWebhooksGet.js +47 -0
  79. package/api/google/docs.md +1 -0
  80. package/api/google/google.constants.js +1 -0
  81. package/api/google/google.utils.js +21 -0
  82. package/api/google/googleanalyticsMetadataGet.js +62 -0
  83. package/api/google/googleanalyticsRealtimeReportRun.js +103 -0
  84. package/api/google/googleanalyticsReportRun.js +114 -0
  85. package/api/gorgias/gorgiasTicketCreate.js +1 -1
  86. package/api/gorgias/gorgiasTicketMessageCreate.js +1 -1
  87. package/api/gorgias/gorgiasTicketUpdate.js +1 -1
  88. package/api/linear/linearAttachmentCreate.js +1 -1
  89. package/api/linear/linearCommentCreate.js +1 -1
  90. package/api/linear/linearCommentUpdate.js +1 -1
  91. package/api/linear/linearIssueLabelCreate.js +1 -1
  92. package/api/linear/linearIssueUpdate.js +1 -1
  93. package/api/linear/linearProjectCreate.js +1 -1
  94. package/api/linear/linearProjectUpdate.js +1 -1
  95. package/api/linear/linearWebhookCreate.js +1 -1
  96. package/api/salesforce/salesforce.constants.js +13 -0
  97. package/api/salesforce/salesforce.utils.js +61 -0
  98. package/api/salesforce/salesforceAuthGet.js +115 -0
  99. package/api/salesforce/salesforceComposite.js +79 -0
  100. package/api/salesforce/salesforceCompositeBatch.js +73 -0
  101. package/api/salesforce/salesforceLimitsGet.js +55 -0
  102. package/api/salesforce/salesforceQuery.js +69 -0
  103. package/api/salesforce/salesforceQueryAll.js +62 -0
  104. package/api/salesforce/salesforceQueryMore.js +75 -0
  105. package/api/salesforce/salesforceRecentItemsGet.js +63 -0
  106. package/api/salesforce/salesforceResourcesGet.js +55 -0
  107. package/api/salesforce/salesforceSearch.js +62 -0
  108. package/api/salesforce/salesforceSobjectBasicInfoGet.js +81 -0
  109. package/api/salesforce/salesforceSobjectBlobGet.js +67 -0
  110. package/api/salesforce/salesforceSobjectCollectionCreate.js +78 -0
  111. package/api/salesforce/salesforceSobjectCollectionDelete.js +70 -0
  112. package/api/salesforce/salesforceSobjectCollectionGet.js +75 -0
  113. package/api/salesforce/salesforceSobjectCollectionUpdate.js +74 -0
  114. package/api/salesforce/salesforceSobjectCreate.js +66 -0
  115. package/api/salesforce/salesforceSobjectDelete.js +86 -0
  116. package/api/salesforce/salesforceSobjectDeleteByExternalId.js +91 -0
  117. package/api/salesforce/salesforceSobjectDeletedGet.js +71 -0
  118. package/api/salesforce/salesforceSobjectDescribe.js +81 -0
  119. package/api/salesforce/salesforceSobjectDescribeLayouts.js +64 -0
  120. package/api/salesforce/salesforceSobjectGet.js +93 -0
  121. package/api/salesforce/salesforceSobjectGetByExternalId.js +98 -0
  122. package/api/salesforce/salesforceSobjectTreeCreate.js +79 -0
  123. package/api/salesforce/salesforceSobjectUpdate.js +94 -0
  124. package/api/salesforce/salesforceSobjectUpdatedGet.js +71 -0
  125. package/api/salesforce/salesforceSobjectUpsert.js +74 -0
  126. package/api/salesforce/salesforceSobjectsDescribeGlobal.js +55 -0
  127. package/api/salesforce/salesforceVersionsGet.js +62 -0
  128. package/api/shopify/shopify.utils.js +53 -4
  129. package/api/shopify/shopifyMetaobjectCreate.js +79 -0
  130. package/api/shopify/shopifyMetaobjectDelete.js +90 -0
  131. package/api/shopify/shopifyMetaobjectGet.js +80 -0
  132. package/api/shopify/shopifyMetaobjectUpdate.js +108 -0
  133. package/api/shopify/shopifyStorefrontSearch.js +158 -0
  134. package/api/spotify/docs.md +8 -0
  135. package/api/spotify/spotify.constants.js +12 -0
  136. package/api/spotify/spotify.utils.js +106 -0
  137. package/api/spotify/spotifyAlbumGet.js +76 -0
  138. package/api/spotify/spotifyAlbumTracksGet.js +49 -0
  139. package/api/spotify/spotifyArtistAlbumsGet.js +55 -0
  140. package/api/spotify/spotifyArtistGet.js +71 -0
  141. package/api/spotify/spotifyArtistTopTracksGet.js +56 -0
  142. package/api/spotify/spotifyGet.js +171 -0
  143. package/api/spotify/spotifyMeGet.js +48 -0
  144. package/api/spotify/spotifyPlayerCurrentlyPlayingGet.js +62 -0
  145. package/api/spotify/spotifyPlayerDevicesGet.js +51 -0
  146. package/api/spotify/spotifyPlayerGet.js +63 -0
  147. package/api/spotify/spotifyPlayerNext.js +55 -0
  148. package/api/spotify/spotifyPlayerPause.js +55 -0
  149. package/api/spotify/spotifyPlayerPlay.js +70 -0
  150. package/api/spotify/spotifyPlayerPrevious.js +55 -0
  151. package/api/spotify/spotifyPlaylistCreate.js +63 -0
  152. package/api/spotify/spotifyPlaylistGet.js +91 -0
  153. package/api/spotify/spotifyPlaylistItemsAdd.js +61 -0
  154. package/api/spotify/spotifyPlaylistItemsGet.js +58 -0
  155. package/api/spotify/spotifyPlaylistItemsRemove.js +67 -0
  156. package/api/spotify/spotifyPlaylistUpdate.js +64 -0
  157. package/api/spotify/spotifyPlaylistsGet.js +47 -0
  158. package/api/spotify/spotifySavedTracksGet.js +46 -0
  159. package/api/spotify/spotifySavedTracksRemove.js +59 -0
  160. package/api/spotify/spotifySavedTracksSave.js +59 -0
  161. package/api/spotify/spotifySearch.js +174 -0
  162. package/api/spotify/spotifyTrackGet.js +76 -0
  163. package/api/tableau/tableau.constants.js +8 -0
  164. package/api/tableau/tableau.utils.js +93 -0
  165. package/api/tableau/tableauGet.js +174 -0
  166. package/api/tableau/tableauUserAdd.js +16 -94
  167. package/api/tableau/tableauUsersGet.js +46 -134
  168. package/api/tagalys/docs.md +2 -2
  169. package/api/tagalys/tagalys.constants.js +17 -0
  170. package/api/tagalys/tagalys.utils.js +125 -0
  171. package/api/tagalys/tagalysAnalyticsEventSend.js +125 -0
  172. package/api/tagalys/tagalysCollectionGet.js +100 -0
  173. package/api/tagalys/tagalysPopularSearchesGet.js +60 -0
  174. package/api/tagalys/tagalysRecommendationGet.js +109 -0
  175. package/api/tagalys/tagalysSearch.js +15 -89
  176. package/api/tagalys/tagalysSearchSuggestionsGet.js +76 -0
  177. package/package.json +2 -1
  178. package/server.js +3 -1
@@ -0,0 +1,174 @@
1
+ // https://developer.spotify.com/documentation/web-api/reference/search
2
+
3
+ const { ArgsWarden, Getter } = require('../utils');
4
+ const { credsValidator } = require('../validators');
5
+ const { spotifyClient } = require('../spotify/spotify.utils');
6
+ const { MAX_SEARCH_PER_PAGE } = require('../spotify/spotify.constants');
7
+
8
+ const argsWarden = new ArgsWarden([
9
+ ['credsPayload', credsValidator],
10
+ ['query'],
11
+ ['types'],
12
+ ]);
13
+
14
+ const digSearchResults = (data, types) => {
15
+ const typeList = (Array.isArray(types) ? types : String(types).split(','))
16
+ .map((t) => t.trim())
17
+ .filter(Boolean);
18
+
19
+ // Flatten matches across requested types, tagging each with its type key.
20
+ const out = [];
21
+ for (const type of typeList) {
22
+ const key = type.endsWith('s') ? type : `${ type }s`;
23
+ const page = data?.[key];
24
+ const items = page?.items ?? [];
25
+ for (const item of items) {
26
+ out.push({ type: key, ...item });
27
+ }
28
+ }
29
+ return out;
30
+ };
31
+
32
+ const spotifySearchPacket = async (
33
+ credsPayload,
34
+ query,
35
+ types,
36
+ {
37
+ params = {},
38
+ perPage = MAX_SEARCH_PER_PAGE,
39
+ fetchClient = spotifyClient,
40
+ } = {},
41
+ ) => {
42
+ const typeParam = Array.isArray(types) ? types.join(',') : types;
43
+
44
+ return fetchClient.fetch({
45
+ context: { credsPayload },
46
+ requestPayload: {
47
+ method: 'get',
48
+ url: '/search',
49
+ params: {
50
+ q: query,
51
+ type: typeParam,
52
+ limit: Math.min(perPage, MAX_SEARCH_PER_PAGE),
53
+ offset: 0,
54
+ ...params,
55
+ },
56
+ },
57
+ });
58
+ };
59
+
60
+ const spotifySearchPaginator = async (currentParams, response) => {
61
+ if (!response?.ok) {
62
+ return [true];
63
+ }
64
+
65
+ const data = response.data ?? {};
66
+ // Any requested type still having a next URL means we continue.
67
+ const hasNext = Object.values(data).some(
68
+ (page) => page && typeof page === 'object' && page.next,
69
+ );
70
+ if (!hasNext) {
71
+ return [true];
72
+ }
73
+
74
+ const { args, options } = currentParams;
75
+ const { params = {}, perPage = MAX_SEARCH_PER_PAGE } = options;
76
+ const currentOffset = Number(params.offset ?? 0);
77
+ const pageLimit = Number(params.limit ?? perPage);
78
+
79
+ return [false, {
80
+ args,
81
+ options: {
82
+ ...options,
83
+ params: {
84
+ ...params,
85
+ offset: currentOffset + pageLimit,
86
+ limit: pageLimit,
87
+ },
88
+ },
89
+ }];
90
+ };
91
+
92
+ const spotifySearch = async (
93
+ returnGetter,
94
+
95
+ credsPayload,
96
+ query,
97
+ types,
98
+ {
99
+ market,
100
+ includeExternal,
101
+ perPage = MAX_SEARCH_PER_PAGE,
102
+ fetchClient,
103
+ ...getterOptions
104
+ } = {},
105
+ ) => {
106
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
107
+ credsPayload,
108
+ query,
109
+ types,
110
+ });
111
+ if (rejectResponse) {
112
+ return rejectResponse;
113
+ }
114
+
115
+ const typeList = Array.isArray(types) ? types : String(types).split(',');
116
+
117
+ const getter = new Getter(
118
+ {
119
+ args: [credsPayload, query, types],
120
+ options: {
121
+ params: {
122
+ ...(market !== undefined && { market }),
123
+ ...(includeExternal !== undefined && {
124
+ include_external: includeExternal,
125
+ }),
126
+ },
127
+ perPage,
128
+ fetchClient,
129
+ },
130
+ },
131
+ {
132
+ func: spotifySearchPacket,
133
+ digester: (response) => {
134
+ if (!response?.ok) {
135
+ return [];
136
+ }
137
+ return digSearchResults(response.data, typeList);
138
+ },
139
+ paginator: spotifySearchPaginator,
140
+ ...getterOptions,
141
+ },
142
+ );
143
+
144
+ if (returnGetter) {
145
+ return getter;
146
+ }
147
+
148
+ const data = await getter.run({ returnAll: true });
149
+
150
+ return {
151
+ ok: true,
152
+ data,
153
+ };
154
+ };
155
+
156
+ const funcApiConfig = {
157
+ argsWarden,
158
+ };
159
+
160
+ module.exports = {
161
+ spotifySearch: (...args) => spotifySearch(false, ...args),
162
+ spotifySearchGetter: (...args) => spotifySearch(true, ...args),
163
+ funcApiConfig,
164
+ };
165
+
166
+ /*
167
+ curl -X POST "http://localhost:8000/spotifySearch" \
168
+ -H "Content-Type: application/json" \
169
+ -d '{
170
+ "credsPayload": { "credsPath": "spotify" },
171
+ "query": "radiohead",
172
+ "types": ["artist", "album"]
173
+ }'
174
+ */
@@ -0,0 +1,76 @@
1
+ // https://developer.spotify.com/documentation/web-api/reference/get-track
2
+
3
+ const { ArgsWarden, actionSingleOrMultiple, logDeep } = require('../utils');
4
+ const { credsValidator } = require('../validators');
5
+ const { spotifyClient } = require('../spotify/spotify.utils');
6
+
7
+ const argsWarden = new ArgsWarden([
8
+ ['credsPayload', credsValidator],
9
+ ['trackId'],
10
+ ]);
11
+
12
+ const spotifyTrackGetSingle = async (
13
+ credsPayload,
14
+ trackId,
15
+ {
16
+ market,
17
+ fetchClient = spotifyClient,
18
+ } = {},
19
+ ) => {
20
+ const response = await fetchClient.fetch({
21
+ context: { credsPayload },
22
+ requestPayload: {
23
+ method: 'get',
24
+ url: `/tracks/${ trackId }`,
25
+ params: {
26
+ ...(market !== undefined && { market }),
27
+ },
28
+ },
29
+ });
30
+
31
+ const { ok, data, error } = response;
32
+ if (!ok) {
33
+ logDeep({ error });
34
+ return { ok: false, error };
35
+ }
36
+
37
+ return { ok: true, data };
38
+ };
39
+
40
+ const spotifyTrackGet = async (
41
+ credsPayload,
42
+ trackId,
43
+ {
44
+ market,
45
+ queueRunOptions,
46
+ fetchClient,
47
+ } = {},
48
+ ) => {
49
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
50
+ credsPayload,
51
+ trackId,
52
+ });
53
+ if (rejectResponse) {
54
+ return rejectResponse;
55
+ }
56
+
57
+ return actionSingleOrMultiple(
58
+ trackId,
59
+ spotifyTrackGetSingle,
60
+ (trackIdItem) => ({
61
+ args: [credsPayload, trackIdItem, { market, fetchClient }],
62
+ }),
63
+ {
64
+ ...(queueRunOptions ? { queueRunOptions } : {}),
65
+ },
66
+ );
67
+ };
68
+
69
+ const funcApiConfig = {
70
+ argsWarden,
71
+ };
72
+
73
+ module.exports = {
74
+ spotifyTrackGet,
75
+ funcApiConfig,
76
+ };
@@ -0,0 +1,8 @@
1
+ const DEFAULT_API_VERSION = '3.22';
2
+ // Tableau's max page size for list endpoints
3
+ const MAX_PER_PAGE = 1000;
4
+
5
+ module.exports = {
6
+ DEFAULT_API_VERSION,
7
+ MAX_PER_PAGE,
8
+ };
@@ -0,0 +1,93 @@
1
+ const { DEFAULT_API_VERSION } = require('../tableau/tableau.constants');
2
+ const { resolveCreds } = require('../pipelineSteps');
3
+ const {
4
+ FetchClient,
5
+ appendUrlToBase,
6
+ fetchClientCommonSteps,
7
+ } = require('../utils');
8
+
9
+ // Tableau sessions are token-based (sign in -> token, valid ~2hrs by default
10
+ // server config), unlike Shopify's static API key. We cache tokens per
11
+ // server+site so we're not re-signing-in on every single call.
12
+ const tokenCache = new Map();
13
+
14
+ const tableauSignIn = async ({
15
+ SERVER_URL,
16
+ PAT_NAME,
17
+ PAT_SECRET,
18
+ SITE_CONTENT_URL = '',
19
+ }) => {
20
+ const cacheKey = `${ SERVER_URL }::${ SITE_CONTENT_URL }`;
21
+ const cached = tokenCache.get(cacheKey);
22
+ if (cached && cached.expiresAt > Date.now()) {
23
+ return cached;
24
+ }
25
+
26
+ const response = await fetch(`${ SERVER_URL }/api/${ DEFAULT_API_VERSION }/auth/signin`, {
27
+ method: 'POST',
28
+ headers: {
29
+ 'Content-Type': 'application/json',
30
+ Accept: 'application/json',
31
+ },
32
+ body: JSON.stringify({
33
+ credentials: {
34
+ personalAccessTokenName: PAT_NAME,
35
+ personalAccessTokenSecret: PAT_SECRET,
36
+ site: { contentUrl: SITE_CONTENT_URL },
37
+ },
38
+ }),
39
+ });
40
+
41
+ if (!response.ok) {
42
+ throw new Error(`Tableau sign-in failed: ${ response.status } ${ await response.text() }`);
43
+ }
44
+
45
+ const { credentials } = await response.json();
46
+
47
+ const session = {
48
+ token: credentials.token,
49
+ siteId: credentials.site.id,
50
+ // Refresh a bit early rather than riding right up against the server's
51
+ // idle/absolute timeout.
52
+ expiresAt: Date.now() + 1000 * 60 * 60 * 2,
53
+ };
54
+
55
+ tokenCache.set(cacheKey, session);
56
+ return session;
57
+ };
58
+
59
+ const useUrlAndAuthHeaders = async (state) => {
60
+ const { requestPayload, context } = state;
61
+ const { creds } = context;
62
+
63
+ const { token, siteId } = await tableauSignIn(creds);
64
+
65
+ return {
66
+ requestPayload: {
67
+ ...requestPayload,
68
+ url: appendUrlToBase(
69
+ `${ creds.SERVER_URL }/api/${ DEFAULT_API_VERSION }`,
70
+ requestPayload.url.replace('{siteId}', siteId),
71
+ ),
72
+ headers: {
73
+ 'X-Tableau-Auth': token,
74
+ Accept: 'application/json',
75
+ ...requestPayload.headers,
76
+ },
77
+ },
78
+ };
79
+ };
80
+
81
+ const tableauClient = new FetchClient({
82
+ pipeline: [
83
+ resolveCreds,
84
+ useUrlAndAuthHeaders,
85
+ 'fetch',
86
+ fetchClientCommonSteps.exitEarlyOnNotOk,
87
+ ],
88
+ });
89
+
90
+ module.exports = {
91
+ tableauClient,
92
+ tableauSignIn,
93
+ };
@@ -0,0 +1,174 @@
1
+ // https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_concepts_paging.htm
2
+
3
+ const { ArgsWarden, Getter } = require('../utils');
4
+ const { credsValidator } = require('../validators');
5
+ const { tableauClient } = require('../tableau/tableau.utils');
6
+ const { MAX_PER_PAGE } = require('../tableau/tableau.constants');
7
+
8
+ const argsWarden = new ArgsWarden([
9
+ ['credsPayload', credsValidator],
10
+ ['url'],
11
+ ]);
12
+
13
+ // Tableau list responses nest items, e.g. data.users.user, data.workbooks.workbook.
14
+ // resultsKey may be a dotted path such as "users.user".
15
+ const digResults = (data, resultsKey) => {
16
+ if (resultsKey) {
17
+ const value = resultsKey.split('.').reduce(
18
+ (node, key) => node?.[key],
19
+ data,
20
+ );
21
+ if (Array.isArray(value)) {
22
+ return value;
23
+ }
24
+ return value != null ? [value] : [];
25
+ }
26
+
27
+ if (Array.isArray(data)) {
28
+ return data;
29
+ }
30
+
31
+ const arrayEntry = Object.entries(data || {}).find(([, value]) => Array.isArray(value));
32
+ return arrayEntry ? arrayEntry[1] : [];
33
+ };
34
+
35
+ const tableauGetPacket = async (
36
+ credsPayload,
37
+ url,
38
+ {
39
+ params,
40
+ perPage = MAX_PER_PAGE,
41
+ fetchClient = tableauClient,
42
+ } = {},
43
+ ) => {
44
+ return fetchClient.fetch({
45
+ requestPayload: {
46
+ method: 'get',
47
+ url,
48
+ params: {
49
+ pageSize: Math.min(perPage, MAX_PER_PAGE),
50
+ pageNumber: 1,
51
+ ...params,
52
+ },
53
+ },
54
+ context: {
55
+ credsPayload,
56
+ },
57
+ });
58
+ };
59
+
60
+ const tableauGetPaginator = async (currentParams, response) => {
61
+ if (!response?.ok) {
62
+ return [true];
63
+ }
64
+
65
+ const pagination = response?.data?.pagination;
66
+ if (!pagination) {
67
+ return [true];
68
+ }
69
+
70
+ const pageNumber = Number(pagination.pageNumber);
71
+ const pageSize = Number(pagination.pageSize);
72
+ const totalAvailable = Number(pagination.totalAvailable);
73
+
74
+ if (!pageNumber || !pageSize || Number.isNaN(totalAvailable)) {
75
+ return [true];
76
+ }
77
+
78
+ if (pageNumber * pageSize >= totalAvailable) {
79
+ return [true];
80
+ }
81
+
82
+ const { args, options } = currentParams;
83
+
84
+ return [false, {
85
+ args,
86
+ options: {
87
+ ...options,
88
+ params: {
89
+ ...options.params,
90
+ pageNumber: pageNumber + 1,
91
+ },
92
+ },
93
+ }];
94
+ };
95
+
96
+ const tableauGet = async (
97
+ returnGetter,
98
+
99
+ credsPayload,
100
+ url,
101
+ {
102
+ params,
103
+ perPage = MAX_PER_PAGE,
104
+ resultsKey,
105
+ fetchClient,
106
+ ...getterOptions
107
+ } = {},
108
+ ) => {
109
+
110
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
111
+ credsPayload,
112
+ url,
113
+ });
114
+ if (rejectResponse) {
115
+ return rejectResponse;
116
+ }
117
+
118
+ const getter = new Getter(
119
+ {
120
+ args: [credsPayload, url],
121
+ options: {
122
+ params,
123
+ perPage,
124
+ fetchClient,
125
+ },
126
+ },
127
+ {
128
+ func: tableauGetPacket,
129
+ digester: (response) => {
130
+ if (!response?.ok) {
131
+ return [];
132
+ }
133
+
134
+ return digResults(response.data, resultsKey);
135
+ },
136
+ paginator: tableauGetPaginator,
137
+ ...getterOptions,
138
+ },
139
+ );
140
+
141
+ if (returnGetter) {
142
+ return getter;
143
+ }
144
+
145
+ const data = await getter.run({ returnAll: true });
146
+
147
+ return {
148
+ ok: true,
149
+ data,
150
+ };
151
+ };
152
+
153
+ const funcApiConfig = {
154
+ argsWarden,
155
+ };
156
+
157
+ module.exports = {
158
+ tableauGet: (...args) => tableauGet(false, ...args),
159
+ tableauGetter: (...args) => tableauGet(true, ...args),
160
+ funcApiConfig,
161
+ };
162
+
163
+ /*
164
+ curl -X POST "http://localhost:8000/tableauGet" \
165
+ -H "Content-Type: application/json" \
166
+ -d '{
167
+ "credsPayload": { "credsPath": "tableau" },
168
+ "url": "/sites/{siteId}/users",
169
+ "options": {
170
+ "resultsKey": "users.user",
171
+ "perPage": 100
172
+ }
173
+ }'
174
+ */
@@ -1,96 +1,11 @@
1
- const { ArgsWarden, logDeep } = require('../utils');
2
- const { resolveCreds } = require('../pipelineSteps');
3
- const {
4
- FetchClient,
5
- appendUrlToBase,
6
- fetchClientCommonSteps,
7
- } = require('../utils');
8
-
9
- const DEFAULT_API_VERSION = '3.22';
10
-
11
- // Tableau sessions are token-based (sign in -> token, valid ~2hrs by default
12
- // server config), unlike Shopify's static API key. We cache tokens per
13
- // server+site so we're not re-signing-in on every single call.
14
- const tokenCache = new Map();
15
-
16
- const tableauSignIn = async ({
17
- SERVER_URL,
18
- PAT_NAME,
19
- PAT_SECRET,
20
- SITE_CONTENT_URL = '',
21
- }) => {
22
- const cacheKey = `${ SERVER_URL }::${ SITE_CONTENT_URL }`;
23
- const cached = tokenCache.get(cacheKey);
24
- if (cached && cached.expiresAt > Date.now()) {
25
- return cached;
26
- }
27
-
28
- const response = await fetch(`${ SERVER_URL }/api/${ DEFAULT_API_VERSION }/auth/signin`, {
29
- method: 'POST',
30
- headers: {
31
- 'Content-Type': 'application/json',
32
- Accept: 'application/json',
33
- },
34
- body: JSON.stringify({
35
- credentials: {
36
- personalAccessTokenName: PAT_NAME,
37
- personalAccessTokenSecret: PAT_SECRET,
38
- site: { contentUrl: SITE_CONTENT_URL },
39
- },
40
- }),
41
- });
42
-
43
- if (!response.ok) {
44
- throw new Error(`Tableau sign-in failed: ${ response.status } ${ await response.text() }`);
45
- }
46
-
47
- const { credentials } = await response.json();
48
-
49
- const session = {
50
- token: credentials.token,
51
- siteId: credentials.site.id,
52
- // Refresh a bit early rather than riding right up against the server's
53
- // idle/absolute timeout.
54
- expiresAt: Date.now() + 1000 * 60 * 60 * 2,
55
- };
56
-
57
- tokenCache.set(cacheKey, session);
58
- return session;
59
- };
60
-
61
- const useUrlAndAuthHeaders = async (state) => {
62
- const { requestPayload, context } = state;
63
- const { creds } = context;
1
+ // https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_users_and_groups.htm#add_user_to_site
64
2
 
65
- const { token, siteId } = await tableauSignIn(creds);
66
-
67
- return {
68
- requestPayload: {
69
- ...requestPayload,
70
- url: appendUrlToBase(
71
- `${ creds.SERVER_URL }/api/${ DEFAULT_API_VERSION }`,
72
- requestPayload.url.replace('{siteId}', siteId),
73
- ),
74
- headers: {
75
- 'X-Tableau-Auth': token,
76
- 'Content-Type': 'application/json',
77
- Accept: 'application/json',
78
- ...requestPayload.headers,
79
- },
80
- },
81
- };
82
- };
83
-
84
- const tableauClient = new FetchClient({
85
- pipeline: [
86
- resolveCreds,
87
- useUrlAndAuthHeaders,
88
- 'fetch',
89
- fetchClientCommonSteps.exitEarlyOnNotOk,
90
- ],
91
- });
3
+ const { ArgsWarden, logDeep } = require('../utils');
4
+ const { credsValidator } = require('../validators');
5
+ const { tableauClient } = require('../tableau/tableau.utils');
92
6
 
93
7
  const argsWarden = new ArgsWarden([
8
+ ['credsPayload', credsValidator],
94
9
  ['username'],
95
10
  ['siteRole'],
96
11
  ]);
@@ -99,13 +14,16 @@ const argsWarden = new ArgsWarden([
99
14
  // role: Creator, Explorer, ExplorerCanPublish, Viewer, SiteAdministratorCreator,
100
15
  // SiteAdministratorExplorer, Unlicensed, etc.
101
16
  const tableauUserAdd = async (
17
+ credsPayload,
102
18
  username,
103
19
  siteRole = 'Viewer',
104
20
  {
105
21
  authSetting, // optional: 'ServerDefault' | 'SAML' | 'OpenID' | 'TableauIDWithMFA' ...
22
+ fetchClient = tableauClient,
106
23
  } = {},
107
24
  ) => {
108
25
  const rejectResponse = await argsWarden.responseIfRejectingArgs({
26
+ credsPayload,
109
27
  username,
110
28
  siteRole,
111
29
  });
@@ -113,9 +31,9 @@ const tableauUserAdd = async (
113
31
  return rejectResponse;
114
32
  }
115
33
 
116
- const response = await tableauClient.fetch({
34
+ const response = await fetchClient.fetch({
117
35
  context: {
118
- credsPayload: { credsPath: ['tableau'] },
36
+ credsPayload,
119
37
  },
120
38
  requestPayload: {
121
39
  url: '/sites/{siteId}/users',
@@ -148,11 +66,15 @@ const funcApiConfig = {
148
66
 
149
67
  module.exports = {
150
68
  tableauUserAdd,
151
- tableauClient,
152
69
  funcApiConfig,
153
70
  };
154
71
 
155
72
  /*
156
73
  curl -X POST "http://localhost:8000/tableauUserAdd" \
157
- -d '{ "username": "dora@example.com", "siteRole": "Explorer" }'
74
+ -H "Content-Type: application/json" \
75
+ -d '{
76
+ "credsPayload": { "credsPath": "tableau" },
77
+ "username": "dora@example.com",
78
+ "siteRole": "Explorer"
79
+ }'
158
80
  */