@ankhorage/projects 0.9.4 → 0.10.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.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  # Ankhorage Projects
5
5
 
6
- ![license: MIT](././paradox/badges/license.svg) ![npm: v0.9.4](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: configured](././paradox/badges/tests.svg) ![paradox: canonical](././paradox/badges/docs.svg)
6
+ ![license: MIT](././paradox/badges/license.svg) ![npm: v0.10.0](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: configured](././paradox/badges/tests.svg) ![paradox: canonical](././paradox/badges/docs.svg)
7
7
 
8
8
  Provides standalone project identity, persistence, and repository-oriented project actions.
9
9
 
@@ -1,13 +1,14 @@
1
- import { lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile, } from 'node:fs/promises';
2
- import { basename, dirname, relative, resolve } from 'node:path';
1
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
3
  import { resolveExpoRuntimeGeneratedAppScaffold, resolveExpoRuntimeGeneratedAppSources, } from '@ankhorage/expo-runtime/generated-app';
4
4
  import { resolveExpoRuntimePlan } from '@ankhorage/expo-runtime/planning';
5
5
  import { materializeTemplateRevision } from '@ankhorage/templates';
6
6
  import { applyWorkerMaterialization } from '../../worker-materialization/composition/composeWorkerMaterialization.js';
7
7
  import { composeGeneratedRuntimeMaterialization } from './composeGeneratedRuntimeMaterialization.js';
8
+ import { createManifestSource } from './createManifestSource.js';
9
+ import { createMaterializationFileSystem, } from './createMaterializationFileSystem.js';
8
10
  import { createNavigatorMaterializationFiles, } from './createNavigatorMaterializationFiles.js';
9
11
  import { createSocialManagerServerFiles } from './createSocialManagerServerFiles.js';
10
- import { formatTypeScriptLiteral } from './formatTypeScriptLiteral.js';
11
12
  /*** Create the public, caller-targeted Expo materializer for stored immutable project revisions. */
12
13
  export function createExpoProjectMaterializer(input) {
13
14
  return {
@@ -17,7 +18,7 @@ export function createExpoProjectMaterializer(input) {
17
18
  /*** Coordinate owner plans and Template output into one prevalidated caller-owned Expo target. */
18
19
  async function materializeExpoProjectAsync(input, project, revision) {
19
20
  assertReleasedOwnerApis();
20
- const targetDirectory = await assertEmptyTargetDirectoryAsync(input.targetDirectory);
21
+ const targetDirectory = await materializationFileSystem.assertEmptyTargetDirectoryAsync(input.targetDirectory);
21
22
  const generatedFiles = createGeneratedFiles(revision.manifest, project.id, input.navigator, input.targetEnvironment);
22
23
  const stagingDirectory = await mkdtemp(`${dirname(targetDirectory)}/.ankhorage-projects-`);
23
24
  try {
@@ -29,7 +30,10 @@ async function materializeExpoProjectAsync(input, project, revision) {
29
30
  });
30
31
  const templateFiles = await readTemplateFilesAsync(template.projectPath, template.createdFiles);
31
32
  assertNoPathCollisions(templateFiles.map(({ relativePath }) => relativePath), generatedFiles.map(({ relativePath }) => relativePath));
32
- await writeFilesAsync(targetDirectory, [...templateFiles, ...generatedFiles]);
33
+ await materializationFileSystem.writeFilesAsync(targetDirectory, [
34
+ ...templateFiles,
35
+ ...generatedFiles,
36
+ ]);
33
37
  return createMaterializationResult(project, revision, targetDirectory, templateFiles, generatedFiles);
34
38
  }
35
39
  finally {
@@ -59,7 +63,7 @@ function createGeneratedFiles(manifest, projectId, navigatorInput, targetEnviron
59
63
  })),
60
64
  {
61
65
  relativePath: 'src/ankh.manifest.ts',
62
- source: `export default ${formatTypeScriptLiteral(manifest)} as const;\n`,
66
+ source: createManifestSource(manifest),
63
67
  },
64
68
  ...app.files,
65
69
  ...createNavigatorMaterializationFiles(manifest, navigatorInput, packageSource.navigatorBindings),
@@ -102,6 +106,7 @@ const ownerApis = {
102
106
  resolveExpoRuntimeGeneratedAppSources: resolveExpoRuntimeGeneratedAppSources,
103
107
  resolveExpoRuntimeGeneratedAppScaffold: resolveExpoRuntimeGeneratedAppScaffold,
104
108
  };
109
+ const materializationFileSystem = createMaterializationFileSystem();
105
110
  /*** Reject unavailable owner emitters rather than reproducing their source in Projects. */
106
111
  function assertReleasedOwnerApis() {
107
112
  if (typeof ownerApis.materializeTemplateRevision !== 'function' ||
@@ -111,18 +116,6 @@ function assertReleasedOwnerApis() {
111
116
  throw new Error('Required released owner materialization API is unavailable.');
112
117
  }
113
118
  }
114
- /*** Resolve one existing, empty, non-symlink target directory before writing any output. */
115
- async function assertEmptyTargetDirectoryAsync(target) {
116
- const resolvedTarget = resolve(target);
117
- const stats = await lstat(resolvedTarget);
118
- if (!stats.isDirectory() || stats.isSymbolicLink()) {
119
- throw new Error(`Materialization target must be a regular directory: ${resolvedTarget}`);
120
- }
121
- if ((await readdir(resolvedTarget)).length > 0) {
122
- throw new Error(`Materialization target must be empty: ${resolvedTarget}`);
123
- }
124
- return realpath(resolvedTarget);
125
- }
126
119
  /*** Reject owner diagnostics that make a generated application invalid before filesystem side effects. */
127
120
  function assertNoErrors(diagnostics, owner) {
128
121
  const errors = diagnostics.filter(({ severity }) => severity === 'error');
@@ -133,32 +126,10 @@ function assertNoErrors(diagnostics, owner) {
133
126
  /*** Read exactly the files reported by Templates while keeping every path inside its staging project. */
134
127
  async function readTemplateFilesAsync(projectPath, files) {
135
128
  return Promise.all(files.map(async (relativePath) => ({
136
- relativePath: assertSafeRelativePath(projectPath, relativePath),
129
+ relativePath: materializationFileSystem.assertSafeRelativePath(projectPath, relativePath),
137
130
  source: await readFile(resolve(projectPath, relativePath)),
138
131
  })));
139
132
  }
140
- /*** Write all materialized files with exclusive creation so no existing caller file is overwritten. */
141
- async function writeFilesAsync(targetDirectory, files) {
142
- for (const file of files) {
143
- const relativePath = assertSafeRelativePath(targetDirectory, file.relativePath);
144
- const targetPath = resolve(targetDirectory, relativePath);
145
- await mkdir(dirname(targetPath), { recursive: true });
146
- await writeFile(targetPath, file.source, { flag: 'wx' });
147
- }
148
- }
149
- /*** Ensure an owner-reported project-relative path never crosses its designated directory. */
150
- function assertSafeRelativePath(directory, candidate) {
151
- const resolvedPath = resolve(directory, candidate);
152
- const pathRelative = relative(directory, resolvedPath);
153
- if (candidate.length === 0 ||
154
- pathRelative.length === 0 ||
155
- pathRelative === '..' ||
156
- pathRelative.startsWith('../') ||
157
- basename(resolvedPath) === '..') {
158
- throw new Error(`Materialized file path escapes its target directory: ${candidate}`);
159
- }
160
- return pathRelative;
161
- }
162
133
  /*** Reject duplicate paths emitted by one owner before any write can begin. */
163
134
  function assertUniqueRelativePaths(paths) {
164
135
  if (new Set(paths).size !== paths.length) {
@@ -0,0 +1,3 @@
1
+ import type { AppManifest } from '@ankhorage/contracts';
2
+ /*** Serialize the immutable manifest as one JSON literal so generated source stays bounded and parser-safe. */
3
+ export declare function createManifestSource(manifest: AppManifest): string;
@@ -0,0 +1,8 @@
1
+ /*** Serialize the immutable manifest as one JSON literal so generated source stays bounded and parser-safe. */
2
+ export function createManifestSource(manifest) {
3
+ const serializedManifest = JSON.stringify(manifest)
4
+ .replaceAll('\u2028', '\\u2028')
5
+ .replaceAll('\u2029', '\\u2029');
6
+ const sourceLiteral = `'${serializedManifest.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`;
7
+ return `import type { AppManifest } from '@ankhorage/contracts';\n\nexport default JSON.parse(\n ${sourceLiteral},\n) as AppManifest;\n`;
8
+ }
@@ -0,0 +1,13 @@
1
+ /*** File content emitted by an owner before Projects writes it into a caller-owned directory. */
2
+ export type MaterializationFile = Readonly<{
3
+ relativePath: string;
4
+ source: string | Uint8Array;
5
+ }>;
6
+ /*** Filesystem boundary shared by Projects materializers that write into caller-owned empty directories. */
7
+ export interface MaterializationFileSystem {
8
+ assertSafeRelativePath(directory: string, candidate: string): string;
9
+ assertEmptyTargetDirectoryAsync(target: string): Promise<string>;
10
+ writeFilesAsync(targetDirectory: string, files: readonly MaterializationFile[]): Promise<void>;
11
+ }
12
+ /*** Create the guarded filesystem boundary used by Projects materialization compositions. */
13
+ export declare function createMaterializationFileSystem(): MaterializationFileSystem;
@@ -0,0 +1,40 @@
1
+ import { lstat, mkdir, readdir, realpath, writeFile } from 'node:fs/promises';
2
+ import { basename, dirname, relative, resolve } from 'node:path';
3
+ /*** Create the guarded filesystem boundary used by Projects materialization compositions. */
4
+ export function createMaterializationFileSystem() {
5
+ return { assertSafeRelativePath, assertEmptyTargetDirectoryAsync, writeFilesAsync };
6
+ }
7
+ /*** Resolve one existing, empty, non-symlink target directory before writing any output. */
8
+ async function assertEmptyTargetDirectoryAsync(target) {
9
+ const resolvedTarget = resolve(target);
10
+ const stats = await lstat(resolvedTarget);
11
+ if (!stats.isDirectory() || stats.isSymbolicLink()) {
12
+ throw new Error(`Materialization target must be a regular directory: ${resolvedTarget}`);
13
+ }
14
+ if ((await readdir(resolvedTarget)).length > 0) {
15
+ throw new Error(`Materialization target must be empty: ${resolvedTarget}`);
16
+ }
17
+ return realpath(resolvedTarget);
18
+ }
19
+ /*** Write all materialized files with exclusive creation so no existing caller file is overwritten. */
20
+ async function writeFilesAsync(targetDirectory, files) {
21
+ for (const file of files) {
22
+ const relativePath = assertSafeRelativePath(targetDirectory, file.relativePath);
23
+ const targetPath = resolve(targetDirectory, relativePath);
24
+ await mkdir(dirname(targetPath), { recursive: true });
25
+ await writeFile(targetPath, file.source, { flag: 'wx' });
26
+ }
27
+ }
28
+ /*** Ensure an owner-reported project-relative path never crosses its designated directory. */
29
+ function assertSafeRelativePath(directory, candidate) {
30
+ const resolvedPath = resolve(directory, candidate);
31
+ const pathRelative = relative(directory, resolvedPath);
32
+ if (candidate.length === 0 ||
33
+ pathRelative.length === 0 ||
34
+ pathRelative === '..' ||
35
+ pathRelative.startsWith('../') ||
36
+ basename(resolvedPath) === '..') {
37
+ throw new Error(`Materialized file path escapes its target directory: ${candidate}`);
38
+ }
39
+ return pathRelative;
40
+ }
@@ -0,0 +1,18 @@
1
+ /*** Inputs for materializing the released minimal universal Expo application scaffold. */
2
+ export interface MaterializePlainExpoAppInput {
3
+ readonly targetDirectory: string;
4
+ readonly project: PlainExpoAppIdentity;
5
+ }
6
+ /*** The caller-owned target and exact owner-generated file inventory for a plain Expo application. */
7
+ export interface PlainExpoAppMaterializationResult {
8
+ readonly targetDirectory: string;
9
+ readonly files: readonly string[];
10
+ }
11
+ /*** Materialize the released Runtime-owned plain Expo scaffold into an empty caller-owned directory. */
12
+ export declare function materializePlainExpoAppAsync(input: MaterializePlainExpoAppInput): Promise<PlainExpoAppMaterializationResult>;
13
+ type PlainExpoAppIdentity = Readonly<{
14
+ name: string;
15
+ slug: string;
16
+ version: string;
17
+ }>;
18
+ export {};
@@ -0,0 +1,21 @@
1
+ import { resolveExpoRuntimePlainExpoAppScaffold } from '@ankhorage/expo-runtime/generated-app';
2
+ import { createMaterializationFileSystem, } from './createMaterializationFileSystem.js';
3
+ /*** Materialize the released Runtime-owned plain Expo scaffold into an empty caller-owned directory. */
4
+ export async function materializePlainExpoAppAsync(input) {
5
+ const targetDirectory = await materializationFileSystem.assertEmptyTargetDirectoryAsync(input.targetDirectory);
6
+ const scaffold = ownerApi.resolveExpoRuntimePlainExpoAppScaffold(input.project);
7
+ const { files } = scaffold;
8
+ assertUniqueRelativePaths(files.map(({ relativePath }) => relativePath));
9
+ await materializationFileSystem.writeFilesAsync(targetDirectory, files);
10
+ return { targetDirectory, files: files.map(({ relativePath }) => relativePath) };
11
+ }
12
+ const materializationFileSystem = createMaterializationFileSystem();
13
+ const ownerApi = {
14
+ resolveExpoRuntimePlainExpoAppScaffold: resolveExpoRuntimePlainExpoAppScaffold,
15
+ };
16
+ /*** Reject duplicate paths emitted by one owner before any write can begin. */
17
+ function assertUniqueRelativePaths(paths) {
18
+ if (new Set(paths).size !== paths.length) {
19
+ throw new Error('An owner emitted duplicate generated file paths.');
20
+ }
21
+ }
@@ -1,3 +1,4 @@
1
+ import { quoteJavaScriptString } from '@ankhorage/utility/string';
1
2
  import { WORKER_ENTRY_SOURCE_PATH, WORKER_WEB_DIRECTORY } from '../constants/worker.js';
2
3
  /** Maximum requests per budget key admitted by the generated Worker. */
3
4
  const WORKER_REQUEST_LIMIT = 10;
@@ -10,7 +11,6 @@ export function createWorkerMaterializationFile(input) {
10
11
  }
11
12
  /*** Render the Worker module that delegates trusted API operations to the published host boundary. */
12
13
  function createWorkerEntrySource(input) {
13
- const operations = Object.fromEntries(input.operations.map((operation) => [operation, operation]));
14
14
  return `import { createNeonServerCallerAuthenticationPort } from '@ankhorage/auth-neon';
15
15
  import { createNeonPostgresRequestBudget } from '@ankhorage/db-postgres';
16
16
  import { createTrustedZefixWorkerEntry } from '@ankhorage/projects/worker';
@@ -19,10 +19,12 @@ import { createTrustedZefixWorkerEntry } from '@ankhorage/projects/worker';
19
19
  // DATABASE_URL, ZEFIX_CREDENTIALS and ANKH_AUTH_ALLOWED_SUBJECTS are Worker secret bindings;
20
20
  // NEON_AUTH_BASE_URL and NEON_AUTH_JWKS_URL are bound from the provisioned Neon Auth outputs.
21
21
  export default createTrustedZefixWorkerEntry({
22
- appId: ${JSON.stringify(input.appId)},
23
- projectId: ${JSON.stringify(input.projectId)},
24
- environment: ${JSON.stringify(input.environment)},
25
- operations: ${JSON.stringify(operations)},
22
+ appId: ${quoteJavaScriptString(input.appId)},
23
+ projectId: ${quoteJavaScriptString(input.projectId)},
24
+ environment: ${quoteJavaScriptString(input.environment)},
25
+ operations: {
26
+ ${renderWorkerOperations(input.operations)}
27
+ },
26
28
  createCallerAuthentication: (env) =>
27
29
  createNeonServerCallerAuthenticationPort({
28
30
  authUrl: env.NEON_AUTH_BASE_URL ?? '',
@@ -36,6 +38,12 @@ export default createTrustedZefixWorkerEntry({
36
38
  });
37
39
  `;
38
40
  }
41
+ /*** Render the declared Worker operation map in the generated application's canonical source format. */
42
+ function renderWorkerOperations(operations) {
43
+ return operations
44
+ .map((operation) => ` ${quoteJavaScriptString(operation)}: ${quoteJavaScriptString(operation)},`)
45
+ .join('\n');
46
+ }
39
47
  /*** Render the Worker module for an application without server APIs: every Worker-routed request is unknown. */
40
48
  function createStaticWorkerEntrySource() {
41
49
  return `// Server-only: bundled to dist/worker/index.js, never into the public ${WORKER_WEB_DIRECTORY} assets.
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export { createProjectRepositoryFileSystemAsync } from './features/projects/adap
2
2
  export { projects } from './features/projects/application/projects.js';
3
3
  export { createExpoProjectMaterializer, type CreateExpoProjectMaterializerInput, type ExpoProjectMaterializationResult, type ExpoProjectMaterializer, } from './features/projects/composition/createExpoProjectMaterializer.js';
4
4
  export { createProjectsApiHandlerResolver } from './features/projects/composition/createProjectsApiHandlerResolver.js';
5
+ export { materializePlainExpoAppAsync, type MaterializePlainExpoAppInput, type PlainExpoAppMaterializationResult, } from './features/projects/composition/materializePlainExpoAppAsync.js';
5
6
  export type { ProjectMaterializer, ProjectRepository, } from './features/projects/ports/ProjectRepository.js';
6
7
  export { type ConnectionFileSystemStore, createConnectionFileSystemStoreAsync, } from './features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.js';
7
8
  export { createSocialManagerDraftStoreAsync } from './features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js';
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ export { createProjectRepositoryFileSystemAsync } from './features/projects/adap
2
2
  export { projects } from './features/projects/application/projects.js';
3
3
  export { createExpoProjectMaterializer, } from './features/projects/composition/createExpoProjectMaterializer.js';
4
4
  export { createProjectsApiHandlerResolver } from './features/projects/composition/createProjectsApiHandlerResolver.js';
5
+ export { materializePlainExpoAppAsync, } from './features/projects/composition/materializePlainExpoAppAsync.js';
5
6
  export { createConnectionFileSystemStoreAsync, } from './features/trusted-social-manager-host/adapters/createConnectionFileSystemStoreAsync.js';
6
7
  export { createSocialManagerDraftStoreAsync } from './features/trusted-social-manager-host/adapters/createSocialManagerDraftStoreAsync.js';
7
8
  export { createSocialManagerFlowSecurityAsync, } from './features/trusted-social-manager-host/adapters/createSocialManagerFlowSecurityAsync.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/projects",
3
- "version": "0.9.4",
3
+ "version": "0.10.0",
4
4
  "description": "Standalone project identity and repository actions.",
5
5
  "keywords": [
6
6
  "ankhorage",
@@ -58,7 +58,7 @@
58
58
  "version-packages": "ankhorage-changeset version"
59
59
  },
60
60
  "devDependencies": {
61
- "@ankhorage/devtools": "^2.12.19",
61
+ "@ankhorage/devtools": "^2.13.4",
62
62
  "@ankhorage/paradox": "^0.6.2",
63
63
  "@types/bun": "^1.4.5",
64
64
  "@types/node": "^26.6.11",
@@ -70,14 +70,14 @@
70
70
  "@ankhorage/connection": "^0.3.0",
71
71
  "@ankhorage/contracts": "^28.0.0",
72
72
  "@ankhorage/data-sources": "^2.4.0",
73
- "@ankhorage/expo-runtime": "^7.10.0",
73
+ "@ankhorage/expo-runtime": "^7.11.0",
74
74
  "@ankhorage/flow": "^0.12.0",
75
75
  "@ankhorage/navigator": "^3.9.0",
76
76
  "@ankhorage/permissions": "^0.2.64",
77
77
  "@ankhorage/runtime": "^5.8.1",
78
78
  "@ankhorage/secrets": "^0.3.2",
79
79
  "@ankhorage/social": "^0.7.0",
80
- "@ankhorage/templates": "^12.8.0",
80
+ "@ankhorage/templates": "12.9.8",
81
81
  "@ankhorage/utility": "^1.11.0"
82
82
  },
83
83
  "ankh": {
@@ -1,2 +0,0 @@
1
- /*** Render serializable data as deterministic, policy-compliant TypeScript source. */
2
- export declare function formatTypeScriptLiteral(value: unknown, depth?: number): string;
@@ -1,46 +0,0 @@
1
- /*** Render serializable data as deterministic, policy-compliant TypeScript source. */
2
- export function formatTypeScriptLiteral(value, depth = 0) {
3
- if (value === null)
4
- return 'null';
5
- if (typeof value === 'string')
6
- return formatTypeScriptString(value);
7
- if (typeof value === 'number' || typeof value === 'boolean')
8
- return String(value);
9
- if (Array.isArray(value))
10
- return formatTypeScriptArray(value, depth);
11
- if (isRecord(value))
12
- return formatTypeScriptRecord(value, depth);
13
- throw new Error('Generated manifest values must be JSON-serializable.');
14
- }
15
- /*** Render a serializable array with canonical indentation and trailing commas. */
16
- function formatTypeScriptArray(values, depth) {
17
- if (values.length === 0)
18
- return '[]';
19
- const indentation = ' '.repeat(depth + 1);
20
- const closingIndentation = ' '.repeat(depth);
21
- return `[\n${values.map((value) => `${indentation}${formatTypeScriptLiteral(value, depth + 1)},`).join('\n')}\n${closingIndentation}]`;
22
- }
23
- /*** Render an object with sorted keys so equal manifests produce equal source. */
24
- function formatTypeScriptRecord(value, depth) {
25
- const entries = Object.entries(value)
26
- .filter(([, entryValue]) => entryValue !== undefined)
27
- .sort(([left], [right]) => left.localeCompare(right));
28
- if (entries.length === 0)
29
- return '{}';
30
- const indentation = ' '.repeat(depth + 1);
31
- const closingIndentation = ' '.repeat(depth);
32
- return `{\n${entries.map(([key, entryValue]) => `${indentation}${formatTypeScriptPropertyKey(key)}: ${formatTypeScriptLiteral(entryValue, depth + 1)},`).join('\n')}\n${closingIndentation}}`;
33
- }
34
- /*** Use an identifier key where TypeScript permits it and quote required property names. */
35
- function formatTypeScriptPropertyKey(key) {
36
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(key) ? key : formatTypeScriptString(key);
37
- }
38
- /*** Emit a single-quoted TypeScript string without a formatter runtime dependency. */
39
- function formatTypeScriptString(value) {
40
- const jsonContent = JSON.stringify(value).slice(1, -1);
41
- return `'${jsonContent.replaceAll("'", "\\'").replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029')}'`;
42
- }
43
- /*** Narrow a JSON-compatible object for recursive rendering. */
44
- function isRecord(value) {
45
- return typeof value === 'object' && value !== null && !Array.isArray(value);
46
- }