@slates/profiles 1.0.0-rc.10

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.
package/src/store.ts ADDED
@@ -0,0 +1,442 @@
1
+ import { execFileSync } from 'child_process';
2
+ import { randomUUID } from 'crypto';
3
+ import { mkdir, readFile, writeFile } from 'fs/promises';
4
+ import path from 'path';
5
+ import type {
6
+ SlatesCliStoreData,
7
+ SlatesCliStoreScope,
8
+ SlatesOAuthCredentialRecord,
9
+ SlatesProfileRecord,
10
+ SlatesProfileTarget,
11
+ SlatesStoredAuth
12
+ } from './types';
13
+
14
+ type SlatesLegacyCliStoreData = {
15
+ version?: number;
16
+ currentProfileId: string | null;
17
+ profiles: Record<string, SlatesProfileRecord>;
18
+ };
19
+
20
+ let STORE_VERSION = 3 as const;
21
+ let CLI_DIR_NAME = '.slates-cli';
22
+ let PROFILES_DIR_NAME = 'profiles';
23
+ let STORE_FILE_NAME = 'store.json';
24
+ let GITIGNORE_FILE_NAME = '.gitignore';
25
+
26
+ let createEmptyStore = (): SlatesCliStoreData => ({
27
+ version: STORE_VERSION,
28
+ currentProfileId: null,
29
+ profiles: {},
30
+ oauthCredentials: {}
31
+ });
32
+
33
+ let now = () => new Date().toISOString();
34
+
35
+ let ensureDir = async (dirPath: string) => {
36
+ await mkdir(dirPath, { recursive: true });
37
+ };
38
+
39
+ let ensureGitIgnore = async (dirPath: string) => {
40
+ let filePath = path.join(dirPath, GITIGNORE_FILE_NAME);
41
+ await writeFile(filePath, '*\n!.gitignore\n', { encoding: 'utf-8' }).catch(async error => {
42
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return;
43
+ throw error;
44
+ });
45
+ };
46
+
47
+ export let resolveSlatesCliRoot = (cwd: string = process.cwd()) => {
48
+ try {
49
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
50
+ cwd,
51
+ stdio: ['ignore', 'pipe', 'ignore'],
52
+ encoding: 'utf-8'
53
+ }).trim();
54
+ } catch {
55
+ return cwd;
56
+ }
57
+ };
58
+
59
+ let resolveSlatesCliDirFromRoot = (rootDir: string) => path.join(rootDir, CLI_DIR_NAME);
60
+
61
+ let resolveSlatesCliProfilesDirFromRoot = (rootDir: string) =>
62
+ path.join(resolveSlatesCliDirFromRoot(rootDir), PROFILES_DIR_NAME);
63
+
64
+ export let resolveSlatesCliDir = (cwd: string = process.cwd()) =>
65
+ resolveSlatesCliDirFromRoot(resolveSlatesCliRoot(cwd));
66
+
67
+ export let resolveSlatesCliProfilesDir = (cwd: string = process.cwd()) =>
68
+ resolveSlatesCliProfilesDirFromRoot(resolveSlatesCliRoot(cwd));
69
+
70
+ let normalizeScopeKey = (scopeKey: string) =>
71
+ path.posix.normalize(scopeKey.replace(/\\/g, '/')).replace(/^\.?\//, '');
72
+
73
+ let splitScopeKey = (scopeKey: string) =>
74
+ normalizeScopeKey(scopeKey)
75
+ .split('/')
76
+ .filter(Boolean)
77
+ .filter(segment => segment !== '.' && segment !== '..');
78
+
79
+ let resolveScopedStoreDir = (rootDir: string, scopeKey: string) =>
80
+ path.join(resolveSlatesCliProfilesDirFromRoot(rootDir), ...splitScopeKey(scopeKey));
81
+
82
+ let resolveScopedStorePath = (rootDir: string, scopeKey: string) =>
83
+ path.join(resolveScopedStoreDir(rootDir, scopeKey), STORE_FILE_NAME);
84
+
85
+ let inferRootDirFromStorePath = (storePath: string) => {
86
+ let normalized = path.resolve(storePath);
87
+ let parts = normalized.split(path.sep).filter(Boolean);
88
+ let cliDirIndex = parts.lastIndexOf(CLI_DIR_NAME);
89
+
90
+ if (cliDirIndex === -1) {
91
+ throw new Error(`Could not infer Slates CLI root from store path: ${storePath}`);
92
+ }
93
+
94
+ let rootParts = parts.slice(0, cliDirIndex);
95
+ return path.join(path.sep, ...rootParts);
96
+ };
97
+
98
+ let resolveScopeKeyFromStorePath = (rootDir: string, storePath: string) => {
99
+ let profilesDir = resolveSlatesCliProfilesDirFromRoot(rootDir);
100
+ let relativeDir = path.relative(profilesDir, path.dirname(storePath));
101
+ if (!relativeDir || relativeDir.startsWith('..') || path.isAbsolute(relativeDir)) {
102
+ return null;
103
+ }
104
+
105
+ return normalizeScopeKey(relativeDir);
106
+ };
107
+
108
+ let readStoreData = async <
109
+ T extends { currentProfileId: string | null; profiles: Record<string, any> }
110
+ >(
111
+ storePath: string
112
+ ): Promise<T | null> => {
113
+ try {
114
+ let raw = await readFile(storePath, 'utf-8');
115
+ if (!raw.trim()) {
116
+ return null;
117
+ }
118
+
119
+ return JSON.parse(raw) as T;
120
+ } catch (error) {
121
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
122
+ return null;
123
+ }
124
+
125
+ throw error;
126
+ }
127
+ };
128
+
129
+ let isProfileInScope = (rootDir: string, scopeKey: string, profile: SlatesProfileRecord) => {
130
+ if (profile.target.type !== 'local') {
131
+ return false;
132
+ }
133
+
134
+ let scopeDir = path.resolve(rootDir, ...splitScopeKey(scopeKey));
135
+ let entryPath = path.isAbsolute(profile.target.entry)
136
+ ? profile.target.entry
137
+ : path.resolve(rootDir, profile.target.entry);
138
+ let relative = path.relative(scopeDir, entryPath);
139
+ return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
140
+ };
141
+
142
+ let loadMigratedLegacyStore = async (
143
+ rootDir: string,
144
+ scopeKey: string
145
+ ): Promise<SlatesCliStoreData> => {
146
+ let legacyStorePath = path.join(resolveSlatesCliDirFromRoot(rootDir), STORE_FILE_NAME);
147
+ let legacy = await readStoreData<SlatesLegacyCliStoreData>(legacyStorePath);
148
+ if (!legacy) {
149
+ return createEmptyStore();
150
+ }
151
+
152
+ let profiles = Object.fromEntries(
153
+ Object.entries(legacy.profiles ?? {}).filter(([, profile]) =>
154
+ isProfileInScope(rootDir, scopeKey, profile)
155
+ )
156
+ );
157
+
158
+ let currentProfileId =
159
+ legacy.currentProfileId && profiles[legacy.currentProfileId]
160
+ ? legacy.currentProfileId
161
+ : null;
162
+
163
+ return {
164
+ version: STORE_VERSION,
165
+ currentProfileId,
166
+ profiles,
167
+ oauthCredentials: {}
168
+ };
169
+ };
170
+
171
+ export class SlatesCliStore {
172
+ constructor(
173
+ readonly rootDir: string,
174
+ readonly cliDir: string,
175
+ readonly dirPath: string,
176
+ readonly storePath: string,
177
+ readonly scope: SlatesCliStoreScope | null,
178
+ readonly data: SlatesCliStoreData
179
+ ) {}
180
+
181
+ static async open(
182
+ opts: {
183
+ cwd?: string;
184
+ rootDir?: string;
185
+ scope?: SlatesCliStoreScope;
186
+ storePath?: string;
187
+ } = {}
188
+ ) {
189
+ let storageRootDir = opts.storePath
190
+ ? inferRootDirFromStorePath(opts.storePath)
191
+ : resolveSlatesCliRoot(opts.cwd);
192
+ let rootDir = opts.rootDir ?? storageRootDir;
193
+ let cliDir = resolveSlatesCliDirFromRoot(storageRootDir);
194
+ let scopeKey = opts.storePath
195
+ ? resolveScopeKeyFromStorePath(storageRootDir, opts.storePath)
196
+ : opts.scope?.key
197
+ ? normalizeScopeKey(opts.scope.key)
198
+ : null;
199
+ let dirPath = opts.storePath
200
+ ? path.dirname(opts.storePath)
201
+ : scopeKey
202
+ ? resolveScopedStoreDir(rootDir, scopeKey)
203
+ : cliDir;
204
+ let storePath =
205
+ opts.storePath ??
206
+ (scopeKey
207
+ ? resolveScopedStorePath(rootDir, scopeKey)
208
+ : path.join(cliDir, STORE_FILE_NAME));
209
+
210
+ await ensureDir(cliDir);
211
+ await ensureGitIgnore(cliDir);
212
+ await ensureDir(dirPath);
213
+
214
+ let parsed = await readStoreData<SlatesCliStoreData>(storePath);
215
+ let data = parsed
216
+ ? {
217
+ version: STORE_VERSION,
218
+ currentProfileId: parsed.currentProfileId ?? null,
219
+ profiles: parsed.profiles ?? {},
220
+ oauthCredentials: parsed.oauthCredentials ?? {}
221
+ }
222
+ : opts.storePath
223
+ ? createEmptyStore()
224
+ : scopeKey
225
+ ? await loadMigratedLegacyStore(rootDir, scopeKey)
226
+ : createEmptyStore();
227
+
228
+ if (!parsed) {
229
+ await writeFile(storePath, `${JSON.stringify(data, null, 2)}\n`, 'utf-8');
230
+ }
231
+
232
+ return new SlatesCliStore(
233
+ rootDir,
234
+ cliDir,
235
+ dirPath,
236
+ storePath,
237
+ scopeKey ? { key: scopeKey, name: opts.scope?.name } : null,
238
+ data
239
+ );
240
+ }
241
+
242
+ async save() {
243
+ await ensureDir(this.dirPath);
244
+ await ensureDir(this.cliDir);
245
+ await ensureGitIgnore(this.cliDir);
246
+ await writeFile(this.storePath, `${JSON.stringify(this.data, null, 2)}\n`, 'utf-8');
247
+ }
248
+
249
+ listProfiles() {
250
+ return Object.values(this.data.profiles).sort((a, b) => a.name.localeCompare(b.name));
251
+ }
252
+
253
+ listOAuthCredentials(authMethodId?: string) {
254
+ return Object.values(this.data.oauthCredentials)
255
+ .filter(credential => !authMethodId || credential.authMethodId === authMethodId)
256
+ .sort((a, b) => a.name.localeCompare(b.name));
257
+ }
258
+
259
+ getOAuthCredential(credentialId?: string | null, authMethodId?: string | null) {
260
+ if (credentialId) {
261
+ let direct = this.data.oauthCredentials[credentialId];
262
+ if (direct && (!authMethodId || direct.authMethodId === authMethodId)) {
263
+ return direct;
264
+ }
265
+
266
+ let matches = this.listOAuthCredentials(authMethodId ?? undefined).filter(
267
+ credential => credential.name === credentialId
268
+ );
269
+ if (matches.length === 1) {
270
+ return matches[0]!;
271
+ }
272
+ }
273
+
274
+ return this.listOAuthCredentials(authMethodId ?? undefined)[0] ?? null;
275
+ }
276
+
277
+ getProfile(profileId?: string | null) {
278
+ if (profileId) {
279
+ if (this.data.profiles[profileId]) {
280
+ return this.data.profiles[profileId] ?? null;
281
+ }
282
+
283
+ let matches = this.listProfiles().filter(profile => profile.name === profileId);
284
+ if (matches.length === 1) {
285
+ return matches[0]!;
286
+ }
287
+ }
288
+
289
+ if (this.data.currentProfileId && this.data.profiles[this.data.currentProfileId]) {
290
+ return this.data.profiles[this.data.currentProfileId]!;
291
+ }
292
+
293
+ return this.listProfiles()[0] ?? null;
294
+ }
295
+
296
+ requireProfile(profileId?: string | null) {
297
+ let profile = this.getProfile(profileId);
298
+ if (!profile) {
299
+ throw new Error('No Slates profile found for this integration.');
300
+ }
301
+
302
+ return profile;
303
+ }
304
+
305
+ upsertProfile(d: {
306
+ profileId?: string;
307
+ name: string;
308
+ target: SlatesProfileTarget;
309
+ config?: SlatesProfileRecord['config'];
310
+ session?: SlatesProfileRecord['session'];
311
+ metadata?: SlatesProfileRecord['metadata'];
312
+ }) {
313
+ let existing = d.profileId ? this.data.profiles[d.profileId] : undefined;
314
+ let id = existing?.id ?? d.profileId ?? randomUUID();
315
+ let createdAt = existing?.createdAt ?? now();
316
+
317
+ let profile: SlatesProfileRecord = {
318
+ id,
319
+ name: d.name,
320
+ target: d.target,
321
+ config: d.config ?? existing?.config ?? null,
322
+ auth: existing?.auth ?? {},
323
+ session: d.session ?? existing?.session ?? null,
324
+ metadata: {
325
+ provider: d.metadata?.provider ?? existing?.metadata?.provider ?? null,
326
+ actions: d.metadata?.actions ?? existing?.metadata?.actions ?? null
327
+ },
328
+ createdAt,
329
+ updatedAt: now()
330
+ };
331
+
332
+ this.data.profiles[id] = profile;
333
+ if (!this.data.currentProfileId) {
334
+ this.data.currentProfileId = id;
335
+ }
336
+
337
+ return profile;
338
+ }
339
+
340
+ upsertOAuthCredential(d: {
341
+ credentialId?: string;
342
+ name: string;
343
+ authMethodId: string;
344
+ clientId: string;
345
+ clientSecret: string;
346
+ }) {
347
+ let existing = d.credentialId ? this.data.oauthCredentials[d.credentialId] : undefined;
348
+ let id = existing?.id ?? d.credentialId ?? randomUUID();
349
+ let credential: SlatesOAuthCredentialRecord = {
350
+ id,
351
+ name: d.name,
352
+ authMethodId: d.authMethodId,
353
+ clientId: d.clientId,
354
+ clientSecret: d.clientSecret,
355
+ createdAt: existing?.createdAt ?? now(),
356
+ updatedAt: now()
357
+ };
358
+
359
+ this.data.oauthCredentials[id] = credential;
360
+ return credential;
361
+ }
362
+
363
+ setCurrentProfile(profileId: string) {
364
+ if (!this.data.profiles[profileId]) {
365
+ throw new Error(`Unknown profile: ${profileId}`);
366
+ }
367
+
368
+ this.data.currentProfileId = profileId;
369
+ }
370
+
371
+ removeProfile(profileId: string) {
372
+ delete this.data.profiles[profileId];
373
+
374
+ if (this.data.currentProfileId === profileId) {
375
+ this.data.currentProfileId = this.listProfiles()[0]?.id ?? null;
376
+ }
377
+ }
378
+
379
+ setProfileConfig(profileId: string, config: SlatesProfileRecord['config']) {
380
+ let profile = this.requireProfile(profileId);
381
+ profile.config = config;
382
+ profile.updatedAt = now();
383
+ return profile;
384
+ }
385
+
386
+ setProfileSession(profileId: string, session: SlatesProfileRecord['session']) {
387
+ let profile = this.requireProfile(profileId);
388
+ profile.session = session;
389
+ profile.updatedAt = now();
390
+ return profile;
391
+ }
392
+
393
+ setProfileMetadata(profileId: string, metadata: Partial<SlatesProfileRecord['metadata']>) {
394
+ let profile = this.requireProfile(profileId);
395
+ profile.metadata = {
396
+ provider: metadata.provider ?? profile.metadata.provider ?? null,
397
+ actions: metadata.actions ?? profile.metadata.actions ?? null
398
+ };
399
+ profile.updatedAt = now();
400
+ return profile;
401
+ }
402
+
403
+ upsertAuth(
404
+ profileId: string,
405
+ auth: Omit<SlatesStoredAuth, 'id' | 'createdAt' | 'updatedAt'> & { id?: string }
406
+ ) {
407
+ let profile = this.requireProfile(profileId);
408
+ let existing = profile.auth[auth.authMethodId];
409
+
410
+ profile.auth[auth.authMethodId] = {
411
+ ...auth,
412
+ id: auth.id ?? existing?.id ?? randomUUID(),
413
+ createdAt: existing?.createdAt ?? now(),
414
+ updatedAt: now()
415
+ };
416
+ profile.updatedAt = now();
417
+
418
+ return profile.auth[auth.authMethodId]!;
419
+ }
420
+
421
+ getAuth(profileId: string, authMethodId?: string | null) {
422
+ let profile = this.requireProfile(profileId);
423
+ if (authMethodId) return profile.auth[authMethodId] ?? null;
424
+ return Object.values(profile.auth)[0] ?? null;
425
+ }
426
+
427
+ listAuth(profileId: string) {
428
+ let profile = this.requireProfile(profileId);
429
+ return Object.values(profile.auth).sort((a, b) =>
430
+ a.authMethodId.localeCompare(b.authMethodId)
431
+ );
432
+ }
433
+ }
434
+
435
+ export let openSlatesCliStore = async (
436
+ opts: {
437
+ cwd?: string;
438
+ rootDir?: string;
439
+ scope?: SlatesCliStoreScope;
440
+ storePath?: string;
441
+ } = {}
442
+ ) => SlatesCliStore.open(opts);
package/src/types.ts ADDED
@@ -0,0 +1,67 @@
1
+ import type { SlatesJsonObject } from '@slates/client';
2
+ import type { SlateAuthenticationMethod, SlatesAction } from '@slates/proto';
3
+
4
+ export interface SlatesStoredAuth {
5
+ id: string;
6
+ authMethodId: string;
7
+ authMethodName?: string;
8
+ authType: SlateAuthenticationMethod['type'];
9
+ input: SlatesJsonObject;
10
+ output: SlatesJsonObject;
11
+ scopes: string[];
12
+ oauthCredentialId?: string;
13
+ clientId?: string;
14
+ clientSecret?: string;
15
+ callbackState?: SlatesJsonObject | null;
16
+ profile?: SlatesJsonObject | null;
17
+ createdAt: string;
18
+ updatedAt: string;
19
+ }
20
+
21
+ export interface SlatesOAuthCredentialRecord {
22
+ id: string;
23
+ name: string;
24
+ authMethodId: string;
25
+ clientId: string;
26
+ clientSecret: string;
27
+ createdAt: string;
28
+ updatedAt: string;
29
+ }
30
+
31
+ export interface SlatesLocalProfileTarget {
32
+ type: 'local';
33
+ entry: string;
34
+ exportName?: string;
35
+ }
36
+
37
+ export type SlatesProfileTarget = SlatesLocalProfileTarget;
38
+
39
+ export interface SlatesCliStoreScope {
40
+ key: string;
41
+ name?: string;
42
+ }
43
+
44
+ export interface SlatesProfileRecord {
45
+ id: string;
46
+ name: string;
47
+ target: SlatesProfileTarget;
48
+ config: SlatesJsonObject | null;
49
+ auth: Record<string, SlatesStoredAuth>;
50
+ session: {
51
+ id: string;
52
+ state: SlatesJsonObject;
53
+ } | null;
54
+ metadata: {
55
+ provider?: SlatesJsonObject | null;
56
+ actions?: SlatesAction[] | null;
57
+ };
58
+ createdAt: string;
59
+ updatedAt: string;
60
+ }
61
+
62
+ export interface SlatesCliStoreData {
63
+ version: 3;
64
+ currentProfileId: string | null;
65
+ profiles: Record<string, SlatesProfileRecord>;
66
+ oauthCredentials: Record<string, SlatesOAuthCredentialRecord>;
67
+ }