Skip to content

Commit

Permalink
chore: format, post-build pkg.json dir fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Nov 6, 2024
1 parent 8883bbf commit d1ba37b
Show file tree
Hide file tree
Showing 14 changed files with 356 additions and 329 deletions.
31 changes: 29 additions & 2 deletions .cspell.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,37 @@
{
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json",
"version": "0.2",
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log"],
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log", "bun.lockb", "eslint.config.mjs"],
"useGitignore": true,
"language": "en",
"words": ["dataurl", "devpool", "fkey", "mswjs", "outdir", "servedir", "supabase", "typebox", "ubiquity-os", "smee", "tomlify", "hono", "cfworker"],
"words": [
"dataurl",
"devpool",
"fkey",
"mswjs",
"outdir",
"servedir",
"supabase",
"typebox",
"ubiquity-os",
"smee",
"tomlify",
"hono",
"cfworker",
"findstr",
"taskkill",
"topk",
"outform",
"nocrypt",
"tokp",
"XVCJ",
"tsup",
"Jsons",
"knip",
"whilefoo",
"miniflare",
"screencast"
],
"dictionaries": ["typescript", "node", "software-terms"],
"import": ["@cspell/dict-typescript/cspell-ext.json", "@cspell/dict-node/cspell-ext.json", "@cspell/dict-software-terms"],
"ignoreRegExpList": ["[0-9a-fA-F]{6}"]
Expand Down
6 changes: 2 additions & 4 deletions .github/workflows/sync-template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Sync branch to template
on:
workflow_dispatch:
schedule:
- cron: '14 0 1 * *'
- cron: "14 0 1 * *"

jobs:
sync:
Expand All @@ -23,7 +23,7 @@ jobs:
with:
app_id: ${{ secrets.APP_ID }}
private_key: ${{ secrets.APP_PRIVATE_KEY }}

- name: Sync branch to template
env:
GH_TOKEN: ${{ steps.get_installation_token.outputs.token }}
Expand All @@ -45,5 +45,3 @@ jobs:
git commit -m "chore: sync template"
git push "$original_remote" "$pr_branch"
gh pr create --title "Sync branch to template" --body "This pull request merges changes from the template repository." --head "$pr_branch" --base "$branch_name"
358 changes: 173 additions & 185 deletions CHANGELOG.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ bun dev
```

6. **Deploy the Kernel:**

- Execute `bun run deploy-dev` to deploy the kernel.

7. **Setup database (optional)**
Expand Down
2 changes: 1 addition & 1 deletion eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default tsEslint.config({
"@typescript-eslint": tsEslint.plugin,
"check-file": checkFile,
},
ignores: [".github/knip.ts", "**/.wrangler/**", "jest.config.ts", ".husky/**"],
ignores: [".github/knip.ts", "**/.wrangler/**", "jest.config.ts", ".husky/**", "dist/**", ".wrangler/**/*"],
extends: [eslint.configs.recommended, ...tsEslint.configs.recommended, sonarjs.configs.recommended],
languageOptions: {
parser: tsEslint.parser,
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"typings": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
}
},
"files": [
Expand Down
108 changes: 62 additions & 46 deletions sdk-build-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,61 +4,77 @@ import fs from "fs/promises";
type Exports = Record<string, { import?: string; require?: string; types: string }>;

interface PackageJson {
name: string;
version: string;
description: string;
main: string;
types: string;
author: string;
license: string;
keywords: string[];
exports: Exports
name: string;
version: string;
description: string;
main: string;
module: string;
types: string;
author: string;
license: string;
keywords: string[];
exports: Exports;
}

export async function createCleanPackageJson(dirName: string, base = false, dirs?: string[]) {
console.log(`Creating package.json for ${dirName}...`);
let exports: Exports;
console.log(`Creating package.json for ${!dirName ? "index" : dirName}...`);
let exports: Exports;

if (base && dirs) {
exports = {
".": {
types: `./dist/index.d.ts`,
},
};
const packageJson = {
name: PACKAGE.name,
version: PACKAGE.version,
description: PACKAGE.description,
main: "./",
module: "./",
types: "./",
author: PACKAGE.author,
license: PACKAGE.license,
keywords: PACKAGE.keywords,
exports: {} as Exports,
} as unknown as PackageJson;

for (const dir of dirs) {
exports[`./${dir}`] = {
import: `./dist/${dir}/index.mjs`,
require: `./dist/${dir}/index.js`,
types: `./dist/${dir}/index.d.ts`,
};
}
} else {
exports = {
[`.`]: {
import: `./index.mjs`,
require: `./index.js`,
types: `./index.d.ts`,
},
};
if (base && dirs) {
exports = {
".": {
types: `./sdk/index.d.ts`,
import: `./sdk/index.mjs`,
require: `./sdk/index.js`,
},
};

for (const dir of dirs) {
exports[`./${dir}`] = {
import: `./${dir}/index.mjs`,
require: `./${dir}/index.js`,
types: `./${dir}/index.d.ts`,
};
}

const packageJson = {
name: PACKAGE.name,
version: PACKAGE.version,
description: PACKAGE.description,
main: PACKAGE.main,
module: PACKAGE.module,
types: PACKAGE.typings,
author: PACKAGE.author,
license: PACKAGE.license,
keywords: PACKAGE.keywords,
exports
packageJson.exports = exports;
packageJson.types = `./sdk/index.d.ts`;
packageJson.main = `./sdk/index.js`;
packageJson.module = `./sdk/index.mjs`;

await writeDirPackageJson("dist", packageJson);
} else {
exports = {
[`.`]: {
import: `./index.mjs`,
require: `./index.js`,
types: `./index.d.ts`,
},
};

await writeDirPackageJson(base ? "dist" : dirName, packageJson);
packageJson.exports = exports;
packageJson.types = `./index.d.ts`;
packageJson.main = `./index.js`;
packageJson.module = `./index.mjs`;

await writeDirPackageJson(dirName, packageJson);
}
}

async function writeDirPackageJson(dirName: string, packageJson: PackageJson) {
await fs.writeFile(`./${dirName === "dist" ? "dist" : `dist/${dirName}`}/package.json`, JSON.stringify(packageJson, null, 2));
}
const path = dirName === "dist" ? "./dist/package.json" : `./dist/${dirName}/package.json`;
await fs.writeFile(path, JSON.stringify(packageJson, null, 2));
}
22 changes: 11 additions & 11 deletions src/sdk/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { Context } from "./context";
import { sanitizeMetadata } from "./util";

export async function postWorkerErrorComment(context: Context, error: LogReturn) {
if ("issue" in context.payload && context.payload.repository?.owner?.login) {
await context.octokit.rest.issues.createComment({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
issue_number: context.payload.issue.number,
body: `${error.logMessage.diff}\n<!--\n${sanitizeMetadata(error.metadata)}\n-->`,
});
} else {
context.logger.info("Cannot post comment because issue is not found in the payload");
}
}
if ("issue" in context.payload && context.payload.repository?.owner?.login) {
await context.octokit.rest.issues.createComment({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
issue_number: context.payload.issue.number,
body: `${error.logMessage.diff}\n<!--\n${sanitizeMetadata(error.metadata)}\n-->`,
});
} else {
context.logger.info("Cannot post comment because issue is not found in the payload");
}
}
119 changes: 60 additions & 59 deletions src/sdk/proxy-callbacks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,76 +14,77 @@ const builder = new CallbackBuilder()
```
*/
export class CallbackBuilder {
private callbacks: ProxyCallbacks = {} as ProxyCallbacks;
private _callbacks: ProxyCallbacks = {} as ProxyCallbacks;

/**
* Add a callback for the given event.
*
* @param event The event to add a callback for.
* @param callback The callback to add.
*/
addCallback<TEvent extends SupportedEventsU>(event: TEvent, callback: CallbackFunction<TEvent>) {
this.callbacks[event] ??= [];
this.callbacks[event].push(callback)
return this;
}
/**
* Add a callback for the given event.
*
* @param event The event to add a callback for.
* @param callback The callback to add.
*/
addCallback<TEvent extends SupportedEventsU>(event: TEvent, callback: CallbackFunction<TEvent>) {
this._callbacks[event] ??= [];
this._callbacks[event].push(callback);
return this;
}

/**
* This simply returns the callbacks object.
*/
build() {
return this.callbacks;
}
/**
* This simply returns the callbacks object.
*/
build() {
return this._callbacks;
}
}

export function proxyCallbacks(context: Context, callbackBuilder: CallbackBuilder): ProxyCallbacks {
return new Proxy(callbackBuilder.build(), {
get(target, prop: SupportedEventsU) {
if (!target[prop]) {
context.logger.info(`No callbacks found for event ${prop}`);
return { status: 204, reason: "skipped" };
return new Proxy(callbackBuilder.build(), {
get(target, prop: SupportedEventsU) {
if (!target[prop]) {
context.logger.info(`No callbacks found for event ${prop}`);
return { status: 204, reason: "skipped" };
}
return (async () => {
try {
const res = await Promise.all(target[prop].map((callback) => handleCallback(callback, context)));
context.logger.info(`${prop} callbacks completed`, { res });
let hasFailed = false;
for (const r of res) {
if (r.status === 500) {
/**
* Once https://github.com/ubiquity-os/ubiquity-os-kernel/pull/169 is merged,
* we'll be able to detect easily if it's a worker or an action using the new context var
* `pluginDeploymentDetails` which is just `inputs.ref` essentially.
*/
await postWorkerErrorComment(context, context.logger.error(r.reason, { content: r.content }));
hasFailed = true;
} else if (r.status === 404) {
context.logger.error(r.reason, { content: r.content });
} else if (r.status === 204) {
context.logger.info(r.reason, { content: r.content });
} else {
context.logger.ok(r.reason, { content: r.content });
}
return (async () => {
try {
const res = await Promise.all(target[prop].map((callback) => handleCallback(callback, context)));
context.logger.info(`${prop} callbacks completed`, { res });
let failed = false;
for (const r of res) {
if (r.status === 500) {
/**
* Once https://github.com/ubiquity-os/ubiquity-os-kernel/pull/169 is merged,
* we'll be able to detect easily if it's a worker or an action using the new context var
* `pluginDeploymentDetails` which is just `inputs.ref` essentially.
*/
await postWorkerErrorComment(context, context.logger.error(r.reason, { content: r.content }));
failed = true;
} else if (r.status === 404) {
context.logger.error(r.reason, { content: r.content });
} else if (r.status === 204) {
context.logger.info(r.reason, { content: r.content });
} else {
context.logger.ok(r.reason, { content: r.content });
}
}
}

if (failed) {
return { status: 500, reason: `One or more callbacks failed for event ${prop}` }
}
return { status: 200, reason: "success" };
} catch (er) {
await postWorkerErrorComment(context, context.logger.error(String(er), { er }));
return { status: 500, reason: "error", content: String(er) };
}
})();
},
});
if (hasFailed) {
return { status: 500, reason: `One or more callbacks failed for event ${prop}` };
}
return { status: 200, reason: "success" };
} catch (er) {
console.log("Error in proxyCallbacks", er);
await postWorkerErrorComment(context, context.logger.fatal("Error in proxyCallbacks", { er }));
return { status: 500, reason: "error", content: String(er) };
}
})();
},
});
}

/**
* Helper for awaiting proxyCallbacks
*/
export async function handleProxyCallbacks(proxyCallbacks: ProxyCallbacks, context: Context) {
return proxyCallbacks[context.eventName]
return proxyCallbacks[context.eventName];
}

/**
Expand All @@ -97,7 +98,7 @@ export async function handleProxyCallbacks(proxyCallbacks: ProxyCallbacks, conte
* matches the expected event and payload types, so this function provides a safe and
* flexible way to handle callbacks without introducing type or logic errors.
*/
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
// eslint-disable-next-line @typescript-eslint/ban-types
function handleCallback(callback: Function, context: Context) {
return callback(context);
return callback(context);
}
1 change: 0 additions & 1 deletion src/sdk/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,3 @@ export function createPlugin<TConfig = unknown, TEnv = unknown, TSupportedEvents

return app;
}

Loading

0 comments on commit d1ba37b

Please sign in to comment.