@slates/profiles 1.0.0-rc.2

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.
@@ -0,0 +1,403 @@
1
+ // src/client.ts
2
+ import { createLocalSlateTransport, createSlatesClient } from "@slates/client";
3
+ import path2 from "path";
4
+ import { pathToFileURL } from "url";
5
+
6
+ // src/store.ts
7
+ import { execFileSync } from "child_process";
8
+ import { randomUUID } from "crypto";
9
+ import { mkdir, readFile, writeFile } from "fs/promises";
10
+ import path from "path";
11
+ var STORE_VERSION = 3;
12
+ var CLI_DIR_NAME = ".slates-cli";
13
+ var PROFILES_DIR_NAME = "profiles";
14
+ var STORE_FILE_NAME = "store.json";
15
+ var GITIGNORE_FILE_NAME = ".gitignore";
16
+ var createEmptyStore = () => ({
17
+ version: STORE_VERSION,
18
+ currentProfileId: null,
19
+ profiles: {},
20
+ oauthCredentials: {}
21
+ });
22
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
23
+ var ensureDir = async (dirPath) => {
24
+ await mkdir(dirPath, { recursive: true });
25
+ };
26
+ var ensureGitIgnore = async (dirPath) => {
27
+ let filePath = path.join(dirPath, GITIGNORE_FILE_NAME);
28
+ await writeFile(filePath, "*\n!.gitignore\n", { encoding: "utf-8" }).catch(async (error) => {
29
+ if (error.code === "EEXIST") return;
30
+ throw error;
31
+ });
32
+ };
33
+ var resolveSlatesCliRoot = (cwd = process.cwd()) => {
34
+ try {
35
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
36
+ cwd,
37
+ stdio: ["ignore", "pipe", "ignore"],
38
+ encoding: "utf-8"
39
+ }).trim();
40
+ } catch {
41
+ return cwd;
42
+ }
43
+ };
44
+ var resolveSlatesCliDir = (cwd = process.cwd()) => path.join(resolveSlatesCliRoot(cwd), CLI_DIR_NAME);
45
+ var resolveSlatesCliProfilesDir = (cwd = process.cwd()) => path.join(resolveSlatesCliDir(cwd), PROFILES_DIR_NAME);
46
+ var normalizeScopeKey = (scopeKey) => path.posix.normalize(scopeKey.replace(/\\/g, "/")).replace(/^\.?\//, "");
47
+ var splitScopeKey = (scopeKey) => normalizeScopeKey(scopeKey).split("/").filter(Boolean).filter((segment) => segment !== "." && segment !== "..");
48
+ var resolveScopedStoreDir = (rootDir, scopeKey) => path.join(resolveSlatesCliProfilesDir(rootDir), ...splitScopeKey(scopeKey));
49
+ var resolveScopedStorePath = (rootDir, scopeKey) => path.join(resolveScopedStoreDir(rootDir, scopeKey), STORE_FILE_NAME);
50
+ var inferRootDirFromStorePath = (storePath) => {
51
+ let normalized = path.resolve(storePath);
52
+ let parts = normalized.split(path.sep).filter(Boolean);
53
+ let cliDirIndex = parts.lastIndexOf(CLI_DIR_NAME);
54
+ if (cliDirIndex === -1) {
55
+ throw new Error(`Could not infer Slates CLI root from store path: ${storePath}`);
56
+ }
57
+ let rootParts = parts.slice(0, cliDirIndex);
58
+ return path.join(path.sep, ...rootParts);
59
+ };
60
+ var resolveScopeKeyFromStorePath = (rootDir, storePath) => {
61
+ let profilesDir = resolveSlatesCliProfilesDir(rootDir);
62
+ let relativeDir = path.relative(profilesDir, path.dirname(storePath));
63
+ if (!relativeDir || relativeDir.startsWith("..") || path.isAbsolute(relativeDir)) {
64
+ return null;
65
+ }
66
+ return normalizeScopeKey(relativeDir);
67
+ };
68
+ var readStoreData = async (storePath) => {
69
+ try {
70
+ let raw = await readFile(storePath, "utf-8");
71
+ if (!raw.trim()) {
72
+ return null;
73
+ }
74
+ return JSON.parse(raw);
75
+ } catch (error) {
76
+ if (error.code === "ENOENT") {
77
+ return null;
78
+ }
79
+ throw error;
80
+ }
81
+ };
82
+ var isProfileInScope = (rootDir, scopeKey, profile) => {
83
+ if (profile.target.type !== "local") {
84
+ return false;
85
+ }
86
+ let scopeDir = path.resolve(rootDir, ...splitScopeKey(scopeKey));
87
+ let entryPath = path.isAbsolute(profile.target.entry) ? profile.target.entry : path.resolve(rootDir, profile.target.entry);
88
+ let relative = path.relative(scopeDir, entryPath);
89
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
90
+ };
91
+ var loadMigratedLegacyStore = async (rootDir, scopeKey) => {
92
+ let legacyStorePath = path.join(resolveSlatesCliDir(rootDir), STORE_FILE_NAME);
93
+ let legacy = await readStoreData(legacyStorePath);
94
+ if (!legacy) {
95
+ return createEmptyStore();
96
+ }
97
+ let profiles = Object.fromEntries(
98
+ Object.entries(legacy.profiles ?? {}).filter(
99
+ ([, profile]) => isProfileInScope(rootDir, scopeKey, profile)
100
+ )
101
+ );
102
+ let currentProfileId = legacy.currentProfileId && profiles[legacy.currentProfileId] ? legacy.currentProfileId : null;
103
+ return {
104
+ version: STORE_VERSION,
105
+ currentProfileId,
106
+ profiles,
107
+ oauthCredentials: {}
108
+ };
109
+ };
110
+ var SlatesCliStore = class _SlatesCliStore {
111
+ constructor(rootDir, dirPath, storePath, scope, data) {
112
+ this.rootDir = rootDir;
113
+ this.dirPath = dirPath;
114
+ this.storePath = storePath;
115
+ this.scope = scope;
116
+ this.data = data;
117
+ }
118
+ rootDir;
119
+ dirPath;
120
+ storePath;
121
+ scope;
122
+ data;
123
+ static async open(opts = {}) {
124
+ let rootDir = opts.storePath ? inferRootDirFromStorePath(opts.storePath) : resolveSlatesCliRoot(opts.cwd);
125
+ let cliDir = resolveSlatesCliDir(rootDir);
126
+ let scopeKey = opts.storePath ? resolveScopeKeyFromStorePath(rootDir, opts.storePath) : opts.scope?.key ? normalizeScopeKey(opts.scope.key) : null;
127
+ let dirPath = opts.storePath ? path.dirname(opts.storePath) : scopeKey ? resolveScopedStoreDir(rootDir, scopeKey) : cliDir;
128
+ let storePath = opts.storePath ?? (scopeKey ? resolveScopedStorePath(rootDir, scopeKey) : path.join(cliDir, STORE_FILE_NAME));
129
+ await ensureDir(cliDir);
130
+ await ensureGitIgnore(cliDir);
131
+ await ensureDir(dirPath);
132
+ let parsed = await readStoreData(storePath);
133
+ let data = parsed ? {
134
+ version: STORE_VERSION,
135
+ currentProfileId: parsed.currentProfileId ?? null,
136
+ profiles: parsed.profiles ?? {},
137
+ oauthCredentials: parsed.oauthCredentials ?? {}
138
+ } : scopeKey ? await loadMigratedLegacyStore(rootDir, scopeKey) : createEmptyStore();
139
+ if (!parsed) {
140
+ await writeFile(storePath, JSON.stringify(data, null, 2) + "\n", "utf-8");
141
+ }
142
+ return new _SlatesCliStore(
143
+ rootDir,
144
+ dirPath,
145
+ storePath,
146
+ scopeKey ? { key: scopeKey, name: opts.scope?.name } : null,
147
+ data
148
+ );
149
+ }
150
+ async save() {
151
+ await ensureDir(this.dirPath);
152
+ await ensureDir(resolveSlatesCliDir(this.rootDir));
153
+ await ensureGitIgnore(resolveSlatesCliDir(this.rootDir));
154
+ await writeFile(this.storePath, JSON.stringify(this.data, null, 2) + "\n", "utf-8");
155
+ }
156
+ listProfiles() {
157
+ return Object.values(this.data.profiles).sort((a, b) => a.name.localeCompare(b.name));
158
+ }
159
+ listOAuthCredentials(authMethodId) {
160
+ return Object.values(this.data.oauthCredentials).filter((credential) => !authMethodId || credential.authMethodId === authMethodId).sort((a, b) => a.name.localeCompare(b.name));
161
+ }
162
+ getOAuthCredential(credentialId, authMethodId) {
163
+ if (credentialId) {
164
+ let direct = this.data.oauthCredentials[credentialId];
165
+ if (direct && (!authMethodId || direct.authMethodId === authMethodId)) {
166
+ return direct;
167
+ }
168
+ let matches = this.listOAuthCredentials(authMethodId ?? void 0).filter(
169
+ (credential) => credential.name === credentialId
170
+ );
171
+ if (matches.length === 1) {
172
+ return matches[0];
173
+ }
174
+ }
175
+ return this.listOAuthCredentials(authMethodId ?? void 0)[0] ?? null;
176
+ }
177
+ getProfile(profileId) {
178
+ if (profileId) {
179
+ if (this.data.profiles[profileId]) {
180
+ return this.data.profiles[profileId] ?? null;
181
+ }
182
+ let matches = this.listProfiles().filter((profile) => profile.name === profileId);
183
+ if (matches.length === 1) {
184
+ return matches[0];
185
+ }
186
+ }
187
+ if (this.data.currentProfileId && this.data.profiles[this.data.currentProfileId]) {
188
+ return this.data.profiles[this.data.currentProfileId];
189
+ }
190
+ return this.listProfiles()[0] ?? null;
191
+ }
192
+ requireProfile(profileId) {
193
+ let profile = this.getProfile(profileId);
194
+ if (!profile) {
195
+ throw new Error("No Slates profile found for this integration.");
196
+ }
197
+ return profile;
198
+ }
199
+ upsertProfile(d) {
200
+ let existing = d.profileId ? this.data.profiles[d.profileId] : void 0;
201
+ let id = existing?.id ?? d.profileId ?? randomUUID();
202
+ let createdAt = existing?.createdAt ?? now();
203
+ let profile = {
204
+ id,
205
+ name: d.name,
206
+ target: d.target,
207
+ config: d.config ?? existing?.config ?? null,
208
+ auth: existing?.auth ?? {},
209
+ session: d.session ?? existing?.session ?? null,
210
+ metadata: {
211
+ provider: d.metadata?.provider ?? existing?.metadata?.provider ?? null,
212
+ actions: d.metadata?.actions ?? existing?.metadata?.actions ?? null
213
+ },
214
+ createdAt,
215
+ updatedAt: now()
216
+ };
217
+ this.data.profiles[id] = profile;
218
+ if (!this.data.currentProfileId) {
219
+ this.data.currentProfileId = id;
220
+ }
221
+ return profile;
222
+ }
223
+ upsertOAuthCredential(d) {
224
+ let existing = d.credentialId ? this.data.oauthCredentials[d.credentialId] : void 0;
225
+ let id = existing?.id ?? d.credentialId ?? randomUUID();
226
+ let credential = {
227
+ id,
228
+ name: d.name,
229
+ authMethodId: d.authMethodId,
230
+ clientId: d.clientId,
231
+ clientSecret: d.clientSecret,
232
+ createdAt: existing?.createdAt ?? now(),
233
+ updatedAt: now()
234
+ };
235
+ this.data.oauthCredentials[id] = credential;
236
+ return credential;
237
+ }
238
+ setCurrentProfile(profileId) {
239
+ if (!this.data.profiles[profileId]) {
240
+ throw new Error(`Unknown profile: ${profileId}`);
241
+ }
242
+ this.data.currentProfileId = profileId;
243
+ }
244
+ removeProfile(profileId) {
245
+ delete this.data.profiles[profileId];
246
+ if (this.data.currentProfileId === profileId) {
247
+ this.data.currentProfileId = this.listProfiles()[0]?.id ?? null;
248
+ }
249
+ }
250
+ setProfileConfig(profileId, config) {
251
+ let profile = this.requireProfile(profileId);
252
+ profile.config = config;
253
+ profile.updatedAt = now();
254
+ return profile;
255
+ }
256
+ setProfileSession(profileId, session) {
257
+ let profile = this.requireProfile(profileId);
258
+ profile.session = session;
259
+ profile.updatedAt = now();
260
+ return profile;
261
+ }
262
+ setProfileMetadata(profileId, metadata) {
263
+ let profile = this.requireProfile(profileId);
264
+ profile.metadata = {
265
+ provider: metadata.provider ?? profile.metadata.provider ?? null,
266
+ actions: metadata.actions ?? profile.metadata.actions ?? null
267
+ };
268
+ profile.updatedAt = now();
269
+ return profile;
270
+ }
271
+ upsertAuth(profileId, auth) {
272
+ let profile = this.requireProfile(profileId);
273
+ let existing = profile.auth[auth.authMethodId];
274
+ profile.auth[auth.authMethodId] = {
275
+ ...auth,
276
+ id: auth.id ?? existing?.id ?? randomUUID(),
277
+ createdAt: existing?.createdAt ?? now(),
278
+ updatedAt: now()
279
+ };
280
+ profile.updatedAt = now();
281
+ return profile.auth[auth.authMethodId];
282
+ }
283
+ getAuth(profileId, authMethodId) {
284
+ let profile = this.requireProfile(profileId);
285
+ if (authMethodId) return profile.auth[authMethodId] ?? null;
286
+ return Object.values(profile.auth)[0] ?? null;
287
+ }
288
+ listAuth(profileId) {
289
+ let profile = this.requireProfile(profileId);
290
+ return Object.values(profile.auth).sort(
291
+ (a, b) => a.authMethodId.localeCompare(b.authMethodId)
292
+ );
293
+ }
294
+ };
295
+ var openSlatesCliStore = async (opts = {}) => SlatesCliStore.open(opts);
296
+
297
+ // src/client.ts
298
+ var resolveEntryPath = (entry, cwd) => {
299
+ if (path2.isAbsolute(entry)) return entry;
300
+ return path2.resolve(resolveSlatesCliRoot(cwd), entry);
301
+ };
302
+ var loadSlateFromProfile = async (profile, cwd) => {
303
+ if (profile.target.type !== "local") {
304
+ throw new Error(`Unsupported profile target type: ${profile.target.type}`);
305
+ }
306
+ let modulePath = resolveEntryPath(profile.target.entry, cwd);
307
+ let loaded = await import(pathToFileURL(modulePath).href);
308
+ let exportName = profile.target.exportName;
309
+ let slate = (exportName ? loaded[exportName] : void 0) ?? loaded.provider ?? loaded.slate ?? loaded.default;
310
+ if (!slate) {
311
+ throw new Error(
312
+ `Could not find a slate export in ${profile.target.entry}. Tried ${exportName ? `\`${exportName}\`, ` : ""}\`provider\`, \`slate\`, and \`default\`.`
313
+ );
314
+ }
315
+ return slate;
316
+ };
317
+ var createSlatesClientFromProfile = async (profile, opts = {}) => {
318
+ let firstAuth = Object.values(profile.auth)[0];
319
+ let slate = await loadSlateFromProfile(profile, opts.cwd);
320
+ let client = createSlatesClient({
321
+ transport: createLocalSlateTransport({ slate }),
322
+ state: {
323
+ config: profile.config,
324
+ session: profile.session,
325
+ auth: firstAuth ? {
326
+ authenticationMethodId: firstAuth.authMethodId,
327
+ output: firstAuth.output
328
+ } : null
329
+ }
330
+ });
331
+ if (firstAuth) {
332
+ attachAutoRefresh(client, profile, firstAuth, opts.store);
333
+ }
334
+ return client;
335
+ };
336
+ var EXPIRY_BUFFER_MS = 60 * 1e3;
337
+ var shouldRefreshOAuthAuth = (auth) => {
338
+ if (auth.authType !== "auth.oauth") return false;
339
+ if (!auth.clientId || !auth.clientSecret) return false;
340
+ if (typeof auth.output?.refreshToken !== "string" || !auth.output.refreshToken) return false;
341
+ if (typeof auth.output?.expiresAt !== "string" || !auth.output.expiresAt) return false;
342
+ let expiresAt = Date.parse(auth.output.expiresAt);
343
+ return Number.isFinite(expiresAt) && expiresAt <= Date.now() + EXPIRY_BUFFER_MS;
344
+ };
345
+ var attachAutoRefresh = (client, profile, storedAuth, store) => {
346
+ let baseRequest = client.request.bind(client);
347
+ let inflightRefresh = null;
348
+ let refreshIfNeeded = async () => {
349
+ if (inflightRefresh) {
350
+ await inflightRefresh;
351
+ return;
352
+ }
353
+ if (!shouldRefreshOAuthAuth(storedAuth)) {
354
+ return;
355
+ }
356
+ inflightRefresh = (async () => {
357
+ let authMethod = await baseRequest("slates/auth.method.get", {
358
+ authenticationMethodId: storedAuth.authMethodId
359
+ });
360
+ if (!authMethod.authenticationMethod.capabilities.handleTokenRefresh?.enabled) {
361
+ return;
362
+ }
363
+ let refreshed = await baseRequest("slates/auth.token_refresh.handle", {
364
+ authenticationMethodId: storedAuth.authMethodId,
365
+ output: storedAuth.output,
366
+ input: storedAuth.input,
367
+ clientId: storedAuth.clientId ?? "",
368
+ clientSecret: storedAuth.clientSecret ?? "",
369
+ scopes: storedAuth.scopes
370
+ });
371
+ storedAuth.input = refreshed.input ?? storedAuth.input;
372
+ storedAuth.output = refreshed.output;
373
+ storedAuth.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
374
+ client.setAuth({
375
+ authenticationMethodId: storedAuth.authMethodId,
376
+ output: storedAuth.output
377
+ });
378
+ if (store) {
379
+ store.upsertAuth(profile.id, storedAuth);
380
+ await store.save();
381
+ }
382
+ })();
383
+ try {
384
+ await inflightRefresh;
385
+ } finally {
386
+ inflightRefresh = null;
387
+ }
388
+ };
389
+ client.request = (async (method, params) => {
390
+ if (method !== "slates/auth.token_refresh.handle") {
391
+ await refreshIfNeeded();
392
+ }
393
+ return baseRequest(method, params);
394
+ });
395
+ };
396
+ export {
397
+ SlatesCliStore,
398
+ createSlatesClientFromProfile,
399
+ openSlatesCliStore,
400
+ resolveSlatesCliDir,
401
+ resolveSlatesCliProfilesDir,
402
+ resolveSlatesCliRoot
403
+ };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@slates/profiles",
3
+ "version": "1.0.0-rc.2",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "files": [
8
+ "src/**",
9
+ "dist/**",
10
+ "README.md",
11
+ "package.json"
12
+ ],
13
+ "author": "Tobias Herber",
14
+ "license": "FSL 1.1",
15
+ "type": "module",
16
+ "source": "src/index.ts",
17
+ "exports": {
18
+ "types": "./dist/index.d.ts",
19
+ "require": "./dist/index.cjs",
20
+ "import": "./dist/index.module.js",
21
+ "default": "./dist/index.module.js"
22
+ },
23
+ "main": "./dist/index.cjs",
24
+ "module": "./dist/index.module.js",
25
+ "types": "dist/index.d.ts",
26
+ "unpkg": "./dist/index.module.js",
27
+ "scripts": {
28
+ "test": "vitest run --passWithNoTests",
29
+ "lint": "prettier src/**/*.ts --check",
30
+ "build": "tsup --config ../../tsup.packages.config.ts --external async_hooks",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "dependencies": {
34
+ "@slates/client": "1.0.0-rc.2",
35
+ "@slates/proto": "1.0.0-rc.7"
36
+ },
37
+ "devDependencies": {
38
+ "@slates/provider": "1.0.0-rc.8",
39
+ "@slates/tsconfig": "1.0.0-rc.1",
40
+ "typescript": "5.8.2",
41
+ "vitest": "^3.1.2",
42
+ "zod": "^4.2.1"
43
+ }
44
+ }
package/src/client.ts ADDED
@@ -0,0 +1,143 @@
1
+ import { createLocalSlateTransport, createSlatesClient } from '@slates/client';
2
+ import path from 'path';
3
+ import { pathToFileURL } from 'url';
4
+ import { resolveSlatesCliRoot, SlatesCliStore } from './store';
5
+ import { SlatesProfileRecord, SlatesStoredAuth } from './types';
6
+
7
+ let resolveEntryPath = (entry: string, cwd?: string) => {
8
+ if (path.isAbsolute(entry)) return entry;
9
+ return path.resolve(resolveSlatesCliRoot(cwd), entry);
10
+ };
11
+
12
+ let loadSlateFromProfile = async (profile: SlatesProfileRecord, cwd?: string) => {
13
+ if (profile.target.type !== 'local') {
14
+ throw new Error(`Unsupported profile target type: ${(profile.target as any).type}`);
15
+ }
16
+
17
+ let modulePath = resolveEntryPath(profile.target.entry, cwd);
18
+ let loaded = await import(pathToFileURL(modulePath).href);
19
+ let exportName = profile.target.exportName;
20
+
21
+ let slate =
22
+ (exportName ? loaded[exportName] : undefined) ??
23
+ loaded.provider ??
24
+ loaded.slate ??
25
+ loaded.default;
26
+
27
+ if (!slate) {
28
+ throw new Error(
29
+ `Could not find a slate export in ${profile.target.entry}. Tried ${
30
+ exportName ? `\`${exportName}\`, ` : ''
31
+ }\`provider\`, \`slate\`, and \`default\`.`
32
+ );
33
+ }
34
+
35
+ return slate;
36
+ };
37
+
38
+ export let createSlatesClientFromProfile = async (
39
+ profile: SlatesProfileRecord,
40
+ opts: { cwd?: string; store?: SlatesCliStore } = {}
41
+ ) => {
42
+ let firstAuth = Object.values(profile.auth)[0];
43
+ let slate = await loadSlateFromProfile(profile, opts.cwd);
44
+ let client = createSlatesClient({
45
+ transport: createLocalSlateTransport({ slate }),
46
+ state: {
47
+ config: profile.config,
48
+ session: profile.session,
49
+ auth: firstAuth
50
+ ? {
51
+ authenticationMethodId: firstAuth.authMethodId,
52
+ output: firstAuth.output
53
+ }
54
+ : null
55
+ }
56
+ });
57
+
58
+ if (firstAuth) {
59
+ attachAutoRefresh(client, profile, firstAuth, opts.store);
60
+ }
61
+
62
+ return client;
63
+ };
64
+
65
+ let EXPIRY_BUFFER_MS = 60 * 1000;
66
+
67
+ let shouldRefreshOAuthAuth = (auth: SlatesStoredAuth) => {
68
+ if (auth.authType !== 'auth.oauth') return false;
69
+ if (!auth.clientId || !auth.clientSecret) return false;
70
+ if (typeof auth.output?.refreshToken !== 'string' || !auth.output.refreshToken) return false;
71
+ if (typeof auth.output?.expiresAt !== 'string' || !auth.output.expiresAt) return false;
72
+
73
+ let expiresAt = Date.parse(auth.output.expiresAt);
74
+ return Number.isFinite(expiresAt) && expiresAt <= Date.now() + EXPIRY_BUFFER_MS;
75
+ };
76
+
77
+ let attachAutoRefresh = (
78
+ client: ReturnType<typeof createSlatesClient>,
79
+ profile: SlatesProfileRecord,
80
+ storedAuth: SlatesStoredAuth,
81
+ store?: SlatesCliStore
82
+ ) => {
83
+ let baseRequest = client.request.bind(client);
84
+ let inflightRefresh: Promise<void> | null = null;
85
+
86
+ let refreshIfNeeded = async () => {
87
+ if (inflightRefresh) {
88
+ await inflightRefresh;
89
+ return;
90
+ }
91
+
92
+ if (!shouldRefreshOAuthAuth(storedAuth)) {
93
+ return;
94
+ }
95
+
96
+ inflightRefresh = (async () => {
97
+ let authMethod = await baseRequest('slates/auth.method.get', {
98
+ authenticationMethodId: storedAuth.authMethodId
99
+ });
100
+
101
+ if (!authMethod.authenticationMethod.capabilities.handleTokenRefresh?.enabled) {
102
+ return;
103
+ }
104
+
105
+ let refreshed = await baseRequest('slates/auth.token_refresh.handle', {
106
+ authenticationMethodId: storedAuth.authMethodId,
107
+ output: storedAuth.output,
108
+ input: storedAuth.input,
109
+ clientId: storedAuth.clientId ?? '',
110
+ clientSecret: storedAuth.clientSecret ?? '',
111
+ scopes: storedAuth.scopes
112
+ });
113
+
114
+ storedAuth.input = refreshed.input ?? storedAuth.input;
115
+ storedAuth.output = refreshed.output;
116
+ storedAuth.updatedAt = new Date().toISOString();
117
+
118
+ client.setAuth({
119
+ authenticationMethodId: storedAuth.authMethodId,
120
+ output: storedAuth.output
121
+ });
122
+
123
+ if (store) {
124
+ store.upsertAuth(profile.id, storedAuth);
125
+ await store.save();
126
+ }
127
+ })();
128
+
129
+ try {
130
+ await inflightRefresh;
131
+ } finally {
132
+ inflightRefresh = null;
133
+ }
134
+ };
135
+
136
+ client.request = (async (method, params) => {
137
+ if (method !== 'slates/auth.token_refresh.handle') {
138
+ await refreshIfNeeded();
139
+ }
140
+
141
+ return baseRequest(method as never, params as never);
142
+ }) as typeof client.request;
143
+ };
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './client';
2
+ export * from './store';
3
+ export * from './types';