@ankhorage/projects 0.7.3 → 0.8.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 (67) hide show
  1. package/README.md +19 -12
  2. package/dist/capabilities/index.d.ts +330 -0
  3. package/dist/capabilities/index.js +194 -0
  4. package/dist/capabilities/socialManagerMediaAnalytics.d.ts +92 -0
  5. package/dist/capabilities/socialManagerMediaAnalytics.js +75 -0
  6. package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.d.ts +1 -0
  7. package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.js +13 -5
  8. package/dist/features/projects/composition/createExpoProjectMaterializer.js +27 -23
  9. package/dist/features/projects/composition/createRootNavigatorGenerationOptions.d.ts +9 -0
  10. package/dist/features/projects/composition/createRootNavigatorGenerationOptions.js +10 -0
  11. package/dist/features/projects/composition/createSocialManagerServerFiles.d.ts +6 -0
  12. package/dist/features/projects/composition/createSocialManagerServerFiles.js +16 -0
  13. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.d.ts +16 -0
  14. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemRepositories.js +201 -0
  15. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.d.ts +25 -0
  16. package/dist/features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.js +72 -0
  17. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.d.ts +7 -0
  18. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js +160 -0
  19. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.d.ts +19 -0
  20. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.js +176 -0
  21. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.d.ts +4 -0
  22. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaPreflight.js +37 -0
  23. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.d.ts +7 -0
  24. package/dist/features/trusted-social-manager-host/adapters/createSocialManagerMediaStoreAsync.js +242 -0
  25. package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.d.ts +13 -0
  26. package/dist/features/trusted-social-manager-host/adapters/createSocialOperationStoresAsync.js +244 -0
  27. package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.d.ts +53 -0
  28. package/dist/features/trusted-social-manager-host/adapters/projectSocialManagerConnection.js +42 -0
  29. package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.d.ts +10 -0
  30. package/dist/features/trusted-social-manager-host/application/createSocialManagerPublicationRuntime.js +240 -0
  31. package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.d.ts +22 -0
  32. package/dist/features/trusted-social-manager-host/application/resolveSocialManagerPublication.js +97 -0
  33. package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.d.ts +22 -0
  34. package/dist/features/trusted-social-manager-host/composition/createSocialManagerCapabilityOperations.js +224 -0
  35. package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.d.ts +20 -0
  36. package/dist/features/trusted-social-manager-host/composition/createSocialManagerConnectionOperations.js +152 -0
  37. package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.d.ts +22 -0
  38. package/dist/features/trusted-social-manager-host/composition/createSocialManagerLocalProviderFixtures.js +271 -0
  39. package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.d.ts +14 -0
  40. package/dist/features/trusted-social-manager-host/composition/createSocialManagerMediaOperations.js +72 -0
  41. package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.d.ts +20 -0
  42. package/dist/features/trusted-social-manager-host/composition/createSocialManagerProvider.js +20 -0
  43. package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.d.ts +15 -0
  44. package/dist/features/trusted-social-manager-host/composition/createSocialManagerPublicationOperations.js +185 -0
  45. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.d.ts +14 -0
  46. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerFileSystemPersistenceAsync.js +17 -0
  47. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.d.ts +51 -0
  48. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.js +188 -0
  49. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.d.ts +18 -0
  50. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalHostAsync.js +177 -0
  51. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.d.ts +26 -0
  52. package/dist/features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.js +66 -0
  53. package/dist/features/trusted-social-manager-host/domain/publicationConfig.d.ts +18 -0
  54. package/dist/features/trusted-social-manager-host/domain/publicationConfig.js +77 -0
  55. package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.d.ts +54 -0
  56. package/dist/features/trusted-social-manager-host/domain/readSocialManagerConnectionRequest.js +77 -0
  57. package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.d.ts +3 -0
  58. package/dist/features/trusted-social-manager-host/domain/readSocialManagerDraftContent.js +47 -0
  59. package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.d.ts +17 -0
  60. package/dist/features/trusted-social-manager-host/domain/socialManagerConnectionIdentity.js +17 -0
  61. package/dist/index.d.ts +16 -0
  62. package/dist/index.js +14 -0
  63. package/dist/types/socialManager.d.ts +77 -0
  64. package/dist/types/socialManager.js +1 -0
  65. package/dist/types/socialManagerPublication.d.ts +27 -0
  66. package/dist/types/socialManagerPublication.js +1 -0
  67. package/package.json +506 -8
@@ -0,0 +1,75 @@
1
+ /*** Publish static media, validation, preview, and analytics descriptors for the Social Manager host. */
2
+ export const SOCIAL_MANAGER_MEDIA_ANALYTICS_CAPABILITIES = [
3
+ {
4
+ id: 'projects.social.media.upload',
5
+ owner: '@ankhorage/projects',
6
+ access: ['write'],
7
+ binding: { kind: 'action', bindableAs: ['target'] },
8
+ label: 'Upload social media',
9
+ description: 'Persist immutable caller-owned social media content.',
10
+ },
11
+ {
12
+ id: 'projects.social.media.list',
13
+ owner: '@ankhorage/projects',
14
+ access: ['read'],
15
+ binding: { kind: 'action', bindableAs: ['target'] },
16
+ label: 'List social media',
17
+ description: 'List immutable social media metadata in the authenticated caller scope.',
18
+ },
19
+ {
20
+ id: 'projects.social.media.read',
21
+ owner: '@ankhorage/projects',
22
+ access: ['read'],
23
+ binding: { kind: 'action', bindableAs: ['target'] },
24
+ label: 'Read social media',
25
+ description: 'Read one immutable social media metadata record.',
26
+ },
27
+ {
28
+ id: 'projects.social.media.remove',
29
+ owner: '@ankhorage/projects',
30
+ access: ['write'],
31
+ binding: { kind: 'action', bindableAs: ['target'] },
32
+ label: 'Remove social media',
33
+ description: 'Remove unreferenced immutable social media content.',
34
+ },
35
+ {
36
+ id: 'projects.social.capabilities.read',
37
+ owner: '@ankhorage/projects',
38
+ access: ['read'],
39
+ binding: { kind: 'action', bindableAs: ['target'] },
40
+ label: 'Read social capability',
41
+ description: 'Read the authenticated destination provider capability.',
42
+ },
43
+ {
44
+ id: 'projects.social.content.validate',
45
+ owner: '@ankhorage/projects',
46
+ access: ['write'],
47
+ binding: { kind: 'action', bindableAs: ['target'] },
48
+ label: 'Validate social content',
49
+ description: 'Validate an immutable social draft destination against provider constraints.',
50
+ },
51
+ {
52
+ id: 'projects.social.preview.prepare',
53
+ owner: '@ankhorage/projects',
54
+ access: ['write'],
55
+ binding: { kind: 'action', bindableAs: ['target'] },
56
+ label: 'Prepare social preview',
57
+ description: 'Prepare a validated redaction-safe social publication preview.',
58
+ },
59
+ {
60
+ id: 'projects.social.analytics.capabilities',
61
+ owner: '@ankhorage/projects',
62
+ access: ['read'],
63
+ binding: { kind: 'action', bindableAs: ['target'] },
64
+ label: 'Read social analytics capabilities',
65
+ description: 'Read provider-native availability for social analytics metrics.',
66
+ },
67
+ {
68
+ id: 'projects.social.analytics.retrieve',
69
+ owner: '@ankhorage/projects',
70
+ access: ['write'],
71
+ binding: { kind: 'action', bindableAs: ['target'] },
72
+ label: 'Retrieve social analytics',
73
+ description: 'Retrieve provider-native social analytics observations.',
74
+ },
75
+ ];
@@ -5,6 +5,7 @@ export declare function composeGeneratedRuntimeMaterialization(input: Readonly<{
5
5
  readonly packageSource: string;
6
6
  readonly runtimeBindings: NavigatorGenerationBindings;
7
7
  readonly runtimeDependencies: Readonly<Record<string, string>>;
8
+ readonly socialManager: boolean;
8
9
  }>): Readonly<{
9
10
  navigatorBindings: NavigatorGenerationBindings;
10
11
  packageSource: string;
@@ -3,9 +3,7 @@ const generatedDevelopmentDependencies = {
3
3
  '@ankhorage/devtools': '^2.12.2',
4
4
  typescript: '~6.0.3',
5
5
  };
6
- const generatedScripts = {
7
- 'devtools:sync': 'ankh devtools sync .',
8
- };
6
+ const generatedScripts = { 'devtools:sync': 'ankh devtools sync .' };
9
7
  /*** Compose generated Runtime dependencies and bindings with caller-owned Navigator extensions. */
10
8
  export function composeGeneratedRuntimeMaterialization(input) {
11
9
  assertNoConflictingRuntimeBindings(input.callerBindings, input.runtimeBindings);
@@ -17,12 +15,22 @@ export function composeGeneratedRuntimeMaterialization(input) {
17
15
  },
18
16
  packageSource: `${JSON.stringify({
19
17
  ...packageJson,
20
- dependencies: { ...packageJson.dependencies, ...input.runtimeDependencies },
18
+ dependencies: {
19
+ ...packageJson.dependencies,
20
+ ...input.runtimeDependencies,
21
+ ...(input.socialManager ? { '@ankhorage/projects': '^0.8.0' } : {}),
22
+ },
21
23
  devDependencies: {
22
24
  ...packageJson.devDependencies,
23
25
  ...generatedDevelopmentDependencies,
24
26
  },
25
- scripts: { ...packageJson.scripts, ...generatedScripts },
27
+ scripts: {
28
+ ...packageJson.scripts,
29
+ ...generatedScripts,
30
+ ...(input.socialManager
31
+ ? { 'social-manager:server': 'bun src/server/socialManager.ts' }
32
+ : {}),
33
+ },
26
34
  }, null, 2)}\n`,
27
35
  };
28
36
  }
@@ -5,6 +5,8 @@ import { resolveExpoRuntimePlan } from '@ankhorage/expo-runtime/planning';
5
5
  import { createNavigatorPlan, generateNavigator } from '@ankhorage/navigator';
6
6
  import { materializeTemplateRevision } from '@ankhorage/templates';
7
7
  import { composeGeneratedRuntimeMaterialization } from './composeGeneratedRuntimeMaterialization.js';
8
+ import { createRootNavigatorGenerationOptions } from './createRootNavigatorGenerationOptions.js';
9
+ import { createSocialManagerServerFiles } from './createSocialManagerServerFiles.js';
8
10
  import { formatTypeScriptLiteral } from './formatTypeScriptLiteral.js';
9
11
  /*** Create the public, caller-targeted Expo materializer for stored immutable project revisions. */
10
12
  export function createExpoProjectMaterializer(input) {
@@ -36,19 +38,14 @@ async function materializeExpoProjectAsync(input, project, revision) {
36
38
  }
37
39
  /*** Produce every Runtime- and Navigator-owned file before Template or target filesystem writes. */
38
40
  function createGeneratedFiles(manifest, navigatorInput) {
39
- const runtimePlan = ownerApis.resolveExpoRuntimePlan(manifest);
40
- assertNoErrors(runtimePlan.diagnostics, 'Expo Runtime');
41
- const runtime = ownerApis.resolveExpoRuntimeGeneratedAppSources(manifest, runtimePlan, {
42
- manifestModuleSpecifier: '../ankh.manifest',
43
- screenModuleSpecifier: '../generated/runtimeManifestScreens',
44
- });
45
- assertNoErrors(runtime.diagnostics, 'Expo Runtime');
46
- const scaffold = ownerApis.resolveExpoRuntimeGeneratedAppScaffold(manifest, runtimePlan);
41
+ const generatedRuntime = createGeneratedRuntimeFiles(manifest);
42
+ const socialManagerFiles = createSocialManagerServerFiles(manifest);
47
43
  const packageSource = composeGeneratedRuntimeMaterialization({
48
44
  callerBindings: navigatorInput.bindings,
49
- packageSource: scaffold.files.find(({ relativePath }) => relativePath === 'package.json')?.source ?? '',
50
- runtimeBindings: runtime.navigatorBindings,
51
- runtimeDependencies: runtime.dependencies,
45
+ packageSource: generatedRuntime.packageSource,
46
+ runtimeBindings: generatedRuntime.navigatorBindings,
47
+ runtimeDependencies: generatedRuntime.dependencies,
48
+ socialManager: socialManagerFiles.length > 0,
52
49
  });
53
50
  const navigatorPlan = ownerApis.createNavigatorPlan(manifest.navigator, {
54
51
  platform: navigatorInput.platform,
@@ -57,14 +54,10 @@ function createGeneratedFiles(manifest, navigatorInput) {
57
54
  const navigator = ownerApis.generateNavigator(navigatorPlan, packageSource.navigatorBindings, createRootNavigatorGenerationOptions(manifest));
58
55
  assertNoErrors(navigator.diagnostics, 'Navigator');
59
56
  const files = [
60
- ...scaffold.files.map((file) => ({
57
+ ...generatedRuntime.files.map((file) => ({
61
58
  relativePath: file.relativePath,
62
59
  source: file.relativePath === 'package.json' ? packageSource.packageSource : file.source,
63
60
  })),
64
- ...runtime.files.map((file) => ({
65
- relativePath: file.relativePath,
66
- source: file.source,
67
- })),
68
61
  {
69
62
  relativePath: 'src/ankh.manifest.ts',
70
63
  source: `export default ${formatTypeScriptLiteral(manifest)} as const;\n`,
@@ -73,18 +66,29 @@ function createGeneratedFiles(manifest, navigatorInput) {
73
66
  relativePath: file.path,
74
67
  source: file.contents,
75
68
  })),
69
+ ...socialManagerFiles,
76
70
  ];
77
71
  assertUniqueRelativePaths(files.map(({ relativePath }) => relativePath));
78
72
  return files;
79
73
  }
80
- /*** Opt into the generated Runtime provider shell and preserve each manifest's configured public start route. */
81
- function createRootNavigatorGenerationOptions(manifest) {
74
+ /*** Resolve all Runtime-owned files and bindings before Navigator generation merges them. */
75
+ function createGeneratedRuntimeFiles(manifest) {
76
+ const runtimePlan = ownerApis.resolveExpoRuntimePlan(manifest);
77
+ assertNoErrors(runtimePlan.diagnostics, 'Expo Runtime');
78
+ const runtime = ownerApis.resolveExpoRuntimeGeneratedAppSources(manifest, runtimePlan, {
79
+ manifestModuleSpecifier: '../ankh.manifest',
80
+ screenModuleSpecifier: '../generated/runtimeManifestScreens',
81
+ });
82
+ assertNoErrors(runtime.diagnostics, 'Expo Runtime');
83
+ const scaffold = ownerApis.resolveExpoRuntimeGeneratedAppScaffold(manifest, runtimePlan);
82
84
  return {
83
- ...(manifest.navigator.initialRouteName === undefined ? {} : { rootRedirect: true }),
84
- rootLayoutWrapper: {
85
- module: '@/generated/runtimeShell',
86
- exportName: 'GeneratedRuntimeShell',
87
- },
85
+ dependencies: runtime.dependencies,
86
+ files: [
87
+ ...scaffold.files,
88
+ ...runtime.files.map((file) => ({ relativePath: file.relativePath, source: file.source })),
89
+ ],
90
+ navigatorBindings: runtime.navigatorBindings,
91
+ packageSource: scaffold.files.find(({ relativePath }) => relativePath === 'package.json')?.source ?? '',
88
92
  };
89
93
  }
90
94
  /*** Return the stable public materialization identity and complete sorted generated-file inventory. */
@@ -0,0 +1,9 @@
1
+ import type { AppManifest } from '@ankhorage/contracts';
2
+ /*** Opt into the generated Runtime provider shell and preserve each manifest's configured public start route. */
3
+ export declare function createRootNavigatorGenerationOptions(manifest: AppManifest): {
4
+ rootLayoutWrapper: {
5
+ module: string;
6
+ exportName: string;
7
+ };
8
+ rootRedirect?: true;
9
+ };
@@ -0,0 +1,10 @@
1
+ /*** Opt into the generated Runtime provider shell and preserve each manifest's configured public start route. */
2
+ export function createRootNavigatorGenerationOptions(manifest) {
3
+ return {
4
+ ...(manifest.navigator.initialRouteName === undefined ? {} : { rootRedirect: true }),
5
+ rootLayoutWrapper: {
6
+ module: '@/generated/runtimeShell',
7
+ exportName: 'GeneratedRuntimeShell',
8
+ },
9
+ };
10
+ }
@@ -0,0 +1,6 @@
1
+ import type { AppManifest } from '@ankhorage/contracts';
2
+ /*** Generate the thin local Social Manager entrypoint only from declared internal API capabilities. */
3
+ export declare function createSocialManagerServerFiles(manifest: AppManifest): readonly Readonly<{
4
+ relativePath: string;
5
+ source: string;
6
+ }>[];
@@ -0,0 +1,16 @@
1
+ /*** Generate the thin local Social Manager entrypoint only from declared internal API capabilities. */
2
+ export function createSocialManagerServerFiles(manifest) {
3
+ return hasSocialManagerApiDeclaration(manifest)
4
+ ? [
5
+ {
6
+ relativePath: 'src/server/socialManager.ts',
7
+ source: `import manifest from '../ankh.manifest';\nimport { createTrustedSocialManagerLocalServerAsync, findTrustedSocialManagerApiDefinition } from '@ankhorage/projects';\n\nconst definition = findTrustedSocialManagerApiDefinition(manifest);\nif (!definition) throw new Error('Social Manager API declaration is missing.');\nconst token = process.env.SOCIAL_MANAGER_DEVELOPMENT_TOKEN;\nif (!token) throw new Error('SOCIAL_MANAGER_DEVELOPMENT_TOKEN is required.');\nconst server = await createTrustedSocialManagerLocalServerAsync({\n appId: manifest.metadata.slug,\n dataDirectory: process.env.SOCIAL_MANAGER_DATA_DIRECTORY ?? '.social-manager-data',\n definition,\n development: { enabled: true, hostname: '127.0.0.1', token },\n scope: { tenantId: 'local', projectId: manifest.metadata.slug, environmentId: 'local' },\n caller: { tenantId: 'local', projectId: manifest.metadata.slug, environmentId: 'local', actorId: 'local-developer' },\n});\nawait server.listenAsync(Number(process.env.SOCIAL_MANAGER_PORT ?? '4310'));\nconst shutdownAsync = async () => { await server.closeAsync(); process.exitCode = 0; };\nprocess.once('SIGINT', shutdownAsync);\nprocess.once('SIGTERM', shutdownAsync);\n`,
8
+ },
9
+ ]
10
+ : [];
11
+ }
12
+ /*** Detect only manifest-bound internal Social Manager operations; template identity is irrelevant. */
13
+ function hasSocialManagerApiDeclaration(manifest) {
14
+ return Object.values(manifest.infra.apis ?? {}).some((api) => api.origin === 'internal' &&
15
+ Object.values(api.handlers ?? {}).some((handler) => handler.capability.startsWith('projects.social.')));
16
+ }
@@ -0,0 +1,16 @@
1
+ import type { ConnectionRepositoryPort, ConnectionTargetDiscoveryPort, DelegatedAuthorizationRepositoryPort, RevocationRepositoryPort } from '@ankhorage/connection';
2
+ import type { ConnectionFileSystemDocument } from './createConnectionFileSystemStoreAsync.js';
3
+ export type ConnectionFileSystemMutationAsync = <Value>(operation: (document: ConnectionFileSystemDocument) => readonly [ConnectionFileSystemDocument, Value]) => Promise<Value>;
4
+ type CreateRepositoriesInput = Readonly<{
5
+ documentPath: string;
6
+ mutateAsync: ConnectionFileSystemMutationAsync;
7
+ readDocumentAsync: (path: string) => Promise<ConnectionFileSystemDocument>;
8
+ }>;
9
+ /*** Construct Connection ports over one validated, atomically rewritten state document. */
10
+ export declare function createConnectionFileSystemRepositories(input: CreateRepositoriesInput): Readonly<{
11
+ delegatedAuthorizationRepository: DelegatedAuthorizationRepositoryPort;
12
+ connectionRepository: ConnectionRepositoryPort;
13
+ targetDiscovery: ConnectionTargetDiscoveryPort;
14
+ revocationRepository: RevocationRepositoryPort;
15
+ }>;
16
+ export {};
@@ -0,0 +1,201 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ /*** Construct Connection ports over one validated, atomically rewritten state document. */
3
+ export function createConnectionFileSystemRepositories(input) {
4
+ return {
5
+ delegatedAuthorizationRepository: createDelegatedAuthorizationRepository(input),
6
+ connectionRepository: createConnectionRepository(input),
7
+ targetDiscovery: createTargetDiscovery(input),
8
+ revocationRepository: createRevocationRepository(input),
9
+ };
10
+ }
11
+ /*** Build the repository that owns authorization-attempt consumption and connection revisions. */
12
+ function createDelegatedAuthorizationRepository(input) {
13
+ return {
14
+ createAttemptAsync: (value) => createAttemptAsync(input.mutateAsync, value),
15
+ loadAttemptAsync: (attemptId) => loadAttemptAsync(input, attemptId),
16
+ consumeAttemptAsync: (attemptId, now) => transitionAttemptAsync(input.mutateAsync, attemptId, now, 'consumed'),
17
+ cancelAttemptAsync: (attemptId, now) => transitionAttemptAsync(input.mutateAsync, attemptId, now, 'cancelled'),
18
+ loadConnectionAsync: (connectionId) => loadConnectionAsync(input, connectionId),
19
+ saveConnectionAsync: (connection, expectedRevision) => saveConnectionAsync(input.mutateAsync, connection, expectedRevision),
20
+ };
21
+ }
22
+ /*** Persist one complete pending authorization attempt under the serialized state mutation. */
23
+ function createAttemptAsync(mutateAsync, input) {
24
+ assertBinding(input);
25
+ const attempt = {
26
+ ...input,
27
+ attemptId: randomUUID(),
28
+ purpose: input.purpose ?? 'connect',
29
+ status: 'pending',
30
+ expiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
31
+ };
32
+ return mutateAsync((document) => [
33
+ { ...document, attempts: [...document.attempts, attempt] },
34
+ attempt,
35
+ ]);
36
+ }
37
+ /*** Read an exact persisted delegated authorization attempt. */
38
+ async function loadAttemptAsync(input, attemptId) {
39
+ return ((await input.readDocumentAsync(input.documentPath)).attempts.find((attempt) => attempt.attemptId === attemptId) ?? null);
40
+ }
41
+ /*** Atomically transition exactly one pending and unexpired delegated attempt. */
42
+ function transitionAttemptAsync(mutateAsync, attemptId, now, status) {
43
+ return mutateAsync((document) => {
44
+ const current = document.attempts.find((attempt) => attempt.attemptId === attemptId);
45
+ if (current?.status !== 'pending')
46
+ return [document, null];
47
+ const nextStatus = Date.parse(current.expiresAt) <= Date.parse(now) ? 'expired' : status;
48
+ const replacement = { ...current, status: nextStatus };
49
+ const attempts = document.attempts.map((attempt) => attempt.attemptId === attemptId ? replacement : attempt);
50
+ return [{ ...document, attempts }, nextStatus === status ? replacement : null];
51
+ });
52
+ }
53
+ /*** Read an exact managed connection from the durable document. */
54
+ async function loadConnectionAsync(input, connectionId) {
55
+ return ((await input.readDocumentAsync(input.documentPath)).connections.find((connection) => connection.connectionId === connectionId) ?? null);
56
+ }
57
+ /*** Compare and replace a managed connection only at its expected durable revision. */
58
+ function saveConnectionAsync(mutateAsync, connection, expectedRevision) {
59
+ assertManagedConnection(connection);
60
+ return mutateAsync((document) => {
61
+ const existing = document.connections.find((item) => item.connectionId === connection.connectionId);
62
+ if ((existing?.revision ?? null) !== expectedRevision)
63
+ return [document, null];
64
+ const connections = existing
65
+ ? document.connections.map((item) => item.connectionId === connection.connectionId ? connection : item)
66
+ : [...document.connections, connection];
67
+ return [{ ...document, connections }, connection];
68
+ });
69
+ }
70
+ /*** Build the Connection read-only access port. */
71
+ function createConnectionRepository(input) {
72
+ return {
73
+ loadAsync: async (id) => {
74
+ const connection = await loadConnectionAsync(input, id);
75
+ return connection ? toConnectionDescriptor(connection) : null;
76
+ },
77
+ };
78
+ }
79
+ /*** Build the authorized target discovery port with exact authorization scope matching. */
80
+ function createTargetDiscovery(input) {
81
+ return {
82
+ discoverAuthorizedTargetsAsync: async (reference) => {
83
+ const connection = await loadExactConnectionAsync(input, reference);
84
+ return connection?.targets.filter((target) => matchesReference(target, reference)) ?? [];
85
+ },
86
+ resolveAuthorizedTargetAsync: async (reference) => {
87
+ const connection = await loadExactConnectionAsync(input, reference);
88
+ return connection?.targets.find((target) => matchesReference(target, reference)) ?? null;
89
+ },
90
+ };
91
+ }
92
+ /*** Build the durable exact-effect repository used by revocation recovery. */
93
+ function createRevocationRepository(input) {
94
+ return {
95
+ loadAsync: async (effectId) => (await input.readDocumentAsync(input.documentPath)).revocations.find((record) => record.operation.effectId === effectId) ?? null,
96
+ recordIntentAsync: (operation) => recordIntentAsync(input.mutateAsync, operation),
97
+ saveAsync: (record) => saveRevocationAsync(input.mutateAsync, record),
98
+ };
99
+ }
100
+ /*** Record the first exact revocation intent while retaining any recovery record. */
101
+ function recordIntentAsync(mutateAsync, operation) {
102
+ assertRevocationOperation(operation);
103
+ return mutateAsync((document) => {
104
+ const existing = document.revocations.find((record) => record.operation.effectId === operation.effectId);
105
+ if (existing)
106
+ return [document, existing];
107
+ const record = { operation, state: 'revocation-pending' };
108
+ return [{ ...document, revocations: [...document.revocations, record] }, record];
109
+ });
110
+ }
111
+ /*** Persist a recovery state only for its original immutable revocation operation. */
112
+ function saveRevocationAsync(mutateAsync, record) {
113
+ assertRevocationRecord(record);
114
+ return mutateAsync((document) => {
115
+ const existing = document.revocations.find((item) => item.operation.effectId === record.operation.effectId);
116
+ if (!existing || JSON.stringify(existing.operation) !== JSON.stringify(record.operation))
117
+ throw new Error('Revocation record operation is unknown or does not match its durable identity.');
118
+ const revocations = document.revocations.map((item) => item.operation.effectId === record.operation.effectId ? record : item);
119
+ return [{ ...document, revocations }, record];
120
+ });
121
+ }
122
+ /*** Validate the immutable binding dimensions shared by attempts and connections. */
123
+ function assertBinding(value) {
124
+ if ([
125
+ value.tenantId,
126
+ value.projectId,
127
+ value.environmentId,
128
+ value.actorId,
129
+ value.connectionId,
130
+ value.provider,
131
+ ...value.requestedScopes,
132
+ ].some((item) => !item.trim()) ||
133
+ value.requestedScopes.length === 0)
134
+ throw new Error('Connection binding is incomplete.');
135
+ }
136
+ /*** Validate a managed connection before it enters durable state. */
137
+ function assertManagedConnection(value) {
138
+ if (!value.connectionId.trim() || !value.revision.trim())
139
+ throw new Error('Managed connection is invalid.');
140
+ }
141
+ /*** Translate Connection's managed reconnect state into the read-only access contract. */
142
+ function toConnectionDescriptor(connection) {
143
+ return {
144
+ id: connection.connectionId,
145
+ provider: connection.provider,
146
+ accountId: connection.accountId,
147
+ status: connection.status === 'connected'
148
+ ? 'connected'
149
+ : connection.status === 'disconnected'
150
+ ? 'disconnected'
151
+ : 'expired',
152
+ scopes: connection.grantedScopes,
153
+ authorizationRef: connection.authorizationRef,
154
+ };
155
+ }
156
+ /*** Load a connection only when every requested authorization dimension agrees. */
157
+ async function loadExactConnectionAsync(input, reference) {
158
+ const connection = await loadConnectionAsync(input, reference.connectionId);
159
+ const connectionReference = {
160
+ tenantId: reference.tenantId,
161
+ projectId: reference.projectId,
162
+ environmentId: reference.environmentId,
163
+ actorId: reference.actorId,
164
+ provider: reference.provider,
165
+ connectionId: reference.connectionId,
166
+ accountId: reference.accountId,
167
+ };
168
+ return connection && matchesReference(connection, connectionReference) ? connection : null;
169
+ }
170
+ /*** Compare every authorization dimension without allowing partial identity matches. */
171
+ function matchesReference(value, reference) {
172
+ return (value.tenantId === reference.tenantId &&
173
+ value.projectId === reference.projectId &&
174
+ value.environmentId === reference.environmentId &&
175
+ value.actorId === reference.actorId &&
176
+ value.provider === reference.provider &&
177
+ value.connectionId === reference.connectionId &&
178
+ value.accountId === reference.accountId &&
179
+ (reference.targetId === undefined || value.targetId === reference.targetId));
180
+ }
181
+ /*** Reject incomplete revocation effects before making their intent durable. */
182
+ function assertRevocationOperation(value) {
183
+ if ([
184
+ value.effectId,
185
+ value.tenantId,
186
+ value.projectId,
187
+ value.environmentId,
188
+ value.actorId,
189
+ value.provider,
190
+ value.authorizationId,
191
+ value.connectionId,
192
+ value.accountId,
193
+ value.targetId,
194
+ ].some((item) => !item.trim()))
195
+ throw new Error('Revocation operation is incomplete.');
196
+ }
197
+ /*** Guard state updates from swapping the immutable revocation operation. */
198
+ function assertRevocationRecord(value) {
199
+ if (!value.operation.effectId.trim())
200
+ throw new Error('Revocation record is invalid.');
201
+ }
@@ -0,0 +1,25 @@
1
+ import type { ConnectionRepositoryPort, ConnectionTargetDiscoveryPort, DelegatedAuthorizationAttempt, DelegatedAuthorizationRepositoryPort, ManagedConnection, RevocationRecord, RevocationRepositoryPort } from '@ankhorage/connection';
2
+ export type ConnectionFileSystemStore = Readonly<{
3
+ delegatedAuthorizationRepository: DelegatedAuthorizationRepositoryPort;
4
+ connectionRepository: ConnectionRepositoryPort;
5
+ targetDiscovery: ConnectionTargetDiscoveryPort;
6
+ revocationRepository: RevocationRepositoryPort;
7
+ listConnectionsAsync: (scope: Readonly<{
8
+ tenantId: string;
9
+ projectId: string;
10
+ environmentId: string;
11
+ actorId: string;
12
+ }>) => Promise<readonly ManagedConnection[]>;
13
+ }>;
14
+ export type ConnectionFileSystemDocument = Readonly<{
15
+ version: 1;
16
+ attempts: readonly DelegatedAuthorizationAttempt[];
17
+ connections: readonly ManagedConnection[];
18
+ revocations: readonly RevocationRecord[];
19
+ }>;
20
+ /***
21
+ * Create private single-writer filesystem persistence for Connection's credential-free ports.
22
+ * The directory is assigned to one process and one adapter instance; cross-process writers are
23
+ * deliberately unsupported and require a database adapter with external coordination.
24
+ */
25
+ export declare function createConnectionFileSystemStoreAsync(directory: string): Promise<ConnectionFileSystemStore>;
@@ -0,0 +1,72 @@
1
+ import { constants, lstat, mkdir, open } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { createKeyedAsyncMutex } from '@ankhorage/utility/concurrency';
4
+ import { isMissingPathError, writeJsonFileAtomic } from '@ankhorage/utility/node/fs';
5
+ import { isRecord } from '@ankhorage/utility/object';
6
+ import { createConnectionFileSystemRepositories, } from './createConnectionFileSystemRepositories.js';
7
+ /***
8
+ * Create private single-writer filesystem persistence for Connection's credential-free ports.
9
+ * The directory is assigned to one process and one adapter instance; cross-process writers are
10
+ * deliberately unsupported and require a database adapter with external coordination.
11
+ */
12
+ export async function createConnectionFileSystemStoreAsync(directory) {
13
+ const root = join(directory, 'connection');
14
+ await mkdir(root, { recursive: true, mode: 0o700 });
15
+ const stat = await lstat(root);
16
+ if (!stat.isDirectory() || (stat.mode & 0o077) !== 0) {
17
+ throw new Error('Connection storage directory must be private.');
18
+ }
19
+ const documentPath = join(root, 'state.json');
20
+ const mutateAsync = createMutationAsync(documentPath);
21
+ const repositories = createConnectionFileSystemRepositories({
22
+ documentPath,
23
+ mutateAsync,
24
+ readDocumentAsync,
25
+ });
26
+ return {
27
+ ...repositories,
28
+ listConnectionsAsync: async (scope) => (await readDocumentAsync(documentPath)).connections.filter((connection) => connection.tenantId === scope.tenantId &&
29
+ connection.projectId === scope.projectId &&
30
+ connection.environmentId === scope.environmentId &&
31
+ connection.actorId === scope.actorId),
32
+ };
33
+ }
34
+ /*** Serialize durable mutations within the explicitly supported adapter instance. */
35
+ function createMutationAsync(documentPath) {
36
+ const mutations = createKeyedAsyncMutex();
37
+ return (operation) => mutations.run('connection', async () => {
38
+ const [next, value] = operation(await readDocumentAsync(documentPath));
39
+ await writeJsonFileAtomic(documentPath, next);
40
+ return value;
41
+ });
42
+ }
43
+ /*** Read the sole atomic state document through a no-follow handle and validate it before use. */
44
+ async function readDocumentAsync(path) {
45
+ try {
46
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
47
+ try {
48
+ if (!(await handle.stat()).isFile())
49
+ throw new Error('Connection storage state must be a regular file.');
50
+ const value = JSON.parse(await handle.readFile('utf8'));
51
+ if (!isDocument(value))
52
+ throw new Error('Connection storage document is invalid.');
53
+ return value;
54
+ }
55
+ finally {
56
+ await handle.close();
57
+ }
58
+ }
59
+ catch (error) {
60
+ if (isMissingPathError(error))
61
+ return { version: 1, attempts: [], connections: [], revocations: [] };
62
+ throw error;
63
+ }
64
+ }
65
+ /*** Check the atomic envelope before its records reach the credential-free host ports. */
66
+ function isDocument(value) {
67
+ return (isRecord(value) &&
68
+ value.version === 1 &&
69
+ Array.isArray(value.attempts) &&
70
+ Array.isArray(value.connections) &&
71
+ Array.isArray(value.revocations));
72
+ }
@@ -0,0 +1,7 @@
1
+ import type { SocialManagerDraftStore } from '../../../types/socialManager.js';
2
+ /***
3
+ * Persist immutable draft revisions for one local development host.
4
+ * The configured directory must be private and trusted. Assign it to one writer
5
+ * process and one adapter instance; this is not a distributed database adapter.
6
+ */
7
+ export declare function createSocialManagerDraftStoreAsync(directory: string): Promise<SocialManagerDraftStore>;